use std::fmt;
const ALLOWED_CHARS: &str =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_-()$!+'";
pub const EMPTY_SCOPES: &str = "_";
#[derive(Clone, Debug, PartialEq, Eq, Hash, Ord, PartialOrd)]
pub struct Scope {
pub name: String,
pub value: String,
}
impl Scope {
pub fn create<V>(name: &str, value: V) -> Result<Self, InvalidScopeError>
where
V: fmt::Display,
{
let value = value.to_string();
if name.is_empty() || value.is_empty() {
return Err(InvalidScopeError::Empty);
}
for c in name.chars().chain(value.chars()) {
if !ALLOWED_CHARS.contains(c) {
return Err(InvalidScopeError::InvalidChar(c));
}
}
Ok(Self {
name: name.to_owned(),
value,
})
}
pub fn name(&self) -> &str {
&self.name
}
pub fn value(&self) -> &str {
&self.value
}
}
#[derive(Clone, Debug, thiserror::Error)]
pub enum InvalidScopeError {
#[error("key and value must be non-empty")]
Empty,
#[error("invalid character '{0}'")]
InvalidChar(char),
#[error("unexpected error, please report a bug")]
Unreachable,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Scopes {
scopes: Vec<Scope>,
}
impl Scopes {
pub fn empty() -> Self {
Self { scopes: vec![] }
}
pub fn is_empty(&self) -> bool {
self.scopes.is_empty()
}
pub fn get(&self, key: &str) -> Option<&Scope> {
self.scopes.iter().find(|s| s.name() == key)
}
pub fn get_value(&self, key: &str) -> Option<&str> {
self.get(key).map(|s| s.value())
}
pub fn iter(&self) -> impl Iterator<Item = &Scope> {
self.into_iter()
}
pub fn push<V>(&mut self, key: &str, value: V) -> Result<(), InvalidScopeError>
where
V: fmt::Display,
{
self.scopes.push(Scope::create(key, value)?);
Ok(())
}
pub fn as_storage_path(&self) -> AsStoragePath<'_> {
AsStoragePath { inner: self }
}
pub fn as_api_path(&self) -> AsApiPath<'_> {
AsApiPath { inner: self }
}
}
impl<'a> IntoIterator for &'a Scopes {
type IntoIter = std::slice::Iter<'a, Scope>;
type Item = &'a Scope;
fn into_iter(self) -> Self::IntoIter {
self.scopes.iter()
}
}
impl FromIterator<Scope> for Scopes {
fn from_iter<T>(iter: T) -> Self
where
T: IntoIterator<Item = Scope>,
{
Self {
scopes: iter.into_iter().collect(),
}
}
}
#[derive(Debug)]
pub struct AsStoragePath<'a> {
inner: &'a Scopes,
}
impl fmt::Display for AsStoragePath<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
for (i, scope) in self.inner.iter().enumerate() {
if i > 0 {
write!(f, "/")?;
}
write!(f, "{}.{}", scope.name, scope.value)?;
}
Ok(())
}
}
#[derive(Debug)]
pub struct AsApiPath<'a> {
inner: &'a Scopes,
}
impl fmt::Display for AsApiPath<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some((first, rest)) = self.inner.scopes.split_first() {
write!(f, "{}={}", first.name, first.value)?;
for scope in rest {
write!(f, ";{}={}", scope.name, scope.value)?;
}
Ok(())
} else {
f.write_str(EMPTY_SCOPES)
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_allowed_characters() {
assert!(!ALLOWED_CHARS.contains('.'));
assert!(!ALLOWED_CHARS.contains('/'));
assert!(!ALLOWED_CHARS.contains('='));
assert!(!ALLOWED_CHARS.contains(';'));
}
#[test]
fn test_create_scope_empty() {
let err = Scope::create("", "value").unwrap_err();
assert!(matches!(err, InvalidScopeError::Empty));
let err = Scope::create("key", "").unwrap_err();
assert!(matches!(err, InvalidScopeError::Empty));
}
#[test]
fn test_create_scope_invalid_char() {
let err = Scope::create("key/", "value").unwrap_err();
assert!(matches!(err, InvalidScopeError::InvalidChar('/')));
let err = dbg!(Scope::create("key", "⚠️").unwrap_err());
assert!(matches!(err, InvalidScopeError::InvalidChar('⚠')));
}
#[test]
fn test_as_storage_path() {
let scopes = Scopes::from_iter([
Scope::create("org", "12345").unwrap(),
Scope::create("project", "1337").unwrap(),
]);
let storage_path = scopes.as_storage_path().to_string();
assert_eq!(storage_path, "org.12345/project.1337");
let empty_scopes = Scopes::empty();
let storage_path = empty_scopes.as_storage_path().to_string();
assert_eq!(storage_path, "");
}
#[test]
fn test_as_api_path() {
let scopes = Scopes::from_iter([
Scope::create("org", "12345").unwrap(),
Scope::create("project", "1337").unwrap(),
]);
let api_path = scopes.as_api_path().to_string();
assert_eq!(api_path, "org=12345;project=1337");
let empty_scopes = Scopes::empty();
let api_path = empty_scopes.as_api_path().to_string();
assert_eq!(api_path, EMPTY_SCOPES);
}
#[test]
fn test_push_and_get() {
let mut scopes = Scopes::empty();
scopes.push("org", "123").unwrap();
scopes.push("project", "456").unwrap();
assert_eq!(scopes.get("org").unwrap().value(), "123");
assert_eq!(scopes.get("project").unwrap().value(), "456");
assert!(scopes.get("missing").is_none());
}
#[test]
fn test_get_value() {
let mut scopes = Scopes::empty();
scopes.push("org", "123").unwrap();
assert_eq!(scopes.get_value("org"), Some("123"));
assert_eq!(scopes.get_value("missing"), None);
}
#[test]
fn test_push_validates() {
let mut scopes = Scopes::empty();
assert!(scopes.push("", "value").is_err());
assert!(scopes.push("key", "").is_err());
assert!(scopes.push("key/bad", "value").is_err());
assert!(scopes.is_empty());
}
#[test]
fn test_is_empty() {
let empty = Scopes::empty();
assert!(empty.is_empty());
let mut non_empty = Scopes::empty();
non_empty.push("org", "1").unwrap();
assert!(!non_empty.is_empty());
}
}