surrealdb-expr 4.0.0

A scalable, distributed, collaborative, document-graph database, for the realtime web
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
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
use std::ops::Bound;

use chrono::{DateTime, Utc};
use rust_decimal::Decimal;
use surrealdb_collections::{VecMap, VecSet};
use surrealdb_strand::Strand;
use surrealdb_types::BigDecimal;

use super::read::{Container, Kind};
use super::tag::*;
use super::varint::{self, VarintError};
use super::{DEPTH_LIMIT, Error, geometry, read_int, read_uint, split_clen, utf8};
use crate::val::{
	Array, Bytes, Date, Datetime, Duration, File, Interval, Number, Object, Range, RecordId,
	RecordIdKey, RecordIdKeyRange, Regex, Set, TableName, Time, Timestamp, Uuid, Value,
};

/// What a walk of the stored grammar produces. [`Build`] constructs each value it reads; [`Check`]
/// reads the same bytes through the same code and produces nothing. Every byte-level check runs in
/// both modes, so the two accept and refuse the same bytes with the same errors.
///
/// Walked values are `Self::Out<T>` and sequences of them are `Self::Seq<T>`. Generic code never
/// looks inside an `Out`: it combines walked values only through these methods, and the closures
/// passed to them run only in [`Build`].
pub(super) trait Mode {
	/// A walked `T`: the value itself in [`Build`], nothing in [`Check`].
	type Out<T>;
	/// A sequence of walked `T`s: a `Vec<T>` in [`Build`], nothing in [`Check`].
	type Seq<T>;
	/// Wraps the value `f` constructs. `f` is not called in [`Check`].
	fn make<T>(f: impl FnOnce() -> T) -> Self::Out<T>;
	/// Applies `f` to a walked value. `f` is not called in [`Check`].
	fn map<T, U>(v: Self::Out<T>, f: impl FnOnce(T) -> U) -> Self::Out<U>;
	/// Pairs two walked values.
	fn zip<A, B>(a: Self::Out<A>, b: Self::Out<B>) -> Self::Out<(A, B)>;
	/// An empty sequence with room for `capacity` items.
	fn seq<T>(capacity: usize) -> Self::Seq<T>;
	/// Appends a walked item to a sequence.
	fn push<T>(seq: &mut Self::Seq<T>, item: Self::Out<T>);
	/// Collects a sequence of walked items.
	fn finish<T>(seq: Self::Seq<T>) -> Self::Out<Vec<T>>;
}

/// The walk that constructs the values it reads.
pub(super) enum Build {}

/// The walk that reads and checks the bytes and constructs nothing, so it allocates nothing for
/// the kinds whose check does not need their value.
pub(super) enum Check {}

impl Mode for Build {
	type Out<T> = T;
	type Seq<T> = Vec<T>;

	#[inline(always)]
	fn make<T>(f: impl FnOnce() -> T) -> T {
		f()
	}

	#[inline(always)]
	fn map<T, U>(v: T, f: impl FnOnce(T) -> U) -> U {
		f(v)
	}

	#[inline(always)]
	fn zip<A, B>(a: A, b: B) -> (A, B) {
		(a, b)
	}

	#[inline(always)]
	fn seq<T>(capacity: usize) -> Vec<T> {
		Vec::with_capacity(capacity)
	}

	#[inline(always)]
	fn push<T>(seq: &mut Vec<T>, item: T) {
		seq.push(item);
	}

	#[inline(always)]
	fn finish<T>(seq: Vec<T>) -> Vec<T> {
		seq
	}
}

impl Mode for Check {
	type Out<T> = ();
	type Seq<T> = ();

	#[inline(always)]
	fn make<T>(_: impl FnOnce() -> T) {}

	#[inline(always)]
	fn map<T, U>(_: (), _: impl FnOnce(T) -> U) {}

	#[inline(always)]
	fn zip<A, B>(_: (), _: ()) {}

	#[inline(always)]
	fn seq<T>(_: usize) {}

	#[inline(always)]
	fn push<T>(_: &mut (), _: ()) {}

	#[inline(always)]
	fn finish<T>(_: ()) {}
}

/// Decodes the value whose stored encoding is exactly `bytes`.
pub fn decode(bytes: &[u8]) -> Result<Value, Error> {
	decode_nested(bytes, 0)
}

/// Decodes the value whose stored encoding is exactly `bytes`, as a value nested `depth`
/// containers deep, so the grammar's depth limit counts the levels above it. An encode and a
/// decode at the same depth accept the same values.
pub fn decode_nested(bytes: &[u8], depth: usize) -> Result<Value, Error> {
	value::<Build>(bytes, depth)
}

/// Whether `bytes` are exactly one value of the stored grammar. Refuses what [`decode`] refuses,
/// with the same error. It builds no value except where a check needs one: a set, a regex or a
/// geometry is constructed to be checked.
pub fn validate(bytes: &[u8]) -> Result<(), Error> {
	validate_nested(bytes, 0)
}

/// [`validate`] for a value nested `depth` containers deep, as [`decode_nested`] counts depth.
pub fn validate_nested(bytes: &[u8], depth: usize) -> Result<(), Error> {
	value::<Check>(bytes, depth)
}

