use ahash::AHasher;
use std::borrow::Cow;
use std::hash::{Hash, Hasher};
use super::error::{Error, Result};
use super::format::{self, Format};
use super::Id;
#[derive(Clone, Debug)]
pub struct Builder<'a> {
format: format::Builder<'a, 7>,
}
impl Id {
#[inline]
#[must_use]
pub fn builder<'a>() -> Builder<'a> {
Builder::default()
}
#[inline]
#[must_use]
pub fn to_builder(&self) -> Builder<'_> {
Builder {
format: self.format.to_builder().with(0, "zri"),
}
}
}
impl<'a> Builder<'a> {
#[inline]
#[must_use]
pub fn provider<S>(mut self, value: S) -> Self
where
S: Into<Cow<'a, str>>,
{
self.format.set(1, value);
self
}
#[inline]
#[must_use]
pub fn resource<S>(mut self, value: S) -> Self
where
S: Into<Cow<'a, str>>,
{
self.format.set(2, value);
self
}
#[inline]
#[must_use]
pub fn variant<S>(mut self, value: S) -> Self
where
S: Into<Cow<'a, str>>,
{
self.format.set(3, value);
self
}
#[inline]
#[must_use]
pub fn context<S>(mut self, value: S) -> Self
where
S: Into<Cow<'a, str>>,
{
self.format.set(4, value);
self
}
#[inline]
#[must_use]
pub fn location<S>(mut self, value: S) -> Self
where
S: Into<Cow<'a, str>>,
{
self.format.set(5, value);
self
}
#[inline]
#[must_use]
pub fn fragment<S>(mut self, value: S) -> Self
where
S: Into<Cow<'a, str>>,
{
self.format.set(6, value);
self
}
pub fn build(self) -> Result<Id> {
let format = self.format.build()?;
if format.get(1).is_empty() {
Err(Error::Component("provider"))?;
}
if format.get(4).is_empty() {
Err(Error::Component("context"))?;
}
if format.get(5).is_empty() {
Err(Error::Component("location"))?;
}
let hash = {
let mut hasher = AHasher::default();
format.hash(&mut hasher);
hasher.finish()
};
Ok(Id { format, hash })
}
}
impl Default for Builder<'_> {
#[inline]
fn default() -> Self {
Self {
format: Format::builder().with(0, "zri"),
}
}
}