72 lines
1.7 KiB
Rust
Raw Normal View History

2022-08-22 18:33:02 +08:00
#[derive(Clone, serde::Serialize, serde::Deserialize)]
pub struct Path(pub Vec<usize>);
2022-08-16 16:25:52 +08:00
impl std::ops::Deref for Path {
type Target = Vec<usize>;
fn deref(&self) -> &Self::Target {
&self.0
2022-08-19 14:43:11 +08:00
}
}
2022-09-08 17:38:11 +08:00
impl std::convert::Into<Path> for usize {
fn into(self) -> Path {
Path(vec![self])
}
}
2022-09-08 17:38:11 +08:00
impl std::convert::Into<Path> for &usize {
fn into(self) -> Path {
Path(vec![*self])
}
}
impl std::convert::Into<Path> for &Path {
fn into(self) -> Path {
self.clone()
}
}
impl From<Vec<usize>> for Path {
fn from(v: Vec<usize>) -> Self {
Path(v)
}
}
impl From<&Vec<usize>> for Path {
fn from(values: &Vec<usize>) -> Self {
Path(values.clone())
}
}
impl Path {
2022-08-19 14:43:11 +08:00
// delta is default to be 1
pub fn transform(pre_insert_path: &Path, b: &Path, offset: i64) -> Path {
2022-08-19 14:43:11 +08:00
if pre_insert_path.len() > b.len() {
return b.clone();
}
if pre_insert_path.is_empty() || b.is_empty() {
return b.clone();
}
// check the prefix
2022-08-22 18:33:02 +08:00
for i in 0..(pre_insert_path.len() - 1) {
2022-08-19 14:43:11 +08:00
if pre_insert_path.0[i] != b.0[i] {
return b.clone();
}
}
let mut prefix: Vec<usize> = pre_insert_path.0[0..(pre_insert_path.len() - 1)].into();
let mut suffix: Vec<usize> = b.0[pre_insert_path.0.len()..].into();
let prev_insert_last: usize = *pre_insert_path.0.last().unwrap();
let b_at_index = b.0[pre_insert_path.0.len() - 1];
if prev_insert_last <= b_at_index {
2022-08-24 11:50:06 +08:00
prefix.push(((b_at_index as i64) + offset) as usize);
2022-08-19 14:43:11 +08:00
} else {
prefix.push(b_at_index);
}
prefix.append(&mut suffix);
Path(prefix)
2022-08-19 14:43:11 +08:00
}
2022-08-16 16:25:52 +08:00
}