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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
use std::{fmt::Debug, sync::Arc};

use shared_buffer::OwnedBuffer;

use crate::{PathSegment, PathSegmentError, PathSegments, ToPathSegments};

/// A WEBC volume.
///
/// A `Volume` represents a collection of files and directories, providing
/// methods to read file contents and traverse directories.
///
/// # Example
///
/// ```
/// use webc::compat::{Metadata, Volume};
/// # use webc::{
/// #     compat::Container,
/// #     PathSegment,
/// #     v2::{
/// #         write::{Directory, Writer},
/// #         read::OwnedReader,
/// #         SignatureAlgorithm,
/// #     },
/// # };
///
/// fn get_webc_volume() -> Volume {
///     /* ... */
/// # let dir = Directory {
/// #   children: [
/// #       (
/// #           PathSegment::parse("path").unwrap(),
/// #           Directory {
/// #               children: [
/// #                   (
/// #                       PathSegment::parse("to").unwrap(),
/// #                       Directory {
/// #                           children: [
/// #                               (PathSegment::parse("file.txt").unwrap(), b"Hello, World!".to_vec().into()),
/// #                           ].into_iter().collect(),
/// #                       }.into(),
/// #                   ),
/// #               ].into_iter().collect(),
/// #           }.into(),
/// #       ),
/// #       (
/// #           PathSegment::parse("another.txt").unwrap(),
/// #           b"Another".to_vec().into(),
/// #       ),
/// #   ].into_iter().collect(),
/// # };
/// # let serialized = Writer::default()
/// #     .write_manifest(&webc::metadata::Manifest::default()).unwrap()
/// #     .write_atoms(std::collections::BTreeMap::new()).unwrap()
/// #     .with_volume("my_volume", dir).unwrap()
/// #     .finish(SignatureAlgorithm::None).unwrap();
/// #     Container::from_bytes(serialized).unwrap().get_volume("my_volume").unwrap()
/// }
///
/// let volume = get_webc_volume();
/// // Accessing file content.
/// let content = volume.read_file("/path/to/file.txt").unwrap();
/// assert_eq!(content, b"Hello, World!");
///
/// // Inspect directories.
/// let entries = volume.read_dir("/").unwrap();
/// assert_eq!(entries.len(), 2);
/// assert_eq!(entries[0], (
///     PathSegment::parse("another.txt").unwrap(),
///     Metadata::File { length: 7 },
/// ));
/// assert_eq!(entries[1], (
///     PathSegment::parse("path").unwrap(),
///     Metadata::Dir,
/// ));
/// ```
#[derive(Debug, Clone)]
pub struct Volume {
    imp: Arc<dyn AbstractVolume + Send + Sync + 'static>,
}

impl Volume {
    pub(crate) fn new(volume: impl AbstractVolume + Send + Sync + 'static) -> Self {
        Volume {
            imp: Arc::new(volume),
        }
    }

    /// Get the metadata of an item at the given path.
    ///
    /// Returns `None` if the item does not exist in the volume or an internal
    /// error occurred.
    pub fn metadata(&self, path: impl ToPathSegments) -> Option<Metadata> {
        let path = path.to_path_segments().ok()?;
        self.imp.metadata(&path)
    }

    /// Read the contents of a directory at the given path.
    ///
    /// Returns a vector of directory entries, including their metadata, if the
    /// path is a directory.
    ///
    /// Returns `None` if the path does not exist or is not a directory.
    pub fn read_dir(&self, path: impl ToPathSegments) -> Option<Vec<(PathSegment, Metadata)>> {
        let path = path.to_path_segments().ok()?;
        self.imp.read_dir(&path)
    }

    /// Read the contents of a file at the given path.
    ///
    /// Returns `None` if the path is not valid or the file is not found.
    pub fn read_file(&self, path: impl ToPathSegments) -> Option<OwnedBuffer> {
        let path = path.to_path_segments().ok()?;
        self.imp.read_file(&path)
    }
}

/// Metadata describing the properties of a file or directory.
#[derive(Debug, Copy, Clone, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(tag = "type", rename_all = "kebab-case")]
pub enum Metadata {
    /// A directory.
    Dir,
    /// A file with a specified length.
    File {
        /// The number of bytes in this file.
        length: usize,
    },
}

impl Metadata {
    /// Returns `true` if the metadata represents a directory.
    pub fn is_dir(self) -> bool {
        matches!(self, Metadata::Dir)
    }

    /// Returns `true` if the metadata represents a file.
    pub fn is_file(self) -> bool {
        matches!(self, Metadata::File { .. })
    }
}

