| 1 | |
|
| 2 | |
|
| 3 | |
|
| 4 | |
|
| 5 | |
|
| 6 | |
|
| 7 | |
|
| 8 | |
|
| 9 | |
|
| 10 | | use crate::cbor::{self, Value}; |
| 11 | | use crate::hash::{hash_object, ChangeHash, KeyId, ObjectRef, ObjectType}; |
| 12 | | use crate::ids::{ChangeId, NodeId}; |
| 13 | | use crate::lines::Lines; |
| 14 | | use std::collections::BTreeMap; |
| 15 | |
|
| 16 | | pub const FORMAT_VERSION: u64 = 1; |
| 17 | |
|
| 18 | |
|
| 19 | |
|
| 20 | |
|
| 21 | |
|
| 22 | |
|
| 23 | | pub const CHANGE_VERSION: u64 = 3; |
| 24 | |
|
| 25 | |
|
| 26 | | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] |
| 27 | | pub enum TextForm { |
| 28 | | |
| 29 | | Cbor, |
| 30 | | |
| 31 | | Raw, |
| 32 | | |
| 33 | | |
| 34 | | CborFallback, |
| 35 | | } |
| 36 | |
|
| 37 | |
|
| 38 | |
|
| 39 | |
|
| 40 | | pub const TEXT_BLOB_MIN: usize = 4096; |
| 41 | |
|
| 42 | | #[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)] |
| 43 | | pub enum ObjectError { |
| 44 | | #[error("cbor: {0}")] |
| 45 | | Cbor(#[from] cbor::CborError), |
| 46 | | #[error("schema: {0}")] |
| 47 | | Schema(String), |
| 48 | | |
| 49 | | |
| 50 | | #[error("damaged index: {0}")] |
| 51 | | DamagedIndex(String), |
| 52 | | } |
| 53 | |
|
| 54 | 18× | pub(crate) fn schema<T>(msg: impl Into<String>) -> Result<T, ObjectError> { |
| 55 | 18× | Err(ObjectError::Schema(msg.into())) |
| 56 | 18× | } |
| 57 | |
|
| 58 | | pub(crate) type Map = BTreeMap<u64, Value>; |
| 59 | |
|
| 60 | 916560× | pub(crate) fn field<'a>(m: &'a Map, k: u64, what: &str) -> Result<&'a Value, ObjectError> { |
| 61 | 916560× | m.get(&k) |
| 62 | 916560× | .ok_or_else(|| ObjectError::Schema(format!("missing field {k} ({what})"))) |
| 63 | 916560× | } |
| 64 | 374808× | pub(crate) fn uint(v: &Value, what: &str) -> Result<u64, ObjectError> { |
| 65 | 374808× | v.as_uint() |
| 66 | 374808× | .ok_or_else(|| ObjectError::Schema(format!("{what}: expected unsigned integer"))) |
| 67 | 374808× | } |
| 68 | 65723× | pub(crate) fn u32_(v: &Value, what: &str) -> Result<u32, ObjectError> { |
| 69 | 65723× | u32::try_from(uint(v, what)?).map_err(|_| ObjectError::Schema(format!("{what}: exceeds u32"))) |
| 70 | 65723× | } |
| 71 | 125024× | pub(crate) fn text<'a>(v: &'a Value, what: &str) -> Result<&'a str, ObjectError> { |
| 72 | 125024× | v.as_text() |
| 73 | 125024× | .ok_or_else(|| ObjectError::Schema(format!("{what}: expected text"))) |
| 74 | 125024× | } |
| 75 | 277125× | pub(crate) fn array<'a>(v: &'a Value, what: &str) -> Result<&'a [Value], ObjectError> { |
| 76 | 277125× | v.as_array() |
| 77 | 277125× | .ok_or_else(|| ObjectError::Schema(format!("{what}: expected array"))) |
| 78 | 277125× | } |
| 79 | 134136× | pub(crate) fn map<'a>(v: &'a Value, what: &str) -> Result<&'a Map, ObjectError> { |
| 80 | 134136× | v.as_map() |
| 81 | 134136× | .ok_or_else(|| ObjectError::Schema(format!("{what}: expected map"))) |
| 82 | 134136× | } |
| 83 | 409054× | pub(crate) fn bytes<'a>(v: &'a Value, what: &str) -> Result<&'a [u8], ObjectError> { |
| 84 | 409054× | v.as_bytes() |
| 85 | 409054× | .ok_or_else(|| ObjectError::Schema(format!("{what}: expected bytes"))) |
| 86 | 409054× | } |
| 87 | 133260× | pub(crate) fn oref(v: &Value, what: &str) -> Result<ObjectRef, ObjectError> { |
| 88 | 133260× | ObjectRef::from_slice(bytes(v, what)?) |
| 89 | 133259× | .ok_or_else(|| ObjectError::Schema(format!("{what}: expected 32 bytes"))) |
| 90 | 133260× | } |
| 91 | 148673× | pub(crate) fn node_id(v: &Value, what: &str) -> Result<NodeId, ObjectError> { |
| 92 | 148673× | NodeId::from_slice(bytes(v, what)?) |
| 93 | 148673× | .ok_or_else(|| ObjectError::Schema(format!("{what}: expected 16 bytes"))) |
| 94 | 148673× | } |
| 95 | 28032× | pub(crate) fn check_version(m: &Map) -> Result<(), ObjectError> { |
| 96 | 28032× | let v = uint(field(m, 0, "version")?, "version")?; |
| 97 | 28032× | if v != FORMAT_VERSION { |
| 98 | 0× | let exe = std::env::current_exe() |
| 99 | 0× | .map(|p| format!(" at {}", p.display())) |
| 100 | 0× | .unwrap_or_default(); |
| 101 | 0× | let which = format!("oxy {}{exe}", crate::VERSION); |
| 102 | 0× | return schema(if v > FORMAT_VERSION { |
| 103 | 0× | format!( |
| 104 | | "this data is format {v}, written by a newer oxy, and {which} reads format {FORMAT_VERSION}: install the current oxy, and check that no older copy comes first on PATH" |
| 105 | | ) |
| 106 | | } else { |
| 107 | 0× | format!( |
| 108 | | "this data is format {v}, written by an older oxy, and {which} reads format {FORMAT_VERSION} only" |
| 109 | | ) |
| 110 | | }); |
| 111 | 28032× | } |
| 112 | 28032× | Ok(()) |
| 113 | 28032× | } |
| 114 | |
|
| 115 | |
|
| 116 | |
|
| 117 | |
|
| 118 | | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] |
| 119 | | pub struct Hlc { |
| 120 | | pub wall_ms: u64, |
| 121 | | pub logical: u32, |
| 122 | | } |
| 123 | |
|
| 124 | | impl Hlc { |
| 125 | 6142× | pub fn now() -> Hlc { |
| 126 | 6142× | let wall_ms = std::time::SystemTime::now() |
| 127 | 6142× | .duration_since(std::time::UNIX_EPOCH) |
| 128 | 6142× | .map(|d| d.as_millis() as u64) |
| 129 | 6142× | .unwrap_or(0); |
| 130 | 6142× | Hlc { |
| 131 | 6142× | wall_ms, |
| 132 | 6142× | logical: 0, |
| 133 | 6142× | } |
| 134 | 6142× | } |
| 135 | 11806× | pub(crate) fn to_value(self) -> Value { |
| 136 | 11806× | Value::map([ |
| 137 | 11806× | (0, Value::Uint(self.wall_ms)), |
| 138 | 11806× | (1, Value::Uint(self.logical as u64)), |
| 139 | 11806× | ]) |
| 140 | 11806× | } |
| 141 | 34956× | pub(crate) fn from_value(v: &Value) -> Result<Hlc, ObjectError> { |
| 142 | 34956× | let m = map(v, "hlc")?; |
| 143 | | Ok(Hlc { |
| 144 | 34956× | wall_ms: uint(field(m, 0, "hlc.wall_ms")?, "hlc.wall_ms")?, |
| 145 | 34956× | logical: u32_(field(m, 1, "hlc.logical")?, "hlc.logical")?, |
| 146 | | }) |
| 147 | 34956× | } |
| 148 | | } |
| 149 | |
|
| 150 | |
|
| 151 | |
|
| 152 | | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 153 | | pub enum NodeKind { |
| 154 | | File, |
| 155 | | Dir, |
| 156 | | Symlink, |
| 157 | | |
| 158 | | Subrepo, |
| 159 | | } |
| 160 | |
|
| 161 | | impl NodeKind { |
| 162 | 73400× | pub(crate) fn tag(self) -> u64 { |
| 163 | 73400× | match self { |
| 164 | 72456× | NodeKind::File => 0, |
| 165 | 920× | NodeKind::Dir => 1, |
| 166 | 3× | NodeKind::Symlink => 2, |
| 167 | 21× | NodeKind::Subrepo => 3, |
| 168 | | } |
| 169 | 73400× | } |
| 170 | 97319× | pub(crate) fn from_tag(t: u64) -> Result<NodeKind, ObjectError> { |
| 171 | 97319× | Ok(match t { |
| 172 | 95291× | 0 => NodeKind::File, |
| 173 | 1921× | 1 => NodeKind::Dir, |
| 174 | 9× | 2 => NodeKind::Symlink, |
| 175 | 98× | 3 => NodeKind::Subrepo, |
| 176 | 0× | _ => return schema(format!("unknown node kind {t}")), |
| 177 | | }) |
| 178 | 97319× | } |
| 179 | | } |
| 180 | |
|
| 181 | |
|
| 182 | | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, PartialOrd, Ord)] |
| 183 | | pub struct Mode { |
| 184 | | pub exec: bool, |
| 185 | | pub opaque: bool, |
| 186 | | } |
| 187 | |
|
| 188 | | impl Mode { |
| 189 | | pub const TEXT: Mode = Mode { |
| 190 | | exec: false, |
| 191 | | opaque: false, |
| 192 | | }; |
| 193 | | pub const OPAQUE: Mode = Mode { |
| 194 | | exec: false, |
| 195 | | opaque: true, |
| 196 | | }; |
| 197 | 73052× | pub(crate) fn bits(self) -> u64 { |
| 198 | 73052× | (self.exec as u64) | ((self.opaque as u64) << 1) |
| 199 | 73052× | } |
| 200 | 97283× | pub(crate) fn from_bits(b: u64) -> Result<Mode, ObjectError> { |
| 201 | 97283× | if b > 3 { |
| 202 | 1× | return schema(format!("unknown mode bits {b}")); |
| 203 | 97282× | } |
| 204 | 97282× | Ok(Mode { |
| 205 | 97282× | exec: b & 1 != 0, |
| 206 | 97282× | opaque: b & 2 != 0, |
| 207 | 97282× | }) |
| 208 | 97283× | } |
| 209 | | } |
| 210 | |
|
| 211 | |
|
| 212 | |
|
| 213 | | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)] |
| 214 | | pub struct OpRef { |
| 215 | | pub change: ChangeHash, |
| 216 | | pub index: u32, |
| 217 | | } |
| 218 | |
|
| 219 | | impl OpRef { |
| 220 | 514× | fn to_value(self) -> Value { |
| 221 | 514× | Value::Array(vec![ |
| 222 | 514× | Value::Bytes(self.change.0.to_vec()), |
| 223 | 514× | Value::Uint(self.index as u64), |
| 224 | 514× | ]) |
| 225 | 514× | } |
| 226 | 859× | fn from_value(v: &Value, what: &str) -> Result<OpRef, ObjectError> { |
| 227 | 859× | let a = array(v, what)?; |
| 228 | 859× | if a.len() != 2 { |
| 229 | 0× | return schema(format!("{what}: expected [hash, index]")); |
| 230 | 859× | } |
| 231 | | Ok(OpRef { |
| 232 | 859× | change: oref(&a[0], what)?, |
| 233 | 859× | index: u32_(&a[1], what)?, |
| 234 | | }) |
| 235 | 859× | } |
| 236 | | |
| 237 | 858× | pub fn resolve(self, me: ChangeHash) -> OpRef { |
| 238 | 858× | if self.change.is_zero() { |
| 239 | 1× | OpRef { change: me, ..self } |
| 240 | | } else { |
| 241 | 857× | self |
| 242 | | } |
| 243 | 858× | } |
| 244 | | } |
| 245 | |
|
| 246 | | #[derive(Debug, Clone, PartialEq, Eq)] |
| 247 | | pub enum TreeOp { |
| 248 | | AddNode { |
| 249 | | node: NodeId, |
| 250 | | kind: NodeKind, |
| 251 | | mode: Mode, |
| 252 | | parent: NodeId, |
| 253 | | name: String, |
| 254 | | }, |
| 255 | | RemoveNode { |
| 256 | | node: NodeId, |
| 257 | | placement: OpRef, |
| 258 | | }, |
| 259 | | Move { |
| 260 | | node: NodeId, |
| 261 | | old: OpRef, |
| 262 | | parent: NodeId, |
| 263 | | name: String, |
| 264 | | }, |
| 265 | | SetMode { |
| 266 | | node: NodeId, |
| 267 | | old: OpRef, |
| 268 | | mode: Mode, |
| 269 | | }, |
| 270 | | } |
| 271 | |
|
| 272 | |
|
| 273 | 47218× | pub fn validate_name(name: &str) -> Result<(), ObjectError> { |
| 274 | 47218× | if name.is_empty() || name == "." || name == ".." || name.contains('/') || name.contains('\0') { |
| 275 | 6× | return schema(format!("invalid placement name {name:?}")); |
| 276 | 47212× | } |
| 277 | 47212× | Ok(()) |
| 278 | 47218× | } |
| 279 | |
|
| 280 | | impl TreeOp { |
| 281 | 104× | pub fn node(&self) -> NodeId { |
| 282 | 104× | match self { |
| 283 | 81× | TreeOp::AddNode { node, .. } |
| 284 | 11× | | TreeOp::RemoveNode { node, .. } |
| 285 | 11× | | TreeOp::Move { node, .. } |
| 286 | 104× | | TreeOp::SetMode { node, .. } => *node, |
| 287 | | } |
| 288 | 104× | } |
| 289 | |
|
| 290 | 6218× | fn to_value(&self) -> Value { |
| 291 | 11953× | let nid = |n: &NodeId| Value::Bytes(n.0.to_vec()); |
| 292 | 6218× | match self { |
| 293 | | TreeOp::AddNode { |
| 294 | 5704× | node, |
| 295 | 5704× | kind, |
| 296 | 5704× | mode, |
| 297 | 5704× | parent, |
| 298 | 5704× | name, |
| 299 | 5704× | } => Value::map([ |
| 300 | 5704× | (0, Value::Uint(0)), |
| 301 | 5704× | (1, nid(node)), |
| 302 | 5704× | (2, Value::Uint(kind.tag())), |
| 303 | 5704× | (3, Value::Uint(mode.bits())), |
| 304 | 5704× | (4, nid(parent)), |
| 305 | 5704× | (5, Value::Text(name.clone())), |
| 306 | 5704× | ]), |
| 307 | 416× | TreeOp::RemoveNode { node, placement } => Value::map([ |
| 308 | 416× | (0, Value::Uint(1)), |
| 309 | 416× | (1, nid(node)), |
| 310 | 416× | (2, placement.to_value()), |
| 311 | 416× | ]), |
| 312 | | TreeOp::Move { |
| 313 | 31× | node, |
| 314 | 31× | old, |
| 315 | 31× | parent, |
| 316 | 31× | name, |
| 317 | 31× | } => Value::map([ |
| 318 | 31× | (0, Value::Uint(2)), |
| 319 | 31× | (1, nid(node)), |
| 320 | 31× | (2, old.to_value()), |
| 321 | 31× | (4, nid(parent)), |
| 322 | 31× | (5, Value::Text(name.clone())), |
| 323 | 31× | ]), |
| 324 | 67× | TreeOp::SetMode { node, old, mode } => Value::map([ |
| 325 | 67× | (0, Value::Uint(3)), |
| 326 | 67× | (1, nid(node)), |
| 327 | 67× | (2, old.to_value()), |
| 328 | 67× | (3, Value::Uint(mode.bits())), |
| 329 | 67× | ]), |
| 330 | | } |
| 331 | 6218× | } |
| 332 | |
|
| 333 | 47891× | fn from_value(v: &Value) -> Result<TreeOp, ObjectError> { |
| 334 | 47891× | let m = map(v, "tree_op")?; |
| 335 | 47891× | let tag = uint(field(m, 0, "tree_op tag")?, "tree_op tag")?; |
| 336 | 47891× | let node = node_id(field(m, 1, "tree_op.node")?, "tree_op.node")?; |
| 337 | 47891× | let op = match tag { |
| 338 | | 0 => { |
| 339 | 47032× | let name = text(field(m, 5, "name")?, "name")?.to_owned(); |
| 340 | 47032× | validate_name(&name)?; |
| 341 | | TreeOp::AddNode { |
| 342 | 47032× | node, |
| 343 | 47032× | kind: NodeKind::from_tag(uint(field(m, 2, "kind")?, "kind")?)?, |
| 344 | 47032× | mode: Mode::from_bits(uint(field(m, 3, "mode")?, "mode")?)?, |
| 345 | 47032× | parent: node_id(field(m, 4, "parent")?, "parent")?, |
| 346 | 47032× | name, |
| 347 | | } |
| 348 | | } |
| 349 | | 1 => TreeOp::RemoveNode { |
| 350 | 653× | node, |
| 351 | 653× | placement: OpRef::from_value(field(m, 2, "placement")?, "placement")?, |
| 352 | | }, |
| 353 | | 2 => { |
| 354 | 167× | let name = text(field(m, 5, "name")?, "name")?.to_owned(); |
| 355 | 167× | validate_name(&name)?; |
| 356 | | TreeOp::Move { |
| 357 | 167× | node, |
| 358 | 167× | old: OpRef::from_value(field(m, 2, "old")?, "old")?, |
| 359 | 167× | parent: node_id(field(m, 4, "parent")?, "parent")?, |
| 360 | 167× | name, |
| 361 | | } |
| 362 | | } |
| 363 | | 3 => TreeOp::SetMode { |
| 364 | 39× | node, |
| 365 | 39× | old: OpRef::from_value(field(m, 2, "old")?, "old")?, |
| 366 | 39× | mode: Mode::from_bits(uint(field(m, 3, "mode")?, "mode")?)?, |
| 367 | | }, |
| 368 | 0× | _ => return schema(format!("unknown tree op tag {tag}")), |
| 369 | | }; |
| 370 | 47891× | if node.is_root() { |
| 371 | 0× | return schema("tree op on the root node"); |
| 372 | 47891× | } |
| 373 | 47891× | Ok(op) |
| 374 | 47891× | } |
| 375 | | } |
| 376 | |
|
| 377 | |
|
| 378 | |
|
| 379 | | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 380 | | pub enum AtomRef { |
| 381 | | Start, |
| 382 | | End, |
| 383 | | Atom { change: ChangeHash, index: u32 }, |
| 384 | | } |
| 385 | |
|
| 386 | | impl AtomRef { |
| 387 | 15308× | fn to_value(self) -> Value { |
| 388 | 15308× | match self { |
| 389 | 5564× | AtomRef::Start => Value::Uint(0), |
| 390 | 5707× | AtomRef::End => Value::Uint(1), |
| 391 | 4037× | AtomRef::Atom { change, index } => Value::Array(vec![ |
| 392 | 4037× | Value::Bytes(change.0.to_vec()), |
| 393 | 4037× | Value::Uint(index as u64), |
| 394 | 4037× | ]), |
| 395 | | } |
| 396 | 15308× | } |
| 397 | 100100× | fn from_value(v: &Value, what: &str) -> Result<AtomRef, ObjectError> { |
| 398 | 8268× | match v { |
| 399 | 45193× | Value::Uint(0) => Ok(AtomRef::Start), |
| 400 | 46639× | Value::Uint(1) => Ok(AtomRef::End), |
| 401 | 8268× | Value::Array(a) if a.len() == 2 => Ok(AtomRef::Atom { |
| 402 | 8268× | change: oref(&a[0], what)?, |
| 403 | 8268× | index: u32_(&a[1], what)?, |
| 404 | | }), |
| 405 | 0× | _ => schema(format!("{what}: expected atom reference")), |
| 406 | | } |
| 407 | 100100× | } |
| 408 | 62088× | pub fn resolve(self, me: ChangeHash) -> AtomRef { |
| 409 | 8838× | match self { |
| 410 | 8838× | AtomRef::Atom { change, index } if change.is_zero() => { |
| 411 | 34× | AtomRef::Atom { change: me, index } |
| 412 | | } |
| 413 | 62054× | other => other, |
| 414 | | } |
| 415 | 62088× | } |
| 416 | | } |
| 417 | |
|
| 418 | |
|
| 419 | | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 420 | | pub struct AtomRange { |
| 421 | | pub change: ChangeHash, |
| 422 | | pub from: u32, |
| 423 | | pub to: u32, |
| 424 | | } |
| 425 | |
|
| 426 | | impl AtomRange { |
| 427 | 2132× | fn to_value(self) -> Value { |
| 428 | 2132× | Value::Array(vec![ |
| 429 | 2132× | Value::Bytes(self.change.0.to_vec()), |
| 430 | 2132× | Value::Uint(self.from as u64), |
| 431 | 2132× | Value::Uint(self.to as u64), |
| 432 | 2132× | ]) |
| 433 | 2132× | } |
| 434 | 3633× | fn from_value(v: &Value) -> Result<AtomRange, ObjectError> { |
| 435 | 3633× | let a = array(v, "atom range")?; |
| 436 | 3633× | if a.len() != 3 { |
| 437 | 0× | return schema("atom range: expected [hash, from, to]"); |
| 438 | 3633× | } |
| 439 | 3633× | let r = AtomRange { |
| 440 | 3633× | change: oref(&a[0], "range.change")?, |
| 441 | 3633× | from: u32_(&a[1], "range.from")?, |
| 442 | 3633× | to: u32_(&a[2], "range.to")?, |
| 443 | | }; |
| 444 | 3633× | if r.from >= r.to { |
| 445 | 0× | return schema("atom range: empty or inverted"); |
| 446 | 3633× | } |
| 447 | 3633× | Ok(r) |
| 448 | 3633× | } |
| 449 | 3971× | pub fn resolve(self, me: ChangeHash) -> AtomRange { |
| 450 | 3971× | if self.change.is_zero() { |
| 451 | 18× | AtomRange { change: me, ..self } |
| 452 | | } else { |
| 453 | 3953× | self |
| 454 | | } |
| 455 | 3971× | } |
| 456 | | } |
| 457 | |
|
| 458 | | #[derive(Debug, Clone, PartialEq, Eq)] |
| 459 | | pub enum Edit { |
| 460 | | Insert { |
| 461 | | node: NodeId, |
| 462 | | after: AtomRef, |
| 463 | | before: AtomRef, |
| 464 | | lines: crate::lines::Lines, |
| 465 | | }, |
| 466 | | Delete { |
| 467 | | node: NodeId, |
| 468 | | atoms: Vec<AtomRange>, |
| 469 | | }, |
| 470 | | Replace { |
| 471 | | node: NodeId, |
| 472 | | old: Option<ObjectRef>, |
| 473 | | new: Option<ObjectRef>, |
| 474 | | }, |
| 475 | | } |
| 476 | |
|
| 477 | | impl Edit { |
| 478 | 47004× | pub fn node(&self) -> NodeId { |
| 479 | 47004× | match self { |
| 480 | 44021× | Edit::Insert { node, .. } | Edit::Delete { node, .. } | Edit::Replace { node, .. } => { |
| 481 | 47004× | *node |
| 482 | | } |
| 483 | | } |
| 484 | 47004× | } |
| 485 | |
|
| 486 | | |
| 487 | 9587× | fn stored_text(&self, version: u64) -> bool { |
| 488 | 7657× | matches!(self, Edit::Insert { lines, .. } |
| 489 | 7657× | if version >= 2 && cbor::byte_strings_len(lines) >= TEXT_BLOB_MIN) |
| 490 | 9587× | } |
| 491 | |
|
| 492 | | |
| 493 | | |
| 494 | | |
| 495 | | |
| 496 | 9580× | fn to_value(&self, stored: Option<(ObjectRef, TextForm)>, compact: bool) -> Value { |
| 497 | 9580× | let nid = |n: &NodeId| Value::Bytes(n.0.to_vec()); |
| 498 | 9580× | let opt = |o: &Option<ObjectRef>| match o { |
| 499 | 185× | Some(r) => Value::Bytes(r.0.to_vec()), |
| 500 | 123× | None => Value::Null, |
| 501 | 308× | }; |
| 502 | 9580× | match (self, stored) { |
| 503 | | ( |
| 504 | | Edit::Insert { |
| 505 | 73× | node, |
| 506 | 73× | after, |
| 507 | 73× | before, |
| 508 | 73× | lines, |
| 509 | | }, |
| 510 | 73× | Some((r, form)), |
| 511 | | ) => { |
| 512 | 73× | let mut fields = vec![ |
| 513 | 73× | (0, Value::Uint(0)), |
| 514 | 73× | (1, nid(node)), |
| 515 | 73× | (2, after.to_value()), |
| 516 | 73× | (3, before.to_value()), |
| 517 | 73× | (5, Value::Bytes(r.0.to_vec())), |
| 518 | 73× | (6, Value::Uint(lines.len() as u64)), |
| 519 | | ]; |
| 520 | 73× | if form == TextForm::CborFallback { |
| 521 | 1× | fields.push((7, Value::Uint(1))); |
| 522 | 72× | } |
| 523 | 73× | Value::map(fields) |
| 524 | | } |
| 525 | | ( |
| 526 | | Edit::Insert { |
| 527 | 7581× | node, |
| 528 | 7581× | after, |
| 529 | 7581× | before, |
| 530 | 7581× | lines, |
| 531 | | }, |
| 532 | | None, |
| 533 | 7581× | ) => Value::map([ |
| 534 | 7581× | (0, Value::Uint(0)), |
| 535 | 7581× | (1, nid(node)), |
| 536 | 7581× | (2, after.to_value()), |
| 537 | 7581× | (3, before.to_value()), |
| 538 | | ( |
| 539 | | 4, |
| 540 | 7581× | if compact { |
| 541 | 7575× | Value::Encoded(cbor::encode_byte_strings(lines)) |
| 542 | | } else { |
| 543 | 1008× | Value::Array(lines.iter().map(|l| Value::Bytes(l.to_vec())).collect()) |
| 544 | | }, |
| 545 | | ), |
| 546 | | ]), |
| 547 | 1772× | (Edit::Delete { node, atoms }, _) => Value::map([ |
| 548 | 1772× | (0, Value::Uint(1)), |
| 549 | 1772× | (1, nid(node)), |
| 550 | | ( |
| 551 | | 2, |
| 552 | 2132× | Value::Array(atoms.iter().map(|r| r.to_value()).collect()), |
| 553 | | ), |
| 554 | | ]), |
| 555 | 154× | (Edit::Replace { node, old, new }, _) => Value::map([ |
| 556 | 154× | (0, Value::Uint(2)), |
| 557 | 154× | (1, nid(node)), |
| 558 | 154× | (2, opt(old)), |
| 559 | 154× | (3, opt(new)), |
| 560 | 154× | ]), |
| 561 | | } |
| 562 | 9580× | } |
| 563 | |
|
| 564 | 7564× | fn from_value(v: &Value, version: u64, resolve: &mut Resolver) -> Result<Edit, ObjectError> { |
| 565 | 7564× | let m = map(v, "edit")?; |
| 566 | 7564× | let tag = uint(field(m, 0, "edit tag")?, "edit tag")?; |
| 567 | 7564× | let node = node_id(field(m, 1, "edit.node")?, "edit.node")?; |
| 568 | 7564× | let opt = |v: &Value, what: &str| -> Result<Option<ObjectRef>, ObjectError> { |
| 569 | 1610× | if v.is_null() { |
| 570 | 706× | Ok(None) |
| 571 | | } else { |
| 572 | 904× | Ok(Some(oref(v, what)?)) |
| 573 | | } |
| 574 | 1610× | }; |
| 575 | 7564× | Ok(match tag { |
| 576 | | 0 => { |
| 577 | 4034× | let lines = match (m.get(&4), m.get(&5)) { |
| 578 | 3768× | (Some(inline), None) => { |
| 579 | 3768× | let lines = array_lines(inline)?; |
| 580 | 3768× | if version >= 2 && cbor::byte_strings_len(&lines) >= TEXT_BLOB_MIN { |
| 581 | 1× | return schema("an insert this large is stored as a text blob in a version 2 change"); |
| 582 | 3767× | } |
| 583 | 3767× | if lines.is_empty() { |
| 584 | 0× | return schema("insert with no lines"); |
| 585 | 3767× | } |
| 586 | 3767× | lines |
| 587 | | } |
| 588 | 266× | (None, Some(text)) if version >= 2 => { |
| 589 | 266× | let text = oref(text, "insert text")?; |
| 590 | 266× | let count = u32_(field(m, 6, "insert line count")?, "insert line count")?; |
| 591 | 266× | if count == 0 { |
| 592 | 0× | return schema("insert with no lines"); |
| 593 | 266× | } |
| 594 | 266× | let form = match (version, m.get(&7)) { |
| 595 | 1× | (2, None) => TextForm::Cbor, |
| 596 | 264× | (_, None) => TextForm::Raw, |
| 597 | 1× | (3.., Some(Value::Uint(1))) => TextForm::CborFallback, |
| 598 | 0× | _ => return schema("unknown text blob form"), |
| 599 | | }; |
| 600 | | |
| 601 | 266× | resolve(&text, count, form)? |
| 602 | | } |
| 603 | | _ => { |
| 604 | 0× | return schema( |
| 605 | | "an insert has either its lines or, in a version 2 change, a text blob", |
| 606 | | ) |
| 607 | | } |
| 608 | | }; |
| 609 | | Edit::Insert { |
| 610 | 4031× | node, |
| 611 | 4031× | after: AtomRef::from_value(field(m, 2, "after")?, "after")?, |
| 612 | 4031× | before: AtomRef::from_value(field(m, 3, "before")?, "before")?, |
| 613 | 4031× | lines, |
| 614 | | } |
| 615 | | } |
| 616 | | 1 => { |
| 617 | 2725× | let atoms = array(field(m, 2, "atoms")?, "atoms")? |
| 618 | 2725× | .iter() |
| 619 | 2725× | .map(AtomRange::from_value) |
| 620 | 2725× | .collect::<Result<Vec<_>, _>>()?; |
| 621 | 2725× | if atoms.is_empty() { |
| 622 | 0× | return schema("delete with no atoms"); |
| 623 | 2725× | } |
| 624 | 2725× | Edit::Delete { node, atoms } |
| 625 | | } |
| 626 | | 2 => Edit::Replace { |
| 627 | 805× | node, |
| 628 | 805× | old: opt(field(m, 2, "old")?, "old")?, |
| 629 | 805× | new: opt(field(m, 3, "new")?, "new")?, |
| 630 | | }, |
| 631 | 0× | _ => return schema(format!("unknown edit tag {tag}")), |
| 632 | | }) |
| 633 | 7564× | } |
| 634 | | } |
| 635 | |
|
| 636 | |
|
| 637 | |
|
| 638 | | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 639 | | pub enum ChangeKind { |
| 640 | | Normal, |
| 641 | | Resolution, |
| 642 | | WorkingCopy, |
| 643 | | } |
| 644 | |
|
| 645 | | impl ChangeKind { |
| 646 | 16281× | pub(crate) fn tag(self) -> u64 { |
| 647 | 16281× | match self { |
| 648 | 13743× | ChangeKind::Normal => 0, |
| 649 | 41× | ChangeKind::Resolution => 1, |
| 650 | 2497× | ChangeKind::WorkingCopy => 2, |
| 651 | | } |
| 652 | 16281× | } |
| 653 | 28311× | pub(crate) fn from_tag(t: u64) -> Result<ChangeKind, ObjectError> { |
| 654 | 28311× | Ok(match t { |
| 655 | 25370× | 0 => ChangeKind::Normal, |
| 656 | 120× | 1 => ChangeKind::Resolution, |
| 657 | 2821× | 2 => ChangeKind::WorkingCopy, |
| 658 | 0× | _ => return schema(format!("unknown change kind {t}")), |
| 659 | | }) |
| 660 | 28311× | } |
| 661 | | } |
| 662 | |
|
| 663 | |
|
| 664 | | #[derive(Debug, Clone, PartialEq, Eq)] |
| 665 | | pub struct Change { |
| 666 | | |
| 667 | | |
| 668 | | pub version: u64, |
| 669 | | pub change_id: ChangeId, |
| 670 | | pub deps: Vec<ChangeHash>, |
| 671 | | pub author: KeyId, |
| 672 | | pub hlc: Hlc, |
| 673 | | pub message: String, |
| 674 | | pub tree_ops: Vec<TreeOp>, |
| 675 | | pub edits: Vec<Edit>, |
| 676 | | pub kind: ChangeKind, |
| 677 | | } |
| 678 | |
|
| 679 | | impl Change { |
| 680 | 5757× | pub fn normalize(&mut self) { |
| 681 | 5757× | self.deps.sort(); |
| 682 | 5757× | self.deps.dedup(); |
| 683 | 5757× | } |
| 684 | |
|
| 685 | 6× | pub fn to_value(&self) -> Value { |
| 686 | 6× | self.value_with(&mut |_| true, false) |
| 687 | 6× | } |
| 688 | |
|
| 689 | | |
| 690 | | |
| 691 | | |
| 692 | | |
| 693 | 7666× | fn stored_texts(&self, sink: &mut TextSink) -> Vec<Option<(ObjectRef, TextForm)>> { |
| 694 | | use rayon::prelude::*; |
| 695 | 7666× | let mut refs: Vec<Option<(ObjectRef, TextForm)>> = vec![None; self.edits.len()]; |
| 696 | 7666× | let stored: Vec<usize> = (0..self.edits.len()) |
| 697 | 9580× | .filter(|i| self.edits[*i].stored_text(self.version)) |
| 698 | 7666× | .collect(); |
| 699 | | |
| 700 | | |
| 701 | | |
| 702 | 7666× | let mut batches: Vec<&[usize]> = Vec::new(); |
| 703 | 7666× | let (mut start, mut bytes) = (0, 0usize); |
| 704 | 7666× | for (k, i) in stored.iter().enumerate() { |
| 705 | 73× | if let Edit::Insert { lines, .. } = &self.edits[*i] { |
| 706 | 73× | bytes += lines.bytes().len(); |
| 707 | 73× | } |
| 708 | 73× | if k + 1 - start == 256 || bytes >= 32 << 20 { |
| 709 | 0× | batches.push(&stored[start..=k]); |
| 710 | 0× | (start, bytes) = (k + 1, 0); |
| 711 | 73× | } |
| 712 | | } |
| 713 | 7666× | if start < stored.len() { |
| 714 | 72× | batches.push(&stored[start..]); |
| 715 | 7594× | } |
| 716 | 7666× | for batch in batches { |
| 717 | 72× | let made: Vec<StoredText> = batch |
| 718 | 72× | .par_iter() |
| 719 | 73× | .map(|i| { |
| 720 | 73× | let Edit::Insert { lines, .. } = &self.edits[*i] else { |
| 721 | 0× | unreachable!("only inserts are stored as text"); |
| 722 | | }; |
| 723 | 73× | let form = text_form(self.version, lines); |
| 724 | 73× | let content = match form { |
| 725 | 71× | TextForm::Raw => lines.bytes().to_vec(), |
| 726 | 2× | TextForm::Cbor | TextForm::CborFallback => cbor::encode_byte_strings(lines), |
| 727 | | }; |
| 728 | 73× | StoredText { |
| 729 | 73× | blob: Blob::of(&content), |
| 730 | 73× | content, |
| 731 | 73× | form, |
| 732 | 73× | } |
| 733 | 73× | }) |
| 734 | 72× | .collect(); |
| 735 | 73× | for (i, t) in batch.iter().zip(&made) { |
| 736 | 73× | refs[*i] = Some((t.blob.hash(), t.form)); |
| 737 | 73× | } |
| 738 | 72× | if !sink(made) { |
| 739 | 0× | break; |
| 740 | 72× | } |
| 741 | | } |
| 742 | 7666× | refs |
| 743 | 7666× | } |
| 744 | |
|
| 745 | | |
| 746 | | |
| 747 | 7666× | fn value_with(&self, sink: &mut TextSink, compact: bool) -> Value { |
| 748 | 7666× | Value::map([ |
| 749 | 7666× | (0, Value::Uint(self.version)), |
| 750 | 7666× | (1, Value::Bytes(self.change_id.0.to_vec())), |
| 751 | | ( |
| 752 | | 2, |
| 753 | | Value::Array( |
| 754 | 7666× | self.deps |
| 755 | 7666× | .iter() |
| 756 | 9194× | .map(|d| Value::Bytes(d.0.to_vec())) |
| 757 | 7666× | .collect(), |
| 758 | | ), |
| 759 | | ), |
| 760 | 7666× | (3, Value::Bytes(self.author.0.to_vec())), |
| 761 | 7666× | (4, self.hlc.to_value()), |
| 762 | 7666× | (5, Value::Text(self.message.clone())), |
| 763 | | ( |
| 764 | | 6, |
| 765 | 7666× | Value::Array(self.tree_ops.iter().map(|t| t.to_value()).collect()), |
| 766 | | ), |
| 767 | | ( |
| 768 | | 7, |
| 769 | | Value::Array( |
| 770 | 7666× | self.edits |
| 771 | 7666× | .iter() |
| 772 | 7666× | .zip(self.stored_texts(sink)) |
| 773 | 9580× | .map(|(e, stored)| e.to_value(stored, compact)) |
| 774 | 7666× | .collect(), |
| 775 | | ), |
| 776 | | ), |
| 777 | 7666× | (8, Value::Uint(self.kind.tag())), |
| 778 | 7666× | (9, Value::Map(BTreeMap::new())), |
| 779 | | ]) |
| 780 | 7666× | } |
| 781 | |
|
| 782 | 3830× | pub fn encode(&self) -> Vec<u8> { |
| 783 | 3830× | debug_assert!( |
| 784 | 3830× | self.deps.windows(2).all(|w| w[0] < w[1]), |
| 785 | | "deps must be normalized" |
| 786 | | ); |
| 787 | 3830× | cbor::encode(&self.value_with(&mut |_| true, true)) |
| 788 | 3830× | } |
| 789 | |
|
| 790 | | |
| 791 | | |
| 792 | 120× | pub fn encode_parts(&self) -> (Vec<u8>, Vec<StoredText>) { |
| 793 | 120× | debug_assert!( |
| 794 | 120× | self.deps.windows(2).all(|w| w[0] < w[1]), |
| 795 | | "deps must be normalized" |
| 796 | | ); |
| 797 | 120× | let mut texts = Vec::new(); |
| 798 | 120× | let bytes = cbor::encode(&self.value_with( |
| 799 | 5× | &mut |batch| { |
| 800 | 5× | texts.extend(batch); |
| 801 | 5× | true |
| 802 | 5× | }, |
| 803 | | true, |
| 804 | | )); |
| 805 | 120× | (bytes, texts) |
| 806 | 120× | } |
| 807 | |
|
| 808 | | |
| 809 | | |
| 810 | | |
| 811 | 3710× | pub fn encode_streaming<E>( |
| 812 | 3710× | &self, |
| 813 | 3710× | mut store: impl FnMut(Vec<StoredText>) -> Result<(), E>, |
| 814 | 3710× | ) -> Result<Vec<u8>, E> { |
| 815 | 3710× | debug_assert!( |
| 816 | 3710× | self.deps.windows(2).all(|w| w[0] < w[1]), |
| 817 | | "deps must be normalized" |
| 818 | | ); |
| 819 | 3710× | let mut failed = None; |
| 820 | 3710× | let value = self.value_with( |
| 821 | 62× | &mut |batch| match store(batch) { |
| 822 | 62× | Ok(()) => true, |
| 823 | 0× | Err(e) => { |
| 824 | 0× | failed = Some(e); |
| 825 | 0× | false |
| 826 | | } |
| 827 | 62× | }, |
| 828 | | true, |
| 829 | | ); |
| 830 | 3710× | match failed { |
| 831 | 0× | Some(e) => Err(e), |
| 832 | 3710× | None => Ok(cbor::encode(&value)), |
| 833 | | } |
| 834 | 3710× | } |
| 835 | |
|
| 836 | | |
| 837 | 3× | pub fn has_stored_text(&self) -> bool { |
| 838 | 7× | self.edits.iter().any(|e| e.stored_text(self.version)) |
| 839 | 3× | } |
| 840 | |
|
| 841 | 3823× | pub fn hash(&self) -> ChangeHash { |
| 842 | 3823× | hash_object(ObjectType::Change, &self.encode()) |
| 843 | 3823× | } |
| 844 | |
|
| 845 | | |
| 846 | | |
| 847 | 4× | pub fn decode(bytes: &[u8]) -> Result<Change, ObjectError> { |
| 848 | 4× | Self::decode_with(bytes, &mut |r, _, _| { |
| 849 | 1× | schema(format!( |
| 850 | | "text blob {} needs a store to read it from", |
| 851 | 1× | r.short(12) |
| 852 | | )) |
| 853 | 1× | }) |
| 854 | 4× | } |
| 855 | |
|
| 856 | | |
| 857 | | |
| 858 | 5154× | pub fn decode_with(bytes: &[u8], resolve: &mut Resolver) -> Result<Change, ObjectError> { |
| 859 | 5154× | let v = cbor::decode(bytes)?; |
| 860 | 5154× | Self::from_value_with(&v, resolve) |
| 861 | 5154× | } |
| 862 | |
|
| 863 | 11077× | pub fn from_value(v: &Value) -> Result<Change, ObjectError> { |
| 864 | 11077× | Self::from_value_with(v, &mut |r, _, _| { |
| 865 | 0× | schema(format!( |
| 866 | | "text blob {} needs a store to read it from", |
| 867 | 0× | r.short(12) |
| 868 | | )) |
| 869 | 0× | }) |
| 870 | 11077× | } |
| 871 | |
|
| 872 | 16231× | pub(crate) fn from_value_with( |
| 873 | 16231× | v: &Value, |
| 874 | 16231× | resolve: &mut Resolver, |
| 875 | 16231× | ) -> Result<Change, ObjectError> { |
| 876 | 16231× | let m = map(v, "change")?; |
| 877 | 16231× | let version = uint(field(m, 0, "version")?, "version")?; |
| 878 | 16231× | if !(1..=CHANGE_VERSION).contains(&version) { |
| 879 | 1× | return schema(format!("unsupported change format version {version}")); |
| 880 | 16230× | } |
| 881 | 16230× | let change_id = ChangeId::from_slice(bytes(field(m, 1, "change_id")?, "change_id")?) |
| 882 | 16230× | .ok_or_else(|| ObjectError::Schema("change_id: expected 16 bytes".into()))?; |
| 883 | 16230× | let deps = array(field(m, 2, "deps")?, "deps")? |
| 884 | 16230× | .iter() |
| 885 | 16230× | .map(|d| oref(d, "dep")) |
| 886 | 16230× | .collect::<Result<Vec<_>, _>>()?; |
| 887 | 16230× | if !deps.windows(2).all(|w| w[0] < w[1]) { |
| 888 | 1× | return schema("deps must be sorted and unique"); |
| 889 | 16229× | } |
| 890 | 16229× | if deps.iter().any(|d| d.is_zero()) { |
| 891 | 0× | return schema("deps may not contain the self reference"); |
| 892 | 16229× | } |
| 893 | 16229× | let extra = map(field(m, 9, "extra")?, "extra")?; |
| 894 | 16229× | if !extra.is_empty() { |
| 895 | 1× | return schema("extra must be empty in format version 1"); |
| 896 | 16228× | } |
| 897 | | Ok(Change { |
| 898 | 16228× | version, |
| 899 | 16228× | change_id, |
| 900 | 16228× | deps, |
| 901 | 16228× | author: oref(field(m, 3, "author")?, "author")?, |
| 902 | 16228× | hlc: Hlc::from_value(field(m, 4, "hlc")?)?, |
| 903 | 16228× | message: text(field(m, 5, "message")?, "message")?.to_owned(), |
| 904 | 16228× | tree_ops: array(field(m, 6, "tree_ops")?, "tree_ops")? |
| 905 | 16228× | .iter() |
| 906 | 16228× | .map(TreeOp::from_value) |
| 907 | 16228× | .collect::<Result<Vec<_>, _>>()?, |
| 908 | 16228× | edits: array(field(m, 7, "edits")?, "edits")? |
| 909 | 16228× | .iter() |
| 910 | 16228× | .map(|e| Edit::from_value(e, version, resolve)) |
| 911 | 16228× | .collect::<Result<Vec<_>, _>>()?, |
| 912 | 16225× | kind: ChangeKind::from_tag(uint(field(m, 8, "kind")?, "kind")?)?, |
| 913 | | }) |
| 914 | 16231× | } |
| 915 | | } |
| 916 | |
|
| 917 | |
|
| 918 | |
|
| 919 | |
|
| 920 | |
|
| 921 | | pub type Resolver<'a> = dyn FnMut(&ObjectRef, u32, TextForm) -> Result<Lines, ObjectError> + 'a; |
| 922 | |
|
| 923 | |
|
| 924 | |
|
| 925 | | type TextSink<'a> = dyn FnMut(Vec<StoredText>) -> bool + 'a; |
| 926 | |
|
| 927 | |
|
| 928 | |
|
| 929 | | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 930 | | pub enum TextRef { |
| 931 | | |
| 932 | | Blob(ObjectRef, u32, TextForm), |
| 933 | | |
| 934 | | |
| 935 | | Inline { |
| 936 | | change: ChangeHash, |
| 937 | | start: u32, |
| 938 | | end: u32, |
| 939 | | }, |
| 940 | | } |
| 941 | |
|
| 942 | |
|
| 943 | |
|
| 944 | 31384× | pub fn inline_lines(array: &[u8]) -> Result<Lines, ObjectError> { |
| 945 | 31384× | let v = cbor::decode(array)?; |
| 946 | 31384× | let lines = array_lines(&v)?; |
| 947 | 31384× | if lines.is_empty() { |
| 948 | 0× | return schema("insert with no lines"); |
| 949 | 31384× | } |
| 950 | 31384× | Ok(lines) |
| 951 | 31384× | } |
| 952 | |
|
| 953 | |
|
| 954 | 35158× | fn array_lines(v: &Value) -> Result<Lines, ObjectError> { |
| 955 | 35158× | Ok(array(v, "lines")? |
| 956 | 35158× | .iter() |
| 957 | 57198× | .map(|l| bytes(l, "line")) |
| 958 | 35158× | .collect::<Result<Vec<&[u8]>, _>>()? |
| 959 | 35158× | .into_iter() |
| 960 | 35158× | .collect()) |
| 961 | 35158× | } |
| 962 | |
|
| 963 | | impl Change { |
| 964 | | |
| 965 | | |
| 966 | | |
| 967 | | |
| 968 | | |
| 969 | 8096× | pub fn decode_skeleton( |
| 970 | 8096× | bytes: &[u8], |
| 971 | 8096× | me: ChangeHash, |
| 972 | 8096× | ) -> Result<(Change, Vec<TextRef>), ObjectError> { |
| 973 | 8096× | let mut c = cbor::Cursor::new(bytes); |
| 974 | 8096× | let (major, n) = c.head()?; |
| 975 | 8096× | if major != 5 { |
| 976 | 0× | return schema("change: expected map"); |
| 977 | 8096× | } |
| 978 | 8096× | let mut fields = Map::new(); |
| 979 | 8096× | let mut edits = Vec::new(); |
| 980 | 8096× | let mut texts = Vec::new(); |
| 981 | 8096× | let mut version = None; |
| 982 | 8096× | let mut last: Option<u64> = None; |
| 983 | 8096× | for _ in 0..n { |
| 984 | 80958× | let k = map_key(&mut c, &mut last)?; |
| 985 | 80958× | if k == 7 { |
| 986 | 8096× | let Some(v) = version else { |
| 987 | 0× | return schema("change: version must come first"); |
| 988 | | }; |
| 989 | 8096× | let (am, an) = c.head()?; |
| 990 | 8096× | if am != 4 { |
| 991 | 0× | return schema("edits: expected array"); |
| 992 | 8096× | } |
| 993 | 8096× | for _ in 0..an { |
| 994 | 48742× | edits.push(edit_skeleton(&mut c, v, me, &mut texts)?); |
| 995 | | } |
| 996 | 8095× | fields.insert(7, Value::Array(Vec::new())); |
| 997 | | } else { |
| 998 | 72862× | let val = c.value()?; |
| 999 | 72862× | if k == 0 { |
| 1000 | 8096× | version = Some(uint(&val, "version")?); |
| 1001 | 64766× | } |
| 1002 | 72862× | fields.insert(k, val); |
| 1003 | | } |
| 1004 | | } |
| 1005 | 8095× | if !c.at_end() { |
| 1006 | 0× | return Err(ObjectError::Cbor(cbor::CborError::TrailingBytes)); |
| 1007 | 8095× | } |
| 1008 | 8095× | let mut change = Change::from_value(&Value::Map(fields))?; |
| 1009 | 8095× | change.edits = edits; |
| 1010 | 8095× | Ok((change, texts)) |
| 1011 | 8096× | } |
| 1012 | | } |
| 1013 | |
|
| 1014 | | impl Change { |
| 1015 | | |
| 1016 | | |
| 1017 | | |
| 1018 | 2978× | pub fn decode_meta(bytes: &[u8]) -> Result<crate::state::ChangeMeta, ObjectError> { |
| 1019 | 2978× | let mut c = cbor::Cursor::new(bytes); |
| 1020 | 2978× | let (major, n) = c.head()?; |
| 1021 | 2978× | if major != 5 { |
| 1022 | 0× | return schema("change: expected map"); |
| 1023 | 2978× | } |
| 1024 | 2978× | let mut fields = Map::new(); |
| 1025 | 2978× | let mut last: Option<u64> = None; |
| 1026 | 2978× | for _ in 0..n { |
| 1027 | 29780× | let k = map_key(&mut c, &mut last)?; |
| 1028 | 29780× | if k == 6 || k == 7 { |
| 1029 | 5956× | c.skip()?; |
| 1030 | 5956× | fields.insert(k, Value::Array(Vec::new())); |
| 1031 | | } else { |
| 1032 | 23824× | fields.insert(k, c.value()?); |
| 1033 | | } |
| 1034 | | } |
| 1035 | 2978× | if !c.at_end() { |
| 1036 | 0× | return Err(ObjectError::Cbor(cbor::CborError::TrailingBytes)); |
| 1037 | 2978× | } |
| 1038 | 2978× | Ok(crate::state::ChangeMeta::of(&Change::from_value( |
| 1039 | 2978× | &Value::Map(fields), |
| 1040 | 0× | )?)) |
| 1041 | 2978× | } |
| 1042 | | } |
| 1043 | |
|
| 1044 | |
|
| 1045 | 350050× | fn map_key(c: &mut cbor::Cursor, last: &mut Option<u64>) -> Result<u64, ObjectError> { |
| 1046 | 350050× | let (km, k) = c.head()?; |
| 1047 | 350050× | if km != 0 || last.is_some_and(|l| k <= l) { |
| 1048 | 0× | return Err(ObjectError::Cbor(cbor::CborError::BadMapKey)); |
| 1049 | 350050× | } |
| 1050 | 350050× | *last = Some(k); |
| 1051 | 350050× | Ok(k) |
| 1052 | 350050× | } |
| 1053 | |
|
| 1054 | |
|
| 1055 | 48742× | fn edit_skeleton( |
| 1056 | 48742× | c: &mut cbor::Cursor, |
| 1057 | 48742× | version: u64, |
| 1058 | 48742× | me: ChangeHash, |
| 1059 | 48742× | texts: &mut Vec<TextRef>, |
| 1060 | 48742× | ) -> Result<Edit, ObjectError> { |
| 1061 | 48742× | let (major, n) = c.head()?; |
| 1062 | 48742× | if major != 5 { |
| 1063 | 0× | return schema("edit: expected map"); |
| 1064 | 48742× | } |
| 1065 | 48742× | let mut fields = Map::new(); |
| 1066 | 48742× | let mut inline: Option<(usize, usize, u64)> = None; |
| 1067 | 48742× | let mut last: Option<u64> = None; |
| 1068 | 48742× | for _ in 0..n { |
| 1069 | 239312× | let k = map_key(c, &mut last)?; |
| 1070 | 239312× | if k == 4 { |
| 1071 | 46020× | let start = c.pos(); |
| 1072 | 46020× | let (am, count) = c.head()?; |
| 1073 | 46020× | if am != 4 { |
| 1074 | 0× | return schema("lines: expected array"); |
| 1075 | 46020× | } |
| 1076 | 46020× | for _ in 0..count { |
| 1077 | 61299× | c.skip()?; |
| 1078 | | } |
| 1079 | 46020× | inline = Some((start, c.pos(), count)); |
| 1080 | 46020× | continue; |
| 1081 | 193292× | } |
| 1082 | 193292× | fields.insert(k, c.value()?); |
| 1083 | | } |
| 1084 | 48742× | let Some((start, end, count)) = inline else { |
| 1085 | 2722× | return Edit::from_value(&Value::Map(fields), version, &mut |text, count, form| { |
| 1086 | 147× | texts.push(TextRef::Blob(*text, count, form)); |
| 1087 | 147× | Ok(Lines::default()) |
| 1088 | 147× | }); |
| 1089 | | }; |
| 1090 | 46020× | if uint(field(&fields, 0, "edit tag")?, "edit tag")? != 0 || fields.contains_key(&5) { |
| 1091 | 0× | return schema("only an insert has inline lines, and not with a text blob"); |
| 1092 | 46020× | } |
| 1093 | 46020× | if count == 0 { |
| 1094 | 0× | return schema("insert with no lines"); |
| 1095 | 46020× | } |
| 1096 | 46020× | if version >= 2 && end - start >= TEXT_BLOB_MIN { |
| 1097 | 1× | return schema("an insert this large is stored as a text blob in a version 2 change"); |
| 1098 | 46019× | } |
| 1099 | 46019× | let (Ok(start), Ok(end)) = (u32::try_from(start), u32::try_from(end)) else { |
| 1100 | 0× | return schema("change too large"); |
| 1101 | | }; |
| 1102 | 46019× | texts.push(TextRef::Inline { |
| 1103 | 46019× | change: me, |
| 1104 | 46019× | start, |
| 1105 | 46019× | end, |
| 1106 | 46019× | }); |
| 1107 | | Ok(Edit::Insert { |
| 1108 | 46019× | node: node_id(field(&fields, 1, "edit.node")?, "edit.node")?, |
| 1109 | 46019× | after: AtomRef::from_value(field(&fields, 2, "after")?, "after")?, |
| 1110 | 46019× | before: AtomRef::from_value(field(&fields, 3, "before")?, "before")?, |
| 1111 | 46019× | lines: Lines::default(), |
| 1112 | | }) |
| 1113 | 48742× | } |
| 1114 | |
|
| 1115 | |
|
| 1116 | |
|
| 1117 | | #[derive(Debug, Clone, PartialEq, Eq)] |
| 1118 | | pub struct StoredText { |
| 1119 | | pub blob: Blob, |
| 1120 | | pub content: Vec<u8>, |
| 1121 | | pub form: TextForm, |
| 1122 | | } |
| 1123 | |
|
| 1124 | |
|
| 1125 | 73× | fn text_form(version: u64, lines: &Lines) -> TextForm { |
| 1126 | 72× | match version { |
| 1127 | 73× | ..=2 => TextForm::Cbor, |
| 1128 | 72× | _ if lines.is_split_form() => TextForm::Raw, |
| 1129 | 1× | _ => TextForm::CborFallback, |
| 1130 | | } |
| 1131 | 73× | } |
| 1132 | |
|
| 1133 | |
|
| 1134 | |
|
| 1135 | |
|
| 1136 | 138× | pub fn text_lines(content: &[u8], count: u32, form: TextForm) -> Result<Lines, ObjectError> { |
| 1137 | 138× | let lines = match form { |
| 1138 | 132× | TextForm::Raw => Lines::split(content), |
| 1139 | 6× | TextForm::Cbor | TextForm::CborFallback => array_lines(&cbor::decode(content)?)?, |
| 1140 | | }; |
| 1141 | | |
| 1142 | | |
| 1143 | 138× | if cbor::byte_strings_len(&lines) < TEXT_BLOB_MIN { |
| 1144 | 2× | return schema(format!( |
| 1145 | | "a text blob of {} bytes is short enough to be inline", |
| 1146 | 2× | content.len() |
| 1147 | | )); |
| 1148 | 136× | } |
| 1149 | 136× | if form == TextForm::CborFallback && lines.is_split_form() { |
| 1150 | 1× | return schema("these lines are stored as their bytes in a version 3 change"); |
| 1151 | 135× | } |
| 1152 | 135× | if lines.len() != count as usize { |
| 1153 | 2× | return schema(format!( |
| 1154 | | "a text blob holds {} lines, the insert says {count}", |
| 1155 | 2× | lines.len() |
| 1156 | | )); |
| 1157 | 133× | } |
| 1158 | 133× | Ok(lines) |
| 1159 | 138× | } |
| 1160 | |
|
| 1161 | |
|
| 1162 | |
|
| 1163 | |
|
| 1164 | | #[derive(Debug, Clone, PartialEq, Eq)] |
| 1165 | | pub struct Blob { |
| 1166 | | pub length: u64, |
| 1167 | | pub chunks: Vec<ObjectRef>, |
| 1168 | | } |
| 1169 | |
|
| 1170 | | impl Blob { |
| 1171 | | |
| 1172 | | |
| 1173 | 473× | pub fn of(content: &[u8]) -> Blob { |
| 1174 | | Blob { |
| 1175 | 473× | length: content.len() as u64, |
| 1176 | 473× | chunks: crate::chunk::chunks(content) |
| 1177 | 473× | .into_iter() |
| 1178 | 596× | .map(|c| hash_object(ObjectType::Chunk, c)) |
| 1179 | 473× | .collect(), |
| 1180 | | } |
| 1181 | 473× | } |
| 1182 | |
|
| 1183 | 601× | pub fn encode(&self) -> Vec<u8> { |
| 1184 | 601× | cbor::encode(&Value::map([ |
| 1185 | 601× | (0, Value::Uint(FORMAT_VERSION)), |
| 1186 | 601× | (1, Value::Uint(self.length)), |
| 1187 | | ( |
| 1188 | | 2, |
| 1189 | | Value::Array( |
| 1190 | 601× | self.chunks |
| 1191 | 601× | .iter() |
| 1192 | 823× | .map(|c| Value::Bytes(c.0.to_vec())) |
| 1193 | 601× | .collect(), |
| 1194 | | ), |
| 1195 | | ), |
| 1196 | | ])) |
| 1197 | 601× | } |
| 1198 | 384× | pub fn hash(&self) -> ObjectRef { |
| 1199 | 384× | hash_object(ObjectType::Blob, &self.encode()) |
| 1200 | 384× | } |
| 1201 | 447× | pub fn decode(bytes: &[u8]) -> Result<Blob, ObjectError> { |
| 1202 | 447× | let v = cbor::decode(bytes)?; |
| 1203 | 447× | let m = map(&v, "blob")?; |
| 1204 | 447× | check_version(m)?; |
| 1205 | | Ok(Blob { |
| 1206 | 447× | length: uint(field(m, 1, "length")?, "length")?, |
| 1207 | 447× | chunks: array(field(m, 2, "chunks")?, "chunks")? |
| 1208 | 447× | .iter() |
| 1209 | 689× | .map(|c| oref(c, "chunk")) |
| 1210 | 447× | .collect::<Result<Vec<_>, _>>()?, |
| 1211 | | }) |
| 1212 | 447× | } |
| 1213 | | } |
| 1214 | |
|
| 1215 | |
|
| 1216 | |
|
| 1217 | |
|
| 1218 | |
|
| 1219 | | #[derive(Debug, Clone, PartialEq, Eq)] |
| 1220 | | pub struct Checkpoint { |
| 1221 | | pub heads: Vec<ChangeHash>, |
| 1222 | | pub count: u64, |
| 1223 | | pub payload: ObjectRef, |
| 1224 | | } |
| 1225 | |
|
| 1226 | | impl Checkpoint { |
| 1227 | 12× | pub fn encode(&self) -> Vec<u8> { |
| 1228 | 12× | cbor::encode(&Value::map([ |
| 1229 | 12× | (0, Value::Uint(FORMAT_VERSION)), |
| 1230 | | ( |
| 1231 | | 1, |
| 1232 | | Value::Array( |
| 1233 | 12× | self.heads |
| 1234 | 12× | .iter() |
| 1235 | 13× | .map(|h| Value::Bytes(h.0.to_vec())) |
| 1236 | 12× | .collect(), |
| 1237 | | ), |
| 1238 | | ), |
| 1239 | 12× | (2, Value::Uint(self.count)), |
| 1240 | 12× | (3, Value::Bytes(self.payload.0.to_vec())), |
| 1241 | | ])) |
| 1242 | 12× | } |
| 1243 | 0× | pub fn hash(&self) -> ObjectRef { |
| 1244 | 0× | hash_object(ObjectType::Checkpoint, &self.encode()) |
| 1245 | 0× | } |
| 1246 | 89× | pub fn decode(bytes: &[u8]) -> Result<Checkpoint, ObjectError> { |
| 1247 | 89× | let v = cbor::decode(bytes)?; |
| 1248 | 89× | let m = map(&v, "checkpoint")?; |
| 1249 | 89× | check_version(m)?; |
| 1250 | | Ok(Checkpoint { |
| 1251 | 89× | heads: array(field(m, 1, "heads")?, "heads")? |
| 1252 | 89× | .iter() |
| 1253 | 91× | .map(|h| oref(h, "head")) |
| 1254 | 89× | .collect::<Result<Vec<_>, _>>()?, |
| 1255 | 89× | count: uint(field(m, 2, "count")?, "count")?, |
| 1256 | 89× | payload: oref(field(m, 3, "payload")?, "payload")?, |
| 1257 | | }) |
| 1258 | 89× | } |
| 1259 | | } |
| 1260 | |
|
| 1261 | |
|
| 1262 | |
|
| 1263 | |
|
| 1264 | | #[derive(Debug, Clone, PartialEq, Eq, Default)] |
| 1265 | | pub struct StateObject { |
| 1266 | | pub heads: Vec<ChangeHash>, |
| 1267 | | } |
| 1268 | |
|
| 1269 | | impl StateObject { |
| 1270 | 3215× | pub fn new(mut heads: Vec<ChangeHash>) -> StateObject { |
| 1271 | 3215× | heads.sort(); |
| 1272 | 3215× | heads.dedup(); |
| 1273 | 3215× | StateObject { heads } |
| 1274 | 3215× | } |
| 1275 | 3214× | pub fn encode(&self) -> Vec<u8> { |
| 1276 | 3214× | debug_assert!(self.heads.windows(2).all(|w| w[0] < w[1])); |
| 1277 | 3214× | cbor::encode(&Value::map([ |
| 1278 | 3214× | (0, Value::Uint(FORMAT_VERSION)), |
| 1279 | | ( |
| 1280 | | 1, |
| 1281 | | Value::Array( |
| 1282 | 3214× | self.heads |
| 1283 | 3214× | .iter() |
| 1284 | 3756× | .map(|h| Value::Bytes(h.0.to_vec())) |
| 1285 | 3214× | .collect(), |
| 1286 | | ), |
| 1287 | | ), |
| 1288 | | ])) |
| 1289 | 3214× | } |
| 1290 | 2× | pub fn hash(&self) -> ObjectRef { |
| 1291 | 2× | hash_object(ObjectType::State, &self.encode()) |
| 1292 | 2× | } |
| 1293 | 5434× | pub fn decode(bytes: &[u8]) -> Result<StateObject, ObjectError> { |
| 1294 | 5434× | let v = cbor::decode(bytes)?; |
| 1295 | 5434× | let m = map(&v, "state")?; |
| 1296 | 5434× | check_version(m)?; |
| 1297 | 5434× | let heads = array(field(m, 1, "heads")?, "heads")? |
| 1298 | 5434× | .iter() |
| 1299 | 8306× | .map(|h| oref(h, "head")) |
| 1300 | 5434× | .collect::<Result<Vec<_>, _>>()?; |
| 1301 | 5434× | if !heads.windows(2).all(|w| w[0] < w[1]) { |
| 1302 | 0× | return schema("state heads must be sorted and unique"); |
| 1303 | 5434× | } |
| 1304 | 5434× | Ok(StateObject { heads }) |
| 1305 | 5434× | } |
| 1306 | | } |
| 1307 | |
|
| 1308 | | #[cfg(test)] |
| 1309 | | pub(crate) mod tests { |
| 1310 | | use super::*; |
| 1311 | |
|
| 1312 | 16× | pub(crate) fn sample_change() -> Change { |
| 1313 | 16× | let n = NodeId([7; 16]); |
| 1314 | 16× | let dep = ObjectRef([1; 32]); |
| 1315 | 16× | let mut c = Change { |
| 1316 | 16× | version: crate::objects::CHANGE_VERSION, |
| 1317 | 16× | change_id: ChangeId([9; 16]), |
| 1318 | 16× | deps: vec![ObjectRef([2; 32]), dep], |
| 1319 | 16× | author: ObjectRef([3; 32]), |
| 1320 | 16× | hlc: Hlc { |
| 1321 | 16× | wall_ms: 1_700_000_000_000, |
| 1322 | 16× | logical: 4, |
| 1323 | 16× | }, |
| 1324 | 16× | message: "Add greeting".into(), |
| 1325 | 16× | tree_ops: vec![ |
| 1326 | 16× | TreeOp::AddNode { |
| 1327 | 16× | node: n, |
| 1328 | 16× | kind: NodeKind::File, |
| 1329 | 16× | mode: Mode::TEXT, |
| 1330 | 16× | parent: NodeId::ROOT, |
| 1331 | 16× | name: "hello.txt".into(), |
| 1332 | 16× | }, |
| 1333 | 16× | TreeOp::SetMode { |
| 1334 | 16× | node: n, |
| 1335 | 16× | old: OpRef { |
| 1336 | 16× | change: ObjectRef::ZERO, |
| 1337 | 16× | index: 0, |
| 1338 | 16× | }, |
| 1339 | 16× | mode: Mode { |
| 1340 | 16× | exec: true, |
| 1341 | 16× | opaque: false, |
| 1342 | 16× | }, |
| 1343 | 16× | }, |
| 1344 | 16× | ], |
| 1345 | 16× | edits: vec![ |
| 1346 | 16× | Edit::Insert { |
| 1347 | 16× | node: n, |
| 1348 | 16× | after: AtomRef::Start, |
| 1349 | 16× | before: AtomRef::End, |
| 1350 | 16× | lines: vec![b"hello\n".to_vec(), b"world\n".to_vec()].into(), |
| 1351 | 16× | }, |
| 1352 | 16× | Edit::Delete { |
| 1353 | 16× | node: n, |
| 1354 | 16× | atoms: vec![AtomRange { |
| 1355 | 16× | change: dep, |
| 1356 | 16× | from: 0, |
| 1357 | 16× | to: 2, |
| 1358 | 16× | }], |
| 1359 | 16× | }, |
| 1360 | 16× | Edit::Replace { |
| 1361 | 16× | node: n, |
| 1362 | 16× | old: None, |
| 1363 | 16× | new: Some(ObjectRef([5; 32])), |
| 1364 | 16× | }, |
| 1365 | 16× | ], |
| 1366 | 16× | kind: ChangeKind::Normal, |
| 1367 | 16× | }; |
| 1368 | 16× | c.normalize(); |
| 1369 | 16× | c |
| 1370 | 16× | } |
| 1371 | |
|
| 1372 | | #[test] |
| 1373 | 1× | fn change_round_trips_and_hash_is_stable() { |
| 1374 | 1× | let c = sample_change(); |
| 1375 | 1× | let bytes = c.encode(); |
| 1376 | 1× | let d = Change::decode(&bytes).unwrap(); |
| 1377 | 1× | assert_eq!(c, d); |
| 1378 | 1× | assert_eq!(c.hash(), d.hash()); |
| 1379 | 1× | assert_eq!(d.encode(), bytes); |
| 1380 | | |
| 1381 | 1× | let mut e = c.clone(); |
| 1382 | 1× | e.message.push('!'); |
| 1383 | 1× | assert_ne!(e.hash(), c.hash()); |
| 1384 | 1× | } |
| 1385 | |
|
| 1386 | | #[test] |
| 1387 | 1× | fn compact_encoding_is_the_plain_one() { |
| 1388 | | |
| 1389 | | |
| 1390 | 1× | let c = sample_change(); |
| 1391 | 1× | assert!(!c.has_stored_text(), "the sample's insert is inline"); |
| 1392 | 1× | let plain = cbor::encode(&c.to_value()); |
| 1393 | 1× | assert_eq!(c.encode(), plain); |
| 1394 | 1× | assert_eq!(c.encode_parts().0, plain); |
| 1395 | 1× | let streamed: Result<Vec<u8>, ()> = c.encode_streaming(|_| Ok(())); |
| 1396 | 1× | assert_eq!(streamed.unwrap(), plain); |
| 1397 | 1× | assert_eq!(Change::decode(&plain).unwrap(), c); |
| 1398 | 1× | } |
| 1399 | |
|
| 1400 | | #[test] |
| 1401 | 1× | fn decode_rejects_bad_changes() { |
| 1402 | 1× | let c = sample_change(); |
| 1403 | 1× | let mut v = c.to_value(); |
| 1404 | 1× | if let Value::Map(m) = &mut v { |
| 1405 | 1× | m.insert(0, Value::Uint(4)); |
| 1406 | 1× | } |
| 1407 | 1× | assert!( |
| 1408 | 1× | matches!(Change::from_value(&v), Err(ObjectError::Schema(s)) if s.contains("version")) |
| 1409 | | ); |
| 1410 | |
|
| 1411 | 1× | let mut v = c.to_value(); |
| 1412 | 1× | if let Value::Map(m) = &mut v { |
| 1413 | 1× | m.insert( |
| 1414 | 1× | 2, |
| 1415 | 1× | Value::Array(vec![Value::Bytes(vec![2; 32]), Value::Bytes(vec![1; 32])]), |
| 1416 | 1× | ); |
| 1417 | 1× | } |
| 1418 | 1× | assert!( |
| 1419 | 1× | matches!(Change::from_value(&v), Err(ObjectError::Schema(s)) if s.contains("sorted")) |
| 1420 | | ); |
| 1421 | |
|
| 1422 | 1× | let mut v = c.to_value(); |
| 1423 | 1× | if let Value::Map(m) = &mut v { |
| 1424 | 1× | m.insert(9, Value::map([(0, Value::Null)])); |
| 1425 | 1× | } |
| 1426 | 1× | assert!( |
| 1427 | 1× | matches!(Change::from_value(&v), Err(ObjectError::Schema(s)) if s.contains("extra")) |
| 1428 | | ); |
| 1429 | 1× | } |
| 1430 | |
|
| 1431 | 6× | fn big_lines(n: usize) -> Lines { |
| 1432 | 6× | (0..n) |
| 1433 | 3000× | .map(|i| format!("line {i} of a large insert\n").into_bytes()) |
| 1434 | 6× | .collect() |
| 1435 | 6× | } |
| 1436 | |
|
| 1437 | 6× | fn with_insert(mut c: Change, lines: Lines) -> Change { |
| 1438 | 6× | c.edits[0] = Edit::Insert { |
| 1439 | 6× | node: NodeId([7; 16]), |
| 1440 | 6× | after: AtomRef::Start, |
| 1441 | 6× | before: AtomRef::End, |
| 1442 | 6× | lines, |
| 1443 | 6× | }; |
| 1444 | 6× | c |
| 1445 | 6× | } |
| 1446 | |
|
| 1447 | | #[test] |
| 1448 | 1× | fn large_inserts_are_stored_as_text_blobs() { |
| 1449 | 1× | assert!( |
| 1450 | 1× | !sample_change().has_stored_text(), |
| 1451 | | "a small insert stays inline" |
| 1452 | | ); |
| 1453 | 1× | let lines = big_lines(500); |
| 1454 | 1× | let c = with_insert(sample_change(), lines.clone()); |
| 1455 | 1× | assert!(c.has_stored_text()); |
| 1456 | 1× | let (bytes, texts) = c.encode_parts(); |
| 1457 | 1× | assert_eq!(bytes, c.encode()); |
| 1458 | 1× | assert!(bytes.len() < 1024, "{}", bytes.len()); |
| 1459 | 1× | assert_eq!(texts.len(), 1); |
| 1460 | | |
| 1461 | 1× | assert_eq!(texts[0].form, TextForm::Raw); |
| 1462 | 1× | assert_eq!(texts[0].content, lines.bytes()); |
| 1463 | 1× | assert_eq!(texts[0].blob, Blob::of(&texts[0].content)); |
| 1464 | 1× | assert!(Change::decode(&bytes).is_err(), "reading it needs the text"); |
| 1465 | 1× | let d = Change::decode_with(&bytes, &mut |r, n, form| { |
| 1466 | 1× | assert_eq!(*r, texts[0].blob.hash()); |
| 1467 | 1× | assert_eq!(form, TextForm::Raw); |
| 1468 | 1× | text_lines(&texts[0].content, n, form) |
| 1469 | 1× | }) |
| 1470 | 1× | .unwrap(); |
| 1471 | 1× | assert_eq!(d, c); |
| 1472 | 1× | assert_eq!(d.hash(), c.hash()); |
| 1473 | | |
| 1474 | 1× | let mut v2 = c.clone(); |
| 1475 | 1× | v2.version = 2; |
| 1476 | 1× | let (b2, t2) = v2.encode_parts(); |
| 1477 | 1× | assert_eq!(t2[0].form, TextForm::Cbor); |
| 1478 | 1× | assert_eq!(t2[0].content, cbor::encode_byte_strings(&lines)); |
| 1479 | 1× | let d2 = Change::decode_with(&b2, &mut |_, n, form| text_lines(&t2[0].content, n, form)) |
| 1480 | 1× | .unwrap(); |
| 1481 | 1× | assert_eq!(d2, v2); |
| 1482 | | |
| 1483 | | |
| 1484 | 1× | let odd: Lines = (0..500) |
| 1485 | 500× | .map(|i| format!("no newline {i}").into_bytes()) |
| 1486 | 1× | .collect(); |
| 1487 | 1× | let c3 = with_insert(sample_change(), odd.clone()); |
| 1488 | 1× | let (b3, t3) = c3.encode_parts(); |
| 1489 | 1× | assert_eq!(t3[0].form, TextForm::CborFallback); |
| 1490 | 1× | let d3 = Change::decode_with(&b3, &mut |_, n, form| text_lines(&t3[0].content, n, form)) |
| 1491 | 1× | .unwrap(); |
| 1492 | 1× | assert_eq!(d3, c3); |
| 1493 | 1× | let marked = cbor::encode_byte_strings(&lines); |
| 1494 | 1× | assert!(text_lines(&marked, 500, TextForm::CborFallback).is_err()); |
| 1495 | 1× | } |
| 1496 | |
|
| 1497 | | #[test] |
| 1498 | 1× | fn version_1_changes_keep_their_inline_inserts_and_hashes() { |
| 1499 | 1× | let mut c = with_insert(sample_change(), big_lines(500)); |
| 1500 | 1× | c.version = 1; |
| 1501 | 1× | let bytes = c.encode(); |
| 1502 | 1× | assert!(bytes.len() > TEXT_BLOB_MIN); |
| 1503 | 1× | let (again, texts) = c.encode_parts(); |
| 1504 | 1× | assert!(texts.is_empty()); |
| 1505 | 1× | assert_eq!(again, bytes); |
| 1506 | 1× | let d = Change::decode(&bytes).unwrap(); |
| 1507 | 1× | assert_eq!(d.version, 1); |
| 1508 | 1× | assert_eq!(d.encode(), bytes); |
| 1509 | | |
| 1510 | 1× | let mut v = c.to_value(); |
| 1511 | 1× | if let Value::Map(m) = &mut v { |
| 1512 | 1× | m.insert(0, Value::Uint(2)); |
| 1513 | 1× | } |
| 1514 | 1× | assert!( |
| 1515 | 1× | matches!(Change::from_value(&v), Err(ObjectError::Schema(s)) if s.contains("text blob")) |
| 1516 | | ); |
| 1517 | 1× | } |
| 1518 | |
|
| 1519 | | #[test] |
| 1520 | 1× | fn a_skeleton_leaves_every_insert_out_and_says_where_its_lines_are() { |
| 1521 | 1× | let mut c = with_insert(sample_change(), big_lines(500)); |
| 1522 | 1× | c.edits.push(Edit::Insert { |
| 1523 | 1× | node: NodeId([8; 16]), |
| 1524 | 1× | after: AtomRef::Start, |
| 1525 | 1× | before: AtomRef::End, |
| 1526 | 1× | lines: vec![b"small\n".to_vec(), b"insert\n".to_vec()].into(), |
| 1527 | 1× | }); |
| 1528 | 1× | let (bytes, stored) = c.encode_parts(); |
| 1529 | 1× | let me = ObjectRef([4; 32]); |
| 1530 | 1× | let (skel, texts) = Change::decode_skeleton(&bytes, me).unwrap(); |
| 1531 | 1× | assert_eq!(texts.len(), 2); |
| 1532 | 1× | let mut filled = skel.clone(); |
| 1533 | 1× | let mut next = texts.iter(); |
| 1534 | 4× | for e in filled.edits.iter_mut() { |
| 1535 | 4× | if let Edit::Insert { lines, .. } = e { |
| 1536 | 2× | assert!(lines.is_empty(), "no line kept"); |
| 1537 | 2× | *lines = match next.next().unwrap() { |
| 1538 | 1× | TextRef::Blob(r, n, form) => { |
| 1539 | 1× | assert_eq!(*r, stored[0].blob.hash()); |
| 1540 | 1× | text_lines(&stored[0].content, *n, *form).unwrap() |
| 1541 | | } |
| 1542 | 1× | TextRef::Inline { change, start, end } => { |
| 1543 | 1× | assert_eq!(*change, me); |
| 1544 | 1× | inline_lines(&bytes[*start as usize..*end as usize]).unwrap() |
| 1545 | | } |
| 1546 | | }; |
| 1547 | 2× | } |
| 1548 | | } |
| 1549 | 1× | assert_eq!(filled, c, "filled in, it is the change"); |
| 1550 | | |
| 1551 | 1× | let mut v1 = with_insert(sample_change(), big_lines(500)); |
| 1552 | 1× | v1.version = 1; |
| 1553 | 1× | assert!(Change::decode_skeleton(&v1.encode(), me).is_ok()); |
| 1554 | 1× | let mut v = v1.to_value(); |
| 1555 | 1× | if let Value::Map(m) = &mut v { |
| 1556 | 1× | m.insert(0, Value::Uint(2)); |
| 1557 | 1× | } |
| 1558 | 1× | assert!(Change::decode_skeleton(&cbor::encode(&v), me).is_err()); |
| 1559 | 1× | } |
| 1560 | |
|
| 1561 | | #[test] |
| 1562 | 1× | fn metadata_reads_without_the_operations() { |
| 1563 | 1× | let c = with_insert(sample_change(), big_lines(500)); |
| 1564 | 1× | let (bytes, _) = c.encode_parts(); |
| 1565 | 1× | let m = Change::decode_meta(&bytes).unwrap(); |
| 1566 | 1× | assert_eq!(m, crate::state::ChangeMeta::of(&c)); |
| 1567 | 1× | } |
| 1568 | |
|
| 1569 | | #[test] |
| 1570 | 1× | fn text_blobs_are_checked() { |
| 1571 | 1× | let lines = big_lines(500); |
| 1572 | 1× | let content = cbor::encode_byte_strings(&lines); |
| 1573 | 1× | assert_eq!(content.len(), cbor::byte_strings_len(&lines)); |
| 1574 | 1× | assert_eq!( |
| 1575 | | content, |
| 1576 | 1× | cbor::encode(&Value::Array( |
| 1577 | 500× | lines.iter().map(|l| Value::Bytes(l.to_vec())).collect() |
| 1578 | | )) |
| 1579 | | ); |
| 1580 | 1× | assert_eq!(text_lines(&content, 500, TextForm::Cbor).unwrap(), lines); |
| 1581 | 1× | assert!(text_lines(&content, 499, TextForm::Cbor).is_err()); |
| 1582 | 1× | assert_eq!( |
| 1583 | 1× | text_lines(lines.bytes(), 500, TextForm::Raw).unwrap(), |
| 1584 | | lines |
| 1585 | | ); |
| 1586 | 1× | assert!(text_lines(lines.bytes(), 501, TextForm::Raw).is_err()); |
| 1587 | 1× | let small = cbor::encode_byte_strings(&vec![b"x\n".to_vec()].into()); |
| 1588 | 1× | assert!( |
| 1589 | 1× | text_lines(&small, 1, TextForm::Cbor).is_err(), |
| 1590 | | "short enough to be inline" |
| 1591 | | ); |
| 1592 | 1× | assert!( |
| 1593 | 1× | text_lines(b"x\n", 1, TextForm::Raw).is_err(), |
| 1594 | | "short enough to be inline" |
| 1595 | | ); |
| 1596 | 1× | } |
| 1597 | |
|
| 1598 | | #[test] |
| 1599 | 1× | fn names_are_validated() { |
| 1600 | 5× | for bad in ["", ".", "..", "a/b", "a\0b"] { |
| 1601 | 5× | assert!(validate_name(bad).is_err(), "{bad:?}"); |
| 1602 | | } |
| 1603 | 1× | assert!(validate_name("Foo.c").is_ok()); |
| 1604 | 1× | assert!(validate_name("...").is_ok()); |
| 1605 | 1× | } |
| 1606 | |
|
| 1607 | | #[test] |
| 1608 | 1× | fn mode_and_kind_tags() { |
| 1609 | 3× | for m in [ |
| 1610 | 1× | Mode::TEXT, |
| 1611 | 1× | Mode::OPAQUE, |
| 1612 | 1× | Mode { |
| 1613 | 1× | exec: true, |
| 1614 | 1× | opaque: true, |
| 1615 | 1× | }, |
| 1616 | 1× | ] { |
| 1617 | 3× | assert_eq!(Mode::from_bits(m.bits()).unwrap(), m); |
| 1618 | | } |
| 1619 | 1× | assert!(Mode::from_bits(4).is_err()); |
| 1620 | 4× | for k in [ |
| 1621 | 1× | NodeKind::File, |
| 1622 | 1× | NodeKind::Dir, |
| 1623 | 1× | NodeKind::Symlink, |
| 1624 | 1× | NodeKind::Subrepo, |
| 1625 | 1× | ] { |
| 1626 | 4× | assert_eq!(NodeKind::from_tag(k.tag()).unwrap(), k); |
| 1627 | | } |
| 1628 | 1× | } |
| 1629 | |
|
| 1630 | | #[test] |
| 1631 | 1× | fn self_references_resolve() { |
| 1632 | 1× | let me = ObjectRef([8; 32]); |
| 1633 | 1× | assert_eq!( |
| 1634 | 1× | AtomRef::Atom { |
| 1635 | 1× | change: ObjectRef::ZERO, |
| 1636 | 1× | index: 3 |
| 1637 | 1× | } |
| 1638 | 1× | .resolve(me), |
| 1639 | 1× | AtomRef::Atom { |
| 1640 | 1× | change: me, |
| 1641 | 1× | index: 3 |
| 1642 | 1× | } |
| 1643 | | ); |
| 1644 | 1× | assert_eq!(AtomRef::Start.resolve(me), AtomRef::Start); |
| 1645 | 1× | let other = ObjectRef([1; 32]); |
| 1646 | 1× | assert_eq!( |
| 1647 | 1× | OpRef { |
| 1648 | 1× | change: other, |
| 1649 | 1× | index: 1 |
| 1650 | 1× | } |
| 1651 | 1× | .resolve(me) |
| 1652 | | .change, |
| 1653 | | other |
| 1654 | | ); |
| 1655 | 1× | } |
| 1656 | |
|
| 1657 | | #[test] |
| 1658 | 1× | fn state_object_round_trip() { |
| 1659 | 1× | let st = StateObject::new(vec![ |
| 1660 | 1× | ObjectRef([2; 32]), |
| 1661 | 1× | ObjectRef([1; 32]), |
| 1662 | 1× | ObjectRef([2; 32]), |
| 1663 | | ]); |
| 1664 | 1× | assert_eq!(st.heads, vec![ObjectRef([1; 32]), ObjectRef([2; 32])]); |
| 1665 | 1× | assert_eq!(StateObject::decode(&st.encode()).unwrap(), st); |
| 1666 | 1× | assert_eq!(StateObject::new(vec![]).heads, vec![]); |
| 1667 | 1× | assert_ne!(StateObject::new(vec![]).hash(), st.hash()); |
| 1668 | 1× | } |
| 1669 | |
|
| 1670 | | #[test] |
| 1671 | 1× | fn blob_round_trip() { |
| 1672 | 1× | let b = Blob { |
| 1673 | 1× | length: 10, |
| 1674 | 1× | chunks: vec![ObjectRef([1; 32]), ObjectRef([2; 32])], |
| 1675 | 1× | }; |
| 1676 | 1× | assert_eq!(Blob::decode(&b.encode()).unwrap(), b); |
| 1677 | 1× | } |
| 1678 | | } |