raz / site / content / advanced / 02-bytes.txt

210 lines · 7.2 KiB · raw · history · last change a5145f64

1title: Strings and bytes
2part: The library
3summary: Copying, hashing and ordering strings, searching bytes many at a time, and reading and writing binary formats.
4---
5A `[]U8` is both a string and a block of bytes. `Str` has what is done with them: comparing, finding, hashing, copying into memory of your own, UTF-8, numbers, and the fixed byte orders of file formats and network protocols. `Bytes` has the searches, made fast.
6
7## Ordering and hashing
8
9`Str.cmp` gives -1, 0 or 1, byte by byte, so it orders UTF-8 text by code point. `Str.eq` is equality. `Str.hash` is FNV-1a, 64 bits; it is what a `Map` of strings uses.
10
11```raz Order run
12module Order;
13import Out, Str, Fmt;
14
15proc main*;
16var names: [4][]const U8; i, j: INT; t: []const U8;
17begin
18 names := ["pear", "Apple", "fig", "apple"];
19 (* a small insertion sort, with Str.cmp *)
20 for i := 1 to 3 do
21 t := names[i];
22 j := i - 1;
23 while (j >= 0) and (Str.cmp(names[j], t) > 0) do
24 names[j + 1] := names[j];
25 DEC(j);
26 end;
27 names[j + 1] := t;
28 end;
29 for i := 0 to 3 do Out.str(names[i]); Out.char(' '); end;
30 Out.ln;
31 Fmt.print("{}\n", [Fmt.hex(Str.hash("raz"))]);
32 if Str.hash("raz") = Str.hash("raz") then Out.str("stable\n"); end;
33end;
34
35end Order.
36```
37
38Upper case sorts before lower, since 'A' is 65 and 'a' is 97: `Str.cmp` doesn't pretend to know a language's alphabet.
39
40## Keeping a string
41
42A slice of a string constant lives forever, but a slice of a buffer lives only as long as the buffer. To keep one past that, `Str.copy` takes memory from an allocator and says whether it got any.
43
44```raz Keep run
45module Keep;
46import Out, Str, Heap, Mem;
47import SYSTEM;
48
49type Entry = record name: []U8; n: INT; end;
50
51var entries: [3]Entry;
52
53(* remembers a name that the caller will overwrite *)
54proc remember(slot: INT; name: []const U8);
55var copy: []U8; ok: BOOL;
56begin
57 copy, ok := Str.copy(Heap.heap, name);
58 if ok then entries[slot].name := copy; entries[slot].n := slot; end;
59end;
60
61proc main*;
62var scratch: [16]U8; i: INT;
63begin
64 for i := 0 to 2 do
65 scratch := "name-";
66 scratch[5] := U8('0' + i);
67 remember(i, scratch[0..6]);
68 scratch := "overwritten!";
69 end;
70 for i := 0 to 2 do
71 Out.str(entries[i].name); Out.char(' ');
72 Mem.free(Heap.heap, ^U8(SYSTEM.ADR(entries[i].name[0])));
73 end;
74 Out.ln;
75end;
76
77end Keep.
78```
79
80## Searching
81
82`Bytes` finds bytes many at a time: `Bytes.index` and `Bytes.last` give the first and the last place of a byte in a `[]U8`, or -1, `Bytes.count` how many places it has, and `Bytes.find` where one `[]U8` first starts in another (`Str.find` is the same). Each is what a loop over the bytes would give, only faster: the library's own body compares eight bytes at once in a `U64`, and on x86-64 a file of its own, `Bytes.x86_64.raz`, compares sixteen with SSE2, in code procedures.
83
84```raz Paths run
85module Paths;
86import Out, Fmt, Bytes;
87
88(* the last part of a path: what follows its last slash *)
89proc base(path: []const U8): []const U8;
90begin
91 return path[Bytes.last(path, '/') + 1..LEN(path)];
92end;
93
94proc main*;
95var text: []const U8; at, n, line: INT;
96begin
97 Out.str(base("/usr/local/lib/raz/Bytes.raz")); Out.char(' ');
98 Out.str(base("Out.raz")); Out.ln;
99
100 text := "one line\nanother line\nthe line with raz in it\nthe last\n";
101 Fmt.print("{} lines\n", [Fmt.int(Bytes.count(text, 10))]);
102 at := Bytes.find(text, "raz");
103 if at >= 0 then
104 (* the line it is on: the newlines before it, plus one *)
105 line := Bytes.count(text[0..at], 10) + 1;
106 n := Bytes.index(text[at..LEN(text)], 10);
107 Fmt.print("raz on line {}, at {}, and the line goes on {} more\n",
108 [Fmt.int(line), Fmt.int(at), Fmt.int(n)]);
109 end;
110 Fmt.print("{} {}\n", [Fmt.int(Bytes.find(text, "zzz")), Fmt.int(Bytes.find(text, ""))]);
111end;
112
113end Paths.
114```
115
116When the byte isn't there, `Bytes.last` gives -1, so `base` of a name with no slash is the whole name. A search of a slice gives places in the slice, counted from its own start: add the place the slice starts at to get one in the whole.
117
118## Binary formats
119
120A file format or a network protocol has a byte order of its own, not the machine's. `Str.le` and `Str.be` read an unsigned number of up to 8 bytes in a fixed order (little- or big-endian) and `Str.putLE` and `Str.putBE` write one. They work on any slice, so a header is read where it lies, with no struct to overlay and no byte swapping to forget.
121
122Here is a small record format: a 4-byte tag, a 2-byte big-endian length, a 4-byte little-endian checksum, then the data.
123
124```raz Frame run
125module Frame;
126import Out, Fmt, Str;
127
128const HeaderSize = 10;
129
130(* the sum of the bytes of data, all mod 2^32 *)
131proc checksum(data: []const U8): U32;
132var i: INT; sum: U32;
133begin
134 for i := 0 to LEN(data) - 1 do sum := sum + U32(data[i]); end;
135 return sum;
136end;
137
138(* writes a frame to out, which must have room; its length *)
139proc pack(out: []U8; tag, data: []const U8): INT;
140begin
141 COPY(out[0..4], tag);
142 Str.putBE(out[4..6], U64(LEN(data)));
143 Str.putLE(out[6..10], U64(checksum(data)));
144 COPY(out[HeaderSize..HeaderSize + LEN(data)], data);
145 return HeaderSize + LEN(data);
146end;
147
148proc main*;
149var buf: [64]U8; n, len: INT; sum: U32; i: INT;
150begin
151 n := pack(buf, "DATA", "hello");
152 for i := 0 to n - 1 do
153 Out.hex(U64(buf[i]), 2); Out.char(' ');
154 end;
155 Out.ln;
156 (* and back *)
157 len := INT(Str.be(buf[4..6]));
158 sum := U32(Str.le(buf[6..10]));
159 Fmt.print("tag {}, {} bytes, checksum {}, ", [Fmt.str(buf[0..4]), Fmt.int(len), Fmt.hex(U64(sum))]);
160 if sum = checksum(buf[HeaderSize..HeaderSize + len]) then
161 Out.str("valid: "); Out.str(buf[HeaderSize..HeaderSize + len]);
162 else
163 Out.str("corrupt");
164 end;
165 Out.ln;
166end;
167
168end Frame.
169```
170
171The output is the same on a little-endian and a big-endian machine, because the bytes are written one at a time in the order the format says.
172
173## Numbers and text
174
175`Str.toInt` reads a decimal number with an optional sign and nothing else, and says whether it was one; `Str.toHex` reads hexadecimal digits, and `Math.toReal` a real, as a constant is written but with `e` for `E` too, to the nearest `F64` exactly. `Str.fromInt` goes the other way into an array of 20 bytes, with no allocator, and `Fmt` does the rest. `Str.encode` and `Str.decode` move between characters and UTF-8, as the first tour showed.
176
177```raz Numbers run
178module Numbers;
179import Out, Str, Math, Fmt;
180
181(* the sum of the numbers in a comma separated list, or -1 if any isn't *)
182proc total(s: []const U8): I64;
183var part: []const U8; sum, n: I64; ok, more: BOOL;
184begin
185 more := true;
186 while more do
187 part, s, more := Str.cut(s, ",");
188 n, ok := Str.toInt(part);
189 if not ok then return -1; end;
190 sum := sum + n;
191 end;
192 return sum;
193end;
194
195proc main*;
196var u: U64; x: F64; ok: BOOL; digits: [20]U8; k: INT;
197begin
198 Out.int(total("10,20,-5,+7")); Out.ln;
199 Out.int(total("10,x,20")); Out.ln;
200 Out.int(total("10,,20")); Out.ln;
201 u, ok := Str.toHex("ff00");
202 if ok then Out.hex(u, 1); Out.ln; end;
203 x, ok := Math.toReal("-1.5e3");
204 if ok then Fmt.print("{}\n", [Fmt.real(x, 1)]); end;
205 digits, k := Str.fromInt(-9223372036854775807 - 1);
206 Out.str(digits[0..k]); Out.ln;
207end;
208
209end Numbers.
210```