// TODO: This will probably need redesigning later on to make `DirEntry`
// "remember" where it is within a directory structure. The current design
//  turns directory walking into an O(n²) operation.
pub(crate) trait AbstractVolume: Debug {
    fn metadata(&self, path: &PathSegments) -> Option<Metadata>;
    fn read_dir(&self, path: &PathSegments) -> Option<Vec<(PathSegment, Metadata)>>;
    fn read_file(&self, path: &PathSegments) -> Option<OwnedBuffer>;
}

impl AbstractVolume for crate::v2::read::VolumeSection {
    fn metadata(&self, path: &PathSegments) -> Option<Metadata> {
        let entry = self.header().find(path).ok().flatten()?;
        Some(v2_metadata(&entry))
    }

    fn read_dir(&self, path: &PathSegments) -> Option<Vec<(PathSegment, Metadata)>> {
        let meta = self
            .header()
            .find(path)
            .ok()
            .flatten()
            .and_then(|entry| entry.into_dir())?;

        let mut entries = Vec::new();

        for (name, entry) in meta.entries().flatten() {
            let segment: PathSegment = name.parse().unwrap();
            let meta = v2_metadata(&entry);
            entries.push((segment, meta));
        }

        Some(entries)
    }

    fn read_file(&self, path: &PathSegments) -> Option<OwnedBuffer> {
        self.lookup_file(path).map(Into::into).ok()
    }
}

fn v2_metadata(header_entry: &crate::v2::read::volume_header::HeaderEntry<'_>) -> Metadata {
    match header_entry {
        crate::v2::read::volume_header::HeaderEntry::Directory(_) => Metadata::Dir,
        crate::v2::read::volume_header::HeaderEntry::File(
            crate::v2::read::volume_header::FileMetadata {
                start_offset,
                end_offset,
                ..
            },
        ) => Metadata::File {
            length: end_offset - start_offset,
        },
    }
}

#[derive(Debug)]
pub(crate) struct VolumeV1 {
    // SAFETY: order is important here because volume has references into
    // bytes.
    pub(crate) volume: crate::v1::Volume<'static>,
    pub(crate) buffer: OwnedBuffer,
}

impl VolumeV1 {
    fn get_shared(&self, needle: &[u8]) -> OwnedBuffer {
        if needle.is_empty() {
            return OwnedBuffer::new();
        }

        let range = crate::utils::subslice_offsets(&self.buffer, needle);
        self.buffer.slice(range)
    }
}

impl AbstractVolume for VolumeV1 {
    fn metadata(&self, path: &PathSegments) -> Option<Metadata> {
        let path = path.to_string();

        if let Ok(bytes) = self.volume.get_file(&path) {
            return Some(Metadata::File {
                length: bytes.len(),
            });
        }

        if self.volume.read_dir(&path).is_ok() {
            return Some(Metadata::Dir);
        }

        None
    }

    fn read_dir(&self, path: &PathSegments) -> Option<Vec<(PathSegment, Metadata)>> {
        let path = path.to_string();

        let mut entries = Vec::new();

        for entry in self.volume.read_dir(&path).ok()? {
            let name: PathSegment = match entry.text.parse() {
                Ok(p) => p,
                Err(_) => continue,
            };
            let meta = v1_metadata(&entry);
            entries.push((name, meta));
        }

        Some(entries)
    }

    fn read_file(&self, path: &PathSegments) -> Option<OwnedBuffer> {
        let path = path.to_string();
        let bytes = self.volume.get_file(&path).ok()?;
        let owned_bytes = self.get_shared(bytes);

        Some(owned_bytes)
    }
}

fn v1_metadata(entry: &crate::v1::FsEntry<'_>) -> Metadata {
    match entry.fs_type {
        crate::v1::FsEntryType::File => Metadata::File {
            length: entry.get_len().try_into().unwrap(),
        },
        crate::v1::FsEntryType::Dir => Metadata::Dir,
    }
}

impl AbstractVolume for crate::wasmer_package::Volume {
    fn metadata(&self, path: &PathSegments) -> Option<Metadata> {
        self.metadata(path)
    }

    fn read_dir(&self, path: &PathSegments) -> Option<Vec<(PathSegment, Metadata)>> {
        self.read_dir(path)
    }

    fn read_file(&self, path: &PathSegments) -> Option<OwnedBuffer> {
        self.read_file(path)
    }
}

