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
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
use std::{
    any::Any,
    borrow::Cow,
    collections::BTreeMap,
    fmt::Debug,
    fs::File,
    io::{BufRead, BufReader, Read, Seek},
    path::Path,
    str::FromStr,
    sync::Arc,
};

use bytes::{Buf, Bytes};
use sha2::Digest;
use shared_buffer::OwnedBuffer;

use crate::{compat::Volume, PathSegmentError, Version};

/// A version-agnostic read-only WEBC container.
///
/// A `Container` provides a high-level interface for reading and manipulating
/// WEBC container files. It supports multiple versions of WEBC container
/// formats and abstracts the underlying differences between them.
#[derive(Debug, Clone)]
pub struct Container {
    imp: Arc<dyn AbstractWebc + Send + Sync>,
}

#[allow(clippy::result_large_err)]
impl Container {
    /// Load a [`Container`] from disk.
    ///
    /// Where possible, this will try to use a memory-mapped implementation
    /// to reduce memory usage.
    pub fn from_disk(path: impl AsRef<Path>) -> Result<Self, ContainerError> {
        let path = path.as_ref();

        if path.is_dir() {
            return parse_dir(path);
        }

        let mut f = File::open(path).map_err(|error| ContainerError::Open {
            error,
            path: path.to_path_buf(),
        })?;

        if is_tarball(&mut f) {
            return parse_tarball(BufReader::new(f));
        }

        match crate::detect(&mut f) {
            Ok(Version::V1) => parse_v1_mmap(f),
            Ok(Version::V2) => parse_v2_mmap(f),
            Ok(Version::V3) => parse_v3_mmap(f),
            Ok(other) => {
                // fall back to the allocating generic version
                let mut buffer = Vec::new();
                f.rewind()
                    .and_then(|_| f.read_to_end(&mut buffer))
                    .map_err(|error| ContainerError::Read {
                        path: path.to_path_buf(),
                        error,
                    })?;

                Container::from_bytes_and_version(buffer.into(), other)
            }
            Err(e) => Err(ContainerError::Detect(e)),
        }
    }

    /// Load a [`Container`] from bytes in memory.
    pub fn from_bytes(bytes: impl Into<Bytes>) -> Result<Self, ContainerError> {
        let bytes: Bytes = bytes.into();

        if is_tarball(std::io::Cursor::new(&bytes)) {
            return parse_tarball(bytes.reader());
        }

        let version = crate::detect(bytes.as_ref())?;
        Container::from_bytes_and_version(bytes, version)
    }

    /// Create a Container from an abstract implementation.
    #[doc(hidden)]
    pub fn new(repr: impl AbstractWebc + Send + Sync + 'static) -> Self {
        Container {
            imp: Arc::new(repr),
        }
    }

    fn from_bytes_and_version(bytes: Bytes, version: Version) -> Result<Self, ContainerError> {
        match version {
            Version::V1 => parse_v1_owned(bytes),
            Version::V2 => parse_v2_owned(bytes),
            Version::V3 => parse_v3_owned(bytes),
            other => Err(ContainerError::UnsupportedVersion(other)),
        }
    }

    /// Get the underlying webc version
    pub fn version(&self) -> Version {
        self.imp.version()
    }

    /// Get the [`Container`]'s manifest.
    pub fn manifest(&self) -> &crate::metadata::Manifest {
        self.imp.manifest()
    }

    /// Get the [`Container`]'s webc hash
    pub fn webc_hash(&self) -> Option<[u8; 32]> {
        self.imp.get_webc_hash()
    }

    /// Get all atoms stored in the container as a map.
    pub fn atoms(&self) -> BTreeMap<String, OwnedBuffer> {
        let mut atoms = BTreeMap::new();

        for name in self.imp.atom_names() {
            if let Some(atom) = self.imp.get_atom(&name) {
                atoms.insert(name.into_owned(), atom);
            }
        }

        atoms
    }

