1use crate::jid::{ObservedJid, observe_token};
3use crate::node::ValueRef;
4use crate::{Node, NodeContent, NodeContentRef, NodeRef, NodeValue};
5use std::fmt;
6
7pub struct ObservedId<'a>(&'a str);
9impl<'a> ObservedId<'a> {
10 pub const fn new(value: &'a str) -> Self {
11 Self(value)
12 }
13}
14impl fmt::Display for ObservedId<'_> {
15 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
16 write!(f, "id#{:016x}", observe_token(self.0))
17 }
18}
19impl fmt::Debug for ObservedId<'_> {
20 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
21 fmt::Display::fmt(self, f)
22 }
23}
24
25pub struct ProtocolText<'a>(&'a str);
27impl<'a> ProtocolText<'a> {
28 pub const fn new(value: &'a str) -> Self {
29 Self(value)
30 }
31}
32impl fmt::Display for ProtocolText<'_> {
33 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34 if self.0.len() <= 5
35 && let Ok(code) = self.0.parse::<u16>()
36 {
37 return write!(f, "{code}");
38 }
39 match protocol_atom(self.0) {
40 Some(atom) => f.write_str(atom),
41 None if self.0.is_empty() => f.write_str("empty"),
42 None => write!(f, "other(len={})", self.0.len()),
43 }
44 }
45}
46impl fmt::Debug for ProtocolText<'_> {
47 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48 fmt::Display::fmt(self, f)
49 }
50}
51
52fn protocol_atom(value: &str) -> Option<&'static str> {
53 if value.len() > 128 {
54 return None;
55 }
56 use crate::token::{self, TokenKind};
57 if let Some(kind) = token::index_of_token(value) {
58 return match kind {
59 TokenKind::Single(i) => token::get_single_token(i),
60 TokenKind::Double(d, i) => token::get_double_token(d, i),
61 };
62 }
63 match value {
64 "chatstate" => Some("chatstate"),
65 "xmlstreamend" => Some("xmlstreamend"),
66 "stream:error" => Some("stream:error"),
67 "replaced" => Some("replaced"),
68 "device_removed" => Some("device_removed"),
69 "wait" => Some("wait"),
70 "cancel" => Some("cancel"),
71 "continue" => Some("continue"),
72 "modify" => Some("modify"),
73 "auth" => Some("auth"),
74 "not-authorized" => Some("not-authorized"),
75 "forbidden" => Some("forbidden"),
76 "gone" => Some("gone"),
77 "feature-not-implemented" => Some("feature-not-implemented"),
78 "recipient-unavailable" => Some("recipient-unavailable"),
79 "redirect" => Some("redirect"),
80 "registration-required" => Some("registration-required"),
81 "remote-server-not-found" => Some("remote-server-not-found"),
82 "remote-server-timeout" => Some("remote-server-timeout"),
83 "subscription-required" => Some("subscription-required"),
84 "unexpected-request" => Some("unexpected-request"),
85 "not-well-formed" => Some("not-well-formed"),
86 "invalid-xml" => Some("invalid-xml"),
87 "xml-not-well-formed" => Some("xml-not-well-formed"),
88 "resource-constraint" => Some("resource-constraint"),
89 "policy-violation" => Some("policy-violation"),
90 "service-unavailable" => Some("service-unavailable"),
91 "internal-server-error" => Some("internal-server-error"),
92 "item-not-found" => Some("item-not-found"),
93 "bad-request" => Some("bad-request"),
94 "not-allowed" => Some("not-allowed"),
95 "not-acceptable" => Some("not-acceptable"),
96 _ => None,
97 }
98}
99
100enum Value<'a> {
101 Text(&'a str),
102 Jid(ObservedJid<'a>),
103}
104enum Content {
105 Empty,
106 Bytes(usize),
107 Text(usize),
108 Children(usize),
109}
110trait Shape {
111 fn tag(&self) -> &str;
112 fn attrs_len(&self) -> usize;
113 fn attr(&self, index: usize) -> Option<(&str, Value<'_>)>;
114 fn content(&self) -> Content;
115 fn child(&self, index: usize) -> Option<&dyn Shape>;
116}
117impl Shape for Node {
118 fn tag(&self) -> &str {
119 &self.tag
120 }
121 fn attrs_len(&self) -> usize {
122 self.attrs.len()
123 }
124 fn attr(&self, index: usize) -> Option<(&str, Value<'_>)> {
125 self.attrs.iter().nth(index).map(|(k, v)| {
126 (
127 k.as_ref(),
128 match v {
129 NodeValue::String(s) => Value::Text(s.as_str()),
130 NodeValue::Jid(j) => Value::Jid(j.observe()),
131 },
132 )
133 })
134 }
135 fn content(&self) -> Content {
136 match self.content.as_ref() {
137 None => Content::Empty,
138 Some(NodeContent::Bytes(b)) => Content::Bytes(b.len()),
139 Some(NodeContent::String(s)) => Content::Text(s.len()),
140 Some(NodeContent::Nodes(n)) => Content::Children(n.len()),
141 }
142 }
143 fn child(&self, index: usize) -> Option<&dyn Shape> {
144 self.children()?.get(index).map(|n| n as &dyn Shape)
145 }
146}
147impl Shape for NodeRef<'_> {
148 fn tag(&self) -> &str {
149 self.tag.as_ref()
150 }
151 fn attrs_len(&self) -> usize {
152 self.attrs.len()
153 }
154 fn attr(&self, index: usize) -> Option<(&str, Value<'_>)> {
155 self.attrs.iter().nth(index).map(|(k, v)| {
156 (
157 k.as_ref(),
158 match v {
159 ValueRef::String(s) => Value::Text(s.as_ref()),
160 ValueRef::Jid(j) => Value::Jid(j.observe()),
161 },
162 )
163 })
164 }
165 fn content(&self) -> Content {
166 match self.content.as_ref() {
167 None => Content::Empty,
168 Some(NodeContentRef::Bytes(b)) => Content::Bytes(b.len()),
169 Some(NodeContentRef::String(s)) => Content::Text(s.len()),
170 Some(NodeContentRef::Nodes(n)) => Content::Children(n.len()),
171 }
172 }
173 fn child(&self, index: usize) -> Option<&dyn Shape> {
174 self.children()?.get(index).map(|n| n as &dyn Shape)
175 }
176}
177
178pub struct NodeSummary<'a>(&'a dyn Shape);
182impl<'a> From<&'a Node> for NodeSummary<'a> {
183 fn from(node: &'a Node) -> Self {
184 Self(node)
185 }
186}
187impl<'a, 'data> From<&'a NodeRef<'data>> for NodeSummary<'a> {
188 fn from(node: &'a NodeRef<'data>) -> Self {
189 Self(node)
190 }
191}
192impl fmt::Display for NodeSummary<'_> {
193 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194 format_node(self.0, f, 0, &mut 32)
195 }
196}
197impl fmt::Debug for NodeSummary<'_> {
198 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
199 fmt::Display::fmt(self, f)
200 }
201}
202fn format_node(
203 node: &dyn Shape,
204 f: &mut fmt::Formatter<'_>,
205 depth: usize,
206 budget: &mut usize,
207) -> fmt::Result {
208 if *budget == 0 {
209 return f.write_str("...");
210 }
211 *budget -= 1;
212 write!(f, "<{}", protocol_atom(node.tag()).unwrap_or("unknown"))?;
213 for index in 0..node.attrs_len().min(16) {
214 let Some((key, value)) = node.attr(index) else {
215 break;
216 };
217 match (key, value) {
218 ("id" | "stanza_id" | "message_id", Value::Text(s)) => {
219 write!(f, " {key}={}", ObservedId::new(s))?
220 }
221 ("from" | "to" | "participant" | "recipient", Value::Text(s)) => {
222 write!(f, " {key}={}", ObservedJid::from(s))?
223 }
224 ("from" | "to" | "participant" | "recipient", Value::Jid(j)) => {
225 write!(f, " {key}={j}")?
226 }
227 ("code" | "error_code" | "error", Value::Text(s)) if s.len() <= 5 => {
228 if let Ok(code) = s.parse::<u16>() {
229 write!(f, " {key}={code}")?;
230 }
231 }
232 (
233 "type" | "reason" | "status" | "stage" | "class" | "xmlns" | "text",
234 Value::Text(s),
235 ) => {
236 if s.len() <= 5
237 && let Ok(code) = s.parse::<u16>()
238 {
239 write!(f, " {key}={code}")?;
240 } else {
241 write!(f, " {key}={}", ProtocolText::new(s))?;
242 }
243 }
244 ("backoff" | "retry" | "v", Value::Text(s)) if s.len() <= 10 => {
245 if let Ok(number) = s.parse::<u32>() {
246 write!(f, " {key}={number}")?;
247 }
248 }
249 _ => {}
250 }
251 }
252 write!(f, " attrs={}", node.attrs_len())?;
253 match node.content() {
254 Content::Empty => f.write_str(" body=none")?,
255 Content::Bytes(n) => write!(f, " body=bytes({n})")?,
256 Content::Text(n) => write!(f, " body=text({n})")?,
257 Content::Children(n) => {
258 write!(f, " children={n}")?;
259 if depth < 2 && *budget > 0 {
260 f.write_str("[")?;
261 let limit = n.min(8);
262 for index in 0..limit {
263 if index > 0 {
264 f.write_str(", ")?;
265 }
266 if let Some(child) = node.child(index) {
267 format_node(child, f, depth + 1, budget)?;
268 }
269 if *budget == 0 {
270 break;
271 }
272 }
273 if n > limit || *budget == 0 {
274 f.write_str(", ...")?;
275 }
276 f.write_str("]")?;
277 }
278 }
279 }
280 f.write_str(">")
281}