~james/core

ref: 452f17b75181d62d1d92016edecd38e1d70fecab core/crates/gix-commitgraph/src/file/commit.rs -rw-r--r-- 11.8 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 17 hours ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
//! Low-level operations on individual commits.
use crate::{
    File, Position,
    bloom::BloomKey,
    file::{
        self, CORRECTED_COMMIT_DATE_OFFSET_OVERFLOW, EXTENDED_EDGES_MASK, LAST_EXTENDED_EDGE_MASK,
        NO_PARENT,
    },
    from_be_u32,
};
use bstr::BStr;
use gix_error::{Message, message};
use std::{
    fmt::{Debug, Formatter},
    slice::Chunks,
};

/// A commit as stored in a [`File`].
#[derive(Copy, Clone)]
pub struct Commit<'a> {
    pub(crate) file: &'a File,
    pos: file::Position,
    // We can parse the below fields lazily if needed.
    commit_timestamp: u64,
    generation: u32,
    parent1: ParentEdge,
    parent2: ParentEdge,
    root_tree_id: &'a gix_hash::oid,
}

impl<'a> Commit<'a> {
    pub(crate) fn new(file: &'a File, pos: file::Position) -> Self {
        let bytes = file.commit_data_bytes(pos);
        Commit {
            file,
            pos,
            root_tree_id: gix_hash::oid::from_bytes_unchecked(&bytes[..file.hash_len]),
            parent1: ParentEdge::from_raw(from_be_u32(&bytes[file.hash_len..][..4])),
            parent2: ParentEdge::from_raw(from_be_u32(&bytes[file.hash_len + 4..][..4])),
            generation: from_be_u32(&bytes[file.hash_len + 8..][..4]) >> 2,
            commit_timestamp: u64::from_be_bytes(
                bytes[file.hash_len + 8..][..8].try_into().unwrap(),
            ) & 0x0003_ffff_ffff,
        }
    }

    /// Returns the committer timestamp of this commit.
    ///
    /// The value is the number of seconds since 1970-01-01 00:00:00 UTC.
    pub fn committer_timestamp(&self) -> u64 {
        self.commit_timestamp
    }

    /// Returns the generation number of this commit.
    ///
    /// Commits without parents have generation number 1. Commits with parents have a generation
    /// number that is the max of their parents' generation numbers + 1.
    pub fn generation(&self) -> u32 {
        self.generation
    }

    /// Returns the corrected commit date of this commit (generation number v2), or `None` if the
    /// owning graph has no generation data.
    ///
    /// It is the larger of this commit's committer timestamp and its parents' corrected commit dates plus one.
    pub fn corrected_commit_date(&self) -> Result<Option<u64>, Message> {
        let file = self.file;
        let Some(start) = file
            .generation_data_offset
            .filter(|_| file.read_generation_data)
        else {
            return Ok(None);
        };
        let offset = from_be_u32(&file.data[start + self.pos.0 as usize * 4..][..4]);
        let offset = if offset & CORRECTED_COMMIT_DATE_OFFSET_OVERFLOW == 0 {
            u64::from(offset)
        } else {
            let range = file.generation_data_overflow_range.clone().ok_or_else(|| {
                message!(
                    "Commit {} requires overflow generation data, but there is none",
                    self.id()
                )
            })?;
            let index = (offset ^ CORRECTED_COMMIT_DATE_OFFSET_OVERFLOW) as usize;
            let bytes = file.data[range]
                .get(index * 8..)
                .and_then(|bytes| bytes.get(..8))
                .ok_or_else(|| {
                    message!(
                        "Commit {} has overflow generation data index {index} out of range",
                        self.id()
                    )
                })?;
            u64::from_be_bytes(bytes.try_into().expect("8 bytes"))
        };
        self.commit_timestamp
            .checked_add(offset)
            .map(Some)
            .ok_or_else(|| {
                message!(
                    "Commit {} has a corrected commit date that overflows",
                    self.id()
                )
            })
    }

