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
/*
 * clickhouse-native-rs — Asynchronous ClickHouse client for Rust over the native TCP protocol
 * Copyright (c) 2026 Alexander Panasenko
 *
 * Contact: alex@prod.codes
 * Author: https://prod.codes/about/
 * Project: https://github.com/alex09x/clickhouse-native-rs
 * SPDX-License-Identifier: MIT
 */

//! `Int256` and `UInt256`, the 256-bit integers of ClickHouse, which Rust has
//! no primitive type for.
//!
//! Each keeps its 32 little-endian bytes, the layout the Native format uses;
//! `#[repr(transparent)]` guarantees it, since columns are read and written as
//! raw bytes.
//! `Int256` converts from `i8` to `i128` and from `u8` to `u128`, `UInt256`
//! from `u8` to `u128`; `Int256` converts to `i128` and `UInt256` to `u128`
//! when the value fits, and each converts to the other when it fits. Both
//! convert to and from decimal text. Arithmetic is left to a big integer
//! crate of the caller's choice through `to_le_bytes` and `from_le_bytes`.

use std::{cmp::Ordering, error, fmt, str::FromStr};

use crate::types::{Marshal, SqlType, StatBuffer, Unmarshal};

/// The 64-bit words of a 256-bit integer, least significant first.
type Limbs = [u64; 4];

const SIGN_BIT: u64 = 1 << 63;

fn limbs(bytes: &[u8; 32]) -> Limbs {
    let mut limbs = [0; 4];
    for (limb, word) in limbs.iter_mut().zip(bytes.as_chunks::<8>().0) {
        *limb = u64::from_le_bytes(*word);
    }
    limbs
}

fn bytes(limbs: Limbs) -> [u8; 32] {
    let mut bytes = [0; 32];
    for (word, limb) in bytes.as_chunks_mut::<8>().0.iter_mut().zip(limbs) {
        *word = limb.to_le_bytes();
    }
    bytes
}

/// `limbs * factor + addend`, or `None` when it needs more than 256 bits.
fn mul_add(limbs: Limbs, factor: u64, addend: u64) -> Option<Limbs> {
    let mut out = [0; 4];
    let mut carry = u128::from(addend);
    for (out, limb) in out.iter_mut().zip(limbs) {
        let value = u128::from(limb) * u128::from(factor) + carry;
        *out = value as u64;
        carry = value >> 64;
    }
    (carry == 0).then_some(out)
}

/// `(limbs / divisor, limbs % divisor)`.
fn div_rem(limbs: Limbs, divisor: u64) -> (Limbs, u64) {
    let mut out = [0; 4];
    let mut rem = 0_u128;
    for i in (0..4).rev() {
        let value = (rem << 64) | u128::from(limbs[i]);
        out[i] = (value / u128::from(divisor)) as u64;
        rem = value % u128::from(divisor);
    }
    (out, rem as u64)
}

/// The two's complement negation.
fn negate(limbs: Limbs) -> Limbs {
    let mut out = [0; 4];
    let mut carry = true;
    for (out, limb) in out.iter_mut().zip(limbs) {
        let (value, overflow) = (!limb).overflowing_add(u64::from(carry));
        *out = value;
        carry = overflow;
    }
    out
}

fn compare(a: Limbs, b: Limbs) -> Ordering {
    a.iter().rev().cmp(b.iter().rev())
}

/// Writes the unsigned value `limbs` in decimal.
fn write_decimal(mut limbs: Limbs, nonnegative: bool, f: &mut fmt::Formatter) -> fmt::Result {
    const CHUNK: u64 = 10_000_000_000_000_000_000; // 10^19
                                                   // 2^256 has 78 digits: at most five chunks of 19.
    let mut chunks = [0_u64; 5];
    let mut count = 0;
    loop {
        let (quotient, rem) = div_rem(limbs, CHUNK);
        chunks[count] = rem;
        count += 1;
        limbs = quotient;
        if limbs == [0; 4] {
            break;
        }
    }
    let mut text = chunks[count - 1].to_string();
    for chunk in chunks[..count - 1].iter().rev() {
        text.push_str(&format!("{chunk:019}"));
    }
    f.pad_integral(nonnegative, "", &text)
}

/// Parses the decimal digits of an unsigned value.
fn parse_digits(digits: &str) -> Result<Limbs, Int256Error> {
    if digits.is_empty() {
        return Err(Int256Error::Empty);
    }
    let mut limbs = [0; 4];
    for byte in digits.bytes() {
        if !byte.is_ascii_digit() {
            return Err(Int256Error::InvalidDigit);
        }
        limbs = mul_add(limbs, 10, u64::from(byte - b'0')).ok_or(Int256Error::OutOfRange)?;
    }
    Ok(limbs)
}