/// [`validate_nested`], answering what an object's entries hold from the walk that validates them:
/// when the value is an object, `entry` is called with the key and the value's tag of each entry,
/// in key order, once that entry has been validated. Answers whether the value is an object.
/// Refuses what [`validate_nested`] refuses, with the same error, so `entry` may have seen some of
/// the entries of a value that is refused.
pub fn validate_entries_nested(
	bytes: &[u8],
	depth: usize,
	entry: impl FnMut(&str, u8),
) -> Result<bool, Error> {
	let (&t, p) = bytes.split_first().ok_or(Error::Truncated)?;
	if depth > DEPTH_LIMIT || !matches!(t, 0x1A..=0x1C) {
		parts::<Check>(t, p, depth)?;
		return Ok(false);
	}
	object_with::<Check>(p, width(t, OBJECT), depth, entry)?;
	Ok(true)
}

/// Decodes the record id key whose stored encoding is exactly `bytes`.
pub fn decode_key(bytes: &[u8]) -> Result<RecordIdKey, Error> {
	decode_key_nested(bytes, 0)
}

/// Decodes the record id key whose stored encoding is exactly `bytes`, nested `depth` containers
/// deep.
pub fn decode_key_nested(bytes: &[u8], depth: usize) -> Result<RecordIdKey, Error> {
	key::<Build>(bytes, depth)
}

/// Whether `bytes` are exactly one record id key of the stored grammar, nested `depth` containers
/// deep. Refuses what [`decode_key_nested`] refuses, with the same error. It builds no key except
/// where a check needs one: a set, a regex or a geometry inside a key is constructed to be checked.
pub fn validate_key_nested(bytes: &[u8], depth: usize) -> Result<(), Error> {
	key::<Check>(bytes, depth)
}

/// Reads a DECIMAL payload (the head byte and the magnitude, without the tag) that is exactly
/// `p`.
///
/// Only the payload [`put_decimal_payload`](super::put_decimal_payload) writes is accepted: a
/// magnitude whose last, most significant byte is zero is refused, so every decimal has one
/// payload.
pub fn decimal_payload(p: &[u8]) -> Result<Decimal, Error> {
	let (_, magnitude) = p.split_first().ok_or(Error::Truncated)?;
	if magnitude.last() == Some(&0) {
		return Err(Error::Malformed("a decimal magnitude with a zero high byte"));
	}
	decimal(p)
}

/// Reads the DATETIME payload `p` that is exactly 12 bytes: `i64` little-endian seconds, then
/// `u32` little-endian nanoseconds. A value outside the representable range is refused.
pub fn decode_datetime_payload(p: &[u8]) -> Result<DateTime<Utc>, Error> {
	if p.len() != 12 {
		return Err(Error::Malformed("a datetime payload that is not 12 bytes"));
	}
	datetime(p)
}

/// Reads the DURATION payload `p` that is exactly 12 bytes: `u64` little-endian seconds, then
/// `u32` little-endian nanoseconds below a second.
pub fn decode_duration_payload(p: &[u8]) -> Result<std::time::Duration, Error> {
	if p.len() != 12 {
		return Err(Error::Malformed("a duration payload that is not 12 bytes"));
	}
	duration(p)
}

#[inline(always)]
pub(super) fn fixed<const N: usize>(p: &[u8]) -> Result<[u8; N], Error> {
	p.try_into().map_err(|_| Error::Malformed("a fixed-width value of the wrong width"))
}

#[inline(always)]
fn empty(p: &[u8]) -> Result<(), Error> {
	match p.is_empty() {
		true => Ok(()),
		false => Err(Error::Malformed("a payload on a value that has none")),
	}
}

#[inline]
pub(super) fn float(p: &[u8]) -> Result<f64, Error> {
	match p.len() {
		4 => Ok(f32::from_le_bytes(fixed(p)?) as f64),
		8 => Ok(f64::from_le_bytes(fixed(p)?)),
		_ => Err(Error::Malformed("a float of the wrong width")),
	}
}

#[inline]
pub(super) fn decimal(p: &[u8]) -> Result<Decimal, Error> {
	let (&head, magnitude) = p.split_first().ok_or(Error::Truncated)?;
	if magnitude.len() > 12 {
		return Err(Error::Malformed("a decimal mantissa wider than 96 bits"));
	}
	let mut m = [0u8; 16];
	m.get_mut(..magnitude.len())
		.ok_or(Error::Malformed("a decimal mantissa wider than 96 bits"))?
		.copy_from_slice(magnitude);
	let mut d =
		Decimal::try_from_i128_with_scale(u128::from_le_bytes(m) as i128, (head & 0x7F) as u32)
			.map_err(|_| Error::Malformed("a decimal out of range"))?;
	d.set_sign_negative(head & 0x80 != 0);
	Ok(d)
}

