Elffuss BraidHub

utopia-ia/elffuss-braid public

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