summaryrefslogtreecommitdiffstats
path: root/openpgp/src/packet/compressed_data.rs
blob: e8a241451a26a1f2e6b367d1c681f304813734fc (plain)
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
use std::fmt;

use crate::packet;
use crate::Packet;
use crate::types::CompressionAlgorithm;

/// Holds a compressed data packet.
///
/// A compressed data packet is a container.  See [Section 5.6 of RFC
/// 4880] for details.
///
/// When the parser encounters a compressed data packet with an
/// unknown compress algorithm, it returns an `Unknown` packet instead
/// of a `CompressedData` packet.
///
/// [Section 5.6 of RFC 4880]: https://tools.ietf.org/html/rfc4880#section-5.6
#[derive(PartialEq, Eq, Hash, Clone)]
pub struct CompressedData {
    /// CTB packet header fields.
    pub(crate) common: packet::Common,
    /// Algorithm used to compress the payload.
    algo: CompressionAlgorithm,

    /// This is a container packet.
    container: packet::Container,
}

impl fmt::Debug for CompressedData {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.debug_struct("CompressedData")
            .field("algo", &self.algo)
            .field("children", &self.container.children_ref())
            .field("body (bytes)",
                   &self.container.body().len())
            .field("body_digest", &self.container.body_digest())
            .finish()
    }
}

impl CompressedData {
    /// Returns a new `CompressedData` packet.
    pub fn new(algo: CompressionAlgorithm) -> Self {
        CompressedData {
            common: Default::default(),
            algo: algo,
            container: Default::default(),
        }
    }

    /// Gets the compression algorithm.
    pub fn algo(&self) -> CompressionAlgorithm {
        self.algo
    }

    /// Sets the compression algorithm.
    pub fn set_algo(&mut self, algo: CompressionAlgorithm) -> CompressionAlgorithm {
        ::std::mem::replace(&mut self.algo, algo)
    }

    /// Adds a new packet to the container.
    #[cfg(test)]
    pub fn push(mut self, packet: Packet) -> Self {
        self.container.children_mut().push(packet);
        self
    }

    /// Inserts a new packet to the container at a particular index.
    /// If `i` is 0, the new packet is insert at the front of the
    /// container.  If `i` is one, it is inserted after the first
    /// packet, etc.
    #[cfg(test)]
    pub fn insert(mut self, i: usize, packet: Packet) -> Self {
        self.container.children_mut().insert(i, packet);
        self
    }
}

impl_container_forwards!(CompressedData);

impl From<CompressedData> for Packet {
    fn from(s: CompressedData) -> Self {
        Packet::CompressedData(s)
    }
}