| 1 | // SPDX-License-Identifier: Apache-2.0 |
| 2 | // Copyright (c) 2026 UtopiaIA |
| 3 | |
| 4 | //! Trees: one directory, stored as a single flat node or, when it is large, as |
| 5 | //! a balanced structure of nodes whose boundaries depend only on entry names. |
| 6 | //! |
| 7 | //! A directory with up to [`MAX_FLAT_ENTRIES`] entries is always one flat node. |
| 8 | //! A larger one is split into leaves and internal nodes: walking the sorted |
| 9 | //! entries, a node ends after an entry whose name hashes below a threshold |
| 10 | //! (once the node holds at least [`MIN_NODE_ENTRIES`]), or when it reaches |
| 11 | //! [`MAX_NODE_ENTRIES`]. The same set of entries therefore always gives the |
| 12 | //! same nodes and the same root id, whatever order it was edited in, and an |
| 13 | //! edit only touches the nodes on its path. |
| 14 | |
| 15 | use core::fmt; |
| 16 | |
| 17 | use crate::codec::{DecodeError, Reader, put_bytes, put_id, put_uv}; |
| 18 | use crate::id::{Kind, ObjectId}; |
| 19 | use crate::name::{NameError, forbidden_as_symlink, validate_name}; |
| 20 | |
| 21 | /// Format byte of every tree node. |
| 22 | pub const FORMAT: u8 = 1; |
| 23 | |
| 24 | /// A directory with at most this many entries is one flat node. |
| 25 | pub const MAX_FLAT_ENTRIES: usize = 1024; |
| 26 | |
| 27 | /// A node of a split directory only ends on a name boundary once it holds |
| 28 | /// at least this many entries or children. |
| 29 | pub const MIN_NODE_ENTRIES: usize = 32; |
| 30 | |
| 31 | /// A node of a split directory never holds more than this many entries or |
| 32 | /// children. |
| 33 | pub const MAX_NODE_ENTRIES: usize = 512; |
| 34 | |
| 35 | const SPLIT_CONTEXT: &str = "elffuss-braid 2026 tree-split v1"; |
| 36 | |
| 37 | /// One name in 128 ends a node: 2³² / 128. |
| 38 | const SPLIT_THRESHOLD: u32 = 1 << 25; |
| 39 | |
| 40 | const NODE_FLAT: u8 = 0; |
| 41 | const NODE_LEAF: u8 = 1; |
| 42 | const NODE_INTERNAL: u8 = 2; |
| 43 | |
| 44 | /// A git object id, kept for submodules (gitlinks). |
| 45 | #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] |
| 46 | pub enum GitId { |
| 47 | /// A SHA-1 id. |
| 48 | Sha1([u8; 20]), |
| 49 | /// A SHA-256 id. |
| 50 | Sha256([u8; 32]), |
| 51 | } |
| 52 | |
| 53 | impl GitId { |
| 54 | /// The raw id bytes. |
| 55 | pub fn as_bytes(&self) -> &[u8] { |
| 56 | match self { |
| 57 | GitId::Sha1(bytes) => bytes, |
| 58 | GitId::Sha256(bytes) => bytes, |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | pub(crate) fn encode(&self, out: &mut Vec<u8>) { |
| 63 | match self { |
| 64 | GitId::Sha1(bytes) => { |
| 65 | out.push(1); |
| 66 | out.extend_from_slice(bytes); |
| 67 | } |
| 68 | GitId::Sha256(bytes) => { |
| 69 | out.push(2); |
| 70 | out.extend_from_slice(bytes); |
| 71 | } |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | pub(crate) fn decode(reader: &mut Reader<'_>) -> Result<Self, DecodeError> { |
| 76 | let at = reader.position(); |
| 77 | match reader.u8()? { |
| 78 | 1 => Ok(GitId::Sha1(reader.array()?)), |
| 79 | 2 => Ok(GitId::Sha256(reader.array()?)), |
| 80 | _ => Err(DecodeError::Invalid { |
| 81 | at, |
| 82 | what: "git id algorithm", |
| 83 | }), |
| 84 | } |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | /// What a directory entry is. |
| 89 | #[derive(Clone, Debug, PartialEq, Eq, Hash)] |
| 90 | pub enum EntryKind { |
| 91 | /// A regular file. |
| 92 | File { blob: ObjectId, size: u64 }, |
| 93 | /// An executable file. |
| 94 | Executable { blob: ObjectId, size: u64 }, |
| 95 | /// A symlink; the blob holds its target. |
| 96 | Symlink { blob: ObjectId, size: u64 }, |
| 97 | /// A subdirectory. |
| 98 | Tree { tree: ObjectId }, |
| 99 | /// A git submodule, pinned to a commit of another repository. |
| 100 | Gitlink { commit: GitId }, |
| 101 | } |
| 102 | |
| 103 | impl EntryKind { |
| 104 | /// The one-byte code of this kind in the encoding. |
| 105 | pub const fn code(&self) -> u8 { |
| 106 | match self { |
| 107 | EntryKind::File { .. } => 0, |
| 108 | EntryKind::Executable { .. } => 1, |
| 109 | EntryKind::Symlink { .. } => 2, |
| 110 | EntryKind::Tree { .. } => 3, |
| 111 | EntryKind::Gitlink { .. } => 4, |
| 112 | } |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | /// One entry of a directory. |
| 117 | #[derive(Clone, Debug, PartialEq, Eq, Hash)] |
| 118 | pub struct Entry { |
| 119 | /// The entry's name, a single path component. |
| 120 | pub name: Vec<u8>, |
| 121 | /// What the entry is. |
| 122 | pub kind: EntryKind, |
| 123 | } |
| 124 | |
| 125 | impl Entry { |
| 126 | fn encode(&self, out: &mut Vec<u8>) { |
| 127 | put_bytes(out, &self.name); |
| 128 | out.push(self.kind.code()); |
| 129 | match &self.kind { |
| 130 | EntryKind::File { blob, size } |
| 131 | | EntryKind::Executable { blob, size } |
| 132 | | EntryKind::Symlink { blob, size } => { |
| 133 | put_id(out, blob); |
| 134 | put_uv(out, *size); |
| 135 | } |
| 136 | EntryKind::Tree { tree } => put_id(out, tree), |
| 137 | EntryKind::Gitlink { commit } => commit.encode(out), |
| 138 | } |
| 139 | } |
| 140 | |
| 141 | fn decode(reader: &mut Reader<'_>) -> Result<Self, TreeError> { |
| 142 | let name = reader.bytes()?.to_vec(); |
| 143 | let at = reader.position(); |
| 144 | let kind = match reader.u8()? { |
| 145 | 0 => EntryKind::File { |
| 146 | blob: reader.id()?, |
| 147 | size: reader.uv()?, |
| 148 | }, |
| 149 | 1 => EntryKind::Executable { |
| 150 | blob: reader.id()?, |
| 151 | size: reader.uv()?, |
| 152 | }, |
| 153 | 2 => EntryKind::Symlink { |
| 154 | blob: reader.id()?, |
| 155 | size: reader.uv()?, |
| 156 | }, |
| 157 | 3 => EntryKind::Tree { tree: reader.id()? }, |
| 158 | 4 => EntryKind::Gitlink { |
| 159 | commit: GitId::decode(reader)?, |
| 160 | }, |
| 161 | _ => { |
| 162 | return Err(TreeError::Decode(DecodeError::Invalid { |
| 163 | at, |
| 164 | what: "entry kind", |
| 165 | })); |
| 166 | } |
| 167 | }; |
| 168 | let entry = Entry { name, kind }; |
| 169 | validate_entry(&entry)?; |
| 170 | Ok(entry) |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | /// Smallest possible encoded entry: a 1-byte name, a kind and a SHA-1 gitlink. |
| 175 | const MIN_ENTRY_BYTES: usize = 1 + 1 + 1 + 1 + 20; |
| 176 | |
| 177 | /// Smallest possible encoded child reference. |
| 178 | const MIN_CHILD_BYTES: usize = 1 + 1 + 32 + 1; |
| 179 | |
| 180 | /// A reference from an internal node to the node below it. |
| 181 | #[derive(Clone, Debug, PartialEq, Eq, Hash)] |
| 182 | pub struct Child { |
| 183 | /// Name of the last entry under this child. |
| 184 | pub last_name: Vec<u8>, |
| 185 | /// Id of the child node. |
| 186 | pub node: ObjectId, |
| 187 | /// Number of entries under this child. |
| 188 | pub entry_count: u64, |
| 189 | } |
| 190 | |
| 191 | /// One encoded tree object. |
| 192 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 193 | pub enum Node { |
| 194 | /// A whole directory of at most [`MAX_FLAT_ENTRIES`] entries. |
| 195 | Flat(Vec<Entry>), |
| 196 | /// A run of entries of a split directory. |
| 197 | Leaf(Vec<Entry>), |
| 198 | /// A run of children of a split directory. |
| 199 | Internal { |
| 200 | /// 1 for the nodes just above the leaves. |
| 201 | level: u8, |
| 202 | /// The nodes below, in name order. |
| 203 | children: Vec<Child>, |
| 204 | }, |
| 205 | } |
| 206 | |
| 207 | /// Why a tree is not valid. |
| 208 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 209 | pub enum TreeError { |
| 210 | /// The bytes are not a canonical encoding. |
| 211 | Decode(DecodeError), |
| 212 | /// An entry name is not valid. |
| 213 | Name { name: Vec<u8>, error: NameError }, |
| 214 | /// A name that git or braid reads is a symlink. |
| 215 | SymlinkName(Vec<u8>), |
| 216 | /// Names are not strictly ascending; `index` is the first entry out of order. |
| 217 | Unsorted { index: usize }, |
| 218 | /// A node holds more entries or children than allowed, or none. |
| 219 | BadNodeSize { count: usize }, |
| 220 | /// A child reference covers no entries. |
| 221 | EmptyChild, |
| 222 | /// A node referenced by a split directory is missing. |
| 223 | MissingNode(ObjectId), |
| 224 | /// The nodes are well-formed but not the canonical split of their entries. |
| 225 | NotCanonical, |
| 226 | } |
| 227 | |
| 228 | impl fmt::Display for TreeError { |
| 229 | fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 230 | match self { |
| 231 | TreeError::Decode(err) => write!(f, "{err}"), |
| 232 | TreeError::Name { name, error } => { |
| 233 | write!(f, "entry {:?}: {error}", String::from_utf8_lossy(name)) |
| 234 | } |
| 235 | TreeError::SymlinkName(name) => write!( |
| 236 | f, |
| 237 | "entry {:?} must not be a symlink", |
| 238 | String::from_utf8_lossy(name) |
| 239 | ), |
| 240 | TreeError::Unsorted { index } => { |
| 241 | write!(f, "entry {index} is out of order or a duplicate") |
| 242 | } |
| 243 | TreeError::BadNodeSize { count } => write!(f, "node holds {count} items"), |
| 244 | TreeError::EmptyChild => f.write_str("child reference covers no entries"), |
| 245 | TreeError::MissingNode(id) => write!(f, "tree node {id} is missing"), |
| 246 | TreeError::NotCanonical => { |
| 247 | f.write_str("nodes are not the canonical split of the directory") |
| 248 | } |
| 249 | } |
| 250 | } |
| 251 | } |
| 252 | |
| 253 | impl std::error::Error for TreeError {} |
| 254 | |
| 255 | impl From<DecodeError> for TreeError { |
| 256 | fn from(err: DecodeError) -> Self { |
| 257 | TreeError::Decode(err) |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | /// Checks one entry on its own: its name, and the symlink restriction. |
| 262 | pub fn validate_entry(entry: &Entry) -> Result<(), TreeError> { |
| 263 | validate_name(&entry.name).map_err(|error| TreeError::Name { |
| 264 | name: entry.name.clone(), |
| 265 | error, |
| 266 | })?; |
| 267 | if matches!(entry.kind, EntryKind::Symlink { .. }) && forbidden_as_symlink(&entry.name) { |
| 268 | return Err(TreeError::SymlinkName(entry.name.clone())); |
| 269 | } |
| 270 | Ok(()) |
| 271 | } |
| 272 | |
| 273 | fn check_ascending<'a>(names: impl Iterator<Item = &'a [u8]>) -> Result<(), TreeError> { |
| 274 | let mut previous: Option<&[u8]> = None; |
| 275 | for (index, name) in names.enumerate() { |
| 276 | if previous.is_some_and(|p| p >= name) { |
| 277 | return Err(TreeError::Unsorted { index }); |
| 278 | } |
| 279 | previous = Some(name); |
| 280 | } |
| 281 | Ok(()) |
| 282 | } |
| 283 | |
| 284 | impl Node { |
| 285 | /// The canonical encoding. |
| 286 | pub fn encode(&self) -> Vec<u8> { |
| 287 | let mut out = vec![FORMAT]; |
| 288 | match self { |
| 289 | Node::Flat(entries) | Node::Leaf(entries) => { |
| 290 | out.push(if matches!(self, Node::Flat(_)) { |
| 291 | NODE_FLAT |
| 292 | } else { |
| 293 | NODE_LEAF |
| 294 | }); |
| 295 | put_uv(&mut out, entries.len() as u64); |
| 296 | for entry in entries { |
| 297 | entry.encode(&mut out); |
| 298 | } |
| 299 | } |
| 300 | Node::Internal { level, children } => { |
| 301 | out.push(NODE_INTERNAL); |
| 302 | out.push(*level); |
| 303 | put_uv(&mut out, children.len() as u64); |
| 304 | for child in children { |
| 305 | put_bytes(&mut out, &child.last_name); |
| 306 | put_id(&mut out, &child.node); |
| 307 | put_uv(&mut out, child.entry_count); |
| 308 | } |
| 309 | } |
| 310 | } |
| 311 | out |
| 312 | } |
| 313 | |
| 314 | /// The id of this node. |
| 315 | pub fn id(&self) -> ObjectId { |
| 316 | ObjectId::hash(Kind::Tree, &self.encode()) |
| 317 | } |
| 318 | |
| 319 | /// Decodes one node and checks everything that can be checked without |
| 320 | /// the other nodes of its directory. |
| 321 | pub fn decode(bytes: &[u8]) -> Result<Self, TreeError> { |
| 322 | let mut reader = Reader::new(bytes); |
| 323 | let at = reader.position(); |
| 324 | if reader.u8()? != FORMAT { |
| 325 | return Err(DecodeError::Invalid { |
| 326 | at, |
| 327 | what: "tree format", |
| 328 | } |
| 329 | .into()); |
| 330 | } |
| 331 | let at = reader.position(); |
| 332 | let node = match reader.u8()? { |
| 333 | node_type @ (NODE_FLAT | NODE_LEAF) => { |
| 334 | let count = reader.count(MIN_ENTRY_BYTES)?; |
| 335 | let limit = if node_type == NODE_FLAT { |
| 336 | MAX_FLAT_ENTRIES |
| 337 | } else { |
| 338 | MAX_NODE_ENTRIES |
| 339 | }; |
| 340 | if count > limit || (node_type == NODE_LEAF && count == 0) { |
| 341 | return Err(TreeError::BadNodeSize { count }); |
| 342 | } |
| 343 | let mut entries = Vec::with_capacity(count); |
| 344 | for _ in 0..count { |
| 345 | entries.push(Entry::decode(&mut reader)?); |
| 346 | } |
| 347 | check_ascending(entries.iter().map(|e| e.name.as_slice()))?; |
| 348 | if node_type == NODE_FLAT { |
| 349 | Node::Flat(entries) |
| 350 | } else { |
| 351 | Node::Leaf(entries) |
| 352 | } |
| 353 | } |
| 354 | NODE_INTERNAL => { |
| 355 | let level_at = reader.position(); |
| 356 | let level = reader.u8()?; |
| 357 | if level == 0 { |
| 358 | return Err(DecodeError::Invalid { |
| 359 | at: level_at, |
| 360 | what: "internal node level", |
| 361 | } |
| 362 | .into()); |
| 363 | } |
| 364 | let count = reader.count(MIN_CHILD_BYTES)?; |
| 365 | if count == 0 || count > MAX_NODE_ENTRIES { |
| 366 | return Err(TreeError::BadNodeSize { count }); |
| 367 | } |
| 368 | let mut children = Vec::with_capacity(count); |
| 369 | for _ in 0..count { |
| 370 | let last_name = reader.bytes()?.to_vec(); |
| 371 | validate_name(&last_name).map_err(|error| TreeError::Name { |
| 372 | name: last_name.clone(), |
| 373 | error, |
| 374 | })?; |
| 375 | let node = reader.id()?; |
| 376 | let entry_count = reader.uv()?; |
| 377 | if entry_count == 0 { |
| 378 | return Err(TreeError::EmptyChild); |
| 379 | } |
| 380 | children.push(Child { |
| 381 | last_name, |
| 382 | node, |
| 383 | entry_count, |
| 384 | }); |
| 385 | } |
| 386 | check_ascending(children.iter().map(|c| c.last_name.as_slice()))?; |
| 387 | Node::Internal { level, children } |
| 388 | } |
| 389 | _ => { |
| 390 | return Err(DecodeError::Invalid { |
| 391 | at, |
| 392 | what: "tree node type", |
| 393 | } |
| 394 | .into()); |
| 395 | } |
| 396 | }; |
| 397 | reader.finish()?; |
| 398 | Ok(node) |
| 399 | } |
| 400 | } |
| 401 | |
| 402 | /// The encoded nodes of one directory, children before parents. The last |
| 403 | /// node is the root, whose id is the directory's id. |
| 404 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 405 | pub struct Directory { |
| 406 | /// `(id, encoding)` of every node. |
| 407 | pub nodes: Vec<(ObjectId, Vec<u8>)>, |
| 408 | } |
| 409 | |
| 410 | impl Directory { |
| 411 | /// The id of the directory: the id of its root node. |
| 412 | pub fn root(&self) -> ObjectId { |
| 413 | self.nodes |
| 414 | .last() |
| 415 | .map(|(id, _)| *id) |
| 416 | .expect("a directory always has a root node") |
| 417 | } |
| 418 | } |
| 419 | |
| 420 | /// Whether a node ends after an item named `name` that makes its size `count`. |
| 421 | fn ends_node(level: u8, name: &[u8], count: usize) -> bool { |
| 422 | if count >= MAX_NODE_ENTRIES { |
| 423 | return true; |
| 424 | } |
| 425 | if count < MIN_NODE_ENTRIES { |
| 426 | return false; |
| 427 | } |
| 428 | let mut hasher = blake3::Hasher::new_derive_key(SPLIT_CONTEXT); |
| 429 | hasher.update(&[level]); |
| 430 | hasher.update(name); |
| 431 | let digest = hasher.finalize(); |
| 432 | let head = digest.as_bytes(); |
| 433 | u32::from_le_bytes([head[0], head[1], head[2], head[3]]) < SPLIT_THRESHOLD |
| 434 | } |
| 435 | |
| 436 | fn push_node(nodes: &mut Vec<(ObjectId, Vec<u8>)>, node: &Node) -> ObjectId { |
| 437 | let bytes = node.encode(); |
| 438 | let id = ObjectId::hash(Kind::Tree, &bytes); |
| 439 | nodes.push((id, bytes)); |
| 440 | id |
| 441 | } |
| 442 | |
| 443 | /// Builds the canonical nodes of a directory from its entries, in any order. |
| 444 | pub fn build_directory(mut entries: Vec<Entry>) -> Result<Directory, TreeError> { |
| 445 | entries.sort_by(|a, b| a.name.cmp(&b.name)); |
| 446 | check_ascending(entries.iter().map(|e| e.name.as_slice()))?; |
| 447 | for entry in &entries { |
| 448 | validate_entry(entry)?; |
| 449 | } |
| 450 | |
| 451 | let mut nodes = Vec::new(); |
| 452 | if entries.len() <= MAX_FLAT_ENTRIES { |
| 453 | push_node(&mut nodes, &Node::Flat(entries)); |
| 454 | return Ok(Directory { nodes }); |
| 455 | } |
| 456 | |
| 457 | // Leaves. |
| 458 | let total = entries.len(); |
| 459 | let mut children = Vec::new(); |
| 460 | let mut run = Vec::new(); |
| 461 | for (i, entry) in entries.into_iter().enumerate() { |
| 462 | let ends = ends_node(0, &entry.name, run.len() + 1); |
| 463 | run.push(entry); |
| 464 | if ends || i + 1 == total { |
| 465 | let last_name = run |
| 466 | .last() |
| 467 | .map(|e: &Entry| e.name.clone()) |
| 468 | .unwrap_or_default(); |
| 469 | let entry_count = run.len() as u64; |
| 470 | let node = push_node(&mut nodes, &Node::Leaf(core::mem::take(&mut run))); |
| 471 | children.push(Child { |
| 472 | last_name, |
| 473 | node, |
| 474 | entry_count, |
| 475 | }); |
| 476 | } |
| 477 | } |
| 478 | |
| 479 | // Internal levels, until one node is left. |
| 480 | let mut level = 1u8; |
| 481 | while children.len() > 1 { |
| 482 | let total = children.len(); |
| 483 | let mut parents = Vec::new(); |
| 484 | let mut run: Vec<Child> = Vec::new(); |
| 485 | for (i, child) in children.into_iter().enumerate() { |
| 486 | let ends = ends_node(level, &child.last_name, run.len() + 1); |
| 487 | run.push(child); |
| 488 | if ends || i + 1 == total { |
| 489 | let last_name = run.last().map(|c| c.last_name.clone()).unwrap_or_default(); |
| 490 | let entry_count = run.iter().map(|c| c.entry_count).sum(); |
| 491 | let node = push_node( |
| 492 | &mut nodes, |
| 493 | &Node::Internal { |
| 494 | level, |
| 495 | children: core::mem::take(&mut run), |
| 496 | }, |
| 497 | ); |
| 498 | parents.push(Child { |
| 499 | last_name, |
| 500 | node, |
| 501 | entry_count, |
| 502 | }); |
| 503 | } |
| 504 | } |
| 505 | children = parents; |
| 506 | level += 1; |
| 507 | } |
| 508 | Ok(Directory { nodes }) |
| 509 | } |
| 510 | |
| 511 | /// Reads every entry of the directory rooted at `root`, fetching nodes through |
| 512 | /// `fetch`, and checks that the nodes are exactly the canonical split of those |
| 513 | /// entries. |
| 514 | pub fn read_directory( |
| 515 | root: ObjectId, |
| 516 | mut fetch: impl FnMut(&ObjectId) -> Option<Vec<u8>>, |
| 517 | ) -> Result<Vec<Entry>, TreeError> { |
| 518 | let mut entries = Vec::new(); |
| 519 | collect(root, &mut fetch, &mut entries, None)?; |
| 520 | if build_directory(entries.clone())?.root() != root { |
| 521 | return Err(TreeError::NotCanonical); |
| 522 | } |
| 523 | Ok(entries) |
| 524 | } |
| 525 | |
| 526 | fn collect( |
| 527 | id: ObjectId, |
| 528 | fetch: &mut impl FnMut(&ObjectId) -> Option<Vec<u8>>, |
| 529 | entries: &mut Vec<Entry>, |
| 530 | expected_level: Option<u8>, |
| 531 | ) -> Result<(), TreeError> { |
| 532 | let bytes = fetch(&id).ok_or(TreeError::MissingNode(id))?; |
| 533 | if ObjectId::hash(Kind::Tree, &bytes) != id { |
| 534 | return Err(TreeError::NotCanonical); |
| 535 | } |
| 536 | match (Node::decode(&bytes)?, expected_level) { |
| 537 | (Node::Flat(found), None) => entries.extend(found), |
| 538 | (Node::Leaf(found), Some(0)) => entries.extend(found), |
| 539 | (Node::Internal { level, children }, expected) if expected.is_none_or(|e| e == level) => { |
| 540 | for child in children { |
| 541 | collect(child.node, fetch, entries, Some(level - 1))?; |
| 542 | } |
| 543 | } |
| 544 | _ => return Err(TreeError::NotCanonical), |
| 545 | } |
| 546 | Ok(()) |
| 547 | } |
| 548 | |
| 549 | #[cfg(test)] |
| 550 | mod tests { |
| 551 | use super::*; |
| 552 | |
| 553 | fn blob(text: &str) -> ObjectId { |
| 554 | ObjectId::hash(Kind::Blob, text.as_bytes()) |
| 555 | } |
| 556 | |
| 557 | fn file(name: &str, text: &str) -> Entry { |
| 558 | Entry { |
| 559 | name: name.as_bytes().to_vec(), |
| 560 | kind: EntryKind::File { |
| 561 | blob: blob(text), |
| 562 | size: text.len() as u64, |
| 563 | }, |
| 564 | } |
| 565 | } |
| 566 | |
| 567 | fn many(n: usize, content: &str) -> Vec<Entry> { |
| 568 | (0..n).map(|i| file(&format!("f{i:05}"), content)).collect() |
| 569 | } |
| 570 | |
| 571 | #[test] |
| 572 | fn empty_tree() { |
| 573 | let dir = build_directory(Vec::new()).unwrap(); |
| 574 | assert_eq!(dir.nodes.len(), 1); |
| 575 | assert_eq!(dir.nodes[0].1, vec![FORMAT, NODE_FLAT, 0]); |
| 576 | assert_eq!( |
| 577 | dir.root().to_hex(), |
| 578 | "3136b0f18562ee73b840ea348c54ae3c7e97e4cc3e547ea9dd03fa1cd8b384cf", |
| 579 | "the empty tree id is part of format v1" |
| 580 | ); |
| 581 | } |
| 582 | |
| 583 | #[test] |
| 584 | fn small_tree_golden() { |
| 585 | let entries = vec![ |
| 586 | file("README.md", "hello\n"), |
| 587 | Entry { |
| 588 | name: b"run.sh".to_vec(), |
| 589 | kind: EntryKind::Executable { |
| 590 | blob: blob("#!/bin/sh\n"), |
| 591 | size: 10, |
| 592 | }, |
| 593 | }, |
| 594 | Entry { |
| 595 | name: b"latest".to_vec(), |
| 596 | kind: EntryKind::Symlink { |
| 597 | blob: blob("README.md"), |
| 598 | size: 9, |
| 599 | }, |
| 600 | }, |
| 601 | Entry { |
| 602 | name: b"src".to_vec(), |
| 603 | kind: EntryKind::Tree { |
| 604 | tree: build_directory(Vec::new()).unwrap().root(), |
| 605 | }, |
| 606 | }, |
| 607 | Entry { |
| 608 | name: b"vendor".to_vec(), |
| 609 | kind: EntryKind::Gitlink { |
| 610 | commit: GitId::Sha1([0x11; 20]), |
| 611 | }, |
| 612 | }, |
| 613 | ]; |
| 614 | let dir = build_directory(entries).unwrap(); |
| 615 | assert_eq!(dir.nodes.len(), 1); |
| 616 | assert_eq!( |
| 617 | dir.root().to_hex(), |
| 618 | "a6c6d54bb7663d576e8f7a702e0670927e22098d6c15c10475e06b51dc3d8c1b" |
| 619 | ); |
| 620 | } |
| 621 | |
| 622 | #[test] |
| 623 | fn flat_up_to_the_limit_then_split() { |
| 624 | let flat = build_directory(many(MAX_FLAT_ENTRIES, "x")).unwrap(); |
| 625 | assert_eq!(flat.nodes.len(), 1); |
| 626 | assert!(matches!( |
| 627 | Node::decode(&flat.nodes[0].1).unwrap(), |
| 628 | Node::Flat(_) |
| 629 | )); |
| 630 | |
| 631 | let split = build_directory(many(MAX_FLAT_ENTRIES + 1, "x")).unwrap(); |
| 632 | assert!(split.nodes.len() >= 3); |
| 633 | assert!(matches!( |
| 634 | Node::decode(&split.nodes.last().unwrap().1).unwrap(), |
| 635 | Node::Internal { .. } |
| 636 | )); |
| 637 | } |
| 638 | |
| 639 | #[test] |
| 640 | fn large_tree_golden() { |
| 641 | let dir = build_directory(many(5000, "x")).unwrap(); |
| 642 | assert_eq!( |
| 643 | dir.root().to_hex(), |
| 644 | "2c88a412664c1fd862c3487e1313a045a20fe4f7bdeaf1bb71e08564edc7dcce" |
| 645 | ); |
| 646 | assert_eq!(dir.nodes.len(), LARGE_TREE_NODES); |
| 647 | } |
| 648 | |
| 649 | const LARGE_TREE_NODES: usize = 30; |
| 650 | |
| 651 | #[test] |
| 652 | fn read_back_and_reject_non_canonical_splits() { |
| 653 | let entries = many(3000, "x"); |
| 654 | let dir = build_directory(entries.clone()).unwrap(); |
| 655 | let store: std::collections::HashMap<ObjectId, Vec<u8>> = |
| 656 | dir.nodes.iter().cloned().collect(); |
| 657 | let read = read_directory(dir.root(), |id| store.get(id).cloned()).unwrap(); |
| 658 | assert_eq!(read, entries); |
| 659 | |
| 660 | // The same entries packed into one oversized flat node are refused. |
| 661 | let fake = Node::Flat(entries.clone()); |
| 662 | let bytes = fake.encode(); |
| 663 | assert!(matches!( |
| 664 | Node::decode(&bytes), |
| 665 | Err(TreeError::BadNodeSize { .. }) |
| 666 | )); |
| 667 | |
| 668 | // Two leaves split at the wrong place, under a hand-made root. |
| 669 | let left = Node::Leaf(entries[..100].to_vec()); |
| 670 | let right = Node::Leaf(entries[100..500].to_vec()); |
| 671 | let root = Node::Internal { |
| 672 | level: 1, |
| 673 | children: vec![ |
| 674 | Child { |
| 675 | last_name: entries[99].name.clone(), |
| 676 | node: left.id(), |
| 677 | entry_count: 100, |
| 678 | }, |
| 679 | Child { |
| 680 | last_name: entries[499].name.clone(), |
| 681 | node: right.id(), |
| 682 | entry_count: 400, |
| 683 | }, |
| 684 | ], |
| 685 | }; |
| 686 | let store: std::collections::HashMap<ObjectId, Vec<u8>> = [&left, &right, &root] |
| 687 | .iter() |
| 688 | .map(|n| (n.id(), n.encode())) |
| 689 | .collect(); |
| 690 | assert_eq!( |
| 691 | read_directory(root.id(), |id| store.get(id).cloned()), |
| 692 | Err(TreeError::NotCanonical) |
| 693 | ); |
| 694 | } |
| 695 | |
| 696 | #[test] |
| 697 | fn decode_rejects_bad_input() { |
| 698 | let unsorted = Node::Flat(vec![file("b", "1"), file("a", "2")]).encode(); |
| 699 | assert_eq!( |
| 700 | Node::decode(&unsorted), |
| 701 | Err(TreeError::Unsorted { index: 1 }) |
| 702 | ); |
| 703 | let duplicate = Node::Flat(vec![file("a", "1"), file("a", "2")]).encode(); |
| 704 | assert_eq!( |
| 705 | Node::decode(&duplicate), |
| 706 | Err(TreeError::Unsorted { index: 1 }) |
| 707 | ); |
| 708 | let reserved = Node::Flat(vec![file(".GIT", "1")]).encode(); |
| 709 | assert!(matches!( |
| 710 | Node::decode(&reserved), |
| 711 | Err(TreeError::Name { .. }) |
| 712 | )); |
| 713 | let symlink = Node::Flat(vec![Entry { |
| 714 | name: b".gitmodules".to_vec(), |
| 715 | kind: EntryKind::Symlink { |
| 716 | blob: blob("x"), |
| 717 | size: 1, |
| 718 | }, |
| 719 | }]) |
| 720 | .encode(); |
| 721 | assert!(matches!( |
| 722 | Node::decode(&symlink), |
| 723 | Err(TreeError::SymlinkName(_)) |
| 724 | )); |
| 725 | let mut trailing = Node::Flat(vec![file("a", "1")]).encode(); |
| 726 | trailing.push(0); |
| 727 | assert!(matches!( |
| 728 | Node::decode(&trailing), |
| 729 | Err(TreeError::Decode(DecodeError::TrailingBytes { .. })) |
| 730 | )); |
| 731 | assert!(Node::decode(&[]).is_err()); |
| 732 | assert!(Node::decode(&[2, 0, 0]).is_err()); |
| 733 | assert!(Node::decode(&[FORMAT, 9]).is_err()); |
| 734 | assert!(Node::decode(&[FORMAT, NODE_LEAF, 0]).is_err()); |
| 735 | assert!(Node::decode(&[FORMAT, NODE_INTERNAL, 0, 0]).is_err()); |
| 736 | } |
| 737 | } |