    /// Get an atom with the given name.
    ///
    /// Returns `None` if the atom does not exist in the container.
    ///
    /// This operation is pretty cheap, typically just a dictionary lookup
    /// followed by reference count bump and some index math.
    pub fn get_atom(&self, name: &str) -> Option<OwnedBuffer> {
        self.imp.get_atom(name)
    }

    /// Get all volumes stored in the container.
    pub fn volumes(&self) -> BTreeMap<String, Volume> {
        let mut volumes = BTreeMap::new();

        for name in self.imp.volume_names() {
            if let Some(atom) = self.imp.get_volume(&name) {
                volumes.insert(name.into_owned(), atom);
            }
        }

        volumes
    }

    /// Get a volume with the given name.
    ///
    /// Returns `None` if the volume does not exist in the container.
    pub fn get_volume(&self, name: &str) -> Option<Volume> {
        self.imp.get_volume(name)
    }

    /// Downcast the [`Container`] a concrete implementation.
    pub fn downcast_ref<T>(&self) -> Option<&T>
    where
        T: 'static,
    {
        self.as_any().downcast_ref()
    }

    /// Downcast the [`Container`] a concrete implementation, returning the
    /// original [`Container`] if the cast fails.
    pub fn downcast<T>(self) -> Result<Arc<T>, Self>
    where
        T: 'static,
    {
        if self.as_any().is::<T>() {
            // Safety: We've just checked that the type matches up.
            unsafe { Ok(Arc::from_raw(Arc::into_raw(self.imp).cast())) }
        } else {
            Err(self)
        }
    }

    /// Unpack the container into a directory.
    ///
    /// This will create a directory at `out_dir` and populate it with the
    /// the contents of each volume and the manifest.
    ///
    /// If the output directory already exists and is not empty, the operation
    /// will fail, unless `overwrite` is set to `true`.
    pub fn unpack(&self, out_dir: &std::path::Path, overwrite: bool) -> Result<(), ContainerError> {
        match out_dir.metadata() {
            Ok(m) => {
                if !m.is_dir() {
                    return Err(ContainerError::Open {
                        path: out_dir.to_path_buf(),
                        error: std::io::Error::new(
                            std::io::ErrorKind::AlreadyExists,
                            "output path is not a directory",
                        ),
                    });
                }
                let mut items = std::fs::read_dir(out_dir).map_err(|err| ContainerError::Open {
                    path: out_dir.to_path_buf(),
                    error: err,
                })?;

                if items.next().is_some() && !overwrite {
                    return Err(ContainerError::Open {
                        path: out_dir.to_path_buf(),
                        error: std::io::Error::new(
                            std::io::ErrorKind::AlreadyExists,
                            "output directory is not empty",
                        ),
                    })?;
                }
            }
            Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
                std::fs::create_dir_all(out_dir).map_err(|err| ContainerError::Open {
                    path: out_dir.to_path_buf(),
                    error: err,
                })?;
            }
            Err(err) => {
                return Err(ContainerError::Open {
                    path: out_dir.to_path_buf(),
                    error: err,
                });
            }
        };

        let manifest_path = out_dir.join("manifest.json");
        // NOTE: this serialization is infallible in practice, hence the unwrap.
        let manifest_data =
            serde_json::to_vec(self.manifest()).expect("could not serialize manifest to JSON");

        std::fs::write(&manifest_path, manifest_data).map_err(|err| ContainerError::Open {
            path: manifest_path,
            error: err,
        })?;

        for (root, volume) in self.volumes() {
            let root = root.strip_prefix('/').unwrap_or(root.as_str());

            let volume_dir = out_dir.join(root);

            volume.unpack("/", &volume_dir)?;
        }

        for (name, contents) in self.atoms() {
            std::fs::write(out_dir.join(name), contents)?;
        }

