cido 0.2.0

Core traits and implementations for indexing with cido
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
use crate::stable_hash;
use bigdecimal::BigDecimal as BD;
pub use inner::BigDecimal;
use num_traits::{FromPrimitive, One, ToPrimitive, Zero};

use super::{BigInt, Sign};

mod inner {
  use super::super::BigInt;
  use super::*;

  /// BigDecimal wrapper that caps precision after every computation
  ///
  /// Capping precision is required to ensure that computations over time are stable and repeatable
  #[repr(transparent)]
  #[derive(
    Eq, PartialEq, PartialOrd, Ord, Clone, Hash, Default, serde::Serialize, serde::Deserialize,
  )]
  #[serde(transparent)]
  pub struct BigDecimal(BD);

  impl BigDecimal {
    pub fn new_with_scale(big_int: BigInt, scale: i64) -> Self {
      Self::new(BD::new(big_int.into_inner(), scale))
    }

    pub fn new_with_exp(big_int: BigInt, exp: i64) -> Self {
      // bigdecimal uses `scale` as the opposite of the power of ten, so negate `exp`.
      Self::new_with_scale(big_int, -exp)
    }

    pub fn new(mut inner: BD) -> Self {
      if inner.is_zero() {
        return Self(BD::zero());
      }

      // TODO: figure out a more deterministic way to do this
      for _ in 0..2 {
        let big_decimal = inner.with_prec(Self::MAX_SIGNIFICANT_DIGITS);
        let (bigint, exp) = big_decimal.into_bigint_and_exponent();
        let (sign, mut digits) = bigint.to_radix_be(10);
        let trailing_count = digits.iter().rev().take_while(|i| **i == 0).count();
        digits.truncate(digits.len() - trailing_count);
        let int_val = num_bigint::BigInt::from_radix_be(sign, &digits, 10).unwrap();
        let scale = exp - trailing_count as i64;
        inner = BD::new(int_val, scale);
      }
      Self(inner)
    }

    #[inline(always)]
    pub(crate) fn into_inner(self) -> BD {
      self.0
    }

    #[inline(always)]
    pub(crate) fn as_inner(&self) -> &BD {
      &self.0
    }

    #[inline(always)]
    pub(super) fn as_mut_inner(&mut self) -> MutInner<'_> {
      MutInner(self, false)
    }
  }
  pub struct MutInner<'a>(&'a mut BigDecimal, bool);
  impl<'a> Drop for MutInner<'a> {
    fn drop(&mut self) {
      if self.1 {
        *self.0 = BigDecimal::new(std::mem::take(self.0).into_inner());
      }
    }
  }
  impl<'a> core::ops::Deref for MutInner<'a> {
    type Target = BD;

    fn deref(&self) -> &Self::Target {
      &self.0.0
    }
  }
  impl<'a> core::ops::DerefMut for MutInner<'a> {
    fn deref_mut(&mut self) -> &mut Self::Target {
      self.1 = true;
      &mut self.0.0
    }
  }
}

impl BigDecimal {
  const MAX_SIGNIFICANT_DIGITS: u64 = 34;

  pub fn zero() -> Self {
    Self::new(BD::zero())
  }

  pub fn one() -> Self {
    Self::new(BD::one())
  }
}

impl BigDecimal {
  pub fn abs(&self) -> Self {
    Self::new(self.as_inner().abs())
  }
  pub fn sign(&self) -> Sign {
    self.as_inner().sign().into()
  }
  pub fn digits(&self) -> u64 {
    self.as_inner().digits()
  }
  pub fn as_bigint_and_exponent(&self) -> (BigInt, i64) {
    let (bi, exp) = self.as_inner().as_bigint_and_exponent();
    (bi.into(), exp)
  }
  pub fn into_bigint_and_exponent(self) -> (BigInt, i64) {
    let (bi, exp) = self.into_inner().into_bigint_and_exponent();
    (bi.into(), exp)
  }
  pub fn sqrt(&self) -> Option<Self> {
    self.as_inner().sqrt().map(Self::new)
  }
  pub fn half(&self) -> Self {
    Self::new(self.as_inner().half())
  }
  pub fn double(&self) -> Self {
    Self::new(self.as_inner().double())
  }
}

impl From<BD> for BigDecimal {
  fn from(value: BD) -> Self {
    Self::new(value)
  }
}
impl From<&BD> for BigDecimal {
  fn from(value: &BD) -> Self {
    Self::from(value.clone())
  }
}
impl From<BigInt> for BigDecimal {
  fn from(value: BigInt) -> Self {
    Self::new(BD::from(value.into_inner()))
  }
}
impl From<&BigInt> for BigDecimal {
  fn from(value: &BigInt) -> Self {
    Self::from(value.clone())
  }
}

