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,
};
pub(super) trait Mode {
type Out<T>;
type Seq<T>;
fn make<T>(f: impl FnOnce() -> T) -> Self::Out<T>;
fn map<T, U>(v: Self::Out<T>, f: impl FnOnce(T) -> U) -> Self::Out<U>;
fn zip<A, B>(a: Self::Out<A>, b: Self::Out<B>) -> Self::Out<(A, B)>;
fn seq<T>(capacity: usize) -> Self::Seq<T>;
fn push<T>(seq: &mut Self::Seq<T>, item: Self::Out<T>);
fn finish<T>(seq: Self::Seq<T>) -> Self::Out<Vec<T>>;
}
pub(super) enum Build {}
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>(_: ()) {}
}
pub fn decode(bytes: &[u8]) -> Result<Value, Error> {
decode_nested(bytes, 0)
}
pub fn decode_nested(bytes: &[u8], depth: usize) -> Result<Value, Error> {
value::<Build>(bytes, depth)
}
pub fn validate(bytes: &[u8]) -> Result<(), Error> {
validate_nested(bytes, 0)
}
pub fn validate_nested(bytes: &[u8], depth: usize) -> Result<(), Error> {
value::<Check>(bytes, depth)
}
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)
}
pub fn decode_key(bytes: &[u8]) -> Result<RecordIdKey, Error> {
decode_key_nested(bytes, 0)
}
pub fn decode_key_nested(bytes: &[u8], depth: usize) -> Result<RecordIdKey, Error> {
key::<Build>(bytes, depth)
}
pub fn validate_key_nested(bytes: &[u8], depth: usize) -> Result<(), Error> {
key::<Check>(bytes, depth)
}
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)
}
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)
}
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)
}
pub fn bigdecimal_payload(p: &[u8]) -> Result<BigDecimal, Error> {
bigdecimal(p)
}
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))
}
#[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)
}
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)?;
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)),
})
}
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};
#[inline(always)]
pub(crate) fn none(t: u8, p: &[u8]) -> Result<Option<()>, Error> {
match t {
NONE => empty(p).map(Some),
_ => Ok(None),
}
}
#[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),
}
}
#[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),
}
}
#[inline(always)]
pub(crate) fn float(t: u8, p: &[u8]) -> Result<Option<f64>, Error> {
match t {
FLOAT => super::float(p).map(Some),
_ => Ok(None),
}
}
#[inline]
pub(crate) fn decimal(t: u8, p: &[u8]) -> Result<Option<Decimal>, Error> {
match t {
DECIMAL => super::decimal(p).map(Some),
_ => Ok(None),
}
}
#[inline]
pub(crate) fn bigdecimal(t: u8, p: &[u8]) -> Result<Option<BigDecimal>, Error> {
match t {
BIGDECIMAL => super::bigdecimal(p).map(Some),
_ => Ok(None),
}
}
#[inline(always)]
pub(crate) fn string(t: u8, p: &[u8]) -> Result<Option<&str>, Error> {
match t {
STRING => utf8(p).map(Some),
_ => Ok(None),
}
}
#[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),
}
}
#[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),
}
}
#[inline]
pub(crate) fn datetime(t: u8, p: &[u8]) -> Result<Option<DateTime<Utc>>, Error> {
match t {
DATETIME => super::datetime(p).map(Some),
_ => Ok(None),
}
}
#[inline]
pub(crate) fn date(t: u8, p: &[u8]) -> Result<Option<Date>, Error> {
match t {
DATE => super::date(p).map(Some),
_ => Ok(None),
}
}
#[inline]
pub(crate) fn time(t: u8, p: &[u8]) -> Result<Option<Time>, Error> {
match t {
TIME => super::time(p).map(Some),
_ => Ok(None),
}
}
#[inline]
pub(crate) fn timestamp(t: u8, p: &[u8]) -> Result<Option<Timestamp>, Error> {
match t {
TIMESTAMP => super::timestamp(p).map(Some),
_ => Ok(None),
}
}
#[inline]
pub(crate) fn interval(t: u8, p: &[u8]) -> Result<Option<Interval>, Error> {
match t {
INTERVAL => super::interval(p).map(Some),
_ => Ok(None),
}
}
#[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),
}
}
#[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),
}
}
#[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),
}
}
#[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),
}
}
#[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),
}
}
#[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),
}
}
#[inline(always)]
pub(crate) fn u64(t: u8, p: &[u8]) -> Result<Option<u64>, Error> {
match t {
U64 => read_uint(p).map(Some),
_ => Ok(None),
}
}
#[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),
}
}
#[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),
}
}
}
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"))
}
#[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),
}
}
#[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()
}
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)),
}
}
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))
}
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))
}
fn set_value(p: &[u8], w: usize, depth: usize) -> Result<Set, Error> {
let v = items::<Build>(p, w, depth)?;
let set = VecSet::try_from_vec(v)
.ok_or(Error::Malformed("a set whose elements have no consistent order"))?;
Ok(Set(set))
}
pub(super) fn object<M: Mode>(p: &[u8], w: usize, depth: usize) -> Result<M::Out<Object>, Error> {
object_with::<M>(p, w, depth, |_, _| {})
}
#[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))
}))
}
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")),
})
}
type Bounds<T> = (Bound<T>, Bound<T>);
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))
}