diff --git a/blockchain-explorer/blockchain-explorer-query.cpp b/blockchain-explorer/blockchain-explorer-query.cpp index b53e79696..5686994db 100644 --- a/blockchain-explorer/blockchain-explorer-query.cpp +++ b/blockchain-explorer/blockchain-explorer-query.cpp @@ -44,6 +44,8 @@ #include "crypto/vm/utils.h" #include "td/utils/crypto.h" +#include "td/utils/StringCase.h" + #include "vm/boc.h" #include "vm/cellops.h" #include "vm/cells/MerkleProof.h" @@ -1418,7 +1420,7 @@ void HttpQueryRunMethod::finish_query() { auto code = state_init.code->prefetch_ref(); auto data = state_init.data->prefetch_ref(); auto stack = td::make_ref(std::move(params_)); - td::int64 method_id = (td::crc16(td::Slice{method_name_}) & 0xffff) | 0x10000; + td::int64 method_id = (td::crc16(td::Slice{td::StringCase::is_camel_case(method_name_) ? td::StringCase::camel_to_snake(method_name_) : method_name_}) & 0xffff) | 0x10000; stack.write().push_smallint(method_id); long long gas_limit = vm::GasLimits::infty; // OstreamLogger ostream_logger(ctx.error_stream); diff --git a/crypto/fift/lib/Asm.fif b/crypto/fift/lib/Asm.fif index 0a4c7074f..3045fd250 100644 --- a/crypto/fift/lib/Asm.fif +++ b/crypto/fift/lib/Asm.fif @@ -1580,6 +1580,9 @@ forget @proclist forget @proccnt -3 constant split_prepare -4 constant split_install +recv_internal constant receiveInternalMessage +recv_external constant receiveExternalMessage + { asm-mode 0 3 ~! } : asm-no-remove-unused { asm-mode 1 1 ~! } : asm-remove-unused // enabled by default { asm-mode 3 3 ~! } : asm-warn-remove-unused diff --git a/crypto/func/builtins.cpp b/crypto/func/builtins.cpp index 9de673fd7..bbe9671bd 100644 --- a/crypto/func/builtins.cpp +++ b/crypto/func/builtins.cpp @@ -1237,6 +1237,26 @@ void define_builtins() { define_builtin_func("cell_at", TypeExpr::new_map(TupleInt, Cell), compile_tuple_at); define_builtin_func("slice_at", TypeExpr::new_map(TupleInt, Slice), compile_tuple_at); define_builtin_func("tuple_at", TypeExpr::new_map(TupleInt, Tuple), compile_tuple_at); + define_builtin_func("isNull", TypeExpr::new_forall({X}, TypeExpr::new_map(X, Int)), compile_is_null); + define_builtin_func("throwIf", impure_bin_op, std::bind(compile_cond_throw, _1, _2, true), true); + define_builtin_func("throwUnless", impure_bin_op, std::bind(compile_cond_throw, _1, _2, false), true); + define_builtin_func("throwArg", throw_arg_op, compile_throw_arg, true); + define_builtin_func("throwArgIf", cond_throw_arg_op, std::bind(compile_cond_throw_arg, _1, _2, true), true); + define_builtin_func("throwArgUnless", cond_throw_arg_op, std::bind(compile_cond_throw_arg, _1, _2, false), true); + define_builtin_func("loadInt", fetch_int_op, std::bind(compile_fetch_int, _1, _2, true, true), {}, {1, 0}); + define_builtin_func("loadUint", fetch_int_op, std::bind(compile_fetch_int, _1, _2, true, false), {}, {1, 0}); + define_builtin_func("preloadInt", prefetch_int_op, std::bind(compile_fetch_int, _1, _2, false, true)); + define_builtin_func("preloadUint", prefetch_int_op, std::bind(compile_fetch_int, _1, _2, false, false)); + define_builtin_func("storeInt", store_int_op, std::bind(compile_store_int, _1, _2, true), {1, 0, 2}); + define_builtin_func("storeUint", store_int_op, std::bind(compile_store_int, _1, _2, false), {1, 0, 2}); + define_builtin_func("~storeInt", store_int_method, std::bind(compile_store_int, _1, _2, true), {1, 0, 2}); + define_builtin_func("~storeUint", store_int_method, std::bind(compile_store_int, _1, _2, false), {1, 0, 2}); + define_builtin_func("loadBits", fetch_slice_op, std::bind(compile_fetch_slice, _1, _2, true), {}, {1, 0}); + define_builtin_func("preloadBits", prefetch_slice_op, std::bind(compile_fetch_slice, _1, _2, false)); + define_builtin_func("intAt", TypeExpr::new_map(TupleInt, Int), compile_tuple_at); + define_builtin_func("cellAt", TypeExpr::new_map(TupleInt, Cell), compile_tuple_at); + define_builtin_func("sliceAt", TypeExpr::new_map(TupleInt, Slice), compile_tuple_at); + define_builtin_func("tupleAt", TypeExpr::new_map(TupleInt, Tuple), compile_tuple_at); define_builtin_func("at", TypeExpr::new_forall({X}, TypeExpr::new_map(TupleInt, X)), compile_tuple_at); define_builtin_func("touch", TypeExpr::new_forall({X}, TypeExpr::new_map(X, X)), AsmOp::Nop()); define_builtin_func("~touch", TypeExpr::new_forall({X}, TypeExpr::new_map(X, TypeExpr::new_tensor({X, Unit}))), diff --git a/crypto/func/keywords.cpp b/crypto/func/keywords.cpp index fedce9db2..3cb45ae09 100644 --- a/crypto/func/keywords.cpp +++ b/crypto/func/keywords.cpp @@ -124,6 +124,8 @@ void define_keywords() { .add_keyword("inline_ref", Kw::_InlineRef) .add_keyword("auto_apply", Kw::_AutoApply) .add_keyword("method_id", Kw::_MethodId) + .add_keyword("inlineRef", Kw::_InlineRef) + .add_keyword("methodId", Kw::_MethodId) .add_keyword("operator", Kw::_Operator) .add_keyword("infix", Kw::_Infix) .add_keyword("infixl", Kw::_Infixl) diff --git a/crypto/func/parse-func.cpp b/crypto/func/parse-func.cpp index 15794c425..b2bfabe8d 100644 --- a/crypto/func/parse-func.cpp +++ b/crypto/func/parse-func.cpp @@ -18,6 +18,7 @@ */ #include "func.h" #include "td/utils/crypto.h" +#include "td/utils/StringCase.h" #include "common/refint.h" #include "openssl/digest.hpp" #include "block/block.h" @@ -1475,7 +1476,7 @@ void parse_func_def(Lexer& lex) { method_name = func_name.str; } if (method_id.is_null()) { - unsigned crc = td::crc16(method_name); + unsigned crc = td::crc16(td::StringCase::is_camel_case(method_name) ? td::StringCase::camel_to_snake(method_name) : method_name); method_id = td::make_refint((crc & 0xffff) | 0x10000); } } diff --git a/crypto/smartcont/stdlibCamel.fc b/crypto/smartcont/stdlibCamel.fc new file mode 100644 index 000000000..dba362440 --- /dev/null +++ b/crypto/smartcont/stdlibCamel.fc @@ -0,0 +1,639 @@ +;; Standard library for funC +;; + +{- + This file is part of TON FunC Standard Library. + + FunC Standard Library is free software: you can redistribute it and/or modify + it under the terms of the GNU Lesser General Public License as published by + the Free Software Foundation, either version 2 of the License, or + (at your option) any later version. + + FunC Standard Library is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Lesser General Public License for more details. + +-} + +{- + # Tuple manipulation primitives + The names and the types are mostly self-explaining. + See [polymorhism with forall](https://ton.org/docs/#/func/functions?id=polymorphism-with-forall) + for more info on the polymorphic functions. + + Note that currently values of atomic type `tuple` can't be cast to composite tuple type (e.g. `[int, cell]`) + and vise versa. +-} + +{- + # Lisp-style lists + + Lists can be represented as nested 2-elements tuples. + Empty list is conventionally represented as TVM `null` value (it can be obtained by calling [null()]). + For example, tuple `(1, (2, (3, null)))` represents list `[1, 2, 3]`. Elements of a list can be of different types. +-} + +;;; Adds an element to the beginning of lisp-style list. +forall X -> tuple cons(X head, tuple tail) asm "CONS"; + +;;; Extracts the head and the tail of lisp-style list. +forall X -> (X, tuple) uncons(tuple list) asm "UNCONS"; + +;;; Extracts the tail and the head of lisp-style list. +forall X -> (tuple, X) listNext(tuple list) asm( -> 1 0) "UNCONS"; + +;;; Returns the head of lisp-style list. +forall X -> X car(tuple list) asm "CAR"; + +;;; Returns the tail of lisp-style list. +tuple cdr(tuple list) asm "CDR"; + +;;; Creates tuple with zero elements. +tuple emptyTuple() asm "NIL"; + +;;; Appends a value `x` to a `Tuple t = (x1, ..., xn)`, but only if the resulting `Tuple t' = (x1, ..., xn, x)` +;;; is of length at most 255. Otherwise throws a type check exception. +forall X -> tuple tpush(tuple t, X value) asm "TPUSH"; +forall X -> (tuple, ()) ~tpush(tuple t, X value) asm "TPUSH"; + +;;; Creates a tuple of length one with given argument as element. +forall X -> [X] single(X x) asm "SINGLE"; + +;;; Unpacks a tuple of length one +forall X -> X unsingle([X] t) asm "UNSINGLE"; + +;;; Creates a tuple of length two with given arguments as elements. +forall X, Y -> [X, Y] pair(X x, Y y) asm "PAIR"; + +;;; Unpacks a tuple of length two +forall X, Y -> (X, Y) unpair([X, Y] t) asm "UNPAIR"; + +;;; Creates a tuple of length three with given arguments as elements. +forall X, Y, Z -> [X, Y, Z] triple(X x, Y y, Z z) asm "TRIPLE"; + +;;; Unpacks a tuple of length three +forall X, Y, Z -> (X, Y, Z) untriple([X, Y, Z] t) asm "UNTRIPLE"; + +;;; Creates a tuple of length four with given arguments as elements. +forall X, Y, Z, W -> [X, Y, Z, W] tuple4(X x, Y y, Z z, W w) asm "4 TUPLE"; + +;;; Unpacks a tuple of length four +forall X, Y, Z, W -> (X, Y, Z, W) untuple4([X, Y, Z, W] t) asm "4 UNTUPLE"; + +;;; Returns the first element of a tuple (with unknown element types). +forall X -> X first(tuple t) asm "FIRST"; + +;;; Returns the second element of a tuple (with unknown element types). +forall X -> X second(tuple t) asm "SECOND"; + +;;; Returns the third element of a tuple (with unknown element types). +forall X -> X third(tuple t) asm "THIRD"; + +;;; Returns the fourth element of a tuple (with unknown element types). +forall X -> X fourth(tuple t) asm "3 INDEX"; + +;;; Returns the first element of a pair tuple. +forall X, Y -> X pairFirst([X, Y] p) asm "FIRST"; + +;;; Returns the second element of a pair tuple. +forall X, Y -> Y pairSecond([X, Y] p) asm "SECOND"; + +;;; Returns the first element of a triple tuple. +forall X, Y, Z -> X tripleFirst([X, Y, Z] p) asm "FIRST"; + +;;; Returns the second element of a triple tuple. +forall X, Y, Z -> Y tripleSecond([X, Y, Z] p) asm "SECOND"; + +;;; Returns the third element of a triple tuple. +forall X, Y, Z -> Z tripleThird([X, Y, Z] p) asm "THIRD"; + + +;;; Push null element (casted to given type) +;;; By the TVM type `Null` FunC represents absence of a value of some atomic type. +;;; So `null` can actually have any atomic type. +forall X -> X null() asm "PUSHNULL"; + +;;; Moves a variable [x] to the top of the stack +forall X -> (X, ()) ~impureTouch(X x) impure asm "NOP"; + + + +;;; Returns the current Unix time as an Integer +int now() asm "NOW"; + +;;; Returns the internal address of the current smart contract as a Slice with a `MsgAddressInt`. +;;; If necessary, it can be parsed further using primitives such as [parse_std_addr]. +slice myAddress() asm "MYADDR"; + +;;; Returns the balance of the smart contract as a tuple consisting of an int +;;; (balance in nanotoncoins) and a `cell` +;;; (a dictionary with 32-bit keys representing the balance of "extra currencies") +;;; at the start of Computation Phase. +;;; Note that RAW primitives such as [send_raw_message] do not update this field. +[int, cell] getBalance() asm "BALANCE"; + +;;; Returns the logical time of the current transaction. +int curLt() asm "LTIME"; + +;;; Returns the starting logical time of the current block. +int blockLt() asm "BLOCKLT"; + +;;; Computes the representation hash of a `cell` [c] and returns it as a 256-bit unsigned integer `x`. +;;; Useful for signing and checking signatures of arbitrary entities represented by a tree of cells. +int cellHash(cell c) asm "HASHCU"; + +;;; Computes the hash of a `slice s` and returns it as a 256-bit unsigned integer `x`. +;;; The result is the same as if an ordinary cell containing only data and references from `s` had been created +;;; and its hash computed by [cell_hash]. +int sliceHash(slice s) asm "HASHSU"; + +;;; Computes sha256 of the data bits of `slice` [s]. If the bit length of `s` is not divisible by eight, +;;; throws a cell underflow exception. The hash value is returned as a 256-bit unsigned integer `x`. +int stringHash(slice s) asm "SHA256U"; + +{- + # Signature checks +-} + +;;; Checks the Ed25519-`signature` of a `hash` (a 256-bit unsigned integer, usually computed as the hash of some data) +;;; using [public_key] (also represented by a 256-bit unsigned integer). +;;; The signature must contain at least 512 data bits; only the first 512 bits are used. +;;; The result is `−1` if the signature is valid, `0` otherwise. +;;; Note that `CHKSIGNU` creates a 256-bit slice with the hash and calls `CHKSIGNS`. +;;; That is, if [hash] is computed as the hash of some data, these data are hashed twice, +;;; the second hashing occurring inside `CHKSIGNS`. +int checkSignature(int hash, slice signature, int publicKey) asm "CHKSIGNU"; + +;;; Checks whether [signature] is a valid Ed25519-signature of the data portion of `slice data` using `public_key`, +;;; similarly to [check_signature]. +;;; If the bit length of [data] is not divisible by eight, throws a cell underflow exception. +;;; The verification of Ed25519 signatures is the standard one, +;;; with sha256 used to reduce [data] to the 256-bit number that is actually signed. +int checkDataSignature(slice data, slice signature, int publicKey) asm "CHKSIGNS"; + +{--- + # Computation of boc size + The primitives below may be useful for computing storage fees of user-provided data. +-} + +;;; Returns `(x, y, z, -1)` or `(null, null, null, 0)`. +;;; Recursively computes the count of distinct cells `x`, data bits `y`, and cell references `z` +;;; in the DAG rooted at `cell` [c], effectively returning the total storage used by this DAG taking into account +;;; the identification of equal cells. +;;; The values of `x`, `y`, and `z` are computed by a depth-first traversal of this DAG, +;;; with a hash table of visited cell hashes used to prevent visits of already-visited cells. +;;; The total count of visited cells `x` cannot exceed non-negative [max_cells]; +;;; otherwise the computation is aborted before visiting the `(max_cells + 1)`-st cell and +;;; a zero flag is returned to indicate failure. If [c] is `null`, returns `x = y = z = 0`. +(int, int, int) computeDataSize(cell c, int maxCells) impure asm "CDATASIZE"; + +;;; Similar to [compute_data_size?], but accepting a `slice` [s] instead of a `cell`. +;;; The returned value of `x` does not take into account the cell that contains the `slice` [s] itself; +;;; however, the data bits and the cell references of [s] are accounted for in `y` and `z`. +(int, int, int) sliceComputeDataSize(slice s, int maxCells) impure asm "SDATASIZE"; + +;;; A non-quiet version of [compute_data_size?] that throws a cell overflow exception (`8`) on failure. +(int, int, int, int) tryComputeDataSize(cell c, int maxCells) asm "CDATASIZEQ NULLSWAPIFNOT2 NULLSWAPIFNOT"; + +;;; A non-quiet version of [slice_compute_data_size?] that throws a cell overflow exception (8) on failure. +(int, int, int, int) trySliceComputeDataSize(cell c, int maxCells) asm "SDATASIZEQ NULLSWAPIFNOT2 NULLSWAPIFNOT"; + +;;; Throws an exception with exit_code excno if cond is not 0 (commented since implemented in compilator) +;; () throw_if(int excno, int cond) impure asm "THROWARGIF"; + +{-- + # Debug primitives + Only works for local TVM execution with debug level verbosity +-} +;;; Dumps the stack (at most the top 255 values) and shows the total stack depth. +() dumpStack() impure asm "DUMPSTK"; + +{- + # Persistent storage save and load +-} + +;;; Returns the persistent contract storage cell. It can be parsed or modified with slice and builder primitives later. +cell getData() asm "c4 PUSH"; + +;;; Sets `cell` [c] as persistent contract data. You can update persistent contract storage with this primitive. +() setData(cell c) impure asm "c4 POP"; + +{- + # Continuation primitives +-} +;;; Usually `c3` has a continuation initialized by the whole code of the contract. It is used for function calls. +;;; The primitive returns the current value of `c3`. +cont getC3() impure asm "c3 PUSH"; + +;;; Updates the current value of `c3`. Usually, it is used for updating smart contract code in run-time. +;;; Note that after execution of this primitive the current code +;;; (and the stack of recursive function calls) won't change, +;;; but any other function call will use a function from the new code. +() setC3(cont c) impure asm "c3 POP"; + +;;; Transforms a `slice` [s] into a simple ordinary continuation `c`, with `c.code = s` and an empty stack and savelist. +cont bless(slice s) impure asm "BLESS"; + +{--- + # Gas related primitives +-} + +;;; Sets current gas limit `gl` to its maximal allowed value `gm`, and resets the gas credit `gc` to zero, +;;; decreasing the value of `gr` by `gc` in the process. +;;; In other words, the current smart contract agrees to buy some gas to finish the current transaction. +;;; This action is required to process external messages, which bring no value (hence no gas) with themselves. +;;; +;;; For more details check [accept_message effects](https://ton.org/docs/#/smart-contracts/accept). +() acceptMessage() impure asm "ACCEPT"; + +;;; Sets current gas limit `gl` to the minimum of limit and `gm`, and resets the gas credit `gc` to zero. +;;; If the gas consumed so far (including the present instruction) exceeds the resulting value of `gl`, +;;; an (unhandled) out of gas exception is thrown before setting new gas limits. +;;; Notice that [set_gas_limit] with an argument `limit ≥ 2^63 − 1` is equivalent to [accept_message]. +() setGasLimit(int limit) impure asm "SETGASLIMIT"; + +;;; Commits the current state of registers `c4` (“persistent data”) and `c5` (“actions”) +;;; so that the current execution is considered “successful” with the saved values even if an exception +;;; in Computation Phase is thrown later. +() commit() impure asm "COMMIT"; + +;;; Not implemented +;;() buy_gas(int gram) impure asm "BUYGAS"; + +;;; Computes the amount of gas that can be bought for `amount` nanoTONs, +;;; and sets `gl` accordingly in the same way as [set_gas_limit]. +() buyGas(int amount) impure asm "BUYGAS"; + +;;; Computes the minimum of two integers [x] and [y]. +int min(int x, int y) asm "MIN"; + +;;; Computes the maximum of two integers [x] and [y]. +int max(int x, int y) asm "MAX"; + +;;; Sorts two integers. +(int, int) minmax(int x, int y) asm "MINMAX"; + +;;; Computes the absolute value of an integer [x]. +int abs(int x) asm "ABS"; + +{- + # Slice primitives + + It is said that a primitive _loads_ some data, + if it returns the data and the remainder of the slice + (so it can also be used as [modifying method](https://ton.org/docs/#/func/statements?id=modifying-methods)). + + It is said that a primitive _preloads_ some data, if it returns only the data + (it can be used as [non-modifying method](https://ton.org/docs/#/func/statements?id=non-modifying-methods)). + + Unless otherwise stated, loading and preloading primitives read the data from a prefix of the slice. +-} + + +;;; Converts a `cell` [c] into a `slice`. Notice that [c] must be either an ordinary cell, +;;; or an exotic cell (see [TVM.pdf](https://ton-blockchain.github.io/docs/tvm.pdf), 3.1.2) +;;; which is automatically loaded to yield an ordinary cell `c'`, converted into a `slice` afterwards. +slice beginParse(cell c) asm "CTOS"; + +;;; Checks if [s] is empty. If not, throws an exception. +() endParse(slice s) impure asm "ENDS"; + +;;; Loads the first reference from the slice. +(slice, cell) loadRef(slice s) asm( -> 1 0) "LDREF"; + +;;; Preloads the first reference from the slice. +cell preloadRef(slice s) asm "PLDREF"; + +{- Functions below are commented because are implemented on compilator level for optimisation -} + +;;; Loads a signed [len]-bit integer from a slice [s]. +;; (slice, int) ~load_int(slice s, int len) asm(s len -> 1 0) "LDIX"; + +;;; Loads an unsigned [len]-bit integer from a slice [s]. +;; (slice, int) ~load_uint(slice s, int len) asm( -> 1 0) "LDUX"; + +;;; Preloads a signed [len]-bit integer from a slice [s]. +;; int preload_int(slice s, int len) asm "PLDIX"; + +;;; Preloads an unsigned [len]-bit integer from a slice [s]. +;; int preload_uint(slice s, int len) asm "PLDUX"; + +;;; Loads the first `0 ≤ len ≤ 1023` bits from slice [s] into a separate `slice s''`. +;; (slice, slice) load_bits(slice s, int len) asm(s len -> 1 0) "LDSLICEX"; + +;;; Preloads the first `0 ≤ len ≤ 1023` bits from slice [s] into a separate `slice s''`. +;; slice preload_bits(slice s, int len) asm "PLDSLICEX"; + +;;; Loads serialized amount of TonCoins (any unsigned integer up to `2^120 - 1`). +(slice, int) loadGrams(slice s) asm( -> 1 0) "LDGRAMS"; +(slice, int) loadCoins(slice s) asm( -> 1 0) "LDGRAMS"; + +;;; Returns all but the first `0 ≤ len ≤ 1023` bits of `slice` [s]. +slice skipBits(slice s, int len) asm "SDSKIPFIRST"; +(slice, ()) ~skipBits(slice s, int len) asm "SDSKIPFIRST"; + +;;; Returns the first `0 ≤ len ≤ 1023` bits of `slice` [s]. +slice firstBits(slice s, int len) asm "SDCUTFIRST"; + +;;; Returns all but the last `0 ≤ len ≤ 1023` bits of `slice` [s]. +slice skipLastBits(slice s, int len) asm "SDSKIPLAST"; +(slice, ()) ~skipLastBits(slice s, int len) asm "SDSKIPLAST"; + +;;; Returns the last `0 ≤ len ≤ 1023` bits of `slice` [s]. +slice sliceLast(slice s, int len) asm "SDCUTLAST"; + +;;; Loads a dictionary `D` (HashMapE) from `slice` [s]. +;;; (returns `null` if `nothing` constructor is used). +(slice, cell) loadDict(slice s) asm( -> 1 0) "LDDICT"; + +;;; Preloads a dictionary `D` from `slice` [s]. +cell preloadDict(slice s) asm "PLDDICT"; + +;;; Loads a dictionary as [load_dict], but returns only the remainder of the slice. +slice skipDict(slice s) asm "SKIPDICT"; + +;;; Loads (Maybe ^Cell) from `slice` [s]. +;;; In other words loads 1 bit and if it is true +;;; loads first ref and return it with slice remainder +;;; otherwise returns `null` and slice remainder +(slice, cell) loadMaybeRef(slice s) asm( -> 1 0) "LDOPTREF"; + +;;; Preloads (Maybe ^Cell) from `slice` [s]. +cell preloadMaybeRef(slice s) asm "PLDOPTREF"; + + +;;; Returns the depth of `cell` [c]. +;;; If [c] has no references, then return `0`; +;;; otherwise the returned value is one plus the maximum of depths of cells referred to from [c]. +;;; If [c] is a `null` instead of a cell, returns zero. +int cellDepth(cell c) asm "CDEPTH"; + + +{- + # Slice size primitives +-} + +;;; Returns the number of references in `slice` [s]. +int sliceRefs(slice s) asm "SREFS"; + +;;; Returns the number of data bits in `slice` [s]. +int sliceBits(slice s) asm "SBITS"; + +;;; Returns both the number of data bits and the number of references in `slice` [s]. +(int, int) sliceBitsRefs(slice s) asm "SBITREFS"; + +;;; Checks whether a `slice` [s] is empty (i.e., contains no bits of data and no cell references). +int isSliceEmpty(slice s) asm "SEMPTY"; + +;;; Checks whether `slice` [s] has no bits of data. +int isSliceDataEmpty(slice s) asm "SDEMPTY"; + +;;; Checks whether `slice` [s] has no references. +int isSliceRefsEmpty(slice s) asm "SREMPTY"; + +;;; Returns the depth of `slice` [s]. +;;; If [s] has no references, then returns `0`; +;;; otherwise the returned value is one plus the maximum of depths of cells referred to from [s]. +int sliceDepth(slice s) asm "SDEPTH"; + +{- + # Builder size primitives +-} + +;;; Returns the number of cell references already stored in `builder` [b] +int builderRefs(builder b) asm "BREFS"; + +;;; Returns the number of data bits already stored in `builder` [b]. +int builderBits(builder b) asm "BBITS"; + +;;; Returns the depth of `builder` [b]. +;;; If no cell references are stored in [b], then returns 0; +;;; otherwise the returned value is one plus the maximum of depths of cells referred to from [b]. +int builderDepth(builder b) asm "BDEPTH"; + +{- + # Builder primitives + It is said that a primitive _stores_ a value `x` into a builder `b` + if it returns a modified version of the builder `b'` with the value `x` stored at the end of it. + It can be used as [non-modifying method](https://ton.org/docs/#/func/statements?id=non-modifying-methods). + + All the primitives below first check whether there is enough space in the `builder`, + and only then check the range of the value being serialized. +-} + +;;; Creates a new empty `builder`. +builder beginCell() asm "NEWC"; + +;;; Converts a `builder` into an ordinary `cell`. +cell endCell(builder b) asm "ENDC"; + +;;; Stores a reference to `cell` [c] into `builder` [b]. +builder storeRef(builder b, cell c) asm(c b) "STREF"; + +;;; Stores an unsigned [len]-bit integer `x` into `b` for `0 ≤ len ≤ 256`. +;; builder store_uint(builder b, int x, int len) asm(x b len) "STUX"; + +;;; Stores a signed [len]-bit integer `x` into `b` for` 0 ≤ len ≤ 257`. +;; builder store_int(builder b, int x, int len) asm(x b len) "STIX"; + + +;;; Stores `slice` [s] into `builder` [b] +builder storeSlice(builder b, slice s) asm "STSLICER"; + +;;; Stores (serializes) an integer [x] in the range `0..2^120 − 1` into `builder` [b]. +;;; The serialization of [x] consists of a 4-bit unsigned big-endian integer `l`, +;;; which is the smallest integer `l ≥ 0`, such that `x < 2^8l`, +;;; followed by an `8l`-bit unsigned big-endian representation of [x]. +;;; If [x] does not belong to the supported range, a range check exception is thrown. +;;; +;;; Store amounts of TonCoins to the builder as VarUInteger 16 +builder storeGrams(builder b, int x) asm "STGRAMS"; +builder storeCoins(builder b, int x) asm "STGRAMS"; + +;;; Stores dictionary `D` represented by `cell` [c] or `null` into `builder` [b]. +;;; In other words, stores a `1`-bit and a reference to [c] if [c] is not `null` and `0`-bit otherwise. +builder storeDict(builder b, cell c) asm(c b) "STDICT"; + +;;; Stores (Maybe ^Cell) to builder: +;;; if cell is null store 1 zero bit +;;; otherwise store 1 true bit and ref to cell +builder storeMaybeRef(builder b, cell c) asm(c b) "STOPTREF"; + + +{- + # Address manipulation primitives + The address manipulation primitives listed below serialize and deserialize values according to the following TL-B scheme: + ```TL-B + addr_none$00 = MsgAddressExt; + addr_extern$01 len:(## 8) external_address:(bits len) + = MsgAddressExt; + anycast_info$_ depth:(#<= 30) { depth >= 1 } + rewrite_pfx:(bits depth) = Anycast; + addr_std$10 anycast:(Maybe Anycast) + workchain_id:int8 address:bits256 = MsgAddressInt; + addr_var$11 anycast:(Maybe Anycast) addr_len:(## 9) + workchain_id:int32 address:(bits addr_len) = MsgAddressInt; + _ _:MsgAddressInt = MsgAddress; + _ _:MsgAddressExt = MsgAddress; + + int_msg_info$0 ihr_disabled:Bool bounce:Bool bounced:Bool + src:MsgAddress dest:MsgAddressInt + value:CurrencyCollection ihr_fee:Grams fwd_fee:Grams + created_lt:uint64 created_at:uint32 = CommonMsgInfoRelaxed; + ext_out_msg_info$11 src:MsgAddress dest:MsgAddressExt + created_lt:uint64 created_at:uint32 = CommonMsgInfoRelaxed; + ``` + A deserialized `MsgAddress` is represented by a tuple `t` as follows: + + - `addr_none` is represented by `t = (0)`, + i.e., a tuple containing exactly one integer equal to zero. + - `addr_extern` is represented by `t = (1, s)`, + where slice `s` contains the field `external_address`. In other words, ` + t` is a pair (a tuple consisting of two entries), containing an integer equal to one and slice `s`. + - `addr_std` is represented by `t = (2, u, x, s)`, + where `u` is either a `null` (if `anycast` is absent) or a slice `s'` containing `rewrite_pfx` (if anycast is present). + Next, integer `x` is the `workchain_id`, and slice `s` contains the address. + - `addr_var` is represented by `t = (3, u, x, s)`, + where `u`, `x`, and `s` have the same meaning as for `addr_std`. +-} + +;;; Loads from slice [s] the only prefix that is a valid `MsgAddress`, +;;; and returns both this prefix `s'` and the remainder `s''` of [s] as slices. +(slice, slice) loadMsgAddr(slice s) asm( -> 1 0) "LDMSGADDR"; + +;;; Decomposes slice [s] containing a valid `MsgAddress` into a `tuple t` with separate fields of this `MsgAddress`. +;;; If [s] is not a valid `MsgAddress`, a cell deserialization exception is thrown. +tuple parseAddr(slice s) asm "PARSEMSGADDR"; + +;;; Parses slice [s] containing a valid `MsgAddressInt` (usually a `msg_addr_std`), +;;; applies rewriting from the anycast (if present) to the same-length prefix of the address, +;;; and returns both the workchain and the 256-bit address as integers. +;;; If the address is not 256-bit, or if [s] is not a valid serialization of `MsgAddressInt`, +;;; throws a cell deserialization exception. +(int, int) parseStdAddr(slice s) asm "REWRITESTDADDR"; + +;;; A variant of [parse_std_addr] that returns the (rewritten) address as a slice [s], +;;; even if it is not exactly 256 bit long (represented by a `msg_addr_var`). +(int, slice) parseVarAddr(slice s) asm "REWRITEVARADDR"; + +{- + # Dictionary primitives +-} + + +;;; Sets the value associated with [key_len]-bit key signed index in dictionary [dict] to [value] (cell), +;;; and returns the resulting dictionary. +cell idictSetRef(cell dict, int keyLen, int index, cell value) asm(value index dict keyLen) "DICTISETREF"; +(cell, ()) ~idictSetRef(cell dict, int keyLen, int index, cell value) asm(value index dict keyLen) "DICTISETREF"; + +;;; Sets the value associated with [key_len]-bit key unsigned index in dictionary [dict] to [value] (cell), +;;; and returns the resulting dictionary. +cell udictSetRef(cell dict, int keyLen, int index, cell value) asm(value index dict keyLen) "DICTUSETREF"; +(cell, ()) ~udictSetRef(cell dict, int keyLen, int index, cell value) asm(value index dict keyLen) "DICTUSETREF"; + +cell idictGetRef(cell dict, int keyLen, int index) asm(index dict keyLen) "DICTIGETOPTREF"; +(cell, int) tryIdictGetRef(cell dict, int keyLen, int index) asm(index dict keyLen) "DICTIGETREF" "NULLSWAPIFNOT"; +(cell, int) tryUdictGetRef(cell dict, int keyLen, int index) asm(index dict keyLen) "DICTUGETREF" "NULLSWAPIFNOT"; +(cell, cell) idictSetGetRef(cell dict, int keyLen, int index, cell value) asm(value index dict keyLen) "DICTISETGETOPTREF"; +(cell, cell) udictSetGetRef(cell dict, int keyLen, int index, cell value) asm(value index dict keyLen) "DICTUSETGETOPTREF"; +(cell, int) tryIdictDelete(cell dict, int keyLen, int index) asm(index dict keyLen) "DICTIDEL"; +(cell, int) tryUdictDelete(cell dict, int keyLen, int index) asm(index dict keyLen) "DICTUDEL"; +(slice, int) tryIdictGet(cell dict, int keyLen, int index) asm(index dict keyLen) "DICTIGET" "NULLSWAPIFNOT"; +(slice, int) tryUdictGet(cell dict, int keyLen, int index) asm(index dict keyLen) "DICTUGET" "NULLSWAPIFNOT"; +(cell, slice, int) tryIdictDeleteGet(cell dict, int keyLen, int index) asm(index dict keyLen) "DICTIDELGET" "NULLSWAPIFNOT"; +(cell, slice, int) tryUdictDeleteGet(cell dict, int keyLen, int index) asm(index dict keyLen) "DICTUDELGET" "NULLSWAPIFNOT"; +(cell, (slice, int)) ~tryIdictDeleteGet(cell dict, int keyLen, int index) asm(index dict keyLen) "DICTIDELGET" "NULLSWAPIFNOT"; +(cell, (slice, int)) ~tryUdictDeleteGet(cell dict, int keyLen, int index) asm(index dict keyLen) "DICTUDELGET" "NULLSWAPIFNOT"; +cell udictSet(cell dict, int keyLen, int index, slice value) asm(value index dict keyLen) "DICTUSET"; +(cell, ()) ~udictSet(cell dict, int keyLen, int index, slice value) asm(value index dict keyLen) "DICTUSET"; +cell idictSet(cell dict, int keyLen, int index, slice value) asm(value index dict keyLen) "DICTISET"; +(cell, ()) ~idictSet(cell dict, int keyLen, int index, slice value) asm(value index dict keyLen) "DICTISET"; +cell dictSet(cell dict, int keyLen, slice index, slice value) asm(value index dict keyLen) "DICTSET"; +(cell, ()) ~dictSet(cell dict, int keyLen, slice index, slice value) asm(value index dict keyLen) "DICTSET"; +(cell, int) tryUdictAdd(cell dict, int keyLen, int index, slice value) asm(value index dict keyLen) "DICTUADD"; +(cell, int) tryUdictReplace(cell dict, int keyLen, int index, slice value) asm(value index dict keyLen) "DICTUREPLACE"; +(cell, int) tryIdictAdd(cell dict, int keyLen, int index, slice value) asm(value index dict keyLen) "DICTIADD"; +(cell, int) tryIdictReplace(cell dict, int keyLen, int index, slice value) asm(value index dict keyLen) "DICTIREPLACE"; +cell udictSetBuilder(cell dict, int keyLen, int index, builder value) asm(value index dict keyLen) "DICTUSETB"; +(cell, ()) ~udictSetBuilder(cell dict, int keyLen, int index, builder value) asm(value index dict keyLen) "DICTUSETB"; +cell idictSetBuilder(cell dict, int keyLen, int index, builder value) asm(value index dict keyLen) "DICTISETB"; +(cell, ()) ~idictSetBuilder(cell dict, int keyLen, int index, builder value) asm(value index dict keyLen) "DICTISETB"; +cell dictSetBuilder(cell dict, int keyLen, slice index, builder value) asm(value index dict keyLen) "DICTSETB"; +(cell, ()) ~dictSetBuilder(cell dict, int keyLen, slice index, builder value) asm(value index dict keyLen) "DICTSETB"; +(cell, int) tryUdictAddBuilder(cell dict, int keyLen, int index, builder value) asm(value index dict keyLen) "DICTUADDB"; +(cell, int) tryUdictReplaceBuilder(cell dict, int keyLen, int index, builder value) asm(value index dict keyLen) "DICTUREPLACEB"; +(cell, int) tryIdictAddBuilder(cell dict, int keyLen, int index, builder value) asm(value index dict keyLen) "DICTIADDB"; +(cell, int) tryIdictReplaceBuilder(cell dict, int keyLen, int index, builder value) asm(value index dict keyLen) "DICTIREPLACEB"; +(cell, int, slice, int) udictDeleteGetMin(cell dict, int keyLen) asm(-> 0 2 1 3) "DICTUREMMIN" "NULLSWAPIFNOT2"; +(cell, (int, slice, int)) ~udict::deleteGetMin(cell dict, int keyLen) asm(-> 0 2 1 3) "DICTUREMMIN" "NULLSWAPIFNOT2"; +(cell, int, slice, int) idictDeleteGetMin(cell dict, int keyLen) asm(-> 0 2 1 3) "DICTIREMMIN" "NULLSWAPIFNOT2"; +(cell, (int, slice, int)) ~idict::deleteGetMin(cell dict, int keyLen) asm(-> 0 2 1 3) "DICTIREMMIN" "NULLSWAPIFNOT2"; +(cell, slice, slice, int) dictDeleteGetMin(cell dict, int keyLen) asm(-> 0 2 1 3) "DICTREMMIN" "NULLSWAPIFNOT2"; +(cell, (slice, slice, int)) ~dict::deleteGetMin(cell dict, int keyLen) asm(-> 0 2 1 3) "DICTREMMIN" "NULLSWAPIFNOT2"; +(cell, int, slice, int) udictDeleteGetMax(cell dict, int keyLen) asm(-> 0 2 1 3) "DICTUREMMAX" "NULLSWAPIFNOT2"; +(cell, (int, slice, int)) ~udict::deleteGetMax(cell dict, int keyLen) asm(-> 0 2 1 3) "DICTUREMMAX" "NULLSWAPIFNOT2"; +(cell, int, slice, int) idictDeleteGetMax(cell dict, int keyLen) asm(-> 0 2 1 3) "DICTIREMMAX" "NULLSWAPIFNOT2"; +(cell, (int, slice, int)) ~idict::deleteGetMax(cell dict, int keyLen) asm(-> 0 2 1 3) "DICTIREMMAX" "NULLSWAPIFNOT2"; +(cell, slice, slice, int) dictDeleteGetMax(cell dict, int keyLen) asm(-> 0 2 1 3) "DICTREMMAX" "NULLSWAPIFNOT2"; +(cell, (slice, slice, int)) ~dict::deleteGetMax(cell dict, int keyLen) asm(-> 0 2 1 3) "DICTREMMAX" "NULLSWAPIFNOT2"; +(int, slice, int) tryUdictGetMin(cell dict, int keyLen) asm (-> 1 0 2) "DICTUMIN" "NULLSWAPIFNOT2"; +(int, slice, int) tryUdictGetMax(cell dict, int keyLen) asm (-> 1 0 2) "DICTUMAX" "NULLSWAPIFNOT2"; +(int, cell, int) tryUdictGetMinRef(cell dict, int keyLen) asm (-> 1 0 2) "DICTUMINREF" "NULLSWAPIFNOT2"; +(int, cell, int) tryUdictGetMaxRef(cell dict, int keyLen) asm (-> 1 0 2) "DICTUMAXREF" "NULLSWAPIFNOT2"; +(int, slice, int) tryIdictGetMin(cell dict, int keyLen) asm (-> 1 0 2) "DICTIMIN" "NULLSWAPIFNOT2"; +(int, slice, int) tryIdictGetMax(cell dict, int keyLen) asm (-> 1 0 2) "DICTIMAX" "NULLSWAPIFNOT2"; +(int, cell, int) tryIdictGetMinRef(cell dict, int keyLen) asm (-> 1 0 2) "DICTIMINREF" "NULLSWAPIFNOT2"; +(int, cell, int) tryIdictGetMaxRef(cell dict, int keyLen) asm (-> 1 0 2) "DICTIMAXREF" "NULLSWAPIFNOT2"; +(int, slice, int) tryUdictGetNext(cell dict, int keyLen, int pivot) asm(pivot dict keyLen -> 1 0 2) "DICTUGETNEXT" "NULLSWAPIFNOT2"; +(int, slice, int) tryUdictGetNexteq(cell dict, int keyLen, int pivot) asm(pivot dict keyLen -> 1 0 2) "DICTUGETNEXTEQ" "NULLSWAPIFNOT2"; +(int, slice, int) tryUdictGetPrev(cell dict, int keyLen, int pivot) asm(pivot dict keyLen -> 1 0 2) "DICTUGETPREV" "NULLSWAPIFNOT2"; +(int, slice, int) tryUdictGetPreveq(cell dict, int keyLen, int pivot) asm(pivot dict keyLen -> 1 0 2) "DICTUGETPREVEQ" "NULLSWAPIFNOT2"; +(int, slice, int) tryIdictGetNext(cell dict, int keyLen, int pivot) asm(pivot dict keyLen -> 1 0 2) "DICTIGETNEXT" "NULLSWAPIFNOT2"; +(int, slice, int) tryIdictGetNexteq(cell dict, int keyLen, int pivot) asm(pivot dict keyLen -> 1 0 2) "DICTIGETNEXTEQ" "NULLSWAPIFNOT2"; +(int, slice, int) tryIdictGetPrev(cell dict, int keyLen, int pivot) asm(pivot dict keyLen -> 1 0 2) "DICTIGETPREV" "NULLSWAPIFNOT2"; +(int, slice, int) tryIdictGetPreveq(cell dict, int keyLen, int pivot) asm(pivot dict keyLen -> 1 0 2) "DICTIGETPREVEQ" "NULLSWAPIFNOT2"; + +;;; Creates an empty dictionary, which is actually a null value. Equivalent to PUSHNULL +cell newDict() asm "NEWDICT"; +;;; Checks whether a dictionary is empty. Equivalent to cell_null?. +int isDictEmpty(cell c) asm "DICTEMPTY"; + + +{- Prefix dictionary primitives -} +(slice, slice, slice, int) tryPfxdictGet(cell dict, int keyLen, slice key) asm(key dict keyLen) "PFXDICTGETQ" "NULLSWAPIFNOT2"; +(cell, int) tryPfxdictSet(cell dict, int keyLen, slice key, slice value) asm(value key dict keyLen) "PFXDICTSET"; +(cell, int) tryPfxdictDelete(cell dict, int keyLen, slice key) asm(key dict keyLen) "PFXDICTDEL"; + +;;; Returns the value of the global configuration parameter with integer index `i` as a `cell` or `null` value. +cell configParam(int x) asm "CONFIGOPTPARAM"; +;;; Checks whether c is a null. Note, that FunC also has polymorphic null? built-in. +int isCellNull(cell c) asm "ISNULL"; + +;;; Creates an output action which would reserve exactly amount nanotoncoins (if mode = 0), at most amount nanotoncoins (if mode = 2), or all but amount nanotoncoins (if mode = 1 or mode = 3), from the remaining balance of the account. It is roughly equivalent to creating an outbound message carrying amount nanotoncoins (or b − amount nanotoncoins, where b is the remaining balance) to oneself, so that the subsequent output actions would not be able to spend more money than the remainder. Bit +2 in mode means that the external action does not fail if the specified amount cannot be reserved; instead, all remaining balance is reserved. Bit +8 in mode means `amount <- -amount` before performing any further actions. Bit +4 in mode means that amount is increased by the original balance of the current account (before the compute phase), including all extra currencies, before performing any other checks and actions. Currently, amount must be a non-negative integer, and mode must be in the range 0..15. +() rawReserve(int amount, int mode) impure asm "RAWRESERVE"; +;;; Similar to raw_reserve, but also accepts a dictionary extra_amount (represented by a cell or null) with extra currencies. In this way currencies other than TonCoin can be reserved. +() rawReserveExtra(int amount, cell extraAmount, int mode) impure asm "RAWRESERVEX"; +;;; Sends a raw message contained in msg, which should contain a correctly serialized object Message X, with the only exception that the source address is allowed to have dummy value addr_none (to be automatically replaced with the current smart contract address), and ihr_fee, fwd_fee, created_lt and created_at fields can have arbitrary values (to be rewritten with correct values during the action phase of the current transaction). Integer parameter mode contains the flags. Currently mode = 0 is used for ordinary messages; mode = 128 is used for messages that are to carry all the remaining balance of the current smart contract (instead of the value originally indicated in the message); mode = 64 is used for messages that carry all the remaining value of the inbound message in addition to the value initially indicated in the new message (if bit 0 is not set, the gas fees are deducted from this amount); mode' = mode + 1 means that the sender wants to pay transfer fees separately; mode' = mode + 2 means that any errors arising while processing this message during the action phase should be ignored. Finally, mode' = mode + 32 means that the current account must be destroyed if its resulting balance is zero. This flag is usually employed together with +128. +() sendRawMessage(cell msg, int mode) impure asm "SENDRAWMSG"; +;;; Creates an output action that would change this smart contract code to that given by cell new_code. Notice that this change will take effect only after the successful termination of the current run of the smart contract +() setCode(cell newCode) impure asm "SETCODE"; + +;;; Generates a new pseudo-random unsigned 256-bit integer x. The algorithm is as follows: if r is the old value of the random seed, considered as a 32-byte array (by constructing the big-endian representation of an unsigned 256-bit integer), then its sha512(r) is computed; the first 32 bytes of this hash are stored as the new value r' of the random seed, and the remaining 32 bytes are returned as the next random value x. +int random() impure asm "RANDU256"; +;;; Generates a new pseudo-random integer z in the range 0..range−1 (or range..−1, if range < 0). More precisely, an unsigned random value x is generated as in random; then z := x * range / 2^256 is computed. +int rand(int range) impure asm "RAND"; +;;; Returns the current random seed as an unsigned 256-bit Integer. +int getSeed() impure asm "RANDSEED"; +;;; Sets the random seed to unsigned 256-bit seed. +() setSeed(int) impure asm "SETRAND"; +;;; Mixes unsigned 256-bit integer x into the random seed r by setting the random seed to sha256 of the concatenation of two 32-byte strings: the first with the big-endian representation of the old seed r, and the second with the big-endian representation of x. +() randomize(int x) impure asm "ADDRAND"; +;;; Equivalent to randomize(cur_lt());. +() randomizeLt() impure asm "LTIME" "ADDRAND"; + +;;; Checks whether the data parts of two slices coinside +int equalSliceBits (slice a, slice b) asm "SDEQ"; + +;;; Concatenates two builders +builder storeBuilder(builder to, builder from) asm "STBR"; diff --git a/lite-client/lite-client.cpp b/lite-client/lite-client.cpp index dd6df40f7..f31f2f0c7 100644 --- a/lite-client/lite-client.cpp +++ b/lite-client/lite-client.cpp @@ -40,6 +40,7 @@ #include "td/utils/Random.h" #include "td/utils/crypto.h" #include "td/utils/overloaded.h" +#include "td/utils/StringCase.h" #include "td/utils/port/signals.h" #include "td/utils/port/stacktrace.h" #include "td/utils/port/StdStreams.h" @@ -1225,7 +1226,7 @@ bool TestNode::get_account_state(ton::WorkchainId workchain, ton::StdSmcAddress td::int64 TestNode::compute_method_id(std::string method) { td::int64 method_id; if (!convert_int64(method, method_id)) { - method_id = (td::crc16(td::Slice{method}) & 0xffff) | 0x10000; + method_id = (td::crc16(td::Slice{td::StringCase::is_camel_case(method) ? td::StringCase::camel_to_snake(method) : method}) & 0xffff) | 0x10000; } return method_id; } diff --git a/tdutils/CMakeLists.txt b/tdutils/CMakeLists.txt index f1e4b1ea5..e44f97899 100644 --- a/tdutils/CMakeLists.txt +++ b/tdutils/CMakeLists.txt @@ -116,6 +116,7 @@ set(TDUTILS_SOURCE td/utils/StackAllocator.cpp td/utils/Status.cpp td/utils/StringBuilder.cpp + td/utils/StringCase.cpp td/utils/Time.cpp td/utils/Timer.cpp td/utils/TsFileLog.cpp @@ -248,6 +249,7 @@ set(TDUTILS_SOURCE td/utils/Storer.h td/utils/StorerBase.h td/utils/StringBuilder.h + td/utils/StringCase.h td/utils/tests.h td/utils/ThreadLocalStorage.h td/utils/ThreadSafeCounter.h diff --git a/tdutils/td/utils/StringCase.cpp b/tdutils/td/utils/StringCase.cpp new file mode 100644 index 000000000..b4f4b9c4c --- /dev/null +++ b/tdutils/td/utils/StringCase.cpp @@ -0,0 +1,69 @@ +#include "StringCase.h" +#include + +namespace td { + +bool StringCase::is_camel_case(const std::string& input_str) { + if (input_str.empty() || !::islower(input_str[0])) + return false; + + for (char c : input_str) { + if (::isupper(c)) { + return true; + } + } + + return false; +} + +bool StringCase::is_snake_case(const std::string& input_str) { + if (input_str.empty() || !::islower(input_str[0])) + return false; + + for (char c : input_str) { + if (::isupper(c) || c == ' ') { + return false; + } + } + + return true; +} + + +std::string StringCase::camel_to_snake(const std::string& input_str) { + std::string result; + result.reserve(input_str.size() + std::count_if(input_str.begin(), input_str.end(), ::isupper)); + + if (!input_str.empty()) { + result += static_cast(::tolower(input_str[0])); + } + + for (size_t i = 1; i < input_str.size(); ++i) { + if (::isupper(input_str[i])) { + result += "_"; + } + result += static_cast(::tolower(input_str[i])); + } + + return result; +} + + +std::string StringCase::snake_to_camel(const std::string& input_str) { + std::string result; + result.reserve(input_str.size()); + bool capitalizeNext = false; + + for (char c : input_str) { + if (c == '_') { + capitalizeNext = true; + } else { + result += capitalizeNext ? static_cast(::toupper(c)) : c; + capitalizeNext = false; + } + } + + return result; +} + +} diff --git a/tdutils/td/utils/StringCase.h b/tdutils/td/utils/StringCase.h new file mode 100644 index 000000000..ccfe85bbe --- /dev/null +++ b/tdutils/td/utils/StringCase.h @@ -0,0 +1,15 @@ +#pragma once + +#include + +namespace td { + +class StringCase { + public: + static bool is_camel_case(const std::string& input_str); + static bool is_snake_case(const std::string& input_str); + static std::string camel_to_snake(const std::string& input_str); + static std::string snake_to_camel(const std::string& input_str); +}; + +}