typed_store/
util.rs

1// Copyright (c) Mysten Labs, Inc.
2// Modifications Copyright (c) 2026 IOTA Stiftung
3// SPDX-License-Identifier: Apache-2.0
4
5use std::ops::{Bound, RangeBounds};
6
7use bincode::Options;
8use serde::Serialize;
9
10#[inline]
11pub fn be_fix_int_ser<S>(t: &S) -> Vec<u8>
12where
13    S: ?Sized + serde::Serialize,
14{
15    bincode::DefaultOptions::new()
16        .with_big_endian()
17        .with_fixint_encoding()
18        .serialize(t)
19        .expect("failed to serialize via be_fix_int_ser method")
20}
21
22pub(crate) fn iterator_bounds<K>(
23    lower_bound: Option<K>,
24    upper_bound: Option<K>,
25) -> (Option<Vec<u8>>, Option<Vec<u8>>)
26where
27    K: Serialize,
28{
29    (
30        lower_bound.map(|b| be_fix_int_ser(&b)),
31        upper_bound.map(|b| be_fix_int_ser(&b)),
32    )
33}
34
35pub(crate) fn iterator_bounds_with_range<K>(
36    range: impl RangeBounds<K>,
37) -> (Option<Vec<u8>>, Option<Vec<u8>>)
38where
39    K: Serialize,
40{
41    let iterator_lower_bound = match range.start_bound() {
42        Bound::Included(lower_bound) => {
43            // Rocksdb lower bound is inclusive by default so nothing to do
44            Some(be_fix_int_ser(&lower_bound))
45        }
46        Bound::Excluded(lower_bound) => {
47            let mut key_buf = be_fix_int_ser(&lower_bound);
48
49            // Since we want exclusive, we need to increment the key to exclude the previous
50            big_endian_saturating_add_one(&mut key_buf);
51            Some(key_buf)
52        }
53        Bound::Unbounded => None,
54    };
55    let iterator_upper_bound = match range.end_bound() {
56        Bound::Included(upper_bound) => {
57            let mut key_buf = be_fix_int_ser(&upper_bound);
58
59            // If the key is already at the limit, there's nowhere else to go, so no upper
60            // bound
61            if !is_max(&key_buf) {
62                // Since we want exclusive, we need to increment the key to get the upper bound
63                big_endian_saturating_add_one(&mut key_buf);
64                Some(key_buf)
65            } else {
66                None
67            }
68        }
69        Bound::Excluded(upper_bound) => {
70            // Rocksdb upper bound is exclusive by default so nothing to do
71            Some(be_fix_int_ser(&upper_bound))
72        }
73        Bound::Unbounded => None,
74    };
75    (iterator_lower_bound, iterator_upper_bound)
76}
77
78/// Given a vec<u8>, find the value which is one more than the vector
79/// if the vector was a big endian number.
80/// If the vector is already minimum, don't change it.
81fn big_endian_saturating_add_one(v: &mut [u8]) {
82    if is_max(v) {
83        return;
84    }
85    for i in (0..v.len()).rev() {
86        if v[i] == u8::MAX {
87            v[i] = 0;
88        } else {
89            v[i] += 1;
90            break;
91        }
92    }
93}
94
95/// Check if all the bytes in the vector are 0xFF
96fn is_max(v: &[u8]) -> bool {
97    v.iter().all(|&x| x == u8::MAX)
98}
99
100#[expect(clippy::assign_op_pattern, clippy::manual_div_ceil)]
101#[test]
102fn test_helpers() {
103    let v = vec![];
104    assert!(is_max(&v));
105
106    fn check_add(v: Vec<u8>) {
107        let mut v = v;
108        let num = Num32::from_big_endian(&v);
109        big_endian_saturating_add_one(&mut v);
110        assert!(num + 1 == Num32::from_big_endian(&v));
111    }
112
113    uint::construct_uint! {
114        // 32 byte number
115        struct Num32(4);
116    }
117
118    let mut v = vec![255; 32];
119    big_endian_saturating_add_one(&mut v);
120    assert!(Num32::MAX == Num32::from_big_endian(&v));
121
122    check_add(vec![1; 32]);
123    check_add(vec![6; 32]);
124    check_add(vec![254; 32]);
125
126    // TBD: More tests coming with randomized arrays
127}