impl From<num_bigint::BigInt> for BigDecimal {
  fn from(value: num_bigint::BigInt) -> Self {
    Self::new(BD::from(value))
  }
}
impl From<&num_bigint::BigInt> for BigDecimal {
  fn from(value: &num_bigint::BigInt) -> Self {
    Self::from(value.clone())
  }
}

impl From<&BigDecimal> for BigDecimal {
  fn from(value: &BigDecimal) -> Self {
    value.clone()
  }
}

macro_rules! impl_from {
  ($ty:ty) => {
    impl From<$ty> for BigDecimal {
      fn from(t: $ty) -> Self {
        Self::new(BD::from(t))
      }
    }
  };
}

impl_from!(u8);
impl_from!(u16);
impl_from!(u32);
impl_from!(u64);
impl_from!(u128);
impl_from!(i8);
impl_from!(i16);
impl_from!(i32);
impl_from!(i64);
impl_from!(i128);

impl TryFrom<f64> for BigDecimal {
  type Error = <BD as TryFrom<f64>>::Error;
  fn try_from(value: f64) -> Result<Self, Self::Error> {
    BD::try_from(value).map(Self::new)
  }
}

impl TryFrom<f32> for BigDecimal {
  type Error = <BD as TryFrom<f32>>::Error;
  fn try_from(value: f32) -> Result<Self, Self::Error> {
    BD::try_from(value).map(Self::new)
  }
}

impl<'x> std::ops::Add for &'x BigDecimal {
  type Output = BigDecimal;
  fn add(self, rhs: &'x BigDecimal) -> Self::Output {
    BigDecimal::new(self.as_inner() + rhs.as_inner())
  }
}

impl<'x> std::ops::Add<BigDecimal> for &'x BigDecimal {
  type Output = BigDecimal;
  fn add(self, rhs: BigDecimal) -> Self::Output {
    BigDecimal::new(self.as_inner() + rhs.into_inner())
  }
}

impl<T: Into<BigDecimal>> std::ops::Add<T> for BigDecimal {
  type Output = BigDecimal;
  fn add(self, rhs: T) -> Self::Output {
    Self::new(self.into_inner() + rhs.into().into_inner())
  }
}

impl<T: Into<BigDecimal>> std::ops::AddAssign<T> for BigDecimal {
  fn add_assign(&mut self, rhs: T) {
    *self.as_mut_inner() += rhs.into().into_inner();
  }
}

impl<'x> std::ops::Sub for &'x BigDecimal {
  type Output = BigDecimal;
  fn sub(self, rhs: &'x BigDecimal) -> Self::Output {
    BigDecimal::new(self.as_inner() - rhs.as_inner())
  }
}

impl<'x> std::ops::Sub<BigDecimal> for &'x BigDecimal {
  type Output = BigDecimal;
  fn sub(self, rhs: BigDecimal) -> Self::Output {
    BigDecimal::new(self.as_inner() - rhs.into_inner())
  }
}

impl<T: Into<BigDecimal>> std::ops::Sub<T> for BigDecimal {
  type Output = BigDecimal;
  fn sub(self, rhs: T) -> Self::Output {
    Self::new(self.into_inner() - rhs.into().into_inner())
  }
}

impl<T: Into<BigDecimal>> std::ops::SubAssign<T> for BigDecimal {
  fn sub_assign(&mut self, rhs: T) {
    *self.as_mut_inner() -= rhs.into().into_inner();
  }
}

impl<'x> std::ops::Mul for &'x BigDecimal {
  type Output = BigDecimal;
  fn mul(self, rhs: &'x BigDecimal) -> Self::Output {
    BigDecimal::new(self.as_inner() * rhs.as_inner())
  }
}

impl<'x> std::ops::Mul<BigDecimal> for &'x BigDecimal {
  type Output = BigDecimal;
  fn mul(self, rhs: BigDecimal) -> Self::Output {
    BigDecimal::new(self.as_inner() * rhs.into_inner())
  }
}

impl<T: Into<BigDecimal>> std::ops::Mul<T> for BigDecimal {
  type Output = BigDecimal;
  fn mul(self, rhs: T) -> Self::Output {
    Self::new(self.into_inner() * rhs.into().into_inner())
  }
}

impl<T: Into<BigDecimal>> std::ops::MulAssign<T> for BigDecimal {
  fn mul_assign(&mut self, rhs: T) {
    *self.as_mut_inner() *= rhs.into().into_inner();
  }
}

impl<'x> std::ops::Div for &'x BigDecimal {
  type Output = BigDecimal;
  fn div(self, rhs: &'x BigDecimal) -> Self::Output {
    BigDecimal::new(self.as_inner() / rhs.as_inner())
  }
}

