1use crate::{
4 Account, Date, Decimal, Duration, Error, FieldType, Float32, Float64, Principal, Subaccount,
5 Timestamp, TypeSchema, U256, Ulid, codec::Decoder, named_schema::unit_enum_len,
6};
7
8#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13pub enum IndexValue<'a> {
14 Absent,
16 Nat8(u8),
18 Nat16(u16),
20 Nat32(u32),
22 Nat64(u64),
24 Nat128(u128),
26 U256(U256),
28 Ulid(Ulid),
30 Date(Date),
32 Duration(Duration),
34 Decimal(Decimal),
36 Timestamp(Timestamp),
38 Account(Account),
40 Subaccount(Subaccount),
42 Float64(Float64),
44 Float32(Float32),
46 Int8(i8),
48 Int16(i16),
50 Int32(i32),
52 Int64(i64),
54 Int128(i128),
56 Principal(Principal),
58 Bool(bool),
60 Text(&'a str),
62 Blob(&'a [u8]),
64 UnitEnum {
66 definition: &'static TypeSchema,
68 ordinal: u8,
70 },
71}
72
73pub(crate) fn operand_type(field: FieldType) -> FieldType {
76 if let FieldType::Named(link) = field {
77 match (link.definition)().body {
78 crate::TypeBody::Wrapped(inner) => return inner,
79 crate::TypeBody::Checked(rule) => return rule.primitive(),
80 _ => {}
81 }
82 }
83 field
84}
85impl<'a> IndexValue<'a> {
86 pub(crate) fn discrete_successor(self) -> Option<Self> {
88 if let Self::UnitEnum {
89 definition,
90 ordinal,
91 } = self
92 {
93 let crate::TypeBody::Enum(variants) = &definition.body else {
94 return None;
95 };
96 let next = ordinal.checked_add(1)?;
97
98 return (usize::from(next) < variants.len()).then_some(Self::UnitEnum {
99 definition,
100 ordinal: next,
101 });
102 }
103
104 self.integer_successor()
105 }
106
107 pub(crate) fn admit(self, field: FieldType, optional: bool) -> Result<(), Error> {
108 if self == Self::Absent {
109 return if optional {
110 Ok(())
111 } else {
112 Err(Error::InvalidOperand)
113 };
114 }
115
116 if let Some(rule) = field.newtype_rule() {
117 return match (rule, self) {
118 (crate::NewtypeRule::Text { .. }, Self::Text(value)) => rule.check_text(value),
119 (crate::NewtypeRule::NonAnonymous, Self::Principal(value)) => {
120 crate::NonAnonymousPrincipal::try_from(value).map(|_| ())
121 }
122 _ => Err(Error::InvalidOperand),
123 };
124 }
125 match (self, operand_type(field)) {
126 (
127 Self::UnitEnum {
128 definition,
129 ordinal,
130 },
131 FieldType::Named(link),
132 ) => {
133 let expected = (link.definition)();
134
135 if unit_enum_len(definition).is_some_and(|len| usize::from(ordinal) < len)
137 && link.name == definition.name
138 && definition == expected
139 {
140 Ok(())
141 } else {
142 Err(Error::InvalidOperand)
143 }
144 }
145 (Self::Nat8(_), FieldType::Nat8)
146 | (Self::Nat16(_), FieldType::Nat16)
147 | (Self::Nat32(_), FieldType::Nat32)
148 | (Self::Nat64(_), FieldType::Nat64)
149 | (Self::Nat128(_), FieldType::Nat128)
150 | (Self::Float32(_), FieldType::Float32)
151 | (Self::Float64(_), FieldType::Float64)
152 | (Self::Subaccount(_), FieldType::Subaccount)
153 | (Self::U256(_), FieldType::U256)
154 | (Self::Ulid(_), FieldType::Ulid)
155 | (Self::Date(_), FieldType::Date)
156 | (Self::Duration(_), FieldType::Duration)
157 | (Self::Timestamp(_), FieldType::Timestamp)
158 | (Self::Int8(_), FieldType::Int8)
159 | (Self::Int16(_), FieldType::Int16)
160 | (Self::Int32(_), FieldType::Int32)
161 | (Self::Int64(_), FieldType::Int64)
162 | (Self::Int128(_), FieldType::Int128)
163 | (Self::Bool(_), FieldType::Bool) => Ok(()),
164 (Self::Decimal(value), FieldType::Decimal { scale }) => value
165 .coefficient_at_scale(scale)
166 .map(|_| ())
167 .ok_or(Error::InvalidOperand),
168 (Self::Account(value), FieldType::Account) => {
169 Self::Principal(value.owner).admit(FieldType::Principal, false)
170 }
171 (Self::Principal(value), FieldType::Principal) => {
172 if value.as_slice().len() <= crate::codec::MAX_PRINCIPAL_BYTES {
173 Ok(())
174 } else {
175 Err(Error::Limit)
176 }
177 }
178 (Self::Text(value), FieldType::Text { max_bytes }) => {
179 if value.len() <= max_bytes as usize {
180 Ok(())
181 } else {
182 Err(Error::Limit)
183 }
184 }
185 (Self::Blob(value), FieldType::Blob { max_bytes }) => {
186 if value.len() <= max_bytes as usize {
187 Ok(())
188 } else {
189 Err(Error::Limit)
190 }
191 }
192 _ => Err(Error::InvalidOperand),
193 }
194 }
195
196 fn append_to(self, out: &mut Vec<u8>) {
198 match self {
199 Self::Absent => {}
200 Self::UnitEnum { ordinal, .. } => out.push(ordinal),
201 Self::Nat8(value) => out.extend(value.to_be_bytes()),
202 Self::Nat16(value) => out.extend(value.to_be_bytes()),
203 Self::Nat32(value) => out.extend(value.to_be_bytes()),
204 Self::Nat64(value) => out.extend(value.to_be_bytes()),
205 Self::Nat128(value) => out.extend(value.to_be_bytes()),
206 Self::Float32(value) => out.extend(value.ordered_bytes()),
207 Self::Float64(value) => out.extend(value.ordered_bytes()),
208 Self::Subaccount(value) => out.extend(value),
209 Self::Account(value) => {
210 Self::Principal(value.owner).append_to(out);
211 out.extend(value.effective_subaccount());
212 }
213 Self::U256(value) => out.extend(value.to_be_bytes()),
214 Self::Ulid(value) => out.extend(value.to_bytes()),
215 Self::Timestamp(value) => Self::Int64(value.as_millis()).append_to(out),
216 Self::Decimal(value) => value.append_ordered(out),
217 Self::Duration(value) => Self::Nat64(value.as_millis()).append_to(out),
218 Self::Date(value) => Self::Int32(value.as_days_since_epoch()).append_to(out),
219 Self::Int8(value) => {
220 let mut bytes = value.to_be_bytes();
221 bytes[0] ^= 0x80;
222 out.extend(bytes);
223 }
224 Self::Int16(value) => {
225 let mut bytes = value.to_be_bytes();
226 bytes[0] ^= 0x80;
227 out.extend(bytes);
228 }
229 Self::Int32(value) => {
230 let mut bytes = value.to_be_bytes();
231 bytes[0] ^= 0x80;
232 out.extend(bytes);
233 }
234 Self::Int64(value) => {
235 let mut bytes = value.to_be_bytes();
236 bytes[0] ^= 0x80;
237 out.extend(bytes);
238 }
239 Self::Int128(value) => {
240 let mut bytes = value.to_be_bytes();
241 bytes[0] ^= 0x80;
242 out.extend(bytes);
243 }
244 Self::Principal(value) => {
245 out.push(value.as_slice().len() as u8);
247 out.extend(value.as_slice());
248 }
249 Self::Bool(value) => out.push(u8::from(value)),
250 Self::Text(value) => append_bytes(value.as_bytes(), out),
251 Self::Blob(value) => append_bytes(value, out),
252 }
253 }
254
255 pub(crate) fn append_component(self, optional: bool, out: &mut Vec<u8>) {
256 if optional {
257 out.push(u8::from(self != Self::Absent));
258 }
259 self.append_to(out);
260 }
261
262 pub(crate) fn read(reader: &mut Decoder<'a>, field: FieldType) -> Result<Self, Error> {
263 if let Some(rule) = field.newtype_rule() {
264 return match rule {
265 crate::NewtypeRule::Text { .. } => Ok(Self::Text(reader.checked_text(rule)?)),
266 crate::NewtypeRule::NonAnonymous => {
267 Ok(reader.named::<crate::NonAnonymousPrincipal>()?.into())
268 }
269 };
270 }
271 Ok(match operand_type(field) {
272 FieldType::Named(link) => {
273 let definition = (link.definition)();
274 let len = unit_enum_len(definition).ok_or(Error::Corrupt)?;
275 let ordinal = reader.unit_enum(len)?;
276
277 Self::UnitEnum {
278 definition,
279 ordinal,
280 }
281 }
282 FieldType::Nat8 => Self::Nat8(reader.nat8()?),
283 FieldType::Nat16 => Self::Nat16(reader.nat16()?),
284 FieldType::Nat32 => Self::Nat32(reader.nat32()?),
285 FieldType::Nat64 => Self::Nat64(reader.nat64()?),
286 FieldType::Nat128 => Self::Nat128(reader.nat128()?),
287 FieldType::Float32 => Self::Float32(reader.float32()?),
288 FieldType::Float64 => Self::Float64(reader.float64()?),
289 FieldType::Subaccount => Self::Subaccount(reader.subaccount()?),
290 FieldType::Account => Self::Account(reader.account()?),
291 FieldType::U256 => Self::U256(reader.u256()?),
292 FieldType::Ulid => Self::Ulid(reader.ulid()?),
293 FieldType::Date => Self::Date(reader.date()?),
294 FieldType::Decimal { scale } => Self::Decimal(reader.decimal(scale)?),
295 FieldType::Duration => Self::Duration(reader.duration()?),
296 FieldType::Timestamp => Self::Timestamp(reader.timestamp()?),
297 FieldType::Int8 => Self::Int8(reader.int8()?),
298 FieldType::Int16 => Self::Int16(reader.int16()?),
299 FieldType::Int32 => Self::Int32(reader.int32()?),
300 FieldType::Int64 => Self::Int64(reader.int64()?),
301 FieldType::Int128 => Self::Int128(reader.int128()?),
302 FieldType::Principal => Self::Principal(reader.principal()?),
303 FieldType::Bool => Self::Bool(reader.boolean()?),
304 FieldType::Text { max_bytes } => Self::Text(reader.text_ref(max_bytes as usize)?),
305 FieldType::Blob { max_bytes } => Self::Blob(reader.blob_ref(max_bytes as usize)?),
306 _ => return Err(Error::Corrupt),
307 })
308 }
309}
310
311pub(crate) fn minimum_bytes(field: FieldType) -> Result<usize, Error> {
314 Ok(match operand_type(field) {
315 FieldType::Named(link) if unit_enum_len((link.definition)()).is_some() => 1,
316 FieldType::Bool
317 | FieldType::Nat8
318 | FieldType::Int8
319 | FieldType::Principal
320 | FieldType::Decimal { .. } => 1,
321 FieldType::Nat16 | FieldType::Int16 | FieldType::Text { .. } | FieldType::Blob { .. } => 2,
322 FieldType::Nat32 | FieldType::Int32 | FieldType::Float32 | FieldType::Date => 4,
323 FieldType::Nat64
324 | FieldType::Int64
325 | FieldType::Float64
326 | FieldType::Timestamp
327 | FieldType::Duration => 8,
328 FieldType::Nat128 | FieldType::Int128 | FieldType::Ulid => 16,
329 FieldType::U256 | FieldType::Subaccount => 32,
330 FieldType::Account => 33,
331 _ => return Err(Error::InvalidOperand),
332 })
333}
334
335#[doc(hidden)]
337#[must_use]
338pub fn encode_index(values: &[(IndexValue<'_>, bool)], present_only: bool) -> Option<Vec<u8>> {
339 if present_only && values.iter().any(|(value, _)| *value == IndexValue::Absent) {
340 return None;
341 }
342 let mut bytes = Vec::new();
343 for &(value, optional) in values {
344 value.append_component(optional, &mut bytes);
345 }
346
347 Some(bytes)
348}
349
350#[doc(hidden)]
354pub trait MemberPresence<'a> {
355 type Scalar: 'a;
356 fn __ic_db_member_presence(self) -> (Option<&'a Self::Scalar>, bool);
357}
358
359impl<'a, T> MemberPresence<'a> for &'a Option<T> {
360 type Scalar = T;
361 fn __ic_db_member_presence(self) -> (Option<&'a T>, bool) {
362 (self.as_ref(), true)
363 }
364}
365
366impl<'a, T> MemberPresence<'a> for &&'a T {
367 type Scalar = T;
368 fn __ic_db_member_presence(self) -> (Option<&'a T>, bool) {
369 (Some(*self), false)
370 }
371}
372
373#[doc(hidden)]
376pub trait MemberOperand<'a> {
377 fn __ic_db_member_operand(self) -> IndexValue<'a>;
378}
379
380impl<'a, T: Into<IndexValue<'a>>> MemberOperand<'a> for T {
381 fn __ic_db_member_operand(self) -> IndexValue<'a> {
382 self.into()
383 }
384}
385
386impl<'a, T: Into<IndexValue<'a>>> From<Option<T>> for IndexValue<'a> {
387 fn from(value: Option<T>) -> Self {
388 value.map_or(Self::Absent, Into::into)
389 }
390}
391
392macro_rules! integer_operands {
394 ($($variant:ident($integer:ty)),+ $(,)?) => {
395 $(
396 impl From<$integer> for IndexValue<'_> {
397 fn from(value: $integer) -> Self {
398 Self::$variant(value)
399 }
400 }
401 )+
402
403 impl IndexValue<'_> {
404 fn integer_successor(self) -> Option<Self> {
405 match self {
406 $(Self::$variant(n) => n.checked_add(<$integer>::from(true)).map(Self::$variant),)+
407 _ => None,
408 }
409 }
410
411 pub(crate) fn is_integer_extreme(self, upper: bool) -> bool {
412 match self {
413 $(Self::$variant(n) => n == if upper { <$integer>::MAX } else { <$integer>::MIN },)+
414 _ => false,
415 }
416 }
417 }
418 };
419}
420
421integer_operands!(
422 Nat8(u8),
423 Nat16(u16),
424 Nat32(u32),
425 Nat64(u64),
426 Nat128(u128),
427 U256(U256),
428 Int8(i8),
429 Int16(i16),
430 Int32(i32),
431 Int64(i64),
432 Int128(i128),
433);
434
435impl From<Principal> for IndexValue<'_> {
436 fn from(value: Principal) -> Self {
437 Self::Principal(value)
438 }
439}
440
441impl From<Ulid> for IndexValue<'_> {
442 fn from(value: Ulid) -> Self {
443 Self::Ulid(value)
444 }
445}
446
447impl From<Timestamp> for IndexValue<'_> {
448 fn from(value: Timestamp) -> Self {
449 Self::Timestamp(value)
450 }
451}
452
453impl From<Decimal> for IndexValue<'_> {
454 fn from(value: Decimal) -> Self {
455 Self::Decimal(value)
456 }
457}
458
459impl From<Duration> for IndexValue<'_> {
460 fn from(value: Duration) -> Self {
461 Self::Duration(value)
462 }
463}
464
465impl From<Date> for IndexValue<'_> {
466 fn from(value: Date) -> Self {
467 Self::Date(value)
468 }
469}
470
471impl From<Float32> for IndexValue<'_> {
472 fn from(value: Float32) -> Self {
473 Self::Float32(value)
474 }
475}
476
477impl From<Float64> for IndexValue<'_> {
478 fn from(value: Float64) -> Self {
479 Self::Float64(value)
480 }
481}
482
483impl From<Subaccount> for IndexValue<'_> {
484 fn from(value: Subaccount) -> Self {
485 Self::Subaccount(value)
486 }
487}
488
489impl From<Account> for IndexValue<'_> {
490 fn from(value: Account) -> Self {
491 Self::Account(value)
492 }
493}
494
495pub(crate) fn fixed_width(field: FieldType) -> Option<usize> {
497 match field {
498 FieldType::Named(link) if unit_enum_len((link.definition)()).is_some() => Some(1),
499 FieldType::Nat8 | FieldType::Int8 | FieldType::Bool => Some(1),
500 FieldType::Nat16 | FieldType::Int16 => Some(2),
501 FieldType::Nat32 | FieldType::Int32 | FieldType::Float32 | FieldType::Date => Some(4),
502 FieldType::Nat64
503 | FieldType::Int64
504 | FieldType::Float64
505 | FieldType::Timestamp
506 | FieldType::Duration => Some(8),
507 FieldType::Nat128 | FieldType::Int128 | FieldType::Ulid => Some(16),
508 FieldType::U256 | FieldType::Subaccount => Some(32),
509 _ => None,
510 }
511}
512
513pub(crate) fn is_fixed_extreme(field: FieldType, bytes: &[u8], upper: bool) -> bool {
515 match operand_type(field) {
516 FieldType::Bool => bytes == [u8::from(upper)],
517 FieldType::Named(link) => unit_enum_len((link.definition)())
518 .is_some_and(|len| bytes == [if upper { (len - 1) as u8 } else { 0 }]),
519 scalar => {
520 fixed_width(scalar) == Some(bytes.len())
521 && bytes.iter().all(|&b| b == if upper { u8::MAX } else { 0 })
522 }
523 }
524}
525
526pub(crate) fn supports(field: FieldType) -> bool {
527 let field = operand_type(field);
528
529 fixed_width(field).is_some()
530 || matches!(
531 field,
532 FieldType::Principal
533 | FieldType::Account
534 | FieldType::Text { .. }
535 | FieldType::Blob { .. }
536 | FieldType::Decimal { .. }
537 )
538}
539
540pub(crate) fn consume_component(
542 bytes: &mut &[u8],
543 field: crate::ValueSchema,
544 present_only: bool,
545 invalid_presence: Error,
546) -> Result<(), Error> {
547 if field.optional {
548 match *bytes {
549 [0, rest @ ..] if !present_only => {
550 *bytes = rest;
551
552 return Ok(());
553 }
554 [1, rest @ ..] => *bytes = rest,
555 _ => return Err(invalid_presence),
556 }
557 }
558
559 consume(bytes, field.value)
560}
561
562pub(crate) fn consume(bytes: &mut &[u8], field: FieldType) -> Result<(), Error> {
564 let rule = field.newtype_rule();
565 let field = operand_type(field);
566 if let FieldType::Named(link) = field {
567 let len = unit_enum_len((link.definition)()).ok_or(Error::Corrupt)?;
568 let (&ordinal, rest) = bytes.split_first().ok_or(Error::Corrupt)?;
569 if usize::from(ordinal) >= len {
570 return Err(Error::Corrupt);
571 }
572 *bytes = rest;
573
574 return Ok(());
575 }
576 if let FieldType::Decimal { scale } = field {
577 let (value, width) = Decimal::read_ordered(bytes).ok_or(Error::Corrupt)?;
578 value.coefficient_at_scale(scale).ok_or(Error::Corrupt)?;
579 *bytes = &bytes[width..];
580
581 return Ok(());
582 }
583 if let FieldType::Text { max_bytes } | FieldType::Blob { max_bytes } = field {
584 let mut decoded = 0;
585 let mut checked = rule.and_then(crate::NewtypeRule::text_check);
586
587 loop {
588 let end = bytes
589 .iter()
590 .position(|&byte| byte == 0)
591 .ok_or(Error::Corrupt)?;
592 if matches!(field, FieldType::Text { .. }) {
593 let segment = std::str::from_utf8(&bytes[..end]).map_err(|_| Error::Corrupt)?;
594 if let Some(check) = &mut checked {
595 check.segment(segment).map_err(|_| Error::Corrupt)?;
596 }
597 }
598 decoded += end;
599 let escaped = *bytes.get(end + 1).ok_or(Error::Corrupt)?;
600 *bytes = &bytes[end + 2..];
601 match escaped {
602 0 if decoded <= max_bytes as usize => {
603 if let Some(check) = checked {
604 check.finish().map_err(|_| Error::Corrupt)?;
605 }
606 return Ok(());
607 }
608 255 => {
609 decoded += 1;
610 if let Some(check) = &mut checked {
611 check.segment("\0").map_err(|_| Error::Corrupt)?;
612 }
613 }
614 _ => return Err(Error::Corrupt),
615 }
616 if decoded > max_bytes as usize {
617 return Err(Error::Corrupt);
618 }
619 }
620 }
621 if field == FieldType::Bool && !matches!(bytes.first(), Some(0 | 1)) {
622 return Err(Error::Corrupt);
623 }
624 let width = if matches!(field, FieldType::Principal | FieldType::Account) {
625 let (&len, _) = bytes.split_first().ok_or(Error::Corrupt)?;
626 if usize::from(len) > crate::codec::MAX_PRINCIPAL_BYTES {
627 return Err(Error::Corrupt);
628 }
629
630 usize::from(len) + 1 + if field == FieldType::Account { 32 } else { 0 }
631 } else {
632 fixed_width(field).ok_or(Error::Corrupt)?
633 };
634 let component = bytes.get(..width).ok_or(Error::Corrupt)?;
635 if let Some(crate::NewtypeRule::NonAnonymous) = rule {
636 let principal = Principal::try_from_slice(&component[1..]).map_err(|_| Error::Corrupt)?;
637 crate::NonAnonymousPrincipal::try_from(principal).map_err(|_| Error::Corrupt)?;
638 }
639 match field {
640 FieldType::Date => {
641 let mut encoded: [u8; 4] = component.try_into().map_err(|_| Error::Corrupt)?;
642 encoded[0] ^= 0x80;
643 Date::try_from_days_since_epoch(i32::from_be_bytes(encoded)).ok_or(Error::Corrupt)?;
644 }
645 FieldType::Float32 => {
646 Float32::from_ordered_bytes(component.try_into().map_err(|_| Error::Corrupt)?)
647 .ok_or(Error::Corrupt)?;
648 }
649 FieldType::Float64 => {
650 Float64::from_ordered_bytes(component.try_into().map_err(|_| Error::Corrupt)?)
651 .ok_or(Error::Corrupt)?;
652 }
653 _ => {}
654 }
655 *bytes = &bytes[width..];
656
657 Ok(())
658}
659
660impl From<bool> for IndexValue<'_> {
661 fn from(value: bool) -> Self {
662 Self::Bool(value)
663 }
664}
665impl<'a> From<&'a str> for IndexValue<'a> {
666 fn from(value: &'a str) -> Self {
667 Self::Text(value)
668 }
669}
670
671impl<'a> From<&'a String> for IndexValue<'a> {
672 fn from(value: &'a String) -> Self {
673 Self::Text(value)
674 }
675}
676
677impl<'a> From<&'a Vec<u8>> for IndexValue<'a> {
678 fn from(value: &'a Vec<u8>) -> Self {
679 Self::Blob(value)
680 }
681}
682
683impl<'a, const N: usize> From<&'a [u8; N]> for IndexValue<'a> {
684 fn from(value: &'a [u8; N]) -> Self {
685 Self::Blob(value)
686 }
687}
688
689impl<'a> From<&'a [u8]> for IndexValue<'a> {
690 fn from(value: &'a [u8]) -> Self {
691 Self::Blob(value)
692 }
693}
694
695pub(crate) fn empty_bytes_component(optional: bool) -> &'static [u8] {
698 const PRESENT_EMPTY: &[u8] = &[1, 0, 0];
699 if optional {
700 PRESENT_EMPTY
701 } else {
702 &PRESENT_EMPTY[1..]
703 }
704}
705
706pub(crate) fn bytes_prefix(component: &[u8]) -> Option<&[u8]> {
708 component.strip_suffix(empty_bytes_component(false))
709}
710
711fn append_bytes(value: &[u8], out: &mut Vec<u8>) {
714 for &byte in value {
715 out.push(byte);
716 if byte == 0 {
717 out.push(255);
718 }
719 }
720 out.extend_from_slice(empty_bytes_component(false));
721}