openstack/common/
protocol.rs

1// Copyright 2018 Dmitry Tantsur <divius.inside@gmail.com>
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//! Common protocol bits.
16
17#![allow(dead_code)] // various things are unused with --no-default-features
18#![allow(missing_docs)]
19
20use std::collections::HashMap;
21
22use reqwest::header::{HeaderMap, HeaderName};
23use reqwest::Url;
24use serde::de::Error as DeserError;
25use serde::{Deserialize, Deserializer};
26
27use super::super::{Error, ErrorKind};
28
29#[derive(Clone, Debug, Deserialize)]
30pub struct KeyValue {
31    pub key: String,
32    pub value: String,
33}
34
35/// Deserialize a URL.
36pub fn deser_optional_url<'de, D>(des: D) -> std::result::Result<Option<Url>, D::Error>
37where
38    D: Deserializer<'de>,
39{
40    let value: Option<String> = Deserialize::deserialize(des)?;
41    match value {
42        Some(s) => Url::parse(&s).map_err(DeserError::custom).map(Some),
43        None => Ok(None),
44    }
45}
46
47/// Deserialize a key-value mapping.
48pub fn deser_key_value<'de, D>(des: D) -> std::result::Result<HashMap<String, String>, D::Error>
49where
50    D: Deserializer<'de>,
51{
52    let value: Vec<KeyValue> = Deserialize::deserialize(des)?;
53    Ok(value.into_iter().map(|kv| (kv.key, kv.value)).collect())
54}
55
56/// Get a header as a string.
57#[inline]
58pub fn get_header<'m>(headers: &'m HeaderMap, key: &HeaderName) -> Result<Option<&'m str>, Error> {
59    Ok(if let Some(hdr) = headers.get(key) {
60        Some(hdr.to_str().map_err(|e| {
61            Error::new(
62                ErrorKind::InvalidResponse,
63                format!("{} header is invalid string: {}", key.as_str(), e),
64            )
65        })?)
66    } else {
67        None
68    })
69}
70
71/// Get a header as a string, failing if it's not present.
72#[inline]
73pub fn get_required_header<'m>(headers: &'m HeaderMap, key: &HeaderName) -> Result<&'m str, Error> {
74    get_header(headers, key)?.ok_or_else(|| {
75        Error::new(
76            ErrorKind::InvalidResponse,
77            format!("Missing {} header", key.as_str()),
78        )
79    })
80}
81
82/// Comma-separated list.
83#[derive(Debug, Clone)]
84pub struct CommaSeparated<T>(pub Vec<T>);
85
86impl<T> std::ops::Deref for CommaSeparated<T> {
87    type Target = Vec<T>;
88
89    fn deref(&self) -> &Vec<T> {
90        &self.0
91    }
92}
93
94impl<T> std::ops::DerefMut for CommaSeparated<T> {
95    fn deref_mut(&mut self) -> &mut Vec<T> {
96        &mut self.0
97    }
98}
99
100impl<T: ToString> std::fmt::Display for CommaSeparated<T> {
101    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
102        let strings = self
103            .0
104            .iter()
105            .map(ToString::to_string)
106            .collect::<Vec<_>>()
107            .join(",");
108        f.write_str(&strings)
109    }
110}