        Ok(())
    }

    /// Validates an [`AbstractWebc`]
    pub fn validate(&self) -> Result<(), anyhow::Error> {
        if self.version() == Version::V1 {
            anyhow::bail!("v1 validation is unsupported");
        }

        let manifest = self.manifest();

        // validate atoms
        for (name, bytes) in self.atoms().iter() {
            let signature = manifest.atom_signature(name)?;
            let expected = sha2::Sha256::digest(bytes);

            if signature.as_bytes() != expected.as_slice() {
                anyhow::bail!(format!(
                    "signature of atom: {name} does not match what is expected"
                ))
            }
        }

        if let Some(fs) = manifest.filesystem()? {
            // validate fs
            for crate::metadata::annotations::FileSystemMapping {
                volume_name,
                host_path,
                ..
            } in fs.iter()
            {
                // validate that volume exists
                let volume = self
                    .get_volume(volume_name)
                    .ok_or_else(|| anyhow::Error::msg(format!("could not find: {volume_name}")))?;

                // in v2, `host_path` should be accessible in the webc volume
                if self.version() == Version::V2 {
                    // host path must be present in v2
                    let host_path = host_path.clone().ok_or_else(|| {
                        anyhow::Error::msg("host_path is not present in fs mapping")
                    })?;
                    let host_path_segments = crate::PathSegments::from_str(&host_path)?;

                    volume.read_dir(host_path_segments).ok_or_else(|| {
                        anyhow::Error::msg(format!("could not read directory: {host_path}"))
                    })?;
                }
            }
        }

        for (_, volume) in self.volumes().iter() {
            traverse_volume(volume, crate::PathSegments::ROOT, self.version())?;
        }

        Ok(())
    }
}

fn traverse_volume(
    volume: &crate::Volume,
    path: crate::PathSegments,
    version: crate::Version,
) -> Result<(), anyhow::Error> {
    let entries = volume
        .read_dir(&path)
        .ok_or_else(|| anyhow::Error::msg(format!("failed to read path: {path}")))?;

    for (name, read_dir_hash, metadata) in entries {
        let entry_path = path.join(name);
        match metadata {
            crate::Metadata::Dir { .. } => traverse_volume(volume, entry_path, version)?,
            crate::Metadata::File { length, .. } => {
                let (content, read_file_hash) =
                    volume.read_file(entry_path.clone()).ok_or_else(|| {
                        anyhow::Error::msg(format!("failed to read file: {entry_path}"))
                    })?;

                if content.len() != length {
                    anyhow::bail!("File: {entry_path} length does not match with the actual content: {} != {}", length, content.len());
                }

                // validate the hashes
                if version == crate::Version::V3 {
                    let expected: [u8; 32] = sha2::Sha256::digest(&content).into();

                    let read_dir_hash = read_dir_hash.ok_or_else(|| {
                        anyhow::Error::msg(format!(
                            "hash of {entry_path} is not present in V3 when calling read_dir"
                        ))
                    })?;

                    let read_file_hash = read_file_hash.ok_or_else(|| {
                        anyhow::Error::msg(format!(
                            "hash of {entry_path} is not present in V3 when calling read_file"
                        ))
                    })?;

                    if expected != read_dir_hash {
                        anyhow::bail!("hash of {entry_path} does not match the expected value when calling read_dir");
                    }

                    if expected != read_file_hash {
                        anyhow::bail!("hash of {entry_path} does not match the expected value when calling read_file");
                    }
                }
            }
        }
    }

    Ok(())
}

/// The AbstractWebc trait allows defining your own
/// Containers easily from memory
#[doc(hidden)]
pub trait AbstractWebc: AsAny + Debug {
    /// Returns the version of the webc container
    fn version(&self) -> Version;

    /// Get the [`Container`]'s manifest.
    fn manifest(&self) -> &crate::metadata::Manifest;

    /// Get all atom names stored in the container.
    fn atom_names(&self) -> Vec<Cow<'_, str>>;

    /// Get an atom.
    fn get_atom(&self, name: &str) -> Option<OwnedBuffer>;

    /// Get hash of the webc
    fn get_webc_hash(&self) -> Option<[u8; 32]>;

