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