zuzu-rust 0.2.0

Rust implementation of ZuzuScript
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
=encoding utf8

=head1 NAME

std/data/cbor - CBOR encoding and decoding for ZuzuScript.

=head1 SYNOPSIS

  from std/data/cbor import CBOR, TaggedValue;
  
  let codec := new CBOR();
  let bytes := codec.encode({ answer: 42 });
  let value := codec.decode(bytes);
  
  // Decode CBOR maps to Zuzu PairLists instead of Dicts.
  // This preserves key order and allows duplicate keys.
  codec := new CBOR( pairlists: true );

=head1 IMPLEMENTATION SUPPORT

This module is supported by zuzu.pl, zuzu-rust, and zuzu-js on Node and
Electron. It is partially supported by zuzu-js in the browser: in-memory
CBOR encode/decode coverage passes, but file-backed load/dump coverage is
unsupported because browser filesystem capability is unavailable.

=head1 DESCRIPTION

Pure-Zuzu implementation of CBOR (RFC 8949).

=head1 EXPORTS

=head2 Classes

=over

=item C<< TaggedValue({ tag: Number, value: value }) >>

Constructs a tagged CBOR value. Returns: C<TaggedValue>. Stores the CBOR
tag number and associated value.

=item C<< CBOR({ pairlists?: Boolean }) >>

Constructs a CBOR codec. Returns: C<CBOR>. The C<pairlists> option makes
decoded maps return as C<PairList> values instead of C<Dict> values.

=over

=item C<< codec.encode(value) >>

Parameters: C<value> is any CBOR-encodable ZuzuScript value. Returns:
C<BinaryString>. Encodes C<value> as CBOR bytes.

=item C<< codec.encode_binarystring(value) >>

Alias for C<codec.encode(value)>.

=item C<< codec.decode(BinaryString raw) >>

Parameters: C<raw> is CBOR data. Returns: value. Decodes CBOR bytes into
the equivalent ZuzuScript value.

=item C<< codec.decode_binarystring(BinaryString raw) >>

Alias for C<codec.decode(raw)>.

=item C<< codec.load(Path path) >>

Parameters: C<path> is a C<std/io> C<Path>. Returns: value. Reads CBOR
bytes from C<path> and decodes them.

=item C<< codec.dump(Path path, value) >>

Parameters: C<path> is a C<std/io> C<Path> and C<value> is any
CBOR-encodable value. Returns: C<null>. Encodes C<value> and writes CBOR
bytes to C<path>.

=back

=back

=head1 COPYRIGHT AND LICENCE

B<< std/data/cbor >> is copyright Toby Inkster.

It is free software; you may redistribute it and/or modify it under
the terms of either the Artistic License 1.0 or the GNU General Public
License version 2.

=cut

from std/string import substr, index;
from std/string/base64 import encode, decode;
from std/time import Time;


let _B64_ALPHABET  := "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";

// Set to "PairList" to return CBOR objects as Zuzu PairLists.
let _DECODE_MAP_AS := "Dict";

class TaggedValue {
	let Number tag;
	let value;
}

function _div_floor ( Number n, Number d ) {
	return floor( n / d ); // fix syntax highlighting
}

function _mod ( Number n, Number d ) {
	return n - _div_floor( n, d ) * d;
}

function _bytes_to_binary ( Array bytes ) {
	let out := "";
	let i := 0;
	let n := bytes.length();

	while ( i < n ) {
		let b0 := bytes[i];
		let b1 := null;
		let b2 := null;
		if ( i + 1 < n ) {
			b1 := bytes[i + 1];
		}
		if ( i + 2 < n ) {
			b2 := bytes[i + 2];
		}

		let c0 := _div_floor( b0, 4 );
		let c1 := _mod( b0, 4 ) * 16;
		let c2 := 64;
		let c3 := 64;

		if ( b1 ≢ null ) {
			c1 += _div_floor( b1, 16 );
			c2 := _mod( b1, 16 ) * 4;
			if ( b2 ≢ null ) {
				c2 += _div_floor( b2, 64 );
				c3 := _mod( b2, 64 );
			}
		}

		out _= substr( _B64_ALPHABET, c0, 1 );
		out _= substr( _B64_ALPHABET, c1, 1 );
		if ( c2 ≡ 64 ) {
			out _= "=";
		}
		else {
			out _= substr( _B64_ALPHABET, c2, 1 );
		}
		if ( c3 ≡ 64 ) {
			out _= "=";
		}
		else {
			out _= substr( _B64_ALPHABET, c3, 1 );
		}
		i += 3;
	}

	return decode(out);
}