/// Why text or a value could not become an [`Int256`] or [`UInt256`], or a
/// 256-bit value could not become a primitive integer.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub enum Int256Error {
    /// The text has no digits.
    Empty,
    /// The text has a character that is not a decimal digit.
    InvalidDigit,
    /// The value does not fit into the target type.
    OutOfRange,
}

impl fmt::Display for Int256Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str(match self {
            Int256Error::Empty => "cannot parse an integer from empty text",
            Int256Error::InvalidDigit => "invalid digit found in the integer text",
            Int256Error::OutOfRange => "the integer is out of range of the target type",
        })
    }
}

impl error::Error for Int256Error {}

/// A ClickHouse `Int256`: a signed 256-bit integer in two's complement.
///
/// ```rust
/// # use clickhouse_native_rs::types::Int256;
/// let min: Int256 = "-57896044618658097711785492504343953926634992332820282019728792003956564819968"
///     .parse()
///     .unwrap();
/// assert_eq!(min, Int256::MIN);
/// assert_eq!(Int256::from(-42_i64).to_string(), "-42");
/// assert_eq!(i128::try_from(Int256::from(i128::MIN)), Ok(i128::MIN));
/// ```
#[derive(Copy, Clone, Default, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub struct Int256([u8; 32]);

/// A ClickHouse `UInt256`: an unsigned 256-bit integer.
///
/// ```rust
/// # use clickhouse_native_rs::types::UInt256;
/// let max: UInt256 = "115792089237316195423570985008687907853269984665640564039457584007913129639935"
///     .parse()
///     .unwrap();
/// assert_eq!(max, UInt256::MAX);
/// assert_eq!(u128::try_from(UInt256::from(7_u8)), Ok(7));
/// ```
#[derive(Copy, Clone, Default, PartialEq, Eq, Hash)]
#[repr(transparent)]
pub struct UInt256([u8; 32]);

impl Int256 {
    pub const ZERO: Int256 = Int256([0; 32]);
    pub const MIN: Int256 = {
        let mut bytes = [0; 32];
        bytes[31] = 0x80;
        Int256(bytes)
    };
    pub const MAX: Int256 = {
        let mut bytes = [0xff; 32];
        bytes[31] = 0x7f;
        Int256(bytes)
    };

    /// The value of its 32 little-endian two's complement bytes.
    pub const fn from_le_bytes(bytes: [u8; 32]) -> Self {
        Int256(bytes)
    }

    /// The 32 little-endian two's complement bytes of the value.
    pub const fn to_le_bytes(self) -> [u8; 32] {
        self.0
    }

    pub const fn is_negative(&self) -> bool {
        self.0[31] & 0x80 != 0
    }

    /// The absolute value, which always fits into a `UInt256`.
    pub fn unsigned_abs(&self) -> UInt256 {
        let limbs = limbs(&self.0);
        if self.is_negative() {
            UInt256(bytes(negate(limbs)))
        } else {
            UInt256(self.0)
        }
    }
}

impl UInt256 {
    pub const ZERO: UInt256 = UInt256([0; 32]);
    pub const MIN: UInt256 = UInt256::ZERO;
    pub const MAX: UInt256 = UInt256([0xff; 32]);

    /// The value of its 32 little-endian bytes.
    pub const fn from_le_bytes(bytes: [u8; 32]) -> Self {
        UInt256(bytes)
    }

    /// The 32 little-endian bytes of the value.
    pub const fn to_le_bytes(self) -> [u8; 32] {
        self.0
    }
}

macro_rules! from_signed {
    ( $( $t:ty ),* ) => {
        $(
            impl From<$t> for Int256 {
                fn from(value: $t) -> Self {
                    let value = i128::from(value);
                    let mut bytes = [if value < 0 { 0xff } else { 0 }; 32];
                    bytes[..16].copy_from_slice(&value.to_le_bytes());
                    Int256(bytes)
                }
            }
        )*
    };
}

macro_rules! from_unsigned {
    ( $( $t:ty ),* ) => {
        $(
            impl From<$t> for Int256 {
                fn from(value: $t) -> Self {
                    Int256(UInt256::from(value).0)
                }
            }

            impl From<$t> for UInt256 {
                fn from(value: $t) -> Self {
                    let mut bytes = [0; 32];
                    bytes[..16].copy_from_slice(&u128::from(value).to_le_bytes());
                    UInt256(bytes)
                }
            }
        )*
    };
}

