use std::borrow::Cow;
use super::{Cookie, CookieBuilder};
pub(crate) const HOST_PREFIX: &str = "__Host-";
pub(crate) const SECURE_PREFIX: &str = "__Secure-";
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum CookiePrefix {
Host,
Secure,
}
impl CookiePrefix {
pub(crate) const fn as_str(self) -> &'static str {
match self {
CookiePrefix::Host => HOST_PREFIX,
CookiePrefix::Secure => SECURE_PREFIX,
}
}
}
pub(crate) fn split_prefix(name: Cow<'_, str>) -> (Option<CookiePrefix>, Cow<'_, str>) {
let (prefix, len) = if name.starts_with(HOST_PREFIX) {
(CookiePrefix::Host, HOST_PREFIX.len())
} else if name.starts_with(SECURE_PREFIX) {
(CookiePrefix::Secure, SECURE_PREFIX.len())
} else {
return (None, name);
};
let stripped = match name {
Cow::Borrowed(borrowed) => Cow::Borrowed(&borrowed[len..]),
Cow::Owned(mut owned) => {
owned.drain(..len);
Cow::Owned(owned)
}
};
(Some(prefix), stripped)
}
impl Cookie {
pub fn host<N, V>(name: N, value: V) -> CookieBuilder
where
N: Into<Cow<'static, str>>,
V: Into<Cow<'static, str>>,
{
CookieBuilder::new(name, value)
.secure()
.path("/")
.with_prefix(CookiePrefix::Host)
}
pub fn secure<N, V>(name: N, value: V) -> CookieBuilder
where
N: Into<Cow<'static, str>>,
V: Into<Cow<'static, str>>,
{
CookieBuilder::new(name, value)
.secure()
.with_prefix(CookiePrefix::Secure)
}
}