    /// Get atoms section hash
    fn get_atoms_hash(&self) -> Option<[u8; 32]>;

    /// Get all volumes names stored in the container.
    fn volume_names(&self) -> Vec<Cow<'_, str>>;

    /// Get the volume for a specific name.
    fn get_volume(&self, name: &str) -> Option<Volume>;
}

/// Create a function which will use the provided implementation when a feature
/// flag is enabled, returning a [`ContainerError::FeatureNotEnabled`] if it
/// isn't.
macro_rules! guarded_fn {
    (
        $(
            #[cfg(feature = $feature:literal)]
            $(#[$meta:meta])*
            fn $name:ident($($arg:ident : $arg_ty:ty)*) $(-> $ret:ty)? $body:block
        )*
    ) => {
        $(
            $(#[$meta])*
            fn $name($($arg : $arg_ty)*) $(-> $ret)* {
                cfg_if::cfg_if! {
                    if #[cfg(feature = $feature)] {
                        $body
                    } else {
                        $(
                            let _ = $arg;
                        )*
                        Err(ContainerError::FeatureNotEnabled {
                            feature: $feature,
                        })
                    }
                }
            }
        )*
    };
}

guarded_fn! {
    #[cfg(feature = "package")]
    #[allow(clippy::result_large_err)]
    fn parse_tarball(reader: impl BufRead) -> Result<Container, ContainerError> {
        let pkg = crate::wasmer_package::Package::from_tarball(reader)
            .map_err(ContainerError::WasmerPackage)?;
        Ok(Container::new(pkg))
    }

    #[cfg(feature = "package")]
    #[allow(clippy::result_large_err)]
    fn parse_dir(path: &Path) -> Result<Container, ContainerError> {
        let wasmer_toml = path.join("wasmer.toml");
        let pkg = crate::wasmer_package::Package::from_manifest(wasmer_toml)?;
        Ok(Container::new(pkg))
    }

    #[cfg(feature = "v1")]
    #[allow(clippy::result_large_err)]
    fn parse_v1_mmap(f: File) -> Result<Container, ContainerError> {
        // We need to explicitly use WebcMmap to get a memory-mapped
        // parser
        let options = crate::v1::ParseOptions::default();
        let webc = crate::v1::WebCMmap::from_file(f, &options)?;
        Ok(Container::new(webc))
    }

    #[cfg(feature = "v1")]
    #[allow(clippy::result_large_err)]
    fn parse_v1_owned(bytes: Bytes) -> Result<Container, ContainerError> {
        let options = crate::v1::ParseOptions::default();
        let webc = crate::v1::WebCOwned::parse(bytes, &options)?;
        Ok(Container::new(webc))
    }

    #[cfg(feature = "v2")]
    #[allow(clippy::result_large_err)]
    fn parse_v2_owned(bytes: Bytes) -> Result<Container, ContainerError> {
        let reader = crate::v2::read::OwnedReader::parse(bytes)?;
        Ok(Container::new(reader))
    }

    #[cfg(feature = "v2")]
    #[allow(clippy::result_large_err)]
    fn parse_v2_mmap(f: File) -> Result<Container, ContainerError> {
        // Note: OwnedReader::from_file() will automatically try to
        // use a memory-mapped file when possible.
        let webc = crate::v2::read::OwnedReader::from_file(f)?;
        Ok(Container::new(webc))
    }

    #[cfg(feature = "v3")]
    #[allow(clippy::result_large_err)]
    fn parse_v3_owned(bytes: Bytes) -> Result<Container, ContainerError> {
        let reader = crate::v3::read::OwnedReader::parse(bytes)?;
        Ok(Container::new(reader))
    }

    #[cfg(feature = "v3")]
    #[allow(clippy::result_large_err)]
    fn
    parse_v3_mmap(f: File) -> Result<Container, ContainerError> {
        // Note: OwnedReader::from_file() will automatically try to
        // use a memory-mapped file when possible.
        let webc = crate::v3::read::OwnedReader::from_file(f)?;
        Ok(Container::new(webc))
    }
}

#[cfg(feature = "v1")]
mod v1 {
    use super::*;

    impl AbstractWebc for crate::v1::WebCMmap {
        fn version(&self) -> Version {
            Version::V1
        }

        fn manifest(&self) -> &crate::metadata::Manifest {
            &self.manifest
        }

        fn atom_names(&self) -> Vec<Cow<'_, str>> {
            self.get_all_atoms().into_keys().map(Cow::Owned).collect()
        }

        fn get_atom(&self, name: &str) -> Option<OwnedBuffer> {
            let atoms = self.get_all_atoms();
            let atom = atoms.get(name)?;
            let range = crate::utils::subslice_offsets(&self.buffer, atom);
            Some(self.buffer.slice(range))
        }

        fn get_webc_hash(&self) -> Option<[u8; 32]> {
            self.webc_hash()
        }

        fn get_atoms_hash(&self) -> Option<[u8; 32]> {
            None
        }

        fn volume_names(&self) -> Vec<Cow<'_, str>> {
            self.volumes
                .keys()
                .map(|s| Cow::Borrowed(s.as_str()))
                .collect()
        }

        fn get_volume(&self, name: &str) -> Option<Volume> {
            let package_name = self.get_package_name();
            let volume = crate::v1::WebC::get_volume(self, &package_name, name)?;
            let buffer = self.buffer.clone();

            Some(Volume::new(crate::volume::v1::VolumeV1 {
                volume: volume.clone(),
                buffer,
            }))
        }
    }

    impl From<crate::v1::WebCMmap> for Container {
        fn from(value: crate::v1::WebCMmap) -> Self {
            Container::new(value)
        }
    }

    impl AbstractWebc for crate::v1::WebCOwned {
        fn version(&self) -> Version {
            Version::V1
        }

        fn manifest(&self) -> &crate::metadata::Manifest {
            &self.manifest
        }

        fn atom_names(&self) -> Vec<Cow<'_, str>> {
            self.get_all_atoms().into_keys().map(Cow::Owned).collect()
        }

        fn get_atom(&self, name: &str) -> Option<OwnedBuffer> {
            let atoms = self.get_all_atoms();
            let atom = atoms.get(name)?;
            let range = crate::utils::subslice_offsets(&self.backing_data, atom);
            Some(self.backing_data.slice(range).into())
        }

        fn get_atoms_hash(&self) -> Option<[u8; 32]> {
            None
        }

        fn get_webc_hash(&self) -> Option<[u8; 32]> {
            self.webc_hash()
        }

        fn volume_names(&self) -> Vec<Cow<'_, str>> {
            self.volumes
                .keys()
                .map(|s| Cow::Borrowed(s.as_str()))
                .collect()
        }

        fn get_volume(&self, name: &str) -> Option<Volume> {
            let package_name = self.get_package_name();
            let volume = crate::v1::WebC::get_volume(self, &package_name, name)?.clone();
            let buffer = self.backing_data.clone().into();

            Some(Volume::new(crate::volume::v1::VolumeV1 { buffer, volume }))
        }
    }

    impl From<crate::v1::WebCOwned> for Container {
        fn from(value: crate::v1::WebCOwned) -> Self {
            Container::new(value)
        }
    }
}

