project_note
Clone
https://git.tahinli.com/Tahinli/project_note.git
0 watching·0 forks·Rust·3.6 MiB·c49f5e7·Tahinli·1 month ago·2 commits
| 1 | use std::{borrow::Cow, ops::Deref}; |
| 2 | |
| 3 | use crate::InternalString; |
| 4 | use loro_common::{ContainerID, ContainerType, Counter, LoroError, LoroResult, PeerID}; |
| 5 | use rustc_hash::FxHashSet; |
| 6 | use serde_columnar::columnar; |
| 7 | |
| 8 | use super::{ |
| 9 | outdated_encode_reordered::PeerIdx, |
| 10 | value::{Value, ValueDecodedArenasTrait, ValueEncodeRegister}, |
| 11 | value_register::ValueRegister, |
| 12 | }; |
| 13 | |
| 14 | #[derive(Debug)] |
| 15 | pub struct EncodedRegisters<'a> { |
| 16 | pub(super) peer: ValueRegister<PeerID>, |
| 17 | pub(super) key: ValueRegister<InternalString>, |
| 18 | pub(super) tree_id: ValueRegister<EncodedTreeID>, |
| 19 | pub(super) position: either::Either<FxHashSet<&'a [u8]>, ValueRegister<&'a [u8]>>, |
| 20 | } |
| 21 | |
| 22 | impl ValueEncodeRegister for EncodedRegisters<'_> { |
| 23 | fn key_mut(&mut self) -> &mut ValueRegister<InternalString> { |
| 24 | &mut self.key |
| 25 | } |
| 26 | |
| 27 | fn peer_mut(&mut self) -> &mut ValueRegister<PeerID> { |
| 28 | &mut self.peer |
| 29 | } |
| 30 | |
| 31 | fn encode_tree_op( |
| 32 | &mut self, |
| 33 | op: &crate::container::tree::tree_op::TreeOp, |
| 34 | ) -> super::value::Value<'static> { |
| 35 | Value::TreeMove(super::value::EncodedTreeMove::from_tree_op(op, self)) |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | #[columnar(vec, ser, de, iterable)] |
| 40 | #[derive(Debug, Copy, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)] |
| 41 | pub(crate) struct EncodedContainer { |
| 42 | #[columnar(strategy = "BoolRle")] |
| 43 | is_root: bool, |
| 44 | #[columnar(strategy = "Rle")] |
| 45 | kind: u8, |
| 46 | #[columnar(strategy = "Rle")] |
| 47 | peer_idx: usize, |
| 48 | #[columnar(strategy = "DeltaRle")] |
| 49 | key_idx_or_counter: i32, |
| 50 | } |
| 51 | |
| 52 | impl EncodedContainer { |
| 53 | pub fn as_container_id(&self, arenas: &dyn ValueDecodedArenasTrait) -> LoroResult<ContainerID> { |
| 54 | if self.is_root { |
| 55 | Ok(ContainerID::Root { |
| 56 | container_type: ContainerType::try_from_u8(self.kind) |
| 57 | .unwrap_or(ContainerType::Unknown(self.kind)), |
| 58 | name: arenas |
| 59 | .keys() |
| 60 | .get(self.key_idx_or_counter as usize) |
| 61 | .ok_or(LoroError::DecodeDataCorruptionError)? |
| 62 | .clone(), |
| 63 | }) |
| 64 | } else { |
| 65 | Ok(ContainerID::Normal { |
| 66 | container_type: ContainerType::try_from_u8(self.kind) |
| 67 | .unwrap_or(ContainerType::Unknown(self.kind)), |
| 68 | peer: *(arenas |
| 69 | .peers() |
| 70 | .get(self.peer_idx) |
| 71 | .ok_or(LoroError::DecodeDataCorruptionError)?), |
| 72 | counter: self.key_idx_or_counter, |
| 73 | }) |
| 74 | } |
| 75 | } |
| 76 | } |
| 77 | |
| 78 | #[columnar(ser, de)] |
| 79 | #[derive(Default)] |
| 80 | pub(crate) struct ContainerArena { |
| 81 | #[columnar(class = "vec", iter = "EncodedContainer")] |
| 82 | pub(super) containers: Vec<EncodedContainer>, |
| 83 | } |
| 84 | |
| 85 | impl Deref for ContainerArena { |
| 86 | type Target = [EncodedContainer]; |
| 87 | |
| 88 | fn deref(&self) -> &Self::Target { |
| 89 | &self.containers |
| 90 | } |
| 91 | } |
| 92 | |
| 93 | impl ContainerArena { |
| 94 | pub fn encode(&self) -> Vec<u8> { |
| 95 | serde_columnar::to_vec(&self.containers).unwrap() |
| 96 | } |
| 97 | |
| 98 | pub fn decode(bytes: &[u8]) -> LoroResult<Self> { |
| 99 | Ok(ContainerArena { |
| 100 | containers: serde_columnar::from_bytes(bytes)?, |
| 101 | }) |
| 102 | } |
| 103 | |
| 104 | pub fn from_containers( |
| 105 | cids: Vec<ContainerID>, |
| 106 | peer_register: &mut ValueRegister<PeerID>, |
| 107 | key_reg: &mut ValueRegister<InternalString>, |
| 108 | ) -> Self { |
| 109 | let mut ans = Self { |
| 110 | containers: Vec::with_capacity(cids.len()), |
| 111 | }; |
| 112 | for cid in cids { |
| 113 | ans.push(cid, peer_register, key_reg); |
| 114 | } |
| 115 | |
| 116 | ans |
| 117 | } |
| 118 | |
| 119 | pub fn push( |
| 120 | &mut self, |
| 121 | id: ContainerID, |
| 122 | peer_register: &mut ValueRegister<PeerID>, |
| 123 | register_key: &mut ValueRegister<InternalString>, |
| 124 | ) { |
| 125 | let (is_root, kind, peer_idx, key_idx_or_counter) = match id { |
| 126 | ContainerID::Root { |
| 127 | container_type, |
| 128 | name, |
| 129 | } => (true, container_type, 0, register_key.register(&name) as i32), |
| 130 | ContainerID::Normal { |
| 131 | container_type, |
| 132 | peer, |
| 133 | counter, |
| 134 | } => ( |
| 135 | false, |
| 136 | container_type, |
| 137 | peer_register.register(&peer), |
| 138 | counter, |
| 139 | ), |
| 140 | }; |
| 141 | self.containers.push(EncodedContainer { |
| 142 | is_root, |
| 143 | kind: kind.to_u8(), |
| 144 | peer_idx, |
| 145 | key_idx_or_counter, |
| 146 | }); |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | #[derive(Clone, Hash, PartialEq, Eq, Debug)] |
| 151 | #[columnar(vec, ser, de, iterable)] |
| 152 | pub struct EncodedTreeID { |
| 153 | #[columnar(strategy = "Rle")] |
| 154 | pub peer_idx: PeerIdx, |
| 155 | #[columnar(strategy = "DeltaRle")] |
| 156 | pub counter: Counter, |
| 157 | } |
| 158 | |
| 159 | #[derive(Clone)] |
| 160 | #[columnar(vec, ser, de, iterable)] |
| 161 | pub(super) struct PositionDelta<'a> { |
| 162 | #[columnar(strategy = "Rle")] |
| 163 | common_prefix_length: usize, |
| 164 | #[columnar(borrow)] |
| 165 | rest: Cow<'a, [u8]>, |
| 166 | } |
| 167 | |
| 168 | #[derive(Default)] |
| 169 | #[columnar(ser, de)] |
| 170 | pub(crate) struct PositionArena<'a> { |
| 171 | #[columnar(class = "vec", iter = "PositionDelta<'a>")] |
| 172 | pub(super) positions: Vec<PositionDelta<'a>>, |
| 173 | } |
| 174 | |
| 175 | impl<'a> PositionArena<'a> { |
| 176 | pub fn from_positions(positions: impl IntoIterator<Item = &'a [u8]>) -> Self { |
| 177 | let iter = positions.into_iter(); |
| 178 | let mut ans = Vec::with_capacity(iter.size_hint().0); |
| 179 | let mut last_bytes: &[u8] = &[]; |
| 180 | for p in iter { |
| 181 | let common = longest_common_prefix_length(last_bytes, p); |
| 182 | let rest = &p[common..]; |
| 183 | last_bytes = p; |
| 184 | ans.push(PositionDelta { |
| 185 | common_prefix_length: common, |
| 186 | rest: Cow::Borrowed(rest), |
| 187 | }) |
| 188 | } |
| 189 | Self { positions: ans } |
| 190 | } |
| 191 | |
| 192 | pub fn try_parse_to_positions(self) -> LoroResult<Vec<Vec<u8>>> { |
| 193 | let mut ans: Vec<Vec<u8>> = Vec::with_capacity(self.positions.len()); |
| 194 | for PositionDelta { |
| 195 | common_prefix_length, |
| 196 | rest, |
| 197 | } in self.positions |
| 198 | { |
| 199 | if let Some(last_bytes) = ans.last() { |
| 200 | if common_prefix_length > last_bytes.len() { |
| 201 | return Err(LoroError::DecodeError( |
| 202 | "Decode position arena failed: common prefix out of range".into(), |
| 203 | )); |
| 204 | } |
| 205 | } else if common_prefix_length != 0 { |
| 206 | return Err(LoroError::DecodeError( |
| 207 | "Decode position arena failed: first common prefix is nonzero".into(), |
| 208 | )); |
| 209 | } |
| 210 | |
| 211 | // +1 for Fractional Index |
| 212 | let capacity = rest |
| 213 | .len() |
| 214 | .checked_add(common_prefix_length) |
| 215 | .and_then(|len| len.checked_add(1)) |
| 216 | .ok_or_else(|| { |
| 217 | LoroError::DecodeError( |
| 218 | "Decode position arena failed: position length overflow".into(), |
| 219 | ) |
| 220 | })?; |
| 221 | let mut p = Vec::with_capacity(capacity); |
| 222 | if let Some(last_bytes) = ans.last() { |
| 223 | p.extend_from_slice(&last_bytes[0..common_prefix_length]); |
| 224 | } |
| 225 | p.extend_from_slice(rest.as_ref()); |
| 226 | ans.push(p); |
| 227 | } |
| 228 | Ok(ans) |
| 229 | } |
| 230 | |
| 231 | pub fn encode(&self) -> Vec<u8> { |
| 232 | serde_columnar::to_vec(&self).unwrap() |
| 233 | } |
| 234 | |
| 235 | pub fn decode<'de: 'a>(bytes: &'de [u8]) -> LoroResult<Self> { |
| 236 | Ok(serde_columnar::from_bytes(bytes)?) |
| 237 | } |
| 238 | |
| 239 | pub fn encode_v2(&self) -> Vec<u8> { |
| 240 | if self.positions.is_empty() { |
| 241 | return Vec::new(); |
| 242 | } |
| 243 | |
| 244 | serde_columnar::to_vec(&self).unwrap() |
| 245 | } |
| 246 | |
| 247 | pub fn decode_v2<'de: 'a>(bytes: &'de [u8]) -> LoroResult<Self> { |
| 248 | if bytes.is_empty() { |
| 249 | return Ok(Self::default()); |
| 250 | } |
| 251 | |
| 252 | Ok(serde_columnar::from_bytes(bytes)?) |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | fn longest_common_prefix_length(a: &[u8], b: &[u8]) -> usize { |
| 257 | a.iter().zip(b.iter()).take_while(|(x, y)| x == y).count() |
| 258 | } |
| 259 | |
| 260 | #[cfg(test)] |
| 261 | mod tests { |
| 262 | use std::borrow::Cow; |
| 263 | |
| 264 | use super::{PositionArena, PositionDelta}; |
| 265 | |
| 266 | #[test] |
| 267 | fn position_arena_rejects_invalid_common_prefix() { |
| 268 | let arena = PositionArena { |
| 269 | positions: vec![PositionDelta { |
| 270 | common_prefix_length: 1, |
| 271 | rest: Cow::Borrowed(&[]), |
| 272 | }], |
| 273 | }; |
| 274 | |
| 275 | assert!(arena.try_parse_to_positions().is_err()); |
| 276 | } |
| 277 | } |