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