1//////////////////////////////////////////////////////////////////////
2// LibFile: strings.scad
3// String manipulation and formatting functions.
4// Includes:
5// include <BOSL2/std.scad>
6// FileGroup: Data Management
7// FileSummary: String manipulation functions.
8// FileFootnotes: STD=Included in std.scad
9//////////////////////////////////////////////////////////////////////
10
11
12// Section: Extracting substrings
13
14// Function: substr()
15// Usage:
16// newstr = substr(str, [pos], [len]);
17// Description:
18// Returns a substring from a string start at position `pos` with length `len`, or
19// if `len` isn't given, the rest of the string.
20// Arguments:
21// str = string to operate on
22// pos = starting index of substring, or vector of first and last position. Default: 0
23// len = length of substring, or omit it to get the rest of the string. If len is zero or less then the emptry string is returned.
24// Example:
25// substr("abcdefg",3,3); // Returns "def"
26// substr("abcdefg",2); // Returns "cdefg"
27// substr("abcdefg",len=3); // Returns "abc"
28// substr("abcdefg",[2,4]); // Returns "cde"
29// substr("abcdefg",len=-2); // Returns ""
30function substr(str, pos=0, len=undef) =
31 is_list(pos) ? _substr(str, pos[0], pos[1]-pos[0]+1) :
32 len == undef ? _substr(str, pos, len(str)-pos) :
33 _substr(str,pos,len);
34
35function _substr(str,pos,len,substr="") =
36 len <= 0 || pos>=len(str) ? substr :
37 _substr(str, pos+1, len-1, str(substr, str[pos]));
38
39
40// Function: suffix()
41// Usage:
42// newstr = suffix(str,len);
43// Description:
44// Returns the last `len` characters from the input string `str`.
45// If `len` is longer than the length of `str`, then the entirety of `str` is returned.
46// Arguments:
47// str = The string to get the suffix of.
48// len = The number of characters of suffix to get.
49function suffix(str,len) =
50 len>=len(str)? str : substr(str, len(str)-len,len);
51
52
53
54// Section: String Searching
55
56
57// Function: str_find()
58// Usage:
59// ind = str_find(str,pattern,[last=],[all=],[start=]);
60// Description:
61// Searches input string `str` for the string `pattern` and returns the index or indices of the matches in `str`.
62// By default `str_find()` returns the index of the first match in `str`. If `last` is true then it returns the index of the last match.
63// If the pattern is the empty string the first match is at zero and the last match is the last character of the `str`.
64// If `start` is set then the search begins at index start, working either forward and backward from that position. If you set `start`
65// and `last` is true then the search will find the pattern if it begins at index `start`. If no match exists, returns `undef`.
66// If you set `all` to true then `str_find()` returns all of the matches in a list, or an empty list if there are no matches.
67// Arguments:
68// str = String to search.
69// pattern = string pattern to search for
70// ---
71// last = set to true to return the last match. Default: false
72// all = set to true to return all matches as a list. Overrides last. Default: false
73// start = index where the search starts
74// Example:
75// str_find("abc123def123abc","123"); // Returns 3
76// str_find("abc123def123abc","b"); // Returns 1
77// str_find("abc123def123abc","1234"); // Returns undef
78// str_find("abc",""); // Returns 0
79// str_find("abc123def123", "123", start=4); // Returns 9
80// str_find("abc123def123abc","123",last=true); // Returns 9
81// str_find("abc123def123abc","b",last=true); // Returns 13
82// str_find("abc123def123abc","1234",last=true); // Returns undef
83// str_find("abc","",last=true); // Returns 3
84// str_find("abc123def123", "123", start=8, last=true)); // Returns 3
85// str_find("abc123def123abc","123",all=true); // Returns [3,9]
86// str_find("abc123def123abc","b",all=true); // Returns [1,13]
87// str_find("abc123def123abc","1234",all=true); // Returns []
88// str_find("abc","",all=true); // Returns [0,1,2]
89function str_find(str,pattern,start=undef,last=false,all=false) =
90 all? _str_find_all(str,pattern) :
91 let( start = first_defined([start,last?len(str)-len(pattern):0]) )
92 pattern==""? start :
93 last? _str_find_last(str,pattern,start) :
94 _str_find_first(str,pattern,len(str)-len(pattern),start);
95
96function _str_find_first(str,pattern,max_sindex,sindex) =
97 sindex<=max_sindex && !substr_match(str,sindex, pattern)?
98 _str_find_first(str,pattern,max_sindex,sindex+1) :
99 (sindex <= max_sindex ? sindex : undef);
100
101function _str_find_last(str,pattern,sindex) =
102 sindex>=0 && !substr_match(str,sindex, pattern)?
103 _str_find_last(str,pattern,sindex-1) :
104 (sindex >=0 ? sindex : undef);
105
106function _str_find_all(str,pattern) =
107 pattern == "" ? count(len(str)) :
108 [for(i=[0:1:len(str)-len(pattern)]) if (substr_match(str,i,pattern)) i];
109
110// Function: substr_match()
111// Usage
112// bool = substr_match(str,start,pattern);
113// Description:
114// Returns true if the string `pattern` matches the string `str` starting
115// at `str[start]`. If the string is too short for the pattern, or
116// `start` is out of bounds---either negative or beyond the end of the
117// string---then substr_match returns false.
118// Arguments:
119// str = String to search
120// start = Starting index for search in str
121// pattern = String pattern to search for
122// Examples:
123// substr_match("abcde",2,"cd"); // Returns true
124// substr_match("abcde",2,"cx"); // Returns false
125// substr_match("abcde",2,"cdef"); // Returns false
126// substr_match("abcde",-2,"cd"); // Returns false
127// substr_match("abcde",19,"cd"); // Returns false
128// substr_match("abc",1,""); // Returns true
129
130//
131// This is carefully optimized for speed. Precomputing the length
132// cuts run time in half when the string is long. Two other string
133// comparison methods were slower.
134function substr_match(str,start,pattern) =
135 len(str)-start <len(pattern)? false
136 : _substr_match_recurse(str,start,pattern,len(pattern));
137
138function _substr_match_recurse(str,sindex,pattern,plen,pindex=0,) =
139 pindex < plen && pattern[pindex]==str[sindex]
140 ? _substr_match_recurse(str,sindex+1,pattern,plen,pindex+1)
141 : (pindex==plen);
142
143
144// Function: starts_with()
145// Usage:
146// bool = starts_with(str,pattern);
147// Description:
148// Returns true if the input string `str` starts with the specified string pattern, `pattern`.
149// Otherwise returns false.
150// Arguments:
151// str = String to search.
152// pattern = String pattern to search for.
153// Example:
154// starts_with("abcdef","abc"); // Returns true
155// starts_with("abcdef","def"); // Returns false
156// starts_with("abcdef",""); // Returns true
157function starts_with(str,pattern) = substr_match(str,0,pattern);
158
159
160// Function: ends_with()
161// Usage:
162// bool = ends_with(str,pattern);
163// Description:
164// Returns true if the input string `str` ends with the specified string pattern, `pattern`.
165// Otherwise returns false.
166// Arguments:
167// str = String to search.
168// pattern = String pattern to search for.
169// Example:
170// ends_with("abcdef","def"); // Returns true
171// ends_with("abcdef","de"); // Returns false
172// ends_with("abcdef",""); // Returns true
173function ends_with(str,pattern) = substr_match(str,len(str)-len(pattern),pattern);
174
175
176
177// Function: str_split()
178// Usage:
179// string_list = str_split(str, sep, [keep_nulls]);
180// Description:
181// Breaks an input string into substrings using a separator or list of separators. If keep_nulls is true
182// then two sequential separator characters produce an empty string in the output list. If keep_nulls is false
183// then no empty strings are included in the output list.
184// .
185// If sep is a single string then each character in sep is treated as a delimiting character and the input string is
186// split at every delimiting character. Empty strings can occur whenever two delimiting characters are sequential.
187// If sep is a list of strings then the input string is split sequentially using each string from the list in order.
188// If keep_nulls is true then the output will have length equal to `len(sep)+1`, possibly with trailing null strings
189// if the string runs out before the separator list.
190// Arguments:
191// str = String to split.
192// sep = a string or list of strings to use for the separator
193// keep_nulls = boolean value indicating whether to keep null strings in the output list. Default: true
194// Example:
195// str_split("abc+def-qrs*iop","*-+"); // Returns ["abc", "def", "qrs", "iop"]
196// str_split("abc+*def---qrs**iop+","*-+");// Returns ["abc", "", "def", "", "", "qrs", "", "iop", ""]
197// str_split("abc def"," "); // Returns ["abc", "", "", "", "", "", "def"]
198// str_split("abc def"," ",keep_nulls=false); // Returns ["abc", "def"]
199// str_split("abc+def-qrs*iop",["+","-","*"]); // Returns ["abc", "def", "qrs", "iop"]
200// str_split("abc+def-qrs*iop",["-","+","*"]); // Returns ["abc+def", "qrs*iop", "", ""]
201function str_split(str,sep,keep_nulls=true) =
202 !keep_nulls ? _remove_empty_strs(str_split(str,sep,keep_nulls=true)) :
203 is_list(sep) ? _str_split_recurse(str,sep,i=0,result=[]) :
204 let( cutpts = concat([-1],sort(flatten(search(sep, str,0))),[len(str)]))
205 [for(i=[0:len(cutpts)-2]) substr(str,cutpts[i]+1,cutpts[i+1]-cutpts[i]-1)];
206
207function _str_split_recurse(str,sep,i,result) =
208 i == len(sep) ? concat(result,[str]) :
209 let(
210 pos = search(sep[i], str),
211 end = pos==[] ? len(str) : pos[0]
212 )
213 _str_split_recurse(
214 substr(str,end+1),
215 sep, i+1,
216 concat(result, [substr(str,0,end)])
217 );
218
219function _remove_empty_strs(list) =
220 list_remove(list, search([""], list,0)[0]);
221
222
223
224// Section: String modification
225
226
227// Function: str_join()
228// Usage:
229// str = str_join(list, [sep]);
230// Description:
231// Returns the concatenation of a list of strings, optionally with a
232// separator string inserted between each string on the list.
233// Arguments:
234// list = list of strings to concatenate
235// sep = separator string to insert. Default: ""
236// Example:
237// str_join(["abc","def","ghi"]); // Returns "abcdefghi"
238// str_join(["abc","def","ghi"], " + "); // Returns "abc + def + ghi"
239function str_join(list,sep="",_i=0, _result="") =
240 _i >= len(list)-1 ? (_i==len(list) ? _result : str(_result,list[_i])) :
241 str_join(list,sep,_i+1,str(_result,list[_i],sep));
242
243
244
245
246// Function: str_strip()
247// Usage:
248// str = str_strip(s,c,[start],[end]);
249// Description:
250// Takes a string `s` and strips off all leading and/or trailing characters that exist in string `c`.
251// By default strips both leading and trailing characters. If you set start or end to true then
252// it will strip only the leading or trailing characters respectively. If you set start
253// or end to false then it will strip only lthe trailing or leading characters.
254// Arguments:
255// s = The string to strip leading or trailing characters from.
256// c = The string of characters to strip.
257// start = if true then strip leading characters
258// end = if true then strip trailing characters
259// Example:
260// str_strip("--##--123--##--","#-"); // Returns: "123"
261// str_strip("--##--123--##--","-"); // Returns: "##--123--##"
262// str_strip("--##--123--##--","#"); // Returns: "--##--123--##--"
263// str_strip("--##--123--##--","#-",end=true); // Returns: "--##--123"
264// str_strip("--##--123--##--","-",end=true); // Returns: "--##--123--##"
265// str_strip("--##--123--##--","#",end=true); // Returns: "--##--123--##--"
266// str_strip("--##--123--##--","#-",start=true); // Returns: "123--##--"
267// str_strip("--##--123--##--","-",start=true); // Returns: "##--123--##--"
268// str_strip("--##--123--##--","#",start=true); // Returns: "--##--123--##--"
269
270function _str_count_leading(s,c,_i=0) =
271 (_i>=len(s)||!in_list(s[_i],[each c]))? _i :
272 _str_count_leading(s,c,_i=_i+1);
273
274function _str_count_trailing(s,c,_i=0) =
275 (_i>=len(s)||!in_list(s[len(s)-1-_i],[each c]))? _i :
276 _str_count_trailing(s,c,_i=_i+1);
277
278function str_strip(s,c,start,end) =
279 let(
280 nstart = (is_undef(start) && !end) ? true : start,
281 nend = (is_undef(end) && !start) ? true : end,
282 startind = nstart ? _str_count_leading(s,c) : 0,
283 endind = len(s) - (nend ? _str_count_trailing(s,c) : 0)
284 )
285 substr(s,startind, endind-startind);
286
287
288
289// Function: str_pad()
290// Usage:
291// padded = str_pad(str, length, char, [left]);
292// Description:
293// Pad the given string `str` with to length `length` with the specified character,
294// which must be a length 1 string. If left is true then pad on the left, otherwise
295// pad on the right. If the string is longer than the specified length the full string
296// is returned unchanged.
297// Arguments:
298// str = string to pad
299// length = length to pad to
300// char = character to pad with. Default: " " (space)
301// left = if true, pad on the left side. Default: false
302function str_pad(str,length,char=" ",left=false) =
303 assert(is_str(str))
304 assert(is_str(char) && len(char)==1, "char must be a single character string")
305 assert(is_bool(left))
306 let(
307 padding = str_join(repeat(char,length-len(str)))
308 )
309 left ? str(padding,str) : str(str,padding);
310
311
312
313// Function: str_replace_char()
314// Usage:
315// newstr = str_replace_char(str, char, replace);
316// Description:
317// Replace every occurence of `char` in the input string with the string `replace` which
318// can be any string.
319function str_replace_char(str,char,replace) =
320 assert(is_str(str))
321 assert(is_str(char) && len(char)==1, "Search pattern 'char' must be a single character string")
322 assert(is_str(replace))
323 str_join([for(c=str) c==char ? replace : c]);
324
325
326// Function: downcase()
327// Usage:
328// newstr = downcase(str);
329// Description:
330// Returns the string with the standard ASCII upper case letters A-Z replaced
331// by their lower case versions.
332// Arguments:
333// str = String to convert.
334// Example:
335// downcase("ABCdef"); // Returns "abcdef"
336function downcase(str) =
337 str_join([for(char=str) let(code=ord(char)) code>=65 && code<=90 ? chr(code+32) : char]);
338
339
340// Function: upcase()
341// Usage:
342// newstr = upcase(str);
343// Description:
344// Returns the string with the standard ASCII lower case letters a-z replaced
345// by their upper case versions.
346// Arguments:
347// str = String to convert.
348// Example:
349// upcase("ABCdef"); // Returns "ABCDEF"
350function upcase(str) =
351 str_join([for(char=str) let(code=ord(char)) code>=97 && code<=122 ? chr(code-32) : char]);
352
353
354// Section: Random strings
355
356// Function: rand_str()
357// Usage:
358// str = rand_str(n, [charset], [seed]);
359// Description:
360// Produce a random string of length `n`. If you give a string `charset` then the
361// characters of the random string are drawn from that list, weighted by the number
362// of times each character appears in the list. If you do not give a character set
363// then the string is generated with characters ranging from 0 to z (based on
364// character code).
365function rand_str(n, charset, seed) =
366 is_undef(charset)? str_join([for(c=rand_int(48,122,n,seed)) chr(c)])
367 : str_join([for(i=rand_int(0,len(charset)-1,n,seed)) charset[i]]);
368
369
370
371// Section: Parsing strings into numbers
372
373// Function: parse_int()
374// Usage:
375// num = parse_int(str, [base])
376// Description:
377// Converts a string into an integer with any base up to 16. Returns NaN if
378// conversion fails. Digits above 9 are represented using letters A-F in either
379// upper case or lower case.
380// Arguments:
381// str = String to convert.
382// base = Base for conversion, from 2-16. Default: 10
383// Example:
384// parse_int("349"); // Returns 349
385// parse_int("-37"); // Returns -37
386// parse_int("+97"); // Returns 97
387// parse_int("43.9"); // Returns nan
388// parse_int("1011010",2); // Returns 90
389// parse_int("13",2); // Returns nan
390// parse_int("dead",16); // Returns 57005
391// parse_int("CEDE", 16); // Returns 52958
392// parse_int(""); // Returns 0
393function parse_int(str,base=10) =
394 str==undef ? undef :
395 len(str)==0 ? 0 :
396 let(str=downcase(str))
397 str[0] == "-" ? -_parse_int_recurse(substr(str,1),base,len(str)-2) :
398 str[0] == "+" ? _parse_int_recurse(substr(str,1),base,len(str)-2) :
399 _parse_int_recurse(str,base,len(str)-1);
400
401function _parse_int_recurse(str,base,i) =
402 let(
403 digit = search(str[i],"0123456789abcdef"),
404 last_digit = digit == [] || digit[0] >= base ? (0/0) : digit[0]
405 ) i==0 ? last_digit :
406 _parse_int_recurse(str,base,i-1)*base + last_digit;
407
408
409// Function: parse_float()
410// Usage:
411// num = parse_float(str);
412// Description:
413// Converts a string to a floating point number. Returns NaN if the
414// conversion fails.
415// Arguments:
416// str = String to convert.
417// Example:
418// parse_float("44"); // Returns 44
419// parse_float("3.4"); // Returns 3.4
420// parse_float("-99.3332"); // Returns -99.3332
421// parse_float("3.483e2"); // Returns 348.3
422// parse_float("-44.9E2"); // Returns -4490
423// parse_float("7.342e-4"); // Returns 0.0007342
424// parse_float(""); // Returns 0
425function parse_float(str) =
426 str==undef ? undef :
427 len(str) == 0 ? 0 :
428 in_list(str[1], ["+","-"]) ? (0/0) : // Don't allow --3, or +-3
429 str[0]=="-" ? -parse_float(substr(str,1)) :
430 str[0]=="+" ? parse_float(substr(str,1)) :
431 let(esplit = str_split(str,"eE") )
432 len(esplit)==2 ? parse_float(esplit[0]) * pow(10,parse_int(esplit[1])) :
433 let( dsplit = str_split(str,["."]))
434 parse_int(dsplit[0])+parse_int(dsplit[1])/pow(10,len(dsplit[1]));
435
436
437// Function: parse_frac()
438// Usage:
439// num = parse_frac(str,[mixed=],[improper=],[signed=]);
440// Description:
441// Converts a string fraction to a floating point number. A string fraction has the form `[-][# ][#/#]` where each `#` is one or more of the
442// digits 0-9, and there is an optional sign character at the beginning.
443// The full form is a sign character and an integer, followed by exactly one space, followed by two more
444// integers separated by a "/" character. The leading integer and
445// space can be omitted or the trailing fractional part can be omitted. If you set `mixed` to false then the leading integer part is not
446// accepted and the input must include a slash. If you set `improper` to false then the fractional part must be a proper fraction, where
447// the numerator is smaller than the denominator. If you set `signed` to false then the leading sign character is not permitted.
448// The empty string evaluates to zero. Any invalid string evaluates to NaN.
449// Arguments:
450// str = String to convert.
451// ---
452// mixed = set to true to accept mixed fractions, false to reject them. Default: true
453// improper = set to true to accept improper fractions, false to reject them. Default: true
454// signed = set to true to accept a leading sign character, false to reject. Default: true
455// Example:
456// parse_frac("3/4"); // Returns 0.75
457// parse_frac("-77/9"); // Returns -8.55556
458// parse_frac("+1/3"); // Returns 0.33333
459// parse_frac("19"); // Returns 19
460// parse_frac("2 3/4"); // Returns 2.75
461// parse_frac("-2 12/4"); // Returns -5
462// parse_frac(""); // Returns 0
463// parse_frac("3/0"); // Returns inf
464// parse_frac("0/0"); // Returns nan
465// parse_frac("-77/9",improper=false); // Returns nan
466// parse_frac("-2 12/4",improper=false); // Returns nan
467// parse_frac("-2 12/4",signed=false); // Returns nan
468// parse_frac("-2 12/4",mixed=false); // Returns nan
469// parse_frac("2 1/4",mixed=false); // Returns nan
470function parse_frac(str,mixed=true,improper=true,signed=true) =
471 str == undef ? undef :
472 len(str)==0 ? 0 :
473 signed && str[0]=="-" ? -parse_frac(substr(str,1),mixed=mixed,improper=improper,signed=false) :
474 signed && str[0]=="+" ? parse_frac(substr(str,1),mixed=mixed,improper=improper,signed=false) :
475 mixed ? (
476 !in_list(str_find(str," "), [undef,0]) || is_undef(str_find(str,"/"))? (
477 let(whole = str_split(str,[" "]))
478 _parse_int_recurse(whole[0],10,len(whole[0])-1) + parse_frac(whole[1], mixed=false, improper=improper, signed=false)
479 ) : parse_frac(str,mixed=false, improper=improper)
480 ) : (
481 let(split = str_split(str,"/"))
482 len(split)!=2 ? (0/0) :
483 let(
484 numerator = _parse_int_recurse(split[0],10,len(split[0])-1),
485 denominator = _parse_int_recurse(split[1],10,len(split[1])-1)
486 ) !improper && numerator>=denominator? (0/0) :
487 denominator<0 ? (0/0) : numerator/denominator
488 );
489
490
491// Function: parse_num()
492// Usage:
493// num = parse_num(str);
494// Description:
495// Converts a string to a number. The string can be either a fraction (two integers separated by a "/") or a floating point number.
496// Returns NaN if the conversion fails.
497// Example:
498// parse_num("3/4"); // Returns 0.75
499// parse_num("3.4e-2"); // Returns 0.034
500function parse_num(str) =
501 str == undef ? undef :
502 let( val = parse_frac(str) )
503 val == val ? val :
504 parse_float(str);
505
506
507
508
509// Section: Formatting numbers into strings
510
511// Function: format_int()
512// Usage:
513// str = format_int(i, [mindigits]);
514// Description:
515// Formats an integer number into a string. This can handle larger numbers than `str()`.
516// Arguments:
517// i = The integer to make a string of.
518// mindigits = If the number has fewer than this many digits, pad the front with zeros until it does. Default: 1.
519// Example:
520// str(123456789012345); // Returns "1.23457e+14"
521// format_int(123456789012345); // Returns "123456789012345"
522// format_int(-123456789012345); // Returns "-123456789012345"
523function format_int(i,mindigits=1) =
524 i<0? str("-", format_int(-i,mindigits)) :
525 let(i=floor(i), e=floor(log(i)))
526 i==0? str_join([for (j=[0:1:mindigits-1]) "0"]) :
527 str_join(
528 concat(
529 [for (j=[0:1:mindigits-e-2]) "0"],
530 [for (j=[e:-1:0]) str(floor(i/pow(10,j)%10))]
531 )
532 );
533
534
535// Function: format_fixed()
536// Usage:
537// s = format_fixed(f, [digits]);
538// Description:
539// Given a floating point number, formats it into a string with the given number of digits after the decimal point.
540// Arguments:
541// f = The floating point number to format.
542// digits = The number of digits after the decimal to show. Default: 6
543function format_fixed(f,digits=6) =
544 assert(is_int(digits))
545 assert(digits>0)
546 is_list(f)? str("[",str_join(sep=", ", [for (g=f) format_fixed(g,digits=digits)]),"]") :
547 str(f)=="nan"? "nan" :
548 str(f)=="inf"? "inf" :
549 f<0? str("-",format_fixed(-f,digits=digits)) :
550 assert(is_num(f))
551 let(
552 sc = pow(10,digits),
553 scaled = floor(f * sc + 0.5),
554 whole = floor(scaled/sc),
555 part = floor(scaled-(whole*sc))
556 ) str(format_int(whole),".",format_int(part,digits));
557
558
559// Function: format_float()
560// Usage:
561// str = format_float(f,[sig]);
562// Description:
563// Formats the given floating point number `f` into a string with `sig` significant digits.
564// Strips trailing `0`s after the decimal point. Strips trailing decimal point.
565// If the number can be represented in `sig` significant digits without a mantissa, it will be.
566// If given a list of numbers, recursively prints each item in the list, returning a string like `[3,4,5]`
567// Arguments:
568// f = The floating point number to format.
569// sig = The number of significant digits to display. Default: 12
570// Example:
571// format_float(PI,12); // Returns: "3.14159265359"
572// format_float([PI,-16.75],12); // Returns: "[3.14159265359, -16.75]"
573function format_float(f,sig=12) =
574 assert(is_int(sig))
575 assert(sig>0)
576 is_list(f)? str("[",str_join(sep=", ", [for (g=f) format_float(g,sig=sig)]),"]") :
577 f==0? "0" :
578 str(f)=="nan"? "nan" :
579 str(f)=="inf"? "inf" :
580 f<0? str("-",format_float(-f,sig=sig)) :
581 assert(is_num(f))
582 let(
583 e = floor(log(f)),
584 mv = sig - e - 1
585 ) mv == 0? format_int(floor(f + 0.5)) :
586 (e<-sig/2||mv<0)? str(format_float(f*pow(10,-e),sig=sig),"e",e) :
587 let(
588 ff = f + pow(10,-mv)*0.5,
589 whole = floor(ff),
590 part = floor((ff-whole) * pow(10,mv))
591 )
592 str_join([
593 str(whole),
594 str_strip(end=true,
595 str_join([
596 ".",
597 format_int(part, mindigits=mv)
598 ]),
599 "0."
600 )
601 ]);
602
603
604/// Function: _format_matrix()
605/// Usage:
606/// _format_matrix(M, [sig], [sep], [eps])
607/// Description:
608/// Convert a numerical matrix into a matrix of strings where every column
609/// is the same width so it will display in neat columns when printed.
610/// Values below eps will display as zero. The matrix can include nans, infs
611/// or undefs and the rows can be different lengths.
612/// Arguments:
613/// M = numerical matrix to convert
614/// sig = significant digits to display. Default: 4
615// sep = number of spaces between columns or a text string to separate columns. Default: 1
616/// eps = values smaller than this are shown as zero. Default: 1e-9
617function _format_matrix(M, sig=4, sep=1, eps=1e-9) =
618 let(
619 figure_dash = chr(8210),
620 space_punc = chr(8200),
621 space_figure = chr(8199),
622 sep = is_num(sep) && sep>=0 ? str_join(repeat(space_figure,sep))
623 : is_string(sep) ? sep
624 : assert(false,"Invalid separator: must be a string or positive integer giving number of spaces"),
625 strarr=
626 [for(row=M)
627 [for(entry=row)
628 let(
629 text = is_undef(entry) ? "und"
630 : !is_num(entry) ? str_join(repeat(figure_dash,2))
631 : abs(entry) < eps ? "0" // Replace hyphens with figure dashes
632 : str_replace_char(format_float(entry, sig),"-",figure_dash),
633 have_dot = is_def(str_find(text, "."))
634 )
635 // If the text lacks a dot we add a space the same width as a dot to
636 // maintain alignment
637 str(have_dot ? "" : space_punc, text)
638 ]
639 ],
640 maxwidth = max([for(row=M) len(row)]),
641 // Find maximum length for each column. Some entries in a column may be missing.
642 maxlen = [for(i=[0:1:maxwidth-1])
643 max(
644 [for(j=idx(M)) i>=len(M[j]) ? 0 : len(strarr[j][i])])
645 ],
646 padded =
647 [for(row=strarr)
648 str_join([for(i=idx(row))
649 let(
650 extra = ends_with(row[i],"inf") ? 1 : 0
651 )
652 str_pad(row[i],maxlen[i]+extra,space_figure,left=true)],sep=sep)]
653 )
654 padded;
655
656
657
658// Function: format()
659// Usage:
660// s = format(fmt, vals);
661// Description:
662// Given a format string and a list of values, inserts the values into the placeholders in the format string and returns it.
663// Formatting placeholders have the following syntax:
664// - A leading `{` character to show the start of the placeholder.
665// - An integer index into the `vals` list to specify which value should be formatted at that place. If not given, the first placeholder will use index `0`, the second will use index `1`, etc.
666// - An optional `:` separator to indicate that what follows if a formatting specifier. If not given, no formatting info follows.
667// - An optional `-` character to indicate that the value should be left justified if the value needs field width padding. If not given, right justification is used.
668// - An optional `0` character to indicate that the field should be padded with `0`s. If not given, spaces will be used for padding.
669// - An optional integer field width, which the value should be padded to. If not given, no padding will be performed.
670// - An optional `.` followed by an integer precision length, for specifying how many digits to display in numeric formats. If not give, 6 digits is assumed.
671// - An optional letter to indicate the formatting style to use. If not given, `s` is assumed, which will do it's generic best to format any data type.
672// - A trailing `}` character to show the end of the placeholder.
673// .
674// Formatting styles, and their effects are as follows:
675// - `s`: Converts the value to a string with `str()` to display. This is very generic.
676// - `i` or `d`: Formats numeric values as integers.
677// - `f`: Formats numeric values with the precision number of digits after the decimal point. NaN and Inf are shown as `nan` and `inf`.
678// - `F`: Formats numeric values with the precision number of digits after the decimal point. NaN and Inf are shown as `NAN` and `INF`.
679// - `g`: Formats numeric values with the precision number of total significant digits. NaN and Inf are shown as `nan` and `inf`. Mantissas are demarked by `e`.
680// - `G`: Formats numeric values with the precision number of total significant digits. NaN and Inf are shown as `NAN` and `INF`. Mantissas are demarked by `E`.
681// - `b`: If the value logically evaluates as true, it shows as `true`, otherwise `false`.
682// - `B`: If the value logically evaluates as true, it shows as `TRUE`, otherwise `FALSE`.
683// Arguments:
684// fmt = The formatting string, with placeholders to format the values into.
685// vals = The list of values to format.
686// Example(NORENDER):
687// format("The value of {} is {:.14f}.", ["pi", PI]); // Returns: "The value of pi is 3.14159265358979."
688// format("The value {1:f} is known as {0}.", ["pi", PI]); // Returns: "The value 3.141593 is known as pi."
689// format("We use a very small value {1:.6g} as {0}.", ["EPSILON", EPSILON]); // Returns: "We use a very small value 1e-9 as EPSILON."
690// format("{:-5s}{:i}{:b}", ["foo", 12e3, 5]); // Returns: "foo 12000true"
691// format("{:-10s}{:.3f}", ["plecostamus",27.43982]); // Returns: "plecostamus27.440"
692// format("{:-10.9s}{:.3f}", ["plecostamus",27.43982]); // Returns: "plecostam 27.440"
693function format(fmt, vals) =
694 let(
695 parts = str_split(fmt,"{")
696 ) str_join([
697 for(i = idx(parts))
698 let(
699 found_brace = i==0 || [for (c=parts[i]) if(c=="}") c] != [],
700 err = assert(found_brace, "Unbalanced { in format string."),
701 p = i==0? [undef,parts[i]] : str_split(parts[i],"}"),
702 fmta = p[0],
703 raw = p[1]
704 ) each [
705 assert(i<99)
706 is_undef(fmta)? "" : let(
707 fmtb = str_split(fmta,":"),
708 num = is_digit(fmtb[0])? parse_int(fmtb[0]) : (i-1),
709 left = fmtb[1][0] == "-",
710 fmtb1 = default(fmtb[1],""),
711 fmtc = left? substr(fmtb1,1) : fmtb1,
712 zero = fmtc[0] == "0",
713 lch = fmtc==""? "" : fmtc[len(fmtc)-1],
714 hastyp = is_letter(lch),
715 typ = hastyp? lch : "s",
716 fmtd = hastyp? substr(fmtc,0,len(fmtc)-1) : fmtc,
717 fmte = str_split((zero? substr(fmtd,1) : fmtd), "."),
718 wid = parse_int(fmte[0]),
719 prec = parse_int(fmte[1]),
720 val = assert(num>=0&&num<len(vals)) vals[num],
721 unpad = typ=="s"? (
722 let( sval = str(val) )
723 is_undef(prec)? sval :
724 substr(sval, 0, min(len(sval)-1, prec))
725 ) :
726 (typ=="d" || typ=="i")? format_int(val) :
727 typ=="b"? (val? "true" : "false") :
728 typ=="B"? (val? "TRUE" : "FALSE") :
729 typ=="f"? downcase(format_fixed(val,default(prec,6))) :
730 typ=="F"? upcase(format_fixed(val,default(prec,6))) :
731 typ=="g"? downcase(format_float(val,default(prec,6))) :
732 typ=="G"? upcase(format_float(val,default(prec,6))) :
733 assert(false,str("Unknown format type: ",typ)),
734 padlen = max(0,wid-len(unpad)),
735 padfill = str_join([for (i=[0:1:padlen-1]) zero? "0" : " "]),
736 out = left? str(unpad, padfill) : str(padfill, unpad)
737 )
738 out, raw
739 ]
740 ]);
741
742
743
744// Section: Checking character class
745
746// Function: is_lower()
747// Usage:
748// x = is_lower(s);
749// Description:
750// Returns true if all the characters in the given string are lowercase letters. (a-z)
751function is_lower(s) =
752 assert(is_string(s))
753 s==""? false :
754 len(s)>1? all([for (v=s) is_lower(v)]) :
755 let(v = ord(s[0])) (v>=ord("a") && v<=ord("z"));
756
757
758// Function: is_upper()
759// Usage:
760// x = is_upper(s);
761// Description:
762// Returns true if all the characters in the given string are uppercase letters. (A-Z)
763function is_upper(s) =
764 assert(is_string(s))
765 s==""? false :
766 len(s)>1? all([for (v=s) is_upper(v)]) :
767 let(v = ord(s[0])) (v>=ord("A") && v<=ord("Z"));
768
769
770// Function: is_digit()
771// Usage:
772// x = is_digit(s);
773// Description:
774// Returns true if all the characters in the given string are digits. (0-9)
775function is_digit(s) =
776 assert(is_string(s))
777 s==""? false :
778 len(s)>1? all([for (v=s) is_digit(v)]) :
779 let(v = ord(s[0])) (v>=ord("0") && v<=ord("9"));
780
781
782// Function: is_hexdigit()
783// Usage:
784// x = is_hexdigit(s);
785// Description:
786// Returns true if all the characters in the given string are valid hexadecimal digits. (0-9 or a-f or A-F))
787function is_hexdigit(s) =
788 assert(is_string(s))
789 s==""? false :
790 len(s)>1? all([for (v=s) is_hexdigit(v)]) :
791 let(v = ord(s[0]))
792 (v>=ord("0") && v<=ord("9")) ||
793 (v>=ord("A") && v<=ord("F")) ||
794 (v>=ord("a") && v<=ord("f"));
795
796
797// Function: is_letter()
798// Usage:
799// x = is_letter(s);
800// Description:
801// Returns true if all the characters in the given string are standard ASCII letters. (A-Z or a-z)
802function is_letter(s) =
803 assert(is_string(s))
804 s==""? false :
805 all([for (v=s) is_lower(v) || is_upper(v)]);
806
807
808
809
810
811// vim: expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap