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