rama_http_types/
body_limit.rs

1/// Can be used to communicate the desire to limit the size of request/response bodies.
2#[derive(Debug, Clone, Copy)]
3pub struct BodyLimit {
4    kind: Option<BodyLimitKind>,
5}
6
7#[derive(Debug, Clone, Copy)]
8enum BodyLimitKind {
9    Bidirectional(usize, usize),
10    Request(usize),
11    Response(usize),
12}
13
14impl BodyLimit {
15    /// Create a new [`BodyLimit`], with the given limit to be applied to the request only.
16    pub fn request_only(limit: usize) -> Self {
17        Self {
18            kind: if limit == 0 {
19                None
20            } else {
21                Some(BodyLimitKind::Request(limit))
22            },
23        }
24    }
25
26    /// Create a new [`BodyLimit`], with the given limit to be applied to the response only.
27    pub fn response_only(limit: usize) -> Self {
28        Self {
29            kind: if limit == 0 {
30                None
31            } else {
32                Some(BodyLimitKind::Response(limit))
33            },
34        }
35    }
36
37    /// Create a new [`BodyLimit`], with the given limit to be applied to both the request and response bodies.
38    pub fn symmetric(limit: usize) -> Self {
39        Self {
40            kind: if limit == 0 {
41                None
42            } else {
43                Some(BodyLimitKind::Bidirectional(limit, limit))
44            },
45        }
46    }
47
48    /// Create a new [`BodyLimit`], with the given limits
49    /// respectively to be applied to the request and response bodies.
50    pub fn asymmetric(request: usize, response: usize) -> Self {
51        match (request, response) {
52            (0, 0) => Self { kind: None },
53            (0, response) => Self {
54                kind: Some(BodyLimitKind::Response(response)),
55            },
56            (request, 0) => Self {
57                kind: Some(BodyLimitKind::Request(request)),
58            },
59            (request, response) => Self {
60                kind: Some(BodyLimitKind::Bidirectional(request, response)),
61            },
62        }
63    }
64
65    /// Get the limit for the request body, if any.
66    pub fn request(&self) -> Option<usize> {
67        match self.kind {
68            Some(BodyLimitKind::Request(limit)) => Some(limit),
69            Some(BodyLimitKind::Bidirectional(request, _)) => Some(request),
70            _ => None,
71        }
72    }
73
74    /// Get the limit for the response body, if any.
75    pub fn response(&self) -> Option<usize> {
76        match self.kind {
77            Some(BodyLimitKind::Response(limit)) => Some(limit),
78            Some(BodyLimitKind::Bidirectional(_, response)) => Some(response),
79            _ => None,
80        }
81    }
82}