/// Reads a BIGDECIMAL payload (the sign byte, the scale and the magnitude, without the tag) that
/// is exactly `p`. Only the payload [`put_bigdecimal_payload`](super::put_bigdecimal_payload)
/// writes is accepted, so every value has one payload.
pub fn bigdecimal_payload(p: &[u8]) -> Result<BigDecimal, Error> {
	bigdecimal(p)
}

/// The sign, scale and little-endian magnitude of the BIGDECIMAL payload `p`, refused unless it
/// is the one payload of a value: a sign byte of 0 or 1, the scale as a canonical varint of at
/// most [`MAX_SCALE`](surrealdb_types::bigdecimal::MAX_SCALE), and a magnitude of at most
/// [`MAX_COEFFICIENT_BYTES`](surrealdb_types::bigdecimal::MAX_COEFFICIENT_BYTES) bytes that
/// does not end in a zero byte, with no negative zero. Reads the parts in place and builds no
/// value, so a reader that validates a payload without decoding it allocates nothing.
pub(super) fn bigdecimal_parts(p: &[u8]) -> Result<(bool, i64, &[u8]), Error> {
	let (&sign, rest) = p.split_first().ok_or(Error::Truncated)?;
	let negative = match sign {
		0x00 => false,
		0x01 => true,
		_ => return Err(Error::Malformed("a bigdecimal sign that is neither 0 nor 1")),
	};
	let (scale, used) = varint::read_u64(rest).map_err(|e| match e {
		VarintError::Truncated => Error::Truncated,
		VarintError::Overlong | VarintError::Overflow => {
			Error::Malformed("a bigdecimal scale that is not a canonical varint")
		}
	})?;
	let scale = i64::try_from(scale)
		.ok()
		.filter(|scale| *scale <= surrealdb_types::bigdecimal::MAX_SCALE)
		.ok_or(Error::Malformed("a bigdecimal out of range"))?;
	let magnitude = rest.get(used..).ok_or(Error::Truncated)?;
	if magnitude.last() == Some(&0) {
		return Err(Error::Malformed("a bigdecimal magnitude with a zero high byte"));
	}
	if negative && magnitude.is_empty() {
		return Err(Error::Malformed("a negative zero bigdecimal"));
	}
	if magnitude.len() > surrealdb_types::bigdecimal::MAX_COEFFICIENT_BYTES {
		return Err(Error::Malformed("a bigdecimal out of range"));
	}
	Ok((negative, scale, magnitude))
}

/// Reads the BIGDECIMAL payload `p`: the sign byte, the scale as a canonical varint, then the
/// magnitude of the coefficient. The magnitude may not end in a zero byte and a negative zero is
/// refused, so every value has one payload.
#[inline]
pub(super) fn bigdecimal(p: &[u8]) -> Result<BigDecimal, Error> {
	let (negative, scale, magnitude) = bigdecimal_parts(p)?;
	BigDecimal::from_le_parts(negative, magnitude, scale)
		.map_err(|_| Error::Malformed("a bigdecimal out of range"))
}

#[inline]
pub(super) fn duration(p: &[u8]) -> Result<std::time::Duration, Error> {
	match p.len() {
		8 => Ok(std::time::Duration::from_nanos(u64::from_le_bytes(fixed(p)?))),
		12 => {
			let (secs, nanos) = p.split_at_checked(8).ok_or(Error::Truncated)?;
			let secs = u64::from_le_bytes(fixed(secs)?);
			let nanos = u32::from_le_bytes(fixed(nanos)?);
			if nanos >= 1_000_000_000 {
				return Err(Error::Malformed("a duration with a nanosecond part past a second"));
			}
			Ok(std::time::Duration::new(secs, nanos))
		}
		_ => Err(Error::Malformed("a duration of the wrong width")),
	}
}

#[inline]
pub(super) fn date(p: &[u8]) -> Result<Date, Error> {
	if p.is_empty() || p.len() > 4 {
		return Err(Error::Malformed("a date of the wrong width"));
	}
	Date::from_days(read_int(p)? as i32).ok_or(Error::Malformed("a date out of range"))
}

#[inline]
pub(super) fn time(p: &[u8]) -> Result<Time, Error> {
	if p.is_empty() || p.len() > 8 {
		return Err(Error::Malformed("a time of the wrong width"));
	}
	Time::from_nanos(read_uint(p)?).ok_or(Error::Malformed("a time past 24:00:00"))
}

#[inline]
pub(super) fn timestamp(p: &[u8]) -> Result<Timestamp, Error> {
	let (secs, nanos) = match p.len() {
		8 => {
			let ns = i64::from_le_bytes(fixed(p)?);
			(ns.div_euclid(1_000_000_000), ns.rem_euclid(1_000_000_000) as u32)
		}
		12 => {
			let (secs, nanos) = p.split_at_checked(8).ok_or(Error::Truncated)?;
			(i64::from_le_bytes(fixed(secs)?), u32::from_le_bytes(fixed(nanos)?))
		}
		_ => return Err(Error::Malformed("a timestamp of the wrong width")),
	};
	Timestamp::from_parts(secs, nanos).ok_or(Error::Malformed("a timestamp out of range"))
}

