1use crate::error::{ErrorKind, ErrorStage};
2use crate::{NetError, Result};
3use std::fmt;
4
5#[derive(Clone, Debug)]
7pub struct CloseFrame {
8 code: u16,
10 reason: String,
12}
13
14impl CloseFrame {
15 pub fn new(code: u16, reason: impl Into<String>) -> Result<Self> {
17 if !matches!(code, 1000..=1003 | 1007..=1014 | 3000..=4999) {
19 return Err(NetError::input(
20 "close.code",
21 "must be an allowed WebSocket wire close code",
22 )
23 .with_stage(ErrorStage::Close));
24 }
25 let reason = reason.into();
26 if reason.len() > 123 {
27 return Err(
28 NetError::input("close.reason", "must be at most 123 UTF-8 bytes")
29 .with_stage(ErrorStage::Close),
30 );
31 }
32 Ok(Self { code, reason })
33 }
34
35 pub fn code(&self) -> u16 {
37 self.code
38 }
39
40 pub fn reason(&self) -> &str {
42 &self.reason
43 }
44
45 pub(crate) fn into_wire(self) -> tokio_tungstenite::tungstenite::protocol::CloseFrame {
46 use tokio_tungstenite::tungstenite::protocol::frame::coding::CloseCode;
47 let code = if self.code == 1014 {
50 CloseCode::Iana(self.code)
51 } else {
52 CloseCode::from(self.code)
53 };
54 tokio_tungstenite::tungstenite::protocol::CloseFrame {
55 code,
56 reason: self.reason.into(),
57 }
58 }
59}
60
61#[derive(Clone)]
63pub struct PeerClose {
64 pub code: Option<u16>,
66 pub reason: String,
68}
69
70impl PeerClose {
71 pub(crate) fn from_frame(
75 frame: Option<&tokio_tungstenite::tungstenite::protocol::CloseFrame>,
76 ) -> Result<Self> {
77 let Some(frame) = frame else {
78 return Ok(Self {
79 code: None,
80 reason: String::new(),
81 });
82 };
83 if frame.reason.len() > 123 {
84 return Err(NetError::from(ErrorKind::Protocol).with_stage(ErrorStage::Close));
87 }
88 let mut reason = String::new();
89 reason
90 .try_reserve_exact(frame.reason.len())
91 .map_err(|error| {
92 NetError::with_source(ErrorKind::ResourceExhausted, error)
93 .with_stage(ErrorStage::Close)
94 })?;
95 reason.push_str(frame.reason.as_str());
96 Ok(Self {
97 code: Some(u16::from(frame.code)),
98 reason,
99 })
100 }
101}
102
103impl fmt::Debug for PeerClose {
104 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
105 formatter
106 .debug_struct("PeerClose")
107 .field("code", &self.code)
108 .field("reason_len", &self.reason.len())
109 .finish()
110 }
111}
112
113#[non_exhaustive]
116#[derive(Clone, Copy, Debug, Eq, PartialEq)]
117pub enum IoEndKind {
118 PeerClose,
120 UnexpectedEof,
122 ConnectionReset,
124 ProtocolError,
126 Other,
128}
129
130#[cfg(test)]
131#[path = "close_tests.rs"]
132mod tests;
133
134#[cfg(test)]
135#[path = "peer_close_tests.rs"]
136mod peer_tests;