#[cfg(feature = "v2")]
mod v2 {
    use super::*;

    impl AbstractWebc for crate::v2::read::OwnedReader {
        fn version(&self) -> Version {
            Version::V2
        }

        fn manifest(&self) -> &crate::metadata::Manifest {
            self.manifest()
        }

        fn atom_names(&self) -> Vec<Cow<'_, str>> {
            self.atom_names().map(Cow::Borrowed).collect()
        }

        fn get_atom(&self, name: &str) -> Option<OwnedBuffer> {
            self.get_atom(name).cloned().map(OwnedBuffer::from)
        }

        fn get_webc_hash(&self) -> Option<[u8; 32]> {
            self.webc_hash()
        }

        fn get_atoms_hash(&self) -> Option<[u8; 32]> {
            None
        }

        fn volume_names(&self) -> Vec<Cow<'_, str>> {
            crate::v2::read::OwnedReader::volume_names(self)
                .map(Cow::Borrowed)
                .collect()
        }

        fn get_volume(&self, name: &str) -> Option<Volume> {
            self.get_volume(name).ok().map(Volume::new)
        }
    }

    impl From<crate::v2::read::OwnedReader> for Container {
        fn from(value: crate::v2::read::OwnedReader) -> Self {
            Container::new(value)
        }
    }
}

