raz / site / public / advanced / bytes.html

248 lines · 18.6 KiB · raw · history · last change de634aad

1<!doctype html>
2<html lang="en">
3<head>
4<meta charset="utf-8">
5<meta name="viewport" content="width=device-width, initial-scale=1">
6<title>Strings and bytes - More Raz</title>
7<meta name="description" content="raz: a small systems language in Wirth's tradition, for x86-64 Linux.">
8<meta name="theme-color" content="#E07A5F">
9<meta property="og:title" content="Strings and bytes - More Raz">
10<meta property="og:description" content="A small systems language for x86-64 Linux. No run time, no GC, one report.">
11<meta property="og:image" content="https://raz.lucela.org/social.png">
12<meta name="twitter:card" content="summary_large_image">
13<link rel="icon" href="../favicon.svg" type="image/svg+xml">
14<link rel="icon" href="../favicon-32.png" type="image/png" sizes="32x32">
15<link rel="apple-touch-icon" href="../apple-touch-icon.png">
16<link rel="stylesheet" href="../style.css">
17</head>
18<body>
19<header><nav><a class="mark" href="../index.html"><img src="../logo.svg" width="26" height="26" alt="">raz</a><a href="../tour/index.html">Raz, Set, Go</a><a href="../advanced/index.html" aria-current="page">More Raz</a><a href="../spec.html">Report</a><a href="../source/index.html">Source</a><a href="../index.html#download">Download</a></nav></header>
20<main>
21<div class="tour"><aside><h2>More Raz</h2><h3>The library</h3><ol start='1'>
22<li><a href="fmt.html">Output and formatting</a></li>
23<li><a href="bytes.html" aria-current="page">Strings and bytes</a></li>
24<li><a href="collections.html">Lists, arrays, maps and sorting</a></li>
25<li><a href="files.html">Files and the command line</a></li>
26<li><a href="processes.html">Time, randomness and other programs</a></li>
27<li><a href="allocators.html">Writing an allocator</a></li>
28</ol>
29<h3>Standing alone</h3><ol start='7'>
30<li><a href="static.html">A program with no run time</a></li>
31<li><a href="linkstatic.html">Threads without C, and keeping the two apart</a></li>
32<li><a href="lifecycle.html">Starting, ending, and signals</a></li>
33<li><a href="targets.html">One module, one file per target</a></li>
34</ol>
35<h3>The machine</h3><ol start='11'>
36<li><a href="asm.html">Procedures in assembly</a></li>
37<li><a href="syscalls.html">System calls</a></li>
38<li><a href="listing.html">What the compiler makes</a></li>
39</ol>
40<h3>Shared memory</h3><ol start='14'>
41<li><a href="volatile.html">Volatile</a></li>
42<li><a href="atomics.html">Atomics</a></li>
43<li><a href="ordering.html">Ordering and publication</a></li>
44<li><a href="lockfree.html">A lock-free stack</a></li>
45<li><a href="ring.html">A ring buffer between threads</a></li>
46</ol></aside><article><p class="kicker">The library &middot; lesson 2 of 18</p><h1>Strings and bytes</h1>
47<p>A <code>[]U8</code> is both a string and a block of bytes. <code>Str</code> 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. <code>Bytes</code> has the searches, made fast.</p>
48<h2>Ordering and hashing</h2>
49<p><code>Str.cmp</code> gives -1, 0 or 1, byte by byte, so it orders UTF-8 text by code point. <code>Str.eq</code> is equality. <code>Str.hash</code> is FNV-1a, 64 bits; it is what a <code>Map</code> of strings uses.</p>
50<div class="file"><span>Order.raz</span></div><pre class="code"><code><span class="kw">module</span> Order;
51<span class="kw">import</span> Out, Str, Fmt;
52
53<span class="kw">proc</span> main*;
54<span class="kw">var</span> names: [<span class="number">4</span>][]<span class="kw">const</span> <span class="ty">U8</span>; i, j: <span class="ty">INT</span>; t: []<span class="kw">const</span> <span class="ty">U8</span>;
55<span class="kw">begin</span>
56 names := [<span class="string">&quot;pear&quot;</span>, <span class="string">&quot;Apple&quot;</span>, <span class="string">&quot;fig&quot;</span>, <span class="string">&quot;apple&quot;</span>];
57 <span class="comment">(* a small insertion sort, with Str.cmp *)</span>
58 <span class="kw">for</span> i := <span class="number">1</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span>
59 t := names[i];
60 j := i - <span class="number">1</span>;
61 <span class="kw">while</span> (j &gt;= <span class="number">0</span>) <span class="kw">and</span> (Str.cmp(names[j], t) &gt; <span class="number">0</span>) <span class="kw">do</span>
62 names[j + <span class="number">1</span>] := names[j];
63 <span class="ty">DEC</span>(j);
64 <span class="kw">end</span>;
65 names[j + <span class="number">1</span>] := t;
66 <span class="kw">end</span>;
67 <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">3</span> <span class="kw">do</span> Out.str(names[i]); Out.char(<span class="string">&#x27; &#x27;</span>); <span class="kw">end</span>;
68 Out.ln;
69 Fmt.print(<span class="string">&quot;{}\n&quot;</span>, [Fmt.hex(Str.hash(<span class="string">&quot;raz&quot;</span>))]);
70 <span class="kw">if</span> Str.hash(<span class="string">&quot;raz&quot;</span>) = Str.hash(<span class="string">&quot;raz&quot;</span>) <span class="kw">then</span> Out.str(<span class="string">&quot;stable\n&quot;</span>); <span class="kw">end</span>;
71<span class="kw">end</span>;
72
73<span class="kw">end</span> Order.</code></pre>
74<pre class="output"><code>Apple apple fig pear
7589F6BC1960FF4912
76stable
77</code></pre>
78<p>Upper case sorts before lower, since 'A' is 65 and 'a' is 97: <code>Str.cmp</code> doesn't pretend to know a language's alphabet.</p>
79<h2>Keeping a string</h2>
80<p>A 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, <code>Str.copy</code> takes memory from an allocator and says whether it got any.</p>
81<div class="file"><span>Keep.raz</span></div><pre class="code"><code><span class="kw">module</span> Keep;
82<span class="kw">import</span> Out, Str, Heap, Mem;
83<span class="kw">import</span> SYSTEM;
84
85<span class="kw">type</span> Entry = <span class="kw">record</span> name: []<span class="ty">U8</span>; n: <span class="ty">INT</span>; <span class="kw">end</span>;
86
87<span class="kw">var</span> entries: [<span class="number">3</span>]Entry;
88
89<span class="comment">(* remembers a name that the caller will overwrite *)</span>
90<span class="kw">proc</span> remember(slot: <span class="ty">INT</span>; name: []<span class="kw">const</span> <span class="ty">U8</span>);
91<span class="kw">var</span> copy: []<span class="ty">U8</span>; ok: <span class="ty">BOOL</span>;
92<span class="kw">begin</span>
93 copy, ok := Str.copy(Heap.heap, name);
94 <span class="kw">if</span> ok <span class="kw">then</span> entries[slot].name := copy; entries[slot].n := slot; <span class="kw">end</span>;
95<span class="kw">end</span>;
96
97<span class="kw">proc</span> main*;
98<span class="kw">var</span> scratch: [<span class="number">16</span>]<span class="ty">U8</span>; i: <span class="ty">INT</span>;
99<span class="kw">begin</span>
100 <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">2</span> <span class="kw">do</span>
101 scratch := <span class="string">&quot;name-&quot;</span>;
102 scratch[<span class="number">5</span>] := <span class="ty">U8</span>(<span class="string">&#x27;0&#x27;</span> + i);
103 remember(i, scratch[<span class="number">0</span>..<span class="number">6</span>]);
104 scratch := <span class="string">&quot;overwritten!&quot;</span>;
105 <span class="kw">end</span>;
106 <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="number">2</span> <span class="kw">do</span>
107 Out.str(entries[i].name); Out.char(<span class="string">&#x27; &#x27;</span>);
108 Mem.free(Heap.heap, ^<span class="ty">U8</span>(SYSTEM.<span class="ty">ADR</span>(entries[i].name[<span class="number">0</span>])));
109 <span class="kw">end</span>;
110 Out.ln;
111<span class="kw">end</span>;
112
113<span class="kw">end</span> Keep.</code></pre>
114<pre class="output"><code>name-0 name-1 name-2
115</code></pre>
116<h2>Searching</h2>
117<p><code>Bytes</code> finds bytes many at a time: <code>Bytes.index</code> and <code>Bytes.last</code> give the first and the last place of a byte in a <code>[]U8</code>, or -1, <code>Bytes.count</code> how many places it has, and <code>Bytes.find</code> where one <code>[]U8</code> first starts in another (<code>Str.find</code> 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 <code>U64</code>, and on x86-64 a file of its own, <code>Bytes.x86_64.raz</code>, compares sixteen with SSE2, in code procedures.</p>
118<div class="file"><span>Paths.raz</span></div><pre class="code"><code><span class="kw">module</span> Paths;
119<span class="kw">import</span> Out, Fmt, Bytes;
120
121<span class="comment">(* the last part of a path: what follows its last slash *)</span>
122<span class="kw">proc</span> base(path: []<span class="kw">const</span> <span class="ty">U8</span>): []<span class="kw">const</span> <span class="ty">U8</span>;
123<span class="kw">begin</span>
124 <span class="kw">return</span> path[Bytes.last(path, <span class="string">&#x27;/&#x27;</span>) + <span class="number">1</span>..<span class="ty">LEN</span>(path)];
125<span class="kw">end</span>;
126
127<span class="kw">proc</span> main*;
128<span class="kw">var</span> text: []<span class="kw">const</span> <span class="ty">U8</span>; at, n, line: <span class="ty">INT</span>;
129<span class="kw">begin</span>
130 Out.str(base(<span class="string">&quot;/usr/local/lib/raz/Bytes.raz&quot;</span>)); Out.char(<span class="string">&#x27; &#x27;</span>);
131 Out.str(base(<span class="string">&quot;Out.raz&quot;</span>)); Out.ln;
132
133 text := <span class="string">&quot;one line\nanother line\nthe line with raz in it\nthe last\n&quot;</span>;
134 Fmt.print(<span class="string">&quot;{} lines\n&quot;</span>, [Fmt.int(Bytes.count(text, <span class="number">10</span>))]);
135 at := Bytes.find(text, <span class="string">&quot;raz&quot;</span>);
136 <span class="kw">if</span> at &gt;= <span class="number">0</span> <span class="kw">then</span>
137 <span class="comment">(* the line it is on: the newlines before it, plus one *)</span>
138 line := Bytes.count(text[<span class="number">0</span>..at], <span class="number">10</span>) + <span class="number">1</span>;
139 n := Bytes.index(text[at..<span class="ty">LEN</span>(text)], <span class="number">10</span>);
140 Fmt.print(<span class="string">&quot;raz on line {}, at {}, and the line goes on {} more\n&quot;</span>,
141 [Fmt.int(line), Fmt.int(at), Fmt.int(n)]);
142 <span class="kw">end</span>;
143 Fmt.print(<span class="string">&quot;{} {}\n&quot;</span>, [Fmt.int(Bytes.find(text, <span class="string">&quot;zzz&quot;</span>)), Fmt.int(Bytes.find(text, <span class="string">&quot;&quot;</span>))]);
144<span class="kw">end</span>;
145
146<span class="kw">end</span> Paths.</code></pre>
147<pre class="output"><code>Bytes.raz Out.raz
1484 lines
149raz on line 3, at 36, and the line goes on 9 more
150-1 0
151</code></pre>
152<p>When the byte isn't there, <code>Bytes.last</code> gives -1, so <code>base</code> 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.</p>
153<h2>Binary formats</h2>
154<p>A file format or a network protocol has a byte order of its own, not the machine's. <code>Str.le</code> and <code>Str.be</code> read an unsigned number of up to 8 bytes in a fixed order (little- or big-endian) and <code>Str.putLE</code> and <code>Str.putBE</code> 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.</p>
155<p>Here is a small record format: a 4-byte tag, a 2-byte big-endian length, a 4-byte little-endian checksum, then the data.</p>
156<div class="file"><span>Frame.raz</span></div><pre class="code"><code><span class="kw">module</span> Frame;
157<span class="kw">import</span> Out, Fmt, Str;
158
159<span class="kw">const</span> HeaderSize = <span class="number">10</span>;
160
161<span class="comment">(* the sum of the bytes of data, all mod 2^32 *)</span>
162<span class="kw">proc</span> checksum(data: []<span class="kw">const</span> <span class="ty">U8</span>): <span class="ty">U32</span>;
163<span class="kw">var</span> i: <span class="ty">INT</span>; sum: <span class="ty">U32</span>;
164<span class="kw">begin</span>
165 <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> <span class="ty">LEN</span>(data) - <span class="number">1</span> <span class="kw">do</span> sum := sum + <span class="ty">U32</span>(data[i]); <span class="kw">end</span>;
166 <span class="kw">return</span> sum;
167<span class="kw">end</span>;
168
169<span class="comment">(* writes a frame to out, which must have room; its length *)</span>
170<span class="kw">proc</span> pack(out: []<span class="ty">U8</span>; tag, data: []<span class="kw">const</span> <span class="ty">U8</span>): <span class="ty">INT</span>;
171<span class="kw">begin</span>
172 COPY(out[<span class="number">0</span>..<span class="number">4</span>], tag);
173 Str.putBE(out[<span class="number">4</span>..<span class="number">6</span>], <span class="ty">U64</span>(<span class="ty">LEN</span>(data)));
174 Str.putLE(out[<span class="number">6</span>..<span class="number">10</span>], <span class="ty">U64</span>(checksum(data)));
175 COPY(out[HeaderSize..HeaderSize + <span class="ty">LEN</span>(data)], data);
176 <span class="kw">return</span> HeaderSize + <span class="ty">LEN</span>(data);
177<span class="kw">end</span>;
178
179<span class="kw">proc</span> main*;
180<span class="kw">var</span> buf: [<span class="number">64</span>]<span class="ty">U8</span>; n, len: <span class="ty">INT</span>; sum: <span class="ty">U32</span>; i: <span class="ty">INT</span>;
181<span class="kw">begin</span>
182 n := pack(buf, <span class="string">&quot;DATA&quot;</span>, <span class="string">&quot;hello&quot;</span>);
183 <span class="kw">for</span> i := <span class="number">0</span> <span class="kw">to</span> n - <span class="number">1</span> <span class="kw">do</span>
184 Out.hex(<span class="ty">U64</span>(buf[i]), <span class="number">2</span>); Out.char(<span class="string">&#x27; &#x27;</span>);
185 <span class="kw">end</span>;
186 Out.ln;
187 <span class="comment">(* and back *)</span>
188 len := <span class="ty">INT</span>(Str.be(buf[<span class="number">4</span>..<span class="number">6</span>]));
189 sum := <span class="ty">U32</span>(Str.le(buf[<span class="number">6</span>..<span class="number">10</span>]));
190 Fmt.print(<span class="string">&quot;tag {}, {} bytes, checksum {}, &quot;</span>, [Fmt.str(buf[<span class="number">0</span>..<span class="number">4</span>]), Fmt.int(len), Fmt.hex(<span class="ty">U64</span>(sum))]);
191 <span class="kw">if</span> sum = checksum(buf[HeaderSize..HeaderSize + len]) <span class="kw">then</span>
192 Out.str(<span class="string">&quot;valid: &quot;</span>); Out.str(buf[HeaderSize..HeaderSize + len]);
193 <span class="kw">else</span>
194 Out.str(<span class="string">&quot;corrupt&quot;</span>);
195 <span class="kw">end</span>;
196 Out.ln;
197<span class="kw">end</span>;
198
199<span class="kw">end</span> Frame.</code></pre>
200<pre class="output"><code>44 41 54 41 00 05 14 02 00 00 68 65 6C 6C 6F
201tag DATA, 5 bytes, checksum 214, valid: hello
202</code></pre>
203<p>The 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.</p>
204<h2>Numbers and text</h2>
205<p><code>Str.toInt</code> reads a decimal number with an optional sign and nothing else, and says whether it was one; <code>Str.toHex</code> reads hexadecimal digits, and <code>Math.toReal</code> a real, as a constant is written but with <code>e</code> for <code>E</code> too, to the nearest <code>F64</code> exactly. <code>Str.fromInt</code> goes the other way into an array of 20 bytes, with no allocator, and <code>Fmt</code> does the rest. <code>Str.encode</code> and <code>Str.decode</code> move between characters and UTF-8, as the first tour showed.</p>
206<div class="file"><span>Numbers.raz</span></div><pre class="code"><code><span class="kw">module</span> Numbers;
207<span class="kw">import</span> Out, Str, Math, Fmt;
208
209<span class="comment">(* the sum of the numbers in a comma separated list, or -1 if any isn&#x27;t *)</span>
210<span class="kw">proc</span> total(s: []<span class="kw">const</span> <span class="ty">U8</span>): <span class="ty">I64</span>;
211<span class="kw">var</span> part: []<span class="kw">const</span> <span class="ty">U8</span>; sum, n: <span class="ty">I64</span>; ok, more: <span class="ty">BOOL</span>;
212<span class="kw">begin</span>
213 more := <span class="ty">true</span>;
214 <span class="kw">while</span> more <span class="kw">do</span>
215 part, s, more := Str.cut(s, <span class="string">&quot;,&quot;</span>);
216 n, ok := Str.toInt(part);
217 <span class="kw">if</span> <span class="kw">not</span> ok <span class="kw">then</span> <span class="kw">return</span> -<span class="number">1</span>; <span class="kw">end</span>;
218 sum := sum + n;
219 <span class="kw">end</span>;
220 <span class="kw">return</span> sum;
221<span class="kw">end</span>;
222
223<span class="kw">proc</span> main*;
224<span class="kw">var</span> u: <span class="ty">U64</span>; x: <span class="ty">F64</span>; ok: <span class="ty">BOOL</span>; digits: [<span class="number">20</span>]<span class="ty">U8</span>; k: <span class="ty">INT</span>;
225<span class="kw">begin</span>
226 Out.int(total(<span class="string">&quot;10,20,-5,+7&quot;</span>)); Out.ln;
227 Out.int(total(<span class="string">&quot;10,x,20&quot;</span>)); Out.ln;
228 Out.int(total(<span class="string">&quot;10,,20&quot;</span>)); Out.ln;
229 u, ok := Str.toHex(<span class="string">&quot;ff00&quot;</span>);
230 <span class="kw">if</span> ok <span class="kw">then</span> Out.hex(u, <span class="number">1</span>); Out.ln; <span class="kw">end</span>;
231 x, ok := Math.toReal(<span class="string">&quot;-1.5e3&quot;</span>);
232 <span class="kw">if</span> ok <span class="kw">then</span> Fmt.print(<span class="string">&quot;{}\n&quot;</span>, [Fmt.real(x, <span class="number">1</span>)]); <span class="kw">end</span>;
233 digits, k := Str.fromInt(-<span class="number">9223372036854775807</span> - <span class="number">1</span>);
234 Out.str(digits[<span class="number">0</span>..k]); Out.ln;
235<span class="kw">end</span>;
236
237<span class="kw">end</span> Numbers.</code></pre>
238<pre class="output"><code>32
239-1
240-1
241FF00
242-1500.0
243-9223372036854775808
244</code></pre><p class="tryit">Save a program under its module&rsquo;s name and run it with <code>raz run Name.raz</code>.</p><div class="pager"><a href="fmt.html">&larr; Output and formatting</a><a href="index.html">Contents</a><a class="next" href="collections.html">Lists, arrays, maps and sorting &rarr;</a></div></article></div>
245</main>
246<footer>raz is under the ISC license. <a href="../source/index.html">Source</a></footer>
247</body>
248</html>