1use crate::bytes::Buf;
37use crate::encode_sink::EncodeSink;
38use crate::encoding::{check_wire_type, decode_varint, encode_varint, varint_len, Tag, WireType};
39use crate::error::DecodeError;
40use crate::types;
41use crate::{DecodeContext, EnumValue, Enumeration, Message, SizeCache};
42use core::hash::Hash;
43
44pub type Map<K, V> = crate::__private::HashMap<K, V>;
98
99#[rustversion::attr(
178 since(1.78),
179 diagnostic::on_unimplemented(
180 message = "`{Self}` cannot be used as a buffa custom map type",
181 note = "buffa owns `MapStorage`, so a foreign type can't implement it directly (orphan rule). \
182 Wrap it in a crate-local newtype and implement `MapStorage` on the newtype. \
183 See the `custom-types` example in the buffa repository for a template."
184 )
185)]
186pub trait MapStorage {
187 type Key;
189 type Value;
191 fn storage_len(&self) -> usize;
193 fn storage_insert(&mut self, key: Self::Key, value: Self::Value);
195 fn storage_clear(&mut self);
199 fn storage_erase_key(_key: &mut Self::Key) {}
206 fn storage_erase_value(_value: &mut Self::Value) {}
209 fn storage_iter<'a>(&'a self) -> impl Iterator<Item = (&'a Self::Key, &'a Self::Value)>
211 where
212 Self::Key: 'a,
213 Self::Value: 'a;
214}
215
216macro_rules! map_storage_hashmap {
223 ($($ty:tt)*) => {
224 impl<K: Eq + Hash, V, S: core::hash::BuildHasher + Default> MapStorage for $($ty)*<K, V, S> {
225 type Key = K;
226 type Value = V;
227 #[inline]
228 fn storage_len(&self) -> usize {
229 self.len()
230 }
231 #[inline]
232 fn storage_insert(&mut self, key: K, value: V) {
233 self.insert(key, value);
234 }
235 #[inline]
236 fn storage_clear(&mut self) {
237 self.clear();
238 }
239 #[inline]
240 fn storage_iter<'a>(&'a self) -> impl Iterator<Item = (&'a K, &'a V)>
241 where
242 K: 'a,
243 V: 'a,
244 {
245 self.iter()
246 }
247 }
248 };
249}
250#[cfg(feature = "std")]
251map_storage_hashmap!(std::collections::HashMap);
252#[cfg(not(feature = "std"))]
253map_storage_hashmap!(hashbrown::HashMap);
254
255impl<K: Ord, V> MapStorage for crate::alloc::collections::BTreeMap<K, V> {
256 type Key = K;
257 type Value = V;
258 #[inline]
259 fn storage_len(&self) -> usize {
260 self.len()
261 }
262 #[inline]
263 fn storage_insert(&mut self, key: K, value: V) {
264 self.insert(key, value);
265 }
266 #[inline]
267 fn storage_clear(&mut self) {
268 self.clear();
269 }
270 #[inline]
271 fn storage_iter<'a>(&'a self) -> impl Iterator<Item = (&'a K, &'a V)>
272 where
273 K: 'a,
274 V: 'a,
275 {
276 self.iter()
277 }
278}
279
280mod sealed {
281 pub trait Sealed {}
290}
291
292pub trait MapValueDecode: sealed::Sealed {
298 type Value: Default;
300 const WIRE_TYPE: WireType;
302 const MAY_RETURN_UNKNOWN: bool = false;
310
311 fn merge(
326 value: &mut Self::Value,
327 buf: &mut impl Buf,
328 ctx: DecodeContext<'_>,
329 ) -> Result<MapValueDecodeStatus, DecodeError>;
330}
331
332#[derive(Clone, Copy, Debug, PartialEq, Eq)]
334#[non_exhaustive]
335pub enum MapValueDecodeStatus {
336 Known,
338 Unknown,
343}
344
345pub trait MapCodec: MapValueDecode {
347 const FIXED_LEN: Option<u64> = None;
355
356 fn encoded_len(value: &Self::Value) -> u64;
362
363 fn encode(value: &Self::Value, buf: &mut impl EncodeSink);
365
366 fn is_default(value: &Self::Value) -> bool;
372}
373
374macro_rules! scalar_codec {
376 ($(#[$doc:meta])* $name:ident, $value:ty, $wire:expr, $fixed:expr,
377 len: $len:expr, encode: $encode:expr, decode: $decode:expr) => {
378 $(#[$doc])*
379 pub struct $name;
380
381 impl sealed::Sealed for $name {}
382
383 impl MapValueDecode for $name {
384 type Value = $value;
385 const WIRE_TYPE: WireType = $wire;
386
387 #[inline]
388 fn merge(
389 value: &mut Self::Value,
390 buf: &mut impl Buf,
391 _ctx: DecodeContext<'_>,
392 ) -> Result<MapValueDecodeStatus, DecodeError> {
393 *value = $decode(buf)?;
394 Ok(MapValueDecodeStatus::Known)
395 }
396 }
397
398 impl MapCodec for $name {
399 const FIXED_LEN: Option<u64> = $fixed;
400
401 #[inline]
402 #[allow(clippy::redundant_closure_call)]
403 fn encoded_len(value: &Self::Value) -> u64 {
404 ($len)(value) as u64
405 }
406
407 #[inline]
408 #[allow(clippy::redundant_closure_call)]
409 fn encode(value: &Self::Value, buf: &mut impl EncodeSink) {
410 ($encode)(value, buf)
411 }
412
413 #[inline]
414 #[allow(clippy::float_cmp)]
415 fn is_default(value: &Self::Value) -> bool {
416 *value == <$value as Default>::default()
417 }
418 }
419 };
420}
421
422scalar_codec!(
423 Int32, i32, WireType::Varint, None,
425 len: |v: &i32| types::int32_encoded_len(*v),
426 encode: |v: &i32, buf: &mut _| types::encode_int32(*v, buf),
427 decode: types::decode_int32
428);
429scalar_codec!(
430 Int64, i64, WireType::Varint, None,
432 len: |v: &i64| types::int64_encoded_len(*v),
433 encode: |v: &i64, buf: &mut _| types::encode_int64(*v, buf),
434 decode: types::decode_int64
435);
436scalar_codec!(
437 Uint32, u32, WireType::Varint, None,
439 len: |v: &u32| types::uint32_encoded_len(*v),
440 encode: |v: &u32, buf: &mut _| types::encode_uint32(*v, buf),
441 decode: types::decode_uint32
442);
443scalar_codec!(
444 Uint64, u64, WireType::Varint, None,
446 len: |v: &u64| types::uint64_encoded_len(*v),
447 encode: |v: &u64, buf: &mut _| types::encode_uint64(*v, buf),
448 decode: types::decode_uint64
449);
450scalar_codec!(
451 Sint32, i32, WireType::Varint, None,
453 len: |v: &i32| types::sint32_encoded_len(*v),
454 encode: |v: &i32, buf: &mut _| types::encode_sint32(*v, buf),
455 decode: types::decode_sint32
456);
457scalar_codec!(
458 Sint64, i64, WireType::Varint, None,
460 len: |v: &i64| types::sint64_encoded_len(*v),
461 encode: |v: &i64, buf: &mut _| types::encode_sint64(*v, buf),
462 decode: types::decode_sint64
463);
464scalar_codec!(
465 Bool, bool, WireType::Varint, Some(types::BOOL_ENCODED_LEN as u64),
467 len: |_: &bool| types::BOOL_ENCODED_LEN,
468 encode: |v: &bool, buf: &mut _| types::encode_bool(*v, buf),
469 decode: types::decode_bool
470);
471scalar_codec!(
472 Fixed32, u32, WireType::Fixed32, Some(types::FIXED32_ENCODED_LEN as u64),
474 len: |_: &u32| types::FIXED32_ENCODED_LEN,
475 encode: |v: &u32, buf: &mut _| types::encode_fixed32(*v, buf),
476 decode: types::decode_fixed32
477);
478scalar_codec!(
479 Fixed64, u64, WireType::Fixed64, Some(types::FIXED64_ENCODED_LEN as u64),
481 len: |_: &u64| types::FIXED64_ENCODED_LEN,
482 encode: |v: &u64, buf: &mut _| types::encode_fixed64(*v, buf),
483 decode: types::decode_fixed64
484);
485scalar_codec!(
486 Sfixed32, i32, WireType::Fixed32, Some(types::FIXED32_ENCODED_LEN as u64),
488 len: |_: &i32| types::FIXED32_ENCODED_LEN,
489 encode: |v: &i32, buf: &mut _| types::encode_sfixed32(*v, buf),
490 decode: types::decode_sfixed32
491);
492scalar_codec!(
493 Sfixed64, i64, WireType::Fixed64, Some(types::FIXED64_ENCODED_LEN as u64),
495 len: |_: &i64| types::FIXED64_ENCODED_LEN,
496 encode: |v: &i64, buf: &mut _| types::encode_sfixed64(*v, buf),
497 decode: types::decode_sfixed64
498);
499scalar_codec!(
500 Float, f32, WireType::Fixed32, Some(types::FIXED32_ENCODED_LEN as u64),
502 len: |_: &f32| types::FIXED32_ENCODED_LEN,
503 encode: |v: &f32, buf: &mut _| types::encode_float(*v, buf),
504 decode: types::decode_float
505);
506scalar_codec!(
507 Double, f64, WireType::Fixed64, Some(types::FIXED64_ENCODED_LEN as u64),
509 len: |_: &f64| types::FIXED64_ENCODED_LEN,
510 encode: |v: &f64, buf: &mut _| types::encode_double(*v, buf),
511 decode: types::decode_double
512);
513scalar_codec!(
514 Str, crate::alloc::string::String, WireType::LengthDelimited, None,
516 len: |v: &crate::alloc::string::String| types::string_encoded_len(v),
517 encode: |v: &crate::alloc::string::String, buf: &mut _| types::encode_string(v, buf),
518 decode: types::decode_string
519);
520scalar_codec!(
521 BytesVec, crate::alloc::vec::Vec<u8>, WireType::LengthDelimited, None,
523 len: |v: &crate::alloc::vec::Vec<u8>| types::bytes_encoded_len(v),
524 encode: |v: &crate::alloc::vec::Vec<u8>, buf: &mut _| types::encode_bytes(v, buf),
525 decode: types::decode_bytes
526);
527scalar_codec!(
528 BytesBuf, crate::bytes::Bytes, WireType::LengthDelimited, None,
531 len: |v: &crate::bytes::Bytes| types::bytes_encoded_len(v),
532 encode: |v: &crate::bytes::Bytes, buf: &mut _| types::encode_shared_bytes(v, buf),
534 decode: types::decode_bytes_to_bytes
535);
536
537pub struct ProtoBytesMap<B>(core::marker::PhantomData<B>);
544
545impl<B: crate::types::ProtoBytes> sealed::Sealed for ProtoBytesMap<B> {}
546
547impl<B: crate::types::ProtoBytes> MapValueDecode for ProtoBytesMap<B> {
548 type Value = B;
549 const WIRE_TYPE: WireType = WireType::LengthDelimited;
550
551 #[inline]
552 fn merge(
553 value: &mut Self::Value,
554 buf: &mut impl Buf,
555 _ctx: DecodeContext<'_>,
556 ) -> Result<MapValueDecodeStatus, DecodeError> {
557 *value = crate::types::decode_bytes_to::<B>(buf)?;
558 Ok(MapValueDecodeStatus::Known)
559 }
560}
561
562impl<B: crate::types::ProtoBytes> MapCodec for ProtoBytesMap<B> {
563 #[inline]
564 fn encoded_len(value: &Self::Value) -> u64 {
565 types::bytes_encoded_len(value.as_ref()) as u64
566 }
567
568 #[inline]
569 fn encode(value: &Self::Value, buf: &mut impl EncodeSink) {
570 types::encode_shared_bytes(value, buf);
573 }
574
575 #[inline]
576 fn is_default(value: &Self::Value) -> bool {
577 value.as_ref().is_empty()
578 }
579}
580
581pub struct ProtoStringMap<S>(core::marker::PhantomData<S>);
595
596impl<S: crate::types::ProtoString> sealed::Sealed for ProtoStringMap<S> {}
597
598impl<S: crate::types::ProtoString> MapValueDecode for ProtoStringMap<S> {
599 type Value = S;
600 const WIRE_TYPE: WireType = WireType::LengthDelimited;
601
602 #[inline]
603 fn merge(
604 value: &mut Self::Value,
605 buf: &mut impl Buf,
606 _ctx: DecodeContext<'_>,
607 ) -> Result<MapValueDecodeStatus, DecodeError> {
608 *value = crate::types::decode_string_to::<S>(buf)?;
609 Ok(MapValueDecodeStatus::Known)
610 }
611}
612
613impl<S: crate::types::ProtoString> MapCodec for ProtoStringMap<S> {
614 #[inline]
615 fn encoded_len(value: &Self::Value) -> u64 {
616 types::string_encoded_len(value.as_ref()) as u64
617 }
618
619 #[inline]
620 fn encode(value: &Self::Value, buf: &mut impl EncodeSink) {
621 types::encode_string(value.as_ref(), buf);
622 }
623
624 #[inline]
625 fn is_default(value: &Self::Value) -> bool {
626 value.as_ref().is_empty()
627 }
628}
629
630pub struct OpenEnum<E>(core::marker::PhantomData<E>);
633
634impl<E: Enumeration> sealed::Sealed for OpenEnum<E> {}
635
636impl<E: Enumeration> MapValueDecode for OpenEnum<E> {
637 type Value = EnumValue<E>;
638 const WIRE_TYPE: WireType = WireType::Varint;
639
640 #[inline]
641 fn merge(
642 value: &mut Self::Value,
643 buf: &mut impl Buf,
644 _ctx: DecodeContext<'_>,
645 ) -> Result<MapValueDecodeStatus, DecodeError> {
646 *value = EnumValue::from(types::decode_int32(buf)?);
647 Ok(MapValueDecodeStatus::Known)
648 }
649}
650
651impl<E: Enumeration> MapCodec for OpenEnum<E> {
652 #[inline]
653 fn encoded_len(value: &Self::Value) -> u64 {
654 types::int32_encoded_len(value.to_i32()) as u64
655 }
656
657 #[inline]
658 fn encode(value: &Self::Value, buf: &mut impl EncodeSink) {
659 types::encode_int32(value.to_i32(), buf);
660 }
661
662 #[inline]
663 fn is_default(value: &Self::Value) -> bool {
664 value.to_i32() == 0
665 }
666}
667
668pub struct ClosedEnum<E>(core::marker::PhantomData<E>);
674
675impl<E: Enumeration + Default> sealed::Sealed for ClosedEnum<E> {}
676
677impl<E: Enumeration + Default> MapValueDecode for ClosedEnum<E> {
678 type Value = E;
679 const WIRE_TYPE: WireType = WireType::Varint;
680 const MAY_RETURN_UNKNOWN: bool = true;
681
682 #[inline]
683 fn merge(
684 value: &mut Self::Value,
685 buf: &mut impl Buf,
686 _ctx: DecodeContext<'_>,
687 ) -> Result<MapValueDecodeStatus, DecodeError> {
688 let raw = types::decode_int32(buf)?;
689 if let Some(v) = E::from_i32(raw) {
690 *value = v;
691 Ok(MapValueDecodeStatus::Known)
692 } else {
693 Ok(MapValueDecodeStatus::Unknown)
694 }
695 }
696}
697
698impl<E: Enumeration + Default> MapCodec for ClosedEnum<E> {
699 #[inline]
700 fn encoded_len(value: &Self::Value) -> u64 {
701 types::int32_encoded_len(value.to_i32()) as u64
702 }
703
704 #[inline]
705 fn encode(value: &Self::Value, buf: &mut impl EncodeSink) {
706 types::encode_int32(value.to_i32(), buf);
707 }
708
709 #[inline]
710 fn is_default(value: &Self::Value) -> bool {
711 *value == E::default()
712 }
713}
714
715pub struct Msg<M>(core::marker::PhantomData<M>);
718
719impl<M: Message + Default> sealed::Sealed for Msg<M> {}
720
721impl<M: Message + Default> MapValueDecode for Msg<M> {
722 type Value = M;
723 const WIRE_TYPE: WireType = WireType::LengthDelimited;
724
725 #[inline]
726 fn merge(
727 value: &mut Self::Value,
728 buf: &mut impl Buf,
729 ctx: DecodeContext<'_>,
730 ) -> Result<MapValueDecodeStatus, DecodeError> {
731 Message::merge_length_delimited(value, buf, ctx)?;
732 Ok(MapValueDecodeStatus::Known)
733 }
734}
735
736const ENTRY_TAG_LEN: u64 = 2;
739
740#[inline]
741fn entry_len<KC: MapCodec, VC: MapCodec>(k: &KC::Value, v: &VC::Value) -> u64 {
742 ENTRY_TAG_LEN + KC::encoded_len(k) + VC::encoded_len(v)
743}
744
745pub fn field_len<KC: MapCodec, VC: MapCodec, C>(map: &C, outer_tag_len: u64) -> u64
752where
753 C: MapStorage<Key = KC::Value, Value = VC::Value>,
754{
755 if let (Some(kf), Some(vf)) = (KC::FIXED_LEN, VC::FIXED_LEN) {
756 let entry = ENTRY_TAG_LEN + kf + vf;
757 return map.storage_len() as u64 * (outer_tag_len + varint_len(entry) as u64 + entry);
758 }
759 let mut size = 0u64;
760 for (k, v) in map.storage_iter() {
761 let entry = entry_len::<KC, VC>(k, v);
762 size += outer_tag_len + varint_len(entry) as u64 + entry;
763 }
764 size
765}
766
767pub fn write_field<KC: MapCodec, VC: MapCodec, C>(
770 map: &C,
771 field_number: u32,
772 buf: &mut impl EncodeSink,
773) where
774 C: MapStorage<Key = KC::Value, Value = VC::Value>,
775{
776 for (k, v) in map.storage_iter() {
777 let entry = entry_len::<KC, VC>(k, v);
778 Tag::new(field_number, WireType::LengthDelimited).encode(buf);
779 encode_varint(entry, buf);
780 Tag::new(1, KC::WIRE_TYPE).encode(buf);
781 KC::encode(k, buf);
782 Tag::new(2, VC::WIRE_TYPE).encode(buf);
783 VC::encode(v, buf);
784 }
785}
786
787pub fn message_field_len<KC: MapCodec, M: Message, C>(
793 map: &C,
794 outer_tag_len: u64,
795 cache: &mut SizeCache,
796) -> u64
797where
798 C: MapStorage<Key = KC::Value, Value = M>,
799{
800 let mut size = 0u64;
801 for (k, v) in map.storage_iter() {
802 let slot = cache.reserve();
803 let inner = v.compute_size(cache);
804 cache.set(slot, inner);
805 let entry =
806 ENTRY_TAG_LEN + KC::encoded_len(k) + varint_len(inner as u64) as u64 + inner as u64;
807 size += outer_tag_len + varint_len(entry) as u64 + entry;
808 }
809 size
810}
811
812pub fn write_message_field<KC: MapCodec, M: Message, C>(
815 map: &C,
816 field_number: u32,
817 cache: &mut SizeCache,
818 buf: &mut impl EncodeSink,
819) where
820 C: MapStorage<Key = KC::Value, Value = M>,
821{
822 for (k, v) in map.storage_iter() {
823 let inner = cache.consume_next();
824 let entry =
825 ENTRY_TAG_LEN + KC::encoded_len(k) + varint_len(inner as u64) as u64 + inner as u64;
826 Tag::new(field_number, WireType::LengthDelimited).encode(buf);
827 encode_varint(entry, buf);
828 Tag::new(1, KC::WIRE_TYPE).encode(buf);
829 KC::encode(k, buf);
830 Tag::new(2, WireType::LengthDelimited).encode(buf);
831 encode_varint(inner as u64, buf);
832 v.write_to(cache, buf);
833 }
834}
835
836const ENTRY_FIELD_TAG_LEN: u64 = 1;
839
840struct Omitted {
843 key: bool,
844 value: bool,
845}
846
847impl Omitted {
848 #[inline]
849 fn of<KC: MapCodec, VC: MapCodec>(k: &KC::Value, v: &VC::Value) -> Self {
850 Self {
851 key: KC::is_default(k),
852 value: VC::is_default(v),
853 }
854 }
855
856 #[inline]
858 fn entry_len<KC: MapCodec, VC: MapCodec>(&self, k: &KC::Value, v: &VC::Value) -> u64 {
859 let value = if self.value {
860 0
861 } else {
862 ENTRY_FIELD_TAG_LEN + VC::encoded_len(v)
863 };
864 sparse_key_len::<KC>(self.key, k) + value
865 }
866}
867
868#[inline]
870fn sparse_key_len<KC: MapCodec>(omitted: bool, k: &KC::Value) -> u64 {
871 if omitted {
872 0
873 } else {
874 ENTRY_FIELD_TAG_LEN + KC::encoded_len(k)
875 }
876}
877
878#[inline]
881fn sparse_message_len(inner: u32) -> u64 {
882 if inner == 0 {
883 0
884 } else {
885 ENTRY_FIELD_TAG_LEN + varint_len(inner as u64) as u64 + inner as u64
886 }
887}
888
889pub fn field_len_omitting_defaults<KC: MapCodec, VC: MapCodec, C>(
892 map: &C,
893 outer_tag_len: u64,
894) -> u64
895where
896 C: MapStorage<Key = KC::Value, Value = VC::Value>,
897{
898 let mut size = 0u64;
899 for (k, v) in map.storage_iter() {
900 let entry = Omitted::of::<KC, VC>(k, v).entry_len::<KC, VC>(k, v);
901 size += outer_tag_len + varint_len(entry) as u64 + entry;
902 }
903 size
904}
905
906pub fn write_field_omitting_defaults<KC: MapCodec, VC: MapCodec, C>(
910 map: &C,
911 field_number: u32,
912 buf: &mut impl EncodeSink,
913) where
914 C: MapStorage<Key = KC::Value, Value = VC::Value>,
915{
916 for (k, v) in map.storage_iter() {
917 let omitted = Omitted::of::<KC, VC>(k, v);
918 Tag::new(field_number, WireType::LengthDelimited).encode(buf);
919 encode_varint(omitted.entry_len::<KC, VC>(k, v), buf);
920 if !omitted.key {
921 Tag::new(1, KC::WIRE_TYPE).encode(buf);
922 KC::encode(k, buf);
923 }
924 if !omitted.value {
925 Tag::new(2, VC::WIRE_TYPE).encode(buf);
926 VC::encode(v, buf);
927 }
928 }
929}
930
931pub fn message_field_len_omitting_defaults<KC: MapCodec, M: Message, C>(
935 map: &C,
936 outer_tag_len: u64,
937 cache: &mut SizeCache,
938) -> u64
939where
940 C: MapStorage<Key = KC::Value, Value = M>,
941{
942 let mut size = 0u64;
943 for (k, v) in map.storage_iter() {
944 let slot = cache.reserve();
945 let inner = v.compute_size(cache);
946 cache.set(slot, inner);
947 let entry = sparse_key_len::<KC>(KC::is_default(k), k) + sparse_message_len(inner);
948 size += outer_tag_len + varint_len(entry) as u64 + entry;
949 }
950 size
951}
952
953pub fn write_message_field_omitting_defaults<KC: MapCodec, M: Message, C>(
957 map: &C,
958 field_number: u32,
959 cache: &mut SizeCache,
960 buf: &mut impl EncodeSink,
961) where
962 C: MapStorage<Key = KC::Value, Value = M>,
963{
964 for (k, v) in map.storage_iter() {
965 let inner = cache.consume_next();
966 let key_omitted = KC::is_default(k);
967 Tag::new(field_number, WireType::LengthDelimited).encode(buf);
968 encode_varint(
969 sparse_key_len::<KC>(key_omitted, k) + sparse_message_len(inner),
970 buf,
971 );
972 if !key_omitted {
973 Tag::new(1, KC::WIRE_TYPE).encode(buf);
974 KC::encode(k, buf);
975 }
976 if inner != 0 {
977 Tag::new(2, WireType::LengthDelimited).encode(buf);
978 encode_varint(inner as u64, buf);
979 }
980 v.write_to(cache, buf);
983 }
984}
985
986fn merge_entry_contents<KC, VC>(
987 key: &mut KC::Value,
988 val: &mut VC::Value,
989 buf: &mut impl Buf,
990 ctx: DecodeContext<'_>,
991) -> Result<MapValueDecodeStatus, DecodeError>
992where
993 KC: MapValueDecode,
994 VC: MapValueDecode,
995{
996 let mut val_status = MapValueDecodeStatus::Known;
1001 while buf.has_remaining() {
1002 let entry_tag = Tag::decode(buf)?;
1003 match entry_tag.field_number() {
1004 1 => {
1005 check_wire_type(entry_tag, KC::WIRE_TYPE)?;
1006 KC::merge(key, buf, ctx)?;
1007 }
1008 2 => {
1009 check_wire_type(entry_tag, VC::WIRE_TYPE)?;
1010 val_status = VC::merge(val, buf, ctx)?;
1011 if matches!(val_status, MapValueDecodeStatus::Unknown) {
1012 ctx.check_unknown_field()?;
1013 }
1014 }
1015 _ => {
1016 crate::encoding::skip_unknown_field(entry_tag, buf, ctx)?;
1017 }
1018 }
1019 }
1020 Ok(val_status)
1021}
1022
1023pub fn merge_entry<KC, VC, C>(
1029 map: &mut C,
1030 buf: &mut impl Buf,
1031 ctx: DecodeContext<'_>,
1032) -> Result<(), DecodeError>
1033where
1034 KC: MapValueDecode,
1035 VC: MapValueDecode,
1036 C: MapStorage<Key = KC::Value, Value = VC::Value>,
1037{
1038 merge_entry_with_unknowns::<KC, VC, C>(map, buf, ctx, None)
1039}
1040
1041pub fn merge_entry_with_unknowns<KC, VC, C>(
1061 map: &mut C,
1062 buf: &mut impl Buf,
1063 ctx: DecodeContext<'_>,
1064 unknown_fields: Option<(u32, &mut crate::UnknownFields)>,
1065) -> Result<(), DecodeError>
1066where
1067 KC: MapValueDecode,
1068 VC: MapValueDecode,
1069 C: MapStorage<Key = KC::Value, Value = VC::Value>,
1070{
1071 let entry_len = decode_varint(buf)?;
1072 let entry_len = usize::try_from(entry_len).map_err(|_| DecodeError::MessageTooLarge)?;
1073 if buf.remaining() < entry_len {
1074 return Err(DecodeError::UnexpectedEof);
1075 }
1076 ctx.register_element_memory(
1082 core::mem::size_of::<KC::Value>() + core::mem::size_of::<VC::Value>(),
1083 )?;
1084 let mut key = crate::erasing::Erasing::new(KC::Value::default(), C::storage_erase_key);
1085 let mut val = crate::erasing::Erasing::new(VC::Value::default(), C::storage_erase_value);
1086
1087 if unknown_fields.is_some() && (KC::MAY_RETURN_UNKNOWN || VC::MAY_RETURN_UNKNOWN) {
1088 if buf.chunk().len() >= entry_len {
1092 let preserved = {
1093 let entry_slice = &buf.chunk()[..entry_len];
1094 let mut entry_cur = entry_slice;
1095 let status =
1096 merge_entry_contents::<KC, VC>(&mut key, &mut val, &mut entry_cur, ctx)?;
1097 matches!(status, MapValueDecodeStatus::Unknown).then(|| entry_slice.to_vec())
1098 };
1099 buf.advance(entry_len);
1100 match preserved {
1101 None => map.storage_insert(key.into_inner(), val.into_inner()),
1102 Some(payload) => {
1103 if let Some((field_number, unknown_fields)) = unknown_fields {
1104 ctx.register_unknown_field()?;
1105 unknown_fields.push(crate::UnknownField {
1106 number: field_number,
1107 data: crate::UnknownFieldData::LengthDelimited(payload),
1108 });
1109 }
1110 }
1111 }
1112 return Ok(());
1113 }
1114 let entry_payload = buf.copy_to_bytes(entry_len);
1117 let mut entry_cur = entry_payload.clone();
1118 let status = merge_entry_contents::<KC, VC>(&mut key, &mut val, &mut entry_cur, ctx)?;
1119 if matches!(status, MapValueDecodeStatus::Known) {
1120 map.storage_insert(key.into_inner(), val.into_inner());
1121 } else if let Some((field_number, unknown_fields)) = unknown_fields {
1122 ctx.register_unknown_field()?;
1123 unknown_fields.push(crate::UnknownField {
1124 number: field_number,
1125 data: crate::UnknownFieldData::LengthDelimited(entry_payload.to_vec()),
1126 });
1127 }
1128 return Ok(());
1129 }
1130
1131 let entry_limit = buf.remaining() - entry_len;
1132 let mut val_status = MapValueDecodeStatus::Known;
1133 while buf.remaining() > entry_limit {
1134 let entry_tag = Tag::decode(buf)?;
1135 match entry_tag.field_number() {
1136 1 => {
1137 check_wire_type(entry_tag, KC::WIRE_TYPE)?;
1138 KC::merge(&mut key, buf, ctx)?;
1139 }
1140 2 => {
1141 check_wire_type(entry_tag, VC::WIRE_TYPE)?;
1142 val_status = VC::merge(&mut val, buf, ctx)?;
1143 if matches!(val_status, MapValueDecodeStatus::Unknown) {
1144 ctx.check_unknown_field()?;
1145 }
1146 }
1147 _ => {
1148 crate::encoding::skip_unknown_field(entry_tag, buf, ctx)?;
1149 }
1150 }
1151 }
1152 if buf.remaining() != entry_limit {
1153 let remaining = buf.remaining();
1154 if remaining > entry_limit {
1155 buf.advance(remaining - entry_limit);
1156 } else {
1157 return Err(DecodeError::UnexpectedEof);
1158 }
1159 }
1160 if matches!(val_status, MapValueDecodeStatus::Known) {
1161 map.storage_insert(key.into_inner(), val.into_inner());
1162 }
1163 Ok(())
1164}
1165
1166#[cfg(test)]
1167mod tests {
1168 use super::*;
1169 use crate::alloc::string::String;
1170 use crate::alloc::vec::Vec;
1171 use crate::encoding::skip_field_depth;
1172
1173 fn encode_field<KC: MapCodec, VC: MapCodec>(
1174 map: &Map<KC::Value, VC::Value>,
1175 field_number: u32,
1176 outer_tag_len: u64,
1177 ) -> Vec<u8>
1178 where
1179 KC::Value: Eq + Hash,
1180 {
1181 let len = field_len::<KC, VC, _>(map, outer_tag_len);
1182 let mut buf = Vec::new();
1183 write_field::<KC, VC, _>(map, field_number, &mut buf);
1184 assert_eq!(buf.len() as u64, len, "field_len must match written bytes");
1185 buf
1186 }
1187
1188 fn decode_field<KC, VC>(mut wire: &[u8]) -> Map<KC::Value, VC::Value>
1189 where
1190 KC: MapValueDecode,
1191 KC::Value: Eq + Hash,
1192 VC: MapValueDecode,
1193 {
1194 let mut map = Map::default();
1195 let limit = core::cell::Cell::new(crate::DEFAULT_UNKNOWN_FIELD_LIMIT);
1196 while !wire.is_empty() {
1197 let tag = Tag::decode(&mut wire).unwrap();
1198 assert_eq!(tag.wire_type(), WireType::LengthDelimited);
1199 let ctx = DecodeContext::new(crate::RECURSION_LIMIT, &limit);
1200 merge_entry::<KC, VC, _>(&mut map, &mut wire, ctx).unwrap();
1201 }
1202 map
1203 }
1204
1205 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
1208 #[repr(i32)]
1209 enum FirstIsOne {
1210 #[default]
1211 A = 1,
1212 B = 0,
1213 }
1214
1215 impl Enumeration for FirstIsOne {
1216 fn from_i32(value: i32) -> Option<Self> {
1217 match value {
1218 1 => Some(Self::A),
1219 0 => Some(Self::B),
1220 _ => None,
1221 }
1222 }
1223 fn to_i32(&self) -> i32 {
1224 *self as i32
1225 }
1226 fn proto_name(&self) -> &'static str {
1227 match self {
1228 Self::A => "A",
1229 Self::B => "B",
1230 }
1231 }
1232 }
1233
1234 #[test]
1235 fn string_int32_round_trip() {
1236 let mut map: Map<String, i32> = Map::default();
1237 map.insert("a".into(), 1);
1238 map.insert("bee".into(), -7);
1239 let wire = encode_field::<Str, Int32>(&map, 5, 1);
1240 let back = decode_field::<Str, Int32>(&wire);
1241 assert_eq!(back, map);
1242 }
1243
1244 #[test]
1245 fn proto_string_map_codec_matches_str() {
1246 let mut map: Map<String, i32> = Map::default();
1251 map.insert("a".into(), 1);
1252 map.insert("bee".into(), -7);
1253
1254 let str_wire = encode_field::<Str, Int32>(&map, 5, 1);
1255 let custom_wire = encode_field::<ProtoStringMap<String>, Int32>(&map, 5, 1);
1256 assert_eq!(
1258 decode_field::<ProtoStringMap<String>, Int32>(&str_wire),
1259 map
1260 );
1261 assert_eq!(decode_field::<Str, Int32>(&custom_wire), map);
1262
1263 let mut vmap: Map<i32, String> = Map::default();
1265 vmap.insert(1, "x".into());
1266 let vwire = encode_field::<Int32, ProtoStringMap<String>>(&vmap, 3, 1);
1267 assert_eq!(decode_field::<Int32, ProtoStringMap<String>>(&vwire), vmap);
1268 }
1269
1270 #[test]
1271 fn fixed_fixed_len_fold_matches_written_bytes() {
1272 let mut map: Map<u32, f64> = Map::default();
1273 map.insert(1, 0.5);
1274 map.insert(9, -2.25);
1275 map.insert(1000, 0.0);
1276 let wire = encode_field::<Fixed32, Double>(&map, 3, 1);
1279 let back = decode_field::<Fixed32, Double>(&wire);
1280 assert_eq!(back, map);
1281 }
1282
1283 #[test]
1286 fn omitting_defaults_leaves_default_fields_out() {
1287 let encode = |key: &str, value: i32| {
1288 let mut map: Map<String, i32> = Map::default();
1289 map.insert(key.into(), value);
1290 let len = field_len_omitting_defaults::<Str, Int32, _>(&map, 1);
1291 let mut buf = Vec::new();
1292 write_field_omitting_defaults::<Str, Int32, _>(&map, 5, &mut buf);
1293 assert_eq!(buf.len() as u64, len, "the size matches the written bytes");
1294 assert_eq!(decode_field::<Str, Int32>(&buf), map);
1295 buf
1296 };
1297 assert_eq!(encode("", 0), [0x2a, 0x00]);
1299 assert_eq!(encode("a", 0), [0x2a, 0x03, 0x0a, 0x01, b'a']);
1301 assert_eq!(encode("", 7), [0x2a, 0x02, 0x10, 0x07]);
1303 assert_eq!(
1304 encode("a", 7),
1305 encode_field::<Str, Int32>(
1306 &{
1307 let mut map = Map::default();
1308 map.insert(String::from("a"), 7);
1309 map
1310 },
1311 5,
1312 1
1313 )
1314 );
1315 let mut floats: Map<u32, f64> = Map::default();
1317 floats.insert(1, -0.0);
1318 let mut buf = Vec::new();
1319 write_field_omitting_defaults::<Uint32, Double, _>(&floats, 2, &mut buf);
1320 assert_eq!(buf, [0x12, 0x02, 0x08, 0x01]);
1321 }
1322
1323 #[test]
1326 fn omitting_defaults_compares_a_closed_enum_with_its_default() {
1327 type Codec = ClosedEnum<FirstIsOne>;
1328 let encode = |value: FirstIsOne| {
1329 let mut map: Map<u32, FirstIsOne> = Map::default();
1330 map.insert(1, value);
1331 let len = field_len_omitting_defaults::<Uint32, Codec, _>(&map, 1);
1332 let mut buf = Vec::new();
1333 write_field_omitting_defaults::<Uint32, Codec, _>(&map, 2, &mut buf);
1334 assert_eq!(buf.len() as u64, len, "the size matches the written bytes");
1335 assert_eq!(decode_field::<Uint32, Codec>(&buf), map);
1336 buf
1337 };
1338 assert_eq!(encode(FirstIsOne::A), [0x12, 0x02, 0x08, 0x01]);
1340 assert_eq!(encode(FirstIsOne::B), [0x12, 0x04, 0x08, 0x01, 0x10, 0x00]);
1342 }
1343
1344 #[test]
1347 fn is_default_is_the_decoded_default() {
1348 fn check<C: MapCodec>(default: C::Value, others: &[C::Value]) {
1349 let decoded = decode_field::<Int32, C>(&[0x0a, 0x00]);
1351 assert!(C::is_default(&decoded[&0]));
1352 assert!(C::is_default(&default));
1353 for other in others {
1354 assert!(!C::is_default(other));
1355 }
1356 }
1357 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
1358 #[repr(i32)]
1359 enum E {
1360 #[default]
1361 A = 0,
1362 B = 1,
1363 }
1364 impl Enumeration for E {
1365 fn from_i32(value: i32) -> Option<Self> {
1366 match value {
1367 0 => Some(E::A),
1368 1 => Some(E::B),
1369 _ => None,
1370 }
1371 }
1372 fn to_i32(&self) -> i32 {
1373 *self as i32
1374 }
1375 fn proto_name(&self) -> &'static str {
1376 match self {
1377 E::A => "A",
1378 E::B => "B",
1379 }
1380 }
1381 }
1382 check::<Int32>(0, &[1, -1]);
1383 check::<Int64>(0, &[1, i64::MIN]);
1384 check::<Uint32>(0, &[1]);
1385 check::<Uint64>(0, &[u64::MAX]);
1386 check::<Sint32>(0, &[-1]);
1387 check::<Sint64>(0, &[-1]);
1388 check::<Fixed32>(0, &[1]);
1389 check::<Fixed64>(0, &[1]);
1390 check::<Sfixed32>(0, &[-1]);
1391 check::<Sfixed64>(0, &[-1]);
1392 check::<Bool>(false, &[true]);
1393 check::<Float>(0.0, &[1.0, f32::NAN, f32::MIN_POSITIVE]);
1394 check::<Float>(-0.0, &[]);
1395 check::<Double>(0.0, &[1.0, f64::NAN, f64::MIN_POSITIVE]);
1396 check::<Double>(-0.0, &[]);
1397 check::<Str>(String::new(), &["a".into()]);
1398 check::<BytesVec>(Vec::new(), &[vec![0]]);
1399 check::<BytesBuf>(
1400 crate::bytes::Bytes::new(),
1401 &[crate::bytes::Bytes::from_static(&[0])],
1402 );
1403 check::<ProtoStringMap<String>>(String::new(), &[" ".into()]);
1404 check::<ProtoBytesMap<Vec<u8>>>(Vec::new(), &[vec![0]]);
1405 check::<OpenEnum<E>>(
1406 EnumValue::from(0),
1407 &[EnumValue::from(1), EnumValue::Unknown(7)],
1408 );
1409 check::<ClosedEnum<E>>(E::A, &[E::B]);
1410 check::<ClosedEnum<FirstIsOne>>(FirstIsOne::A, &[FirstIsOne::B]);
1412 check::<OpenEnum<FirstIsOne>>(EnumValue::from(0), &[EnumValue::from(1)]);
1413 }
1414
1415 #[test]
1416 fn missing_key_and_value_take_defaults() {
1417 let wire = [0x00u8];
1419 let mut map: Map<String, i32> = Map::default();
1420 let limit = core::cell::Cell::new(crate::DEFAULT_UNKNOWN_FIELD_LIMIT);
1421 merge_entry::<Str, Int32, _>(&mut map, &mut &wire[..], DecodeContext::new(10, &limit))
1422 .unwrap();
1423 assert_eq!(map.get(""), Some(&0));
1424 }
1425
1426 #[test]
1427 fn unknown_entry_field_is_skipped() {
1428 let mut entry = Vec::new();
1430 Tag::new(1, WireType::LengthDelimited).encode(&mut entry);
1431 types::encode_string("a", &mut entry);
1432 Tag::new(3, WireType::Varint).encode(&mut entry);
1433 encode_varint(99, &mut entry);
1434 Tag::new(2, WireType::Varint).encode(&mut entry);
1435 types::encode_int32(7, &mut entry);
1436 let mut wire = Vec::new();
1437 encode_varint(entry.len() as u64, &mut wire);
1438 wire.extend_from_slice(&entry);
1439
1440 let mut map: Map<String, i32> = Map::default();
1441 let limit = core::cell::Cell::new(crate::DEFAULT_UNKNOWN_FIELD_LIMIT);
1442 merge_entry::<Str, Int32, _>(
1443 &mut map,
1444 &mut wire.as_slice(),
1445 DecodeContext::new(10, &limit),
1446 )
1447 .unwrap();
1448 assert_eq!(map.get("a"), Some(&7));
1449 }
1450
1451 #[test]
1452 fn entry_wire_type_mismatch_errors() {
1453 let mut entry = Vec::new();
1455 Tag::new(1, WireType::Fixed64).encode(&mut entry);
1456 entry.extend_from_slice(&[0u8; 8]);
1457 let mut wire = Vec::new();
1458 encode_varint(entry.len() as u64, &mut wire);
1459 wire.extend_from_slice(&entry);
1460
1461 let mut map: Map<String, i32> = Map::default();
1462 let limit = core::cell::Cell::new(crate::DEFAULT_UNKNOWN_FIELD_LIMIT);
1463 let err = merge_entry::<Str, Int32, _>(
1464 &mut map,
1465 &mut wire.as_slice(),
1466 DecodeContext::new(10, &limit),
1467 )
1468 .unwrap_err();
1469 assert!(matches!(err, DecodeError::WireTypeMismatch { .. }));
1470 }
1471
1472 #[test]
1473 fn truncated_entry_errors() {
1474 let wire = [0x05u8, 0x08];
1476 let mut map: Map<String, i32> = Map::default();
1477 let limit = core::cell::Cell::new(crate::DEFAULT_UNKNOWN_FIELD_LIMIT);
1478 let err =
1479 merge_entry::<Str, Int32, _>(&mut map, &mut &wire[..], DecodeContext::new(10, &limit))
1480 .unwrap_err();
1481 assert!(matches!(err, DecodeError::UnexpectedEof));
1482 }
1483
1484 #[test]
1485 fn message_map_two_pass_round_trip() {
1486 use crate::{DefaultInstance, SizeCache};
1487
1488 #[derive(Clone, PartialEq, Eq, Debug, Default)]
1489 struct FlatMsg {
1490 value: i32,
1491 }
1492
1493 impl DefaultInstance for FlatMsg {
1494 fn default_instance() -> &'static Self {
1495 static INST: crate::__private::OnceBox<FlatMsg> = crate::__private::OnceBox::new();
1496 INST.get_or_init(|| crate::alloc::boxed::Box::new(FlatMsg::default()))
1497 }
1498 }
1499
1500 impl Message for FlatMsg {
1501 fn compute_size(&self, _cache: &mut SizeCache) -> u32 {
1502 if self.value != 0 {
1503 1 + types::int32_encoded_len(self.value) as u32
1504 } else {
1505 0
1506 }
1507 }
1508 fn write_to(&self, _cache: &mut SizeCache, buf: &mut impl EncodeSink) {
1509 if self.value != 0 {
1510 Tag::new(1, WireType::Varint).encode(buf);
1511 types::encode_int32(self.value, buf);
1512 }
1513 }
1514 fn merge_field(
1515 &mut self,
1516 tag: Tag,
1517 buf: &mut impl Buf,
1518 ctx: DecodeContext<'_>,
1519 ) -> Result<(), DecodeError> {
1520 match tag.field_number() {
1521 1 => self.value = types::decode_int32(buf)?,
1522 _ => skip_field_depth(tag, buf, ctx.depth())?,
1523 }
1524 Ok(())
1525 }
1526 fn clear(&mut self) {
1527 *self = Self::default();
1528 }
1529 }
1530
1531 let mut map: Map<i32, FlatMsg> = Map::default();
1532 map.insert(1, FlatMsg { value: 0 }); map.insert(2, FlatMsg { value: -3 }); map.insert(9, FlatMsg { value: 7 });
1535
1536 let mut cache = SizeCache::default();
1540 let len = message_field_len::<Int32, FlatMsg, _>(&map, 1, &mut cache);
1541 let mut wire = Vec::new();
1542 write_message_field::<Int32, FlatMsg, _>(&map, 4, &mut cache, &mut wire);
1543 assert_eq!(wire.len() as u64, len, "size pass must match write pass");
1544
1545 let back = decode_field::<Int32, Msg<FlatMsg>>(&wire);
1546 assert_eq!(back, map);
1547
1548 let mut cache = SizeCache::default();
1551 let mut sparse: Map<i32, FlatMsg> = Map::default();
1552 sparse.insert(0, FlatMsg { value: 5 });
1553 sparse.insert(1, FlatMsg { value: 0 });
1554 sparse.insert(2, FlatMsg { value: -3 });
1555 let len = message_field_len_omitting_defaults::<Int32, FlatMsg, _>(&sparse, 1, &mut cache);
1556 let mut wire = Vec::new();
1557 write_message_field_omitting_defaults::<Int32, FlatMsg, _>(
1558 &sparse, 4, &mut cache, &mut wire,
1559 );
1560 assert_eq!(wire.len() as u64, len, "size pass must match write pass");
1561 assert_eq!(decode_field::<Int32, Msg<FlatMsg>>(&wire), sparse);
1562 let entries: Vec<Vec<u8>> = {
1563 let mut rest = wire.as_slice();
1564 let mut out = Vec::new();
1565 while !rest.is_empty() {
1566 Tag::decode(&mut rest).unwrap();
1567 let len = decode_varint(&mut rest).unwrap() as usize;
1568 out.push(rest[..len].to_vec());
1569 rest = &rest[len..];
1570 }
1571 out
1572 };
1573 assert!(
1575 entries.contains(&vec![0x12, 0x02, 0x08, 0x05]),
1576 "{entries:?}"
1577 );
1578 assert!(entries.contains(&vec![0x08, 0x01]), "{entries:?}");
1579
1580 #[derive(Clone, PartialEq, Eq, Debug, Default)]
1583 struct Outer {
1584 inner: Option<FlatMsg>,
1585 }
1586
1587 impl DefaultInstance for Outer {
1588 fn default_instance() -> &'static Self {
1589 static INST: crate::__private::OnceBox<Outer> = crate::__private::OnceBox::new();
1590 INST.get_or_init(|| crate::alloc::boxed::Box::new(Outer::default()))
1591 }
1592 }
1593
1594 impl Message for Outer {
1595 fn compute_size(&self, cache: &mut SizeCache) -> u32 {
1596 let Some(inner) = &self.inner else {
1597 return 0;
1598 };
1599 let slot = cache.reserve();
1600 let len = inner.compute_size(cache);
1601 cache.set(slot, len);
1602 1 + varint_len(len as u64) as u32 + len
1603 }
1604 fn write_to(&self, cache: &mut SizeCache, buf: &mut impl EncodeSink) {
1605 if let Some(inner) = &self.inner {
1606 let len = cache.consume_next();
1607 Tag::new(1, WireType::LengthDelimited).encode(buf);
1608 encode_varint(len as u64, buf);
1609 inner.write_to(cache, buf);
1610 }
1611 }
1612 fn merge_field(
1613 &mut self,
1614 tag: Tag,
1615 buf: &mut impl Buf,
1616 ctx: DecodeContext<'_>,
1617 ) -> Result<(), DecodeError> {
1618 match tag.field_number() {
1619 1 => Message::merge_length_delimited(
1620 self.inner.get_or_insert_with(FlatMsg::default),
1621 buf,
1622 ctx,
1623 )?,
1624 _ => skip_field_depth(tag, buf, ctx.depth())?,
1625 }
1626 Ok(())
1627 }
1628 fn clear(&mut self) {
1629 *self = Self::default();
1630 }
1631 }
1632
1633 let mut nested = crate::alloc::collections::BTreeMap::new();
1634 nested.insert(1, Outer::default());
1635 nested.insert(
1636 2,
1637 Outer {
1638 inner: Some(FlatMsg { value: 7 }),
1639 },
1640 );
1641 let mut cache = SizeCache::default();
1642 let len = message_field_len_omitting_defaults::<Int32, Outer, _>(&nested, 1, &mut cache);
1643 let mut wire = Vec::new();
1644 write_message_field_omitting_defaults::<Int32, Outer, _>(&nested, 4, &mut cache, &mut wire);
1645 assert_eq!(wire.len() as u64, len, "size pass must match write pass");
1646 #[rustfmt::skip]
1647 assert_eq!(wire, [
1648 0x22, 0x02, 0x08, 0x01, 0x22, 0x08, 0x08, 0x02, 0x12, 0x04, 0x0a, 0x02, 0x08, 0x07, ]);
1651 }
1652
1653 #[test]
1654 fn open_enum_value_preserves_unknown() {
1655 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
1656 #[repr(i32)]
1657 enum E {
1658 #[default]
1659 A = 0,
1660 }
1661 impl Enumeration for E {
1662 fn from_i32(value: i32) -> Option<Self> {
1663 (value == 0).then_some(E::A)
1664 }
1665 fn to_i32(&self) -> i32 {
1666 *self as i32
1667 }
1668 fn proto_name(&self) -> &'static str {
1669 "A"
1670 }
1671 fn from_proto_name(name: &str) -> Option<Self> {
1672 (name == "A").then_some(E::A)
1673 }
1674 }
1675
1676 let mut map: Map<i32, EnumValue<E>> = Map::default();
1677 map.insert(1, EnumValue::Unknown(42));
1678 let wire = encode_field::<Int32, OpenEnum<E>>(&map, 2, 1);
1679 let back = decode_field::<Int32, OpenEnum<E>>(&wire);
1680 assert_eq!(back.get(&1), Some(&EnumValue::Unknown(42)));
1681
1682 let back = decode_field::<Int32, ClosedEnum<E>>(&wire);
1685 assert!(!back.contains_key(&1));
1686 }
1687
1688 #[test]
1689 fn closed_enum_unknown_preserves_whole_entry_when_requested() {
1690 #[derive(Clone, Copy, PartialEq, Eq, Hash, Debug, Default)]
1691 #[repr(i32)]
1692 enum E {
1693 #[default]
1694 A = 0,
1695 B = 1,
1696 }
1697 impl Enumeration for E {
1698 fn from_i32(value: i32) -> Option<Self> {
1699 match value {
1700 0 => Some(E::A),
1701 1 => Some(E::B),
1702 _ => None,
1703 }
1704 }
1705 fn to_i32(&self) -> i32 {
1706 *self as i32
1707 }
1708 fn proto_name(&self) -> &'static str {
1709 match self {
1710 E::A => "A",
1711 E::B => "B",
1712 }
1713 }
1714 }
1715
1716 let mut entry = Vec::new();
1717 Tag::new(1, WireType::Varint).encode(&mut entry);
1718 types::encode_int32(7, &mut entry);
1719 Tag::new(2, WireType::Varint).encode(&mut entry);
1720 types::encode_int32(99, &mut entry);
1721
1722 let mut wire = Vec::new();
1723 encode_varint(entry.len() as u64, &mut wire);
1724 wire.extend_from_slice(&entry);
1725
1726 let mut map: Map<i32, E> = Map::default();
1727 let mut unknown_fields = crate::UnknownFields::new();
1728 let limit = core::cell::Cell::new(crate::DEFAULT_UNKNOWN_FIELD_LIMIT);
1729 merge_entry_with_unknowns::<Int32, ClosedEnum<E>, _>(
1730 &mut map,
1731 &mut wire.as_slice(),
1732 DecodeContext::new(10, &limit),
1733 Some((5, &mut unknown_fields)),
1734 )
1735 .unwrap();
1736
1737 assert!(map.is_empty());
1738 let unknowns: Vec<_> = unknown_fields.iter().collect();
1739 assert_eq!(unknowns.len(), 1);
1740 assert_eq!(unknowns[0].number, 5);
1741 assert!(matches!(
1742 &unknowns[0].data,
1743 crate::UnknownFieldData::LengthDelimited(payload) if payload == &entry
1744 ));
1745
1746 let mut map: Map<i32, E> = Map::default();
1751 let mut unknown_fields = crate::UnknownFields::new();
1752 let (a, b) = wire.split_at(3);
1753 let mut chained = bytes::Buf::chain(a, b);
1754 merge_entry_with_unknowns::<Int32, ClosedEnum<E>, _>(
1755 &mut map,
1756 &mut chained,
1757 DecodeContext::new(10, &limit),
1758 Some((5, &mut unknown_fields)),
1759 )
1760 .unwrap();
1761 assert!(map.is_empty());
1762 let unknowns: Vec<_> = unknown_fields.iter().collect();
1763 assert_eq!(unknowns.len(), 1);
1764 assert!(matches!(
1765 &unknowns[0].data,
1766 crate::UnknownFieldData::LengthDelimited(payload) if payload == &entry
1767 ));
1768
1769 let mut entry = Vec::new();
1772 Tag::new(1, WireType::Varint).encode(&mut entry);
1773 types::encode_int32(7, &mut entry);
1774 Tag::new(2, WireType::Varint).encode(&mut entry);
1775 types::encode_int32(99, &mut entry);
1776 Tag::new(2, WireType::Varint).encode(&mut entry);
1777 types::encode_int32(1, &mut entry);
1778
1779 let mut wire = Vec::new();
1780 encode_varint(entry.len() as u64, &mut wire);
1781 wire.extend_from_slice(&entry);
1782
1783 let mut map: Map<i32, E> = Map::default();
1784 let mut unknown_fields = crate::UnknownFields::new();
1785 merge_entry_with_unknowns::<Int32, ClosedEnum<E>, _>(
1786 &mut map,
1787 &mut wire.as_slice(),
1788 DecodeContext::new(10, &limit),
1789 Some((5, &mut unknown_fields)),
1790 )
1791 .unwrap();
1792 assert_eq!(map.get(&7), Some(&E::B));
1793 assert_eq!(unknown_fields.iter().count(), 0);
1794 }
1795}