function _binary_to_bytes ( BinaryString raw ) {
	let b64 := encode(raw);
	let out := [];
	let i := 0;
	let n := length b64;

	while ( i < n ) {
		let c0 := index( _B64_ALPHABET, substr( b64, i, 1 ) );
		let c1 := index( _B64_ALPHABET, substr( b64, i + 1, 1 ) );
		let ch2 := substr( b64, i + 2, 1 );
		let ch3 := substr( b64, i + 3, 1 );
		let c2 := -1;
		let c3 := -1;
		if ( ch2 ≢ "=" ) {
			c2 := index( _B64_ALPHABET, ch2 );
		}
		if ( ch3 ≢ "=" ) {
			c3 := index( _B64_ALPHABET, ch3 );
		}

		out.push( c0 * 4 + _div_floor( c1, 16 ) );

		if ( c2 >= 0 ) {
			out.push( _mod( c1, 16 ) * 16 + _div_floor( c2, 4 ) );
		}
		if ( c3 >= 0 ) {
			out.push( _mod( c2, 4 ) * 64 + c3 );
		}

		i += 4;
	}

	return out;
}

function _is_int ( value ) {
	if ( not( value instanceof Number ) ) {
		return false;
	}

	return _mod( value, 1 ) ≡ 0;
}

function _emit_uint ( Array out, Number major, Number n ) {
	if ( n < 24 ) {
		out.push( major * 32 + n );
		return;
	}
	if ( n < 256 ) {
		out.push( major * 32 + 24 );
		out.push(n);
		return;
	}
	if ( n < 65536 ) {
		out.push( major * 32 + 25 );
		out.push( _mod( _div_floor( n, 256 ), 256 ) );
		out.push( _mod( n, 256 ) );
		return;
	}
	if ( n < 4294967296 ) {
		out.push( major * 32 + 26 );
		out.push( _mod( _div_floor( n, 16777216 ), 256 ) );
		out.push( _mod( _div_floor( n, 65536 ), 256 ) );
		out.push( _mod( _div_floor( n, 256 ), 256 ) );
		out.push( _mod( n, 256 ) );
		return;
	}

	let hi := _div_floor( n, 4294967296 );
	let lo := _mod( n, 4294967296 );
	out.push( major * 32 + 27 );
	out.push( _mod( _div_floor( hi, 16777216 ), 256 ) );
	out.push( _mod( _div_floor( hi, 65536 ), 256 ) );
	out.push( _mod( _div_floor( hi, 256 ), 256 ) );
	out.push( _mod( hi, 256 ) );
	out.push( _mod( _div_floor( lo, 16777216 ), 256 ) );
	out.push( _mod( _div_floor( lo, 65536 ), 256 ) );
	out.push( _mod( _div_floor( lo, 256 ), 256 ) );
	out.push( _mod( lo, 256 ) );
}

function _encode_value ( Array out, value ) {
	if ( value ≡ null ) {
		out.push(246);
		return;
	}
	if ( value ≡ true ) {
		out.push(245);
		return;
	}
	if ( value ≡ false ) {
		out.push(244);
		return;
	}

	if ( value instanceof Number ) {
		die "CBOR.encode currently supports only integer Number values" if not _is_int(value);
		if ( value >= 0 ) {
			_emit_uint( out, 0, value );
		}
		else {
			_emit_uint( out, 1, -1 - value );
		}
		return;
	}

	if ( value instanceof BinaryString ) {
		let b := _binary_to_bytes(value);
		_emit_uint( out, 2, b.length() );
		let i := 0;
		while ( i < b.length() ) {
			out.push( b[i] );
			i++;
		}
		return;
	}

	if ( value instanceof String ) {
		let b := _binary_to_bytes( to_binary(value) );
		_emit_uint( out, 3, b.length() );
		let i := 0;
		while ( i < b.length() ) {
			out.push( b[i] );
			i++;
		}
		return;
	}

	if ( value instanceof Array ) {
		_emit_uint( out, 4, value.length() );
		let i := 0;
		while ( i < value.length() ) {
			_encode_value( out, value[i] );
			i++;
		}
		return;
	}

	if ( value instanceof Set ) {
		_emit_uint( out, 6, 258 );
		_encode_value( out, value.sortstr() );
		return;
	}

	if ( value instanceof Bag ) {
		_encode_value( out, value.sortstr() );
		return;
	}

	if ( value instanceof PairList ) {
		let pairs := value.to_Array();
		_emit_uint( out, 5, pairs.length() );
		let i := 0;
		while ( i < pairs.length() ) {
			let pair := pairs[i]{pair};
			_encode_value( out, pair[0] );
			_encode_value( out, pair[1] );
			i++;
		}
		return;
	}

	if ( value instanceof Dict ) {
		let keys := value.sorted_keys();
		_emit_uint( out, 5, keys.length() );
		let i := 0;
		while ( i < keys.length() ) {
			let k := keys[i];
			_encode_value( out, k );
			_encode_value( out, value.get(k) );
			i++;
		}
		return;
	}

	if ( value instanceof TaggedValue ) {
		_emit_uint( out, 6, value { tag } );
		_encode_value( out, value { value } );
		return;
	}
	if ( value instanceof Time ) {
		_emit_uint( out, 6, 0 );
		_encode_value( out, value.epoch() );
		return;
	}

	die `CBOR cannot encode value of type ${typeof value}`;
}

