Skip to main content

thegraph_headers/
graph_attestable.rs

1//! An HTTP _typed header_ for the `graph-attestable` header.
2//!
3//! This HTTP header is used to indicate whether a response is _attestable_ or not.
4//!
5//! # Using the `headers::HeaderMapExt` extension trait
6//!
7//! ```rust
8//! use headers::HeaderMapExt as _;
9//! use thegraph_headers::graph_attestable::{GraphAttestable, HEADER_NAME};
10//!
11//! let mut header_map = http::HeaderMap::new();
12//! # let value = true;
13//!
14//! // Insert a `graph-attestable` HTTP header
15//! header_map.typed_insert(GraphAttestable(value));
16//!
17//! // Get the `graph-attestable` HTTP header by name
18//! let header_by_name = header_map.get(HEADER_NAME);
19//! assert!(header_by_name.is_some());
20//!
21//! // Get the `graph-attestable` HTTP header by type
22//! let header_typed = header_map.typed_get::<GraphAttestable>();
23//! assert!(matches!(header_typed, Some(GraphAttestable(..))));
24//! ```
25
26use headers::{Error as HeaderError, Header, HeaderName, HeaderValue};
27
28/// The HTTP header name for the `graph-attestable` header.
29pub const HEADER_NAME: &str = "graph-attestable";
30
31/// An HTTP _typed header_ for the `graph-attestable` header.
32///
33/// This HTTP header is used to indicate whether a response is attestable or not.
34///
35/// The `graph-attestable` header can contain a boolean value, either `true` or `false`.
36#[derive(Debug, Clone)]
37pub struct GraphAttestable(pub bool);
38
39impl Header for GraphAttestable {
40    fn name() -> &'static HeaderName {
41        static HTTP_HEADER_NAME: HeaderName = HeaderName::from_static(HEADER_NAME);
42        &HTTP_HEADER_NAME
43    }
44
45    fn decode<'i, I>(values: &mut I) -> Result<Self, HeaderError>
46    where
47        Self: Sized,
48        I: Iterator<Item = &'i HeaderValue>,
49    {
50        let value = values.next().ok_or_else(HeaderError::invalid)?;
51        if value == "true" {
52            Ok(Self(true))
53        } else if value == "false" {
54            Ok(Self(false))
55        } else {
56            Err(HeaderError::invalid())
57        }
58    }
59
60    fn encode<E: Extend<HeaderValue>>(&self, values: &mut E) {
61        let value = if self.0 {
62            HeaderValue::from_static("true")
63        } else {
64            HeaderValue::from_static("false")
65        };
66        values.extend(std::iter::once(value));
67    }
68}