1use std::io::{Read, Write};
2
3use super::alert::*;
4use super::application_data::*;
5use super::change_cipher_spec::*;
6use super::handshake::*;
7use shared::error::*;
8
9#[derive(Default, Copy, Clone, PartialEq, Eq, Debug)]
15#[non_exhaustive]
16pub enum ContentType {
17 ChangeCipherSpec = 20,
19 Alert = 21,
21 Handshake = 22,
23 ApplicationData = 23,
25 #[default]
26 Invalid,
28 Tls12Cid = 25,
31}
32
33impl From<u8> for ContentType {
34 fn from(val: u8) -> Self {
35 match val {
36 20 => ContentType::ChangeCipherSpec,
37 21 => ContentType::Alert,
38 22 => ContentType::Handshake,
39 23 => ContentType::ApplicationData,
40 25 => ContentType::Tls12Cid,
41 _ => ContentType::Invalid,
42 }
43 }
44}
45
46#[derive(PartialEq, Debug, Clone)]
47#[non_exhaustive]
49pub enum Content {
50 ChangeCipherSpec(ChangeCipherSpec),
52 Alert(Alert),
54 Handshake(Handshake),
56 ApplicationData(ApplicationData),
58}
59
60impl Content {
61 pub fn content_type(&self) -> ContentType {
63 match self {
64 Content::ChangeCipherSpec(c) => c.content_type(),
65 Content::Alert(c) => c.content_type(),
66 Content::Handshake(c) => c.content_type(),
67 Content::ApplicationData(c) => c.content_type(),
68 }
69 }
70
71 pub fn size(&self) -> usize {
73 match self {
74 Content::ChangeCipherSpec(c) => c.size(),
75 Content::Alert(c) => c.size(),
76 Content::Handshake(c) => c.size(),
77 Content::ApplicationData(c) => c.size(),
78 }
79 }
80
81 pub fn marshal<W: Write>(&self, writer: &mut W) -> Result<()> {
87 match self {
88 Content::ChangeCipherSpec(c) => c.marshal(writer),
89 Content::Alert(c) => c.marshal(writer),
90 Content::Handshake(c) => c.marshal(writer),
91 Content::ApplicationData(c) => c.marshal(writer),
92 }
93 }
94
95 pub fn unmarshal<R: Read>(content_type: ContentType, reader: &mut R) -> Result<Self> {
101 match content_type {
102 ContentType::ChangeCipherSpec => Ok(Content::ChangeCipherSpec(
103 ChangeCipherSpec::unmarshal(reader)?,
104 )),
105 ContentType::Alert => Ok(Content::Alert(Alert::unmarshal(reader)?)),
106 ContentType::Handshake => Ok(Content::Handshake(Handshake::unmarshal(reader)?)),
107 ContentType::ApplicationData => Ok(Content::ApplicationData(
108 ApplicationData::unmarshal(reader)?,
109 )),
110 _ => Err(Error::ErrInvalidContentType),
111 }
112 }
113}