#[inline]
pub(super) fn interval(p: &[u8]) -> Result<Interval, Error> {
	let b: [u8; 16] = fixed(p)?;
	let months = i32::from_le_bytes([b[0], b[1], b[2], b[3]]);
	let days = i32::from_le_bytes([b[4], b[5], b[6], b[7]]);
	let micros = i64::from_le_bytes([b[8], b[9], b[10], b[11], b[12], b[13], b[14], b[15]]);
	Ok(Interval::new(months, days, micros))
}

#[inline]
pub(super) fn datetime(p: &[u8]) -> Result<DateTime<Utc>, Error> {
	match p.len() {
		8 => Ok(DateTime::from_timestamp_nanos(i64::from_le_bytes(fixed(p)?))),
		12 => {
			let (secs, nanos) = p.split_at_checked(8).ok_or(Error::Truncated)?;
			let secs = i64::from_le_bytes(fixed(secs)?);
			let nanos = u32::from_le_bytes(fixed(nanos)?);
			DateTime::from_timestamp(secs, nanos).ok_or(Error::Malformed("a datetime out of range"))
		}
		_ => Err(Error::Malformed("a datetime of the wrong width")),
	}
}

fn value<M: Mode>(v: &[u8], depth: usize) -> Result<M::Out<Value>, Error> {
	let (&t, p) = v.split_first().ok_or(Error::Truncated)?;
	parts::<M>(t, p, depth)
}

/// Walks the value with tag `t` and payload `p`.
pub(super) fn parts<M: Mode>(t: u8, p: &[u8], depth: usize) -> Result<M::Out<Value>, Error> {
	if depth > DEPTH_LIMIT {
		return Err(Error::TooDeep(DEPTH_LIMIT));
	}
	Ok(match t {
		NONE => {
			empty(p)?;
			M::make(|| Value::None)
		}
		NULL => {
			empty(p)?;
			M::make(|| Value::Null)
		}
		FALSE => {
			empty(p)?;
			M::make(|| Value::Bool(false))
		}
		TRUE => {
			empty(p)?;
			M::make(|| Value::Bool(true))
		}
		INT => {
			let i = read_int(p)?;
			M::make(|| Value::Number(Number::Int(i)))
		}
		FLOAT => {
			let f = float(p)?;
			M::make(|| Value::Number(Number::Float(f)))
		}
		DECIMAL => {
			let d = decimal(p)?;
			M::make(|| Value::Number(Number::Decimal(d)))
		}
		BIGDECIMAL => {
			let d = bigdecimal(p)?;
			M::make(|| Value::Number(Number::BigDecimal(Box::new(d))))
		}
		I8 => {
			let [b] = fixed(p)?;
			M::make(|| Value::Number(Number::I8(b as i8)))
		}
		U8 => {
			let [b] = fixed(p)?;
			M::make(|| Value::Number(Number::U8(b)))
		}
		I16 => {
			if p.is_empty() || p.len() > 2 {
				return Err(Error::Malformed("an i16 of the wrong width"));
			}
			let i = read_int(p)? as i16;
			M::make(|| Value::Number(Number::I16(i)))
		}
		U16 => {
			if p.is_empty() || p.len() > 2 {
				return Err(Error::Malformed("a u16 of the wrong width"));
			}
			let u = read_uint(p)? as u16;
			M::make(|| Value::Number(Number::U16(u)))
		}
		I32 => {
			if p.is_empty() || p.len() > 4 {
				return Err(Error::Malformed("an i32 of the wrong width"));
			}
			let i = read_int(p)? as i32;
			M::make(|| Value::Number(Number::I32(i)))
		}
		U32 => {
			if p.is_empty() || p.len() > 4 {
				return Err(Error::Malformed("a u32 of the wrong width"));
			}
			let u = read_uint(p)? as u32;
			M::make(|| Value::Number(Number::U32(u)))
		}
		U64 => {
			let u = read_uint(p)?;
			M::make(|| Value::Number(Number::U64(u)))
		}
		F16 => {
			let b = fixed(p)?;
			M::make(|| Value::Number(Number::F16(half::f16::from_bits(u16::from_le_bytes(b)))))
		}
		F32 => {
			let b = fixed(p)?;
			M::make(|| Value::Number(Number::F32(f32::from_le_bytes(b))))
		}
		STRING => {
			let s = utf8(p)?;
			M::make(|| Value::String(Strand::new(s)))
		}
		DURATION => {
			let d = duration(p)?;
			M::make(|| Value::Duration(Duration(d)))
		}
		DATETIME => {
			let d = datetime(p)?;
			M::make(|| Value::Datetime(Datetime(d)))
		}
		DATE => {
			let d = date(p)?;
			M::make(|| Value::Date(d))
		}
		TIME => {
			let t = time(p)?;
			M::make(|| Value::Time(t))
		}
		TIMESTAMP => {
			let t = timestamp(p)?;
			M::make(|| Value::Timestamp(t))
		}
		INTERVAL => {
			let i = interval(p)?;
			M::make(|| Value::Interval(i))
		}
		UUID => {
			let u: [u8; 16] = fixed(p)?;
			M::make(|| Value::Uuid(Uuid(uuid::Uuid::from_bytes(u))))
		}
		BYTES => M::make(|| Value::Bytes(Bytes(::bytes::Bytes::copy_from_slice(p)))),
		TABLE => {
			let s = utf8(p)?;
			M::make(|| Value::Table(TableName::new(s)))
		}
		RECORD_ID => {
			let (table, k) = split_clen(p)?;
			let table = utf8(table)?;
			let key = key::<M>(k, depth + 1)?;
			M::map(key, |key: RecordIdKey| {
				Value::RecordId(RecordId {
					table: TableName::new(table),
					key,
				})
			})
		}
		FILE => {
			let (bucket, k) = split_clen(p)?;
			let bucket = utf8(bucket)?;
			let key = utf8(k)?;
			// Built field by field: `File::new` prepends a `/` to a key without one.
			M::make(|| {
				Value::File(File {
					bucket: bucket.to_owned(),
					key: key.to_owned(),
				})
			})
		}
		REGEX => {
			let r = regex(utf8(p)?)?;
			M::make(|| Value::Regex(r))
		}
		RANGE => {
			let b = bounds::<M, Value, _>(p, |b| value::<M>(b, depth + 1))?;
			M::map(b, |(start, end): (Bound<Value>, Bound<Value>)| {
				Value::Range(Box::new(Range {
					start,
					end,
				}))
			})
		}
		GEOMETRY => {
			let g = geometry::decode(p, depth)?;
			M::make(|| Value::Geometry(g))
		}
		F64_ARRAY | F32_ARRAY | I8_ARRAY..=I64_ARRAY | 0x14..=0x16 => {
			M::map(array::<M>(t, p, depth)?, Value::Array)
		}
		0x17..=0x19 => M::map(set::<M>(p, width(t, SET), depth)?, Value::Set),
		0x1A..=0x1C => M::map(object::<M>(p, width(t, OBJECT), depth)?, Value::Object),
		0x80..=0xFE => {
			empty(p)?;
			let i = (t - SMALL_INT) as i64;
			M::make(|| Value::Number(Number::Int(i)))
		}
		other => return Err(Error::UnknownTag(other)),
	})
}

