From 5a4ca1887fc3e84383406962ed01cd239057f79c Mon Sep 17 00:00:00 2001 From: Chip Senkbeil Date: Sun, 11 Jun 2023 15:37:45 -0500 Subject: [PATCH] Clean up header --- distant-net/src/common/packet/header.rs | 26 ++++++++++++++++++------- 1 file changed, 19 insertions(+), 7 deletions(-) diff --git a/distant-net/src/common/packet/header.rs b/distant-net/src/common/packet/header.rs index a876c0c..b6cb715 100644 --- a/distant-net/src/common/packet/header.rs +++ b/distant-net/src/common/packet/header.rs @@ -14,25 +14,25 @@ use std::ops::{Deref, DerefMut}; #[macro_export] macro_rules! header { ($($key:literal -> $value:expr),* $(,)?) => {{ - let mut _header = ::std::collections::HashMap::new(); + let mut _header = $crate::common::Header::default(); $( - _header.insert($key.to_string(), $crate::common::Value::from($value)); + _header.insert($key, $value); )* - $crate::common::Header::new(_header) + _header }}; } -/// Represents a packet header for a request or response +/// Represents a packet header comprised of arbitrary data tied to string keys. #[derive(Clone, Debug, Default, PartialEq, Eq, IntoIterator, Serialize, Deserialize)] #[serde(transparent)] pub struct Header(HashMap); impl Header { - /// Creates a new [`Header`] newtype wrapper. - pub fn new(map: HashMap) -> Self { - Self(map) + /// Creates an empty [`Header`] newtype wrapper. + pub fn new() -> Self { + Self::default() } /// Exists purely to support serde serialization checks. @@ -40,6 +40,18 @@ impl Header { pub(crate) fn is_empty(&self) -> bool { self.0.is_empty() } + + /// Inserts a key-value pair into the map. + /// + /// If the map did not have this key present, [`None`] is returned. + /// + /// If the map did have this key present, the value is updated, and the old value is returned. + /// The key is not updated, though; this matters for types that can be `==` without being + /// identical. See the [module-level documentation](std::collections#insert-and-complex-keys) + /// for more. + pub fn insert(&mut self, key: impl Into, value: impl Into) -> Option { + self.0.insert(key.into(), value.into()) + } } impl Deref for Header {