1use std::borrow::Cow;
2use std::str::FromStr;
3
4use crate::error::{BinaryError, Result};
5use crate::jid::Jid;
6use crate::node::{Attrs, Node, NodeRef, NodeStr, NodeValue, ValueRef};
7
8fn coerce_protocol_bool(s: &str) -> Option<bool> {
13 match s {
14 "1" | "true" | "True" | "t" | "T" | "TRUE" => Some(true),
15 "0" | "false" | "False" | "f" | "F" | "FALSE" => Some(false),
16 _ => None,
17 }
18}
19
20pub struct AttrParser<'a> {
21 pub attrs: &'a Attrs,
22 pub errors: Vec<BinaryError>,
23}
24
25pub struct AttrParserRef<'a> {
26 pub(crate) attrs: &'a [(NodeStr<'a>, ValueRef<'a>)],
27 pub errors: Vec<BinaryError>,
28}
29
30impl<'a> AttrParserRef<'a> {
31 pub fn new(node: &'a NodeRef<'a>) -> Self {
32 Self {
33 attrs: node.attrs.as_slice(),
34 errors: Vec::new(),
35 }
36 }
37
38 pub fn ok(&self) -> bool {
39 self.errors.is_empty()
40 }
41
42 pub fn finish(&self) -> Result<()> {
43 if self.ok() {
44 Ok(())
45 } else {
46 Err(BinaryError::AttrList(self.errors.clone()))
47 }
48 }
49
50 fn get_raw(&mut self, key: &str, require: bool) -> Option<&'a ValueRef<'a>> {
51 let val = self.attrs.iter().find(|(k, _)| **k == *key).map(|(_, v)| v);
52
53 if require && val.is_none() {
54 self.errors.push(BinaryError::AttrParse(format!(
55 "Required attribute '{key}' not found"
56 )));
57 }
58
59 val
60 }
61
62 pub fn optional_string(&mut self, key: &str) -> Option<Cow<'a, str>> {
66 self.get_raw(key, false).map(|v| v.as_str())
67 }
68
69 pub fn required_string(&mut self, key: &str) -> Result<Cow<'a, str>> {
74 self.optional_string(key)
75 .ok_or_else(|| BinaryError::MissingAttr(key.to_string()))
76 }
77
78 pub fn optional_jid(&mut self, key: &str) -> Option<Jid> {
82 self.get_jid(key, false)
83 }
84
85 fn get_jid(&mut self, key: &str, require: bool) -> Option<Jid> {
90 self.get_raw(key, require).and_then(|v| match v.to_jid() {
91 Some(jid) => Some(jid),
92 None => {
93 if let ValueRef::String(s) = v {
95 self.errors.push(BinaryError::AttrParse(format!(
96 "Invalid JID for key {} ({} bytes)",
97 crate::diagnostics::ProtocolText::new(key),
98 s.len()
99 )));
100 }
101 None
102 }
103 })
104 }
105
106 pub fn optional_jid_result(&mut self, key: &str) -> Result<Option<Jid>> {
108 match self.get_raw(key, false) {
109 None => Ok(None),
110 Some(ValueRef::Jid(jid)) => Ok(Some(jid.to_owned())),
111 Some(ValueRef::String(value)) => {
112 Jid::from_str(value).map(Some).map_err(BinaryError::from)
113 }
114 }
115 }
116
117 pub fn required_jid(&mut self, key: &str) -> Result<Jid> {
122 self.optional_jid_result(key)?
123 .ok_or_else(|| BinaryError::MissingAttr(key.to_string()))
124 }
125
126 pub fn jid(&mut self, key: &str) -> Jid {
127 self.get_jid(key, true).unwrap_or_default()
128 }
129
130 pub fn non_ad_jid(&mut self, key: &str) -> Jid {
131 self.jid(key).to_non_ad()
132 }
133
134 fn get_string_value(&mut self, key: &str, require: bool) -> Option<Cow<'a, str>> {
135 self.get_raw(key, require).map(|v| v.as_str())
136 }
137
138 fn get_bool(&mut self, key: &str, require: bool) -> Option<bool> {
139 self.get_string_value(key, require)
140 .and_then(|s| match coerce_protocol_bool(&s) {
141 Some(val) => Some(val),
142 None => {
143 self.errors.push(BinaryError::AttrParse(format!(
144 "Failed to parse bool for key {} ({} bytes)",
145 crate::diagnostics::ProtocolText::new(key),
146 s.len()
147 )));
148 None
149 }
150 })
151 }
152
153 pub fn optional_bool_value(&mut self, key: &str) -> Option<bool> {
155 self.get_bool(key, false)
156 }
157
158 pub fn optional_bool(&mut self, key: &str) -> bool {
159 self.optional_bool_value(key).unwrap_or(false)
160 }
161
162 pub fn bool(&mut self, key: &str) -> bool {
163 self.get_bool(key, true).unwrap_or(false)
164 }
165
166 pub fn optional_u64(&mut self, key: &str) -> Option<u64> {
167 self.get_string_value(key, false)
168 .and_then(|s| match s.parse::<u64>() {
169 Ok(val) => Some(val),
170 Err(e) => {
171 self.errors.push(BinaryError::AttrParse(format!(
172 "Failed to parse u64 for key {} ({} bytes): {e}",
173 crate::diagnostics::ProtocolText::new(key),
174 s.len()
175 )));
176 None
177 }
178 })
179 }
180
181 pub fn unix_time(&mut self, key: &str) -> i64 {
182 self.get_i64(key, true).unwrap_or_default()
183 }
184
185 pub fn optional_unix_time(&mut self, key: &str) -> Option<i64> {
186 self.get_i64(key, false)
187 }
188
189 pub fn unix_milli(&mut self, key: &str) -> i64 {
190 self.get_i64(key, true).unwrap_or_default()
191 }
192
193 pub fn optional_unix_milli(&mut self, key: &str) -> Option<i64> {
194 self.get_i64(key, false)
195 }
196
197 fn get_i64(&mut self, key: &str, require: bool) -> Option<i64> {
198 self.get_string_value(key, require)
199 .and_then(|s| match s.parse::<i64>() {
200 Ok(val) => Some(val),
201 Err(e) => {
202 self.errors.push(BinaryError::AttrParse(format!(
203 "Failed to parse i64 for key {} ({} bytes): {e}",
204 crate::diagnostics::ProtocolText::new(key),
205 s.len()
206 )));
207 None
208 }
209 })
210 }
211}
212
213impl<'a> AttrParser<'a> {
214 pub fn new(node: &'a Node) -> Self {
215 Self {
216 attrs: &node.attrs,
217 errors: Vec::new(),
218 }
219 }
220
221 pub fn ok(&self) -> bool {
222 self.errors.is_empty()
223 }
224
225 pub fn finish(&self) -> Result<()> {
226 if self.ok() {
227 Ok(())
228 } else {
229 Err(BinaryError::AttrList(self.errors.clone()))
230 }
231 }
232
233 fn get_raw(&mut self, key: &str, require: bool) -> Option<&'a NodeValue> {
234 let val = self.attrs.get(key);
235 if require && val.is_none() {
236 self.errors.push(BinaryError::AttrParse(format!(
237 "Required attribute '{key}' not found"
238 )));
239 }
240 val
241 }
242
243 fn get_string_value(&mut self, key: &str, require: bool) -> Option<Cow<'a, str>> {
245 self.get_raw(key, require).map(|v| match v {
246 NodeValue::String(s) => Cow::Borrowed(s.as_str()),
247 NodeValue::Jid(j) => Cow::Owned(j.to_string()),
248 })
249 }
250
251 pub fn optional_string(&mut self, key: &str) -> Option<Cow<'a, str>> {
256 self.get_raw(key, false).map(|v| v.as_str())
257 }
258
259 pub fn required_string(&mut self, key: &str) -> Result<Cow<'a, str>> {
264 self.optional_string(key)
265 .ok_or_else(|| BinaryError::MissingAttr(key.to_string()))
266 }
267
268 pub fn optional_jid(&mut self, key: &str) -> Option<Jid> {
273 self.get_jid(key, false)
274 }
275
276 fn get_jid(&mut self, key: &str, require: bool) -> Option<Jid> {
281 self.get_raw(key, require).and_then(|v| match v {
282 NodeValue::Jid(j) => Some(j.clone()),
283 NodeValue::String(s) => match Jid::from_str(s) {
284 Ok(jid) => Some(jid),
285 Err(e) => {
286 self.errors.push(BinaryError::from(e));
287 None
288 }
289 },
290 })
291 }
292
293 pub fn required_jid(&mut self, key: &str) -> Result<Jid> {
295 match self
296 .get_raw(key, false)
297 .ok_or_else(|| BinaryError::MissingAttr(key.to_string()))?
298 {
299 NodeValue::Jid(jid) => Ok(jid.clone()),
300 NodeValue::String(value) => Jid::from_str(value).map_err(BinaryError::from),
301 }
302 }
303
304 pub fn jid(&mut self, key: &str) -> Jid {
305 self.get_jid(key, true).unwrap_or_default()
306 }
307
308 pub fn non_ad_jid(&mut self, key: &str) -> Jid {
309 self.jid(key).to_non_ad()
310 }
311
312 fn get_bool(&mut self, key: &str, require: bool) -> Option<bool> {
314 self.get_string_value(key, require)
315 .and_then(|s| match coerce_protocol_bool(&s) {
316 Some(val) => Some(val),
317 None => {
318 self.errors.push(BinaryError::AttrParse(format!(
319 "Failed to parse bool for key {} ({} bytes)",
320 crate::diagnostics::ProtocolText::new(key),
321 s.len()
322 )));
323 None
324 }
325 })
326 }
327
328 pub fn optional_bool_value(&mut self, key: &str) -> Option<bool> {
330 self.get_bool(key, false)
331 }
332
333 pub fn optional_bool(&mut self, key: &str) -> bool {
334 self.optional_bool_value(key).unwrap_or(false)
335 }
336
337 pub fn bool(&mut self, key: &str) -> bool {
338 self.get_bool(key, true).unwrap_or(false)
339 }
340
341 pub fn optional_u64(&mut self, key: &str) -> Option<u64> {
343 self.get_string_value(key, false)
344 .and_then(|s| match s.parse::<u64>() {
345 Ok(val) => Some(val),
346 Err(e) => {
347 self.errors.push(BinaryError::AttrParse(format!(
348 "Failed to parse u64 for key {} ({} bytes): {e}",
349 crate::diagnostics::ProtocolText::new(key),
350 s.len()
351 )));
352 None
353 }
354 })
355 }
356
357 pub fn unix_time(&mut self, key: &str) -> i64 {
358 self.get_i64(key, true).unwrap_or_default()
359 }
360
361 pub fn optional_unix_time(&mut self, key: &str) -> Option<i64> {
362 self.get_i64(key, false)
363 }
364
365 pub fn unix_milli(&mut self, key: &str) -> i64 {
366 self.get_i64(key, true).unwrap_or_default()
367 }
368
369 pub fn optional_unix_milli(&mut self, key: &str) -> Option<i64> {
370 self.get_i64(key, false)
371 }
372
373 fn get_i64(&mut self, key: &str, require: bool) -> Option<i64> {
374 self.get_string_value(key, require)
375 .and_then(|s| match s.parse::<i64>() {
376 Ok(val) => Some(val),
377 Err(e) => {
378 self.errors.push(BinaryError::AttrParse(format!(
379 "Failed to parse i64 for key {} ({} bytes): {e}",
380 crate::diagnostics::ProtocolText::new(key),
381 s.len()
382 )));
383 None
384 }
385 })
386 }
387}
388
389#[cfg(test)]
390mod required_getter_tests {
391 use super::*;
392 use crate::builder::NodeBuilder;
393
394 #[test]
395 fn rejected_values_do_not_become_nested_error_payloads() {
396 let node = NodeBuilder::new("message")
397 .attr("from", "synthetic-credential")
398 .attr("offline", "synthetic-key-bytes")
399 .attr("count", "synthetic-message-content")
400 .build();
401 let borrowed = node.as_node_ref();
402 let mut parser = AttrParserRef::new(&borrowed);
403 parser.jid("from");
404 parser.bool("offline");
405 parser.optional_u64("count");
406 let error = parser
407 .finish()
408 .expect_err("invalid attribute values must fail");
409 let output = format!("{error}: {error:#?}");
410 for marker in [
411 "synthetic-credential",
412 "synthetic-key-bytes",
413 "synthetic-message-content",
414 ] {
415 assert!(!output.contains(marker));
416 }
417 assert!(output.contains("Invalid JID"));
418 assert!(output.contains("bool"));
419 assert!(output.contains("u64"));
420 assert!(output.contains("offline"));
421 }
422
423 #[test]
429 fn required_getters_keep_reporting_missing_and_invalid_separately() {
430 let node = NodeBuilder::new("message")
431 .attr("from", "5511999998888@s.whatsapp.net")
432 .attr("bad_jid", "@@@")
433 .attr("t", "1700000000")
434 .attr("bad_t", "not-a-number")
435 .build();
436
437 let mut p = AttrParser::new(&node);
439 assert_eq!(p.jid("from").user, "5511999998888");
440 assert_eq!(p.unix_time("t"), 1700000000);
441 assert!(p.ok(), "clean parse should not record errors");
442
443 let mut p = AttrParser::new(&node);
445 assert_eq!(p.jid("nope"), Jid::default());
446 assert!(format!("{:?}", p.errors).contains("not found"));
447
448 let mut p = AttrParser::new(&node);
449 assert_eq!(p.unix_time("nope"), 0);
450 assert!(format!("{:?}", p.errors).contains("not found"));
451
452 let mut p = AttrParser::new(&node);
454 assert_eq!(p.jid("bad_jid"), Jid::default());
455 assert!(!p.ok());
456 assert!(!format!("{:?}", p.errors).contains("not found"));
457
458 let mut p = AttrParser::new(&node);
459 assert_eq!(p.unix_time("bad_t"), 0);
460 assert!(!p.ok());
461 assert!(!format!("{:?}", p.errors).contains("not found"));
462 }
463}
464
465#[cfg(test)]
466mod bool_coercion_tests {
467 use super::coerce_protocol_bool;
468
469 #[test]
470 fn coerce_protocol_bool_accepts_wire_forms() {
471 for t in ["1", "true", "True", "t", "T", "TRUE"] {
473 assert_eq!(coerce_protocol_bool(t), Some(true), "{t}");
474 }
475 for f in ["0", "false", "False", "f", "F", "FALSE"] {
476 assert_eq!(coerce_protocol_bool(f), Some(false), "{f}");
477 }
478 for bad in ["", "yes", "no", "2", "on", "off"] {
480 assert_eq!(coerce_protocol_bool(bad), None, "{bad}");
481 }
482 }
483}