    /// Returns an iterator over the parent positions for lookup in the owning [Graph][crate::Graph].
    pub fn iter_parents(self) -> Parents<'a> {
        // I didn't find a combinator approach that a) was as strict as ParentIterator, b) supported
        // fuse-after-first-error behavior, and b) was significantly shorter or more understandable
        // than ParentIterator. So here we are.
        Parents {
            commit_data: self,
            state: ParentIteratorState::First,
        }
    }

    /// Returns the hash of this commit.
    pub fn id(&self) -> &'a gix_hash::oid {
        self.file.id_at(self.pos)
    }

    /// Returns the first parent of this commit.
    pub fn parent1(&self) -> Result<Option<Position>, Message> {
        self.iter_parents().next().transpose()
    }

    /// Returns the position at which this commit is stored in the parent [File].
    pub fn position(&self) -> file::Position {
        self.pos
    }

    /// Return the hash of the tree this commit points to.
    pub fn root_tree_id(&self) -> &gix_hash::oid {
        self.root_tree_id
    }

    /// Return the raw bytes of this commit's changed-path Bloom filter, see [`File::bloom_filter_at()`].
    pub fn bloom_filter(&self) -> Option<&'a [u8]> {
        self.file.bloom_filter_at(self.pos)
    }

    /// Query if `path` may be present in this commit's changed-path Bloom filter.
    pub fn maybe_contains_path(&self, path: &BStr) -> Option<bool> {
        self.file.maybe_contains_path(self.pos, path)
    }

    /// Query if all `keys` may be present in this commit's changed-path Bloom filter.
    pub fn maybe_contains_all_keys(&self, keys: &[BloomKey]) -> Option<bool> {
        self.file.maybe_contains_all_keys(self.pos, keys)
    }
}

impl Debug for Commit<'_> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Commit {{ id: {}, lex_pos: {}, generation: {}, root_tree_id: {}, parent1: {:?}, parent2: {:?} }}",
            self.id(),
            self.pos,
            self.generation(),
            self.root_tree_id(),
            self.parent1,
            self.parent2,
        )
    }
}

impl Eq for Commit<'_> {}

impl PartialEq for Commit<'_> {
    fn eq(&self, other: &Self) -> bool {
        std::ptr::eq(self.file, other.file) && self.pos == other.pos
    }
}

/// An iterator over parents of a [`Commit`].
pub struct Parents<'a> {
    commit_data: Commit<'a>,
    state: ParentIteratorState<'a>,
}