/// Scalar accessors for readers that treat a value's tag as part of a declared schema.
///
/// Each takes a value's tag and payload and applies exactly the payload checks of [`parts`]: no
/// payload at all on NONE, FALSE, TRUE and the small ints, the widths of the fixed-width kinds, a
/// whole UTF-8 string. `Ok(None)` means the tag is another kind, so the caller can report the wrong
/// kind; an `Err` means the tag is this kind and its payload is malformed. They read a tag and
/// payload split by the caller, so they check for themselves what
/// [`ValueRef::new`](super::read::ValueRef::new) checks of a value it is handed.
pub(crate) mod strict {
	use chrono::{DateTime, Utc};
	use rust_decimal::Decimal;
	use surrealdb_types::BigDecimal;

	use super::{empty, fixed};
	use crate::val::stored::tag::*;
	use crate::val::stored::{Error, read_int, read_uint, utf8};
	use crate::val::{Date, Interval, Time, Timestamp};

	/// NONE, whose payload is empty.
	#[inline(always)]
	pub(crate) fn none(t: u8, p: &[u8]) -> Result<Option<()>, Error> {
		match t {
			NONE => empty(p).map(Some),
			_ => Ok(None),
		}
	}

	/// FALSE or TRUE, whose payload is empty.
	#[inline(always)]
	pub(crate) fn bool(t: u8, p: &[u8]) -> Result<Option<bool>, Error> {
		match t {
			FALSE => empty(p).map(|()| Some(false)),
			TRUE => empty(p).map(|()| Some(true)),
			_ => Ok(None),
		}
	}

	/// An INT of 1 to 8 bytes, or a small int, whose payload is empty.
	#[inline(always)]
	pub(crate) fn int(t: u8, p: &[u8]) -> Result<Option<i64>, Error> {
		match t {
			INT => read_int(p).map(Some),
			0x80..=0xFE => empty(p).map(|()| Some(i64::from(t - SMALL_INT))),
			_ => Ok(None),
		}
	}

	/// A FLOAT of 4 or 8 bytes.
	#[inline(always)]
	pub(crate) fn float(t: u8, p: &[u8]) -> Result<Option<f64>, Error> {
		match t {
			FLOAT => super::float(p).map(Some),
			_ => Ok(None),
		}
	}

	/// A DECIMAL.
	#[inline]
	pub(crate) fn decimal(t: u8, p: &[u8]) -> Result<Option<Decimal>, Error> {
		match t {
			DECIMAL => super::decimal(p).map(Some),
			_ => Ok(None),
		}
	}

	/// A BIGDECIMAL.
	#[inline]
	pub(crate) fn bigdecimal(t: u8, p: &[u8]) -> Result<Option<BigDecimal>, Error> {
		match t {
			BIGDECIMAL => super::bigdecimal(p).map(Some),
			_ => Ok(None),
		}
	}

