use std::fmt;
use serde::ser::{Serialize, Serializer};
use crate::util::StrJoin;
#[derive(Debug)]
pub struct OptionVal(pub String);
impl<'a> From<&'a str> for OptionVal {
fn from(from: &'a str) -> OptionVal {
OptionVal(from.to_owned())
}
}
from_exp!(String, OptionVal, from, OptionVal(from));
from_exp!(i32, OptionVal, from, OptionVal(from.to_string()));
from_exp!(i64, OptionVal, from, OptionVal(from.to_string()));
from_exp!(u32, OptionVal, from, OptionVal(from.to_string()));
from_exp!(u64, OptionVal, from, OptionVal(from.to_string()));
from_exp!(bool, OptionVal, from, OptionVal(from.to_string()));
#[derive(Default, Debug)]
pub struct Options<'a>(pub Vec<(&'a str, OptionVal)>);
impl<'a> Options<'a> {
pub fn new() -> Options<'a> {
Options(Vec::new())
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn push<O: Into<OptionVal>>(&mut self, key: &'a str, val: O) {
self.0.push((key, val.into()));
}
}
impl<'a> fmt::Display for Options<'a> {
fn fmt(&self, formatter: &mut fmt::Formatter) -> Result<(), fmt::Error> {
if !self.is_empty() {
formatter.write_str("?")?;
formatter.write_str(
&self
.0
.iter()
.map(|&(ref k, ref v)| format!("{}={}", k, v.0))
.join("&"),
)?;
}
Ok(())
}
}
macro_rules! add_option {
($n:ident, $e:expr) => (
pub fn $n<T: Into<OptionVal>>(&'a mut self, val: T) -> &'a mut Self {
self.options.push($e, val);
self
}
)
}
#[derive(Debug)]
pub enum VersionType {
Internal,
External,
ExternalGt,
ExternalGte,
Force,
}
impl Serialize for VersionType {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
self.to_string().serialize(serializer)
}
}
impl ToString for VersionType {
fn to_string(&self) -> String {
match *self {
VersionType::Internal => "internal",
VersionType::External => "external",
VersionType::ExternalGt => "external_gt",
VersionType::ExternalGte => "external_gte",
VersionType::Force => "force",
}
.to_owned()
}
}
from_exp!(VersionType, OptionVal, from, OptionVal(from.to_string()));
#[derive(Debug)]
pub enum Consistency {
One,
Quorum,
All,
}
impl From<Consistency> for OptionVal {
fn from(from: Consistency) -> OptionVal {
OptionVal(
match from {
Consistency::One => "one",
Consistency::Quorum => "quorum",
Consistency::All => "all",
}
.to_owned(),
)
}
}
#[derive(Debug)]
pub enum DefaultOperator {
And,
Or,
}
impl From<DefaultOperator> for OptionVal {
fn from(from: DefaultOperator) -> OptionVal {
OptionVal(
match from {
DefaultOperator::And => "and",
DefaultOperator::Or => "or",
}
.to_owned(),
)
}
}