#![allow(clippy::all)]
use std::marker::PhantomData;
use bytes::BytesMut;
use http::HeaderValue;
#[derive(Clone, PartialEq, Eq, Hash)]
pub(crate) struct FlatCsv<Sep = Comma> {
pub(crate) value: HeaderValue,
_marker: PhantomData<Sep>,
}
pub(crate) trait Separator {
const BYTE: u8;
const CHAR: char;
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) enum Comma {}
impl Separator for Comma {
const BYTE: u8 = b',';
const CHAR: char = ',';
}
#[allow(unused)]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub(crate) enum SemiColon {}
impl Separator for SemiColon {
const BYTE: u8 = b';';
const CHAR: char = ';';
}
impl<Sep: Separator> FlatCsv<Sep> {
pub(crate) fn iter(&self) -> impl Iterator<Item = &str> {
self.value.to_str().ok().into_iter().flat_map(|value_str| {
let mut in_quotes = false;
value_str
.split(move |c| {
if in_quotes {
if c == '"' {
in_quotes = false;
}
false } else {
if c == Sep::CHAR {
true } else {
if c == '"' {
in_quotes = true;
}
false }
}
})
.map(|item| item.trim())
})
}
}
impl<Sep> From<HeaderValue> for FlatCsv<Sep> {
fn from(value: HeaderValue) -> Self {
FlatCsv {
value,
_marker: PhantomData,
}
}
}
impl<'a, Sep: Separator> FromIterator<&'a HeaderValue> for FlatCsv<Sep> {
fn from_iter<I>(iter: I) -> Self
where
I: IntoIterator<Item = &'a HeaderValue>,
{
let mut values = iter.into_iter();
if let (1, Some(1)) = values.size_hint() {
return values.next().expect("size_hint claimed 1 item").clone().into();
}
let mut buf = values
.next()
.cloned()
.map(|val| BytesMut::from(val.as_bytes()))
.unwrap_or_else(|| BytesMut::new());
for val in values {
buf.extend_from_slice(&[Sep::BYTE, b' ']);
buf.extend_from_slice(val.as_bytes());
}
let val = HeaderValue::from_maybe_shared(buf.freeze()).expect("comma separated HeaderValues are valid");
val.into()
}
}