1use bytes::{Buf, BufMut, Bytes, BytesMut};
51#[cfg(feature = "chrono")]
52use chrono::{DateTime, Local, NaiveDate, NaiveTime, Timelike, Utc};
53#[cfg(feature = "indexmap")]
54use indexmap::{IndexMap, IndexSet};
55#[cfg(feature = "rust_decimal")]
56use rust_decimal::Decimal;
57pub use senax_encoder_derive::{Decode, Encode};
58#[cfg(feature = "serde_json")]
59use serde_json::{Map, Number, Value};
60use std::collections::HashMap;
61use std::collections::{BTreeMap, BTreeSet, HashSet};
62use std::sync::Arc;
63use thiserror::Error;
64#[cfg(feature = "ulid")]
65use ulid::Ulid;
66#[cfg(feature = "uuid")]
67use uuid::Uuid;
68
69#[derive(Debug, Error)]
74pub enum EncoderError {
75 #[error("Encode error: {0}")]
77 Encode(String),
78 #[error("Decode error: {0}")]
80 Decode(String),
81 #[error("Insufficient data in buffer")]
83 InsufficientData,
84}
85
86pub type Result<T> = std::result::Result<T, EncoderError>;
90
91pub trait Encoder {
99 fn encode(&self, writer: &mut BytesMut) -> Result<()>;
104
105 fn is_default(&self) -> bool;
108}
109
110pub trait Decoder: Sized {
118 fn decode(reader: &mut Bytes) -> Result<Self>;
123}
124
125pub const TAG_NONE: u8 = 1;
133pub const TAG_SOME: u8 = 2;
135pub const TAG_ZERO: u8 = 3;
137pub const TAG_ONE: u8 = 4;
139pub const TAG_U8_2_BASE: u8 = 5; pub const TAG_U8_127: u8 = 130; pub const TAG_U8: u8 = 131;
144pub const TAG_U16: u8 = 132;
146pub const TAG_U32: u8 = 133;
148pub const TAG_U64: u8 = 134;
150pub const TAG_U128: u8 = 135;
152pub const TAG_NEGATIVE: u8 = 136;
154pub const TAG_F32: u8 = 137;
156pub const TAG_F64: u8 = 138;
158pub const TAG_STRING_BASE: u8 = 139;
160pub const TAG_STRING_LONG: u8 = 180;
162pub const TAG_BINARY: u8 = 181;
164pub const TAG_STRUCT_UNIT: u8 = 182;
166pub const TAG_STRUCT_NAMED: u8 = 183;
168pub const TAG_STRUCT_UNNAMED: u8 = 184;
170pub const TAG_ENUM: u8 = 185;
172pub const TAG_ENUM_NAMED: u8 = 186;
174pub const TAG_ENUM_UNNAMED: u8 = 187;
176pub const TAG_ARRAY_VEC_SET_BASE: u8 = 188;
178pub const TAG_ARRAY_VEC_SET_LONG: u8 = 194;
180pub const TAG_TUPLE: u8 = 195;
182pub const TAG_MAP: u8 = 196;
184pub const TAG_CHRONO_DATETIME: u8 = 197;
186pub const TAG_CHRONO_NAIVE_DATE: u8 = 198;
188pub const TAG_CHRONO_NAIVE_TIME: u8 = 199;
190pub const TAG_DECIMAL: u8 = 200;
192pub const TAG_UUID: u8 = 201;
194pub const TAG_JSON_NULL: u8 = 202;
196pub const TAG_JSON_BOOL: u8 = 203; pub const TAG_JSON_NUMBER: u8 = 204;
198pub const TAG_JSON_STRING: u8 = 205; pub const TAG_JSON_ARRAY: u8 = 206;
200pub const TAG_JSON_OBJECT: u8 = 207;
201
202impl Encoder for bool {
205 fn encode(&self, writer: &mut BytesMut) -> Result<()> {
206 let tag = if !*self { TAG_ZERO } else { TAG_ONE }; writer.put_u8(tag);
208 Ok(())
209 }
210
211 fn is_default(&self) -> bool {
212 !(*self)
213 }
214}
215impl Decoder for bool {
220 fn decode(reader: &mut Bytes) -> Result<Self> {
221 if reader.remaining() == 0 {
222 return Err(EncoderError::InsufficientData);
223 }
224 let tag = reader.get_u8();
225 match tag {
226 TAG_ZERO => Ok(false),
227 TAG_ONE => Ok(true),
228 other => Err(EncoderError::Decode(format!(
229 "Expected bool tag ({} or {}), got {}",
230 TAG_ZERO, TAG_ONE, other
231 ))),
232 }
233 }
234}
235
236#[inline]
243fn decode_u8_from_tag(tag: u8, reader: &mut Bytes) -> Result<u8> {
244 if (TAG_ZERO..=TAG_ZERO + 127).contains(&tag) {
245 Ok(tag - TAG_ZERO)
246 } else if tag == TAG_U8 {
247 if reader.remaining() < 1 {
248 return Err(EncoderError::InsufficientData);
249 }
250 let stored_val = reader.get_u8();
251 stored_val.checked_add(128).ok_or_else(|| {
252 EncoderError::Decode(format!("u8 TAG_U8 value overflow: {}", stored_val))
253 })
254 } else {
255 Err(EncoderError::Decode(format!(
256 "Unexpected tag for u8: {}",
257 tag
258 )))
259 }
260}
261#[inline(never)]
264fn decode_u16_from_tag(tag: u8, reader: &mut Bytes) -> Result<u16> {
265 if (TAG_ZERO..=TAG_ZERO + 127).contains(&tag) {
266 Ok((tag - TAG_ZERO) as u16)
267 } else if tag == TAG_U8 {
268 if reader.remaining() < 1 {
269 return Err(EncoderError::InsufficientData);
270 }
271 Ok(reader.get_u8() as u16 + 128)
272 } else if tag == TAG_U16 {
273 if reader.remaining() < 2 {
274 return Err(EncoderError::InsufficientData);
275 }
276 Ok(reader.get_u16_le())
277 } else {
278 Err(EncoderError::Decode(format!(
279 "Unexpected tag for u16: {}",
280 tag
281 )))
282 }
283}
284#[inline]
287fn decode_u32_from_tag(tag: u8, reader: &mut Bytes) -> Result<u32> {
288 if (TAG_ZERO..=TAG_ZERO + 127).contains(&tag) {
289 Ok((tag - TAG_ZERO) as u32)
290 } else if tag == TAG_U8 {
291 if reader.remaining() < 1 {
292 return Err(EncoderError::InsufficientData);
293 }
294 Ok(reader.get_u8() as u32 + 128)
295 } else if tag == TAG_U16 {
296 if reader.remaining() < 2 {
297 return Err(EncoderError::InsufficientData);
298 }
299 Ok(reader.get_u16_le() as u32)
300 } else if tag == TAG_U32 {
301 if reader.remaining() < 4 {
302 return Err(EncoderError::InsufficientData);
303 }
304 Ok(reader.get_u32_le())
305 } else {
306 Err(EncoderError::Decode(format!(
307 "Unexpected tag for u32: {}",
308 tag
309 )))
310 }
311}
312#[inline]
315fn decode_u64_from_tag(tag: u8, reader: &mut Bytes) -> Result<u64> {
316 if (TAG_ZERO..=TAG_ZERO + 127).contains(&tag) {
317 Ok((tag - TAG_ZERO) as u64)
318 } else if tag == TAG_U8 {
319 if reader.remaining() < 1 {
320 return Err(EncoderError::InsufficientData);
321 }
322 Ok(reader.get_u8() as u64 + 128)
323 } else if tag == TAG_U16 {
324 if reader.remaining() < 2 {
325 return Err(EncoderError::InsufficientData);
326 }
327 Ok(reader.get_u16_le() as u64)
328 } else if tag == TAG_U32 {
329 if reader.remaining() < 4 {
330 return Err(EncoderError::InsufficientData);
331 }
332 Ok(reader.get_u32_le() as u64)
333 } else if tag == TAG_U64 {
334 if reader.remaining() < 8 {
335 return Err(EncoderError::InsufficientData);
336 }
337 Ok(reader.get_u64_le())
338 } else {
339 Err(EncoderError::Decode(format!(
340 "Unexpected tag for u64: {}",
341 tag
342 )))
343 }
344}
345#[inline(never)]
348fn decode_u128_from_tag(tag: u8, reader: &mut Bytes) -> Result<u128> {
349 if (TAG_ZERO..=TAG_ZERO + 127).contains(&tag) {
350 Ok((tag - TAG_ZERO) as u128)
351 } else if tag == TAG_U8 {
352 if reader.remaining() < 1 {
353 return Err(EncoderError::InsufficientData);
354 }
355 Ok(reader.get_u8() as u128 + 128)
356 } else if tag == TAG_U16 {
357 if reader.remaining() < 2 {
358 return Err(EncoderError::InsufficientData);
359 }
360 Ok(reader.get_u16_le() as u128)
361 } else if tag == TAG_U32 {
362 if reader.remaining() < 4 {
363 return Err(EncoderError::InsufficientData);
364 }
365 Ok(reader.get_u32_le() as u128)
366 } else if tag == TAG_U64 {
367 if reader.remaining() < 8 {
368 return Err(EncoderError::InsufficientData);
369 }
370 Ok(reader.get_u64_le() as u128)
371 } else if tag == TAG_U128 {
372 if reader.remaining() < 16 {
373 return Err(EncoderError::InsufficientData);
374 }
375 Ok(reader.get_u128_le())
376 } else {
377 Err(EncoderError::Decode(format!(
378 "Unexpected tag for u128: {}",
379 tag
380 )))
381 }
382}
383
384impl Encoder for u8 {
392 fn encode(&self, writer: &mut BytesMut) -> Result<()> {
393 if *self <= 127 {
394 writer.put_u8(TAG_ZERO + *self);
395 } else {
396 writer.put_u8(TAG_U8);
397 writer.put_u8(*self - 128);
398 }
399 Ok(())
400 }
401
402 fn is_default(&self) -> bool {
403 *self == 0
404 }
405}
406impl Decoder for u8 {
408 fn decode(reader: &mut Bytes) -> Result<Self> {
409 if reader.remaining() == 0 {
410 return Err(EncoderError::InsufficientData);
411 }
412 let tag = reader.get_u8();
413 decode_u8_from_tag(tag, reader)
414 }
415}
416impl Encoder for u16 {
418 fn encode(&self, writer: &mut BytesMut) -> Result<()> {
419 if *self <= 127 {
420 writer.put_u8(TAG_ZERO + (*self as u8));
421 } else if *self <= 255 + 128 {
422 writer.put_u8(TAG_U8);
423 writer.put_u8((*self - 128) as u8);
424 } else {
425 writer.put_u8(TAG_U16);
426 writer.put_u16_le(*self);
427 }
428 Ok(())
429 }
430
431 fn is_default(&self) -> bool {
432 *self == 0
433 }
434}
435impl Decoder for u16 {
436 fn decode(reader: &mut Bytes) -> Result<Self> {
437 if reader.remaining() == 0 {
438 return Err(EncoderError::InsufficientData);
439 }
440 let tag = reader.get_u8();
441 decode_u16_from_tag(tag, reader)
442 }
443}
444impl Encoder for u32 {
445 fn encode(&self, writer: &mut BytesMut) -> Result<()> {
446 if *self <= 127 {
447 writer.put_u8(TAG_ZERO + (*self as u8));
448 } else if *self <= 255 + 128 {
449 writer.put_u8(TAG_U8);
450 writer.put_u8((*self - 128) as u8);
451 } else if *self <= 65535 {
452 writer.put_u8(TAG_U16);
453 writer.put_u16_le(*self as u16);
454 } else {
455 writer.put_u8(TAG_U32);
456 writer.put_u32_le(*self);
457 }
458 Ok(())
459 }
460
461 fn is_default(&self) -> bool {
462 *self == 0
463 }
464}
465impl Decoder for u32 {
466 fn decode(reader: &mut Bytes) -> Result<Self> {
467 if reader.remaining() == 0 {
468 return Err(EncoderError::InsufficientData);
469 }
470 let tag = reader.get_u8();
471 decode_u32_from_tag(tag, reader)
472 }
473}
474impl Encoder for u64 {
475 fn encode(&self, writer: &mut BytesMut) -> Result<()> {
476 if *self <= 127 {
477 writer.put_u8(TAG_ZERO + (*self as u8));
478 } else if *self <= 255 + 128 {
479 writer.put_u8(TAG_U8);
480 writer.put_u8((*self - 128) as u8);
481 } else if *self <= 65535 {
482 writer.put_u8(TAG_U16);
483 writer.put_u16_le(*self as u16);
484 } else if *self <= 4294967295 {
485 writer.put_u8(TAG_U32);
486 writer.put_u32_le(*self as u32);
487 } else {
488 writer.put_u8(TAG_U64);
489 writer.put_u64_le(*self);
490 }
491 Ok(())
492 }
493
494 fn is_default(&self) -> bool {
495 *self == 0
496 }
497}
498impl Decoder for u64 {
499 fn decode(reader: &mut Bytes) -> Result<Self> {
500 if reader.remaining() == 0 {
501 return Err(EncoderError::InsufficientData);
502 }
503 let tag = reader.get_u8();
504 decode_u64_from_tag(tag, reader)
505 }
506}
507impl Encoder for u128 {
508 fn encode(&self, writer: &mut BytesMut) -> Result<()> {
509 if *self <= 127 {
510 writer.put_u8(TAG_ZERO + (*self as u8));
511 } else if *self <= 255 + 128 {
512 writer.put_u8(TAG_U8);
513 writer.put_u8((*self - 128) as u8);
514 } else if *self <= 65535 {
515 writer.put_u8(TAG_U16);
516 writer.put_u16_le(*self as u16);
517 } else if *self <= 4294967295 {
518 writer.put_u8(TAG_U32);
519 writer.put_u32_le(*self as u32);
520 } else if *self <= 18446744073709551615 {
521 writer.put_u8(TAG_U64);
522 writer.put_u64_le(*self as u64);
523 } else {
524 writer.put_u8(TAG_U128);
525 writer.put_u128_le(*self);
526 }
527 Ok(())
528 }
529
530 fn is_default(&self) -> bool {
531 *self == 0
532 }
533}
534impl Decoder for u128 {
535 fn decode(reader: &mut Bytes) -> Result<Self> {
536 if reader.remaining() == 0 {
537 return Err(EncoderError::InsufficientData);
538 }
539 let tag = reader.get_u8();
540 decode_u128_from_tag(tag, reader)
541 }
542}
543impl Encoder for usize {
545 #[inline]
546 fn encode(&self, writer: &mut BytesMut) -> Result<()> {
547 if usize::BITS == u64::BITS {
548 let v = *self as u64;
549 v.encode(writer)
550 } else if usize::BITS == u32::BITS {
551 let v = *self as u32;
552 v.encode(writer)
553 } else if usize::BITS == u16::BITS {
554 let v = *self as u16;
555 v.encode(writer)
556 } else {
557 let v = *self as u128;
558 v.encode(writer)
559 }
560 }
561
562 fn is_default(&self) -> bool {
563 *self == 0
564 }
565}
566impl Decoder for usize {
567 fn decode(reader: &mut Bytes) -> Result<Self> {
568 if reader.remaining() == 0 {
569 return Err(EncoderError::InsufficientData);
570 }
571 let tag = reader.get_u8();
572 if usize::BITS == u64::BITS {
573 Ok(decode_u64_from_tag(tag, reader)? as usize)
574 } else if usize::BITS == u32::BITS {
575 Ok(decode_u32_from_tag(tag, reader)? as usize)
576 } else if usize::BITS == u16::BITS {
577 Ok(decode_u16_from_tag(tag, reader)? as usize)
578 } else {
579 Ok(decode_u128_from_tag(tag, reader)? as usize)
580 }
581 }
582}
583
584impl Encoder for i8 {
590 fn encode(&self, writer: &mut BytesMut) -> Result<()> {
591 if *self >= 0 {
592 (*self as u8).encode(writer)
593 } else {
594 writer.put_u8(TAG_NEGATIVE);
595 let inv = !(*self as u8);
596 inv.encode(writer)
597 }
598 }
599
600 fn is_default(&self) -> bool {
601 *self == 0
602 }
603}
604impl Decoder for i8 {
609 fn decode(reader: &mut Bytes) -> Result<Self> {
610 if reader.remaining() == 0 {
611 return Err(EncoderError::InsufficientData);
612 }
613 let tag = reader.get_u8();
614 match tag {
615 TAG_NEGATIVE => {
616 let inv = u8::decode(reader)?;
617 Ok(!inv as i8)
618 }
619 t => {
620 let v = decode_u8_from_tag(t, reader)?;
621 if v > i8::MAX as u8 {
622 return Err(EncoderError::Decode(format!(
623 "Value {} too large for i8",
624 v
625 )));
626 }
627 Ok(v as i8)
628 }
629 }
630 }
631}
632impl Encoder for i16 {
634 fn encode(&self, writer: &mut BytesMut) -> Result<()> {
635 if *self >= 0 {
636 (*self as u16).encode(writer)
637 } else {
638 writer.put_u8(TAG_NEGATIVE);
639 let inv = !(*self as u16);
640 inv.encode(writer)
641 }
642 }
643
644 fn is_default(&self) -> bool {
645 *self == 0
646 }
647}
648impl Decoder for i16 {
649 fn decode(reader: &mut Bytes) -> Result<Self> {
650 if reader.remaining() == 0 {
651 return Err(EncoderError::InsufficientData);
652 }
653 let tag = reader.get_u8();
654 match tag {
655 TAG_NEGATIVE => {
656 let inv = u16::decode(reader)?;
657 Ok(!inv as i16)
658 }
659 t => {
660 let v = decode_u16_from_tag(t, reader)?;
661 if v > i16::MAX as u16 {
662 return Err(EncoderError::Decode(format!(
663 "Value {} too large for i16",
664 v
665 )));
666 }
667 Ok(v as i16)
668 }
669 }
670 }
671}
672impl Encoder for i32 {
674 fn encode(&self, writer: &mut BytesMut) -> Result<()> {
675 if *self >= 0 {
676 (*self as u32).encode(writer)
677 } else {
678 writer.put_u8(TAG_NEGATIVE);
679 let inv = !(*self as u32);
680 inv.encode(writer)
681 }
682 }
683
684 fn is_default(&self) -> bool {
685 *self == 0
686 }
687}
688impl Decoder for i32 {
689 fn decode(reader: &mut Bytes) -> Result<Self> {
690 if reader.remaining() == 0 {
691 return Err(EncoderError::InsufficientData);
692 }
693 let tag = reader.get_u8();
694 match tag {
695 TAG_NEGATIVE => {
696 let inv = u32::decode(reader)?;
697 Ok(!inv as i32)
698 }
699 t => {
700 let v = decode_u32_from_tag(t, reader)?;
701 if v > i32::MAX as u32 {
702 return Err(EncoderError::Decode(format!(
703 "Value {} too large for i32",
704 v
705 )));
706 }
707 Ok(v as i32)
708 }
709 }
710 }
711}
712impl Encoder for i64 {
714 fn encode(&self, writer: &mut BytesMut) -> Result<()> {
715 if *self >= 0 {
716 (*self as u64).encode(writer)
717 } else {
718 writer.put_u8(TAG_NEGATIVE);
719 let inv = !(*self as u64);
720 inv.encode(writer)
721 }
722 }
723
724 fn is_default(&self) -> bool {
725 *self == 0
726 }
727}
728impl Decoder for i64 {
729 fn decode(reader: &mut Bytes) -> Result<Self> {
730 if reader.remaining() == 0 {
731 return Err(EncoderError::InsufficientData);
732 }
733 let tag = reader.get_u8();
734 match tag {
735 TAG_NEGATIVE => {
736 let inv = u64::decode(reader)?;
737 Ok(!inv as i64)
738 }
739 t => {
740 let v = decode_u64_from_tag(t, reader)?;
741 if v > i64::MAX as u64 {
742 return Err(EncoderError::Decode(format!(
743 "Value {} too large for i64",
744 v
745 )));
746 }
747 Ok(v as i64)
748 }
749 }
750 }
751}
752impl Encoder for i128 {
754 fn encode(&self, writer: &mut BytesMut) -> Result<()> {
755 if *self >= 0 {
756 (*self as u128).encode(writer)
757 } else {
758 writer.put_u8(TAG_NEGATIVE);
759 let inv = !(*self as u128);
760 inv.encode(writer)
761 }
762 }
763
764 fn is_default(&self) -> bool {
765 *self == 0
766 }
767}
768impl Decoder for i128 {
769 fn decode(reader: &mut Bytes) -> Result<Self> {
770 if reader.remaining() == 0 {
771 return Err(EncoderError::InsufficientData);
772 }
773 let tag = reader.get_u8();
774 match tag {
775 TAG_NEGATIVE => {
776 let inv = u128::decode(reader)?;
777 Ok(!inv as i128)
778 }
779 t => {
780 let v = decode_u128_from_tag(t, reader)?;
781 if v > i128::MAX as u128 {
782 return Err(EncoderError::Decode(format!(
783 "Value {} too large for i128",
784 v
785 )));
786 }
787 Ok(v as i128)
788 }
789 }
790 }
791}
792impl Encoder for isize {
794 fn encode(&self, writer: &mut BytesMut) -> Result<()> {
795 if usize::BITS == u64::BITS {
796 let v = *self as i64;
797 v.encode(writer)
798 } else if usize::BITS == u32::BITS {
799 let v = *self as i32;
800 v.encode(writer)
801 } else if usize::BITS == u16::BITS {
802 let v = *self as i16;
803 v.encode(writer)
804 } else {
805 let v = *self as i128;
806 v.encode(writer)
807 }
808 }
809
810 fn is_default(&self) -> bool {
811 *self == 0
812 }
813}
814impl Decoder for isize {
815 fn decode(reader: &mut Bytes) -> Result<Self> {
816 if reader.remaining() == 0 {
817 return Err(EncoderError::InsufficientData);
818 }
819 if usize::BITS == u64::BITS {
820 Ok(i64::decode(reader)? as isize)
821 } else if usize::BITS == u32::BITS {
822 Ok(i32::decode(reader)? as isize)
823 } else if usize::BITS == u16::BITS {
824 Ok(i16::decode(reader)? as isize)
825 } else {
826 Ok(i128::decode(reader)? as isize)
827 }
828 }
829}
830
831impl Encoder for f32 {
834 fn encode(&self, writer: &mut BytesMut) -> Result<()> {
835 writer.put_u8(TAG_F32);
836 writer.put_f32_le(*self);
837 Ok(())
838 }
839
840 fn is_default(&self) -> bool {
841 *self == 0.0
842 }
843}
844impl Decoder for f32 {
846 fn decode(reader: &mut Bytes) -> Result<Self> {
847 if reader.remaining() == 0 {
848 return Err(EncoderError::InsufficientData);
849 }
850 let tag = reader.get_u8();
851 if tag == TAG_F32 {
852 if reader.remaining() < 4 {
853 return Err(EncoderError::InsufficientData);
854 }
855 let mut bytes = [0u8; 4];
856 reader.copy_to_slice(&mut bytes);
857 Ok(f32::from_le_bytes(bytes))
858 } else if tag == TAG_F64 {
859 if reader.remaining() < 8 {
860 return Err(EncoderError::InsufficientData);
861 }
862 let mut bytes = [0u8; 8];
863 reader.copy_to_slice(&mut bytes);
864 Ok(f64::from_le_bytes(bytes) as f32)
865 } else {
866 Err(EncoderError::Decode(format!(
867 "Expected f32/f64 tag ({} or {}), got {}",
868 TAG_F32, TAG_F64, tag
869 )))
870 }
871 }
872}
873impl Encoder for f64 {
875 fn encode(&self, writer: &mut BytesMut) -> Result<()> {
876 writer.put_u8(TAG_F64);
877 writer.put_f64_le(*self);
878 Ok(())
879 }
880
881 fn is_default(&self) -> bool {
882 *self == 0.0
883 }
884}
885impl Decoder for f64 {
887 fn decode(reader: &mut Bytes) -> Result<Self> {
888 if reader.remaining() == 0 {
889 return Err(EncoderError::InsufficientData);
890 }
891 let tag = reader.get_u8();
892 if tag == TAG_F64 {
893 if reader.remaining() < 8 {
894 return Err(EncoderError::InsufficientData);
895 }
896 let mut bytes = [0u8; 8];
897 reader.copy_to_slice(&mut bytes);
898 Ok(f64::from_le_bytes(bytes))
899 } else {
900 Err(EncoderError::Decode(format!(
901 "Expected f64 tag ({}), got {}. f32 to f64 cross-decoding is not supported due to precision concerns.",
902 TAG_F64, tag
903 )))
904 }
905 }
906}
907
908impl Encoder for String {
911 fn encode(&self, writer: &mut BytesMut) -> Result<()> {
912 let len = self.len();
913 let max_short = (TAG_STRING_LONG - TAG_STRING_BASE - 1) as usize;
914 if len <= max_short {
915 let tag = TAG_STRING_BASE + len as u8; writer.put_u8(tag);
917 writer.put_slice(self.as_bytes());
918 } else {
919 writer.put_u8(TAG_STRING_LONG);
920 len.encode(writer)?;
921 writer.put_slice(self.as_bytes());
922 }
923 Ok(())
924 }
925
926 fn is_default(&self) -> bool {
927 self.is_empty()
928 }
929}
930impl Decoder for String {
932 fn decode(reader: &mut Bytes) -> Result<Self> {
933 if reader.remaining() == 0 {
934 return Err(EncoderError::InsufficientData);
935 }
936 let tag = reader.get_u8();
937 let len = if (TAG_STRING_BASE..TAG_STRING_LONG).contains(&tag) {
938 (tag - TAG_STRING_BASE) as usize
939 } else if tag == TAG_STRING_LONG {
940 usize::decode(reader)?
941 } else {
942 return Err(EncoderError::Decode(format!(
943 "Expected String tag ({}..={}), got {}",
944 TAG_STRING_BASE, TAG_STRING_LONG, tag
945 )));
946 };
947 if reader.remaining() < len {
948 return Err(EncoderError::InsufficientData);
949 }
950 let mut bytes = vec![0u8; len];
951 if len > 0 {
952 reader.copy_to_slice(&mut bytes);
953 }
954 String::from_utf8(bytes).map_err(|e| EncoderError::Decode(e.to_string()))
955 }
956}
957
958impl<T: Encoder> Encoder for Option<T> {
961 fn encode(&self, writer: &mut BytesMut) -> Result<()> {
962 match self {
963 Some(value) => {
964 writer.put_u8(TAG_SOME);
965 value.encode(writer)
966 }
967 None => {
968 writer.put_u8(TAG_NONE);
969 Ok(())
970 }
971 }
972 }
973
974 fn is_default(&self) -> bool {
975 self.is_none()
976 }
977}
978impl<T: Decoder> Decoder for Option<T> {
980 fn decode(reader: &mut Bytes) -> Result<Self> {
981 if reader.remaining() == 0 {
982 return Err(EncoderError::InsufficientData); }
984 let tag = reader.get_u8();
985 match tag {
986 TAG_NONE => Ok(None),
987 TAG_SOME => {
988 if reader.remaining() == 0 {
989 return Err(EncoderError::InsufficientData);
991 }
992 Ok(Some(T::decode(reader)?))
993 }
994 other => Err(EncoderError::Decode(format!(
995 "Expected Option tag ({} or {}), got {}",
996 TAG_NONE, TAG_SOME, other
997 ))),
998 }
999 }
1000}
1001
1002impl<T: Encoder + 'static> Encoder for Vec<T> {
1005 fn encode(&self, writer: &mut BytesMut) -> Result<()> {
1006 if std::any::TypeId::of::<T>() == std::any::TypeId::of::<u8>() {
1007 writer.put_u8(TAG_BINARY);
1008 let len = self.len();
1009 len.encode(writer)?;
1010 let bytes =
1011 unsafe { std::slice::from_raw_parts(self.as_ptr() as *const u8, self.len()) };
1012 writer.put_slice(bytes);
1013 Ok(())
1014 } else {
1015 let len = self.len();
1016 let max_short = (TAG_ARRAY_VEC_SET_LONG - TAG_ARRAY_VEC_SET_BASE - 1) as usize;
1017 if len <= max_short {
1018 let tag = TAG_ARRAY_VEC_SET_BASE + len as u8;
1019 writer.put_u8(tag);
1020 for item in self {
1021 item.encode(writer)?;
1022 }
1023 } else {
1024 writer.put_u8(TAG_ARRAY_VEC_SET_LONG);
1025 len.encode(writer)?;
1026 for item in self {
1027 item.encode(writer)?;
1028 }
1029 }
1030 Ok(())
1031 }
1032 }
1033
1034 fn is_default(&self) -> bool {
1035 self.is_empty()
1036 }
1037}
1038impl<T: Decoder + 'static> Decoder for Vec<T> {
1040 fn decode(reader: &mut Bytes) -> Result<Self> {
1041 if reader.remaining() == 0 {
1042 return Err(EncoderError::InsufficientData);
1043 }
1044 let tag = reader.get_u8();
1045 if tag == TAG_BINARY && std::any::TypeId::of::<T>() == std::any::TypeId::of::<u8>() {
1046 let len = usize::decode(reader)?;
1047 let mut vec = vec![0u8; len];
1048 reader.copy_to_slice(&mut vec);
1049 let ptr = vec.as_mut_ptr() as *mut T;
1050 let len = vec.len();
1051 let cap = vec.capacity();
1052 std::mem::forget(vec);
1053 unsafe { Ok(Vec::from_raw_parts(ptr, len, cap)) }
1054 } else if (TAG_ARRAY_VEC_SET_BASE..TAG_ARRAY_VEC_SET_LONG).contains(&tag) {
1055 let len = (tag - TAG_ARRAY_VEC_SET_BASE) as usize;
1056 let mut vec = Vec::with_capacity(len);
1057 for _ in 0..len {
1058 vec.push(T::decode(reader)?);
1059 }
1060 Ok(vec)
1061 } else if tag == TAG_ARRAY_VEC_SET_LONG {
1062 let len = usize::decode(reader)?;
1063 let mut vec = Vec::with_capacity(len);
1064 for _ in 0..len {
1065 vec.push(T::decode(reader)?);
1066 }
1067 Ok(vec)
1068 } else {
1069 Err(EncoderError::Decode(format!(
1070 "Expected Vec tag ({}..={} or {}), got {}",
1071 TAG_ARRAY_VEC_SET_BASE, TAG_ARRAY_VEC_SET_LONG, TAG_BINARY, tag
1072 )))
1073 }
1074 }
1075}
1076
1077impl<T: Encoder, const N: usize> Encoder for [T; N] {
1080 fn encode(&self, writer: &mut BytesMut) -> Result<()> {
1081 let max_short = (TAG_ARRAY_VEC_SET_LONG - TAG_ARRAY_VEC_SET_BASE - 1) as usize;
1082 if N <= max_short {
1083 let tag = TAG_ARRAY_VEC_SET_BASE + N as u8;
1084 writer.put_u8(tag);
1085 for item in self {
1086 item.encode(writer)?;
1087 }
1088 } else {
1089 writer.put_u8(TAG_ARRAY_VEC_SET_LONG);
1090 N.encode(writer)?;
1091 for item in self {
1092 item.encode(writer)?;
1093 }
1094 }
1095 Ok(())
1096 }
1097
1098 fn is_default(&self) -> bool {
1099 self.iter().all(|item| item.is_default())
1100 }
1101}
1102impl<T: Decoder, const N: usize> Decoder for [T; N] {
1104 fn decode(reader: &mut Bytes) -> Result<Self> {
1105 if reader.remaining() == 0 {
1106 return Err(EncoderError::InsufficientData);
1107 }
1108 let tag = reader.get_u8();
1109 let len = if (TAG_ARRAY_VEC_SET_BASE..TAG_ARRAY_VEC_SET_LONG).contains(&tag) {
1110 (tag - TAG_ARRAY_VEC_SET_BASE) as usize
1111 } else if tag == TAG_ARRAY_VEC_SET_LONG {
1112 usize::decode(reader)?
1113 } else {
1114 return Err(EncoderError::Decode(format!(
1115 "Expected Array tag ({}..={}), got {}",
1116 TAG_ARRAY_VEC_SET_BASE, TAG_ARRAY_VEC_SET_LONG, tag
1117 )));
1118 };
1119 if len != N {
1120 return Err(EncoderError::Decode(format!(
1121 "Array length mismatch: expected {}, got {}",
1122 N, len
1123 )));
1124 }
1125 let mut array = Vec::with_capacity(N);
1126 for _ in 0..N {
1127 array.push(T::decode(reader)?);
1128 }
1129 array
1130 .try_into()
1131 .map_err(|_| EncoderError::Decode("Failed to convert Vec to array".to_string()))
1132 }
1133}
1134
1135macro_rules! impl_tuple {
1140 () => {
1141impl Encoder for () {
1142 fn encode(&self, writer: &mut BytesMut) -> Result<()> {
1143 writer.put_u8(TAG_TUPLE);
1144 0usize.encode(writer)?;
1145 Ok(())
1146 }
1147
1148 fn is_default(&self) -> bool {
1149 true
1150 }
1151}
1152impl Decoder for () {
1153 fn decode(reader: &mut Bytes) -> Result<Self> {
1154 if reader.remaining() == 0 {
1155 return Err(EncoderError::InsufficientData);
1156 }
1157 let tag = reader.get_u8();
1158 if tag != TAG_TUPLE {
1159 return Err(EncoderError::Decode(format!("Expected Tuple tag ({}), got {}", TAG_TUPLE, tag)));
1160 }
1161 let len = usize::decode(reader)?;
1162 if len != 0 {
1163 return Err(EncoderError::Decode(format!("Expected 0-tuple but got {}-tuple", len)));
1164 }
1165 Ok(())
1166 }
1167}
1168 };
1169 ($($T:ident : $idx:tt),+) => {
1170 impl<$($T: Encoder),+> Encoder for ($($T,)+) {
1171 fn encode(&self, writer: &mut BytesMut) -> Result<()> {
1172 writer.put_u8(TAG_TUPLE);
1173 let count = count_args!($($T),+);
1174 count.encode(writer)?;
1175 $(
1176 self.$idx.encode(writer)?;
1177 )+
1178 Ok(())
1179 }
1180
1181 fn is_default(&self) -> bool {
1182 $(self.$idx.is_default())&&+
1183 }
1184}
1185 impl<$($T: Decoder),+> Decoder for ($($T,)+) {
1186 fn decode(reader: &mut Bytes) -> Result<Self> {
1187 if reader.remaining() == 0 {
1188 return Err(EncoderError::InsufficientData);
1189 }
1190 let tag = reader.get_u8();
1191 if tag != TAG_TUPLE {
1192 return Err(EncoderError::Decode(format!("Expected Tuple tag ({}), got {}", TAG_TUPLE, tag)));
1193 }
1194 let len = usize::decode(reader)?;
1195 let expected_len = count_args!($($T),+);
1196 if len != expected_len {
1197 return Err(EncoderError::Decode(format!("Expected {}-tuple but got {}-tuple", expected_len, len)));
1198 }
1199 Ok(($(
1200 $T::decode(reader)?,
1201 )+))
1202 }
1203 }
1204 };
1205}
1206
1207macro_rules! count_args {
1208 () => { 0 };
1209 ($head:ident $(, $tail:ident)*) => { 1 + count_args!($($tail),*) };
1210}
1211
1212impl_tuple!();
1214impl_tuple!(T0: 0);
1215impl_tuple!(T0: 0, T1: 1);
1216impl_tuple!(T0: 0, T1: 1, T2: 2);
1217impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3);
1218impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4);
1219impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5);
1220impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6);
1221impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7);
1222impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7, T8: 8);
1223impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7, T8: 8, T9: 9);
1224impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7, T8: 8, T9: 9, T10: 10);
1225impl_tuple!(T0: 0, T1: 1, T2: 2, T3: 3, T4: 4, T5: 5, T6: 6, T7: 7, T8: 8, T9: 9, T10: 10, T11: 11);
1226
1227impl<K: Encoder, V: Encoder> Encoder for HashMap<K, V> {
1230 fn encode(&self, writer: &mut BytesMut) -> Result<()> {
1231 writer.put_u8(TAG_MAP);
1232 let len = self.len();
1233 len.encode(writer)?;
1234 for (k, v) in self {
1235 k.encode(writer)?;
1236 v.encode(writer)?;
1237 }
1238 Ok(())
1239 }
1240
1241 fn is_default(&self) -> bool {
1242 self.is_empty()
1243 }
1244}
1245impl<K: Decoder + Eq + std::hash::Hash, V: Decoder> Decoder for HashMap<K, V> {
1247 fn decode(reader: &mut Bytes) -> Result<Self> {
1248 if reader.remaining() == 0 {
1249 return Err(EncoderError::InsufficientData);
1250 }
1251 let tag = reader.get_u8();
1252 if tag != TAG_MAP {
1253 return Err(EncoderError::Decode(format!(
1254 "Expected Map tag ({}), got {}",
1255 TAG_MAP, tag
1256 )));
1257 }
1258 let len = usize::decode(reader)?;
1259 let mut map = HashMap::with_capacity(len);
1260 for _ in 0..len {
1261 let k = K::decode(reader)?;
1262 let v = V::decode(reader)?;
1263 map.insert(k, v);
1264 }
1265 Ok(map)
1266 }
1267}
1268pub fn write_u32_le(writer: &mut BytesMut, value: u32) -> Result<()> {
1276 writer.put_u32_le(value);
1277 Ok(())
1278}
1279
1280pub fn read_u32_le(reader: &mut Bytes) -> Result<u32> {
1284 if reader.remaining() < 4 {
1285 return Err(EncoderError::InsufficientData);
1286 }
1287 Ok(reader.get_u32_le())
1288}
1289
1290pub fn write_u64_le(writer: &mut BytesMut, value: u64) -> Result<()> {
1294 writer.put_u64_le(value);
1295 Ok(())
1296}
1297
1298pub fn read_u64_le(reader: &mut Bytes) -> Result<u64> {
1302 if reader.remaining() < 8 {
1303 return Err(EncoderError::InsufficientData);
1304 }
1305 Ok(reader.get_u64_le())
1306}
1307
1308pub fn skip_value(reader: &mut Bytes) -> Result<()> {
1315 if reader.remaining() == 0 {
1316 return Err(EncoderError::InsufficientData);
1317 }
1318 let tag = reader.get_u8();
1319 match tag {
1320 TAG_ZERO | TAG_ONE => Ok(()),
1321 TAG_U8_2_BASE..=TAG_U8_127 => Ok(()),
1322 TAG_U8 => {
1323 if reader.remaining() < 1 {
1324 return Err(EncoderError::InsufficientData);
1325 }
1326 reader.advance(1);
1327 Ok(())
1328 }
1329 TAG_U16 => {
1330 if reader.remaining() < 2 {
1331 return Err(EncoderError::InsufficientData);
1332 }
1333 reader.advance(2);
1334 Ok(())
1335 }
1336 TAG_U32 => {
1337 if reader.remaining() < 4 {
1338 return Err(EncoderError::InsufficientData);
1339 }
1340 reader.advance(4);
1341 Ok(())
1342 }
1343 TAG_U64 => {
1344 if reader.remaining() < 8 {
1345 return Err(EncoderError::InsufficientData);
1346 }
1347 reader.advance(8);
1348 Ok(())
1349 }
1350 TAG_U128 => {
1351 if reader.remaining() < 16 {
1352 return Err(EncoderError::InsufficientData);
1353 }
1354 reader.advance(16);
1355 Ok(())
1356 }
1357 TAG_F32 => {
1358 if reader.remaining() < 4 {
1359 return Err(EncoderError::InsufficientData);
1360 }
1361 reader.advance(4);
1362 Ok(())
1363 }
1364 TAG_F64 => {
1365 if reader.remaining() < 8 {
1366 return Err(EncoderError::InsufficientData);
1367 }
1368 reader.advance(8);
1369 Ok(())
1370 }
1371 TAG_STRING_BASE..=TAG_STRING_LONG => {
1372 let len = if tag < TAG_STRING_LONG {
1373 (tag - TAG_STRING_BASE) as usize
1374 } else {
1375 usize::decode(reader)?
1376 };
1377 if reader.remaining() < len {
1378 return Err(EncoderError::InsufficientData);
1379 }
1380 reader.advance(len);
1381 Ok(())
1382 }
1383 TAG_BINARY => {
1384 let len = usize::decode(reader)?;
1385 if reader.remaining() < len {
1386 return Err(EncoderError::InsufficientData);
1387 }
1388 reader.advance(len);
1389 Ok(())
1390 }
1391 TAG_ARRAY_VEC_SET_BASE..=TAG_ARRAY_VEC_SET_LONG => {
1392 let len = if tag < TAG_ARRAY_VEC_SET_LONG {
1393 (tag - TAG_ARRAY_VEC_SET_BASE) as usize
1394 } else {
1395 usize::decode(reader)?
1396 };
1397 for _ in 0..len {
1398 skip_value(reader)?;
1399 }
1400 Ok(())
1401 }
1402 TAG_STRUCT_UNIT => Ok(()),
1403 TAG_STRUCT_NAMED => {
1404 loop {
1405 let field_id = read_field_id_optimized(reader)?;
1406 if field_id == 0 {
1407 break;
1408 }
1409 skip_value(reader)?;
1410 }
1411 Ok(())
1412 }
1413 TAG_STRUCT_UNNAMED => {
1414 let field_count = usize::decode(reader)?;
1415 for _ in 0..field_count {
1416 skip_value(reader)?;
1417 }
1418 Ok(())
1419 }
1420 TAG_ENUM => {
1421 let _variant_id = read_field_id_optimized(reader)?;
1422 Ok(())
1423 }
1424 TAG_ENUM_NAMED => {
1425 let _variant_id = read_field_id_optimized(reader)?;
1426 loop {
1427 let field_id = read_field_id_optimized(reader)?;
1428 if field_id == 0 {
1429 break;
1430 }
1431 skip_value(reader)?;
1432 }
1433 Ok(())
1434 }
1435 TAG_ENUM_UNNAMED => {
1436 let _variant_id = read_field_id_optimized(reader)?;
1437 let field_count = usize::decode(reader)?;
1438 for _ in 0..field_count {
1439 skip_value(reader)?;
1440 }
1441 Ok(())
1442 }
1443 TAG_TUPLE => {
1444 let len = usize::decode(reader)?;
1445 for _ in 0..len {
1446 skip_value(reader)?;
1447 }
1448 Ok(())
1449 }
1450 TAG_MAP => {
1451 let len = usize::decode(reader)?;
1452 for _ in 0..len {
1453 skip_value(reader)?; skip_value(reader)?; }
1456 Ok(())
1457 }
1458 TAG_CHRONO_DATETIME => {
1459 if reader.remaining() < 12 {
1460 return Err(EncoderError::InsufficientData);
1461 } let _timestamp_seconds = i64::decode(reader)?;
1463 let _timestamp_nanos = u32::decode(reader)?;
1464 Ok(())
1465 }
1466 TAG_CHRONO_NAIVE_DATE => {
1467 if reader.remaining() < 8 {
1468 return Err(EncoderError::InsufficientData);
1469 } let _days_from_epoch = i64::decode(reader)?;
1471 Ok(())
1472 }
1473 TAG_CHRONO_NAIVE_TIME => {
1474 if reader.remaining() < 8 {
1475 return Err(EncoderError::InsufficientData);
1476 } let _seconds_from_midnight = u32::decode(reader)?;
1478 let _nanoseconds = u32::decode(reader)?;
1479 Ok(())
1480 }
1481 TAG_DECIMAL => {
1482 if reader.remaining() < 20 {
1483 return Err(EncoderError::InsufficientData);
1484 } let _mantissa = i128::decode(reader)?;
1486 let _scale = u32::decode(reader)?;
1487 Ok(())
1488 }
1489 TAG_UUID => {
1490 if reader.remaining() < 16 {
1492 return Err(EncoderError::InsufficientData);
1493 }
1494 reader.advance(16);
1495 Ok(())
1496 }
1497 TAG_JSON_NULL => Ok(()),
1498 TAG_JSON_BOOL => Ok(()),
1499 TAG_JSON_NUMBER => {
1500 if reader.remaining() == 0 {
1502 return Err(EncoderError::InsufficientData);
1503 }
1504 let number_type = reader.get_u8();
1505 match number_type {
1506 0 => {
1507 u64::decode(reader)?;
1508 }
1509 1 => {
1510 i64::decode(reader)?;
1511 }
1512 2 => {
1513 f64::decode(reader)?;
1514 }
1515 _ => {
1516 return Err(EncoderError::Decode(format!(
1517 "Invalid JSON Number type marker: {}",
1518 number_type
1519 )));
1520 }
1521 }
1522 Ok(())
1523 }
1524 TAG_JSON_STRING => {
1525 String::decode(reader)?;
1527 Ok(())
1528 }
1529 TAG_JSON_ARRAY => {
1530 let len = usize::decode(reader)?;
1531 for _ in 0..len {
1532 skip_value(reader)?;
1533 }
1534 Ok(())
1535 }
1536 TAG_JSON_OBJECT => {
1537 let len = usize::decode(reader)?;
1538 for _ in 0..len {
1539 String::decode(reader)?; skip_value(reader)?; }
1542 Ok(())
1543 }
1544 TAG_NONE | TAG_SOME => {
1545 if tag == TAG_SOME {
1548 skip_value(reader)?;
1549 }
1550 Ok(())
1551 }
1552 _ => Err(EncoderError::Decode(format!(
1553 "skip_value: unknown or unhandled tag {}",
1554 tag
1555 ))),
1556 }
1557}
1558
1559impl<T: Encoder + Eq + std::hash::Hash> Encoder for HashSet<T> {
1562 fn encode(&self, writer: &mut BytesMut) -> Result<()> {
1563 let len = self.len();
1564 let max_short = (TAG_ARRAY_VEC_SET_LONG - TAG_ARRAY_VEC_SET_BASE - 1) as usize;
1565 if len <= max_short {
1566 let tag = TAG_ARRAY_VEC_SET_BASE + len as u8;
1567 writer.put_u8(tag);
1568 for v in self {
1569 v.encode(writer)?;
1570 }
1571 } else {
1572 writer.put_u8(TAG_ARRAY_VEC_SET_LONG);
1573 len.encode(writer)?;
1574 for v in self {
1575 v.encode(writer)?;
1576 }
1577 }
1578 Ok(())
1579 }
1580
1581 fn is_default(&self) -> bool {
1582 self.is_empty()
1583 }
1584}
1585impl<T: Decoder + Eq + std::hash::Hash + 'static> Decoder for HashSet<T> {
1587 fn decode(reader: &mut Bytes) -> Result<Self> {
1588 let vec: Vec<T> = Vec::decode(reader)?;
1589 Ok(vec.into_iter().collect())
1590 }
1591}
1592impl<T: Encoder + Ord> Encoder for BTreeSet<T> {
1594 fn encode(&self, writer: &mut BytesMut) -> Result<()> {
1595 let len = self.len();
1596 let max_short = (TAG_ARRAY_VEC_SET_LONG - TAG_ARRAY_VEC_SET_BASE - 1) as usize;
1597 if len <= max_short {
1598 let tag = TAG_ARRAY_VEC_SET_BASE + len as u8;
1599 writer.put_u8(tag);
1600 for v in self {
1601 v.encode(writer)?;
1602 }
1603 } else {
1604 writer.put_u8(TAG_ARRAY_VEC_SET_LONG);
1605 len.encode(writer)?;
1606 for v in self {
1607 v.encode(writer)?;
1608 }
1609 }
1610 Ok(())
1611 }
1612
1613 fn is_default(&self) -> bool {
1614 self.is_empty()
1615 }
1616}
1617impl<T: Decoder + Ord + 'static> Decoder for BTreeSet<T> {
1618 fn decode(reader: &mut Bytes) -> Result<Self> {
1619 let vec: Vec<T> = Vec::decode(reader)?;
1620 Ok(vec.into_iter().collect())
1621 }
1622}
1623#[cfg(feature = "indexmap")]
1625impl<T: Encoder + Eq + std::hash::Hash> Encoder for IndexSet<T> {
1626 fn encode(&self, writer: &mut BytesMut) -> Result<()> {
1627 let len = self.len();
1628 let max_short = (TAG_ARRAY_VEC_SET_LONG - TAG_ARRAY_VEC_SET_BASE - 1) as usize;
1629 if len <= max_short {
1630 let tag = TAG_ARRAY_VEC_SET_BASE + len as u8;
1631 writer.put_u8(tag);
1632 for v in self {
1633 v.encode(writer)?;
1634 }
1635 } else {
1636 writer.put_u8(TAG_ARRAY_VEC_SET_LONG);
1637 len.encode(writer)?;
1638 for v in self {
1639 v.encode(writer)?;
1640 }
1641 }
1642 Ok(())
1643 }
1644
1645 fn is_default(&self) -> bool {
1646 self.is_empty()
1647 }
1648}
1649#[cfg(feature = "indexmap")]
1650impl<T: Decoder + Eq + std::hash::Hash + 'static> Decoder for IndexSet<T> {
1651 fn decode(reader: &mut Bytes) -> Result<Self> {
1652 let vec: Vec<T> = Vec::decode(reader)?;
1653 Ok(vec.into_iter().collect())
1654 }
1655}
1656impl<K: Encoder + Ord, V: Encoder> Encoder for BTreeMap<K, V> {
1658 fn encode(&self, writer: &mut BytesMut) -> Result<()> {
1659 writer.put_u8(TAG_MAP);
1660 let len = self.len();
1661 len.encode(writer)?;
1662 for (k, v) in self {
1663 k.encode(writer)?;
1664 v.encode(writer)?;
1665 }
1666 Ok(())
1667 }
1668
1669 fn is_default(&self) -> bool {
1670 self.is_empty()
1671 }
1672}
1673impl<K: Decoder + Ord, V: Decoder> Decoder for BTreeMap<K, V> {
1674 fn decode(reader: &mut Bytes) -> Result<Self> {
1675 if reader.remaining() == 0 {
1676 return Err(EncoderError::InsufficientData);
1677 }
1678 let tag = reader.get_u8();
1679 if tag != TAG_MAP {
1680 return Err(EncoderError::Decode(format!(
1681 "Expected Map tag ({}), got {}",
1682 TAG_MAP, tag
1683 )));
1684 }
1685 let len = usize::decode(reader)?;
1686 let mut map = BTreeMap::new();
1687 for _ in 0..len {
1688 let k = K::decode(reader)?;
1689 let v = V::decode(reader)?;
1690 map.insert(k, v);
1691 }
1692 Ok(map)
1693 }
1694}
1695#[cfg(feature = "indexmap")]
1697impl<K: Encoder + Eq + std::hash::Hash, V: Encoder> Encoder for IndexMap<K, V> {
1698 fn encode(&self, writer: &mut BytesMut) -> Result<()> {
1699 writer.put_u8(TAG_MAP);
1700 let len = self.len();
1701 len.encode(writer)?;
1702 for (k, v) in self {
1703 k.encode(writer)?;
1704 v.encode(writer)?;
1705 }
1706 Ok(())
1707 }
1708
1709 fn is_default(&self) -> bool {
1710 self.is_empty()
1711 }
1712}
1713#[cfg(feature = "indexmap")]
1714impl<K: Decoder + Eq + std::hash::Hash, V: Decoder> Decoder for IndexMap<K, V> {
1715 fn decode(reader: &mut Bytes) -> Result<Self> {
1716 if reader.remaining() == 0 {
1717 return Err(EncoderError::InsufficientData);
1718 }
1719 let tag = reader.get_u8();
1720 if tag != TAG_MAP {
1721 return Err(EncoderError::Decode(format!(
1722 "Expected Map tag ({}), got {}",
1723 TAG_MAP, tag
1724 )));
1725 }
1726 let len = usize::decode(reader)?;
1727 let mut map = IndexMap::with_capacity(len);
1728 for _ in 0..len {
1729 let k = K::decode(reader)?;
1730 let v = V::decode(reader)?;
1731 map.insert(k, v);
1732 }
1733 Ok(map)
1734 }
1735}
1736
1737#[cfg(feature = "chrono")]
1740impl Encoder for DateTime<Utc> {
1741 fn encode(&self, writer: &mut BytesMut) -> Result<()> {
1742 writer.put_u8(TAG_CHRONO_DATETIME);
1743 let timestamp_seconds = self.timestamp();
1744 let timestamp_nanos = self.timestamp_subsec_nanos();
1745 timestamp_seconds.encode(writer)?;
1746 timestamp_nanos.encode(writer)?;
1747 Ok(())
1748 }
1749
1750 fn is_default(&self) -> bool {
1751 *self == DateTime::<Utc>::default()
1752 }
1753}
1754#[cfg(feature = "chrono")]
1756impl Decoder for DateTime<Utc> {
1757 fn decode(reader: &mut Bytes) -> Result<Self> {
1758 if reader.remaining() == 0 {
1759 return Err(EncoderError::InsufficientData);
1760 }
1761 let tag = reader.get_u8();
1762 if tag != TAG_CHRONO_DATETIME {
1763 return Err(EncoderError::Decode(format!(
1764 "Expected DateTime<Utc> tag ({}), got {}",
1765 TAG_CHRONO_DATETIME, tag
1766 )));
1767 }
1768 let timestamp_seconds = i64::decode(reader)?;
1769 let timestamp_nanos = u32::decode(reader)?;
1770 DateTime::from_timestamp(timestamp_seconds, timestamp_nanos).ok_or_else(|| {
1771 EncoderError::Decode(format!(
1772 "Invalid timestamp: {} seconds, {} nanos",
1773 timestamp_seconds, timestamp_nanos
1774 ))
1775 })
1776 }
1777}
1778
1779#[cfg(feature = "chrono")]
1781impl Encoder for DateTime<Local> {
1782 fn encode(&self, writer: &mut BytesMut) -> Result<()> {
1783 writer.put_u8(TAG_CHRONO_DATETIME);
1784 let utc_dt = self.with_timezone(&Utc);
1785 let timestamp_seconds = utc_dt.timestamp();
1786 let timestamp_nanos = utc_dt.timestamp_subsec_nanos();
1787 timestamp_seconds.encode(writer)?;
1788 timestamp_nanos.encode(writer)?;
1789 Ok(())
1790 }
1791
1792 fn is_default(&self) -> bool {
1793 *self == DateTime::<Local>::default()
1794 }
1795}
1796#[cfg(feature = "chrono")]
1797impl Decoder for DateTime<Local> {
1798 fn decode(reader: &mut Bytes) -> Result<Self> {
1799 if reader.remaining() == 0 {
1800 return Err(EncoderError::InsufficientData);
1801 }
1802 let tag = reader.get_u8();
1803 if tag != TAG_CHRONO_DATETIME {
1804 return Err(EncoderError::Decode(format!(
1805 "Expected DateTime<Local> tag ({}), got {}",
1806 TAG_CHRONO_DATETIME, tag
1807 )));
1808 }
1809 let timestamp_seconds = i64::decode(reader)?;
1810 let timestamp_nanos = u32::decode(reader)?;
1811 let utc_dt =
1812 DateTime::from_timestamp(timestamp_seconds, timestamp_nanos).ok_or_else(|| {
1813 EncoderError::Decode(format!(
1814 "Invalid timestamp: {} seconds, {} nanos",
1815 timestamp_seconds, timestamp_nanos
1816 ))
1817 })?;
1818 Ok(utc_dt.with_timezone(&Local))
1819 }
1820}
1821
1822#[cfg(feature = "chrono")]
1824impl Encoder for NaiveDate {
1825 fn encode(&self, writer: &mut BytesMut) -> Result<()> {
1826 writer.put_u8(TAG_CHRONO_NAIVE_DATE);
1827 let days_from_epoch = self
1829 .signed_duration_since(NaiveDate::from_ymd_opt(1970, 1, 1).unwrap())
1830 .num_days();
1831 days_from_epoch.encode(writer)?;
1832 Ok(())
1833 }
1834
1835 fn is_default(&self) -> bool {
1836 *self == NaiveDate::default()
1837 }
1838}
1839#[cfg(feature = "chrono")]
1840impl Decoder for NaiveDate {
1841 fn decode(reader: &mut Bytes) -> Result<Self> {
1842 if reader.remaining() == 0 {
1843 return Err(EncoderError::InsufficientData);
1844 }
1845 let tag = reader.get_u8();
1846 if tag != TAG_CHRONO_NAIVE_DATE {
1847 return Err(EncoderError::Decode(format!(
1848 "Expected NaiveDate tag ({}), got {}",
1849 TAG_CHRONO_NAIVE_DATE, tag
1850 )));
1851 }
1852 let days_from_epoch = i64::decode(reader)?;
1853 let epoch_date = NaiveDate::from_ymd_opt(1970, 1, 1).unwrap();
1854 epoch_date
1855 .checked_add_signed(chrono::TimeDelta::try_days(days_from_epoch).unwrap())
1856 .ok_or_else(|| {
1857 EncoderError::Decode(format!("Invalid days from epoch: {}", days_from_epoch))
1858 })
1859 }
1860}
1861
1862#[cfg(feature = "chrono")]
1864impl Encoder for NaiveTime {
1865 fn encode(&self, writer: &mut BytesMut) -> Result<()> {
1866 writer.put_u8(TAG_CHRONO_NAIVE_TIME);
1867 let seconds_from_midnight = self.num_seconds_from_midnight();
1869 let nanoseconds = self.nanosecond();
1870 seconds_from_midnight.encode(writer)?;
1871 nanoseconds.encode(writer)?;
1872 Ok(())
1873 }
1874
1875 fn is_default(&self) -> bool {
1876 *self == NaiveTime::default()
1877 }
1878}
1879#[cfg(feature = "chrono")]
1880impl Decoder for NaiveTime {
1881 fn decode(reader: &mut Bytes) -> Result<Self> {
1882 if reader.remaining() == 0 {
1883 return Err(EncoderError::InsufficientData);
1884 }
1885 let tag = reader.get_u8();
1886 if tag != TAG_CHRONO_NAIVE_TIME {
1887 return Err(EncoderError::Decode(format!(
1888 "Expected NaiveTime tag ({}), got {}",
1889 TAG_CHRONO_NAIVE_TIME, tag
1890 )));
1891 }
1892 let seconds_from_midnight = u32::decode(reader)?;
1893 let nanoseconds = u32::decode(reader)?;
1894 NaiveTime::from_num_seconds_from_midnight_opt(seconds_from_midnight, nanoseconds)
1895 .ok_or_else(|| {
1896 EncoderError::Decode(format!(
1897 "Invalid seconds from midnight: {}, nanoseconds: {}",
1898 seconds_from_midnight, nanoseconds
1899 ))
1900 })
1901 }
1902}
1903
1904impl Encoder for Bytes {
1906 fn encode(&self, writer: &mut BytesMut) -> Result<()> {
1907 writer.put_u8(TAG_BINARY);
1908 let len = self.len();
1909 len.encode(writer)?;
1910 writer.put_slice(self);
1911 Ok(())
1912 }
1913
1914 fn is_default(&self) -> bool {
1915 self.is_empty()
1916 }
1917}
1918impl Decoder for Bytes {
1919 fn decode(reader: &mut Bytes) -> Result<Self> {
1920 if reader.remaining() == 0 {
1921 return Err(EncoderError::InsufficientData);
1922 }
1923 let tag = reader.get_u8();
1924 let len = if tag == TAG_BINARY {
1925 usize::decode(reader)?
1926 } else if (TAG_STRING_BASE..=TAG_STRING_LONG).contains(&tag) {
1927 if tag < TAG_STRING_LONG {
1928 (tag - TAG_STRING_BASE) as usize
1929 } else {
1930 usize::decode(reader)?
1931 }
1932 } else {
1933 return Err(EncoderError::Decode(format!(
1934 "Expected Bytes tag ({} or {}..={}), got {}",
1935 TAG_BINARY, TAG_STRING_BASE, TAG_STRING_LONG, tag
1936 )));
1937 };
1938
1939 if reader.remaining() < len {
1940 return Err(EncoderError::InsufficientData);
1941 }
1942
1943 Ok(reader.split_to(len))
1944 }
1945}
1946
1947#[cfg(feature = "rust_decimal")]
1949impl Encoder for Decimal {
1950 fn encode(&self, writer: &mut BytesMut) -> Result<()> {
1951 writer.put_u8(TAG_DECIMAL);
1952 let mantissa = self.mantissa();
1954 let scale = self.scale();
1955 mantissa.encode(writer)?;
1956 scale.encode(writer)?;
1957 Ok(())
1958 }
1959
1960 fn is_default(&self) -> bool {
1961 *self == Decimal::default()
1962 }
1963}
1964#[cfg(feature = "rust_decimal")]
1965impl Decoder for Decimal {
1966 fn decode(reader: &mut Bytes) -> Result<Self> {
1967 if reader.remaining() == 0 {
1968 return Err(EncoderError::InsufficientData);
1969 }
1970 let tag = reader.get_u8();
1971 if tag != TAG_DECIMAL {
1972 return Err(EncoderError::Decode(format!(
1973 "Expected Decimal tag ({}), got {}",
1974 TAG_DECIMAL, tag
1975 )));
1976 }
1977 let mantissa = i128::decode(reader)?;
1978 let scale = u32::decode(reader)?;
1979
1980 Decimal::try_from_i128_with_scale(mantissa, scale).map_err(|e| {
1981 EncoderError::Decode(format!(
1982 "Invalid decimal: mantissa={}, scale={}, error={}",
1983 mantissa, scale, e
1984 ))
1985 })
1986 }
1987}
1988
1989#[cfg(feature = "uuid")]
1991impl Encoder for Uuid {
1992 fn encode(&self, writer: &mut BytesMut) -> Result<()> {
1993 writer.put_u8(TAG_UUID);
1994 let uuid_u128 = self.as_u128();
1996 writer.put_u128_le(uuid_u128);
1997 Ok(())
1998 }
1999
2000 fn is_default(&self) -> bool {
2001 *self == Uuid::default()
2002 }
2003}
2004#[cfg(feature = "uuid")]
2005impl Decoder for Uuid {
2006 fn decode(reader: &mut Bytes) -> Result<Self> {
2007 if reader.remaining() == 0 {
2008 return Err(EncoderError::InsufficientData);
2009 }
2010 let tag = reader.get_u8();
2011 if tag != TAG_UUID {
2012 return Err(EncoderError::Decode(format!(
2013 "Expected UUID tag ({}), got {}",
2014 TAG_UUID, tag
2015 )));
2016 }
2017 if reader.remaining() < 16 {
2018 return Err(EncoderError::InsufficientData);
2019 }
2020 let uuid_u128 = reader.get_u128_le();
2021 Ok(Uuid::from_u128(uuid_u128))
2022 }
2023}
2024
2025#[cfg(feature = "ulid")]
2027impl Encoder for Ulid {
2028 fn encode(&self, writer: &mut BytesMut) -> Result<()> {
2029 writer.put_u8(TAG_UUID); let ulid_u128 = self.0;
2032 writer.put_u128_le(ulid_u128);
2033 Ok(())
2034 }
2035
2036 fn is_default(&self) -> bool {
2037 *self == Ulid::default()
2038 }
2039}
2040#[cfg(feature = "ulid")]
2041impl Decoder for Ulid {
2042 fn decode(reader: &mut Bytes) -> Result<Self> {
2043 if reader.remaining() == 0 {
2044 return Err(EncoderError::InsufficientData);
2045 }
2046 let tag = reader.get_u8();
2047 if tag != TAG_UUID {
2048 return Err(EncoderError::Decode(format!(
2049 "Expected ULID tag ({}), got {}",
2050 TAG_UUID, tag
2051 )));
2052 }
2053 if reader.remaining() < 16 {
2054 return Err(EncoderError::InsufficientData);
2055 }
2056 let ulid_u128 = reader.get_u128_le();
2057 Ok(Ulid(ulid_u128))
2058 }
2059}
2060
2061impl<T: Encoder> Encoder for Arc<T> {
2064 fn encode(&self, writer: &mut BytesMut) -> Result<()> {
2065 (**self).encode(writer)
2066 }
2067
2068 fn is_default(&self) -> bool {
2069 T::is_default(self)
2070 }
2071}
2072
2073impl<T: Decoder> Decoder for Arc<T> {
2075 fn decode(reader: &mut Bytes) -> Result<Self> {
2076 Ok(Arc::new(T::decode(reader)?))
2077 }
2078}
2079
2080#[cfg(feature = "serde_json")]
2082impl Encoder for Value {
2083 fn encode(&self, writer: &mut BytesMut) -> Result<()> {
2084 match self {
2085 Value::Null => {
2086 writer.put_u8(TAG_JSON_NULL);
2087 Ok(())
2088 }
2089 Value::Bool(b) => {
2090 writer.put_u8(TAG_JSON_BOOL);
2091 b.encode(writer)?;
2092 Ok(())
2093 }
2094 Value::Number(n) => {
2095 writer.put_u8(TAG_JSON_NUMBER);
2096 if let Some(u) = n.as_u64() {
2098 writer.put_u8(0); u.encode(writer)?;
2101 } else if let Some(i) = n.as_i64() {
2102 writer.put_u8(1); i.encode(writer)?;
2105 } else {
2106 writer.put_u8(2); let float_val = n.as_f64().unwrap_or(0.0);
2109 float_val.encode(writer)?;
2110 }
2111 Ok(())
2112 }
2113 Value::String(s) => {
2114 writer.put_u8(TAG_JSON_STRING);
2115 s.encode(writer)?;
2116 Ok(())
2117 }
2118 Value::Array(arr) => {
2119 writer.put_u8(TAG_JSON_ARRAY);
2120 let len = arr.len();
2121 len.encode(writer)?;
2122 for item in arr {
2123 item.encode(writer)?;
2124 }
2125 Ok(())
2126 }
2127 Value::Object(obj) => {
2128 writer.put_u8(TAG_JSON_OBJECT);
2129 let len = obj.len();
2130 len.encode(writer)?;
2131 for (key, value) in obj {
2132 key.encode(writer)?;
2133 value.encode(writer)?;
2134 }
2135 Ok(())
2136 }
2137 }
2138 }
2139
2140 fn is_default(&self) -> bool {
2141 *self == Value::default()
2142 }
2143}
2144
2145#[cfg(feature = "serde_json")]
2146impl Decoder for Value {
2147 fn decode(reader: &mut Bytes) -> Result<Self> {
2148 if reader.remaining() == 0 {
2149 return Err(EncoderError::InsufficientData);
2150 }
2151 let tag = reader.get_u8();
2152 match tag {
2153 TAG_JSON_NULL => Ok(Value::Null),
2154 TAG_JSON_BOOL => {
2155 let b = bool::decode(reader)?;
2156 Ok(Value::Bool(b))
2157 }
2158 TAG_JSON_NUMBER => {
2159 if reader.remaining() == 0 {
2160 return Err(EncoderError::InsufficientData);
2161 }
2162 let number_type = reader.get_u8();
2163 match number_type {
2164 0 => {
2165 let u = u64::decode(reader)?;
2167 Ok(Value::Number(Number::from(u)))
2168 }
2169 1 => {
2170 let i = i64::decode(reader)?;
2172 Ok(Value::Number(Number::from(i)))
2173 }
2174 2 => {
2175 let f = f64::decode(reader)?;
2177 Ok(Value::Number(
2178 Number::from_f64(f).unwrap_or(Number::from(0)),
2179 ))
2180 }
2181 _ => Err(EncoderError::Decode(format!(
2182 "Invalid JSON Number type marker: {}",
2183 number_type
2184 ))),
2185 }
2186 }
2187 TAG_JSON_STRING => {
2188 let s = String::decode(reader)?;
2189 Ok(Value::String(s))
2190 }
2191 TAG_JSON_ARRAY => {
2192 let len = usize::decode(reader)?;
2193 let mut arr = Vec::with_capacity(len);
2194 for _ in 0..len {
2195 arr.push(Value::decode(reader)?);
2196 }
2197 Ok(Value::Array(arr))
2198 }
2199 TAG_JSON_OBJECT => {
2200 let len = usize::decode(reader)?;
2201 let mut obj = Map::with_capacity(len);
2202 for _ in 0..len {
2203 let key = String::decode(reader)?;
2204 let value = Value::decode(reader)?;
2205 obj.insert(key, value);
2206 }
2207 Ok(Value::Object(obj))
2208 }
2209 _ => Err(EncoderError::Decode(format!(
2210 "Expected JSON Value tag (202-207), got {}",
2211 tag
2212 ))),
2213 }
2214 }
2215}
2216
2217pub fn write_field_id_optimized(writer: &mut BytesMut, field_id: u64) -> Result<()> {
2221 if field_id == 0 {
2222 writer.put_u8(0);
2224 } else if (1..=250).contains(&field_id) {
2225 writer.put_u8(field_id as u8);
2227 } else {
2228 writer.put_u8(255);
2230 writer.put_u64_le(field_id);
2231 }
2232 Ok(())
2233}
2234
2235pub fn read_field_id_optimized(reader: &mut Bytes) -> Result<u64> {
2239 if reader.remaining() < 1 {
2240 return Err(EncoderError::InsufficientData);
2241 }
2242
2243 let first_byte = reader.get_u8();
2244
2245 if first_byte == 0 {
2246 Ok(0)
2248 } else if first_byte == 255 {
2249 if reader.remaining() < 8 {
2251 return Err(EncoderError::InsufficientData);
2252 }
2253 Ok(reader.get_u64_le())
2254 } else {
2255 Ok(first_byte as u64)
2257 }
2258}