raz / lib / Str.raz

989 lines · 34.0 KiB · raw · history · last change e0d008cd

1(* Operations on strings, which are []const U8. = and # compare them; this
2 module orders, searches and hashes them, trims them and takes them
3 apart, tells an ASCII character's kind and changes a letter's case,
4 joins them and replaces in them, reads and writes their UTF-8, reads
5 a number from one and writes one, and copies one to keep. A part it
6 gives is a slice of the string it was given, with no memory of its
7 own. *)
8module Str;
9import Mem, Heap, Rt, Bytes, Buf;
10import SYSTEM;
11
12const least = -9223372036854775807 - 1; (* the smallest I64 *)
13
14(* s's bytes, copied into memory from a, to keep after s's own are
15 gone; "" and false if a has no room. *)
16proc copy*(a: ^Mem.Allocator; s: []const U8): ([]U8, BOOL);
17var p: ^U8;
18begin
19 if LEN(s) = 0 then return [], true; end;
20 p := Mem.alloc(a, LEN(s), 1);
21 if p = nil then return [], false; end;
22 COPY(p[0..LEN(s)], s);
23 return p[0..LEN(s)], true;
24end;
25
26(* Gives back to a a copy that copy made from it; "", which copy gives
27 for an empty string, was never a's, and is left alone. *)
28proc free*(a: ^Mem.Allocator; s: []U8);
29begin
30 if LEN(s) > 0 then Mem.free(a, SYSTEM.ADR(s[0])); end;
31end;
32
33(* -1, 0 or 1 as a sorts before, with or after b, byte by byte. *)
34proc cmp*(a, b: []const U8): INT;
35var i, n: INT;
36begin
37 n := LEN(a);
38 if LEN(b) < n then n := LEN(b); end;
39 for i := 0 to n - 1 do
40 if a[i] # b[i] then
41 if a[i] < b[i] then return -1; end;
42 return 1;
43 end;
44 end;
45 if LEN(a) < LEN(b) then return -1; end;
46 if LEN(a) > LEN(b) then return 1; end;
47 return 0;
48end;
49
50(* Whether a and b hold the same bytes: a = b, as a procedure value. *)
51proc eq*(a, b: []const U8): BOOL;
52begin
53 return a = b;
54end;
55
56(* c, a small letter if it is an ASCII capital. *)
57proc small(c: U8): U8;
58begin
59 if (c >= 'A') and (c <= 'Z') then return c + 32; end;
60 return c;
61end;
62
63(* Whether a and b are the same but for the case of ASCII letters. *)
64proc eqFold*(a, b: []const U8): BOOL;
65var i: INT;
66begin
67 if LEN(a) # LEN(b) then return false; end;
68 for i := 0 to LEN(a) - 1 do
69 if small(a[i]) # small(b[i]) then return false; end;
70 end;
71 return true;
72end;
73
74(* FNV-1a, 64 bits. *)
75proc hash*(s: []const U8): U64;
76var h: U64; i: INT;
77begin
78 h := 0CBF29CE484222325H;
79 for i := 0 to LEN(s) - 1 do
80 h := (h xor U64(s[i])) * 100000001B3H;
81 end;
82 return h;
83end;
84
85(* Where sub first starts in s, or -1. *)
86proc find*(s, sub: []const U8): INT;
87begin
88 return Bytes.find(s, sub);
89end;
90
91(* Where sub first starts in s at or after from, or -1; from is at
92 most LEN(s). *)
93proc findFrom*(s, sub: []const U8; from: INT): INT;
94var i: INT;
95begin
96 i := Bytes.find(s[from..LEN(s)], sub);
97 if i < 0 then return -1; end;
98 return from + i;
99end;
100
101(* Where sub last starts in s, or -1. *)
102proc findLast*(s, sub: []const U8): INT;
103var i: INT;
104begin
105 for i := LEN(s) - LEN(sub) to 0 by -1 do
106 if s[i..i + LEN(sub)] = sub then return i; end;
107 end;
108 return -1;
109end;
110
111(* Whether s starts with p. *)
112proc hasPrefix*(s, p: []const U8): BOOL;
113begin
114 return (LEN(s) >= LEN(p)) and (s[0..LEN(p)] = p);
115end;
116
117(* Whether s ends with x. *)
118proc hasSuffix*(s, x: []const U8): BOOL;
119begin
120 return (LEN(s) >= LEN(x)) and (s[LEN(s) - LEN(x)..LEN(s)] = x);
121end;
122
123(* Whether c is a space: a blank, a tab, a line feed, a vertical tab, a
124 form feed or a carriage return. *)
125proc isSpace*(c: U8): BOOL;
126begin
127 return (c = ' ') or (c >= 9) and (c <= 13);
128end;
129
130(* Whether c is an ASCII digit, 0 to 9. *)
131proc isDigit*(c: U8): BOOL;
132begin
133 return (c >= '0') and (c <= '9');
134end;
135
136(* Whether c is an ASCII letter, A to Z or a to z. *)
137proc isLetter*(c: U8): BOOL;
138begin
139 return (small(c) >= 'a') and (small(c) <= 'z');
140end;
141
142(* Whether c is printable ASCII and neither a letter, a digit nor the
143 blank: one of !"#$%&'()*+,-./:;<=>?@[\]^_`{|}~. *)
144proc isPunct*(c: U8): BOOL;
145begin
146 return (c > ' ') and (c < 127) and not isLetter(c) and not isDigit(c);
147end;
148
149(* c's value as a hexadecimal digit, capital or small; -1 if it isn't one. *)
150proc hexVal*(c: U8): INT;
151begin
152 match c of
153 | '0'..'9': return INT(c) - '0';
154 | 'A'..'F': return INT(c) - 'A' + 10;
155 | 'a'..'f': return INT(c) - 'a' + 10;
156 | else: return -1;
157 end;
158end;
159
160(* s without the spaces at its start. *)
161proc trimLeft*(s: []const U8): []const U8;
162var i: INT;
163begin
164 i := 0;
165 while (i < LEN(s)) and isSpace(s[i]) do INC(i); end;
166 return s[i..LEN(s)];
167end;
168
169(* s without the spaces at its end. *)
170proc trimRight*(s: []const U8): []const U8;
171var n: INT;
172begin
173 n := LEN(s);
174 while (n > 0) and isSpace(s[n - 1]) do DEC(n); end;
175 return s[0..n];
176end;
177
178(* s without the spaces at either end. *)
179proc trim*(s: []const U8): []const U8;
180begin
181 return trimRight(trimLeft(s));
182end;
183
184(* What comes before the first sep in s, what comes after it, and true;
185 or s, an empty string and false if s has no sep. *)
186proc cut*(s, sep: []const U8): ([]const U8, []const U8, BOOL);
187var i: INT;
188begin
189 i := find(s, sep);
190 if i < 0 then return s, s[LEN(s)..LEN(s)], false; end;
191 return s[0..i], s[i + LEN(sep)..LEN(s)], true;
192end;
193
194(* The first word of s, the bytes after the spaces at its start up to
195 the next space or the end, and the rest of s from there; two empty
196 strings if s holds only spaces. *)
197proc field*(s: []const U8): ([]const U8, []const U8);
198var i: INT;
199begin
200 s := trimLeft(s);
201 i := 0;
202 while (i < LEN(s)) and not isSpace(s[i]) do INC(i); end;
203 return s[0..i], s[i..LEN(s)];
204end;
205
206(* s's ASCII capitals made small, in place. *)
207proc lower*(s: []U8);
208var i: INT;
209begin
210 for i := 0 to LEN(s) - 1 do s[i] := small(s[i]); end;
211end;
212
213(* s's small ASCII letters made capitals, in place. *)
214proc upper*(s: []U8);
215var i: INT;
216begin
217 for i := 0 to LEN(s) - 1 do
218 if (s[i] >= 'a') and (s[i] <= 'z') then s[i] := s[i] - 32; end;
219 end;
220end;
221
222(* The parts added to b, with sep between each two. *)
223proc join*(var b: Buf.Buf; parts: [][]const U8; sep: []const U8);
224var i: INT;
225begin
226 for i := 0 to LEN(parts) - 1 do
227 if i > 0 then Buf.str(b, sep); end;
228 Buf.str(b, parts[i]);
229 end;
230end;
231
232(* s added to b, with new for each old in it, from the left, none
233 overlapping another; s as it is if old is empty. *)
234proc replace*(var b: Buf.Buf; s, old, new: []const U8);
235var i: INT;
236begin
237 i := -1;
238 if LEN(old) > 0 then i := find(s, old); end;
239 while i >= 0 do
240 Buf.str(b, s[0..i]);
241 Buf.str(b, new);
242 s := s[i + LEN(old)..LEN(s)];
243 i := find(s, old);
244 end;
245 Buf.str(b, s);
246end;
247
248(* c in UTF-8: its bytes, and how many. A number that isn't a
249 character, a surrogate or one past 10FFFFH, becomes FFFDH, the
250 character that stands for a wrong one. *)
251proc encode*(c: I32): ([4]U8, INT);
252var b: [4]U8;
253begin
254 if (c < 0) or (c > 10FFFFH) or (c >= 0D800H) and (c <= 0DFFFH) then c := 0FFFDH; end;
255 if c < 80H then
256 b[0] := U8(c);
257 return b, 1;
258 elsif c < 800H then
259 b[0] := U8(0C0H + (c shr 6));
260 b[1] := U8(80H + (c & 3FH));
261 return b, 2;
262 elsif c < 10000H then
263 b[0] := U8(0E0H + (c shr 12));
264 b[1] := U8(80H + (c shr 6 & 3FH));
265 b[2] := U8(80H + (c & 3FH));
266 return b, 3;
267 end;
268 b[0] := U8(0F0H + (c shr 18));
269 b[1] := U8(80H + (c shr 12 & 3FH));
270 b[2] := U8(80H + (c shr 6 & 3FH));
271 b[3] := U8(80H + (c & 3FH));
272 return b, 4;
273end;
274
275(* The character s starts with, and its length in bytes: FFFDH and 1
276 if its first byte doesn't start one rightly, being a continuation,
277 or followed by too few continuations, or spelling a surrogate or a
278 character in more bytes than it needs; 0 and 0 if s is empty. *)
279proc decode*(s: []const U8): (I32, INT);
280var c, least: I32; n, i: INT;
281begin
282 if LEN(s) = 0 then return 0, 0; end;
283 c := I32(s[0]);
284 if c < 80H then return c, 1;
285 elsif c < 0C0H then return 0FFFDH, 1;
286 elsif c < 0E0H then n := 2; c := c & 1FH; least := 80H;
287 elsif c < 0F0H then n := 3; c := c & 0FH; least := 800H;
288 elsif c < 0F8H then n := 4; c := c & 7H; least := 10000H;
289 else return 0FFFDH, 1;
290 end;
291 if LEN(s) < n then return 0FFFDH, 1; end;
292 for i := 1 to n - 1 do
293 if s[i] & 0C0H # 80H then return 0FFFDH, 1; end;
294 c := c shl 6 + I32(s[i] & 3FH);
295 end;
296 if (c < least) or (c > 10FFFFH) or (c >= 0D800H) and (c <= 0DFFFH) then return 0FFFDH, 1; end;
297 return c, n;
298end;
299
300(* The character s ends with, and its length in bytes, read as decode
301 reads one: FFFDH and 1 if the last byte doesn't end one rightly; 0
302 and 0 if s is empty. *)
303proc decodeLast*(s: []const U8): (I32, INT);
304var c: I32; i, n: INT;
305begin
306 if LEN(s) = 0 then return 0, 0; end;
307 (* back to the byte that starts it, at most 3 continuations back *)
308 i := LEN(s) - 1;
309 while (i > 0) and (i > LEN(s) - 4) and (s[i] & 0C0H = 80H) do DEC(i); end;
310 c, n := decode(s[i..LEN(s)]);
311 if i + n # LEN(s) then return 0FFFDH, 1; end;
312 return c, n;
313end;
314
315(* The character at i in s, as decode reads it, and where the one after
316 it starts; 0 and -1 if i is at the end or past it. *)
317proc next*(s: []const U8; i: INT): (I32, INT);
318var c: I32; n: INT;
319begin
320 if i >= LEN(s) then return 0, -1; end;
321 c, n := decode(s[i..LEN(s)]);
322 return c, i + n;
323end;
324
325(* The characters in s, as decode reads them, each byte that doesn't
326 start one rightly counted as one. *)
327proc chars*(s: []const U8): INT;
328var i, n: INT;
329begin
330 _, i := next(s, 0);
331 while i >= 0 do
332 INC(n);
333 _, i := next(s, i);
334 end;
335 return n;
336end;
337
338(* Whether s is UTF-8: decode finds no byte that doesn't start a
339 character rightly. *)
340proc valid*(s: []const U8): BOOL;
341var c: I32; i, n: INT;
342begin
343 while i < LEN(s) do
344 c, n := decode(s[i..LEN(s)]);
345 if (c = 0FFFDH) and (n = 1) then return false; end;
346 INC(i, n);
347 end;
348 return true;
349end;
350
351(* s as a decimal number, with a - or + before it if any, and nothing
352 else; false if it isn't one, or an I64 can't hold it. *)
353proc toInt*(s: []const U8): (I64, BOOL);
354var n, d: I64; i: INT; neg: BOOL;
355begin
356 neg := (LEN(s) > 0) and (s[0] = '-');
357 if (LEN(s) > 0) and ((s[0] = '-') or (s[0] = '+')) then i := 1; end;
358 if i = LEN(s) then return 0, false; end;
359 (* the digits are taken off below zero, since the smallest I64 has no positive *)
360 while i < LEN(s) do
361 if (s[i] < '0') or (s[i] > '9') then return 0, false; end;
362 d := I64(s[i] - '0');
363 if n < (least + d) div 10 then return 0, false; end;
364 n := n * 10 - d;
365 INC(i);
366 end;
367 if not neg then
368 if n = least then return 0, false; end;
369 n := -n;
370 end;
371 return n, true;
372end;
373
374(* s in hexadecimal, digits only, capitals or not; false if it isn't
375 that, or a U64 can't hold it. *)
376proc toHex*(s: []const U8): (U64, BOOL);
377var v: U64; d, i: INT;
378begin
379 if LEN(s) = 0 then return 0, false; end;
380 for i := 0 to LEN(s) - 1 do
381 d := hexVal(s[i]);
382 if d < 0 then return 0, false; end;
383 if v shr 60 # 0 then return 0, false; end;
384 v := v shl 4 | U64(d);
385 end;
386 return v, true;
387end;
388
389const
390 (* The digits of RFC 4648: section 4's base64, and section 5's, which
391 has - and _ for + and / and is safe in a URL or a file name. *)
392 Base64* = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
393 Base64Url* = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
394
395(* The bytes base64 makes of n bytes: 4 for each 3, or part of 3. *)
396proc base64Size*(n: INT): INT;
397begin
398 return (n + 2) div 3 * 4;
399end;
400
401(* s in base64 into out, which holds base64Size(LEN(s)) bytes at least;
402 a shorter out stops the program at the byte it lacks, as any slice
403 does. alphabet holds the 64 digits (Base64 or Base64Url, or one's
404 own). A last group of 1 or 2 bytes is padded with = to four if pad,
405 and else has 2 or 3 digits. The bytes written. *)
406proc base64With*(s: []const U8; out: []U8; alphabet: []const U8; pad: BOOL): INT;
407var i, k, v, left: INT;
408begin
409 k := 0;
410 i := 0;
411 while i < LEN(s) do
412 left := LEN(s) - i; (* the bytes not yet taken; 3 or more fill a group *)
413 v := INT(s[i]) shl 16;
414 if left > 1 then v := v | (INT(s[i + 1]) shl 8); end;
415 if left > 2 then v := v | INT(s[i + 2]); end;
416 out[k] := alphabet[v shr 18];
417 out[k + 1] := alphabet[(v shr 12) & 63];
418 INC(k, 2);
419 if left > 1 then
420 out[k] := alphabet[(v shr 6) & 63];
421 INC(k);
422 elsif pad then
423 out[k] := '=';
424 INC(k);
425 end;
426 if left > 2 then
427 out[k] := alphabet[v & 63];
428 INC(k);
429 elsif pad then
430 out[k] := '=';
431 INC(k);
432 end;
433 INC(i, 3);
434 end;
435 return k;
436end;
437
438(* s in base64 (RFC 4648, section 4), padded, into out as base64With
439 writes it. *)
440proc base64*(s: []const U8; out: []U8): INT;
441begin
442 return base64With(s, out, Base64, true);
443end;
444
445(* c's value as a digit of alphabet, 0 to 63, or -1 if it isn't one; = is -1. *)
446proc base64Val(c: U8; alphabet: []const U8): INT;
447var i: INT;
448begin
449 for i := 0 to 63 do
450 if alphabet[i] = c then return i; end;
451 end;
452 return -1;
453end;
454
455(* The last 2 or 3 digits of an unpadded s, at s, decoded into out:
456 the bytes written, 1 or 2; or -1 if a digit isn't one, or the bits
457 that no byte uses aren't 0. *)
458proc unbase64Tail(s: []const U8; out: []U8; alphabet: []const U8): INT;
459var a, b, c: INT;
460begin
461 a := base64Val(s[0], alphabet);
462 b := base64Val(s[1], alphabet);
463 if (a < 0) or (b < 0) then return -1; end;
464 out[0] := U8(((a shl 6) | b) shr 4);
465 if LEN(s) = 2 then
466 if b & 15 # 0 then return -1; end; (* b's low 4 bits belong to no byte *)
467 return 1;
468 end;
469 c := base64Val(s[2], alphabet);
470 if (c < 0) or (c & 3 # 0) then return -1; end; (* c's low 2 bits belong to no byte *)
471 out[1] := U8((((a shl 12) | (b shl 6) | c) shr 2) & 255);
472 return 2;
473end;
474
475(* s, base64 with the digits of alphabet, decoded into out, which holds
476 (LEN(s) + 3) div 4 * 3 bytes at least; a shorter out stops the
477 program at the byte it lacks, as any slice does. The bytes written,
478 and true; or 0 and false, with out left in no state to use, if s is
479 not base64 as the RFC writes it and in no other way. With pad: its
480 length a multiple of 4, every byte a digit but the last one or two,
481 which may be = (and then both of the last two are, or the last
482 alone). Without: no =, and a length that is not 1 more than a
483 multiple of 4. Either way the bits of the last digit that no byte
484 uses are 0, so a byte string has the one spelling that base64 gives
485 it (RFC 4648, section 3.5 allows a decoder to take that). Line
486 breaks, and padding or its lack, are the caller's to mend first. *)
487proc unbase64With*(s: []const U8; out: []U8; alphabet: []const U8; pad: BOOL): (INT, BOOL);
488var i, k, a, b, c, d, v, whole, n: INT; last: BOOL;
489begin
490 whole := LEN(s); (* the bytes in groups of 4 *)
491 if pad then
492 if LEN(s) mod 4 # 0 then return 0, false; end;
493 else
494 whole := LEN(s) div 4 * 4;
495 if LEN(s) mod 4 = 1 then return 0, false; end;
496 end;
497 k := 0;
498 i := 0;
499 while i < whole do
500 last := i + 4 = LEN(s); (* padding is for the last group only *)
501 a := base64Val(s[i], alphabet);
502 b := base64Val(s[i + 1], alphabet);
503 c := base64Val(s[i + 2], alphabet);
504 d := base64Val(s[i + 3], alphabet);
505 if (a < 0) or (b < 0) then return 0, false; end;
506 v := (a shl 6) | b;
507 out[k] := U8(v shr 4);
508 if c >= 0 then
509 v := (v shl 6) | c;
510 out[k + 1] := U8((v shr 2) & 255);
511 if d >= 0 then
512 out[k + 2] := U8(((v shl 6) | d) & 255);
513 INC(k, 3);
514 elsif pad and last and (s[i + 3] = '=') and (c & 3 = 0) then
515 INC(k, 2); (* "xxx=": c's low 2 bits belong to no byte *)
516 else
517 return 0, false;
518 end;
519 elsif pad and last and (s[i + 2] = '=') and (s[i + 3] = '=') and (b & 15 = 0) then
520 INC(k); (* "xx==": b's low 4 bits belong to no byte *)
521 else
522 return 0, false;
523 end;
524 INC(i, 4);
525 end;
526 if whole < LEN(s) then
527 n := unbase64Tail(s[whole..LEN(s)], out[k..LEN(out)], alphabet);
528 if n < 0 then return 0, false; end;
529 INC(k, n);
530 end;
531 return k, true;
532end;
533
534(* s, base64 (RFC 4648, section 4), padded, decoded into out as
535 unbase64With reads it; out holds LEN(s) div 4 * 3 bytes at least. *)
536proc unbase64*(s: []const U8; out: []U8): (INT, BOOL);
537begin
538 return unbase64With(s, out, Base64, true);
539end;
540
541(* s as a decimal number, digits only; false if it isn't one, or a U64
542 can't hold it. *)
543proc toU64*(s: []const U8): (U64, BOOL);
544var v, d: U64; i: INT;
545begin
546 if LEN(s) = 0 then return 0, false; end;
547 for i := 0 to LEN(s) - 1 do
548 if not isDigit(s[i]) then return 0, false; end;
549 d := U64(s[i] - '0');
550 if v > (0FFFFFFFFFFFFFFFFH - d) div 10 then return 0, false; end;
551 v := v * 10 + d;
552 end;
553 return v, true;
554end;
555
556(* The bytes at p up to its zero byte, not copied; "" for nil. *)
557proc fromC*(p: ^U8): []const U8;
558var n: INT;
559begin
560 if p = nil then return ""; end;
561 while p[n] # 0 do INC(n); end;
562 return p[0..n];
563end;
564
565(* s copied into out with a zero byte after it, for C: out holds
566 LEN(s) + 1 bytes at least, or the program stops at the byte it
567 lacks, as any slice does. The pointer C is given, SYSTEM.PTR(out). *)
568proc toC*(s: []const U8; out: []U8): ^U8;
569var i: INT;
570begin
571 for i := 0 to LEN(s) - 1 do out[i] := s[i]; end;
572 out[LEN(s)] := 0;
573 return SYSTEM.PTR(out);
574end;
575
576(* n in decimal, as Out.int writes it: its bytes, the first of the 20,
577 and how many. *)
578proc fromInt*(n: I64): ([20]U8, INT);
579var t, d: [20]U8; u: U64; i: INT;
580begin
581 (* as a U64, which holds the smallest I64's magnitude *)
582 if n < 0 then u := U64(-(n + 1)) + 1; else u := U64(n); end;
583 i := 20;
584 repeat
585 DEC(i);
586 t[i] := U8(u mod 10) + '0';
587 u := u div 10;
588 until u = 0;
589 if n < 0 then DEC(i); t[i] := '-'; end;
590 COPY(d[0..20 - i], t[i..20]);
591 return d, 20 - i;
592end;
593
594(* The bytes of s, at most 8, as an unsigned number, the first byte
595 the lowest: how a file or a message in little-endian order is read,
596 whatever the machine's own order. *)
597proc le*(s: []const U8): U64;
598var v: U64; i: INT;
599begin
600 if LEN(s) > 8 then Rt.stop("Str.le: more than 8 bytes"); end;
601 for i := LEN(s) - 1 to 0 by -1 do v := v shl 8 | U64(s[i]); end;
602 return v;
603end;
604
605(* As le, the first byte the highest: big-endian, network order. *)
606proc be*(s: []const U8): U64;
607var v: U64; i: INT;
608begin
609 if LEN(s) > 8 then Rt.stop("Str.be: more than 8 bytes"); end;
610 for i := 0 to LEN(s) - 1 do v := v shl 8 | U64(s[i]); end;
611 return v;
612end;
613
614(* v into the bytes of s, at most 8, the lowest first; what doesn't
615 fit is left out. *)
616proc putLE*(s: []U8; v: U64);
617var i: INT;
618begin
619 if LEN(s) > 8 then Rt.stop("Str.putLE: more than 8 bytes"); end;
620 for i := 0 to LEN(s) - 1 do s[i] := U8(v); v := v shr 8; end;
621end;
622
623(* As putLE, the highest first. *)
624proc putBE*(s: []U8; v: U64);
625var i: INT;
626begin
627 if LEN(s) > 8 then Rt.stop("Str.putBE: more than 8 bytes"); end;
628 for i := LEN(s) - 1 to 0 by -1 do s[i] := U8(v); v := v shr 8; end;
629end;
630
631proc testOrder;
632var b: [8]U8;
633begin
634 putLE(b[0..4], 12345678H);
635 if (b[0] # 78H) or (b[3] # 12H) or (le(b[0..4]) # 12345678H) or (be(b[0..2]) # 7856H) then
636 Rt.stop("Str.putLE");
637 end;
638 putBE(b, 0102030405060708H);
639 if (b[0] # 1) or (b[7] # 8) or (be(b) # 0102030405060708H) or (le(b[6..8]) # 0807H) then
640 Rt.stop("Str.putBE");
641 end;
642 putBE(b[0..2], 0ABCDH);
643 if (be(b[0..2]) # 0ABCDH) or (le(b[0..0]) # 0) then Rt.stop("Str.be"); end;
644end;
645
646proc testUtf8;
647var b: [4]U8; n: INT; c, i: I32;
648begin
649 b, n := encode('a');
650 if (n # 1) or (b[0] # 'a') then Rt.stop("Str.encode: a"); end;
651 b, n := encode(0E9H);
652 if b[0..n] # "é" then Rt.stop("Str.encode: é"); end;
653 b, n := encode(20ACH);
654 if b[0..n] # "€" then Rt.stop("Str.encode: €"); end;
655 b, n := encode(1F600H);
656 if b[0..n] # "😀" then Rt.stop("Str.encode: 😀"); end;
657 b, n := encode(0D800H);
658 if b[0..n] # "\u{FFFD}" then Rt.stop("Str.encode: a surrogate"); end;
659 b, n := encode(110000H);
660 if n # 3 then Rt.stop("Str.encode: past 10FFFFH"); end;
661 (* every character back through decode *)
662 for i := 0 to 10FFFFH do
663 if (i < 0D800H) or (i > 0DFFFH) then
664 b, n := encode(i);
665 c, n := decode(b[0..n]);
666 if c # i then Rt.stop("Str.decode: not what encode wrote"); end;
667 end;
668 end;
669 c, n := decode("");
670 if (c # 0) or (n # 0) then Rt.stop("Str.decode: empty"); end;
671 c, n := decode("é!");
672 if (c # 0E9H) or (n # 2) then Rt.stop("Str.decode: é"); end;
673 b := [80H, 'a', 0, 0];
674 c, n := decode(b[0..2]);
675 if (c # 0FFFDH) or (n # 1) then Rt.stop("Str.decode: a continuation"); end;
676 b := [0E2H, 82H, 'a', 0];
677 c, n := decode(b[0..3]);
678 if (c # 0FFFDH) or (n # 1) then Rt.stop("Str.decode: too few continuations"); end;
679 c, n := decode(b[0..2]);
680 if (c # 0FFFDH) or (n # 1) then Rt.stop("Str.decode: cut short"); end;
681 b := [0C0H, 0AFH, 0, 0];
682 c, n := decode(b[0..2]);
683 if (c # 0FFFDH) or (n # 1) then Rt.stop("Str.decode: overlong"); end;
684 b := [0EDH, 0A0H, 80H, 0];
685 c, n := decode(b[0..3]);
686 if (c # 0FFFDH) or (n # 1) then Rt.stop("Str.decode: a surrogate"); end;
687 b := [0F4H, 90H, 80H, 80H];
688 c, n := decode(b);
689 if (c # 0FFFDH) or (n # 1) then Rt.stop("Str.decode: past 10FFFFH"); end;
690 if not valid(b[1..1]) or valid(b) then Rt.stop("Str.valid"); end;
691 c, n := decodeLast("a€");
692 if (c # 20ACH) or (n # 3) then Rt.stop("Str.decodeLast: €"); end;
693 c, n := decodeLast("");
694 if (c # 0) or (n # 0) then Rt.stop("Str.decodeLast: empty"); end;
695 b := ['a', 0E2H, 82H, 0];
696 c, n := decodeLast(b[0..3]);
697 if (c # 0FFFDH) or (n # 1) then Rt.stop("Str.decodeLast: cut short"); end;
698 b := [80H, 80H, 80H, 80H];
699 c, n := decodeLast(b);
700 if (c # 0FFFDH) or (n # 1) then Rt.stop("Str.decodeLast: continuations"); end;
701 if (chars("héllo😀") # 6) or (chars("") # 0) or (chars(b) # 4) or not valid("héllo😀")
702 then Rt.stop("Str.chars"); end;
703 c, n := next("é!", 0);
704 if (c # 0E9H) or (n # 2) then Rt.stop("Str.next"); end;
705 c, n := next("é!", 2);
706 if (c # '!') or (n # 3) then Rt.stop("Str.next: !"); end;
707 c, n := next("é!", 3);
708 if (c # 0) or (n # -1) then Rt.stop("Str.next: the end"); end;
709end;
710
711proc testParts;
712var b: Buf.Buf; w, rest, k, v: []const U8; ok: BOOL; up: [5]U8;
713begin
714 if not eqFold("Hello", "hELLO") or eqFold("a", "b") or eqFold("a", "ab") or not eqFold("", "")
715 or eqFold("@", "`") then Rt.stop("Str.eqFold"); end;
716 if (findLast("abcabc", "bc") # 4) or (findLast("abc", "x") # -1) or (findLast("abc", "") # 3)
717 or (findLast("ab", "abc") # -1) then Rt.stop("Str.findLast"); end;
718 if not hasSuffix("hello", "lo") or hasSuffix("lo", "hello") or not hasSuffix("x", "")
719 then Rt.stop("Str.hasSuffix"); end;
720 if (trim(" \t a b \r\n") # "a b") or (trimLeft(" a ") # "a ") or (trimRight(" a ") # " a")
721 or (trim(" ") # "") or (trim("") # "") then Rt.stop("Str.trim"); end;
722 k, v, ok := cut("key=val=ue", "=");
723 if not ok or (k # "key") or (v # "val=ue") then Rt.stop("Str.cut"); end;
724 k, v, ok := cut("none", "=");
725 if ok or (k # "none") or (v # "") then Rt.stop("Str.cut: none"); end;
726 w, rest := field(" one two\tthree ");
727 if (w # "one") or (rest # " two\tthree ") then Rt.stop("Str.field"); end;
728 w, rest := field(rest);
729 w, rest := field(rest);
730 if w # "three" then Rt.stop("Str.field: three"); end;
731 w, rest := field(rest);
732 if (w # "") or (rest # "") then Rt.stop("Str.field: none"); end;
733 up := "aB-z9";
734 upper(up);
735 if up # "AB-Z9" then Rt.stop("Str.upper"); end;
736 lower(up);
737 if up # "ab-z9" then Rt.stop("Str.lower"); end;
738 Buf.init(b, Heap.heap);
739 join(b, ["a", "b", "c"], ", ");
740 if Buf.bytes(b) # "a, b, c" then Rt.stop("Str.join"); end;
741 Buf.reset(b);
742 join(b, [], "-");
743 replace(b, "a.b..c", ".", "::");
744 if Buf.bytes(b) # "a::b::::c" then Rt.stop("Str.replace"); end;
745 Buf.reset(b);
746 replace(b, "aaa", "aa", "b");
747 replace(b, "xy", "", "-");
748 if Buf.bytes(b) # "baxy" then Rt.stop("Str.replace: overlapping, empty"); end;
749 Buf.done(b);
750end;
751
752proc testChars;
753var c: INT;
754begin
755 for c := 0 to 255 do
756 if isDigit(U8(c)) # ((c >= 48) and (c <= 57)) then Rt.stop("Str.isDigit"); end;
757 if isLetter(U8(c)) # ((c >= 65) and (c <= 90) or (c >= 97) and (c <= 122)) then Rt.stop("Str.isLetter"); end;
758 if isPunct(U8(c)) # ((c > 32) and (c < 127) and not isLetter(U8(c)) and not isDigit(U8(c))) then
759 Rt.stop("Str.isPunct");
760 end;
761 end;
762 if not isSpace(' ') or not isSpace(9) or not isSpace(13) or isSpace(14) or isSpace('a') then Rt.stop("Str.isSpace"); end;
763 if isPunct(' ') or not isPunct('~') or not isPunct('!') or isPunct(127) then Rt.stop("Str.isPunct: ends"); end;
764 if (hexVal('0') # 0) or (hexVal('9') # 9) or (hexVal('a') # 10) or (hexVal('F') # 15) or (hexVal('g') # -1)
765 or (hexVal('@') # -1) then Rt.stop("Str.hexVal"); end;
766end;
767
768proc testToInt;
769var n: I64; ok: BOOL;
770begin
771 n, ok := toInt("42");
772 if not ok or (n # 42) then Rt.stop("Str.toInt: 42"); end;
773 n, ok := toInt("-17");
774 if not ok or (n # -17) then Rt.stop("Str.toInt: -17"); end;
775 n, ok := toInt("+0");
776 if not ok or (n # 0) then Rt.stop("Str.toInt: +0"); end;
777 n, ok := toInt("9223372036854775807");
778 if not ok or (n # 9223372036854775807) then Rt.stop("Str.toInt: the largest"); end;
779 n, ok := toInt("-9223372036854775808");
780 if not ok or (n # least) then Rt.stop("Str.toInt: the smallest"); end;
781 n, ok := toInt("9223372036854775808");
782 if ok then Rt.stop("Str.toInt: past the largest"); end;
783 n, ok := toInt("-9223372036854775809");
784 if ok then Rt.stop("Str.toInt: past the smallest"); end;
785 n, ok := toInt("");
786 if ok then Rt.stop("Str.toInt: empty"); end;
787 n, ok := toInt("-");
788 if ok then Rt.stop("Str.toInt: a sign alone"); end;
789 n, ok := toInt("12a");
790 if ok then Rt.stop("Str.toInt: a letter"); end;
791 n, ok := toInt(" 1");
792 if ok then Rt.stop("Str.toInt: a space"); end;
793end;
794
795proc testNumbers;
796var u: U64; ok: BOOL; d: [20]U8; n: INT;
797begin
798 u, ok := toU64("18446744073709551615");
799 if not ok or (u # 0FFFFFFFFFFFFFFFFH) then Rt.stop("Str.toU64: the largest"); end;
800 u, ok := toU64("18446744073709551616");
801 if ok then Rt.stop("Str.toU64: past the largest"); end;
802 u, ok := toU64("0042");
803 if not ok or (u # 42) then Rt.stop("Str.toU64: 0042"); end;
804 u, ok := toU64("");
805 if ok then Rt.stop("Str.toU64: empty"); end;
806 u, ok := toU64("+1");
807 if ok then Rt.stop("Str.toU64: +1"); end;
808 u, ok := toU64("-1");
809 if ok then Rt.stop("Str.toU64: -1"); end;
810 u, ok := toU64("12a");
811 if ok then Rt.stop("Str.toU64: 12a"); end;
812 u, ok := toHex("ff");
813 if not ok or (u # 255) then Rt.stop("Str.toHex: ff"); end;
814 u, ok := toHex("FFFFFFFFFFFFFFFF");
815 if not ok or (u # 0FFFFFFFFFFFFFFFFH) then Rt.stop("Str.toHex: the largest"); end;
816 u, ok := toHex("10000000000000000");
817 if ok then Rt.stop("Str.toHex: past the largest"); end;
818 u, ok := toHex("0x1");
819 if ok then Rt.stop("Str.toHex: 0x"); end;
820 u, ok := toHex("");
821 if ok then Rt.stop("Str.toHex: empty"); end;
822 d, n := fromInt(0);
823 if d[0..n] # "0" then Rt.stop("Str.fromInt: 0"); end;
824 d, n := fromInt(-1234);
825 if d[0..n] # "-1234" then Rt.stop("Str.fromInt: -1234"); end;
826 d, n := fromInt(least);
827 if d[0..n] # "-9223372036854775808" then Rt.stop("Str.fromInt: the smallest"); end;
828 d, n := fromInt(9223372036854775807);
829 if d[0..n] # "9223372036854775807" then Rt.stop("Str.fromInt: the largest"); end;
830end;
831
832(* fromC and toC. *)
833proc testC;
834var room: [4]U8; c: [4]U8; p: ^U8;
835begin
836 if LEN(fromC(nil)) # 0 then Rt.stop("Str.fromC: nil"); end;
837 c := "abc\x00";
838 if fromC(SYSTEM.ADR(c[0])) # "abc" then Rt.stop("Str.fromC: abc"); end;
839 c[0] := 0;
840 if LEN(fromC(SYSTEM.ADR(c[0]))) # 0 then Rt.stop("Str.fromC: empty"); end;
841 room := "xxxx";
842 p := toC("abc", room);
843 if (p # SYSTEM.ADR(room[0])) or (room[0..3] # "abc") or (room[3] # 0) then Rt.stop("Str.toC: abc"); end;
844 p := toC("", room);
845 if room[0] # 0 then Rt.stop("Str.toC: empty"); end;
846end;
847
848(* One of the RFC 4648 section 10 vectors: plain codes to coded and back. *)
849proc testVector(plain, coded: []const U8);
850var buf: [16]U8; n: INT; ok: BOOL;
851begin
852 if base64Size(LEN(plain)) # LEN(coded) then Rt.stop("Str.base64Size"); end;
853 n := base64(plain, buf[0..base64Size(LEN(plain))]);
854 if buf[0..n] # coded then Rt.stop("Str.base64: vector"); end;
855 n, ok := unbase64(coded, buf[0..LEN(coded) div 4 * 3]);
856 if not ok or (buf[0..n] # plain) then Rt.stop("Str.unbase64: vector"); end;
857end;
858
859(* s must not decode. *)
860proc testBad(s: []const U8);
861var buf: [16]U8; ok: BOOL;
862begin
863 _, ok := unbase64(s, buf[0..LEN(s) div 4 * 3]);
864 if ok then Rt.stop("Str.unbase64: took a bad string"); end;
865end;
866
867(* Every byte value, in 256 strings of 1 to 256 bytes, goes there and back. *)
868proc testBase64Round;
869var plain: [256]U8; back: [258]U8; coded: [344]U8; i, n: INT; ok: BOOL;
870begin
871 for i := 0 to 255 do plain[i] := U8(i); end;
872 for i := 1 to 256 do
873 n := base64(plain[0..i], coded[0..base64Size(i)]);
874 if n # base64Size(i) then Rt.stop("Str.base64: size"); end;
875 n, ok := unbase64(coded[0..base64Size(i)], back[0..base64Size(i) div 4 * 3]);
876 if not ok or (back[0..n] # plain[0..i]) then Rt.stop("Str.base64: round trip"); end;
877 end;
878end;
879
880(* plain in the other alphabet and unpadded, and back; in the padded
881 form too, with the - and _ of base64url. *)
882proc testUrlVector(plain, bare, padded: []const U8);
883var buf: [16]U8; n: INT; ok: BOOL;
884begin
885 n := base64With(plain, buf[0..base64Size(LEN(plain))], Base64Url, false);
886 if buf[0..n] # bare then Rt.stop("Str.base64With: unpadded"); end;
887 n, ok := unbase64With(bare, buf[0..(LEN(bare) + 3) div 4 * 3], Base64Url, false);
888 if not ok or (buf[0..n] # plain) then Rt.stop("Str.unbase64With: unpadded"); end;
889 n := base64With(plain, buf[0..base64Size(LEN(plain))], Base64Url, true);
890 if buf[0..n] # padded then Rt.stop("Str.base64With: padded"); end;
891 n, ok := unbase64With(padded, buf[0..LEN(padded) div 4 * 3], Base64Url, true);
892 if not ok or (buf[0..n] # plain) then Rt.stop("Str.unbase64With: padded"); end;
893end;
894
895(* s must not decode, unpadded, in base64url's alphabet. *)
896proc testUrlBad(s: []const U8);
897var buf: [16]U8; ok: BOOL;
898begin
899 _, ok := unbase64With(s, buf[0..(LEN(s) + 3) div 4 * 3], Base64Url, false);
900 if ok then Rt.stop("Str.unbase64With: took a bad string"); end;
901end;
902
903(* RFC 4648 section 5's alphabet, padded and not. *)
904proc testBase64Url;
905var buf: [8]U8; ok: BOOL;
906begin
907 testUrlVector("", "", "");
908 testUrlVector("f", "Zg", "Zg==");
909 testUrlVector("fo", "Zm8", "Zm8=");
910 testUrlVector("foo", "Zm9v", "Zm9v");
911 testUrlVector("foob", "Zm9vYg", "Zm9vYg==");
912 testUrlVector("fooba", "Zm9vYmE", "Zm9vYmE=");
913 testUrlVector("foobar", "Zm9vYmFy", "Zm9vYmFy");
914 testUrlVector("\xfb\xff", "-_8", "-_8=");
915 testUrlBad("Z"); (* one digit over *)
916 testUrlBad("Zm9vY");
917 testUrlBad("Zg=="); (* padding, unpadded *)
918 testUrlBad("Zm8=");
919 testUrlBad("Zm+v"); (* base64's digit *)
920 testUrlBad("Zm/v");
921 testUrlBad("Zh"); (* the low 4 bits of h are not 0 *)
922 testUrlBad("Zm9"); (* the low 2 bits of 9 are not 0 *)
923 testUrlBad("Zm9v\n");
924 _, ok := unbase64With("Zg", buf[0..3], Base64, true); (* padding left off *)
925 if ok then Rt.stop("Str.unbase64With: padding left off"); end;
926 _, ok := unbase64With("Zm-v", buf[0..3], Base64, true);
927 if ok then Rt.stop("Str.unbase64With: base64url's digit in base64"); end;
928end;
929
930proc testBase64;
931begin
932 testVector("", "");
933 testVector("f", "Zg==");
934 testVector("fo", "Zm8=");
935 testVector("foo", "Zm9v");
936 testVector("foob", "Zm9vYg==");
937 testVector("fooba", "Zm9vYmE=");
938 testVector("foobar", "Zm9vYmFy");
939 testVector("\xfb\xff", "+/8=");
940 testBad("Zg="); (* length not a multiple of 4 *)
941 testBad("Zg"); (* padding left off *)
942 testBad("Zm9v\n"); (* a line break *)
943 testBad("Zm9!"); (* a byte outside the alphabet *)
944 testBad("Zm-v"); (* base64url's digit *)
945 testBad("Zg==Zm9v"); (* padding in the middle *)
946 testBad("Z=9v"); (* = in a group's second place *)
947 testBad("=m9v"); (* = in a group's first place *)
948 testBad("Zm=v"); (* = before a digit *)
949 testBad("Z==="); (* three pads *)
950 testBad("====");
951 testBad("Zg=A"); (* one pad but a digit last *)
952 testBad("Zh=="); (* the low 4 bits of h are not 0 *)
953 testBad("Zm9="); (* the low 2 bits of 9 are not 0 *)
954 testBad("Zm8=Zm9v"); (* padding, then another group *)
955 testBase64Round;
956 testBase64Url;
957end;
958
959(* The module's test: stops the program if something is wrong. *)
960proc main*;
961var buf: [3]U8; t: []U8; ok: BOOL;
962begin
963 buf := "abc";
964 t, ok := copy(Heap.heap, buf);
965 buf[0] := 'x';
966 if not ok or (t # "abc") then Rt.stop("Str.copy"); end;
967 free(Heap.heap, t);
968 t, ok := copy(Heap.heap, "");
969 free(Heap.heap, t); (* Heap would stop the program at a block it never gave *)
970 if (cmp("a", "b") # -1) or (cmp("b", "a") # 1) or (cmp("ab", "ab") # 0)
971 or (cmp("a", "ab") # -1) or (cmp("", "") # 0) then Rt.stop("Str.cmp"); end;
972 if not eq("x", "x") or eq("x", "y") then Rt.stop("Str.eq"); end;
973 if (hash("") # 0CBF29CE484222325H) or (hash("a") # 0AF63DC4C8601EC8CH) then Rt.stop("Str.hash"); end;
974 if (find("hello", "ll") # 2) or (find("hello", "x") # -1) or (find("", "") # 0)
975 or (find("ab", "abc") # -1) then Rt.stop("Str.find"); end;
976 if not hasPrefix("hello", "he") or hasPrefix("he", "hello") then Rt.stop("Str.hasPrefix"); end;
977 if (findFrom("abcabc", "bc", 1) # 1) or (findFrom("abcabc", "bc", 2) # 4) or (findFrom("abc", "c", 3) # -1)
978 or (findFrom("abc", "", 3) # 3) then Rt.stop("Str.findFrom"); end;
979 testChars;
980 testParts;
981 testUtf8;
982 testToInt;
983 testNumbers;
984 testC;
985 testBase64;
986 testOrder;
987end;
988
989end Str.