/// Errors that may occur when doing [`Volume`] operations.
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
pub enum VolumeError {
    /// The item wasn't found.
    #[error("The item wasn't found")]
    NotFound,
    /// The provided path wasn't valid.
    #[error("Invalid path")]
    Path(#[from] PathSegmentError),
    /// A non-directory was found where a directory was expected.
    #[error("Not a directory")]
    NotADirectory,
    /// A non-file was found where a file was expected.
    #[error("Not a file")]
    NotAFile,
}

#[cfg(test)]
mod tests {
    use std::collections::BTreeMap;

    use super::*;
    use crate::{metadata::Manifest, v1::DirOrFile, v2::write::Writer};

    fn v2_volume(volume: crate::v2::write::Directory<'static>) -> crate::v2::read::VolumeSection {
        let manifest = Manifest::default();
        let mut writer = Writer::default()
            .write_manifest(&manifest)
            .unwrap()
            .write_atoms(BTreeMap::new())
            .unwrap();
        writer.write_volume("volume", volume).unwrap();
        let serialized = writer.finish(crate::v2::SignatureAlgorithm::None).unwrap();
        let reader = crate::v2::read::OwnedReader::parse(serialized).unwrap();
        reader.get_volume("volume").unwrap()
    }

    #[test]
    fn v2() {
        let dir = dir_map! {
            "path" => dir_map! {
                "to" => dir_map! {
                    "file.txt" => b"Hello, World!",
                }
            },
            "another.txt" => b"Another",
        };
        let volume = v2_volume(dir);

        let volume = Volume::new(volume);

        assert!(volume.read_file("").is_none());
        assert_eq!(volume.read_file("/another.txt").unwrap(), b"Another");
        assert_eq!(
            volume.metadata("/another.txt").unwrap(),
            Metadata::File { length: 7 }
        );
        assert_eq!(
            volume.read_file("/path/to/file.txt").unwrap(),
            b"Hello, World!",
        );
        assert_eq!(
            volume.read_dir("/").unwrap(),
            vec![
                (
                    PathSegment::parse("another.txt").unwrap(),
                    Metadata::File { length: 7 },
                ),
                (PathSegment::parse("path").unwrap(), Metadata::Dir),
            ],
        );
        assert_eq!(
            volume.read_dir("/path").unwrap(),
            vec![(PathSegment::parse("to").unwrap(), Metadata::Dir)],
        );
        assert_eq!(
            volume.read_dir("/path/to/").unwrap(),
            vec![(
                PathSegment::parse("file.txt").unwrap(),
                Metadata::File { length: 13 }
            )],
        );
    }

    fn owned_volume_v1(entries: BTreeMap<DirOrFile, Vec<u8>>) -> VolumeV1 {
        let bytes = crate::v1::Volume::serialize_files(entries);

        let borrowed_volume = crate::v1::Volume::parse(&bytes).unwrap();
        VolumeV1 {
            // SAFETY: We need to transmute the lifetime away.
            volume: unsafe { std::mem::transmute(borrowed_volume) },
            buffer: bytes.into(),
        }
    }

    #[test]
    fn v1_owned() {
        let mut dir = BTreeMap::new();
        dir.insert(DirOrFile::Dir("/path".into()), Vec::new());
        dir.insert(DirOrFile::Dir("/path/to".into()), Vec::new());
        dir.insert(
            DirOrFile::File("/path/to/file.txt".into()),
            b"Hello, World!".to_vec(),
        );
        dir.insert(DirOrFile::Dir("/path/to".into()), Vec::new());
        dir.insert(DirOrFile::File("/another.txt".into()), b"Another".to_vec());
        let volume = owned_volume_v1(dir);

        let volume = Volume::new(volume);

        assert!(volume.read_file("").is_none());
        assert_eq!(volume.read_file("/another.txt").unwrap(), b"Another");
        assert_eq!(
            volume.metadata("/another.txt").unwrap(),
            Metadata::File { length: 7 }
        );
        assert_eq!(
            volume.read_file("/path/to/file.txt").unwrap(),
            b"Hello, World!",
        );

        assert_eq!(volume.metadata("/path/to").unwrap(), Metadata::Dir,);
        assert_eq!(
            volume.read_dir("/").unwrap(),
            vec![
                (
                    PathSegment::parse("another.txt").unwrap(),
                    Metadata::File { length: 7 }
                ),
                (PathSegment::parse("path").unwrap(), Metadata::Dir),
            ],
        );
        assert_eq!(
            volume.read_dir("/path").unwrap(),
            vec![(PathSegment::parse("to").unwrap(), Metadata::Dir)],
        );
        assert_eq!(
            volume.read_dir("/path/to/").unwrap(),
            vec![(
                PathSegment::parse("file.txt").unwrap(),
                Metadata::File { length: 13 }
            )],
        );
    }
}