diff --git a/Readme.md b/Readme.md index 3323440..e7978a7 100644 --- a/Readme.md +++ b/Readme.md @@ -68,6 +68,9 @@ utils/local_install.sh (read-url "https://api.nasdaq.com/api/calendar/dividends/") ; hangs in sslclient.cpp line 132 ### TODO +- add functions from stdlib into doc +- string-case, save-csv fix doc +- add test for >>> (range 1.5 (inc 5.5)) => (1.500000 2.500000 3.500000 4.500000 5.500000) - better formating of help - unify -f and -run options - add debug support, at least call stack diff --git a/clib/sslclient.cpp b/clib/sslclient.cpp index c3a8b84..c721edd 100644 --- a/clib/sslclient.cpp +++ b/clib/sslclient.cpp @@ -1,16 +1,11 @@ -//============================================================================ -// clang++ -o sslclient sslclient.cpp -lssl -lcrypto -L/usr/local/opt/openssl/lib -I/usr/local/opt/openssl/include -//============================================================================ -// - #include "sslclient.h" #include #include #include -#include #include +#include #include #include #include @@ -20,8 +15,10 @@ // https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/POST // https://developer.mozilla.org/en-US/docs/Web/HTTP/Methods/GET -std::pair HttpClient::doRequest(const std::string &method, const std::string &url, const std::map &headers, const std::string &request_body) { +// TODO user streams instead of printf's + +std::pair HttpClient::doRequest(const std::string &method, const std::string &url, const std::map &headers, const std::string &request_body) { // split url to parts parseURL(url); if (proto != "https") @@ -36,7 +33,7 @@ std::pair HttpClient::doRequest(const std::string &method, con request.append(request_body); // read response - int bytes_read = sslRequest(server, request); // TODO memory leaks ??? + int bytes_read = sslRequest(server, request); if (bytes_read <= 0) { std::cerr << "no data read" << std::endl; return std::make_pair(403, ""); @@ -45,19 +42,18 @@ std::pair HttpClient::doRequest(const std::string &method, con // get headers std::string::size_type position = ssl_read_packet.find("\r\n\r\n"); - if (position == std::string::npos) { - std::cerr << "end of headers not found" << std::endl; - // TODO invalid packet, throw exception - } + if (position == std::string::npos) + throw std::runtime_error("invalid reply, end of headers not found"); + - const std::string hdr = ssl_read_packet.substr(0, position); - auto status_pos = hdr.find("\r\n"); + const std::string response = ssl_read_packet.substr(0, position); + auto status_pos = response.find("\r\n"); - const std::string status_str = hdr.substr(0, status_pos); - const std::string response_headers = hdr.substr(status_pos + 2, hdr.length() - 2 - status_pos); + const std::string response_headers = response.substr(status_pos + 2, response.length() - 2 - status_pos); + const std::string status_string = response.substr(0, status_pos); // parse status code - const int resp_status = responseStatusCode(status_str); + const int resp_status = responseStatusCode(status_string); // parse headers responseHeaders(response_headers); @@ -69,19 +65,19 @@ std::pair HttpClient::doRequest(const std::string &method, con return std::make_pair(resp_status, body); } -void HttpClient::responseHeaders(const std::string &hdr) { - std::istringstream resp(hdr); +void HttpClient::responseHeaders(const std::string &headers) { + std::istringstream resp(headers); std::string header; - std::string::size_type index; + while (std::getline(resp, header) && header != "\r") { - index = header.find(": ", 0); + auto index = header.find(": ", 0); if (index != std::string::npos) headers_map.insert(std::make_pair(header.substr(0, index), header.substr(index + 1))); } } int HttpClient::responseStatusCode(const std::string &status_str) const { - int resp_status = 200; // default is OK + auto resp_status = 200; // default is OK std::regex status_rgx{"^HTTP/\\d\\.\\d (\\d{3}) .+$"}; std::smatch status_matches; @@ -89,15 +85,15 @@ int HttpClient::responseStatusCode(const std::string &status_str) const { if (status_matches.size() > 1) resp_status = std::stoi(status_matches[1].str()); } + return resp_status; } std::string HttpClient::createRequestHeaders(const std::map &headers) { std::string headers_string; - for (const auto & header : headers) { + for (const auto & header : headers) headers_string.append("\r\n" + header.first + ": " + header.second); -// std::cerr << "KEY: `" << it->first << "`, VALUE: `" << it->second << '`' << std::endl; - } + return headers_string; } @@ -154,6 +150,7 @@ int HttpClient::sslRecvPacket() { int len = 16384; char buf[len + 1]; + memset(buf, 0, sizeof(buf)); do { len = SSL_read(ssl, buf, len); if (len >= 0) { diff --git a/doc/Doc.md b/doc/Doc.md index 55b0210..0fc27b6 100644 --- a/doc/Doc.md +++ b/doc/Doc.md @@ -21,146 +21,145 @@ ## Syntax and Special Forms -|Special Form|Argument Evaluations|Purpose| -|:-|-|-| -|`(if cond a b)`|`if` only evaluates its `cond` argument. If `cond` is truthy (non-zero), then `a` is evaluated. Otherwise, `b` is evaluated.|This special form is the main method of control flow.| -|`(cond (test1 action1) (test2 action2) ... (testn actionn))`|The first clause whose test evaluates to non-nil is selected; all other clauses are ignored, and the consequents of the selected clause are evaluated in order. If none of the test conditions are evaluated to be true, then the cond statement returns nil.|This special form is method of control flow.| -|`(do a b c ...)`|`do` takes a list of s-expressions and evaluates them in the order they were given (in the current scope), and then returns the result of the last s-expression.|This special form allows lambda functions to have multi-step bodies.| -|`(scope a b c ...)`|`scope` takes a list of s-expressions and evaluates them in the order they were given _in a new scope_, and then returns the result of the last s-expression.|This special form allows the user to evaluate blocks of code in new scopes.| -|`(defun name params body)`|`defun` evaluates none of its arguments.|This special form allows the user to conveniently define functions.| -|`(define name value)`|`define` evaluates the `value` argument, which is then assigned to `name` in the current scope.|This special form allows the user to bind atoms to values in a scope.| -|`(lambda params body)`|`lambda` evaluates none of its arguments.|This special form allows the user to define anonymous functions.| -|`(quote x)`|`quote` evaluates none of its arguments.|This is equivalent to the `'expr` syntactic sugar.| -|`(for x list ...)`|`for` evaluates only its list argument.|`for` iterates through the list storing each element in `x`, and then evaluating all of the rest of the values in the `for` body. It then returns the last value evaluated.| -|`(while cond ...)`|`while` evaluates only its cond argument.|`while` evaluates its condition expression every iteration before running. If it is true, it continues to evaluate every expression in the `while` body. It then returns the last value evaluated.| -|`(and ...)`|`and` evaluates logical and on its list argument.|`and` evaluates only until its true, it stops when becomes false. -|`(or ...)`|`or` evaluates logical or on its list argument.|`or` evaluates while its false, it stops when becomes true.| -|`(benchmark msg_string ...)`|`benchmark` takes a list of s-expressions and evaluates them in the order they were given (in the current scope), and then returns the result of the last s-expression and prints msg_string and timing info.|| +|Special Form|Argument Evaluations|Purpose|Section| +|:-|-|-|-| +|`(if cond a b)`|`if` only evaluates its `cond` argument. If `cond` is truthy (non-zero), then `a` is evaluated. Otherwise, `b` is evaluated.|This special form is the main method of control flow.|Language| +|`(cond (test1 action1) (test2 action2) ... (testn actionn))`|The first clause whose test evaluates to non-nil is selected; all other clauses are ignored, and the consequents of the selected clause are evaluated in order. If none of the test conditions are evaluated to be true, then the cond statement returns nil.|This special form is method of control flow.|Language| +|`(do a b c ...)`|`do` takes a list of s-expressions and evaluates them in the order they were given (in the current scope), and then returns the result of the last s-expression.|This special form allows lambda functions to have multi-step bodies.|Language| +|`(scope a b c ...)`|`scope` takes a list of s-expressions and evaluates them in the order they were given _in a new scope_, and then returns the result of the last s-expression.|This special form allows the user to evaluate blocks of code in new scopes.|Language| +|`(defun name params body)`|`defun` evaluates none of its arguments.|This special form allows the user to conveniently define functions.|Language| +|`(define name value)`|`define` evaluates the `value` argument, which is then assigned to `name` in the current scope.|This special form allows the user to bind atoms to values in a scope.|Language| +|`(lambda params body)`|`lambda` evaluates none of its arguments.|This special form allows the user to define anonymous functions.|Language| +|`(quote x)`|`quote` evaluates none of its arguments.|This is equivalent to the `'expr` syntactic sugar.|Language| +|`(for x list ...)`|`for` evaluates only its list argument.|`for` iterates through the list storing each element in `x`, and then evaluating all of the rest of the values in the `for` body. It then returns the last value evaluated.|Language| +|`(while cond ...)`|`while` evaluates only its cond argument.|`while` evaluates its condition expression every iteration before running. If it is true, it continues to evaluate every expression in the `while` body. It then returns the last value evaluated.|Language| +|`(and ...)`|`and` evaluates logical and on its list argument.|`and` evaluates only until its true, it stops when becomes false.|Language| +|`(or ...)`|`or` evaluates logical or on its list argument.|`or` evaluates while its false, it stops when becomes true.|Language| +|`(benchmark msg_string ...)`|`benchmark` takes a list of s-expressions and evaluates them in the order they were given (in the current scope), and then returns the result of the last s-expression and prints msg_string and timing info.||Language| ## Library -|Signature|Description|Return values| -|:-|-|-| -|`(= a b)`|Test whether two values are equal|`1` when equal otherwise `nil`| -|`(!= a b)`|Test whether two values are not equal|`1` when not equal otherwise `nil`| -|`(> a b)`|Test whether one value is greater to another |`1` when greater otherwise `nil`| -|`(< a b)`|Test whether one value is less to another |`1` when less otherwise `nil`| -|`(>= a b)`|Test whether one value is greater or equal to another |`1` when greater or equal otherwise `nil`| -|`(<= a b)`|Test whether one value is less or equal to another |`1` when less or equal otherwise `nil`| -|`(+ a b ..)`|Sum multiple values |sum of values| -|`(- a b)`|Substract two values |result of substraction| -|`(* a b ..)`|Multiply several values|result of multiplication| -|`(/ a b)`|Divide two values|result of division| -|`(% a b)`|Remainder of division|result of operation| -|`(list ..)`|Create a list of values|| -|`(insert list index element)`|Insert an element into a list. Indexed from 0|new list with value inserted| -|`(index list index)`|Return element at index in list. First element is at index 0|Element at index| -|`(remove list index)`|Remove a value at an index from a list|List with element removed| -|`(len list)`|Get the length of a list|list length| -|`(push list element)`|Add an item to the end of a list|new list with element added| -|`(pop list)`|Returns last element of list|Last element| -|`(head list)`|Returns first element of a list|First element| -|`(tail list)`|Return all elements of list except first one|List without first element| -|`(first list)`|Returns first element of a list|First element| -|`(last list)`|Returns last element of list|Last element| -|`(range low high)`|Returns list with elements in range low .. high|`(range 1 5) => (1 2 3 4)`| -|`(member list item)`|Returns true when list contains item|| -|`(uniq list)`|Returns list with removed duplicates || -|`(make-list len)`|Return list with len nil elements|`(make-list 3) => (nil nil nil)`| -|`(make-list-of len value)`|Return list with len value elements|| -|`(map ..)`||`(map (lambda (x) (+ x 10)) '(1 2 3 4 5 6)) => (11 12 13 14 15 16)`| -|`(filter lambda list)`||`(filter (lambda (x) (> x 2)) '(1 2 3 4 5)) => (3 4 5)`| -|`(reduce lambda acumulator list)`||`>>> (reduce (lambda (x y) (+ (* x 10) y)) 0 '(1 2 3 4)) => 1234`| -|`(exit code)`|Exit the program with an integer code|| -|`(quit code)`|Same as (exit ..)|| -|`(print ..)`|Print several values and return the last one|| -|`(input [prompt])`|Get user input with an optional prompt|| -|`(random low high)`|Get a random number between two numbers inclusively|| -|`(include file)`|Read a file and execute its code|| -|`(read-file filename)`|Get the contents of a file|| -|`(read-file-lines filename lambda)`|Reads file and for each line call lambda with passing the line as a parameter|`(read-file-lines "/tmp/f.txt" (lambda (ln) (print ln))`| -|`(write-file filename content-str)`|Write a string to a file|| -|`(read-url url [headers] [body] [method])`|Reads URL|Returns list (status-code content)| -|`(system-cmd command_str)`|Execute system command|| +|Signature|Description|Return values|Section| +|:-|-|-|-| +|`(= a b)`|Test whether two values are equal|`1` when equal otherwise `nil`|Language| +|`(!= a b)`|Test whether two values are not equal|`1` when not equal otherwise `nil`|Language| +|`(> a b)`|Test whether one value is greater to another |`1` when greater otherwise `nil`|Language| +|`(< a b)`|Test whether one value is less to another |`1` when less otherwise `nil`|Language| +|`(>= a b)`|Test whether one value is greater or equal to another |`1` when greater or equal otherwise `nil`|Language| +|`(<= a b)`|Test whether one value is less or equal to another |`1` when less or equal otherwise `nil`|Language| +|`(+ a b ..)`|Sum multiple values |sum of values|Language| +|`(- a b)`|Substract two values |result of substraction|Language| +|`(* a b ..)`|Multiply several values|result of multiplication|Language| +|`(/ a b)`|Divide two values|result of division|Language| +|`(% a b)`|Remainder of division|result of operation|Language| +|`(list ..)`|Create a list of values||List manipulation| +|`(insert list index element)`|Insert an element into a list. Indexed from 0|new list with value inserted|List manipulation| +|`(index list index)`|Return element at index in list. First element is at index 0|Element at index|List manipulation| +|`(remove list index)`|Remove a value at an index from a list|List with element removed|List manipulation| +|`(len list)`|Get the length of a list|list length|List manipulation| +|`(push list element)`|Add an item to the end of a list|new list with element added|List manipulation| +|`(pop list)`|Returns last element of list|Last element|List manipulation| +|`(head list)`|Returns first element of a list|First element|List manipulation| +|`(tail list)`|Return all elements of list except first one|List without first element|List manipulation| +|`(first list)`|Returns first element of a list|First element|List manipulation| +|`(last list)`|Returns last element of list|Last element|List manipulation| +|`(range low high)`|Returns list with elements in range low .. high|`(range 1 5) => (1 2 3 4)`|List manipulation| +|`(member list item)`|Returns true when list contains item||List manipulation| +|`(uniq list)`|Returns list with removed duplicates ||List manipulation| +|`(make-list len)`|Return list with len nil elements|`(make-list 3) => (nil nil nil)`|List manipulation| +|`(make-list-of len value)`|Return list with len value elements||List manipulation| +|`(map ..)`||`(map (lambda (x) (+ x 10)) '(1 2 3 4 5 6)) => (11 12 13 14 15 16)`|List manipulation| +|`(filter lambda list)`||`(filter (lambda (x) (> x 2)) '(1 2 3 4 5)) => (3 4 5)`|List manipulation| +|`(reduce lambda acumulator list)`||`>>> (reduce (lambda (x y) (+ (* x 10) y)) 0 '(1 2 3 4)) => 1234`|List manipulation| +|`(exit code)`|Exit the program with an integer code||System| +|`(quit code)`|Same as (exit ..)||System| +|`(print ..)`|Print several values and return the last one||IO| +|`(input [prompt])`|Get user input with an optional prompt||IO| +|`(random low high)`|Get a random number between two numbers inclusively||System| +|`(include file)`|Read a file and execute its code||IO| +|`(read-file filename)`|Get the contents of a file||IO| +|`(read-file-lines filename lambda)`|Reads file and for each line call lambda with passing the line as a parameter|`(read-file-lines "/tmp/f.txt" (lambda (ln) (print ln))`|IO| +|`(write-file filename content-str)`|Write a string to a file||IO| +|`(read-url url [headers] [body] [method])`|Reads URL|Returns list (status-code content)|IO| +|`(system-cmd command_str)`|Execute system command||System| |`(ls-dir dir)`|List a dir|List of directory entries| -|`(is-file? filename)`|Returns true if passed filename is a file|| -|`(is-dir? filename)`|Returns true if passed filename is a directory|| -|`(tcp-server port handler)`|Starts listening on port and when request comes calls passed lambda and writes its returned value back to client. Lambda must return either string or two element list where first element is boolean and second string.When first element is true it closes listening socker.|(`tcp-server 7777 (lambda (str) (list #t (string-upcase str))))`| -|`(tcp-client address port data)`|Opens connection to server on port, writes there data and returns response.|`(print (tcp-client "127.0.0.1" 7777 "abcd"))`| -|`(is-dir? filename)`|Returns true if passed filename is a directory|| -|`(parse-csv string)`|Parse CSV string|| -|`(parse-json json_string)`|Parse JSON string|| -|`(save-csv ..)`||| -|`(get-universal-time)`|Get current time as secs from epoch|| -|`(get-localtime-offset)`|Offset in seconds between local time and gmt time|| -|`(date-to-str date format)`|Converts date to formated string. Format is strftime format (https://www.tutorialspoint.com/c_standard_library/c_function_strftime.htm)|`>>> (date-to-str (get-universal-time) "%Y-%m-%d %H:%M:%S") - => "2021-03-13 19:53:01"`| -|`(str-to-date string format)`|Converst string to time of secs since epoch. |`>>> (str-to-date "2021-03-13 19:53:01" "%Y-%m-%d %H:%M:%S") => 1615665181`| -|`(date-add date amount unit)`|Add number of units to date. A unit is one of 'year', 'month', 'day', 'hour', 'minute' or 'second'|`>>> (date-to-str (date-add (str-to-date "2021-03-13 19:53:01" "%Y-%m-%d %H:%M:%S") 10 "day") "%Y-%m-%d %H:%M:%S") => "2021-03-23 20:53:01"`| -|`start-of-day datetime`||`>>> (start-of-day (str-to-date "2021-05-13 10:32:12" "%Y-%m-%d %H:%M:%S")) => 1620864000`| -|`end-of-day datetime`||`>>> (end-of-day (str-to-date "2021-05-13 10:32:12" "%Y-%m-%d %H:%M:%S")) => 1620950399`| -|`start-of-month datetime`||`>>> (start-of-month (str-to-date "2021-05-13 10:32:12" "%Y-%m-%d %H:%M:%S")) => 1619827200`| -|`start-of-next-month datetime`||`>>> (end-of-month (str-to-date "2021-05-13 10:32:12" "%Y-%m-%d %H:%M:%S")) => 1622505599`| -|`end-of-next-month datetime`||`>>> (start-of-next-month (str-to-date "2021-05-13 10:32:12" "%Y-%m-%d %H:%M:%S")) => 1622505600`| -|`end-of-month datetime`||`>>> (end-of-next-month (str-to-date "2021-05-13 10:32:12" "%Y-%m-%d %H:%M:%S")) => 1625097599`| -|`start-of-prev-month datetime`||`>>> (start-of-prev-month (str-to-date "2021-05-13 10:32:12" "%Y-%m-%d %H:%M:%S")) => 1617235200`| -|`end-of-prev-month datetime`||`>>> (end-of-prev-month (str-to-date "2021-05-13 10:32:12" "%Y-%m-%d %H:%M:%S")) => 1619827199`| -|`start-of-year datetime`||`>>> (start-of-year (str-to-date "2021-05-13 10:32:12" "%Y-%m-%d %H:%M:%S")) => 1609459200`| -|`end-of-year datetime`||`>>> (end-of-year (str-to-date "2021-05-13 10:32:12" "%Y-%m-%d %H:%M:%S")) => 1640995199`| -|`(debug ..)`||| -|`(display ..)`|Displays passed parameters|`>>> (display '(1 2 3)) => "(1 2 3)"`| -|`(string-replace source substr replacement)`|Replace a substring with a replacement string in a source string|`>>> (string-replace "abcdefg" "de" "DE") => "abcDEfg"`| -|`(string-replace-re source substr replacement)`|Replace a substring regex with a replacement string in a source string|`>>> (string-replace-re "there is a subsequence in the string" "\\b(sub)([^ ]*)" "sub-$2") => "there is a sub-sequence in the string"`| -|`(string-regex? where regex)`| Returns true if where contains regex|`>>> (string-regex? "aba123cdefg" "[0-9]+") => 1`| -|`(string-regex-list where regex [mode] [ignorecase])`| Returns list of substring from where captured by regex in mode match or tokens|`>>> (string-regex-list "12" "(.*?)" "match" "ignore") => (("1" "2"))` `>>> (string-regex-list "12" "(.*?)" "token") => (("1") ("2"))`| -|`(string-pad str len char rpad_lpad)`||| -|`(string-lpad str len char)`|Pad string from start with char to length len|`>>> (string-lpad "0" 10 "x") => "xxxxxxxxx0"`| -|`(string-rpad str len char)`|Pad string from righ with char to length len|`>>> (string-rpad "0" 10 "x") => "0xxxxxxxxx"`| +|`(is-file? filename)`|Returns true if passed filename is a file||IO| +|`(is-dir? filename)`|Returns true if passed filename is a directory||IO| +|`(tcp-server port handler)`|Starts listening on port and when request comes calls passed lambda and writes its returned value back to client. Lambda must return either string or two element list where first element is boolean and second string.When first element is true it closes listening socker.|(`tcp-server 7777 (lambda (str) (list #t (string-upcase str))))`|IO| +|`(tcp-client address port data)`|Opens connection to server on port, writes there data and returns response.|`(print (tcp-client "127.0.0.1" 7777 "abcd"))`|IO| +|`(is-dir? filename)`|Returns true if passed filename is a directory||IO| +|`(parse-csv string)`|Parse CSV string||String manipulation| +|`(parse-json json_string)`|Parse JSON string||String manipulation| +|`(save-csv ..)`|Save list as csv||IO| +|`(get-universal-time)`|Get current time as secs from epoch|`>>> (get-universal-time) => 1642152733`|Date and time| +|`(get-localtime-offset)`|Offset in seconds between local time and gmt time||Date and time| +|`(date-to-str date format)`|Converts date to formated string. Format is strftime format (https://www.tutorialspoint.com/c_standard_library/c_function_strftime.htm)|`>>> (date-to-str (get-universal-time) "%Y-%m-%d %H:%M:%S") => "2021-03-13 19:53:01"`|Date and time| +|`(str-to-date string format)`|Converst string to time of secs since epoch. |`>>> (str-to-date "2021-03-13 19:53:01" "%Y-%m-%d %H:%M:%S") => 1615665181`|Date and time| +|`(date-add date amount unit)`|Add number of units to date. A unit is one of 'year', 'month', 'day', 'hour', 'minute' or 'second'|`>>> (date-to-str (date-add (str-to-date "2021-03-13 19:53:01" "%Y-%m-%d %H:%M:%S") 10 "day") "%Y-%m-%d %H:%M:%S") => "2021-03-23 20:53:01"`|Date and time| +|`start-of-day datetime`||`>>> (start-of-day (str-to-date "2021-05-13 10:32:12" "%Y-%m-%d %H:%M:%S")) => 1620864000`|Date and time| +|`end-of-day datetime`||`>>> (end-of-day (str-to-date "2021-05-13 10:32:12" "%Y-%m-%d %H:%M:%S")) => 1620950399`|Date and time| +|`start-of-month datetime`||`>>> (start-of-month (str-to-date "2021-05-13 10:32:12" "%Y-%m-%d %H:%M:%S")) => 1619827200`|Date and time| +|`start-of-next-month datetime`||`>>> (end-of-month (str-to-date "2021-05-13 10:32:12" "%Y-%m-%d %H:%M:%S")) => 1622505599`|Date and time| +|`end-of-next-month datetime`||`>>> (start-of-next-month (str-to-date "2021-05-13 10:32:12" "%Y-%m-%d %H:%M:%S")) => 1622505600`|Date and time| +|`end-of-month datetime`||`>>> (end-of-next-month (str-to-date "2021-05-13 10:32:12" "%Y-%m-%d %H:%M:%S")) => 1625097599`|Date and time| +|`start-of-prev-month datetime`||`>>> (start-of-prev-month (str-to-date "2021-05-13 10:32:12" "%Y-%m-%d %H:%M:%S")) => 1617235200`|Date and time| +|`end-of-prev-month datetime`||`>>> (end-of-prev-month (str-to-date "2021-05-13 10:32:12" "%Y-%m-%d %H:%M:%S")) => 1619827199`|Date and time| +|`start-of-year datetime`||`>>> (start-of-year (str-to-date "2021-05-13 10:32:12" "%Y-%m-%d %H:%M:%S")) => 1609459200`|Date and time| +|`end-of-year datetime`||`>>> (end-of-year (str-to-date "2021-05-13 10:32:12" "%Y-%m-%d %H:%M:%S")) => 1640995199`|Date and time| +|`(debug ..)`|||IO| +|`(display ..)`|Displays passed parameters|`>>> (display '(1 2 3)) => "(1 2 3)"`|IO| +|`(string-replace source substr replacement)`|Replace a substring with a replacement string in a source string|`>>> (string-replace "abcdefg" "de" "DE") => "abcDEfg"`|String manipulation| +|`(string-replace-re source substr replacement)`|Replace a substring regex with a replacement string in a source string|`>>> (string-replace-re "there is a subsequence in the string" "\\b(sub)([^ ]*)" "sub-$2") => "there is a sub-sequence in the string"`|String manipulation| +|`(string-regex? where regex)`| Returns true if where contains regex|`>>> (string-regex? "aba123cdefg" "[0-9]+") => 1`|Regex| +|`(string-regex-list where regex [mode] [ignorecase])`| Returns list of substring from where captured by regex in mode match or tokens|`>>> (string-regex-list "12" "(.*?)" "match" "ignore") => (("1" "2"))` `>>> (string-regex-list "12" "(.*?)" "token") => (("1") ("2"))`|Regex| +|`(string-pad str len char rpad_lpad)`|||String manipulation| +|`(string-lpad str len char)`|Pad string from start with char to length len|`>>> (string-lpad "0" 10 "x") => "xxxxxxxxx0"`|String manipulation| +|`(string-rpad str len char)`|Pad string from righ with char to length len|`>>> (string-rpad "0" 10 "x") => "0xxxxxxxxx"`|String manipulation| |`(string-split str separator)`|Splits string into list by regexp|`>>> (string-split "split me by space" "\s+") => ("split" "me" "by" "space")`| -`(string-rltrim str len RKRRKR)`| || -`(string-ltrim str)`|Removes " \n\r\t" from the begininfg of str|| -`(string-rtrim str)`|Removes " \n\r\t" from the end of str|| -`(string-trim str)`|Removes " \n\r\t" from the both strart and end of str|| -`(string-case str RKRRKR)`||| -`(string-upcase str)`|Returns up cased string|`>>> (string-upcase "abcdefghchijklmn") => "ABCDEFGHCHIJKLMN"`| -`(string-downcase str)`|Returns down cased string |`>>> (string-downcase "ABCDefghchijklmn") => "abcdefghchijklmn"`| -`(string-join lst sep)`|Returns string created as elements of concatenation of lst elements separated by sep|`>>> (string-join ("A" "B" "C" "D") ",") => "A,B,C,D"`| -`(string-len str)`|Returns string length|`>>> (string-len "abcdef") => 6`| -`(string-substr str pos len`|Returns substring from str starting at pos with len. If pos is negative returns substring from the end of string. First character is on pos 0|`>>> (string-substr "ABCD" -2 2) => "CD"`| -`(string-find str lookup pos`|Returns position of lookup in str starting on position. First char index is 0. If not found returns nil|`>>> (string-find " long long int;" "long" 2) => 6`| -|`(int value)`|Cast an item to an int|`>>> (int 3.41) => 3`| -|`(float value)`|Cast item to a float|`>>> (int 3.41) => 3.14`| -|`(string value)`|Cast int or float item to a string|`>>> (string 3.14) => "3.14"`| -|`(eval )`|Eval returns the value of the second evaluation|`>>> (eval '(+ 1 2)) => 3`| -|`(type e)`|Returns data type of e|`>>> (type (+ 1 2)) => "int"`| -|`(parse ..)`||`>>> (eval (first (parse "(+ 1 2)"))) => 3`| -|`(make-list-of size value)`|Makes list with size elements of values|`>>> (make-list-of 5 0) => (0 0 0 0 0)`| -|`(make-list size)`|Makes list of nil values with size length|`>>> (make-list 5) => (nil nil nil nil nil)`| -|`(empty-list? lst)`|Return true is lst is list with zero elements|`>>> (empty-list? '()) => 1`| -|`(memeber lst item)`|Returns 1 when item is inluded in lst otherwise 0|| -|`(uniq list)`|Filter out any duplicates from list|`>>> (uniq '(1 2 2 3 4 5 2 2)) => (1 2 3 4 5)`| -|`(flatten list)`||`>>> (flatten '(1 (2 2) 3)) => (1 2 2 3)`| -|`(quick-sort-by list cmp)`||| -|`(quick-sort list)`|return sorted list|`>>> (quick-sort '(2 4 6 1 7 3 3 9 5)) => (1 2 3 3 4 5 6 7 9)`| -|`(quick-sort-reverse list)`|return reverse sorted list|`>>> (quick-sort-reverse '(2 4 6 1 7 3 3 9 5)) => (9 7 6 5 4 3 3 2 1)`| -|`(not c)`|Logical NOT of c|`>>> (not 1) => nil`| -|`(neg n)`|Negates number|`>>> (neg -5) => 5`| -|`(is-pos? n)`|Returns true if n is positive number|| -|`(is-neg? n)`|Returns true if n is negative number|| -|`(dec n)`|Return n decremented by 1|`>>> (dec 5) => 4`| -|`(inc n)`|Return n incremented by 1|`>>> (inc 5) => 6`| -|`(sleep time)`|Pauses execution for time interval of seconds|| -|`(get-env var)`|Return environment variable var|`>>> (get-env "HOME") => "/Users/vaclavt"`| -|`(second list)`|Returns second element of list|`>>> (second '(1 2 3 4 5 6 7)) => 2`| -|`(third list)`|Returns third element of list|`>>> (third '(1 2 3 4 5 6 7)) => 3`| -|`(fourth list)`|Returns fourth element of list|`>>> (fourth '(1 2 3 4 5 6 7)) => 4`| -|`(fifth list)`|Returns fifth element of list|`>>> (fifth '(1 2 3 4 5 6 7)) => 5`| -|`(nth i list)`|Return i-th elemenet of list. First element has index 1|`>>> (nth 7 '(1 2 3 4 5 6 7)) => 7`| -|`( make-csv list)`|creates csv string from list of lists|(print (make-csv '(("r1c1" "r1c2") ("r2c1" "r2c2")))) -|`(sprintf ..)`||`>>> (sprintf "%s, %d, %.2f" (list "string" 1000 3.14)) => "string, 1000, 3.14"`| -|`(thread-create code..)`|Creates new thread, starts evalueating code and returns immediatelly thread id|| -|`(thread-under-lock lockname code)`|Acquire lock with lockname and eval code. "ilock" currently is only allowed lockname|| -|`(thread-sleep milisecons)`|Sleeps thread for given amount of miliseconds|| -|`(threads-join)`|Wait for all running threads to finish|| -|`(try block catch_block [finally_block])`|Evaluates block and if an exception is thrown, evaluates catch_block.Eventually in both cases evals finally_block. Return evaluated last expression from block if no exception or last expression from catch_block, if exception is thrown from block. Variable ml-exception in catch block is available with astring describing exception|| -|`(throw-exception exp_desc)`|Throws an exception with exp_desc describing what happened || -|`(xx ..)`||| +|`(string-rltrim str len RKRRKR)`|||Regex| +|`(string-ltrim str)`|Removes " \n\r\t" from the begininfg of str||String manipulation| +|`(string-rtrim str)`|Removes " \n\r\t" from the end of str||String manipulation| +|`(string-trim str)`|Removes " \n\r\t" from the both strart and end of str||String manipulation| +|`(string-case str RKRRKR)`|||String manipulation| +|`(string-upcase str)`|Returns up cased string|`>>> (string-upcase "abcdefghchijklmn") => "ABCDEFGHCHIJKLMN"`|String manipulation| +|`(string-downcase str)`|Returns down cased string |`>>> (string-downcase "ABCDefghchijklmn") => "abcdefghchijklmn"`|String manipulation| +|`(string-join lst sep)`|Returns string created as elements of concatenation of lst elements separated by sep|`>>> (string-join ("A" "B" "C" "D") ",") => "A,B,C,D"`|String manipulation| +|`(string-len str)`|Returns string length|`>>> (string-len "abcdef") => 6`|String manipulation| +|`(string-substr str pos len`|Returns substring from str starting at pos with len. If pos is negative returns substring from the end of string. First character is on pos 0|`>>> (string-substr "ABCD" -2 2) => "CD"`|String manipulation| +|`(string-find str lookup pos`|Returns position of lookup in str starting on position. First char index is 0. If not found returns nil|`>>> (string-find " long long int;" "long" 2) => 6`|String manipulation| +|`(int value)`|Cast an item to an int|`>>> (int 3.41) => 3`|Type casting| +|`(float value)`|Cast item to a float|`>>> (int 3.41) => 3.14`|Type casting| +|`(string value)`|Cast int or float item to a string|`>>> (string 3.14) => "3.14"`|Type casting| +|`(eval )`|Eval returns the value of the second evaluation|`>>> (eval '(+ 1 2)) => 3`|Language| +|`(type e)`|Returns data type of e|`>>> (type (+ 1 2)) => "int"`|Type casting| +|`(parse ..)`||`>>> (eval (first (parse "(+ 1 2)"))) => 3`|Language| +|`(make-list-of size value)`|Makes list with size elements of values|`>>> (make-list-of 5 0) => (0 0 0 0 0)`|List manipulation| +|`(make-list size)`|Makes list of nil values with size length|`>>> (make-list 5) => (nil nil nil nil nil)`|List manipulation| +|`(empty-list? lst)`|Return true is lst is list with zero elements|`>>> (empty-list? '()) => 1`|Type casting| +|`(memeber lst item)`|Returns 1 when item is inluded in lst otherwise 0||List manipulation| +|`(uniq list)`|Filter out any duplicates from list|`>>> (uniq '(1 2 2 3 4 5 2 2)) => (1 2 3 4 5)`|List manipulation| +|`(flatten list)`||`>>> (flatten '(1 (2 2) 3)) => (1 2 2 3)`|List manipulation| +|`(quick-sort-by list cmp)`|||Language| +|`(quick-sort list)`|return sorted list|`>>> (quick-sort '(2 4 6 1 7 3 3 9 5)) => (1 2 3 3 4 5 6 7 9)`|Language| +|`(quick-sort-reverse list)`|return reverse sorted list|`>>> (quick-sort-reverse '(2 4 6 1 7 3 3 9 5)) => (9 7 6 5 4 3 3 2 1)`|Language| +|`(not c)`|Logical NOT of c|`>>> (not 1) => nil`|Logical| +|`(neg n)`|Negates number|`>>> (neg -5) => 5`|Language| +|`(is-pos? n)`|Returns true if n is positive number||Language| +|`(is-neg? n)`|Returns true if n is negative number||Language| +|`(dec n)`|Return n decremented by 1|`>>> (dec 5) => 4`|Language| +|`(inc n)`|Return n incremented by 1|`>>> (inc 5) => 6`|Language| +|`(sleep time)`|Pauses execution for time interval of seconds||System| +|`(get-env var)`|Return environment variable var|`>>> (get-env "HOME") => "/Users/vaclavt"`|System| +|`(second list)`|Returns second element of list|`>>> (second '(1 2 3 4 5 6 7)) => 2`|List manipulation| +|`(third list)`|Returns third element of list|`>>> (third '(1 2 3 4 5 6 7)) => 3`|List manipulation| +|`(fourth list)`|Returns fourth element of list|`>>> (fourth '(1 2 3 4 5 6 7)) => 4`|List manipulation| +|`(fifth list)`|Returns fifth element of list|`>>> (fifth '(1 2 3 4 5 6 7)) => 5`|List manipulation| +|`(nth i list)`|Return i-th elemenet of list. First element has index 1|`>>> (nth 7 '(1 2 3 4 5 6 7)) => 7`|List manipulation| +|`(make-csv list)`|creates csv string from list of lists|(print (make-csv '(("r1c1" "r1c2") ("r2c1" "r2c2"))))|List manipulation| +|`(sprintf ..)`||`>>> (sprintf "%s, %d, %.2f" (list "string" 1000 3.14)) => "string, 1000, 3.14"`|String manipulation| +|`(thread-create code..)`|Creates new thread, starts evalueating code and returns immediatelly thread id||Threading| +|`(thread-under-lock lockname code)`|Acquire lock with lockname and eval code. "ilock" currently is only allowed lockname||Threading| +|`(thread-sleep milisecons)`|Sleeps thread for given amount of miliseconds||Threading| +|`(threads-join)`|Wait for all running threads to finish||Threading| +|`(try block catch_block [finally_block])`|Evaluates block and if an exception is thrown, evaluates catch_block.Eventually in both cases evals finally_block. Return evaluated last expression from block if no exception or last expression from catch_block, if exception is thrown from block. Variable ml-exception in catch block is available with astring describing exception||Exceptions| +|`(throw-exception exp_desc)`|Throws an exception with exp_desc describing what happened ||Exceptions| +|`(xx ..)`|||| diff --git a/ml.cpp b/ml.cpp index f561d63..e87a4fb 100644 --- a/ml.cpp +++ b/ml.cpp @@ -1941,7 +1941,8 @@ MlValue range(std::vector args, MlEnvironment &env) { if (low >= high) return MlValue(result); - while (low < high) { + result.reserve(high.as_int() - low.as_int()); + while (low < high) { // use MlValue to keep number datatype result.push_back(low); low = low + MlValue(1l); }