function _read_uint ( Array bytes, Number ai, Number pos ) {
	if ( ai < 24 ) {
		return [ ai, pos ];
	}
	if ( ai ≡ 24 ) {
		return [ bytes[pos], pos + 1 ];
	}
	if ( ai ≡ 25 ) {
		return [ bytes[pos] * 256 + bytes[pos + 1], pos + 2 ];
	}
	if ( ai ≡ 26 ) {
		return [ bytes[pos] * 16777216 + bytes[pos + 1] * 65536 + bytes[pos + 2] * 256 + bytes[pos + 3], pos + 4 ];
	}
	if ( ai ≡ 27 ) {
		let hi := bytes[pos] * 16777216 + bytes[pos + 1] * 65536 + bytes[pos + 2] * 256 + bytes[pos + 3];
		let lo := bytes[pos + 4] * 16777216 + bytes[pos + 5] * 65536 + bytes[pos + 6] * 256 + bytes[pos + 7];
		return [ hi * 4294967296 + lo, pos + 8 ];
	}

	die `Unsupported CBOR additional info: ${ai}`;
}

function _decode_at ( Array bytes, Number pos ) {
	let head := bytes[pos];
	let major := _div_floor( head, 32 );
	let ai := _mod( head, 32 );
	let parsed := _read_uint( bytes, ai, pos + 1 );
	let arg := parsed[0];
	let p := parsed[1];

	if ( major ≡ 0 ) {
		return [ arg, p ];
	}
	if ( major ≡ 1 ) {
		return [ -1 - arg, p ];
	}
	if ( major ≡ 2 ) {
		let chunk := [];
		let i := 0;
		while ( i < arg ) {
			chunk.push( bytes[p + i] );
			i++;
		}
		return [ _bytes_to_binary(chunk), p + arg ];
	}
	if ( major ≡ 3 ) {
		let chunk := [];
		let i := 0;
		while ( i < arg ) {
			chunk.push( bytes[p + i] );
			i++;
		}
		return [ to_string( _bytes_to_binary(chunk) ), p + arg ];
	}
	if ( major ≡ 4 ) {
		let arr := [];
		let i := 0;
		let q := p;
		while ( i < arg ) {
			let item := _decode_at( bytes, q );
			arr.push( item[0] );
			q := item[1];
			i++;
		}
		return [ arr, q ];
	}
	if ( major ≡ 5 ) {
		let d := _DECODE_MAP_AS eq "PairList" ? new PairList() : new Dict();
		let i := 0;
		let q := p;
		while ( i < arg ) {
			let k := _decode_at( bytes, q );
			let v := _decode_at( bytes, k[1] );
			d.add( k[0], v[0] ) unless _DECODE_MAP_AS eq "Dict" and d.exists( k[0] );
			q := v[1];
			i++;
		}
		return [ d, q ];
	}
	if ( major ≡ 6 ) {
		let tagged := _decode_at( bytes, p );
		if ( arg ≡ 0 and tagged[0] instanceof Number ) {
			return [ new Time( tagged[0] ), tagged[1] ];
		}
		if ( arg ≡ 258 and tagged[0] instanceof Array ) {
			return [ tagged[0].to_Set(), tagged[1] ];
		}
		return [ new TaggedValue( tag: arg, value: tagged[0] ), tagged[1] ];
	}
	if ( major ≡ 7 ) {
		if ( ai ≡ 20 ) {
			return [ false, pos + 1 ];
		}
		if ( ai ≡ 21 ) {
			return [ true, pos + 1 ];
		}
		if ( ai ≡ 22 ) {
			return [ null, pos + 1 ];
		}
		die `Unsupported CBOR simple/float value (ai=${ai})`;
	}

	die `Unsupported CBOR major type: ${major}`;
}

class CBOR {
	let pairlists := false;
	
	method encode ( value ) {
		let out := [];
		_encode_value( out, value );
		return _bytes_to_binary(out);
	}

	method encode_binarystring ( value ) {
		return self.encode(value);
	}

	method decode ( BinaryString raw ) {
		_DECODE_MAP_AS := pairlists ? "PairList" : "Dict";
		let bytes := _binary_to_bytes(raw);
		let parsed := _decode_at( bytes, 0 );
		die "Trailing bytes after CBOR value" if parsed[1] < bytes.length();
		return parsed[0];
	}

	method decode_binarystring ( BinaryString raw ) {
		return self.decode(raw);
	}

	method load ( path ) {
		from std/io import Path;
		die "CBOR.load is denied by runtime policy" if __system__{deny_fs};
		die "CBOR.load expects a std/io Path object" if not( path instanceof Path );
		return self.decode( path.slurp() );
	}

	method dump ( path, value ) {
		from std/io import Path;
		die "CBOR.dump is denied by runtime policy" if __system__{deny_fs};
		die "CBOR.dump expects a std/io Path object" if not( path instanceof Path );
		path.spew( self.encode(value) );
		return path;
	}
}