impl<'x> std::ops::Div<BigDecimal> for &'x BigDecimal {
  type Output = BigDecimal;
  fn div(self, rhs: BigDecimal) -> Self::Output {
    BigDecimal::new(self.as_inner() / rhs.into_inner())
  }
}

impl<T: Into<BigDecimal>> std::ops::Div<T> for BigDecimal {
  type Output = BigDecimal;
  fn div(self, rhs: T) -> Self::Output {
    Self::new(self.into_inner() / rhs.into().into_inner())
  }
}

impl<T: Into<BigDecimal>> std::ops::DivAssign<T> for BigDecimal {
  fn div_assign(&mut self, rhs: T) {
    Self::new(self.as_inner() / rhs.into().into_inner());
  }
}

impl std::ops::Neg for BigDecimal {
  type Output = BigDecimal;

  fn neg(self) -> Self::Output {
    Self::new(self.into_inner().neg())
  }
}

impl One for BigDecimal {
  fn one() -> Self {
    Self::new(BD::one())
  }
}

impl Zero for BigDecimal {
  fn zero() -> Self {
    Self::new(BD::zero())
  }

  fn is_zero(&self) -> bool {
    self.as_inner().is_zero()
  }
}

impl ToPrimitive for BigDecimal {
  fn to_i64(&self) -> Option<i64> {
    self.as_inner().to_i64()
  }

  fn to_u64(&self) -> Option<u64> {
    self.as_inner().to_u64()
  }

  fn to_isize(&self) -> Option<isize> {
    self.as_inner().to_isize()
  }

  fn to_i8(&self) -> Option<i8> {
    self.as_inner().to_i8()
  }

  fn to_i16(&self) -> Option<i16> {
    self.as_inner().to_i16()
  }

  fn to_i32(&self) -> Option<i32> {
    self.as_inner().to_i32()
  }

  fn to_i128(&self) -> Option<i128> {
    self.as_inner().to_i128()
  }

  fn to_usize(&self) -> Option<usize> {
    self.as_inner().to_usize()
  }

  fn to_u8(&self) -> Option<u8> {
    self.as_inner().to_u8()
  }

  fn to_u16(&self) -> Option<u16> {
    self.as_inner().to_u16()
  }

  fn to_u32(&self) -> Option<u32> {
    self.as_inner().to_u32()
  }

  fn to_u128(&self) -> Option<u128> {
    self.as_inner().to_u128()
  }

  fn to_f32(&self) -> Option<f32> {
    self.as_inner().to_f32()
  }

  fn to_f64(&self) -> Option<f64> {
    self.as_inner().to_f64()
  }
}

impl FromPrimitive for BigDecimal {
  fn from_i64(n: i64) -> Option<Self> {
    BD::from_i64(n).map(Self::new)
  }

  fn from_u64(n: u64) -> Option<Self> {
    BD::from_u64(n).map(Self::new)
  }

  fn from_isize(n: isize) -> Option<Self> {
    BD::from_isize(n).map(Self::new)
  }

  fn from_i8(n: i8) -> Option<Self> {
    BD::from_i8(n).map(Self::new)
  }

  fn from_i16(n: i16) -> Option<Self> {
    BD::from_i16(n).map(Self::new)
  }

  fn from_i32(n: i32) -> Option<Self> {
    BD::from_i32(n).map(Self::new)
  }

  fn from_i128(n: i128) -> Option<Self> {
    BD::from_i128(n).map(Self::new)
  }

  fn from_usize(n: usize) -> Option<Self> {
    BD::from_usize(n).map(Self::new)
  }

  fn from_u8(n: u8) -> Option<Self> {
    BD::from_u8(n).map(Self::new)
  }

  fn from_u16(n: u16) -> Option<Self> {
    BD::from_u16(n).map(Self::new)
  }

  fn from_u32(n: u32) -> Option<Self> {
    BD::from_u32(n).map(Self::new)
  }

  fn from_u128(n: u128) -> Option<Self> {
    BD::from_u128(n).map(Self::new)
  }

  fn from_f32(n: f32) -> Option<Self> {
    BD::from_f32(n).map(Self::new)
  }

  fn from_f64(n: f64) -> Option<Self> {
    BD::from_f64(n).map(Self::new)
  }
}

impl std::str::FromStr for BigDecimal {
  type Err = <BD as std::str::FromStr>::Err;
  #[inline]
  fn from_str(s: &str) -> Result<BigDecimal, Self::Err> {
    BD::from_str(s).map(Self::new)
  }
}

impl core::fmt::Display for BigDecimal {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    self.as_inner().fmt(f)
  }
}

impl core::fmt::Debug for BigDecimal {
  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
    <BD as core::fmt::Display>::fmt(self.as_inner(), f)
  }
}

