libsip/
request.rs

1use crate::*;
2
3use std::io::{Error as IoError, ErrorKind as IoErrorKind, Result as IoResult};
4
5/// Sip Request Generator. When build is called the struct
6/// is consumed and produces a SipMessage::Request variant.
7/// Calling the `method` & `uri` methods before the `build`
8/// method is required.
9#[derive(Default)]
10pub struct RequestGenerator {
11    method: Option<Method>,
12    uri: Option<Uri>,
13    version: Version,
14    headers: Headers,
15    body: Vec<u8>,
16}
17
18impl RequestGenerator {
19    /// Create a new instance.
20    pub fn new() -> RequestGenerator {
21        RequestGenerator {
22            method: None,
23            uri: None,
24            version: Version::default(),
25            headers: Headers::new(),
26            body: vec![],
27        }
28    }
29
30    /// Set the sip request method.
31    pub fn method(mut self, method: Method) -> RequestGenerator {
32        self.method = Some(method);
33        self
34    }
35
36    /// Set the sip request uri.
37    pub fn uri(mut self, uri: Uri) -> RequestGenerator {
38        self.uri = Some(uri);
39        self
40    }
41
42    /// Add multiple headers to the request header list.
43    /// This use's Vec::extend so that the current items
44    /// in the header list are kept.
45    pub fn headers(mut self, headers: Vec<Header>) -> RequestGenerator {
46        self.headers.extend(headers);
47        self
48    }
49
50    /// Add a single header to the request header list.
51    pub fn header(mut self, header: Header) -> RequestGenerator {
52        self.headers.push(header);
53        self
54    }
55
56    /// Get a reference to the header list.
57    pub fn header_ref(&self) -> &Headers {
58        &self.headers
59    }
60
61    /// Get a mutable reference to the header list.
62    pub fn headers_ref_mut(&mut self) -> &mut Headers {
63        &mut self.headers
64    }
65
66    /// Set the sip request body. This completely replaces
67    /// the current request body.
68    pub fn body(mut self, body: Vec<u8>) -> RequestGenerator {
69        self.body = body;
70        self
71    }
72
73    /// Build the sip request.
74    pub fn build(self) -> IoResult<SipMessage> {
75        if let Some(method) = self.method {
76            if let Some(uri) = self.uri {
77                Ok(SipMessage::Request {
78                    method,
79                    uri,
80                    version: self.version,
81                    headers: self.headers,
82                    body: self.body,
83                })
84            } else {
85                Err(IoError::new(
86                    IoErrorKind::InvalidInput,
87                    "`uri` method call required",
88                ))
89            }
90        } else {
91            Err(IoError::new(
92                IoErrorKind::InvalidInput,
93                "`method` method call required",
94            ))
95        }
96    }
97}