use discard::DiscardOnDrop;
use crate::buffer::SaslString;
use std::iter::{FromIterator, IntoIterator};
pub struct Mechanisms {
inner: Alloc,
}
enum Alloc {
Rust(String),
Gsasl(DiscardOnDrop<SaslString>),
}
impl Mechanisms {
pub fn from_sasl(inner: DiscardOnDrop<SaslString>) -> Self {
Self {
inner: Alloc::Gsasl(inner),
}
}
pub fn iter(&self) -> impl Iterator<Item = &str> {
let s = match self.inner {
Alloc::Gsasl(ref s) => s.to_str().unwrap(),
Alloc::Rust(ref s) => s,
};
s.split_ascii_whitespace()
}
pub fn as_slice(&self) -> &[u8] {
match self.inner {
Alloc::Gsasl(ref s) => s.to_bytes(),
Alloc::Rust(ref s) => s.as_bytes(),
}
}
pub fn as_raw_ptr(&self) -> *const libc::c_char {
match self.inner {
Alloc::Gsasl(ref s) => s.as_raw_ptr() as *const libc::c_char,
Alloc::Rust(ref s) => s.as_ptr() as *const libc::c_char,
}
}
}
impl<B: AsRef<str>> FromIterator<B> for Mechanisms {
fn from_iter<I: IntoIterator<Item = B>>(iter: I) -> Self {
let mut buf = String::new();
for m in iter {
buf.push_str(m.as_ref());
buf.push(' ');
}
buf.pop();
Self {
inner: Alloc::Rust(buf),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn from_iter_test() {
let mechs = ["PLAIN", "SCRAM-SHA1", "GSSAPI"];
let m: Mechanisms = mechs.iter().collect();
assert_eq!(m.as_slice(), b"PLAIN SCRAM-SHA1 GSSAPI");
}
}