1use 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 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 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 !is_max(&key_buf) {
62 big_endian_saturating_add_one(&mut key_buf);
64 Some(key_buf)
65 } else {
66 None
67 }
68 }
69 Bound::Excluded(upper_bound) => {
70 Some(be_fix_int_ser(&upper_bound))
72 }
73 Bound::Unbounded => None,
74 };
75 (iterator_lower_bound, iterator_upper_bound)
76}
77
78fn 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
95fn 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 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 }