#![deny(missing_docs)]
use std::borrow::{Borrow, Cow};
mod dump;
pub mod iter;
mod load;
#[derive(thiserror::Error, Debug)]
#[non_exhaustive]
pub enum Error {
#[error("line {0} is malformed \"{1}\"")]
MalformedLine(usize, String),
#[error("line {0} is not proper utf-8 \"{1}\"")]
InvalidUtf8(usize, std::str::Utf8Error),
#[error("line {0} has invalid escape sequence \"{1}\"")]
InvalidEscape(usize, String),
}
#[derive(Debug, Default)]
pub struct Properties<'bytes> {
pairs: Vec<(Cow<'bytes, str>, Cow<'bytes, str>)>,
}
impl<'bytes> Properties<'bytes> {
pub fn load(content: &'bytes [u8]) -> Result<Self, Error> {
load::load(content)
}
pub fn len(&self) -> usize {
self.pairs.len()
}
pub fn is_empty(&self) -> bool {
self.pairs.is_empty()
}
pub fn get<'container>(&'container self, key: &str) -> Option<&'bytes str>
where
'container: 'bytes,
{
for (k, v) in &self.pairs {
if k == key {
return Some(v.borrow());
}
}
None
}
pub fn get_all<'container>(&'container self, key: &str) -> Vec<&'bytes str>
where
'container: 'bytes,
{
let mut res = Vec::new();
for (k, v) in &self.pairs {
if k == key {
res.push(v.borrow());
}
}
res
}
pub fn insert(&mut self, key: String, value: String) {
self.pairs.push((Cow::Owned(key), Cow::Owned(value)));
}
pub fn insert_str(&mut self, key: &'bytes str, value: &'bytes str) {
self.pairs.push((Cow::Borrowed(key), Cow::Borrowed(value)));
}
pub fn delete(&mut self, key: &str) {
for i in (0..self.pairs.len()).rev() {
if self.pairs[i].0 == key {
self.pairs.remove(i);
}
}
}
pub fn merge<'other>(&mut self, other: Properties<'other>)
where
'other: 'bytes,
{
for (k, v) in other.pairs {
self.pairs.push((k, v));
}
}
pub fn key_values<'a>(&'a self) -> iter::KVIter<'a, 'bytes> {
iter::KVIter(self, 0)
}
pub fn keys<'a>(&'a self) -> iter::KIter<'a, 'bytes> {
iter::KIter(self, 0)
}
}
impl<'bytes> std::ops::Index<&str> for Properties<'bytes> {
type Output = str;
fn index(&self, index: &str) -> &Self::Output {
for (k, v) in &self.pairs {
if k == index {
return v.borrow();
}
}
panic!("properties does not have {index}")
}
}