no_mistakes_postgres_engine/embedded/
byte_origins.rs1#[derive(Debug, Clone, PartialEq, Eq)]
6pub struct SqlByteOrigins {
7 kind: Kind,
8}
9
10#[derive(Debug, Clone, PartialEq, Eq)]
11enum Kind {
12 Empty,
13 Affine { base: u32, len: u32, step: u32 },
14 Runs(Vec<Run>),
15}
16
17#[derive(Debug, Clone, PartialEq, Eq)]
18struct Run {
19 at: u32,
20 origin: u32,
21 len: u32,
22 step: u32,
23}
24
25impl Default for SqlByteOrigins {
26 fn default() -> Self {
27 Self { kind: Kind::Empty }
28 }
29}
30
31impl From<Vec<u32>> for SqlByteOrigins {
32 fn from(values: Vec<u32>) -> Self {
33 Self::compress(&values)
34 }
35}
36
37impl SqlByteOrigins {
38 pub fn empty() -> &'static Self {
39 static EMPTY: SqlByteOrigins = SqlByteOrigins { kind: Kind::Empty };
40 &EMPTY
41 }
42
43 pub fn get(&self, index: usize) -> Option<u32> {
44 match &self.kind {
45 Kind::Empty => None,
46 Kind::Affine { base, len, step } => (index < *len as usize)
47 .then_some(base.wrapping_add((index as u32).wrapping_mul(*step))),
48 Kind::Runs(runs) => lookup(runs, index),
49 }
50 }
51
52 pub fn at(&self, index: usize) -> u32 {
53 self.get(index)
54 .unwrap_or_else(|| panic!("sql byte origin {index} out of range"))
55 }
56
57 pub fn len(&self) -> usize {
58 match &self.kind {
59 Kind::Empty => 0,
60 Kind::Affine { len, .. } => *len as usize,
61 Kind::Runs(runs) => runs
62 .last()
63 .map(|run| run.at as usize + run.len as usize)
64 .unwrap_or(0),
65 }
66 }
67
68 pub fn is_empty(&self) -> bool {
69 self.len() == 0
70 }
71
72 pub fn clear(&mut self) {
73 *self = Self::default();
74 }
75
76 pub fn first(&self) -> Option<u32> {
77 self.get(0)
78 }
79
80 fn compress(values: &[u32]) -> Self {
81 if values.is_empty() {
82 return Self::default();
83 }
84 let mut runs = Vec::new();
85 let mut index = 0;
86 while index < values.len() {
87 let origin = values[index];
88 let (len, step) = match values.get(index + 1).copied() {
89 None => (1, 0),
90 Some(next) => {
91 let step = next.wrapping_sub(origin);
92 let mut len = 2;
93 while index + len < values.len()
94 && values[index + len].wrapping_sub(values[index + len - 1]) == step
95 {
96 len += 1;
97 }
98 (len, step)
99 }
100 };
101 runs.push(Run {
102 at: index as u32,
103 origin,
104 len: len as u32,
105 step,
106 });
107 index += len;
108 }
109 if let [run] = runs.as_slice() {
110 return Self {
111 kind: Kind::Affine {
112 base: run.origin,
113 len: run.len,
114 step: run.step,
115 },
116 };
117 }
118 Self {
119 kind: Kind::Runs(runs),
120 }
121 }
122}
123
124fn lookup(runs: &[Run], index: usize) -> Option<u32> {
125 let mut found = None;
126 for run in runs {
127 let start = run.at as usize;
128 let end = start + run.len as usize;
129 if index >= start && index < end {
130 let local = (index - start) as u32;
131 found = Some(run.origin.wrapping_add(local.wrapping_mul(run.step)));
132 break;
133 }
134 }
135 found
136}
137
138#[cfg(all(test, any(nm_shard_all, nm_shard_1)))]
139#[path = "byte_origins_tests.rs"]
140pub(crate) mod tests;