#[cfg(feature = "v3")]
mod v3 {
    use super::*;

    impl AbstractWebc for crate::v3::read::OwnedReader {
        fn version(&self) -> Version {
            Version::V3
        }

        fn manifest(&self) -> &crate::metadata::Manifest {
            self.manifest()
        }

        fn atom_names(&self) -> Vec<Cow<'_, str>> {
            self.atom_names().map(Cow::Borrowed).collect()
        }

        fn get_atom(&self, name: &str) -> Option<OwnedBuffer> {
            self.get_atom(name)
                .cloned()
                .map(|(_, b)| OwnedBuffer::from(b))
        }

        fn get_webc_hash(&self) -> Option<[u8; 32]> {
            self.webc_hash()
        }

        fn get_atoms_hash(&self) -> Option<[u8; 32]> {
            Some(self.atoms_hash())
        }

        fn volume_names(&self) -> Vec<Cow<'_, str>> {
            crate::v3::read::OwnedReader::volume_names(self)
                .map(Cow::Borrowed)
                .collect()
        }

        fn get_volume(&self, name: &str) -> Option<Volume> {
            self.get_volume(name).ok().map(Volume::new)
        }
    }

    impl From<crate::v3::read::OwnedReader> for Container {
        fn from(value: crate::v3::read::OwnedReader) -> Self {
            Container::new(value)
        }
    }
}

#[cfg(feature = "package")]
mod package {
    use super::*;

    impl AbstractWebc for crate::wasmer_package::Package {
        fn version(&self) -> Version {
            Version::V3
        }

        fn manifest(&self) -> &crate::metadata::Manifest {
            self.manifest()
        }

        fn atom_names(&self) -> Vec<Cow<'_, str>> {
            self.atoms()
                .keys()
                .map(|s| Cow::Borrowed(s.as_str()))
                .collect()
        }

        fn get_atom(&self, name: &str) -> Option<OwnedBuffer> {
            self.atoms().get(name).cloned()
        }

        fn get_webc_hash(&self) -> Option<[u8; 32]> {
            self.webc_hash()
        }

        fn get_atoms_hash(&self) -> Option<[u8; 32]> {
            None
        }

        fn volume_names(&self) -> Vec<Cow<'_, str>> {
            self.volume_names()
        }

        fn get_volume(&self, name: &str) -> Option<Volume> {
            self.get_volume(name).map(Volume::new)
        }
    }

    impl From<crate::wasmer_package::Package> for Container {
        fn from(value: crate::wasmer_package::Package) -> Self {
            Container::new(value)
        }
    }
}

