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