1use std::collections::BTreeMap;
2
3use crate::error::{AppError, Result};
4
5#[derive(Debug, Clone, PartialEq)]
6pub enum MsgValue {
7 Nil,
8 Bool(bool),
9 Int(i64),
10 UInt(u64),
11 Float(f64),
12 String(String),
13 Array(Vec<MsgValue>),
14 Map(BTreeMap<String, MsgValue>),
15}
16
17impl MsgValue {
18 pub fn get(&self, key: &str) -> Option<&MsgValue> {
19 match self {
20 MsgValue::Map(map) => map.get(key),
21 _ => None,
22 }
23 }
24
25 pub fn as_str(&self) -> Option<&str> {
26 match self {
27 MsgValue::String(value) => Some(value.as_str()),
28 _ => None,
29 }
30 }
31
32 pub fn as_array(&self) -> Option<&[MsgValue]> {
33 match self {
34 MsgValue::Array(values) => Some(values.as_slice()),
35 _ => None,
36 }
37 }
38
39 pub fn as_map(&self) -> Option<&BTreeMap<String, MsgValue>> {
40 match self {
41 MsgValue::Map(map) => Some(map),
42 _ => None,
43 }
44 }
45
46 pub fn as_u64(&self) -> Option<u64> {
47 match self {
48 MsgValue::UInt(value) => Some(*value),
49 MsgValue::Int(value) if *value >= 0 => Some(*value as u64),
50 _ => None,
51 }
52 }
53}
54
55pub fn encode(value: &MsgValue) -> Vec<u8> {
56 let mut buffer = Vec::new();
57 encode_value(value, &mut buffer);
58 buffer
59}
60
61pub fn decode(bytes: &[u8]) -> Result<MsgValue> {
62 let (value, consumed) = decode_value(bytes, 0)?;
63 if consumed != bytes.len() {
64 return Err(AppError::Msgpack(
65 "trailing bytes in msgpack payload".to_string(),
66 ));
67 }
68 Ok(value)
69}
70
71fn encode_value(value: &MsgValue, buffer: &mut Vec<u8>) {
72 match value {
73 MsgValue::Nil => buffer.push(0xc0),
74 MsgValue::Bool(false) => buffer.push(0xc2),
75 MsgValue::Bool(true) => buffer.push(0xc3),
76 MsgValue::Int(value) => encode_int(*value, buffer),
77 MsgValue::UInt(value) => encode_uint(*value, buffer),
78 MsgValue::Float(value) => {
79 buffer.push(0xcb);
80 buffer.extend_from_slice(&value.to_be_bytes());
81 }
82 MsgValue::String(value) => encode_str(value, buffer),
83 MsgValue::Array(values) => encode_array(values, buffer),
84 MsgValue::Map(map) => encode_map(map, buffer),
85 }
86}
87
88fn encode_uint(value: u64, buffer: &mut Vec<u8>) {
89 match value {
90 0..=127 => buffer.push(value as u8),
91 128..=255 => {
92 buffer.push(0xcc);
93 buffer.push(value as u8);
94 }
95 256..=65_535 => {
96 buffer.push(0xcd);
97 buffer.extend_from_slice(&(value as u16).to_be_bytes());
98 }
99 65_536..=4_294_967_295 => {
100 buffer.push(0xce);
101 buffer.extend_from_slice(&(value as u32).to_be_bytes());
102 }
103 _ => {
104 buffer.push(0xcf);
105 buffer.extend_from_slice(&value.to_be_bytes());
106 }
107 }
108}
109
110fn encode_int(value: i64, buffer: &mut Vec<u8>) {
111 if (-32..=127).contains(&value) {
112 if value >= 0 {
113 buffer.push(value as u8);
114 } else {
115 buffer.push((value as i8) as u8);
116 }
117 return;
118 }
119
120 if (-128..=-33).contains(&value) {
121 buffer.push(0xd0);
122 buffer.push(value as i8 as u8);
123 } else if (-32_768..=-129).contains(&value) {
124 buffer.push(0xd1);
125 buffer.extend_from_slice(&(value as i16).to_be_bytes());
126 } else if (-2_147_483_648..=-32_769).contains(&value) {
127 buffer.push(0xd2);
128 buffer.extend_from_slice(&(value as i32).to_be_bytes());
129 } else {
130 buffer.push(0xd3);
131 buffer.extend_from_slice(&value.to_be_bytes());
132 }
133}
134
135fn encode_str(value: &str, buffer: &mut Vec<u8>) {
136 let bytes = value.as_bytes();
137 let len = bytes.len();
138 if len <= 31 {
139 buffer.push(0xa0 | (len as u8));
140 } else if len <= 255 {
141 buffer.push(0xd9);
142 buffer.push(len as u8);
143 } else if len <= 65_535 {
144 buffer.push(0xda);
145 buffer.extend_from_slice(&(len as u16).to_be_bytes());
146 } else {
147 buffer.push(0xdb);
148 buffer.extend_from_slice(&(len as u32).to_be_bytes());
149 }
150 buffer.extend_from_slice(bytes);
151}
152
153fn encode_array(values: &[MsgValue], buffer: &mut Vec<u8>) {
154 let len = values.len();
155 if len <= 15 {
156 buffer.push(0x90 | (len as u8));
157 } else if len <= 65_535 {
158 buffer.push(0xdc);
159 buffer.extend_from_slice(&(len as u16).to_be_bytes());
160 } else {
161 buffer.push(0xdd);
162 buffer.extend_from_slice(&(len as u32).to_be_bytes());
163 }
164 for value in values {
165 encode_value(value, buffer);
166 }
167}
168
169fn encode_map(map: &BTreeMap<String, MsgValue>, buffer: &mut Vec<u8>) {
170 let len = map.len();
171 if len <= 15 {
172 buffer.push(0x80 | (len as u8));
173 } else if len <= 65_535 {
174 buffer.push(0xde);
175 buffer.extend_from_slice(&(len as u16).to_be_bytes());
176 } else {
177 buffer.push(0xdf);
178 buffer.extend_from_slice(&(len as u32).to_be_bytes());
179 }
180 for (key, value) in map {
181 encode_str(key, buffer);
182 encode_value(value, buffer);
183 }
184}
185
186fn decode_value(bytes: &[u8], index: usize) -> Result<(MsgValue, usize)> {
187 let prefix = *bytes
188 .get(index)
189 .ok_or_else(|| AppError::Msgpack("unexpected end of msgpack payload".to_string()))?;
190
191 match prefix {
192 0xc0 => Ok((MsgValue::Nil, index + 1)),
193 0xc2 => Ok((MsgValue::Bool(false), index + 1)),
194 0xc3 => Ok((MsgValue::Bool(true), index + 1)),
195 0xc4 => {
196 let len = read_u8(bytes, index + 1)? as usize;
197 let slice = bytes
198 .get(index + 2..index + 2 + len)
199 .ok_or_else(|| {
200 AppError::Msgpack("unexpected end of msgpack binary data".to_string())
201 })?;
202 let value = String::from_utf8_lossy(slice).into_owned();
203 Ok((MsgValue::String(value), index + 2 + len))
204 }
205 0xc5 => {
206 let len = read_u16(bytes, index + 1)? as usize;
207 let slice = bytes
208 .get(index + 3..index + 3 + len)
209 .ok_or_else(|| {
210 AppError::Msgpack("unexpected end of msgpack binary data".to_string())
211 })?;
212 let value = String::from_utf8_lossy(slice).into_owned();
213 Ok((MsgValue::String(value), index + 3 + len))
214 }
215 0xc6 => {
216 let len = read_u32(bytes, index + 1)? as usize;
217 let slice = bytes
218 .get(index + 5..index + 5 + len)
219 .ok_or_else(|| {
220 AppError::Msgpack("unexpected end of msgpack binary data".to_string())
221 })?;
222 let value = String::from_utf8_lossy(slice).into_owned();
223 Ok((MsgValue::String(value), index + 5 + len))
224 }
225 0xca => {
226 let end = index + 5;
227 let slice = bytes
228 .get(index + 1..end)
229 .ok_or_else(|| AppError::Msgpack("unexpected end of msgpack payload".to_string()))?;
230 let value = f32::from_be_bytes([slice[0], slice[1], slice[2], slice[3]]);
231 Ok((MsgValue::Float(value as f64), end))
232 }
233 0xcb => {
234 let end = index + 9;
235 let slice = bytes
236 .get(index + 1..end)
237 .ok_or_else(|| AppError::Msgpack("unexpected end of msgpack payload".to_string()))?;
238 let value = f64::from_be_bytes([
239 slice[0], slice[1], slice[2], slice[3],
240 slice[4], slice[5], slice[6], slice[7],
241 ]);
242 Ok((MsgValue::Float(value), end))
243 }
244 0xcc => {
245 let value = read_u8(bytes, index + 1)? as u64;
246 Ok((MsgValue::UInt(value), index + 2))
247 }
248 0xcd => {
249 let value = read_u16(bytes, index + 1)? as u64;
250 Ok((MsgValue::UInt(value), index + 3))
251 }
252 0xce => {
253 let value = read_u32(bytes, index + 1)? as u64;
254 Ok((MsgValue::UInt(value), index + 5))
255 }
256 0xcf => {
257 let value = read_u64(bytes, index + 1)?;
258 Ok((MsgValue::UInt(value), index + 9))
259 }
260 0xd0 => {
261 let value = read_i8(bytes, index + 1)? as i64;
262 Ok((MsgValue::Int(value), index + 2))
263 }
264 0xd1 => {
265 let value = read_i16(bytes, index + 1)? as i64;
266 Ok((MsgValue::Int(value), index + 3))
267 }
268 0xd2 => {
269 let value = read_i32(bytes, index + 1)? as i64;
270 Ok((MsgValue::Int(value), index + 5))
271 }
272 0xd3 => {
273 let value = read_i64(bytes, index + 1)?;
274 Ok((MsgValue::Int(value), index + 9))
275 }
276 0xd9 => {
277 let len = read_u8(bytes, index + 1)? as usize;
278 decode_str(bytes, index + 2, len)
279 }
280 0xda => {
281 let len = read_u16(bytes, index + 1)? as usize;
282 decode_str(bytes, index + 3, len)
283 }
284 0xdb => {
285 let len = read_u32(bytes, index + 1)? as usize;
286 decode_str(bytes, index + 5, len)
287 }
288 0xdc => {
289 let len = read_u16(bytes, index + 1)? as usize;
290 decode_array(bytes, index + 3, len)
291 }
292 0xdd => {
293 let len = read_u32(bytes, index + 1)? as usize;
294 decode_array(bytes, index + 5, len)
295 }
296 0xde => {
297 let len = read_u16(bytes, index + 1)? as usize;
298 decode_map(bytes, index + 3, len)
299 }
300 0xdf => {
301 let len = read_u32(bytes, index + 1)? as usize;
302 decode_map(bytes, index + 5, len)
303 }
304 0x80..=0x8f => {
305 let len = (prefix & 0x0f) as usize;
306 decode_map(bytes, index + 1, len)
307 }
308 0x90..=0x9f => {
309 let len = (prefix & 0x0f) as usize;
310 decode_array(bytes, index + 1, len)
311 }
312 0xa0..=0xbf => {
313 let len = (prefix & 0x1f) as usize;
314 decode_str(bytes, index + 1, len)
315 }
316 0xe0..=0xff => Ok((MsgValue::Int((prefix as i8) as i64), index + 1)),
317 0x00..=0x7f => Ok((MsgValue::UInt(prefix as u64), index + 1)),
318 _ => Err(AppError::Msgpack(format!(
319 "unsupported msgpack prefix: 0x{prefix:02x}"
320 ))),
321 }
322}
323
324fn decode_str(bytes: &[u8], index: usize, len: usize) -> Result<(MsgValue, usize)> {
325 let end = index
326 .checked_add(len)
327 .ok_or_else(|| AppError::Msgpack("msgpack string length overflow".to_string()))?;
328 let slice = bytes
329 .get(index..end)
330 .ok_or_else(|| AppError::Msgpack("unexpected end of msgpack string".to_string()))?;
331 let value = String::from_utf8(slice.to_vec())
332 .map_err(|e| AppError::Msgpack(format!("invalid utf-8 string: {e}")))?;
333 Ok((MsgValue::String(value), end))
334}
335
336fn decode_array(bytes: &[u8], mut index: usize, len: usize) -> Result<(MsgValue, usize)> {
337 let mut values = Vec::with_capacity(len);
338 for _ in 0..len {
339 let (value, next) = decode_value(bytes, index)?;
340 values.push(value);
341 index = next;
342 }
343 Ok((MsgValue::Array(values), index))
344}
345
346fn decode_map(bytes: &[u8], mut index: usize, len: usize) -> Result<(MsgValue, usize)> {
347 let mut map = BTreeMap::new();
348 for _ in 0..len {
349 let (key_value, next_key) = decode_value(bytes, index)?;
350 index = next_key;
351 let key = key_value
352 .as_str()
353 .ok_or_else(|| AppError::Msgpack("msgpack map key was not a string".to_string()))?;
354 let (value, next_value) = decode_value(bytes, index)?;
355 index = next_value;
356 map.insert(key.to_string(), value);
357 }
358 Ok((MsgValue::Map(map), index))
359}
360
361fn read_u8(bytes: &[u8], index: usize) -> Result<u8> {
362 bytes
363 .get(index)
364 .copied()
365 .ok_or_else(|| AppError::Msgpack("unexpected end of msgpack payload".to_string()))
366}
367
368fn read_i8(bytes: &[u8], index: usize) -> Result<i8> {
369 Ok(read_u8(bytes, index)? as i8)
370}
371
372fn read_u16(bytes: &[u8], index: usize) -> Result<u16> {
373 let end = index + 2;
374 let slice = bytes
375 .get(index..end)
376 .ok_or_else(|| AppError::Msgpack("unexpected end of msgpack payload".to_string()))?;
377 Ok(u16::from_be_bytes([slice[0], slice[1]]))
378}
379
380fn read_i16(bytes: &[u8], index: usize) -> Result<i16> {
381 Ok(i16::from_be_bytes(read_u16(bytes, index)?.to_be_bytes()))
382}
383
384fn read_u32(bytes: &[u8], index: usize) -> Result<u32> {
385 let end = index + 4;
386 let slice = bytes
387 .get(index..end)
388 .ok_or_else(|| AppError::Msgpack("unexpected end of msgpack payload".to_string()))?;
389 Ok(u32::from_be_bytes([slice[0], slice[1], slice[2], slice[3]]))
390}
391
392fn read_i32(bytes: &[u8], index: usize) -> Result<i32> {
393 Ok(i32::from_be_bytes(read_u32(bytes, index)?.to_be_bytes()))
394}
395
396fn read_u64(bytes: &[u8], index: usize) -> Result<u64> {
397 let end = index + 8;
398 let slice = bytes
399 .get(index..end)
400 .ok_or_else(|| AppError::Msgpack("unexpected end of msgpack payload".to_string()))?;
401 Ok(u64::from_be_bytes([
402 slice[0], slice[1], slice[2], slice[3], slice[4], slice[5], slice[6], slice[7],
403 ]))
404}
405
406fn read_i64(bytes: &[u8], index: usize) -> Result<i64> {
407 Ok(i64::from_be_bytes(read_u64(bytes, index)?.to_be_bytes()))
408}
409
410#[cfg(test)]
411mod tests {
412 use super::*;
413
414 #[test]
415 fn roundtrip_nil() {
416 let v = MsgValue::Nil;
417 let bytes = encode(&v);
418 let decoded = decode(&bytes).unwrap();
419 assert_eq!(v, decoded);
420 }
421
422 #[test]
423 fn roundtrip_bool() {
424 for b in [true, false] {
425 let v = MsgValue::Bool(b);
426 let bytes = encode(&v);
427 let decoded = decode(&bytes).unwrap();
428 assert_eq!(v, decoded);
429 }
430 }
431
432 #[test]
433 fn roundtrip_positive_fixint() {
434 for i in [0u64, 1, 127] {
435 let v = MsgValue::UInt(i);
436 let bytes = encode(&v);
437 let decoded = decode(&bytes).unwrap();
438 assert_eq!(v, decoded);
439 }
440 }
441
442 #[test]
443 fn roundtrip_u8() {
444 let v = MsgValue::UInt(200);
445 let bytes = encode(&v);
446 assert_eq!(bytes[0], 0xcc);
447 assert_eq!(bytes[1], 200);
448 let decoded = decode(&bytes).unwrap();
449 assert_eq!(v, decoded);
450 }
451
452 #[test]
453 fn roundtrip_u16() {
454 let v = MsgValue::UInt(1000);
455 let bytes = encode(&v);
456 assert_eq!(bytes[0], 0xcd);
457 let decoded = decode(&bytes).unwrap();
458 assert_eq!(v, decoded);
459 }
460
461 #[test]
462 fn roundtrip_u32() {
463 let v = MsgValue::UInt(100_000);
464 let bytes = encode(&v);
465 assert_eq!(bytes[0], 0xce);
466 let decoded = decode(&bytes).unwrap();
467 assert_eq!(v, decoded);
468 }
469
470 #[test]
471 fn roundtrip_negative_fixint() {
472 for i in [-1i64, -32] {
473 let v = MsgValue::Int(i);
474 let bytes = encode(&v);
475 let decoded = decode(&bytes).unwrap();
476 assert_eq!(v, decoded);
477 }
478 }
479
480 #[test]
481 fn roundtrip_i8() {
482 let v = MsgValue::Int(-100);
483 let bytes = encode(&v);
484 assert_eq!(bytes[0], 0xd0);
485 let decoded = decode(&bytes).unwrap();
486 assert_eq!(v, decoded);
487 }
488
489 #[test]
490 fn roundtrip_fixstr() {
491 let v = MsgValue::String("hello".to_string());
492 let bytes = encode(&v);
493 assert_eq!(bytes[0], 0xa5);
494 let decoded = decode(&bytes).unwrap();
495 assert_eq!(v, decoded);
496 }
497
498 #[test]
499 fn roundtrip_str8() {
500 let s = "a".repeat(32);
501 let v = MsgValue::String(s);
502 let bytes = encode(&v);
503 assert_eq!(bytes[0], 0xd9);
504 assert_eq!(bytes[1], 32);
505 let decoded = decode(&bytes).unwrap();
506 assert_eq!(v, decoded);
507 }
508
509 #[test]
510 fn roundtrip_fixarray() {
511 let v = MsgValue::Array(vec![
512 MsgValue::UInt(1),
513 MsgValue::String("two".to_string()),
514 MsgValue::Bool(true),
515 ]);
516 let bytes = encode(&v);
517 assert_eq!(bytes[0], 0x93);
518 let decoded = decode(&bytes).unwrap();
519 assert_eq!(v, decoded);
520 }
521
522 #[test]
523 fn roundtrip_fixmap() {
524 let mut map = BTreeMap::new();
525 map.insert("key".to_string(), MsgValue::String("value".to_string()));
526 let v = MsgValue::Map(map);
527 let bytes = encode(&v);
528 assert_eq!(bytes[0], 0x81);
529 let decoded = decode(&bytes).unwrap();
530 assert_eq!(v, decoded);
531 }
532
533 #[test]
534 fn decode_bin8() {
535 let bytes = vec![0xc4, 0x05, 0x68, 0x65, 0x6c, 0x6c, 0x6f];
537 let decoded = decode(&bytes).unwrap();
538 assert_eq!(decoded, MsgValue::String("hello".to_string()));
539 }
540
541 #[test]
542 fn decode_bin16() {
543 let mut bytes = vec![0xc5, 0x00, 0x05, 0x77, 0x6f, 0x72, 0x6c, 0x64];
545 let decoded = decode(&bytes).unwrap();
546 assert_eq!(decoded, MsgValue::String("world".to_string()));
547
548 let long = "x".repeat(300);
550 bytes = vec![0xc5, 0x01, 0x2c];
551 bytes.extend_from_slice(long.as_bytes());
552 let decoded = decode(&bytes).unwrap();
553 assert_eq!(decoded, MsgValue::String(long));
554 }
555
556 #[test]
557 fn decode_bin32() {
558 let long = "z".repeat(70000);
559 let mut bytes = vec![0xc6, 0x00, 0x01, 0x11, 0x70];
560 bytes.extend_from_slice(long.as_bytes());
561 let decoded = decode(&bytes).unwrap();
562 assert_eq!(decoded, MsgValue::String(long));
563 }
564
565 #[test]
566 fn decode_float32() {
567 let mut bytes = vec![0xca];
568 bytes.extend_from_slice(&3.14f32.to_be_bytes());
569 let decoded = decode(&bytes).unwrap();
570 match decoded {
571 MsgValue::Float(f) => assert!((f - 3.14).abs() < 0.001),
572 _ => panic!("expected Float"),
573 }
574 }
575
576 #[test]
577 fn decode_float64() {
578 let mut bytes = vec![0xcb];
579 bytes.extend_from_slice(&std::f64::consts::PI.to_be_bytes());
580 let decoded = decode(&bytes).unwrap();
581 match decoded {
582 MsgValue::Float(f) => assert!((f - std::f64::consts::PI).abs() < 1e-15),
583 _ => panic!("expected Float"),
584 }
585 }
586
587 #[test]
588 fn decode_msf_auth_response() {
589 let mut bytes = Vec::new();
592 bytes.push(0x82);
594 bytes.extend_from_slice(&[0xc4, 0x06, 0x72, 0x65, 0x73, 0x75, 0x6c, 0x74]);
596 bytes.extend_from_slice(&[0xc4, 0x07, 0x73, 0x75, 0x63, 0x63, 0x65, 0x73, 0x73]);
598 bytes.extend_from_slice(&[0xc4, 0x05, 0x74, 0x6f, 0x6b, 0x65, 0x6e]);
600 bytes.extend_from_slice(&[0xc4, 0x08, 0x61, 0x62, 0x63, 0x64, 0x31, 0x32, 0x33, 0x34]);
602
603 let decoded = decode(&bytes).unwrap();
604 let result = decoded.get("result").and_then(|v| v.as_str()).unwrap();
605 let token = decoded.get("token").and_then(|v| v.as_str()).unwrap();
606 assert_eq!(result, "success");
607 assert_eq!(token, "abcd1234");
608 }
609
610 #[test]
611 fn decode_msf_error_response() {
612 let mut bytes = Vec::new();
615 bytes.push(0x82); bytes.extend_from_slice(&[0xc4, 0x05, 0x65, 0x72, 0x72, 0x6f, 0x72]); bytes.push(0xc3); bytes.extend_from_slice(&[0xc4, 0x0c, 0x65, 0x72, 0x72, 0x6f, 0x72, 0x5f, 0x73, 0x74, 0x72, 0x69, 0x6e, 0x67]); bytes.extend_from_slice(&[0xc4, 0x16, 0x49, 0x6e, 0x76, 0x61, 0x6c, 0x69, 0x64, 0x20, 0x4d, 0x65, 0x73, 0x73, 0x61, 0x67, 0x65, 0x20, 0x46, 0x6f, 0x72, 0x6d, 0x61, 0x74]); let decoded = decode(&bytes).unwrap();
622 let error = decoded.get("error").unwrap();
623 assert_eq!(error, &MsgValue::Bool(true));
624 let error_string = decoded.get("error_string").and_then(|v| v.as_str()).unwrap();
625 assert_eq!(error_string, "Invalid Message Format");
626 }
627
628 #[test]
629 fn decode_trailing_bytes_fails() {
630 let mut bytes = vec![0xa5, 0x68, 0x65, 0x6c, 0x6c, 0x6f]; bytes.push(0x00); let result = decode(&bytes);
633 assert!(result.is_err());
634 assert!(result.unwrap_err().to_string().contains("trailing bytes"));
635 }
636
637 #[test]
638 fn encode_array_format_auth_login() {
639 let v = MsgValue::Array(vec![
642 MsgValue::String("auth.login".to_string()),
643 MsgValue::String("Mithun".to_string()),
644 MsgValue::String("Mithun@2806".to_string()),
645 ]);
646 let bytes = encode(&v);
647 assert_eq!(bytes[0], 0x93);
649 let decoded = decode(&bytes).unwrap();
650 assert_eq!(v, decoded);
651 }
652}