gel-protocol 0.9.2

Low-level protocol implementation for Gel database client. For applications, use gel-tokio. Formerly published as edgedb-protocol.
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
use std::fmt::Write;

#[cfg(feature = "num-bigint")]
mod num_bigint_interop;

#[cfg(feature = "bigdecimal")]
mod bigdecimal_interop;

/// Virtually unlimited precision integer.
///
/// See Gel [protocol documentation](https://docs.edgedb.com/database/reference/protocol/dataformats#std-bigint).
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "with-serde", derive(serde::Serialize, serde::Deserialize))]
pub struct BigInt {
    pub(crate) negative: bool,
    pub(crate) weight: i16,
    pub(crate) digits: Vec<u16>,
}

/// High-precision decimal number.
///
/// See Gel [protocol documentation](https://docs.edgedb.com/database/reference/protocol/dataformats#std-decimal).
#[derive(Clone, Debug, PartialEq)]
#[cfg_attr(feature = "with-serde", derive(serde::Serialize, serde::Deserialize))]
pub struct Decimal {
    pub(crate) negative: bool,
    pub(crate) weight: i16,
    pub(crate) decimal_digits: u16,
    pub(crate) digits: Vec<u16>,
}

impl BigInt {
    pub fn negative(&self) -> bool {
        self.negative
    }

    pub fn weight(&self) -> i16 {
        self.weight
    }

    pub fn digits(&self) -> &[u16] {
        &self.digits
    }

    fn normalize(mut self) -> BigInt {
        while let Some(0) = self.digits.last() {
            self.digits.pop();
        }
        while let Some(0) = self.digits.first() {
            self.digits.remove(0);
            self.weight -= 1;
        }
        self
    }

    fn trailing_zero_groups(&self) -> i16 {
        self.weight - self.digits.len() as i16 + 1
    }
}

impl std::fmt::Display for BigInt {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.negative {
            write!(f, "-")?;
        }
        if let Some(digit) = self.digits.first() {
            write!(f, "{digit}")?;
            for digit in &mut self.digits.iter().skip(1) {
                write!(f, "{digit:04}")?;
            }
            let trailing_zero_groups = self.trailing_zero_groups();
            debug_assert!(trailing_zero_groups >= 0);
            for _ in 0..trailing_zero_groups {
                write!(f, "0000")?;
            }
        } else {
            write!(f, "0")?;
        }
        Ok(())
    }
}

impl From<u64> for BigInt {
    fn from(v: u64) -> BigInt {
        BigInt {
            negative: false,
            weight: 4,
            digits: vec![
                (v / 10_000_000_000_000_000 % 10000) as u16,
                (v / 1_000_000_000_000 % 10000) as u16,
                (v / 100_000_000 % 10000) as u16,
                (v / 10000 % 10000) as u16,
                (v % 10000) as u16,
            ],
        }
        .normalize()
    }
}

impl From<i64> for BigInt {
    fn from(v: i64) -> BigInt {
        let (abs, negative) = if v < 0 {
            (u64::MAX - v as u64 + 1, true)
        } else {
            (v as u64, false)
        };
        BigInt {
            negative,
            weight: 4,
            digits: vec![
                (abs / 10_000_000_000_000_000 % 10000) as u16,
                (abs / 1_000_000_000_000 % 10000) as u16,
                (abs / 100_000_000 % 10000) as u16,
                (abs / 10000 % 10000) as u16,
                (abs % 10000) as u16,
            ],
        }
        .normalize()
    }
}

impl From<u32> for BigInt {
    fn from(v: u32) -> BigInt {
        BigInt {
            negative: false,
            weight: 2,
            digits: vec![
                (v / 100_000_000) as u16,
                (v / 10000 % 10000) as u16,
                (v % 10000) as u16,
            ],
        }
        .normalize()
    }
}

impl From<i32> for BigInt {
    fn from(v: i32) -> BigInt {
        let (abs, negative) = if v < 0 {
            (u32::MAX - v as u32 + 1, true)
        } else {
            (v as u32, false)
        };
        BigInt {
            negative,
            weight: 2,
            digits: vec![
                (abs / 100_000_000) as u16,
                (abs / 10000 % 10000) as u16,
                (abs % 10000) as u16,
            ],
        }
        .normalize()
    }
}

