conjure_http/safe_params.rs
1// Copyright 2019 Palantir Technologies, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Safe-loggable request parameters.
16
17use conjure_object::Any;
18use serde::Serialize;
19use std::collections::{hash_map, HashMap};
20
21/// A data structure storing safe-loggable parameters of a request.
22///
23/// This can be included in the response extensions of a request to be included in request logs.
24#[derive(Clone, Debug, Default, PartialEq, Eq)]
25pub struct SafeParams(HashMap<&'static str, Any>);
26
27impl SafeParams {
28 /// Creates a new, empty `SafeParams`.
29 #[inline]
30 pub fn new() -> Self {
31 SafeParams::default()
32 }
33
34 /// Inserts a parameter.
35 ///
36 /// # Panics
37 ///
38 /// Panics if the value fails to serialize into an [`Any`].
39 pub fn insert<T>(&mut self, name: &'static str, value: &T)
40 where
41 T: Serialize,
42 {
43 self.0.insert(
44 name,
45 Any::new(value).expect("safe param failed to serialize"),
46 );
47 }
48
49 /// Returns an iterator over the parameters.
50 #[inline]
51 pub fn iter(&self) -> Iter<'_> {
52 Iter(self.0.iter())
53 }
54}
55
56impl<'a> IntoIterator for &'a SafeParams {
57 type IntoIter = Iter<'a>;
58 type Item = (&'a str, &'a Any);
59
60 #[inline]
61 fn into_iter(self) -> Self::IntoIter {
62 self.iter()
63 }
64}
65
66/// An iterator over safe parameters.
67pub struct Iter<'a>(hash_map::Iter<'a, &'static str, Any>);
68
69impl<'a> Iterator for Iter<'a> {
70 type Item = (&'a str, &'a Any);
71
72 #[inline]
73 fn next(&mut self) -> Option<Self::Item> {
74 self.0.next().map(|(k, v)| (*k, v))
75 }
76
77 #[inline]
78 fn size_hint(&self) -> (usize, Option<usize>) {
79 self.0.size_hint()
80 }
81}
82
83impl ExactSizeIterator for Iter<'_> {
84 #[inline]
85 fn len(&self) -> usize {
86 self.0.len()
87 }
88}