use crate::guard::Guard;
pub trait Guarded: Send + Sync {
fn guard(&self) -> &Guard;
}
impl Guarded for Guard {
fn guard(&self) -> &Guard {
self
}
}
impl Guarded for std::sync::Arc<Guard> {
fn guard(&self) -> &Guard {
self
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct GuardNotConfigured;
impl std::fmt::Display for GuardNotConfigured {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(
"应用状态里没有注册加密守卫(encryption Guard)—— \
请检查框架的 manage / app_data / with_state / data 装配步骤",
)
}
}
impl std::error::Error for GuardNotConfigured {}
#[cfg(feature = "axum")]
pub mod axum;
#[cfg(feature = "actix-web")]
pub mod actix;
#[cfg(feature = "rocket")]
pub mod rocket;
#[cfg(feature = "poem")]
pub mod poem;
#[cfg(feature = "salvo")]
pub mod salvo;
#[cfg(feature = "warp")]
pub mod warp;
#[cfg(feature = "bee-rust")]
pub mod bee_rust {
pub use super::Guarded;
pub use super::axum::GuardExtractor;
pub const USAGE: &str = "见本模块文档";
}
#[cfg(feature = "ecat")]
pub mod ecat;
#[cfg(test)]
mod tests {
use super::*;
use std::sync::Arc;
fn guard() -> Guard {
Guard::from_master_key(&[7u8; 32], "aes-256-gcm").unwrap()
}
#[test]
fn guard_is_itself_guarded() {
let g = guard();
assert_eq!(g.guard().identifiers().len(), 5);
}
#[test]
fn arc_guard_is_guarded() {
let g = Arc::new(guard());
assert_eq!(g.guard().identifiers().len(), 5);
}
#[test]
fn a_larger_state_can_point_at_its_guard() {
struct AppState {
#[allow(dead_code)]
pool: Arc<()>,
encryption: Guard,
}
impl Guarded for AppState {
fn guard(&self) -> &Guard {
&self.encryption
}
}
let state = AppState {
pool: Arc::new(()),
encryption: guard(),
};
let blob = state.guard().encrypt(b"x").unwrap();
assert_eq!(state.guard().decrypt(&blob).unwrap(), b"x");
}
}