impl Decimal {
    pub fn negative(&self) -> bool {
        self.negative
    }

    pub fn weight(&self) -> i16 {
        self.weight
    }

    pub fn decimal_digits(&self) -> u16 {
        self.decimal_digits
    }

    pub fn digits(&self) -> &[u16] {
        &self.digits
    }

    #[allow(dead_code)] // isn't used when BigDecimal is disabled
    fn normalize(mut self) -> Decimal {
        while let Some(0) = self.digits.last() {
            self.digits.pop();
        }
        while let Some(0) = self.digits.first() {
            self.digits.remove(0);
            self.weight -= 1;
        }
        self
    }
}

impl std::fmt::Display for Decimal {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        if self.negative {
            write!(f, "-")?;
        }

        let mut index = 0;

        // integer part
        while self.weight - index >= 0 {
            if let Some(digit) = self.digits.get(index as usize) {
                if index == 0 {
                    write!(f, "{digit}")?;
                } else {
                    write!(f, "{digit:04}")?;
                }
                index += 1;
            } else {
                break;
            }
        }

        // trailing zeros of the integer part
        for _ in 0..(self.weight - index + 1) {
            f.write_str("0000")?;
        }

        if index == 0 {
            write!(f, "0")?;
        }

        // dot
        write!(f, ".")?;

        // leading zeros of the decimal part
        let mut decimals = u16::max(self.decimal_digits, 1);
        if index == 0 && self.weight < 0 {
            for _ in 0..(-1 - self.weight) {
                f.write_str("0000")?;
                decimals -= 4;
            }
        }

        while decimals > 0 {
            if let Some(digit) = self.digits.get(index as usize) {
                let digit = format!("{digit:04}");
                let consumed = u16::min(4, decimals);
                f.write_str(&digit[0..consumed as usize])?;
                decimals -= consumed;
                index += 1;
            } else {
                break;
            }
        }
        // trailing zeros
        for _ in 0..decimals {
            f.write_char('0')?;
        }
        Ok(())
    }
}

#[cfg(test)]
#[allow(dead_code)] // used by optional tests
mod test_helpers {
    use rand::Rng;

    pub fn gen_u64<T: Rng>(rng: &mut T) -> u64 {
        // change distribution to generate different length more frequently
        let max = 10_u64.pow(rng.random_range(0..20));
        rng.random_range(0..max)
    }

    pub fn gen_i64<T: Rng>(rng: &mut T) -> i64 {
        // change distribution to generate different length more frequently
        let max = 10_i64.pow(rng.random_range(0..19));
        rng.random_range(-max..max)
    }

    pub fn gen_f64<T: Rng>(rng: &mut T) -> f64 {
        rng.random::<f64>()
    }
}

#[cfg(test)]
#[allow(unused_imports)] // because of optional tests
mod test {
    use super::{BigInt, Decimal};
    use std::convert::TryFrom;
    use std::str::FromStr;

