aboutsummaryrefslogtreecommitdiff
path: root/sip/src/encoding/mod.rs
blob: 3c2f3fd86ee653ccd93476ac05d87b9e914799f2 (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
use std::{fmt::Display, str::FromStr};

use headers::ContentLength;
use request::Request;
use response::Response;

pub mod headermap;
pub mod headers;
pub mod method;
pub mod request;
pub mod response;
pub mod status;
pub mod uri;

#[derive(Debug, Clone)]
pub enum Message {
    Request(Request),
    Response(Response),
}

impl Display for Message {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Message::Request(r) => write!(f, "{r}"),
            Message::Response(r) => write!(f, "{r}"),
        }
    }
}
impl FromStr for Message {
    type Err = anyhow::Error;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if s.starts_with("SIP/") {
            Response::from_str(s).map(Message::Response)
        } else {
            Request::from_str(s).map(Message::Request)
        }
    }
}

impl Message {
    pub fn body_mut(&mut self) -> &mut String {
        match self {
            Message::Request(r) => &mut r.body,
            Message::Response(r) => &mut r.body,
        }
    }
    pub fn content_length(&self) -> Option<Result<ContentLength, anyhow::Error>> {
        match self {
            Message::Request(r) => r.headers.get::<ContentLength>(),
            Message::Response(r) => r.headers.get::<ContentLength>(),
        }
    }
}