1use serde_json::{json, Value};
16
17use crate::backend::storage::filestore::FileStore;
18
19pub const CONSOL: &str = "output.consol";
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub struct Run {
25 pub old_line: u64,
27 pub dropped: u64,
28 pub synthesized: u64,
30}
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub struct ByteRun {
35 pub old_at: i64,
36 pub old_len: i64,
37 pub new_len: i64,
39}
40
41#[derive(Debug, Clone, PartialEq, Eq)]
43pub struct Map {
44 pub gen_before: String,
45 pub gen_after: String,
46 pub runs: Vec<Run>,
47 pub byte_runs: Vec<ByteRun>,
48}
49
50impl Map {
51 pub fn to_json(&self) -> Value {
53 let runs: Vec<[u64; 3]> = self.runs.iter().map(|r| [r.old_line, r.dropped, r.synthesized]).collect();
54 let bytes: Vec<[i64; 3]> = self.byte_runs.iter().map(|r| [r.old_at, r.old_len, r.new_len]).collect();
55 json!({ "k": "map", "gen_before": self.gen_before, "gen_after": self.gen_after, "runs": runs, "bytes": bytes })
56 }
57
58 pub fn from_json(v: &Value) -> Option<Self> {
60 if v.get("k").and_then(Value::as_str) != Some("map") {
61 return None;
62 }
63 let triples = |key: &str| -> Option<Vec<[i64; 3]>> {
64 v.get(key)?.as_array()?.iter().map(|t| {
65 let t = t.as_array()?;
66 Some([t.first()?.as_i64()?, t.get(1)?.as_i64()?, t.get(2)?.as_i64()?])
67 }).collect()
68 };
69 Some(Self {
70 gen_before: v.get("gen_before")?.as_str()?.to_string(),
71 gen_after: v.get("gen_after")?.as_str()?.to_string(),
72 runs: triples("runs")?.into_iter().map(|[a, b, c]| Run { old_line: a as u64, dropped: b as u64, synthesized: c as u64 }).collect(),
73 byte_runs: triples("bytes").unwrap_or_default().into_iter().map(|[a, b, c]| ByteRun { old_at: a, old_len: b, new_len: c }).collect(),
74 })
75 }
76
77 pub fn line(&self, old: u64) -> u64 {
80 let mut delta: i64 = 0;
81 for r in &self.runs {
82 if r.old_line + r.dropped <= old {
83 delta += r.synthesized as i64 - r.dropped as i64;
84 } else {
85 if r.old_line < old {
86 return (r.old_line as i64 + delta).max(0) as u64;
88 }
89 break;
90 }
91 }
92 (old as i64 + delta).max(0) as u64
93 }
94
95 pub fn byte(&self, old: i64) -> i64 {
97 let mut delta: i64 = 0;
98 for r in &self.byte_runs {
99 if r.old_at + r.old_len <= old {
100 delta += r.new_len - r.old_len;
101 } else {
102 if r.old_at < old {
103 return r.old_at + delta;
104 }
105 break;
106 }
107 }
108 (old + delta).max(0)
109 }
110}
111
112pub fn maps(fs: &FileStore, zone: &str) -> Vec<Map> {
115 let Ok(Some(state)) = fs.line_state(zone, CONSOL) else { return Vec::new() };
116 let Ok(raw) = fs.read_bytes_db(zone, CONSOL, 0, state.size) else { return Vec::new() };
117 String::from_utf8_lossy(&raw).lines().filter(|l| l.contains("\"k\":\"map\"")).filter_map(|l| serde_json::from_str::<Value>(l).ok()).filter_map(|v| Map::from_json(&v)).collect()
118}
119
120pub fn chain(all: &[Map], from: &str, to: &str) -> Option<Vec<Map>> {
123 let mut out = Vec::new();
124 let mut at = from.to_string();
125 while at != to {
126 let next = all.iter().find(|m| m.gen_before == at)?;
127 at = next.gen_after.clone();
128 out.push(next.clone());
129 if out.len() > 64 {
130 return None;
131 }
132 }
133 Some(out)
134}
135
136pub fn translate_line(all: &[Map], from: &str, to: &str, line: u64) -> Option<u64> {
138 Some(chain(all, from, to)?.iter().fold(line, |l, m| m.line(l)))
139}
140
141pub fn translate_byte(all: &[Map], from: &str, to: &str, byte: i64) -> Option<i64> {
143 Some(chain(all, from, to)?.iter().fold(byte, |b, m| m.byte(b)))
144}
145
146#[cfg(test)]
147mod tests {
148 use super::*;
149
150 fn map(gen_before: &str, gen_after: &str) -> Map {
151 Map {
152 gen_before: gen_before.into(),
153 gen_after: gen_after.into(),
154 runs: vec![Run { old_line: 2, dropped: 3, synthesized: 0 }, Run { old_line: 10, dropped: 2, synthesized: 1 }],
156 byte_runs: vec![ByteRun { old_at: 20, old_len: 100, new_len: 0 }, ByteRun { old_at: 200, old_len: 40, new_len: 25 }],
158 }
159 }
160
161 #[test]
162 fn a_kept_line_moves_exactly_and_a_dropped_one_goes_to_where_its_run_began() {
163 let m = map("a", "b");
164 assert_eq!([0, 1, 2].map(|l| m.line(l)), [0, 1, 2], "before the first run");
165 assert_eq!(m.line(3), 2, "inside a run: where it began");
166 assert_eq!(m.line(4), 2);
167 assert_eq!(m.line(5), 2, "the first line after the run");
168 assert_eq!(m.line(9), 6);
169 assert_eq!(m.line(10), 7, "the start of the second run");
170 assert_eq!(m.line(11), 7, "inside it");
171 assert_eq!(m.line(12), 8, "after it: two dropped, one written");
172 assert_eq!(m.line(20), 16);
173 assert_eq!([20, 120, 119, 121, 200, 240, 300].map(|b| m.byte(b)), [20, 20, 20, 21, 100, 125, 185]);
174 }
175
176 #[test]
177 fn a_map_survives_its_json_and_other_lines_are_not_maps() {
178 let m = map("a", "b");
179 assert_eq!(Map::from_json(&m.to_json()), Some(m));
180 assert_eq!(Map::from_json(&json!({ "k": "done", "gen_before": "a" })), None);
181 assert_eq!(Map::from_json(&json!({ "k": "map", "gen_before": "a", "gen_after": "b", "runs": [[1, 2]] })), None, "a short triple is no map");
182 }
183
184 #[test]
185 fn positions_cross_several_swaps_and_a_broken_chain_is_not_guessed() {
186 let all = [map("a", "b"), map("b", "c")];
187 assert_eq!(translate_line(&all, "a", "a", 12), Some(12), "the same file: no change");
188 assert_eq!(translate_line(&all, "a", "b", 12), Some(8));
189 assert_eq!(translate_line(&all, "a", "c", 20), Some(map("a", "b").line(map("a", "b").line(20))));
190 assert_eq!(translate_line(&all, "z", "c", 5), None);
191 assert_eq!(translate_line(&all[1..], "a", "c", 5), None, "a swap in the chain is missing");
192 assert_eq!(translate_byte(&all, "b", "c", 300), Some(map("b", "c").byte(300)));
193 }
194}