use zeroize::Zeroize;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum ItemKind {
Note,
Credential,
File,
}
impl ItemKind {
pub fn as_str(self) -> &'static str {
match self {
Self::Note => "note",
Self::Credential => "credential",
Self::File => "file",
}
}
pub fn parse(value: &str) -> Option<Self> {
match value {
"note" => Some(Self::Note),
"credential" => Some(Self::Credential),
"file" => Some(Self::File),
_ => None,
}
}
}
impl std::fmt::Display for ItemKind {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Payload {
Note {
text: String,
},
Credential(Credential),
File {
filename: String,
bytes: Vec<u8>,
},
}
impl Payload {
pub fn kind(&self) -> ItemKind {
match self {
Self::Note { .. } => ItemKind::Note,
Self::Credential(_) => ItemKind::Credential,
Self::File { .. } => ItemKind::File,
}
}
}
impl Zeroize for Payload {
fn zeroize(&mut self) {
match self {
Self::Note { text } => text.zeroize(),
Self::Credential(credential) => credential.zeroize(),
Self::File { filename, bytes } => {
filename.zeroize();
bytes.zeroize();
}
}
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Zeroize)]
pub struct Credential {
pub login: String,
pub password: String,
pub url: Option<String>,
pub totp: Option<String>,
pub notes: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ItemSummary {
pub id: i64,
pub uuid: String,
pub title: String,
pub kind: ItemKind,
pub tags: Vec<String>,
pub created_at: i64,
pub updated_at: i64,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Item {
pub summary: ItemSummary,
pub payload: Payload,
}
#[derive(Debug, Clone)]
pub struct NewItem {
pub title: String,
pub payload: Payload,
pub tags: Vec<String>,
}
impl NewItem {
pub fn new(title: impl Into<String>, payload: Payload) -> Self {
Self {
title: title.into(),
payload,
tags: Vec::new(),
}
}
pub fn with_tags<I, S>(mut self, tags: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.tags = tags.into_iter().map(Into::into).collect();
self
}
}
#[derive(Debug, Clone, Default)]
pub struct Query {
pub text: Option<String>,
pub kind: Option<ItemKind>,
pub tags: Vec<String>,
}
impl Query {
pub fn all() -> Self {
Self::default()
}
pub fn text(mut self, text: impl Into<String>) -> Self {
self.text = Some(text.into());
self
}
pub fn kind(mut self, kind: ItemKind) -> Self {
self.kind = Some(kind);
self
}
pub fn tags<I, S>(mut self, tags: I) -> Self
where
I: IntoIterator<Item = S>,
S: Into<String>,
{
self.tags = tags.into_iter().map(Into::into).collect();
self
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn kind_names_round_trip() {
for kind in [ItemKind::Note, ItemKind::Credential, ItemKind::File] {
assert_eq!(ItemKind::parse(kind.as_str()), Some(kind));
}
assert_eq!(ItemKind::parse("passport"), None);
}
}