use serde::{Deserialize, Serialize};
use zeroize::Zeroizing;
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct LibrageResponse<T: Serialize> {
pub success: bool,
#[serde(skip_serializing_if = "Option::is_none")]
pub data: Option<T>,
#[serde(skip_serializing_if = "Option::is_none")]
pub error: Option<ErrorBody>,
}
impl<T: Serialize> LibrageResponse<T> {
pub fn ok(data: T) -> Self {
Self {
success: true,
data: Some(data),
error: None,
}
}
pub fn err(error: ErrorBody) -> Self {
Self {
success: false,
data: None,
error: Some(error),
}
}
pub fn to_json(&self) -> String {
serde_json::to_string(self).unwrap_or_else(|_| r#"{"success":false}"#.into())
}
}
impl<T: Serialize> From<Result<T, crate::handler::error::LibrageError>> for LibrageResponse<T> {
fn from(r: Result<T, crate::handler::error::LibrageError>) -> Self {
match r {
Ok(v) => Self::ok(v),
Err(e) => Self::err(e.into()),
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct ErrorBody {
pub code: String,
pub message: String,
}
impl ErrorBody {
pub fn new(code: impl Into<String>, message: impl Into<String>) -> Self {
Self {
code: code.into(),
message: message.into(),
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct KeyGenData {
pub public_key: String,
pub secret_key: Zeroizing<String>,
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct EncryptOutput {
pub ciphertext: Zeroizing<Vec<u8>>,
pub armored: bool,
}
impl EncryptOutput {
pub fn new(ciphertext: Vec<u8>, armored: bool) -> Self {
Self {
ciphertext: Zeroizing::new(ciphertext),
armored,
}
}
pub fn as_string(&self) -> String {
if self.armored {
String::from_utf8_lossy(&self.ciphertext).to_string()
} else {
hex::encode(&*self.ciphertext)
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct DecryptOutput {
pub plaintext: Zeroizing<Vec<u8>>,
}
impl DecryptOutput {
pub fn new(plaintext: Vec<u8>) -> Self {
Self {
plaintext: Zeroizing::new(plaintext),
}
}
pub fn as_string(&self) -> String {
String::from_utf8_lossy(&self.plaintext).to_string()
}
pub fn as_bytes(&self) -> &[u8] {
&self.plaintext
}
}