Elffuss BraidHub

utopia-ia/elffuss-braid public

main · 27.5 KiBRawPermalink
1// SPDX-License-Identifier: Apache-2.0
2// Copyright (c) 2026 UtopiaIA
3
4//! The two-way mapping between git objects and braid objects.
5//!
6//! Every imported git object has a braid counterpart: a commit has a
7//! changeset, a tree a braid tree, a blob a braid blob, and an annotated tag
8//! the blob holding its raw bytes. The map records both directions, plus the
9//! raw bytes of the git trees that cannot be regenerated from their braid
10//! tree. Objects made in braid enter the map when they are exported, so that
11//! importing them back gives the same braid objects. It is derived data:
12//! importing the same repository again, and exporting the same changesets
13//! again, rebuilds it.
14
15use std::collections::hash_map::Entry;
16use std::collections::{BTreeMap, HashMap};
17
18use braid_format::codec::{Reader, put_bytes, put_id, put_uv};
19use braid_format::{DecodeError, ObjectId};
20
21use crate::oid::{GitKind, GitOid};
22
23/// What the map records about an annotated tag object.
24#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
25pub struct TagEntry {
26 /// The braid blob holding the tag's raw bytes.
27 pub raw: ObjectId,
28 /// The object the tag points to.
29 pub target: GitOid,
30 /// The kind of that object.
31 pub target_kind: GitKind,
32}
33
34/// What one insert added to a map, with what it replaced: enough to take it
35/// back with [`GitMap::take_back`].
36#[derive(Clone, Copy, Debug, PartialEq, Eq)]
37pub(crate) enum Added {
38 Commit {
39 commit: GitOid,
40 changeset: ObjectId,
41 /// The commit the changeset mapped back to before, if any.
42 replaced: Option<GitOid>,
43 },
44 Tree {
45 tree: GitOid,
46 braid: ObjectId,
47 /// Whether the tree became the canonical tree of its braid tree.
48 canonical: bool,
49 },
50 Blob {
51 blob: GitOid,
52 braid: ObjectId,
53 /// The git blob the braid blob mapped back to before, if any.
54 replaced: Option<GitOid>,
55 },
56}
57
58/// Puts back the value `key` had before an insert replaced it, or removes it.
59fn restore<K: core::hash::Hash + Eq, V>(map: &mut HashMap<K, V>, key: K, before: Option<V>) {
60 match before {
61 Some(value) => {
62 map.insert(key, value);
63 }
64 None => {
65 map.remove(&key);
66 }
67 }
68}
69
70/// How many objects of each kind a map holds, or an operation added to it.
71#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
72pub struct MapCounts {
73 /// Commits.
74 pub commits: usize,
75 /// Trees, raw or not.
76 pub trees: usize,
77 /// Trees kept as raw bytes.
78 pub raw_trees: usize,
79 /// Blobs.
80 pub blobs: usize,
81 /// Annotated tag objects.
82 pub tags: usize,
83 /// Tag names.
84 pub tag_names: usize,
85}
86
87/// Git objects an export generated and the braid objects they come from:
88/// the commits of changesets, canonical trees, and blobs. Each list is
89/// sorted by git id.
90///
91/// [`Exporter::pairings`](crate::Exporter::pairings) collects them and
92/// [`GitMap::record`] adds them to a map. Exports are deterministic, so a
93/// pairing stays true wherever the git object goes: a commit that comes back
94/// from a remote is the export of its changeset, and importing it must give
95/// that changeset rather than a second one.
96#[derive(Clone, Debug, Default, PartialEq, Eq)]
97pub struct Pairings {
98 pub(crate) commits: Vec<(GitOid, ObjectId)>,
99 pub(crate) trees: Vec<(GitOid, ObjectId)>,
100 pub(crate) blobs: Vec<(GitOid, ObjectId, u64)>,
101}
102
103impl Pairings {
104 /// Each commit and the changeset it was exported from.
105 pub fn commits(&self) -> &[(GitOid, ObjectId)] {
106 &self.commits
107 }
108
109 /// Each git tree and the braid tree it is the canonical export of.
110 pub fn trees(&self) -> &[(GitOid, ObjectId)] {
111 &self.trees
112 }
113
114 /// Each git blob, its braid blob, and its size.
115 pub fn blobs(&self) -> &[(GitOid, ObjectId, u64)] {
116 &self.blobs
117 }
118
119 /// Whether there are no pairings.
120 pub fn is_empty(&self) -> bool {
121 self.commits.is_empty() && self.trees.is_empty() && self.blobs.is_empty()
122 }
123}
124
125/// The two-way mapping between imported git objects and braid objects.
126///
127/// - **Commits** map one to one to changesets.
128/// - **Trees**: every git tree maps to one braid tree. A git tree is
129/// *canonical* when exporting its braid tree gives it back byte for byte; a
130/// braid tree has at most one canonical git tree, which is its reverse
131/// mapping. A git tree that is not canonical (a mode such as `100664`,
132/// unsorted or duplicate entries, or a subtree that is itself not canonical)
133/// keeps its raw bytes in a blob, keyed by its git id: several git trees can
134/// share one braid tree, so the git id is what tells them apart.
135/// - **Blobs** map one to one, with the size of the content.
136/// - **Tags**: an annotated tag maps to the blob with its raw bytes, and
137/// records its target. Tag names map to the tag object they point to.
138///
139/// [`to_bytes`](Self::to_bytes) and [`from_bytes`](Self::from_bytes) give a
140/// versioned, canonical encoding, so the store can keep the map as a derived
141/// record.
142#[derive(Clone, Debug, Default, PartialEq, Eq)]
143pub struct GitMap {
144 commits: HashMap<GitOid, ObjectId>,
145 changesets: HashMap<ObjectId, GitOid>,
146 trees: HashMap<GitOid, ObjectId>,
147 canonical_trees: HashMap<ObjectId, GitOid>,
148 raw_trees: HashMap<GitOid, ObjectId>,
149 blobs: HashMap<GitOid, (ObjectId, u64)>,
150 git_blobs: HashMap<ObjectId, GitOid>,
151 tags: HashMap<GitOid, TagEntry>,
152 tag_blobs: HashMap<ObjectId, GitOid>,
153 tag_names: BTreeMap<Vec<u8>, GitOid>,
154}
155
156impl GitMap {
157 /// An empty map.
158 pub fn new() -> Self {
159 Self::default()
160 }
161
162 /// The changeset imported from a commit.
163 pub fn changeset(&self, commit: &GitOid) -> Option<ObjectId> {
164 self.commits.get(commit).copied()
165 }
166
167 /// The commit a changeset was imported from.
168 pub fn commit(&self, changeset: &ObjectId) -> Option<GitOid> {
169 self.changesets.get(changeset).copied()
170 }
171
172 /// The braid tree of a git tree.
173 pub fn tree(&self, tree: &GitOid) -> Option<ObjectId> {
174 self.trees.get(tree).copied()
175 }
176
177 /// The canonical git tree of a braid tree, if one was imported.
178 pub fn git_tree(&self, tree: &ObjectId) -> Option<GitOid> {
179 self.canonical_trees.get(tree).copied()
180 }
181
182 /// The blob holding the raw bytes of a git tree that is not canonical.
183 pub fn raw_tree(&self, tree: &GitOid) -> Option<ObjectId> {
184 self.raw_trees.get(tree).copied()
185 }
186
187 /// The braid blob of a git blob, and its size.
188 pub fn blob(&self, blob: &GitOid) -> Option<(ObjectId, u64)> {
189 self.blobs.get(blob).copied()
190 }
191
192 /// The git blob of a braid blob.
193 pub fn git_blob(&self, blob: &ObjectId) -> Option<GitOid> {
194 self.git_blobs.get(blob).copied()
195 }
196
197 /// What the map knows about an annotated tag object.
198 pub fn tag(&self, tag: &GitOid) -> Option<TagEntry> {
199 self.tags.get(tag).copied()
200 }
201
202 /// The tag object whose raw bytes are in this braid blob.
203 pub fn git_tag(&self, raw: &ObjectId) -> Option<GitOid> {
204 self.tag_blobs.get(raw).copied()
205 }
206
207 /// The annotated tag a tag name points to, by its full ref name such as
208 /// `refs/tags/v1.0`, with what the map knows about it.
209 pub fn tag_by_name(&self, name: &[u8]) -> Option<(GitOid, TagEntry)> {
210 let oid = *self.tag_names.get(name)?;
211 Some((oid, self.tags.get(&oid).copied()?))
212 }
213
214 /// Every tag name and the annotated tag it points to, in name order.
215 pub fn tag_names(&self) -> impl Iterator<Item = (&[u8], GitOid)> + '_ {
216 self.tag_names
217 .iter()
218 .map(|(name, oid)| (name.as_slice(), *oid))
219 }
220
221 /// Every commit and its changeset, in no particular order.
222 pub fn commits(&self) -> impl Iterator<Item = (GitOid, ObjectId)> + '_ {
223 self.commits.iter().map(|(oid, id)| (*oid, *id))
224 }
225
226 /// How many objects of each kind the map holds.
227 pub fn counts(&self) -> MapCounts {
228 MapCounts {
229 commits: self.commits.len(),
230 trees: self.trees.len(),
231 raw_trees: self.raw_trees.len(),
232 blobs: self.blobs.len(),
233 tags: self.tags.len(),
234 tag_names: self.tag_names.len(),
235 }
236 }
237
238 /// Adds the pairings an export computed, and returns how many of each
239 /// kind were new.
240 ///
241 /// The map stays one to one: a pairing is left out when the map already
242 /// maps either of its objects, and a tree when its braid tree already has
243 /// a canonical git tree. What the map knows wins.
244 pub fn record(&mut self, pairings: &Pairings) -> MapCounts {
245 let mut added = MapCounts::default();
246 for (commit, changeset) in &pairings.commits {
247 if self.add_commit(*commit, *changeset) {
248 added.commits += 1;
249 }
250 }
251 for (tree, braid) in &pairings.trees {
252 if self.add_tree(*tree, *braid, None) {
253 added.trees += 1;
254 }
255 }
256 for (blob, braid, size) in &pairings.blobs {
257 if self.add_blob(*blob, *braid, *size) {
258 added.blobs += 1;
259 }
260 }
261 added
262 }
263
264 /// Adds every entry of `other` that this map lacks, such as what another
265 /// process recorded since this map was read, and returns how many of each
266 /// kind were new. As in [`record`](Self::record), what this map knows
267 /// wins wherever the two disagree, so the result is still one to one.
268 pub fn absorb(&mut self, other: &GitMap) -> MapCounts {
269 let mut added = MapCounts::default();
270 for (commit, changeset) in &other.commits {
271 if self.add_commit(*commit, *changeset) {
272 added.commits += 1;
273 }
274 }
275 for (tree, braid) in &other.trees {
276 let raw = other.raw_trees.get(tree).copied();
277 if self.add_tree(*tree, *braid, raw) {
278 added.trees += 1;
279 if raw.is_some() {
280 added.raw_trees += 1;
281 }
282 }
283 }
284 for (blob, (braid, size)) in &other.blobs {
285 if self.add_blob(*blob, *braid, *size) {
286 added.blobs += 1;
287 }
288 }
289 for (tag, entry) in &other.tags {
290 if !self.tags.contains_key(tag) && !self.tag_blobs.contains_key(&entry.raw) {
291 self.insert_tag(*tag, *entry);
292 added.tags += 1;
293 }
294 }
295 for (name, tag) in &other.tag_names {
296 if !self.tag_names.contains_key(name) && self.tags.contains_key(tag) {
297 self.set_tag_name(name.clone(), *tag);
298 added.tag_names += 1;
299 }
300 }
301 added
302 }
303
304 /// Inserts a commit unless either side is mapped already.
305 fn add_commit(&mut self, commit: GitOid, changeset: ObjectId) -> bool {
306 if self.commits.contains_key(&commit) || self.changesets.contains_key(&changeset) {
307 return false;
308 }
309 self.insert_commit(commit, changeset);
310 true
311 }
312
313 /// Inserts a tree unless it is mapped already, or it would be a second
314 /// canonical tree for its braid tree.
315 fn add_tree(&mut self, tree: GitOid, braid: ObjectId, raw: Option<ObjectId>) -> bool {
316 if self.trees.contains_key(&tree)
317 || (raw.is_none() && self.canonical_trees.contains_key(&braid))
318 {
319 return false;
320 }
321 self.insert_tree(tree, braid, raw);
322 true
323 }
324
325 /// Inserts a blob unless either side is mapped already.
326 fn add_blob(&mut self, blob: GitOid, braid: ObjectId, size: u64) -> bool {
327 if self.blobs.contains_key(&blob) || self.git_blobs.contains_key(&braid) {
328 return false;
329 }
330 self.insert_blob(blob, braid, size);
331 true
332 }
333
334 /// Records a commit that the map does not hold yet.
335 pub(crate) fn insert_commit(&mut self, commit: GitOid, changeset: ObjectId) -> Added {
336 let replaced = self.changesets.insert(changeset, commit);
337 let previous = self.commits.insert(commit, changeset);
338 debug_assert!(previous.is_none(), "commit {commit} is mapped already");
339 Added::Commit {
340 commit,
341 changeset,
342 replaced,
343 }
344 }
345
346 /// Records a git tree that the map does not hold yet. `raw` is the blob
347 /// with its bytes when it is not canonical.
348 pub(crate) fn insert_tree(
349 &mut self,
350 tree: GitOid,
351 braid: ObjectId,
352 raw: Option<ObjectId>,
353 ) -> Added {
354 let previous = self.trees.insert(tree, braid);
355 debug_assert!(previous.is_none(), "tree {tree} is mapped already");
356 let mut canonical = false;
357 match raw {
358 Some(blob) => {
359 self.raw_trees.insert(tree, blob);
360 }
361 None => {
362 if let Entry::Vacant(vacant) = self.canonical_trees.entry(braid) {
363 vacant.insert(tree);
364 canonical = true;
365 }
366 }
367 }
368 Added::Tree {
369 tree,
370 braid,
371 canonical,
372 }
373 }
374
375 /// Records a blob that the map does not hold yet.
376 pub(crate) fn insert_blob(&mut self, blob: GitOid, braid: ObjectId, size: u64) -> Added {
377 let previous = self.blobs.insert(blob, (braid, size));
378 debug_assert!(previous.is_none(), "blob {blob} is mapped already");
379 let replaced = self.git_blobs.insert(braid, blob);
380 Added::Blob {
381 blob,
382 braid,
383 replaced,
384 }
385 }
386
387 /// Takes back what one insert added, given what it returned. Taking back
388 /// the inserts since some point, the last one first, gives back the map
389 /// as it was at that point.
390 pub(crate) fn take_back(&mut self, added: &Added) {
391 match *added {
392 Added::Commit {
393 commit,
394 changeset,
395 replaced,
396 } => {
397 self.commits.remove(&commit);
398 restore(&mut self.changesets, changeset, replaced);
399 }
400 Added::Tree {
401 tree,
402 braid,
403 canonical,
404 } => {
405 self.trees.remove(&tree);
406 self.raw_trees.remove(&tree);
407 if canonical {
408 self.canonical_trees.remove(&braid);
409 }
410 }
411 Added::Blob {
412 blob,
413 braid,
414 replaced,
415 } => {
416 self.blobs.remove(&blob);
417 restore(&mut self.git_blobs, braid, replaced);
418 }
419 }
420 }
421
422 pub(crate) fn insert_tag(&mut self, tag: GitOid, entry: TagEntry) {
423 self.tags.insert(tag, entry);
424 self.tag_blobs.insert(entry.raw, tag);
425 }
426
427 pub(crate) fn set_tag_name(&mut self, name: Vec<u8>, tag: GitOid) {
428 self.tag_names.insert(name, tag);
429 }
430
431 pub(crate) fn remove_tag_name(&mut self, name: &[u8]) {
432 self.tag_names.remove(name);
433 }
434
435 /// The canonical encoding: a magic string and a version, then each table
436 /// sorted by key.
437 ///
438 /// ```text
439 /// "braid-git-map" u8 version = 1
440 /// uv n, n × ([20] commit, [32] changeset)
441 /// uv n, n × ([20] tree, [32] braid tree)
442 /// uv n, n × ([20] tree, [32] blob with its raw bytes)
443 /// uv n, n × ([20] blob, [32] braid blob, uv size)
444 /// uv n, n × ([20] tag, [32] blob with its raw bytes, [20] target, u8 target kind)
445 /// uv n, n × (bytes name, [20] tag)
446 /// ```
447 ///
448 /// Target kinds are 1 commit, 2 tree, 3 blob, 4 tag.
449 pub fn to_bytes(&self) -> Vec<u8> {
450 let mut out = Vec::new();
451 out.extend_from_slice(MAGIC);
452 out.push(VERSION);
453 put_table(&mut out, &self.commits, put_id);
454 put_table(&mut out, &self.trees, put_id);
455 put_table(&mut out, &self.raw_trees, put_id);
456 put_table(&mut out, &self.blobs, |out, (id, size)| {
457 put_id(out, id);
458 put_uv(out, *size);
459 });
460 put_table(&mut out, &self.tags, |out, entry| {
461 put_id(out, &entry.raw);
462 out.extend_from_slice(entry.target.as_bytes());
463 out.push(entry.target_kind.code());
464 });
465 put_uv(&mut out, self.tag_names.len() as u64);
466 for (name, oid) in &self.tag_names {
467 put_bytes(&mut out, name);
468 out.extend_from_slice(oid.as_bytes());
469 }
470 out
471 }
472
473 /// Decodes [`to_bytes`](Self::to_bytes), checking that the encoding is
474 /// canonical and that the tables agree with each other.
475 pub fn from_bytes(bytes: &[u8]) -> Result<Self, DecodeError> {
476 let mut reader = Reader::new(bytes);
477 let at = reader.position();
478 if reader.take(MAGIC.len())? != MAGIC {
479 return Err(invalid(at, "git map magic"));
480 }
481 let at = reader.position();
482 if reader.u8()? != VERSION {
483 return Err(invalid(at, "git map version"));
484 }
485 let mut map = GitMap::new();
486 for (oid, id) in read_table(&mut reader, 32, |r| r.id())? {
487 if map.changesets.insert(id, oid).is_some() {
488 return Err(invalid(reader.position(), "changeset mapped twice"));
489 }
490 map.commits.insert(oid, id);
491 }
492 map.trees = read_table(&mut reader, 32, |r| r.id())?
493 .into_iter()
494 .collect();
495 for (oid, blob) in read_table(&mut reader, 32, |r| r.id())? {
496 if !map.trees.contains_key(&oid) {
497 return Err(invalid(reader.position(), "raw tree that is not a tree"));
498 }
499 map.raw_trees.insert(oid, blob);
500 }
501 for (oid, braid) in &map.trees {
502 if !map.raw_trees.contains_key(oid)
503 && map.canonical_trees.insert(*braid, *oid).is_some()
504 {
505 return Err(invalid(
506 reader.position(),
507 "two canonical trees for one tree",
508 ));
509 }
510 }
511 for (oid, (id, size)) in read_table(&mut reader, 33, |r| Ok((r.id()?, r.uv()?)))? {
512 if map.git_blobs.insert(id, oid).is_some() {
513 return Err(invalid(reader.position(), "blob mapped twice"));
514 }
515 map.blobs.insert(oid, (id, size));
516 }
517 let tags = read_table(&mut reader, 53, |r| {
518 let raw = r.id()?;
519 let target = GitOid::from_bytes(r.array()?);
520 let at = r.position();
521 let target_kind = GitKind::from_code(r.u8()?).ok_or(invalid(at, "tag target kind"))?;
522 Ok(TagEntry {
523 raw,
524 target,
525 target_kind,
526 })
527 })?;
528 for (oid, entry) in tags {
529 if map.tag_blobs.insert(entry.raw, oid).is_some() {
530 return Err(invalid(reader.position(), "tag mapped twice"));
531 }
532 map.tags.insert(oid, entry);
533 }
534 let count = reader.count(1 + GitOid::LEN)?;
535 let mut previous: Option<Vec<u8>> = None;
536 for _ in 0..count {
537 let at = reader.position();
538 let name = reader.bytes()?.to_vec();
539 let oid = GitOid::from_bytes(reader.array()?);
540 if previous.as_ref().is_some_and(|p| *p >= name) {
541 return Err(invalid(at, "tag names out of order"));
542 }
543 if !map.tags.contains_key(&oid) {
544 return Err(invalid(at, "tag name for an unknown tag"));
545 }
546 previous = Some(name.clone());
547 map.tag_names.insert(name, oid);
548 }
549 reader.finish()?;
550 Ok(map)
551 }
552}
553
554const MAGIC: &[u8] = b"braid-git-map";
555const VERSION: u8 = 1;
556
557fn invalid(at: usize, what: &'static str) -> DecodeError {
558 DecodeError::Invalid { at, what }
559}
560
561fn put_table<V>(
562 out: &mut Vec<u8>,
563 table: &HashMap<GitOid, V>,
564 mut put_value: impl FnMut(&mut Vec<u8>, &V),
565) {
566 let mut keys: Vec<&GitOid> = table.keys().collect();
567 keys.sort_unstable();
568 put_uv(out, keys.len() as u64);
569 for key in keys {
570 out.extend_from_slice(key.as_bytes());
571 put_value(out, &table[key]);
572 }
573}
574
575/// Reads a table written by [`put_table`]: keys strictly ascending, each
576/// value at least `min_value_bytes` long.
577fn read_table<V>(
578 reader: &mut Reader<'_>,
579 min_value_bytes: usize,
580 mut read_value: impl FnMut(&mut Reader<'_>) -> Result<V, DecodeError>,
581) -> Result<Vec<(GitOid, V)>, DecodeError> {
582 let count = reader.count(GitOid::LEN + min_value_bytes)?;
583 let mut rows: Vec<(GitOid, V)> = Vec::with_capacity(count);
584 for _ in 0..count {
585 let at = reader.position();
586 let key = GitOid::from_bytes(reader.array()?);
587 if rows.last().is_some_and(|(previous, _)| *previous >= key) {
588 return Err(invalid(at, "git map keys out of order"));
589 }
590 let value = read_value(reader)?;
591 rows.push((key, value));
592 }
593 Ok(rows)
594}
595
596#[cfg(test)]
597mod tests {
598 use super::*;
599 use braid_format::Kind;
600
601 fn oid(byte: u8) -> GitOid {
602 GitOid::from_bytes([byte; 20])
603 }
604
605 fn id(text: &str) -> ObjectId {
606 ObjectId::hash(Kind::Blob, text.as_bytes())
607 }
608
609 fn sample() -> GitMap {
610 let mut map = GitMap::new();
611 map.insert_commit(oid(1), id("c1"));
612 map.insert_commit(oid(2), id("c2"));
613 map.insert_tree(oid(3), id("t1"), None);
614 map.insert_tree(oid(4), id("t1"), Some(id("raw t1")));
615 map.insert_tree(oid(5), id("t2"), None);
616 map.insert_blob(oid(6), id("b1"), 42);
617 map.insert_tag(
618 oid(7),
619 TagEntry {
620 raw: id("tag"),
621 target: oid(1),
622 target_kind: GitKind::Commit,
623 },
624 );
625 map.set_tag_name(b"refs/tags/v1".to_vec(), oid(7));
626 map
627 }
628
629 #[test]
630 fn lookups_both_ways() {
631 let map = sample();
632 assert_eq!(map.changeset(&oid(1)), Some(id("c1")));
633 assert_eq!(map.commit(&id("c2")), Some(oid(2)));
634 assert_eq!(map.tree(&oid(4)), Some(id("t1")));
635 assert_eq!(map.git_tree(&id("t1")), Some(oid(3)));
636 assert_eq!(map.raw_tree(&oid(4)), Some(id("raw t1")));
637 assert_eq!(map.raw_tree(&oid(3)), None);
638 assert_eq!(map.blob(&oid(6)), Some((id("b1"), 42)));
639 assert_eq!(map.git_blob(&id("b1")), Some(oid(6)));
640 assert_eq!(map.git_tag(&id("tag")), Some(oid(7)));
641 let (tag, entry) = map.tag_by_name(b"refs/tags/v1").unwrap();
642 assert_eq!(tag, oid(7));
643 assert_eq!(entry.target, oid(1));
644 assert_eq!(
645 map.counts(),
646 MapCounts {
647 commits: 2,
648 trees: 3,
649 raw_trees: 1,
650 blobs: 1,
651 tags: 1,
652 tag_names: 1,
653 }
654 );
655 }
656
657 #[test]
658 fn bytes_round_trip() {
659 let map = sample();
660 let bytes = map.to_bytes();
661 let decoded = GitMap::from_bytes(&bytes).unwrap();
662 assert_eq!(decoded, map);
663 assert_eq!(decoded.to_bytes(), bytes);
664 assert_eq!(
665 GitMap::from_bytes(&GitMap::new().to_bytes()).unwrap(),
666 GitMap::new()
667 );
668 }
669
670 #[test]
671 fn rejects_bad_encodings() {
672 let bytes = sample().to_bytes();
673 for cut in 0..bytes.len() {
674 assert!(GitMap::from_bytes(&bytes[..cut]).is_err(), "cut at {cut}");
675 }
676 let mut trailing = bytes.clone();
677 trailing.push(0);
678 assert!(GitMap::from_bytes(&trailing).is_err());
679 let mut version = bytes.clone();
680 version[MAGIC.len()] = 2;
681 assert!(GitMap::from_bytes(&version).is_err());
682
683 // Two commits for one changeset.
684 let mut map = GitMap::new();
685 map.commits.insert(oid(1), id("c"));
686 map.commits.insert(oid(2), id("c"));
687 assert!(GitMap::from_bytes(&map.to_bytes()).is_err());
688
689 // Two canonical trees for one braid tree.
690 let mut map = GitMap::new();
691 map.trees.insert(oid(1), id("t"));
692 map.trees.insert(oid(2), id("t"));
693 assert!(GitMap::from_bytes(&map.to_bytes()).is_err());
694
695 // A raw tree that is not a tree, and a name for an unknown tag.
696 let mut map = GitMap::new();
697 map.raw_trees.insert(oid(1), id("raw"));
698 assert!(GitMap::from_bytes(&map.to_bytes()).is_err());
699 let mut map = GitMap::new();
700 map.tag_names.insert(b"refs/tags/x".to_vec(), oid(9));
701 assert!(GitMap::from_bytes(&map.to_bytes()).is_err());
702
703 // Keys out of order: swap the two commit rows.
704 let map = sample();
705 let mut swapped = map.to_bytes();
706 let start = MAGIC.len() + 1 + 1;
707 let row = 20 + 32;
708 let (first, second) = swapped[start..start + 2 * row].split_at_mut(row);
709 first.swap_with_slice(second);
710 assert!(GitMap::from_bytes(&swapped).is_err());
711 }
712
713 #[test]
714 fn recording_keeps_the_map_one_to_one() {
715 let mut map = sample();
716 let pairings = Pairings {
717 commits: vec![
718 (oid(1), id("another changeset")),
719 (oid(8), id("c1")),
720 (oid(9), id("c9")),
721 ],
722 trees: vec![(oid(3), id("t9")), (oid(10), id("t1")), (oid(11), id("t3"))],
723 blobs: vec![
724 (oid(6), id("b9"), 1),
725 (oid(12), id("b1"), 42),
726 (oid(13), id("b2"), 7),
727 ],
728 };
729 assert!(!pairings.is_empty());
730 let added = map.record(&pairings);
731 assert_eq!(
732 added,
733 MapCounts {
734 commits: 1,
735 trees: 1,
736 blobs: 1,
737 ..MapCounts::default()
738 }
739 );
740 // What the map knew stays.
741 assert_eq!(map.changeset(&oid(1)), Some(id("c1")));
742 assert_eq!(map.changeset(&oid(8)), None);
743 assert_eq!(map.git_tree(&id("t1")), Some(oid(3)));
744 assert_eq!(map.tree(&oid(10)), None);
745 assert_eq!(map.blob(&oid(12)), None);
746 // The rest is added both ways.
747 assert_eq!(map.changeset(&oid(9)), Some(id("c9")));
748 assert_eq!(map.commit(&id("c9")), Some(oid(9)));
749 assert_eq!(map.git_tree(&id("t3")), Some(oid(11)));
750 assert_eq!(map.raw_tree(&oid(11)), None);
751 assert_eq!(map.blob(&oid(13)), Some((id("b2"), 7)));
752 assert_eq!(map.git_blob(&id("b2")), Some(oid(13)));
753 // The result still encodes, and recording again adds nothing.
754 assert_eq!(GitMap::from_bytes(&map.to_bytes()).unwrap(), map);
755 assert_eq!(map.record(&pairings), MapCounts::default());
756 assert!(Pairings::default().is_empty());
757 }
758
759 #[test]
760 fn absorbing_adds_what_is_missing() {
761 let theirs = sample();
762 let mut ours = GitMap::new();
763 ours.insert_commit(oid(1), id("c1"));
764 ours.insert_tree(oid(5), id("t2"), None);
765 assert_eq!(
766 ours.absorb(&theirs),
767 MapCounts {
768 commits: 1,
769 trees: 2,
770 raw_trees: 1,
771 blobs: 1,
772 tags: 1,
773 tag_names: 1,
774 }
775 );
776 assert_eq!(ours, theirs);
777 assert_eq!(ours.absorb(&theirs), MapCounts::default());
778
779 // Where the two disagree, this map wins and stays one to one.
780 let mut mine = GitMap::new();
781 mine.insert_commit(oid(2), id("mine"));
782 mine.insert_tree(oid(20), id("t1"), None);
783 mine.absorb(&theirs);
784 assert_eq!(mine.changeset(&oid(2)), Some(id("mine")));
785 assert_eq!(mine.commit(&id("c2")), None);
786 assert_eq!(mine.git_tree(&id("t1")), Some(oid(20)));
787 assert_eq!(mine.tree(&oid(3)), None);
788 assert_eq!(mine.raw_tree(&oid(4)), Some(id("raw t1")));
789 assert_eq!(GitMap::from_bytes(&mine.to_bytes()).unwrap(), mine);
790 }
791}