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
use std::collections::BTreeMap;

use crate::{
    v3::{
        read::{
            volume_header::{DirectoryMetadata, FileMetadata, HeaderEntry},
            VolumeHeaderError,
        },
        Span, Timestamps,
    },
    PathSegmentError,
};
use shared_buffer::OwnedBuffer;

/// An item in a volume.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum DirEntry<'volume> {
    Dir(Directory<'volume>),
    File(FileEntry),
}

impl<'volume> DirEntry<'volume> {
    fn from_metadata(
        metadata: HeaderEntry<'volume>,
        data_offset: usize,
        data_section: OwnedBuffer,
    ) -> Result<Self, DirEntryError> {
        match metadata {
            HeaderEntry::Directory(dir) => {
                Ok(Directory::new(dir, data_offset, data_section).into())
            }
            HeaderEntry::File(meta) => {
                let file = FileEntry::from_metadata(meta, data_offset, data_section)?;
                Ok(file.into())
            }
        }
    }

    /// Convert the [`DirEntry`] into a [`FileEntry`], if it is one.
    pub fn into_file(self) -> Option<FileEntry> {
        match self {
            DirEntry::File(f) => Some(f),
            _ => None,
        }
    }

    /// Convert the [`DirEntry`] into a [`Directory`], if it is one.
    pub fn into_dir(self) -> Option<Directory<'volume>> {
        match self {
            DirEntry::Dir(d) => Some(d),
            _ => None,
        }
    }
}

impl<'volume> From<Directory<'volume>> for DirEntry<'volume> {
    fn from(v: Directory<'volume>) -> Self {
        Self::Dir(v)
    }
}

impl From<FileEntry> for DirEntry<'_> {
    fn from(f: FileEntry) -> Self {
        Self::File(f)
    }
}

/// A directory that contains zero or more [`DirEntry`]'s.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Directory<'volume> {
    metadata: DirectoryMetadata<'volume>,
    /// The offset of the data section, relative to the start of the volume.
    data_offset: usize,
    data_section: OwnedBuffer,
}

impl<'volume> Directory<'volume> {
    pub(crate) fn new(
        metadata: DirectoryMetadata<'volume>,
        data_offset: usize,
        data_section: OwnedBuffer,
    ) -> Self {
        Directory {
            metadata,
            data_offset,
            data_section,
        }
    }

    /// Lazily parse the entries in this directory.
    pub fn entries(
        &self,
    ) -> impl Iterator<Item = Result<(&'volume str, [u8; 32], DirEntry<'volume>), DirEntryError>> + '_
    {
        self.metadata.clone().entries().map(|result| {
            result
                .map_err(DirEntryError::from)
                .and_then(|(name, hash, entry)| {
                    let entry = DirEntry::from_metadata(
                        entry,
                        self.data_offset,
                        self.data_section.clone(),
                    )?;
                    Ok((name, hash, entry))
                })
        })
    }

    /// Look up a particular entry by name.
    pub fn find(&self, name: &str) -> Result<Option<([u8; 32], DirEntry<'volume>)>, DirEntryError> {
        for result in self.entries() {
            let (entry_name, hash, entry) = result?;
            if name == entry_name {
                return Ok(Some((hash, entry)));
            }
        }

        Ok(None)
    }

    /// Is this directory empty?
    pub fn is_empty(&self) -> bool {
        self.entries().filter_map(|result| result.ok()).count() == 0
    }
}

/// The contents of a file in the volume.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct FileEntry {
    data: OwnedBuffer,
    offset: usize,
    checksum: [u8; 32],
    timestamps: Timestamps,
}

impl FileEntry {
    pub(crate) fn from_metadata(
        meta: FileMetadata,
        data_offset: usize,
        data_section: OwnedBuffer,
    ) -> Result<FileEntry, DirEntryError> {
        let FileMetadata {
            start_offset,
            end_offset,
            checksum,
            timestamps,
        } = meta;

        if start_offset > data_section.len() || end_offset > data_section.len() {
            return Err(DirEntryError::FileOutOfBounds {
                start_offset,
                end_offset,
                data_section_length: data_section.len(),
            });
        }

        let data = data_section.slice(start_offset..end_offset);
        Ok(FileEntry {
            data,
            offset: data_offset + start_offset,
            checksum,
            timestamps,
        })
    }

    /// The file's data.
    pub fn bytes(&self) -> &OwnedBuffer {
        &self.data
    }

    /// The length of the file.
    pub fn len(&self) -> usize {
        self.bytes().len()
    }

    /// Is the file empty?
    pub fn is_empty(&self) -> bool {
        self.bytes().is_empty()
    }

    /// The location of the file, relative to the start of its volume.
    pub fn span(&self) -> Span {
        Span::new(self.offset, self.len())
    }

    /// A SHA-256 checksum for this file.
    pub fn checksum(&self) -> [u8; 32] {
        self.checksum
    }
}

/// Errors that may occur while parsing a [`DirEntry`].
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum DirEntryError {
    #[error("The volume header was corrupted")]
    Header(#[from] VolumeHeaderError),
    #[error("File data is out of bounds ({start_offset}..{end_offset} is outside of 0..{data_section_length})")]
    FileOutOfBounds {
        start_offset: usize,
        end_offset: usize,
        data_section_length: usize,
    },
    #[error("\"{segment}\" is an invalid path segment")]
    InvalidPathSegment {
        #[source]
        error: PathSegmentError,
        segment: String,
    },
}

impl TryFrom<DirEntry<'_>> for crate::v3::write::DirEntry<'_> {
    type Error = DirEntryError;

    fn try_from(value: DirEntry<'_>) -> Result<Self, Self::Error> {
        match value {
            DirEntry::Dir(d) => d.try_into().map(crate::v3::write::DirEntry::Dir),
            DirEntry::File(f) => Ok(crate::v3::write::DirEntry::File(f.into())),
        }
    }
}

impl TryFrom<Directory<'_>> for crate::v3::write::Directory<'_> {
    type Error = DirEntryError;

    fn try_from(dir: Directory<'_>) -> Result<Self, Self::Error> {
        let mut children = BTreeMap::new();

        for result in dir.entries() {
            let (name, _hash, entry) = result?;
            let name = name
                .parse()
                .map_err(|error| DirEntryError::InvalidPathSegment {
                    error,
                    segment: name.to_string(),
                })?;
            children.insert(name, entry.try_into()?);
        }

        Ok(crate::v3::write::Directory {
            children,
            timestamps: dir.metadata.timestamps(),
        })
    }
}

impl From<FileEntry> for crate::v3::write::FileEntry<'_> {
    fn from(value: FileEntry) -> Self {
        crate::v3::write::FileEntry::owned(value.bytes().clone().into_bytes(), value.timestamps)
    }
}