	/// A STRING of valid UTF-8.
	#[inline(always)]
	pub(crate) fn string(t: u8, p: &[u8]) -> Result<Option<&str>, Error> {
		match t {
			STRING => utf8(p).map(Some),
			_ => Ok(None),
		}
	}

	/// A UUID of 16 bytes.
	#[inline(always)]
	pub(crate) fn uuid(t: u8, p: &[u8]) -> Result<Option<uuid::Uuid>, Error> {
		match t {
			UUID => Ok(Some(uuid::Uuid::from_bytes(fixed(p)?))),
			_ => Ok(None),
		}
	}

	/// A DURATION in either of its two widths.
	#[inline]
	pub(crate) fn duration(t: u8, p: &[u8]) -> Result<Option<std::time::Duration>, Error> {
		match t {
			DURATION => super::duration(p).map(Some),
			_ => Ok(None),
		}
	}

	/// A DATETIME in either of its two widths.
	#[inline]
	pub(crate) fn datetime(t: u8, p: &[u8]) -> Result<Option<DateTime<Utc>>, Error> {
		match t {
			DATETIME => super::datetime(p).map(Some),
			_ => Ok(None),
		}
	}

	/// A DATE of 1 to 4 bytes.
	#[inline]
	pub(crate) fn date(t: u8, p: &[u8]) -> Result<Option<Date>, Error> {
		match t {
			DATE => super::date(p).map(Some),
			_ => Ok(None),
		}
	}

	/// A TIME of 1 to 8 bytes.
	#[inline]
	pub(crate) fn time(t: u8, p: &[u8]) -> Result<Option<Time>, Error> {
		match t {
			TIME => super::time(p).map(Some),
			_ => Ok(None),
		}
	}

	/// A TIMESTAMP in either of its two widths.
	#[inline]
	pub(crate) fn timestamp(t: u8, p: &[u8]) -> Result<Option<Timestamp>, Error> {
		match t {
			TIMESTAMP => super::timestamp(p).map(Some),
			_ => Ok(None),
		}
	}

	/// An INTERVAL of 16 bytes.
	#[inline]
	pub(crate) fn interval(t: u8, p: &[u8]) -> Result<Option<Interval>, Error> {
		match t {
			INTERVAL => super::interval(p).map(Some),
			_ => Ok(None),
		}
	}

	/// An I8 of 1 byte.
	#[inline(always)]
	pub(crate) fn i8(t: u8, p: &[u8]) -> Result<Option<i8>, Error> {
		match t {
			I8 => {
				let [b] = fixed(p)?;
				Ok(Some(b as i8))
			}
			_ => Ok(None),
		}
	}

	/// A U8 of 1 byte.
	#[inline(always)]
	pub(crate) fn u8(t: u8, p: &[u8]) -> Result<Option<u8>, Error> {
		match t {
			U8 => {
				let [b] = fixed(p)?;
				Ok(Some(b))
			}
			_ => Ok(None),
		}
	}

	/// An I16 of 1 to 2 bytes.
	#[inline(always)]
	pub(crate) fn i16(t: u8, p: &[u8]) -> Result<Option<i16>, Error> {
		match t {
			I16 => {
				if p.is_empty() || p.len() > 2 {
					return Err(Error::Malformed("an i16 of the wrong width"));
				}
				read_int(p).map(|i| Some(i as i16))
			}
			_ => Ok(None),
		}
	}

	/// A U16 of 1 to 2 bytes.
	#[inline(always)]
	pub(crate) fn u16(t: u8, p: &[u8]) -> Result<Option<u16>, Error> {
		match t {
			U16 => {
				if p.is_empty() || p.len() > 2 {
					return Err(Error::Malformed("a u16 of the wrong width"));
				}
				read_uint(p).map(|u| Some(u as u16))
			}
			_ => Ok(None),
		}
	}

	/// An I32 of 1 to 4 bytes.
	#[inline(always)]
	pub(crate) fn i32(t: u8, p: &[u8]) -> Result<Option<i32>, Error> {
		match t {
			I32 => {
				if p.is_empty() || p.len() > 4 {
					return Err(Error::Malformed("an i32 of the wrong width"));
				}
				read_int(p).map(|i| Some(i as i32))
			}
			_ => Ok(None),
		}
	}

	/// A U32 of 1 to 4 bytes.
	#[inline(always)]
	pub(crate) fn u32(t: u8, p: &[u8]) -> Result<Option<u32>, Error> {
		match t {
			U32 => {
				if p.is_empty() || p.len() > 4 {
					return Err(Error::Malformed("a u32 of the wrong width"));
				}
				read_uint(p).map(|u| Some(u as u32))
			}
			_ => Ok(None),
		}
	}

	/// A U64 of 1 to 8 bytes.
	#[inline(always)]
	pub(crate) fn u64(t: u8, p: &[u8]) -> Result<Option<u64>, Error> {
		match t {
			U64 => read_uint(p).map(Some),
			_ => Ok(None),
		}
	}

