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