from_signed! { i8, i16, i32, i64, i128 }
from_unsigned! { u8, u16, u32, u64, u128 }

impl TryFrom<Int256> for i128 {
    type Error = Int256Error;

    fn try_from(value: Int256) -> Result<Self, Self::Error> {
        let mut low = [0; 16];
        low.copy_from_slice(&value.0[..16]);
        let low = i128::from_le_bytes(low);
        let sign = if low < 0 { 0xff } else { 0 };
        if value.0[16..].iter().all(|&byte| byte == sign) {
            Ok(low)
        } else {
            Err(Int256Error::OutOfRange)
        }
    }
}

impl TryFrom<UInt256> for u128 {
    type Error = Int256Error;

    fn try_from(value: UInt256) -> Result<Self, Self::Error> {
        if value.0[16..].iter().all(|&byte| byte == 0) {
            let mut low = [0; 16];
            low.copy_from_slice(&value.0[..16]);
            Ok(u128::from_le_bytes(low))
        } else {
            Err(Int256Error::OutOfRange)
        }
    }
}

impl TryFrom<UInt256> for Int256 {
    type Error = Int256Error;

    fn try_from(value: UInt256) -> Result<Self, Self::Error> {
        if value.0[31] & 0x80 == 0 {
            Ok(Int256(value.0))
        } else {
            Err(Int256Error::OutOfRange)
        }
    }
}

impl TryFrom<Int256> for UInt256 {
    type Error = Int256Error;

    fn try_from(value: Int256) -> Result<Self, Self::Error> {
        if value.is_negative() {
            Err(Int256Error::OutOfRange)
        } else {
            Ok(UInt256(value.0))
        }
    }
}

impl Ord for Int256 {
    fn cmp(&self, other: &Self) -> Ordering {
        // Flipping the sign bit orders two's complement values as unsigned.
        let (mut a, mut b) = (limbs(&self.0), limbs(&other.0));
        a[3] ^= SIGN_BIT;
        b[3] ^= SIGN_BIT;
        compare(a, b)
    }
}

impl PartialOrd for Int256 {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for UInt256 {
    fn cmp(&self, other: &Self) -> Ordering {
        compare(limbs(&self.0), limbs(&other.0))
    }
}

impl PartialOrd for UInt256 {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl fmt::Display for Int256 {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write_decimal(limbs(&self.unsigned_abs().0), !self.is_negative(), f)
    }
}

impl fmt::Display for UInt256 {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write_decimal(limbs(&self.0), true, f)
    }
}

impl fmt::Debug for Int256 {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

impl fmt::Debug for UInt256 {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

impl FromStr for Int256 {
    type Err = Int256Error;

    fn from_str(text: &str) -> Result<Self, Self::Err> {
        let (negative, digits) = match text.as_bytes().first() {
            Some(b'-') => (true, &text[1..]),
            Some(b'+') => (false, &text[1..]),
            _ => (false, text),
        };
        let magnitude = parse_digits(digits)?;
        if negative {
            // The magnitude may be 2^255 at most, the magnitude of MIN.
            let min = limbs(&Int256::MIN.0);
            if compare(magnitude, min) == Ordering::Greater {
                return Err(Int256Error::OutOfRange);
            }
            Ok(Int256(bytes(negate(magnitude))))
        } else if magnitude[3] & SIGN_BIT != 0 {
            Err(Int256Error::OutOfRange)
        } else {
            Ok(Int256(bytes(magnitude)))
        }
    }
}

impl FromStr for UInt256 {
    type Err = Int256Error;

    fn from_str(text: &str) -> Result<Self, Self::Err> {
        let digits = text.strip_prefix('+').unwrap_or(text);
        parse_digits(digits).map(|limbs| UInt256(bytes(limbs)))
    }
}

// The column storage: the bytes of a value are its Native format.
macro_rules! storage {
    ( $( $t:ident: $k:ident ),* ) => {
        $(
            impl StatBuffer for $t {
                type Buffer = [u8; 32];

                fn buffer() -> Self::Buffer {
                    [0; 32]
                }

                fn sql_type() -> SqlType {
                    SqlType::$k
                }
            }

            impl Marshal for $t {
                fn marshal(&self, scratch: &mut [u8]) {
                    scratch.copy_from_slice(&self.0);
                }
            }

            impl Unmarshal<$t> for $t {
                fn unmarshal(scratch: &[u8]) -> Self {
                    let mut bytes = [0; 32];
                    bytes.copy_from_slice(scratch);
                    $t(bytes)
                }
            }
        )*
    };
}

storage! { Int256: Int256, UInt256: UInt256 }

#[cfg(test)]
mod test {
    use super::*;

