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 #[inline]
258 pub(crate) fn component(self, optional: bool) -> Vec<u8> {
259 let mut bytes = Vec::new();
260 self.append_component(optional, &mut bytes);
261 bytes
262 }
263
264 pub(crate) fn append_component(self, optional: bool, out: &mut Vec<u8>) {
265 if optional {
266 out.push(u8::from(self != Self::Absent));
267 }
268 self.append_to(out);
269 }
270
271 pub(crate) fn read(reader: &mut Decoder<'a>, field: FieldType) -> Result<Self, Error> {
272 if let Some(rule) = field.newtype_rule() {
273 return match rule {
274 crate::NewtypeRule::Text { .. } => Ok(Self::Text(reader.checked_text(rule)?)),
275 crate::NewtypeRule::NonAnonymous => {
276 Ok(reader.named::<crate::NonAnonymousPrincipal>()?.into())
277 }
278 };
279 }
280 Ok(match operand_type(field) {
281 FieldType::Named(link) => {
282 let definition = (link.definition)();
283 let len = unit_enum_len(definition).ok_or(Error::Corrupt)?;
284 let ordinal = reader.unit_enum(len)?;
285
286 Self::UnitEnum {
287 definition,
288 ordinal,
289 }
290 }
291 FieldType::Nat8 => Self::Nat8(reader.nat8()?),
292 FieldType::Nat16 => Self::Nat16(reader.nat16()?),
293 FieldType::Nat32 => Self::Nat32(reader.nat32()?),
294 FieldType::Nat64 => Self::Nat64(reader.nat64()?),
295 FieldType::Nat128 => Self::Nat128(reader.nat128()?),
296 FieldType::Float32 => Self::Float32(reader.float32()?),
297 FieldType::Float64 => Self::Float64(reader.float64()?),
298 FieldType::Subaccount => Self::Subaccount(reader.subaccount()?),
299 FieldType::Account => Self::Account(reader.account()?),
300 FieldType::U256 => Self::U256(reader.u256()?),
301 FieldType::Ulid => Self::Ulid(reader.ulid()?),
302 FieldType::Date => Self::Date(reader.date()?),
303 FieldType::Decimal { scale } => Self::Decimal(reader.decimal(scale)?),
304 FieldType::Duration => Self::Duration(reader.duration()?),
305 FieldType::Timestamp => Self::Timestamp(reader.timestamp()?),
306 FieldType::Int8 => Self::Int8(reader.int8()?),
307 FieldType::Int16 => Self::Int16(reader.int16()?),
308 FieldType::Int32 => Self::Int32(reader.int32()?),
309 FieldType::Int64 => Self::Int64(reader.int64()?),
310 FieldType::Int128 => Self::Int128(reader.int128()?),
311 FieldType::Principal => Self::Principal(reader.principal()?),
312 FieldType::Bool => Self::Bool(reader.boolean()?),
313 FieldType::Text { max_bytes } => Self::Text(reader.text_ref(max_bytes as usize)?),
314 FieldType::Blob { max_bytes } => Self::Blob(reader.blob_ref(max_bytes as usize)?),
315 _ => return Err(Error::Corrupt),
316 })
317 }
318}
319
320pub(crate) fn minimum_bytes(field: FieldType) -> Result<usize, Error> {
323 let field = operand_type(field);
324 if let Some(width) = fixed_width(field) {
325 return Ok(width);
326 }
327 match field {
328 FieldType::Principal | FieldType::Decimal { .. } => Ok(1),
329 FieldType::Text { .. } | FieldType::Blob { .. } => Ok(2),
330 FieldType::Account => Ok(33),
331 _ => Err(Error::InvalidOperand),
332 }
333}
334
335#[derive(Clone, Copy)]
340pub struct IndexComponent<'a> {
341 pub value: IndexValue<'a>,
343 pub optional: bool,
345}
346
347#[doc(hidden)]
349#[must_use]
350pub fn encode_index(values: &[IndexComponent<'_>], present_only: bool) -> Option<Vec<u8>> {
351 let mut bytes = None;
352 encode_index_into(values, present_only, &mut bytes);
353
354 bytes
355}
356
357pub(crate) fn encode_index_into(
358 values: &[IndexComponent<'_>],
359 present_only: bool,
360 slot: &mut Option<Vec<u8>>,
361) {
362 if present_only
363 && values
364 .iter()
365 .any(|component| component.value == IndexValue::Absent)
366 {
367 *slot = None;
368 return;
369 }
370 let bytes = slot.get_or_insert_with(Vec::new);
371 bytes.clear();
372 for component in values {
373 component.value.append_component(component.optional, bytes);
374 }
375}
376
377#[doc(hidden)]
381pub trait MemberPresence<'a> {
382 type Scalar: 'a;
383 fn __ic_db_member_presence(self) -> (Option<&'a Self::Scalar>, bool);
384}
385
386impl<'a, T> MemberPresence<'a> for &'a Option<T> {
387 type Scalar = T;
388 fn __ic_db_member_presence(self) -> (Option<&'a T>, bool) {
389 (self.as_ref(), true)
390 }
391}
392
393impl<'a, T> MemberPresence<'a> for &&'a T {
394 type Scalar = T;
395 fn __ic_db_member_presence(self) -> (Option<&'a T>, bool) {
396 (Some(*self), false)
397 }
398}
399
400#[doc(hidden)]
403pub trait MemberOperand<'a> {
404 fn __ic_db_member_operand(self) -> IndexValue<'a>;
405}
406
407impl<'a, T: Into<IndexValue<'a>>> MemberOperand<'a> for T {
408 fn __ic_db_member_operand(self) -> IndexValue<'a> {
409 self.into()
410 }
411}
412
413impl<'a, T: Into<IndexValue<'a>>> From<Option<T>> for IndexValue<'a> {
414 fn from(value: Option<T>) -> Self {
415 value.map_or(Self::Absent, Into::into)
416 }
417}
418
419macro_rules! integer_operands {
421 ($($variant:ident($integer:ty)),+ $(,)?) => {
422 $(
423 impl From<$integer> for IndexValue<'_> {
424 fn from(value: $integer) -> Self {
425 Self::$variant(value)
426 }
427 }
428 )+
429
430 impl IndexValue<'_> {
431 pub(crate) fn integer_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
432 match (self, other) {
433 $((Self::$variant(left), Self::$variant(right)) => Some(left.cmp(right)),)+
434 _ => None,
435 }
436 }
437
438 fn integer_successor(self) -> Option<Self> {
439 match self {
440 $(Self::$variant(n) => n.checked_add(<$integer>::from(true)).map(Self::$variant),)+
441 _ => None,
442 }
443 }
444
445 pub(crate) fn is_integer_extreme(self, upper: bool) -> bool {
446 match self {
447 $(Self::$variant(n) => n == if upper { <$integer>::MAX } else { <$integer>::MIN },)+
448 _ => false,
449 }
450 }
451 }
452 };
453}
454
455integer_operands!(
456 Nat8(u8),
457 Nat16(u16),
458 Nat32(u32),
459 Nat64(u64),
460 Nat128(u128),
461 U256(U256),
462 Int8(i8),
463 Int16(i16),
464 Int32(i32),
465 Int64(i64),
466 Int128(i128),
467);
468
469macro_rules! scalar_conversions {
470 ($($scalar:ident),+ $(,)?) => {$(
471 impl From<$scalar> for IndexValue<'_> {
472 fn from(value: $scalar) -> Self {
473 Self::$scalar(value)
474 }
475 }
476 )+};
477}
478scalar_conversions!(
479 Principal, Ulid, Timestamp, Decimal, Duration, Date, Float32, Float64, Subaccount, Account
480);
481
482pub(crate) fn fixed_width(field: FieldType) -> Option<usize> {
484 match field {
485 FieldType::Named(link) if unit_enum_len((link.definition)()).is_some() => Some(1),
486 FieldType::Nat8 | FieldType::Int8 | FieldType::Bool => Some(1),
487 FieldType::Nat16 | FieldType::Int16 => Some(2),
488 FieldType::Nat32 | FieldType::Int32 | FieldType::Float32 | FieldType::Date => Some(4),
489 FieldType::Nat64
490 | FieldType::Int64
491 | FieldType::Float64
492 | FieldType::Timestamp
493 | FieldType::Duration => Some(8),
494 FieldType::Nat128 | FieldType::Int128 | FieldType::Ulid => Some(16),
495 FieldType::U256 | FieldType::Subaccount => Some(32),
496 _ => None,
497 }
498}
499
500fn ordered_i32(value: i32) -> [u8; 4] {
501 (value ^ i32::MIN).to_be_bytes()
502}
503
504pub(crate) fn is_fixed_extreme(field: FieldType, bytes: &[u8], upper: bool) -> bool {
506 match operand_type(field) {
507 FieldType::Bool => bytes == [u8::from(upper)],
508 FieldType::Date => {
509 let date = if upper { Date::MAX } else { Date::MIN };
510 bytes == ordered_i32(date.as_days_since_epoch())
511 }
512 FieldType::Named(link) => unit_enum_len((link.definition)())
513 .is_some_and(|len| bytes == [if upper { (len - 1) as u8 } else { 0 }]),
514 scalar => {
515 fixed_width(scalar) == Some(bytes.len())
516 && bytes.iter().all(|&b| b == if upper { u8::MAX } else { 0 })
517 }
518 }
519}
520
521pub(crate) fn supports(field: FieldType) -> bool {
522 minimum_bytes(field).is_ok()
523}
524
525pub(crate) fn consume_component(
527 bytes: &mut &[u8],
528 field: crate::ValueSchema,
529 present_only: bool,
530 invalid_presence: Error,
531) -> Result<(), Error> {
532 if field.optional {
533 match *bytes {
534 [0, rest @ ..] if !present_only => {
535 *bytes = rest;
536
537 return Ok(());
538 }
539 [1, rest @ ..] => *bytes = rest,
540 _ => return Err(invalid_presence),
541 }
542 }
543
544 consume(bytes, field.value)
545}
546
547pub(crate) fn consume(bytes: &mut &[u8], field: FieldType) -> Result<(), Error> {
549 let rule = field.newtype_rule();
550 let field = operand_type(field);
551 if let FieldType::Named(link) = field {
552 let len = unit_enum_len((link.definition)()).ok_or(Error::Corrupt)?;
553 let (&ordinal, rest) = bytes.split_first().ok_or(Error::Corrupt)?;
554 if usize::from(ordinal) >= len {
555 return Err(Error::Corrupt);
556 }
557 *bytes = rest;
558
559 return Ok(());
560 }
561 if let FieldType::Decimal { scale } = field {
562 let (value, width) = Decimal::read_ordered(bytes).ok_or(Error::Corrupt)?;
563 value.coefficient_at_scale(scale).ok_or(Error::Corrupt)?;
564 *bytes = &bytes[width..];
565
566 return Ok(());
567 }
568 if let FieldType::Text { max_bytes } | FieldType::Blob { max_bytes } = field {
569 let mut decoded = 0;
570 let mut checked = rule.and_then(crate::NewtypeRule::text_check);
571
572 loop {
573 let end = bytes
574 .iter()
575 .position(|&byte| byte == 0)
576 .ok_or(Error::Corrupt)?;
577 if matches!(field, FieldType::Text { .. }) {
578 let segment = std::str::from_utf8(&bytes[..end]).map_err(|_| Error::Corrupt)?;
579 if let Some(check) = &mut checked {
580 check.segment(segment).map_err(|_| Error::Corrupt)?;
581 }
582 }
583 decoded += end;
584 let escaped = *bytes.get(end + 1).ok_or(Error::Corrupt)?;
585 *bytes = &bytes[end + 2..];
586 match escaped {
587 0 if decoded <= max_bytes as usize => {
588 if let Some(check) = checked {
589 check.finish().map_err(|_| Error::Corrupt)?;
590 }
591 return Ok(());
592 }
593 255 => {
594 decoded += 1;
595 if let Some(check) = &mut checked {
596 check.segment("\0").map_err(|_| Error::Corrupt)?;
597 }
598 }
599 _ => return Err(Error::Corrupt),
600 }
601 if decoded > max_bytes as usize {
602 return Err(Error::Corrupt);
603 }
604 }
605 }
606 if field == FieldType::Bool && !matches!(bytes.first(), Some(0 | 1)) {
607 return Err(Error::Corrupt);
608 }
609 let width = if matches!(field, FieldType::Principal | FieldType::Account) {
610 let (&len, _) = bytes.split_first().ok_or(Error::Corrupt)?;
611 if usize::from(len) > crate::codec::MAX_PRINCIPAL_BYTES {
612 return Err(Error::Corrupt);
613 }
614
615 usize::from(len) + 1 + if field == FieldType::Account { 32 } else { 0 }
616 } else {
617 fixed_width(field).ok_or(Error::Corrupt)?
618 };
619 let component = bytes.get(..width).ok_or(Error::Corrupt)?;
620 if let Some(crate::NewtypeRule::NonAnonymous) = rule {
621 let principal = Principal::try_from_slice(&component[1..]).map_err(|_| Error::Corrupt)?;
622 crate::NonAnonymousPrincipal::try_from(principal).map_err(|_| Error::Corrupt)?;
623 }
624 match field {
625 FieldType::Date => {
626 let mut encoded: [u8; 4] = component.try_into().map_err(|_| Error::Corrupt)?;
627 encoded[0] ^= 0x80;
628 Date::try_from_days_since_epoch(i32::from_be_bytes(encoded)).ok_or(Error::Corrupt)?;
629 }
630 FieldType::Float32 => {
631 Float32::from_ordered_bytes(component.try_into().map_err(|_| Error::Corrupt)?)
632 .ok_or(Error::Corrupt)?;
633 }
634 FieldType::Float64 => {
635 Float64::from_ordered_bytes(component.try_into().map_err(|_| Error::Corrupt)?)
636 .ok_or(Error::Corrupt)?;
637 }
638 _ => {}
639 }
640 *bytes = &bytes[width..];
641
642 Ok(())
643}
644
645impl From<bool> for IndexValue<'_> {
646 fn from(value: bool) -> Self {
647 Self::Bool(value)
648 }
649}
650impl<'a> From<&'a str> for IndexValue<'a> {
651 fn from(value: &'a str) -> Self {
652 Self::Text(value)
653 }
654}
655
656impl<'a> From<&'a String> for IndexValue<'a> {
657 fn from(value: &'a String) -> Self {
658 Self::Text(value)
659 }
660}
661
662impl<'a> From<&'a Vec<u8>> for IndexValue<'a> {
663 fn from(value: &'a Vec<u8>) -> Self {
664 Self::Blob(value)
665 }
666}
667
668impl<'a, const N: usize> From<&'a [u8; N]> for IndexValue<'a> {
669 fn from(value: &'a [u8; N]) -> Self {
670 Self::Blob(value)
671 }
672}
673
674impl<'a> From<&'a [u8]> for IndexValue<'a> {
675 fn from(value: &'a [u8]) -> Self {
676 Self::Blob(value)
677 }
678}
679
680pub(crate) fn empty_bytes_component(optional: bool) -> &'static [u8] {
683 const PRESENT_EMPTY: &[u8] = &[1, 0, 0];
684 if optional {
685 PRESENT_EMPTY
686 } else {
687 &PRESENT_EMPTY[1..]
688 }
689}
690
691pub(crate) fn bytes_prefix(component: &[u8]) -> Option<&[u8]> {
693 component.strip_suffix(empty_bytes_component(false))
694}
695
696fn append_bytes(value: &[u8], out: &mut Vec<u8>) {
699 for &byte in value {
700 out.push(byte);
701 if byte == 0 {
702 out.push(255);
703 }
704 }
705 out.extend_from_slice(empty_bytes_component(false));
706}