    #[test]
    fn big_int_conversion() {
        assert_eq!(BigInt::from(125u32).weight, 0);
        assert_eq!(&BigInt::from(125u32).digits, &[125]);
        assert_eq!(BigInt::from(30000u32).weight, 1);
        assert_eq!(&BigInt::from(30000u32).digits, &[3]);
        assert_eq!(BigInt::from(30001u32).weight, 1);
        assert_eq!(&BigInt::from(30001u32).digits, &[3, 1]);
        assert_eq!(BigInt::from(u32::MAX).weight, 2);
        assert_eq!(BigInt::from(u32::MAX).digits, &[42, 9496, 7295]);

        assert_eq!(BigInt::from(125i32).weight, 0);
        assert_eq!(&BigInt::from(125i32).digits, &[125]);
        assert_eq!(BigInt::from(30000i32).weight, 1);
        assert_eq!(&BigInt::from(30000i32).digits, &[3]);
        assert_eq!(BigInt::from(30001i32).weight, 1);
        assert_eq!(&BigInt::from(30001i32).digits, &[3, 1]);
        assert_eq!(BigInt::from(i32::MAX).weight, 2);
        assert_eq!(BigInt::from(i32::MAX).digits, &[21, 4748, 3647]);

        assert_eq!(BigInt::from(-125i32).weight, 0);
        assert_eq!(&BigInt::from(-125i32).digits, &[125]);
        assert_eq!(BigInt::from(-30000i32).weight, 1);
        assert_eq!(&BigInt::from(-30000i32).digits, &[3]);
        assert_eq!(BigInt::from(-30001i32).weight, 1);
        assert_eq!(&BigInt::from(-30001i32).digits, &[3, 1]);
        assert_eq!(BigInt::from(i32::MIN).weight, 2);
        assert_eq!(BigInt::from(i32::MIN).digits, &[21, 4748, 3648]);

        assert_eq!(BigInt::from(125u64).weight, 0);
        assert_eq!(&BigInt::from(125u64).digits, &[125]);
        assert_eq!(BigInt::from(30000u64).weight, 1);
        assert_eq!(&BigInt::from(30000u64).digits, &[3]);
        assert_eq!(BigInt::from(30001u64).weight, 1);
        assert_eq!(&BigInt::from(30001u64).digits, &[3, 1]);
        assert_eq!(BigInt::from(u64::MAX).weight, 4);
        assert_eq!(BigInt::from(u64::MAX).digits, &[1844, 6744, 737, 955, 1615]);

        assert_eq!(BigInt::from(125i64).weight, 0);
        assert_eq!(&BigInt::from(125i64).digits, &[125]);
        assert_eq!(BigInt::from(30000i64).weight, 1);
        assert_eq!(&BigInt::from(30000i64).digits, &[3]);
        assert_eq!(BigInt::from(30001i64).weight, 1);
        assert_eq!(&BigInt::from(30001i64).digits, &[3, 1]);
        assert_eq!(BigInt::from(i64::MAX).weight, 4);
        assert_eq!(BigInt::from(i64::MAX).digits, &[922, 3372, 368, 5477, 5807]);

        assert_eq!(BigInt::from(-125i64).weight, 0);
        assert_eq!(&BigInt::from(-125i64).digits, &[125]);
        assert_eq!(BigInt::from(-30000i64).weight, 1);
        assert_eq!(&BigInt::from(-30000i64).digits, &[3]);
        assert_eq!(BigInt::from(-30001i64).weight, 1);
        assert_eq!(&BigInt::from(-30001i64).digits, &[3, 1]);
        assert_eq!(BigInt::from(i64::MIN).weight, 4);
        assert_eq!(BigInt::from(i64::MIN).digits, &[922, 3372, 368, 5477, 5808]);
    }

    #[test]
    fn bigint_display() {
        let cases = [0, 1, -1, 1_0000, -1_0000, 1_2345_6789, i64::MAX, i64::MIN];
        for i in cases.iter() {
            assert_eq!(BigInt::from(*i).to_string(), i.to_string());
        }
    }

    #[test]
    fn bigint_display_rand() {
        use rand::{rngs::StdRng, Rng, SeedableRng};
        let mut rng = StdRng::seed_from_u64(4);
        for _ in 0..1000 {
            let i = super::test_helpers::gen_i64(&mut rng);
            assert_eq!(BigInt::from(i).to_string(), i.to_string());
        }
    }

    #[test]
    fn decimal_display() {
        assert_eq!(
            Decimal {
                negative: false,
                weight: 0,
                decimal_digits: 0,
                digits: vec![42],
            }
            .to_string(),
            "42.0"
        );

        assert_eq!(
            Decimal {
                negative: false,
                weight: 0,
                decimal_digits: 10,
                digits: vec![42],
            }
            .to_string(),
            "42.0000000000"
        );

        assert_eq!(
            Decimal {
                negative: true,
                weight: 0,
                decimal_digits: 1,
                digits: vec![42],
            }
            .to_string(),
            "-42.0"
        );

        assert_eq!(
            Decimal {
                negative: false,
                weight: 1,
                decimal_digits: 10,
                digits: vec![42],
            }
            .to_string(),
            "420000.0000000000"
        );

        assert_eq!(
            Decimal {
                negative: false,
                weight: -2,
                decimal_digits: 10,
                digits: vec![42],
            }
            .to_string(),
            "0.0000004200"
        );

        assert_eq!(
            Decimal {
                negative: false,
                weight: -6,
                decimal_digits: 21,
                digits: vec![1000],
            }
            .to_string(),
            "0.000000000000000000001"
        );
    }
}