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
// Copyright (C) 2023-2024  The Software Heritage developers
// See the AUTHORS file at the top-level directory of this distribution
// License: GNU General Public License version 3, or any later version
// See top-level LICENSE file for more information

use thiserror::Error;

use crate::SWHType;

/// Intermediary type that needs to be casted into one of the [`EdgeLabel`] variants
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct UntypedEdgeLabel(pub(crate) u64);

impl From<u64> for UntypedEdgeLabel {
    fn from(n: u64) -> UntypedEdgeLabel {
        UntypedEdgeLabel(n)
    }
}

#[derive(Error, Debug, Clone, PartialEq, Eq, Hash)]
pub enum EdgeTypingError {
    #[error("{src} -> {dst} arcs cannot have labels")]
    NodeTypes { src: SWHType, dst: SWHType },
}

impl UntypedEdgeLabel {
    pub fn for_edge_type(
        &self,
        src: SWHType,
        dst: SWHType,
        transpose_graph: bool,
    ) -> Result<EdgeLabel, EdgeTypingError> {
        use crate::SWHType::*;

        let (src, dst) = if transpose_graph {
            (dst, src)
        } else {
            (src, dst)
        };

        match (src, dst) {
            (Snapshot, _) => Ok(EdgeLabel::Branch(self.0.into())),
            (Directory, _) => Ok(EdgeLabel::DirEntry(self.0.into())),
            (Origin, Snapshot) => Ok(EdgeLabel::Visit(self.0.into())),
            _ => Err(EdgeTypingError::NodeTypes { src, dst }),
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum EdgeLabel {
    /// `snp -> *` branches (or `* -> snp` on the transposed graph)
    Branch(Branch),
    /// `dir -> *` branches (or `* -> dir` on the transposed graph)
    DirEntry(DirEntry),
    /// `ori -> snp` branches (or `snp -> ori` on the transposed graph)
    Visit(Visit),
}

macro_rules! impl_edgelabel_convert {
    ( $variant:ident ( $inner:ty ) ) => {
        impl From<$inner> for EdgeLabel {
            fn from(v: $inner) -> EdgeLabel {
                EdgeLabel::$variant(v)
            }
        }

        impl TryFrom<EdgeLabel> for $inner {
            type Error = ();

            fn try_from(label: EdgeLabel) -> Result<$inner, Self::Error> {
                match label {
                    EdgeLabel::$variant(v) => Ok(v),
                    _ => Err(()),
                }
            }
        }

        impl From<UntypedEdgeLabel> for $inner {
            fn from(label: UntypedEdgeLabel) -> $inner {
                <$inner>::from(label.0)
            }
        }
    };
}

impl_edgelabel_convert!(Branch(Branch));
impl_edgelabel_convert!(DirEntry(DirEntry));
impl_edgelabel_convert!(Visit(Visit));

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum VisitStatus {
    Full,
    Partial,
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Visit(pub(crate) u64);

impl From<u64> for Visit {
    fn from(n: u64) -> Visit {
        Visit(n)
    }
}

impl Visit {
    /// Returns a new [`Visit`]
    ///
    /// or `None` if `timestamp` is 2^59 or greater
    pub fn new(status: VisitStatus, timestamp: u64) -> Option<Visit> {
        let is_full = match status {
            VisitStatus::Full => 1u64,
            VisitStatus::Partial => 0,
        };
        let reserved_bits = 0b1111u64;
        timestamp
            .checked_shl(5)
            .map(|shifted_timestamp| Visit(shifted_timestamp | is_full << 4 | reserved_bits))
    }

    pub fn timestamp(&self) -> u64 {
        self.0 >> 5
    }

    pub fn status(&self) -> VisitStatus {
        if self.0 & 0b10000 != 0 {
            VisitStatus::Full
        } else {
            VisitStatus::Partial
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Branch(pub(crate) u64);

impl From<u64> for Branch {
    fn from(n: u64) -> Branch {
        Branch(n)
    }
}

impl Branch {
    /// Returns a new [`Branch`]
    ///
    /// or `None` if `filename_id` is 2^61 or greater
    pub fn new(filename_id: FilenameId) -> Option<Branch> {
        filename_id
            .0
            .checked_shl(3)
            .map(|shifted_filename_id| Branch(shifted_filename_id))
    }

    /// Returns an id of the filename of the entry.
    ///
    /// The id can be resolved to the filename through graph properties.
    pub fn filename_id(self) -> FilenameId {
        FilenameId(self.0 >> 3)
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct DirEntry(pub(crate) u64);

impl From<u64> for DirEntry {
    fn from(n: u64) -> DirEntry {
        DirEntry(n)
    }
}

impl DirEntry {
    /// Returns a new [`DirEntry`]
    ///
    /// or `None` if `filename_id` is 2^61 or greater
    pub fn new(permission: Permission, filename_id: FilenameId) -> Option<DirEntry> {
        filename_id
            .0
            .checked_shl(3)
            .map(|shifted_filename_id| DirEntry(shifted_filename_id | (permission as u64)))
    }

    /// Returns an id of the filename of the entry.
    ///
    /// The id can be resolved to the filename through graph properties.
    pub fn filename_id(self) -> FilenameId {
        FilenameId(self.0 >> 3)
    }

    /// Returns the file permission of the given directory entry
    ///
    /// # Panics
    ///
    /// When the labelled graph is corrupt or generated by a newer swh-graph version
    /// with more [`Permission`] variants
    pub fn permission(self) -> Option<Permission> {
        use Permission::*;
        match self.0 & 0b111 {
            0 => Some(None),
            1 => Some(Content),
            2 => Some(ExecutableContent),
            3 => Some(Symlink),
            4 => Some(Directory),
            5 => Some(Revision),
            _ => Option::None,
        }
    }

    /// Returns the file permission of the given directory entry
    ///
    /// # Safety
    ///
    /// May return an invalid [`Permission`] variant if the labelled graph is corrupt
    /// or generated by a newer swh-graph version with more variants
    pub unsafe fn permission_unchecked(self) -> Permission {
        use Permission::*;
        match self.0 & 0b111 {
            0 => None,
            1 => Content,
            2 => ExecutableContent,
            3 => Symlink,
            4 => Directory,
            5 => Revision,
            n => unreachable!("{} mode", n),
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct FilenameId(pub u64);

#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[repr(u8)]
pub enum Permission {
    None = 0,
    Content = 1,
    ExecutableContent = 2,
    Symlink = 3,
    Directory = 4,
    Revision = 5,
}

impl Permission {
    /// Returns a UNIX-like mode matching the permission
    ///
    /// `0100644` for contents, `0100755` for executable contents, `0120000` for symbolic
    /// links, `0040000` for directories, and `0160000` for revisions (git submodules);
    /// or `0` if the [`DirEntry`] has no associated permission.
    pub fn to_git(self) -> u16 {
        use Permission::*;
        match self {
            None => 0,
            Content => 0o100644,
            ExecutableContent => 0o100755,
            Symlink => 0o120000,
            Directory => 0o040000,
            Revision => 0o160000,
        }
    }

    /// Returns a permission from a subset of UNIX-like modes.
    ///
    /// This is the inverse of [`Permission::to_git`].
    pub fn from_git(mode: u16) -> Option<Permission> {
        use Permission::*;
        match mode {
            0 => Some(None),
            0o100644 => Some(Content),
            0o100755 => Some(ExecutableContent),
            0o120000 => Some(Symlink),
            0o040000 => Some(Directory),
            0o160000 => Some(Revision),
            _ => Option::None,
        }
    }

    /// Returns a permission from a subset of UNIX-like modes.
    ///
    /// This is the inverse of [`Permission::to_git`].
    ///
    /// # Safety
    ///
    /// Undefined behavior if the given mode is not one of the values returned by [`Permission::to_git`]
    pub unsafe fn from_git_unchecked(mode: u16) -> Permission {
        use Permission::*;
        match mode {
            0 => None,
            0o100644 => Content,
            0o100755 => ExecutableContent,
            0o120000 => Symlink,
            0o040000 => Directory,
            0o160000 => Revision,
            _ => unreachable!("{} mode", mode),
        }
    }
}