#![cfg_attr(not(feature = "std"), no_std)]
#![cfg_attr(nightly, feature(doc_cfg))]
#![doc(html_root_url = "https://docs.rs/cookie/0.15")]
#![deny(missing_docs)]
#[cfg(test)]
#[macro_use]
extern crate std;
extern crate alloc;
mod builder;
mod delta;
mod draft;
mod jar;
mod parse;
use alloc::borrow::Cow;
use alloc::str::FromStr;
use alloc::string::ToString;
use core::fmt::Write;
use core::time::Duration;
pub use crate::builder::CookieBuilder;
pub use crate::draft::*;
pub use crate::jar::{CookieJar, Delta, Iter};
use crate::parse::parse_cookie;
pub use crate::parse::ParseError;
#[cfg(not(feature = "std"))]
use core::fmt::Debug;
#[cfg(feature = "std")]
use std::error::Error as StdError;
#[cfg(not(feature = "std"))]
trait StdError: Debug + core::fmt::Display {
fn source(&self) -> Option<&(dyn StdError + 'static)> {
None
}
}
#[derive(Debug, Clone)]
enum CookieStr<'c> {
Indexed(usize, usize),
Concrete(Cow<'c, str>),
}
impl<'c> CookieStr<'c> {
fn to_str<'s>(&'s self, string: Option<&'s Cow<str>>) -> &'s str {
match *self {
CookieStr::Indexed(i, j) => {
let s = string.expect(
"`Some` base string must exist when \
converting indexed str to str! (This is a module invariant.)",
);
&s[i..j]
}
CookieStr::Concrete(ref cstr) => &*cstr,
}
}
#[allow(clippy::ptr_arg)]
fn to_raw_str<'s, 'b: 's>(&'s self, string: &'s Cow<'b, str>) -> Option<&'b str> {
match *self {
CookieStr::Indexed(i, j) => match *string {
Cow::Borrowed(s) => Some(&s[i..j]),
Cow::Owned(_) => None,
},
CookieStr::Concrete(_) => None,
}
}
fn into_owned(self) -> CookieStr<'static> {
use crate::CookieStr::*;
match self {
Indexed(a, b) => Indexed(a, b),
Concrete(Cow::Owned(c)) => Concrete(Cow::Owned(c)),
Concrete(Cow::Borrowed(c)) => Concrete(Cow::Owned(c.into())),
}
}
}
#[derive(Debug, Clone)]
pub struct Cookie<'c> {
cookie_string: Option<Cow<'c, str>>,
name: CookieStr<'c>,
value: CookieStr<'c>,
max_age: Option<Duration>,
domain: Option<CookieStr<'c>>,
path: Option<CookieStr<'c>>,
secure: Option<bool>,
http_only: Option<bool>,
same_site: Option<SameSite>,
}
impl<'c> Cookie<'c> {
pub fn new<N, V>(name: N, value: V) -> Self
where
N: Into<Cow<'c, str>>,
V: Into<Cow<'c, str>>,
{
Cookie {
cookie_string: None,
name: CookieStr::Concrete(name.into()),
value: CookieStr::Concrete(value.into()),
max_age: None,
domain: None,
path: None,
secure: None,
http_only: None,
same_site: None,
}
}
pub fn named<N>(name: N) -> Cookie<'c>
where
N: Into<Cow<'c, str>>,
{
Cookie::new(name, "")
}
pub fn build<N, V>(name: N, value: V) -> CookieBuilder<'c>
where
N: Into<Cow<'c, str>>,
V: Into<Cow<'c, str>>,
{
CookieBuilder::new(name, value)
}
pub fn parse<S>(s: S) -> Result<Cookie<'c>, ParseError>
where
S: Into<Cow<'c, str>>,
{
parse_cookie(s)
}
pub fn into_owned(self) -> Cookie<'static> {
Cookie {
cookie_string: self.cookie_string.map(|s| s.into_owned().into()),
name: self.name.into_owned(),
value: self.value.into_owned(),
max_age: self.max_age,
domain: self.domain.map(|s| s.into_owned()),
path: self.path.map(|s| s.into_owned()),
secure: self.secure,
http_only: self.http_only,
same_site: self.same_site,
}
}
#[inline]
pub fn name(&self) -> &str {
self.name.to_str(self.cookie_string.as_ref())
}
#[inline]
pub fn value(&self) -> &str {
self.value.to_str(self.cookie_string.as_ref())
}
#[inline]
pub fn name_value(&self) -> (&str, &str) {
(self.name(), self.value())
}
#[inline]
pub fn http_only(&self) -> Option<bool> {
self.http_only
}
#[inline]
pub fn secure(&self) -> Option<bool> {
self.secure
}
#[inline]
pub fn same_site(&self) -> Option<SameSite> {
self.same_site
}
#[inline]
pub fn max_age(&self) -> Option<Duration> {
self.max_age
}
#[inline]
pub fn path(&self) -> Option<&str> {
match self.path {
Some(ref c) => Some(c.to_str(self.cookie_string.as_ref())),
None => None,
}
}
#[inline]
pub fn domain(&self) -> Option<&str> {
match self.domain {
Some(ref c) => Some(c.to_str(self.cookie_string.as_ref())),
None => None,
}
}
pub fn set_name<N: Into<Cow<'c, str>>>(&mut self, name: N) {
self.name = CookieStr::Concrete(name.into())
}
pub fn set_value<V: Into<Cow<'c, str>>>(&mut self, value: V) {
self.value = CookieStr::Concrete(value.into())
}
#[inline]
pub fn set_http_only<T: Into<Option<bool>>>(&mut self, value: T) {
self.http_only = value.into();
}
#[inline]
pub fn set_secure<T: Into<Option<bool>>>(&mut self, value: T) {
self.secure = value.into();
}
#[inline]
pub fn set_same_site<T: Into<Option<SameSite>>>(&mut self, value: T) {
self.same_site = value.into();
}
#[inline]
pub fn set_max_age<D: Into<Option<Duration>>>(&mut self, value: D) {
self.max_age = value.into();
}
pub fn set_path<P: Into<Cow<'c, str>>>(&mut self, path: P) {
self.path = Some(CookieStr::Concrete(path.into()));
}
pub fn unset_path(&mut self) {
self.path = None;
}
pub fn set_domain<D: Into<Cow<'c, str>>>(&mut self, domain: D) {
self.domain = Some(CookieStr::Concrete(domain.into()));
}
pub fn unset_domain(&mut self) {
self.domain = None;
}
pub fn make_permanent(&mut self) {
let twenty_years = Duration::from_secs(86400 * 365 * 20);
self.set_max_age(twenty_years);
}
pub fn make_removal(&mut self) {
self.set_value("");
self.set_max_age(Duration::ZERO);
}
fn fmt_parameters(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
if let Some(true) = self.http_only() {
f.write_str("; HttpOnly")?;
}
if let Some(same_site) = self.same_site() {
f.write_str("; SameSite=")?;
f.write_str(&same_site.to_string())?;
if same_site.is_none() && self.secure().is_none() {
f.write_str("; Secure")?;
}
}
if let Some(true) = self.secure() {
f.write_str("; Secure")?;
}
if let Some(path) = self.path() {
f.write_str("; Path=")?;
f.write_str(path)?;
}
if let Some(domain) = self.domain() {
f.write_str("; Domain=")?;
f.write_str(domain)?;
}
if let Some(max_age) = self.max_age() {
f.write_str("; Max-Age=")?;
f.write_str(&max_age.as_secs().to_string())?;
}
Ok(())
}
#[inline]
pub fn name_raw(&self) -> Option<&'c str> {
self.cookie_string
.as_ref()
.and_then(|s| self.name.to_raw_str(s))
}
#[inline]
pub fn value_raw(&self) -> Option<&'c str> {
self.cookie_string
.as_ref()
.and_then(|s| self.value.to_raw_str(s))
}
#[inline]
pub fn path_raw(&self) -> Option<&'c str> {
match (self.path.as_ref(), self.cookie_string.as_ref()) {
(Some(path), Some(string)) => path.to_raw_str(string),
_ => None,
}
}
#[inline]
pub fn domain_raw(&self) -> Option<&'c str> {
match (self.domain.as_ref(), self.cookie_string.as_ref()) {
(Some(domain), Some(string)) => domain.to_raw_str(string),
_ => None,
}
}
}
impl<'c> core::fmt::Display for Cookie<'c> {
fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result {
f.write_str(self.name())?;
f.write_char('=')?;
f.write_str(self.value())?;
self.fmt_parameters(f)
}
}
impl FromStr for Cookie<'static> {
type Err = ParseError;
fn from_str(s: &str) -> Result<Cookie<'static>, ParseError> {
Cookie::parse(s).map(|c| c.into_owned())
}
}
impl<'a, 'b> PartialEq<Cookie<'b>> for Cookie<'a> {
fn eq(&self, other: &Cookie<'b>) -> bool {
let so_far_so_good = self.name() == other.name()
&& self.value() == other.value()
&& self.http_only() == other.http_only()
&& self.secure() == other.secure()
&& self.max_age() == other.max_age();
if !so_far_so_good {
return false;
}
match (self.path(), other.path()) {
(Some(a), Some(b)) if a.eq_ignore_ascii_case(b) => {}
(None, None) => {}
_ => return false,
};
match (self.domain(), other.domain()) {
(Some(a), Some(b)) if a.eq_ignore_ascii_case(b) => {}
(None, None) => {}
_ => return false,
};
true
}
}
#[cfg(test)]
mod tests {
use std::time::Duration;
use alloc::{borrow::ToOwned, string::ToString};
use crate::{Cookie, SameSite};
#[test]
fn format() {
let cookie = Cookie::new("foo", "bar");
assert_eq!(&cookie.to_string(), "foo=bar");
let cookie = Cookie::build("foo", "bar").http_only(true).finish();
assert_eq!(&cookie.to_string(), "foo=bar; HttpOnly");
let cookie = Cookie::build("foo", "bar")
.max_age(Duration::from_secs(10))
.finish();
assert_eq!(&cookie.to_string(), "foo=bar; Max-Age=10");
let cookie = Cookie::build("foo", "bar").secure(true).finish();
assert_eq!(&cookie.to_string(), "foo=bar; Secure");
let cookie = Cookie::build("foo", "bar").path("/").finish();
assert_eq!(&cookie.to_string(), "foo=bar; Path=/");
let cookie = Cookie::build("foo", "bar")
.domain("www.rust-lang.org")
.finish();
assert_eq!(&cookie.to_string(), "foo=bar; Domain=www.rust-lang.org");
let cookie = Cookie::build("foo", "bar")
.same_site(SameSite::Strict)
.finish();
assert_eq!(&cookie.to_string(), "foo=bar; SameSite=Strict");
let cookie = Cookie::build("foo", "bar")
.same_site(SameSite::Lax)
.finish();
assert_eq!(&cookie.to_string(), "foo=bar; SameSite=Lax");
let mut cookie = Cookie::build("foo", "bar")
.same_site(SameSite::None)
.finish();
assert_eq!(&cookie.to_string(), "foo=bar; SameSite=None; Secure");
cookie.set_same_site(None);
assert_eq!(&cookie.to_string(), "foo=bar");
let mut cookie = Cookie::build("foo", "bar")
.same_site(SameSite::None)
.secure(false)
.finish();
assert_eq!(&cookie.to_string(), "foo=bar; SameSite=None");
cookie.set_secure(true);
assert_eq!(&cookie.to_string(), "foo=bar; SameSite=None; Secure");
}
#[test]
fn cookie_string_long_lifetimes() {
let cookie_string = "bar=baz; Path=/subdir; HttpOnly; Domain=crates.io".to_owned();
let (name, value, path, domain) = {
let c = Cookie::parse(cookie_string.as_str()).unwrap();
(c.name_raw(), c.value_raw(), c.path_raw(), c.domain_raw())
};
assert_eq!(name, Some("bar"));
assert_eq!(value, Some("baz"));
assert_eq!(path, Some("/subdir"));
assert_eq!(domain, Some("crates.io"));
}
#[test]
fn owned_cookie_string() {
let cookie_string = "bar=baz; Path=/subdir; HttpOnly; Domain=crates.io".to_owned();
let (name, value, path, domain) = {
let c = Cookie::parse(cookie_string).unwrap();
(c.name_raw(), c.value_raw(), c.path_raw(), c.domain_raw())
};
assert_eq!(name, None);
assert_eq!(value, None);
assert_eq!(path, None);
assert_eq!(domain, None);
}
#[test]
fn owned_cookie_struct() {
let cookie_string = "bar=baz; Path=/subdir; HttpOnly; Domain=crates.io";
let (name, value, path, domain) = {
let c = Cookie::parse(cookie_string).unwrap().into_owned();
(c.name_raw(), c.value_raw(), c.path_raw(), c.domain_raw())
};
assert_eq!(name, None);
assert_eq!(value, None);
assert_eq!(path, None);
assert_eq!(domain, None);
}
}