open_net/api/ws/
request_id.rs1use crate::error::{ErrorKind, ErrorStage};
2use crate::{NetError, Result};
3use std::fmt;
4use std::str::FromStr;
5
6#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Hash)]
11pub struct RequestId(
12 String,
14);
15
16impl RequestId {
17 pub fn new(value: impl Into<String>) -> Result<Self> {
19 let value = value.into();
20 if value.len() > 1024 {
21 return Err(NetError::input(
22 "request_id",
23 "must be at most 1024 UTF-8 bytes",
24 ));
25 }
26 if value.trim().is_empty() {
27 return Err(NetError::input(
28 "request_id",
29 "must contain a non-whitespace character",
30 ));
31 }
32 Ok(Self(value))
33 }
34
35 pub fn random() -> Result<Self> {
37 Self::random_with(getrandom::fill)
38 }
39
40 fn random_with(
41 fill: impl FnOnce(&mut [u8]) -> std::result::Result<(), getrandom::Error>,
42 ) -> Result<Self> {
43 let mut bytes = [0_u8; 16];
44 fill(&mut bytes).map_err(|error| {
45 NetError::with_source(ErrorKind::Io, error).with_stage(ErrorStage::RequestBuild)
46 })?;
47 Ok(Self(
48 uuid::Builder::from_random_bytes(bytes)
49 .into_uuid()
50 .to_string(),
51 ))
52 }
53
54 pub fn as_str(&self) -> &str {
56 &self.0
57 }
58
59 pub fn into_string(self) -> String {
61 self.0
62 }
63}
64
65impl fmt::Debug for RequestId {
66 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
67 formatter
68 .debug_struct("RequestId")
69 .field("bytes", &self.0.len())
70 .finish()
71 }
72}
73
74impl fmt::Display for RequestId {
75 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
76 formatter.write_str(self.as_str())
77 }
78}
79
80impl AsRef<str> for RequestId {
81 fn as_ref(&self) -> &str {
82 self.as_str()
83 }
84}
85
86impl FromStr for RequestId {
87 type Err = NetError;
88
89 fn from_str(value: &str) -> Result<Self> {
90 Self::new(value)
91 }
92}
93
94impl TryFrom<String> for RequestId {
95 type Error = NetError;
96
97 fn try_from(value: String) -> Result<Self> {
98 Self::new(value)
99 }
100}
101
102#[cfg(test)]
103#[path = "request_id_tests.rs"]
104mod tests;