	/// An F16 of 2 bytes.
	#[inline(always)]
	pub(crate) fn f16(t: u8, p: &[u8]) -> Result<Option<half::f16>, Error> {
		match t {
			F16 => {
				let b = fixed(p)?;
				Ok(Some(half::f16::from_bits(u16::from_le_bytes(b))))
			}
			_ => Ok(None),
		}
	}

	/// An F32 of 4 bytes.
	#[inline(always)]
	pub(crate) fn f32(t: u8, p: &[u8]) -> Result<Option<f32>, Error> {
		match t {
			F32 => {
				let b = fixed(p)?;
				Ok(Some(f32::from_le_bytes(b)))
			}
			_ => Ok(None),
		}
	}
}

/// Compiles a stored pattern exactly as written. A pattern that compiled when it
/// was stored stays readable when the configured size limit has since been
/// lowered: past the limit it compiles with the regex engine's default.
fn regex(s: &str) -> Result<Regex, Error> {
	crate::val::regex::regex_new(s)
		.or_else(|_| surrealdb_types::regex_engine::compile(s, None))
		.map(Regex)
		.map_err(|_| Error::Malformed("a regex that does not compile"))
}

/// The element width in bytes of the integer array with tag `t` (one of
/// `I8_ARRAY..=I64_ARRAY`) and payload `p`.
///
/// An integer array is never empty and holds a whole number of elements; the
/// element count is `p.len() / width`.
#[inline(always)]
pub(super) fn int_array_element_width(t: u8, p: &[u8]) -> Result<usize, Error> {
	let w = width(t, I8_ARRAY);
	match p.is_empty() || !p.len().is_multiple_of(w) {
		true => Err(Error::Malformed("an integer array of the wrong width")),
		false => Ok(w),
	}
}

/// The elements of an integer array whose payload is a whole number of `W`-byte elements.
#[inline]
fn ints<const W: usize>(p: &[u8], from: fn([u8; W]) -> i64) -> Vec<Value> {
	p.as_chunks::<W>().0.iter().map(|c| Value::Number(Number::Int(from(*c)))).collect()
}

/// Walks the array with tag `t` (a typed array or a container) and payload `p`.
fn array<M: Mode>(t: u8, p: &[u8], depth: usize) -> Result<M::Out<Array>, Error> {
	match t {
		I8_ARRAY..=I64_ARRAY => {
			let w = int_array_element_width(t, p)?;
			Ok(match w {
				1 => M::make(|| Array(ints::<1>(p, |c| i8::from_le_bytes(c) as i64))),
				2 => M::make(|| Array(ints::<2>(p, |c| i16::from_le_bytes(c) as i64))),
				4 => M::make(|| Array(ints::<4>(p, |c| i32::from_le_bytes(c) as i64))),
				_ => M::make(|| Array(ints::<8>(p, i64::from_le_bytes))),
			})
		}
		F64_ARRAY => {
			if p.is_empty() || !p.len().is_multiple_of(8) {
				return Err(Error::Malformed("a float array of the wrong width"));
			}
			Ok(M::make(|| {
				Array(
					p.as_chunks::<8>()
						.0
						.iter()
						.map(|c| Value::Number(Number::Float(f64::from_le_bytes(*c))))
						.collect(),
				)
			}))
		}
		F32_ARRAY => {
			if p.is_empty() || !p.len().is_multiple_of(4) {
				return Err(Error::Malformed("a float array of the wrong width"));
			}
			Ok(M::make(|| {
				Array(
					p.as_chunks::<4>()
						.0
						.iter()
						.map(|c| Value::Number(Number::Float(f32::from_le_bytes(*c) as f64)))
						.collect(),
				)
			}))
		}
		0x14..=0x16 => Ok(M::map(items::<M>(p, width(t, ARRAY), depth)?, Array)),
		other => Err(Error::UnknownTag(other)),
	}
}

/// Walks the entries of a container of values, in order.
fn items<M: Mode>(p: &[u8], w: usize, depth: usize) -> Result<M::Out<Vec<Value>>, Error> {
	let c = Container::split(p, w)?;
	let mut out = M::seq::<Value>(c.n);
	for i in 0..c.n {
		M::push::<Value>(&mut out, value::<M>(c.entry(i)?, depth + 1)?);
	}
	Ok(M::finish::<Value>(out))
}

/// Walks the set with tag `t`'s container payload `p`.
fn set<M: Mode>(p: &[u8], w: usize, depth: usize) -> Result<M::Out<Set>, Error> {
	let s = set_value(p, w, depth)?;
	Ok(M::make(|| s))
}

/// Builds the set in `p`. Set elements are checked by building them, so both walks use this.
fn set_value(p: &[u8], w: usize, depth: usize) -> Result<Set, Error> {
	let v = items::<Build>(p, w, depth)?;
	// A set is ordered by `Value`'s ordering, which, unlike byte order, belongs
	// to the code rather than to the bytes. Elements are taken in that order:
	// out-of-order elements are sorted and elements that compare equal are
	// merged, so a set written under another ordering still reads. A set that
	// no order can sort into a strictly ascending run is refused. The sort
	// cannot panic whatever the comparison does.
	let set = VecSet::try_from_vec(v)
		.ok_or(Error::Malformed("a set whose elements have no consistent order"))?;
	Ok(Set(set))
}

