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#[doc(hidden)]
337#[must_use]
338pub fn encode_index(values: &[(IndexValue<'_>, bool)], present_only: bool) -> Option<Vec<u8>> {
339 let mut bytes = None;
340 encode_index_into(values, present_only, &mut bytes);
341
342 bytes
343}
344
345pub(crate) fn encode_index_into(
346 values: &[(IndexValue<'_>, bool)],
347 present_only: bool,
348 slot: &mut Option<Vec<u8>>,
349) {
350 if present_only && values.iter().any(|(value, _)| *value == IndexValue::Absent) {
351 *slot = None;
352 return;
353 }
354 let bytes = slot.get_or_insert_with(Vec::new);
355 bytes.clear();
356 for &(value, optional) in values {
357 value.append_component(optional, bytes);
358 }
359}
360
361#[doc(hidden)]
365pub trait MemberPresence<'a> {
366 type Scalar: 'a;
367 fn __ic_db_member_presence(self) -> (Option<&'a Self::Scalar>, bool);
368}
369
370impl<'a, T> MemberPresence<'a> for &'a Option<T> {
371 type Scalar = T;
372 fn __ic_db_member_presence(self) -> (Option<&'a T>, bool) {
373 (self.as_ref(), true)
374 }
375}
376
377impl<'a, T> MemberPresence<'a> for &&'a T {
378 type Scalar = T;
379 fn __ic_db_member_presence(self) -> (Option<&'a T>, bool) {
380 (Some(*self), false)
381 }
382}
383
384#[doc(hidden)]
387pub trait MemberOperand<'a> {
388 fn __ic_db_member_operand(self) -> IndexValue<'a>;
389}
390
391impl<'a, T: Into<IndexValue<'a>>> MemberOperand<'a> for T {
392 fn __ic_db_member_operand(self) -> IndexValue<'a> {
393 self.into()
394 }
395}
396
397impl<'a, T: Into<IndexValue<'a>>> From<Option<T>> for IndexValue<'a> {
398 fn from(value: Option<T>) -> Self {
399 value.map_or(Self::Absent, Into::into)
400 }
401}
402
403macro_rules! integer_operands {
405 ($($variant:ident($integer:ty)),+ $(,)?) => {
406 $(
407 impl From<$integer> for IndexValue<'_> {
408 fn from(value: $integer) -> Self {
409 Self::$variant(value)
410 }
411 }
412 )+
413
414 impl IndexValue<'_> {
415 pub(crate) fn integer_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
416 match (self, other) {
417 $((Self::$variant(left), Self::$variant(right)) => Some(left.cmp(right)),)+
418 _ => None,
419 }
420 }
421
422 fn integer_successor(self) -> Option<Self> {
423 match self {
424 $(Self::$variant(n) => n.checked_add(<$integer>::from(true)).map(Self::$variant),)+
425 _ => None,
426 }
427 }
428
429 pub(crate) fn is_integer_extreme(self, upper: bool) -> bool {
430 match self {
431 $(Self::$variant(n) => n == if upper { <$integer>::MAX } else { <$integer>::MIN },)+
432 _ => false,
433 }
434 }
435 }
436 };
437}
438
439integer_operands!(
440 Nat8(u8),
441 Nat16(u16),
442 Nat32(u32),
443 Nat64(u64),
444 Nat128(u128),
445 U256(U256),
446 Int8(i8),
447 Int16(i16),
448 Int32(i32),
449 Int64(i64),
450 Int128(i128),
451);
452
453macro_rules! scalar_conversions {
454 ($($scalar:ident),+ $(,)?) => {$(
455 impl From<$scalar> for IndexValue<'_> {
456 fn from(value: $scalar) -> Self {
457 Self::$scalar(value)
458 }
459 }
460 )+};
461}
462scalar_conversions!(
463 Principal, Ulid, Timestamp, Decimal, Duration, Date, Float32, Float64, Subaccount, Account
464);
465
466pub(crate) fn fixed_width(field: FieldType) -> Option<usize> {
468 match field {
469 FieldType::Named(link) if unit_enum_len((link.definition)()).is_some() => Some(1),
470 FieldType::Nat8 | FieldType::Int8 | FieldType::Bool => Some(1),
471 FieldType::Nat16 | FieldType::Int16 => Some(2),
472 FieldType::Nat32 | FieldType::Int32 | FieldType::Float32 | FieldType::Date => Some(4),
473 FieldType::Nat64
474 | FieldType::Int64
475 | FieldType::Float64
476 | FieldType::Timestamp
477 | FieldType::Duration => Some(8),
478 FieldType::Nat128 | FieldType::Int128 | FieldType::Ulid => Some(16),
479 FieldType::U256 | FieldType::Subaccount => Some(32),
480 _ => None,
481 }
482}
483
484fn ordered_i32(value: i32) -> [u8; 4] {
485 (value ^ i32::MIN).to_be_bytes()
486}
487
488pub(crate) fn is_fixed_extreme(field: FieldType, bytes: &[u8], upper: bool) -> bool {
490 match operand_type(field) {
491 FieldType::Bool => bytes == [u8::from(upper)],
492 FieldType::Date => {
493 let date = if upper { Date::MAX } else { Date::MIN };
494 bytes == ordered_i32(date.as_days_since_epoch())
495 }
496 FieldType::Named(link) => unit_enum_len((link.definition)())
497 .is_some_and(|len| bytes == [if upper { (len - 1) as u8 } else { 0 }]),
498 scalar => {
499 fixed_width(scalar) == Some(bytes.len())
500 && bytes.iter().all(|&b| b == if upper { u8::MAX } else { 0 })
501 }
502 }
503}
504
505pub(crate) fn supports(field: FieldType) -> bool {
506 minimum_bytes(field).is_ok()
507}
508
509pub(crate) fn consume_component(
511 bytes: &mut &[u8],
512 field: crate::ValueSchema,
513 present_only: bool,
514 invalid_presence: Error,
515) -> Result<(), Error> {
516 if field.optional {
517 match *bytes {
518 [0, rest @ ..] if !present_only => {
519 *bytes = rest;
520
521 return Ok(());
522 }
523 [1, rest @ ..] => *bytes = rest,
524 _ => return Err(invalid_presence),
525 }
526 }
527
528 consume(bytes, field.value)
529}
530
531pub(crate) fn consume(bytes: &mut &[u8], field: FieldType) -> Result<(), Error> {
533 let rule = field.newtype_rule();
534 let field = operand_type(field);
535 if let FieldType::Named(link) = field {
536 let len = unit_enum_len((link.definition)()).ok_or(Error::Corrupt)?;
537 let (&ordinal, rest) = bytes.split_first().ok_or(Error::Corrupt)?;
538 if usize::from(ordinal) >= len {
539 return Err(Error::Corrupt);
540 }
541 *bytes = rest;
542
543 return Ok(());
544 }
545 if let FieldType::Decimal { scale } = field {
546 let (value, width) = Decimal::read_ordered(bytes).ok_or(Error::Corrupt)?;
547 value.coefficient_at_scale(scale).ok_or(Error::Corrupt)?;
548 *bytes = &bytes[width..];
549
550 return Ok(());
551 }
552 if let FieldType::Text { max_bytes } | FieldType::Blob { max_bytes } = field {
553 let mut decoded = 0;
554 let mut checked = rule.and_then(crate::NewtypeRule::text_check);
555
556 loop {
557 let end = bytes
558 .iter()
559 .position(|&byte| byte == 0)
560 .ok_or(Error::Corrupt)?;
561 if matches!(field, FieldType::Text { .. }) {
562 let segment = std::str::from_utf8(&bytes[..end]).map_err(|_| Error::Corrupt)?;
563 if let Some(check) = &mut checked {
564 check.segment(segment).map_err(|_| Error::Corrupt)?;
565 }
566 }
567 decoded += end;
568 let escaped = *bytes.get(end + 1).ok_or(Error::Corrupt)?;
569 *bytes = &bytes[end + 2..];
570 match escaped {
571 0 if decoded <= max_bytes as usize => {
572 if let Some(check) = checked {
573 check.finish().map_err(|_| Error::Corrupt)?;
574 }
575 return Ok(());
576 }
577 255 => {
578 decoded += 1;
579 if let Some(check) = &mut checked {
580 check.segment("\0").map_err(|_| Error::Corrupt)?;
581 }
582 }
583 _ => return Err(Error::Corrupt),
584 }
585 if decoded > max_bytes as usize {
586 return Err(Error::Corrupt);
587 }
588 }
589 }
590 if field == FieldType::Bool && !matches!(bytes.first(), Some(0 | 1)) {
591 return Err(Error::Corrupt);
592 }
593 let width = if matches!(field, FieldType::Principal | FieldType::Account) {
594 let (&len, _) = bytes.split_first().ok_or(Error::Corrupt)?;
595 if usize::from(len) > crate::codec::MAX_PRINCIPAL_BYTES {
596 return Err(Error::Corrupt);
597 }
598
599 usize::from(len) + 1 + if field == FieldType::Account { 32 } else { 0 }
600 } else {
601 fixed_width(field).ok_or(Error::Corrupt)?
602 };
603 let component = bytes.get(..width).ok_or(Error::Corrupt)?;
604 if let Some(crate::NewtypeRule::NonAnonymous) = rule {
605 let principal = Principal::try_from_slice(&component[1..]).map_err(|_| Error::Corrupt)?;
606 crate::NonAnonymousPrincipal::try_from(principal).map_err(|_| Error::Corrupt)?;
607 }
608 match field {
609 FieldType::Date => {
610 let mut encoded: [u8; 4] = component.try_into().map_err(|_| Error::Corrupt)?;
611 encoded[0] ^= 0x80;
612 Date::try_from_days_since_epoch(i32::from_be_bytes(encoded)).ok_or(Error::Corrupt)?;
613 }
614 FieldType::Float32 => {
615 Float32::from_ordered_bytes(component.try_into().map_err(|_| Error::Corrupt)?)
616 .ok_or(Error::Corrupt)?;
617 }
618 FieldType::Float64 => {
619 Float64::from_ordered_bytes(component.try_into().map_err(|_| Error::Corrupt)?)
620 .ok_or(Error::Corrupt)?;
621 }
622 _ => {}
623 }
624 *bytes = &bytes[width..];
625
626 Ok(())
627}
628
629impl From<bool> for IndexValue<'_> {
630 fn from(value: bool) -> Self {
631 Self::Bool(value)
632 }
633}
634impl<'a> From<&'a str> for IndexValue<'a> {
635 fn from(value: &'a str) -> Self {
636 Self::Text(value)
637 }
638}
639
640impl<'a> From<&'a String> for IndexValue<'a> {
641 fn from(value: &'a String) -> Self {
642 Self::Text(value)
643 }
644}
645
646impl<'a> From<&'a Vec<u8>> for IndexValue<'a> {
647 fn from(value: &'a Vec<u8>) -> Self {
648 Self::Blob(value)
649 }
650}
651
652impl<'a, const N: usize> From<&'a [u8; N]> for IndexValue<'a> {
653 fn from(value: &'a [u8; N]) -> Self {
654 Self::Blob(value)
655 }
656}
657
658impl<'a> From<&'a [u8]> for IndexValue<'a> {
659 fn from(value: &'a [u8]) -> Self {
660 Self::Blob(value)
661 }
662}
663
664pub(crate) fn empty_bytes_component(optional: bool) -> &'static [u8] {
667 const PRESENT_EMPTY: &[u8] = &[1, 0, 0];
668 if optional {
669 PRESENT_EMPTY
670 } else {
671 &PRESENT_EMPTY[1..]
672 }
673}
674
675pub(crate) fn bytes_prefix(component: &[u8]) -> Option<&[u8]> {
677 component.strip_suffix(empty_bytes_component(false))
678}
679
680fn append_bytes(value: &[u8], out: &mut Vec<u8>) {
683 for &byte in value {
684 out.push(byte);
685 if byte == 0 {
686 out.push(255);
687 }
688 }
689 out.extend_from_slice(empty_bytes_component(false));
690}