    const INT256_MIN: &str =
        "-57896044618658097711785492504343953926634992332820282019728792003956564819968";
    const INT256_MAX: &str =
        "57896044618658097711785492504343953926634992332820282019728792003956564819967";
    const UINT256_MAX: &str =
        "115792089237316195423570985008687907853269984665640564039457584007913129639935";

    #[test]
    fn test_text_round_trip() {
        for text in [
            INT256_MIN,
            INT256_MAX,
            "0",
            "-1",
            "1",
            "-170141183460469231731687303715884105729",
        ] {
            let value: Int256 = text.parse().unwrap();
            assert_eq!(value.to_string(), text);
        }
        for text in [
            UINT256_MAX,
            "0",
            "18446744073709551616",
            "10000000000000000000",
        ] {
            let value: UInt256 = text.parse().unwrap();
            assert_eq!(value.to_string(), text);
        }
        assert_eq!(INT256_MIN.parse::<Int256>(), Ok(Int256::MIN));
        assert_eq!(INT256_MAX.parse::<Int256>(), Ok(Int256::MAX));
        assert_eq!(UINT256_MAX.parse::<UInt256>(), Ok(UInt256::MAX));
        assert_eq!("+5".parse::<Int256>(), Ok(Int256::from(5)));
        assert_eq!(format!("{:>5}", Int256::from(-3)), "   -3");
    }

    #[test]
    fn test_parse_errors() {
        assert_eq!("".parse::<Int256>(), Err(Int256Error::Empty));
        assert_eq!("-".parse::<Int256>(), Err(Int256Error::Empty));
        assert_eq!("12a".parse::<UInt256>(), Err(Int256Error::InvalidDigit));
        assert_eq!("-5".parse::<UInt256>(), Err(Int256Error::InvalidDigit));
        // One past each end of the range.
        let past_min =
            "-57896044618658097711785492504343953926634992332820282019728792003956564819969";
        let past_max =
            "57896044618658097711785492504343953926634992332820282019728792003956564819968";
        let past_umax =
            "115792089237316195423570985008687907853269984665640564039457584007913129639936";
        assert_eq!(past_min.parse::<Int256>(), Err(Int256Error::OutOfRange));
        assert_eq!(past_max.parse::<Int256>(), Err(Int256Error::OutOfRange));
        assert_eq!(past_umax.parse::<UInt256>(), Err(Int256Error::OutOfRange));
    }

    #[test]
    fn test_primitive_conversions() {
        assert_eq!(Int256::from(-1_i8).to_le_bytes(), [0xff; 32]);
        assert_eq!(i128::try_from(Int256::from(i128::MIN)), Ok(i128::MIN));
        assert_eq!(i128::try_from(Int256::from(i128::MAX)), Ok(i128::MAX));
        assert_eq!(
            i128::try_from(Int256::from(u128::MAX)),
            Err(Int256Error::OutOfRange)
        );
        assert_eq!(i128::try_from(Int256::MIN), Err(Int256Error::OutOfRange));
        assert_eq!(u128::try_from(UInt256::from(u128::MAX)), Ok(u128::MAX));
        assert_eq!(u128::try_from(UInt256::MAX), Err(Int256Error::OutOfRange));
        assert_eq!(
            UInt256::try_from(Int256::from(-1)),
            Err(Int256Error::OutOfRange)
        );
        assert_eq!(Int256::try_from(UInt256::MAX), Err(Int256Error::OutOfRange));
        assert_eq!(Int256::try_from(UInt256::from(9_u8)), Ok(Int256::from(9)));
        assert_eq!(Int256::MIN.unsigned_abs().to_string(), &INT256_MIN[1..]);
    }

    #[test]
    fn test_order() {
        let mut values: Vec<Int256> = [INT256_MAX, "1", "-1", INT256_MIN, "0"]
            .iter()
            .map(|t| t.parse().unwrap())
            .collect();
        values.sort();
        let sorted: Vec<String> = values.iter().map(Int256::to_string).collect();
        assert_eq!(sorted, [INT256_MIN, "-1", "0", "1", INT256_MAX]);
        assert!(UInt256::from(1_u128 << 64) > UInt256::from(u64::MAX));
        assert!(UInt256::MAX > UInt256::from(u128::MAX));
    }
}