pub(crate) mod sql {
  use super::*;
  use sqlx::Postgres;

  impl sqlx::Type<Postgres> for BigDecimal {
    fn type_info() -> <Postgres as sqlx::Database>::TypeInfo {
      <BD as sqlx::Type<Postgres>>::type_info()
    }
  }

  impl<'q> sqlx::Encode<'q, Postgres> for BigDecimal {
    fn encode_by_ref(
      &self,
      buf: &mut <Postgres as sqlx::Database>::ArgumentBuffer<'q>,
    ) -> Result<sqlx::encode::IsNull, sqlx::error::BoxDynError> {
      self.as_inner().encode_by_ref(buf)
    }
  }

  impl<'r> sqlx::Decode<'r, Postgres> for BigDecimal {
    fn decode(value: sqlx::postgres::PgValueRef) -> Result<Self, sqlx::error::BoxDynError> {
      BD::decode(value).map(Self::new)
    }
  }

  impl sqlx::postgres::PgHasArrayType for BigDecimal {
    fn array_type_info() -> sqlx::postgres::PgTypeInfo {
      <BD as sqlx::postgres::PgHasArrayType>::array_type_info()
    }
  }
}

mod graphql {
  use super::{BD, BigDecimal};

  use async_graphql::{InputValueError, InputValueResult, Scalar, ScalarType, Value};

  #[Scalar(name = "BigDecimal")]
  impl ScalarType for BigDecimal {
    fn parse(value: Value) -> InputValueResult<Self> {
      match &value {
        Value::Number(n) => {
          if let Some(f) = n.as_f64() {
            return BD::try_from(f)
              .map_err(InputValueError::custom)
              .map(Self::new);
          }

          if let Some(f) = n.as_i64() {
            return Ok(Self::from(f));
          }

          // unwrap safe here, because we have check the other possibility
          Ok(Self::from(n.as_u64().unwrap()))
        }
        Value::String(s) => <BD as std::str::FromStr>::from_str(s)
          .map(Self::new)
          .map_err(Into::into),
        _ => Err(InputValueError::expected_type(value)),
      }
    }

    fn to_value(&self) -> Value {
      Value::String(self.as_inner().to_string())
    }
  }
}

impl stable_hash::StableHash for BigDecimal {
  fn stable_hash<H: stable_hash::StableHasher>(&self, field_address: H::Addr, state: &mut H) {
    use stable_hash::FieldAddress;
    // This implementation allows for backward compatible changes from integers (signed or unsigned)
    // when the exponent is zero.
    // let _d = stable_hash::CallDepth::new();
    // stable_hash::hash_debug!("start BigDecimal stable_hash: {self}");
    let (int, exp) = self.as_bigint_and_exponent();
    stable_hash::StableHash::stable_hash(&exp, field_address.child(1), state);
    // Normally it would be a red flag to pass field_address in after having used a child slot.
    // But, we know the implementation of StableHash for BigInt will not use child(1) and that
    // it will not in the future due to having no forward schema evolutions for ints and the
    // stability guarantee.
    //
    // For reference, ints use child(0) for the sign and write the little endian bytes to the parent slot.
    int.stable_hash(field_address, state);
    // stable_hash::hash_debug!("end BigDecimal stable_hash: {self}");
  }
}

#[cfg(test)]
mod test {
  use crate::types::BigDecimal;
  use bigdecimal::BigDecimal as BD;
  use bigdecimal::BigDecimal as BDO;

  #[test]
  fn test_mul() {
    let l = "6625.0776824274553963848109507954";
    let r = "-43.399999999999999998";
    let res: BigDecimal = l.parse::<BigDecimal>().unwrap() * r.parse::<BigDecimal>().unwrap();
    let result = l.parse::<BD>().unwrap() * r.parse::<BD>().unwrap();
    let result_old = l.parse::<BDO>().unwrap() * r.parse::<BDO>().unwrap();
    println!(
      "digits: {}, {}, {}",
      res.digits(),
      result.digits(),
      result_old.digits()
    );
    println!(
      "with_prec: {}, {}, {}",
      res,
      result.with_prec(34),
      result_old.with_prec(34),
    );
    assert_eq!(res.to_string(), result_old.with_prec(34).to_string(),);
  }

  #[test]
  fn test_price_bug() {
    let tvl0 = "69.443015385421607094";
    let tvl1 = "-6063484.465072869046808563";
    let tvl0_b = tvl0.parse::<BigDecimal>().unwrap();
    let tvl1_b = tvl1.parse::<BigDecimal>().unwrap();
    let price_b = &tvl1_b / &tvl0_b;
    let expected_price = "-87315.97312443024485924387921881404";
    assert_eq!(price_b.to_string(), expected_price);
  }
}