use crate::{
Account, Date, Decimal, Duration, Error, FieldType, Float32, Float64, Principal, Subaccount,
Timestamp, TypeSchema, U256, Ulid, codec::Decoder, named_schema::unit_enum_len,
};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum IndexValue<'a> {
Absent,
Nat8(u8),
Nat16(u16),
Nat32(u32),
Nat64(u64),
Nat128(u128),
U256(U256),
Ulid(Ulid),
Date(Date),
Duration(Duration),
Decimal(Decimal),
Timestamp(Timestamp),
Account(Account),
Subaccount(Subaccount),
Float64(Float64),
Float32(Float32),
Int8(i8),
Int16(i16),
Int32(i32),
Int64(i64),
Int128(i128),
Principal(Principal),
Bool(bool),
Text(&'a str),
Blob(&'a [u8]),
UnitEnum {
definition: &'static TypeSchema,
ordinal: u8,
},
}
pub(crate) fn operand_type(field: FieldType) -> FieldType {
if let FieldType::Named(link) = field {
match (link.definition)().body {
crate::TypeBody::Wrapped(inner) => return inner,
crate::TypeBody::Checked(rule) => return rule.primitive(),
_ => {}
}
}
field
}
impl<'a> IndexValue<'a> {
pub(crate) fn discrete_successor(self) -> Option<Self> {
match self {
Self::Date(date) => date.checked_add_days(1).map(Self::Date),
Self::Timestamp(time) => Some(Self::Timestamp(Timestamp::from_millis(
time.as_millis().checked_add(1)?,
))),
Self::Duration(duration) => Some(Self::Duration(Duration::from_millis(
duration.as_millis().checked_add(1)?,
))),
Self::UnitEnum {
definition,
ordinal,
} => {
let crate::TypeBody::Enum(variants) = &definition.body else {
return None;
};
let next = ordinal.checked_add(1)?;
(usize::from(next) < variants.len()).then_some(Self::UnitEnum {
definition,
ordinal: next,
})
}
_ => self.integer_successor(),
}
}
pub(crate) fn admit(self, field: FieldType, optional: bool) -> Result<(), Error> {
if self == Self::Absent {
return if optional {
Ok(())
} else {
Err(Error::InvalidOperand)
};
}
if let Some(rule) = field.newtype_rule() {
return match (rule, self) {
(crate::NewtypeRule::Text { .. }, Self::Text(value)) => rule.check_text(value),
(crate::NewtypeRule::NonAnonymous, Self::Principal(value)) => {
crate::NonAnonymousPrincipal::try_from(value).map(|_| ())
}
_ => Err(Error::InvalidOperand),
};
}
match (self, operand_type(field)) {
(
Self::UnitEnum {
definition,
ordinal,
},
FieldType::Named(link),
) => {
let expected = (link.definition)();
if unit_enum_len(definition).is_some_and(|len| usize::from(ordinal) < len)
&& link.name == definition.name
&& definition == expected
{
Ok(())
} else {
Err(Error::InvalidOperand)
}
}
(Self::Nat8(_), FieldType::Nat8)
| (Self::Nat16(_), FieldType::Nat16)
| (Self::Nat32(_), FieldType::Nat32)
| (Self::Nat64(_), FieldType::Nat64)
| (Self::Nat128(_), FieldType::Nat128)
| (Self::Float32(_), FieldType::Float32)
| (Self::Float64(_), FieldType::Float64)
| (Self::Subaccount(_), FieldType::Subaccount)
| (Self::U256(_), FieldType::U256)
| (Self::Ulid(_), FieldType::Ulid)
| (Self::Date(_), FieldType::Date)
| (Self::Duration(_), FieldType::Duration)
| (Self::Timestamp(_), FieldType::Timestamp)
| (Self::Int8(_), FieldType::Int8)
| (Self::Int16(_), FieldType::Int16)
| (Self::Int32(_), FieldType::Int32)
| (Self::Int64(_), FieldType::Int64)
| (Self::Int128(_), FieldType::Int128)
| (Self::Bool(_), FieldType::Bool) => Ok(()),
(Self::Decimal(value), FieldType::Decimal { scale }) => value
.coefficient_at_scale(scale)
.map(|_| ())
.ok_or(Error::InvalidOperand),
(Self::Account(value), FieldType::Account) => {
Self::Principal(value.owner).admit(FieldType::Principal, false)
}
(Self::Principal(value), FieldType::Principal) => {
if value.as_slice().len() <= crate::codec::MAX_PRINCIPAL_BYTES {
Ok(())
} else {
Err(Error::Limit)
}
}
(Self::Text(value), FieldType::Text { max_bytes }) => {
if value.len() <= max_bytes as usize {
Ok(())
} else {
Err(Error::Limit)
}
}
(Self::Blob(value), FieldType::Blob { max_bytes }) => {
if value.len() <= max_bytes as usize {
Ok(())
} else {
Err(Error::Limit)
}
}
_ => Err(Error::InvalidOperand),
}
}
fn append_to(self, out: &mut Vec<u8>) {
match self {
Self::Absent => {}
Self::UnitEnum { ordinal, .. } => out.push(ordinal),
Self::Nat8(value) => out.extend(value.to_be_bytes()),
Self::Nat16(value) => out.extend(value.to_be_bytes()),
Self::Nat32(value) => out.extend(value.to_be_bytes()),
Self::Nat64(value) => out.extend(value.to_be_bytes()),
Self::Nat128(value) => out.extend(value.to_be_bytes()),
Self::Float32(value) => out.extend(value.ordered_bytes()),
Self::Float64(value) => out.extend(value.ordered_bytes()),
Self::Subaccount(value) => out.extend(value),
Self::Account(value) => {
Self::Principal(value.owner).append_to(out);
out.extend(value.effective_subaccount());
}
Self::U256(value) => out.extend(value.to_be_bytes()),
Self::Ulid(value) => out.extend(value.to_bytes()),
Self::Timestamp(value) => Self::Int64(value.as_millis()).append_to(out),
Self::Decimal(value) => value.append_ordered(out),
Self::Duration(value) => Self::Nat64(value.as_millis()).append_to(out),
Self::Date(value) => Self::Int32(value.as_days_since_epoch()).append_to(out),
Self::Int8(value) => {
let mut bytes = value.to_be_bytes();
bytes[0] ^= 0x80;
out.extend(bytes);
}
Self::Int16(value) => {
let mut bytes = value.to_be_bytes();
bytes[0] ^= 0x80;
out.extend(bytes);
}
Self::Int32(value) => out.extend(ordered_i32(value)),
Self::Int64(value) => {
let mut bytes = value.to_be_bytes();
bytes[0] ^= 0x80;
out.extend(bytes);
}
Self::Int128(value) => {
let mut bytes = value.to_be_bytes();
bytes[0] ^= 0x80;
out.extend(bytes);
}
Self::Principal(value) => {
out.push(value.as_slice().len() as u8);
out.extend(value.as_slice());
}
Self::Bool(value) => out.push(u8::from(value)),
Self::Text(value) => append_bytes(value.as_bytes(), out),
Self::Blob(value) => append_bytes(value, out),
}
}
#[inline]
pub(crate) fn component(self, optional: bool) -> Vec<u8> {
let mut bytes = Vec::new();
self.append_component(optional, &mut bytes);
bytes
}
pub(crate) fn append_component(self, optional: bool, out: &mut Vec<u8>) {
if optional {
out.push(u8::from(self != Self::Absent));
}
self.append_to(out);
}
pub(crate) fn read(reader: &mut Decoder<'a>, field: FieldType) -> Result<Self, Error> {
if let Some(rule) = field.newtype_rule() {
return match rule {
crate::NewtypeRule::Text { .. } => Ok(Self::Text(reader.checked_text(rule)?)),
crate::NewtypeRule::NonAnonymous => {
Ok(reader.named::<crate::NonAnonymousPrincipal>()?.into())
}
};
}
Ok(match operand_type(field) {
FieldType::Named(link) => {
let definition = (link.definition)();
let len = unit_enum_len(definition).ok_or(Error::Corrupt)?;
let ordinal = reader.unit_enum(len)?;
Self::UnitEnum {
definition,
ordinal,
}
}
FieldType::Nat8 => Self::Nat8(reader.nat8()?),
FieldType::Nat16 => Self::Nat16(reader.nat16()?),
FieldType::Nat32 => Self::Nat32(reader.nat32()?),
FieldType::Nat64 => Self::Nat64(reader.nat64()?),
FieldType::Nat128 => Self::Nat128(reader.nat128()?),
FieldType::Float32 => Self::Float32(reader.float32()?),
FieldType::Float64 => Self::Float64(reader.float64()?),
FieldType::Subaccount => Self::Subaccount(reader.subaccount()?),
FieldType::Account => Self::Account(reader.account()?),
FieldType::U256 => Self::U256(reader.u256()?),
FieldType::Ulid => Self::Ulid(reader.ulid()?),
FieldType::Date => Self::Date(reader.date()?),
FieldType::Decimal { scale } => Self::Decimal(reader.decimal(scale)?),
FieldType::Duration => Self::Duration(reader.duration()?),
FieldType::Timestamp => Self::Timestamp(reader.timestamp()?),
FieldType::Int8 => Self::Int8(reader.int8()?),
FieldType::Int16 => Self::Int16(reader.int16()?),
FieldType::Int32 => Self::Int32(reader.int32()?),
FieldType::Int64 => Self::Int64(reader.int64()?),
FieldType::Int128 => Self::Int128(reader.int128()?),
FieldType::Principal => Self::Principal(reader.principal()?),
FieldType::Bool => Self::Bool(reader.boolean()?),
FieldType::Text { max_bytes } => Self::Text(reader.text_ref(max_bytes as usize)?),
FieldType::Blob { max_bytes } => Self::Blob(reader.blob_ref(max_bytes as usize)?),
_ => return Err(Error::Corrupt),
})
}
}
pub(crate) fn minimum_bytes(field: FieldType) -> Result<usize, Error> {
let field = operand_type(field);
if let Some(width) = fixed_width(field) {
return Ok(width);
}
match field {
FieldType::Principal | FieldType::Decimal { .. } => Ok(1),
FieldType::Text { .. } | FieldType::Blob { .. } => Ok(2),
FieldType::Account => Ok(33),
_ => Err(Error::InvalidOperand),
}
}
#[doc(hidden)]
#[must_use]
pub fn encode_index(values: &[(IndexValue<'_>, bool)], present_only: bool) -> Option<Vec<u8>> {
let mut bytes = None;
encode_index_into(values, present_only, &mut bytes);
bytes
}
pub(crate) fn encode_index_into(
values: &[(IndexValue<'_>, bool)],
present_only: bool,
slot: &mut Option<Vec<u8>>,
) {
if present_only && values.iter().any(|(value, _)| *value == IndexValue::Absent) {
*slot = None;
return;
}
let bytes = slot.get_or_insert_with(Vec::new);
bytes.clear();
for &(value, optional) in values {
value.append_component(optional, bytes);
}
}
#[doc(hidden)]
pub trait MemberPresence<'a> {
type Scalar: 'a;
fn __ic_db_member_presence(self) -> (Option<&'a Self::Scalar>, bool);
}
impl<'a, T> MemberPresence<'a> for &'a Option<T> {
type Scalar = T;
fn __ic_db_member_presence(self) -> (Option<&'a T>, bool) {
(self.as_ref(), true)
}
}
impl<'a, T> MemberPresence<'a> for &&'a T {
type Scalar = T;
fn __ic_db_member_presence(self) -> (Option<&'a T>, bool) {
(Some(*self), false)
}
}
#[doc(hidden)]
pub trait MemberOperand<'a> {
fn __ic_db_member_operand(self) -> IndexValue<'a>;
}
impl<'a, T: Into<IndexValue<'a>>> MemberOperand<'a> for T {
fn __ic_db_member_operand(self) -> IndexValue<'a> {
self.into()
}
}
impl<'a, T: Into<IndexValue<'a>>> From<Option<T>> for IndexValue<'a> {
fn from(value: Option<T>) -> Self {
value.map_or(Self::Absent, Into::into)
}
}
macro_rules! integer_operands {
($($variant:ident($integer:ty)),+ $(,)?) => {
$(
impl From<$integer> for IndexValue<'_> {
fn from(value: $integer) -> Self {
Self::$variant(value)
}
}
)+
impl IndexValue<'_> {
pub(crate) fn integer_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
match (self, other) {
$((Self::$variant(left), Self::$variant(right)) => Some(left.cmp(right)),)+
_ => None,
}
}
fn integer_successor(self) -> Option<Self> {
match self {
$(Self::$variant(n) => n.checked_add(<$integer>::from(true)).map(Self::$variant),)+
_ => None,
}
}
pub(crate) fn is_integer_extreme(self, upper: bool) -> bool {
match self {
$(Self::$variant(n) => n == if upper { <$integer>::MAX } else { <$integer>::MIN },)+
_ => false,
}
}
}
};
}
integer_operands!(
Nat8(u8),
Nat16(u16),
Nat32(u32),
Nat64(u64),
Nat128(u128),
U256(U256),
Int8(i8),
Int16(i16),
Int32(i32),
Int64(i64),
Int128(i128),
);
macro_rules! scalar_conversions {
($($scalar:ident),+ $(,)?) => {$(
impl From<$scalar> for IndexValue<'_> {
fn from(value: $scalar) -> Self {
Self::$scalar(value)
}
}
)+};
}
scalar_conversions!(
Principal, Ulid, Timestamp, Decimal, Duration, Date, Float32, Float64, Subaccount, Account
);
pub(crate) fn fixed_width(field: FieldType) -> Option<usize> {
match field {
FieldType::Named(link) if unit_enum_len((link.definition)()).is_some() => Some(1),
FieldType::Nat8 | FieldType::Int8 | FieldType::Bool => Some(1),
FieldType::Nat16 | FieldType::Int16 => Some(2),
FieldType::Nat32 | FieldType::Int32 | FieldType::Float32 | FieldType::Date => Some(4),
FieldType::Nat64
| FieldType::Int64
| FieldType::Float64
| FieldType::Timestamp
| FieldType::Duration => Some(8),
FieldType::Nat128 | FieldType::Int128 | FieldType::Ulid => Some(16),
FieldType::U256 | FieldType::Subaccount => Some(32),
_ => None,
}
}
fn ordered_i32(value: i32) -> [u8; 4] {
(value ^ i32::MIN).to_be_bytes()
}
pub(crate) fn is_fixed_extreme(field: FieldType, bytes: &[u8], upper: bool) -> bool {
match operand_type(field) {
FieldType::Bool => bytes == [u8::from(upper)],
FieldType::Date => {
let date = if upper { Date::MAX } else { Date::MIN };
bytes == ordered_i32(date.as_days_since_epoch())
}
FieldType::Named(link) => unit_enum_len((link.definition)())
.is_some_and(|len| bytes == [if upper { (len - 1) as u8 } else { 0 }]),
scalar => {
fixed_width(scalar) == Some(bytes.len())
&& bytes.iter().all(|&b| b == if upper { u8::MAX } else { 0 })
}
}
}
pub(crate) fn supports(field: FieldType) -> bool {
minimum_bytes(field).is_ok()
}
pub(crate) fn consume_component(
bytes: &mut &[u8],
field: crate::ValueSchema,
present_only: bool,
invalid_presence: Error,
) -> Result<(), Error> {
if field.optional {
match *bytes {
[0, rest @ ..] if !present_only => {
*bytes = rest;
return Ok(());
}
[1, rest @ ..] => *bytes = rest,
_ => return Err(invalid_presence),
}
}
consume(bytes, field.value)
}
pub(crate) fn consume(bytes: &mut &[u8], field: FieldType) -> Result<(), Error> {
let rule = field.newtype_rule();
let field = operand_type(field);
if let FieldType::Named(link) = field {
let len = unit_enum_len((link.definition)()).ok_or(Error::Corrupt)?;
let (&ordinal, rest) = bytes.split_first().ok_or(Error::Corrupt)?;
if usize::from(ordinal) >= len {
return Err(Error::Corrupt);
}
*bytes = rest;
return Ok(());
}
if let FieldType::Decimal { scale } = field {
let (value, width) = Decimal::read_ordered(bytes).ok_or(Error::Corrupt)?;
value.coefficient_at_scale(scale).ok_or(Error::Corrupt)?;
*bytes = &bytes[width..];
return Ok(());
}
if let FieldType::Text { max_bytes } | FieldType::Blob { max_bytes } = field {
let mut decoded = 0;
let mut checked = rule.and_then(crate::NewtypeRule::text_check);
loop {
let end = bytes
.iter()
.position(|&byte| byte == 0)
.ok_or(Error::Corrupt)?;
if matches!(field, FieldType::Text { .. }) {
let segment = std::str::from_utf8(&bytes[..end]).map_err(|_| Error::Corrupt)?;
if let Some(check) = &mut checked {
check.segment(segment).map_err(|_| Error::Corrupt)?;
}
}
decoded += end;
let escaped = *bytes.get(end + 1).ok_or(Error::Corrupt)?;
*bytes = &bytes[end + 2..];
match escaped {
0 if decoded <= max_bytes as usize => {
if let Some(check) = checked {
check.finish().map_err(|_| Error::Corrupt)?;
}
return Ok(());
}
255 => {
decoded += 1;
if let Some(check) = &mut checked {
check.segment("\0").map_err(|_| Error::Corrupt)?;
}
}
_ => return Err(Error::Corrupt),
}
if decoded > max_bytes as usize {
return Err(Error::Corrupt);
}
}
}
if field == FieldType::Bool && !matches!(bytes.first(), Some(0 | 1)) {
return Err(Error::Corrupt);
}
let width = if matches!(field, FieldType::Principal | FieldType::Account) {
let (&len, _) = bytes.split_first().ok_or(Error::Corrupt)?;
if usize::from(len) > crate::codec::MAX_PRINCIPAL_BYTES {
return Err(Error::Corrupt);
}
usize::from(len) + 1 + if field == FieldType::Account { 32 } else { 0 }
} else {
fixed_width(field).ok_or(Error::Corrupt)?
};
let component = bytes.get(..width).ok_or(Error::Corrupt)?;
if let Some(crate::NewtypeRule::NonAnonymous) = rule {
let principal = Principal::try_from_slice(&component[1..]).map_err(|_| Error::Corrupt)?;
crate::NonAnonymousPrincipal::try_from(principal).map_err(|_| Error::Corrupt)?;
}
match field {
FieldType::Date => {
let mut encoded: [u8; 4] = component.try_into().map_err(|_| Error::Corrupt)?;
encoded[0] ^= 0x80;
Date::try_from_days_since_epoch(i32::from_be_bytes(encoded)).ok_or(Error::Corrupt)?;
}
FieldType::Float32 => {
Float32::from_ordered_bytes(component.try_into().map_err(|_| Error::Corrupt)?)
.ok_or(Error::Corrupt)?;
}
FieldType::Float64 => {
Float64::from_ordered_bytes(component.try_into().map_err(|_| Error::Corrupt)?)
.ok_or(Error::Corrupt)?;
}
_ => {}
}
*bytes = &bytes[width..];
Ok(())
}
impl From<bool> for IndexValue<'_> {
fn from(value: bool) -> Self {
Self::Bool(value)
}
}
impl<'a> From<&'a str> for IndexValue<'a> {
fn from(value: &'a str) -> Self {
Self::Text(value)
}
}
impl<'a> From<&'a String> for IndexValue<'a> {
fn from(value: &'a String) -> Self {
Self::Text(value)
}
}
impl<'a> From<&'a Vec<u8>> for IndexValue<'a> {
fn from(value: &'a Vec<u8>) -> Self {
Self::Blob(value)
}
}
impl<'a, const N: usize> From<&'a [u8; N]> for IndexValue<'a> {
fn from(value: &'a [u8; N]) -> Self {
Self::Blob(value)
}
}
impl<'a> From<&'a [u8]> for IndexValue<'a> {
fn from(value: &'a [u8]) -> Self {
Self::Blob(value)
}
}
pub(crate) fn empty_bytes_component(optional: bool) -> &'static [u8] {
const PRESENT_EMPTY: &[u8] = &[1, 0, 0];
if optional {
PRESENT_EMPTY
} else {
&PRESENT_EMPTY[1..]
}
}
pub(crate) fn bytes_prefix(component: &[u8]) -> Option<&[u8]> {
component.strip_suffix(empty_bytes_component(false))
}
fn append_bytes(value: &[u8], out: &mut Vec<u8>) {
for &byte in value {
out.push(byte);
if byte == 0 {
out.push(255);
}
}
out.extend_from_slice(empty_bytes_component(false));
}