summaryrefslogtreecommitdiff
path: root/src/with_index.rs
diff options
context:
space:
mode:
authorAlex Auvolat <alex@adnab.me>2023-02-02 15:17:23 +0100
committerAlex Auvolat <alex@adnab.me>2023-02-02 15:17:23 +0100
commit552fc7e5a0d623114901d4d8e8e29bfffa47e09c (patch)
tree324903c281474e15aea8e9d86b600c6ecb3999f0 /src/with_index.rs
parent19220178311ca80374f6f5ff4069c0adcaab932d (diff)
downloaddf-consul-552fc7e5a0d623114901d4d8e8e29bfffa47e09c.tar.gz
df-consul-552fc7e5a0d623114901d4d8e8e29bfffa47e09c.zip
Split into several files and make more APIs
Diffstat (limited to 'src/with_index.rs')
-rw-r--r--src/with_index.rs75
1 files changed, 75 insertions, 0 deletions
diff --git a/src/with_index.rs b/src/with_index.rs
new file mode 100644
index 0000000..90e06be
--- /dev/null
+++ b/src/with_index.rs
@@ -0,0 +1,75 @@
+use std::fmt::{Debug, Display};
+
+use anyhow::{bail, Result};
+use reqwest::Response;
+
+pub struct WithIndex<T> {
+ value: T,
+ index: usize,
+}
+
+impl<T> WithIndex<T> {
+ pub fn index_from(resp: &Response) -> Result<WithIndexBuilder<T>> {
+ let index = match resp.headers().get("X-Consul-Index") {
+ Some(v) => v.to_str()?.parse::<usize>()?,
+ None => bail!("X-Consul-Index header not found"),
+ };
+ Ok(WithIndexBuilder {
+ index,
+ _phantom: Default::default(),
+ })
+ }
+
+ pub fn into_inner(self) -> T {
+ self.value
+ }
+
+ pub fn index(&self) -> usize {
+ self.index
+ }
+}
+
+impl<T> std::convert::AsRef<T> for WithIndex<T> {
+ fn as_ref(&self) -> &T {
+ &self.value
+ }
+}
+
+impl<T> std::borrow::Borrow<T> for WithIndex<T> {
+ fn borrow(&self) -> &T {
+ &self.value
+ }
+}
+
+impl<T> std::ops::Deref for WithIndex<T> {
+ type Target = T;
+ fn deref(&self) -> &T {
+ &self.value
+ }
+}
+
+impl<T: Debug> Debug for WithIndex<T> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ <T as Debug>::fmt(self, f)
+ }
+}
+
+impl<T: Display> Display for WithIndex<T> {
+ fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ <T as Display>::fmt(self, f)
+ }
+}
+
+pub struct WithIndexBuilder<T> {
+ _phantom: std::marker::PhantomData<T>,
+ index: usize,
+}
+
+impl<T> WithIndexBuilder<T> {
+ pub fn value(self, value: T) -> WithIndex<T> {
+ WithIndex {
+ value,
+ index: self.index,
+ }
+ }
+}