/// Walks the object whose container payload is `p`.
pub(super) fn object<M: Mode>(p: &[u8], w: usize, depth: usize) -> Result<M::Out<Object>, Error> {
	object_with::<M>(p, w, depth, |_, _| {})
}

/// [`object`], calling `entry` with the key and the value's tag of each entry once it is walked.
#[inline(always)]
fn object_with<M: Mode>(
	p: &[u8],
	w: usize,
	depth: usize,
	mut entry: impl FnMut(&str, u8),
) -> Result<M::Out<Object>, Error> {
	let c = Container::split(p, w)?;
	let mut entries = M::seq::<(Strand, Value)>(c.n);
	let mut prev: Option<&[u8]> = None;
	for i in 0..c.n {
		let (k, v) = split_clen(c.entry(i)?)?;
		if prev.is_some_and(|prev| prev >= k) {
			return Err(Error::Malformed("object keys out of order"));
		}
		prev = Some(k);
		let ks = utf8(k)?;
		let name = M::make(|| Strand::new(ks));
		let val = value::<M>(v, depth + 1)?;
		if let Some(&tag) = v.first() {
			entry(ks, tag);
		}
		M::push::<(Strand, Value)>(&mut entries, M::zip::<Strand, Value>(name, val));
	}
	Ok(M::map(M::finish::<(Strand, Value)>(entries), |entries: Vec<(Strand, Value)>| {
		Object(VecMap::from_sorted_vec_unchecked(entries))
	}))
}

/// Walks the record id key `b`, nested `depth` containers deep.
fn key<M: Mode>(b: &[u8], depth: usize) -> Result<M::Out<RecordIdKey>, Error> {
	if depth > DEPTH_LIMIT {
		return Err(Error::TooDeep(DEPTH_LIMIT));
	}
	let (&t, p) = b.split_first().ok_or(Error::Truncated)?;
	Ok(match t {
		INT => {
			let i = read_int(p)?;
			M::make(|| RecordIdKey::Number(i))
		}
		0x80..=0xFE => {
			empty(p)?;
			let i = (t - SMALL_INT) as i64;
			M::make(|| RecordIdKey::Number(i))
		}
		STRING => {
			let s = utf8(p)?;
			M::make(|| RecordIdKey::String(Strand::new(s)))
		}
		UUID => {
			let u: [u8; 16] = fixed(p)?;
			M::make(|| RecordIdKey::Uuid(Uuid(uuid::Uuid::from_bytes(u))))
		}
		F64_ARRAY | F32_ARRAY | I8_ARRAY..=I64_ARRAY | 0x14..=0x16 => {
			M::map(array::<M>(t, p, depth)?, RecordIdKey::Array)
		}
		0x1A..=0x1C => M::map(object::<M>(p, width(t, OBJECT), depth)?, RecordIdKey::Object),
		RANGE => {
			let b = bounds::<M, RecordIdKey, _>(p, |b| key::<M>(b, depth + 1))?;
			M::map(b, |(start, end): (Bound<RecordIdKey>, Bound<RecordIdKey>)| {
				RecordIdKey::Range(Box::new(RecordIdKeyRange {
					start,
					end,
				}))
			})
		}
		t if Kind::of(t) == Kind::Unknown => return Err(Error::UnknownTag(t)),
		_ => return Err(Error::Malformed("a record id key of a kind keys cannot have")),
	})
}

/// A range's start and end bounds.
type Bounds<T> = (Bound<T>, Bound<T>);

/// Walks a range's two bounds. The start bound's value is `clen`-prefixed; the end bound's runs to
/// the end of the range.
fn bounds<M: Mode, T, F>(p: &[u8], f: F) -> Result<M::Out<Bounds<T>>, Error>
where
	F: Fn(&[u8]) -> Result<M::Out<T>, Error>,
{
	let (&kind, rest) = p.split_first().ok_or(Error::Truncated)?;
	let (start, rest): (M::Out<Bound<T>>, &[u8]) = match kind {
		UNBOUNDED => (M::make(|| Bound::<T>::Unbounded), rest),
		INCLUDED | EXCLUDED => {
			let (v, rest) = split_clen(rest)?;
			let v = f(v)?;
			(
				M::map(v, |v: T| match kind {
					INCLUDED => Bound::Included(v),
					_ => Bound::Excluded(v),
				}),
				rest,
			)
		}
		_ => return Err(Error::Malformed("a range bound of an unknown kind")),
	};
	let (&kind, v) = rest.split_first().ok_or(Error::Truncated)?;
	let end: M::Out<Bound<T>> = match kind {
		UNBOUNDED => {
			empty(v)?;
			M::make(|| Bound::<T>::Unbounded)
		}
		INCLUDED => M::map(f(v)?, Bound::Included),
		EXCLUDED => M::map(f(v)?, Bound::Excluded),
		_ => return Err(Error::Malformed("a range bound of an unknown kind")),
	};
	Ok(M::zip::<Bound<T>, Bound<T>>(start, end))
}