/// A trait for downcasting a reference to a concrete type.
#[doc(hidden)]
pub trait AsAny {
    /// Downcast a reference to a concrete type.
    fn as_any(&self) -> &(dyn Any + 'static);
}

impl<T> AsAny for T
where
    T: Any,
{
    fn as_any(&self) -> &(dyn Any + 'static) {
        self
    }
}

/// Various errors that may occur during [`Container`] operations.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ContainerError {
    /// Unable to detect the WEBC version.
    #[error("Unable to detect the WEBC version")]
    Detect(#[from] crate::DetectError),
    /// An unsupported WEBC version was found.
    #[error("Unsupported WEBC version, {_0}")]
    UnsupportedVersion(crate::Version),
    /// Parsing requires a feature to be enabled.
    #[error("Unable to parse because the \"{feature}\" must be enabled")]
    FeatureNotEnabled {
        /// The feature name
        feature: &'static str,
    },
    /// An error occurred while parsing a v1 WEBC file.
    #[error(transparent)]
    #[cfg(feature = "v1")]
    V1(#[from] crate::v1::Error),
    /// An error occurred while parsing a v2 WEBC file.
    #[error(transparent)]
    #[cfg(feature = "v2")]
    V2Owned(#[from] crate::v2::read::OwnedReaderError),
    /// An error occurred while parsing a v3 WEBC file.
    #[error(transparent)]
    #[cfg(feature = "v3")]
    V3Owned(#[from] crate::v3::read::OwnedReaderError),
    /// an error occurred while loading a Wasmer package from disk.
    #[error(transparent)]
    #[cfg(feature = "package")]
    WasmerPackage(#[from] crate::wasmer_package::WasmerPackageError),
    /// Path segment parsing failed.
    #[error(transparent)]
    Path(#[from] PathSegmentError),
    /// Unable to open a file.
    #[error("Unable to open \"{}\"", path.display())]
    Open {
        /// The file's path.
        path: std::path::PathBuf,
        /// The underlying error.
        #[source]
        error: std::io::Error,
    },
    /// Unable to read a file's contents into memory.
    #[error("Unable to read \"{}\"", path.display())]
    Read {
        /// The file's path.
        path: std::path::PathBuf,
        /// The underlying error.
        #[source]
        error: std::io::Error,
    },
    /// An IO error
    #[error("IOError: {0:?}")]
    IOError(#[from] std::io::Error),
}

/// Check if something looks like a `*.tar.gz` file.
fn is_tarball(mut file: impl Read + Seek) -> bool {
    /// Magic bytes for a `*.tar.gz` file according to
    /// [Wikipedia](https://en.wikipedia.org/wiki/List_of_file_signatures).
    const TAR_GZ_MAGIC_BYTES: [u8; 2] = [0x1F, 0x8B];

    let mut buffer = [0_u8; 2];
    let result = match file.read_exact(&mut buffer) {
        Ok(_) => buffer == TAR_GZ_MAGIC_BYTES,
        Err(_) => false,
    };

    let _ = file.rewind();

    result
}

#[cfg(test)]
mod tests {
    use tempfile::TempDir;

    use crate::{wasmer_package::Package, Container};

    #[test]
    fn container_unpacks_atoms() {
        let temp = TempDir::new().unwrap();
        let wasmer_toml = r#"
                [package]
                name = "some/package"
                version = "0.0.0"
                description = "Test package"

                [[module]]
                name = "foo"
                source = "foo.wasm"
                abi = "wasi"

                [fs]
                "/bar" = "bar"
            "#;

        let manifest = temp.path().join("wasmer.toml");
        std::fs::write(&manifest, wasmer_toml).unwrap();

        let atom_path = temp.path().join("foo.wasm");
        std::fs::write(&atom_path, b"").unwrap();

        let bar = temp.path().join("bar");
        std::fs::create_dir(&bar).unwrap();

        let webc = Package::from_manifest(&manifest)
            .unwrap()
            .serialize()
            .unwrap();
        let container = Container::from_bytes(webc).unwrap();

        let out_dir = temp.path().join("out");
        container.unpack(&out_dir, false).unwrap();

        let expected_entries = vec![
            "bar",      // the volume
            "metadata", // the metadata volume
            "foo",      // the atom
            "manifest.json",
        ];
        let entries = std::fs::read_dir(&out_dir)
            .unwrap()
            .map(|e| e.unwrap())
            .collect::<Vec<_>>();

        assert_eq!(expected_entries.len(), entries.len());
        assert!(expected_entries.iter().all(|e| {
            entries
                .iter()
                .any(|entry| entry.file_name().as_os_str() == *e)
        }))
    }
}