impl Iterator for Parents<'_> {
    type Item = Result<Position, Message>;

    fn next(&mut self) -> Option<Self::Item> {
        let state = std::mem::replace(&mut self.state, ParentIteratorState::Exhausted);
        match state {
            ParentIteratorState::First => match self.commit_data.parent1 {
                ParentEdge::None => match self.commit_data.parent2 {
                    ParentEdge::None => None,
                    _ => Some(Err(message!(
                        "commit {} has a second parent but not a first parent",
                        self.commit_data.id()
                    ))),
                },
                ParentEdge::GraphPosition(pos) => {
                    self.state = ParentIteratorState::Second;
                    Some(Ok(pos))
                }
                ParentEdge::ExtraEdgeIndex(_) => Some(Err(message!(
                    "commit {}'s first parent is an extra edge index, which is invalid",
                    self.commit_data.id(),
                ))),
            },
            ParentIteratorState::Second => match self.commit_data.parent2 {
                ParentEdge::None => None,
                ParentEdge::GraphPosition(pos) => Some(Ok(pos)),
                ParentEdge::ExtraEdgeIndex(extra_edge_index) => {
                    if let Some(extra_edges_list) = self.commit_data.file.extra_edges_data() {
                        let start_offset: usize = extra_edge_index
                            .try_into()
                            .expect("an architecture able to hold 32 bits of integer");
                        let start_offset = start_offset
                            .checked_mul(4)
                            .expect("an extended edge index small enough to fit in usize");
                        if let Some(tail) = extra_edges_list.get(start_offset..) {
                            self.state = ParentIteratorState::Extra(tail.chunks(4));
                            // This recursive call is what blocks me from replacing ParentIterator
                            // with a std::iter::from_fn closure.
                            self.next()
                        } else {
                            Some(Err(message!(
                                "commit {}'s extra edges overflows the commit-graph file's extra edges list",
                                self.commit_data.id()
                            )))
                        }
                    } else {
                        Some(Err(message!(
                            "commit {} has extra edges, but commit-graph file has no extra edges list",
                            self.commit_data.id()
                        )))
                    }
                }
            },
            ParentIteratorState::Extra(mut chunks) => {
                if let Some(chunk) = chunks.next() {
                    let extra_edge = from_be_u32(chunk);
                    match ExtraEdge::from_raw(extra_edge) {
                        ExtraEdge::Internal(pos) => {
                            self.state = ParentIteratorState::Extra(chunks);
                            Some(Ok(pos))
                        }
                        ExtraEdge::Last(pos) => Some(Ok(pos)),
                    }
                } else {
                    Some(Err(message!(
                        "commit {}'s extra edges overflows the commit-graph file's extra edges list",
                        self.commit_data.id()
                    )))
                }
            }
            ParentIteratorState::Exhausted => None,
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        match (
            &self.state,
            self.commit_data.parent1,
            self.commit_data.parent2,
        ) {
            (ParentIteratorState::First, ParentEdge::None, ParentEdge::None) => (0, Some(0)),
            (ParentIteratorState::First, ParentEdge::None, _) => (1, Some(1)),
            (ParentIteratorState::First, ParentEdge::GraphPosition(_), ParentEdge::None) => {
                (1, Some(1))
            }
            (
                ParentIteratorState::First,
                ParentEdge::GraphPosition(_),
                ParentEdge::GraphPosition(_),
            ) => (2, Some(2)),
            (
                ParentIteratorState::First,
                ParentEdge::GraphPosition(_),
                ParentEdge::ExtraEdgeIndex(_),
            ) => (3, None),
            (ParentIteratorState::First, ParentEdge::ExtraEdgeIndex(_), _) => (1, Some(1)),
            (ParentIteratorState::Second, _, ParentEdge::None) => (0, Some(0)),
            (ParentIteratorState::Second, _, ParentEdge::GraphPosition(_)) => (1, Some(1)),
            (ParentIteratorState::Second, _, ParentEdge::ExtraEdgeIndex(_)) => (2, None),
            (ParentIteratorState::Extra(_), _, _) => (1, None),
            (ParentIteratorState::Exhausted, _, _) => (0, Some(0)),
        }
    }
}

#[derive(Debug)]
enum ParentIteratorState<'a> {
    First,
    Second,
    Extra(Chunks<'a, u8>),
    Exhausted,
}

#[derive(Clone, Copy, Debug)]
enum ParentEdge {
    None,
    GraphPosition(Position),
    ExtraEdgeIndex(u32),
}

impl ParentEdge {
    pub fn from_raw(raw: u32) -> ParentEdge {
        if raw == NO_PARENT {
            return ParentEdge::None;
        }
        if raw & EXTENDED_EDGES_MASK != 0 {
            ParentEdge::ExtraEdgeIndex(raw & !EXTENDED_EDGES_MASK)
        } else {
            ParentEdge::GraphPosition(Position(raw))
        }
    }
}

enum ExtraEdge {
    Internal(Position),
    Last(Position),
}

impl ExtraEdge {
    pub fn from_raw(raw: u32) -> Self {
        if raw & LAST_EXTENDED_EDGE_MASK != 0 {
            Self::Last(Position(raw & !LAST_EXTENDED_EDGE_MASK))
        } else {
            Self::Internal(Position(raw))
        }
    }
}