use surrealdb_kvs::release::Release;
use super::{MAX_SCHEMA_DEPTH, SchemaError, StoredField};
use crate::val::stored::decode::strict;
use crate::val::stored::{Encoder, Error, Item, MapRef, Open};
pub fn map<'a>(item: Item<'a>, depth: u32, ty: &'static str) -> Result<MapRef<'a>, SchemaError> {
if depth > MAX_SCHEMA_DEPTH {
return Err(SchemaError::TooDeep {
ty,
});
}
item.map()?.ok_or(SchemaError::WrongKind {
ty,
n: 0,
})
}
pub fn entry<'a>(
map: &MapRef<'a>,
i: usize,
prev: &mut u32,
ty: &'static str,
) -> Result<(u32, Item<'a>), SchemaError> {
let (n, item) = map.entry(i)?;
if n <= *prev {
return Err(SchemaError::FieldOrder {
ty,
});
}
*prev = n;
Ok((n, item))
}
pub fn field<T: StoredField>(
item: Item<'_>,
depth: u32,
ty: &'static str,
n: u32,
) -> Result<T, SchemaError> {
T::decode_item(item, depth.saturating_add(1)).map_err(|e| e.at(ty, n))
}
pub fn field_via<T, O: StoredField>(
item: Item<'_>,
depth: u32,
ty: &'static str,
n: u32,
narrow: fn(&T) -> Option<O>,
) -> Result<O, SchemaError> {
let _ = narrow;
field::<O>(item, depth, ty, n)
}
pub const fn narrow_type_name<T, O: StoredField>(narrow: fn(&T) -> Option<O>) -> fn(&mut String) {
let _ = narrow;
O::write_type_name
}
pub fn unknown(n: u32, ty: &'static str, reserved: &[u32]) -> Result<(), SchemaError> {
if reserved.contains(&n) || n % 2 == 1 {
Ok(())
} else {
Err(SchemaError::UnknownCriticalField {
ty,
n,
})
}
}
pub const fn missing(ty: &'static str, n: u32) -> SchemaError {
SchemaError::MissingField {
ty,
n,
}
}
pub const fn order(ty: &'static str) -> SchemaError {
SchemaError::FieldOrder {
ty,
}
}
pub const fn legacy(ty: &'static str) -> SchemaError {
SchemaError::LegacyVariant {
ty,
}
}
pub fn max_release(a: Option<Release>, b: Option<Release>) -> Option<Release> {
match (a, b) {
(Some(a), Some(b)) => Some(a.max(b)),
(a, None) => a,
(None, b) => b,
}
}
pub fn one_variant<'a>(
item: Item<'a>,
depth: u32,
ty: &'static str,
) -> Result<(u32, Item<'a>), SchemaError> {
let map = map(item, depth, ty)?;
if map.len() != 1 {
return Err(SchemaError::NotOneVariant {
ty,
});
}
Ok(map.entry(0)?)
}
pub fn unit(payload: Item<'_>, ty: &'static str, n: u32) -> Result<(), SchemaError> {
let (&tag, rest) = payload.bytes().split_first().ok_or(Error::Truncated)?;
match strict::none(tag, rest)? {
Some(()) => Ok(()),
None => Err(SchemaError::WrongKind {
ty,
n,
}),
}
}
pub fn variant_prior(prior: Option<Item<'_>>, n: u32) -> Option<Item<'_>> {
let map = prior?.map().ok().flatten()?;
if map.len() != 1 {
return None;
}
let (k, item) = map.entry(0).ok()?;
(k == n).then_some(item)
}
pub struct Entries<'p> {
map: Option<MapRef<'p>>,
left: usize,
}
impl<'p> Entries<'p> {
pub fn new(prior: Option<Item<'p>>) -> Self {
let map =
prior.and_then(|item| item.map().ok().flatten()).filter(|map| map.validate().is_ok());
Self {
left: map.as_ref().map_or(0, MapRef::len),
map,
}
}
pub fn take(
&mut self,
enc: &mut Encoder,
open: &mut Open,
n: u32,
ours: fn(u32) -> bool,
) -> Result<Option<Item<'p>>, SchemaError> {
let Some(map) = self.map else {
return Ok(None);
};
while let Some(last) = self.left.checked_sub(1) {
let (k, item) = map.entry(last)?;
if k < n {
return Ok(None);
}
self.left = last;
if k == n {
return Ok(Some(item));
}
if k % 2 == 1 && !ours(k) {
enc.raw_entry(open, k, item.bytes())?;
}
}
Ok(None)
}
}
pub struct MapWriter<'e, 'p> {
enc: &'e mut Encoder,
open: Open,
entries: Entries<'p>,
ty: &'static str,
ours: fn(u32) -> bool,
}
impl<'e, 'p> MapWriter<'e, 'p> {
pub fn new(
enc: &'e mut Encoder,
prior: Option<Item<'p>>,
ty: &'static str,
ours: fn(u32) -> bool,
) -> Result<Self, SchemaError> {
let open = enc.open()?;
Ok(Self {
enc,
open,
entries: Entries::new(prior),
ty,
ours,
})
}
pub fn put<T: StoredField>(&mut self, value: &T, n: u32) -> Result<(), SchemaError> {
let prior = self.entries.take(self.enc, &mut self.open, n, self.ours)?;
value.encode_item(self.enc, prior).map_err(|e| e.at(self.ty, n))?;
self.enc.end_entry(&mut self.open, n)?;
Ok(())
}
pub fn skip(&mut self, n: u32) -> Result<(), SchemaError> {
self.entries.take(self.enc, &mut self.open, n, self.ours)?;
Ok(())
}
pub fn finish(mut self) -> Result<(), SchemaError> {
self.entries.take(self.enc, &mut self.open, 0, self.ours)?;
self.enc.close_map(self.open)?;
Ok(())
}
}