Skip to main content

crypto_literal/
lib.rs

1//! Crypto literal
2//!
3//! # Examples
4//!
5//! Basic usage:
6//!
7//! ```
8//! # #![feature(proc_macro_hygiene)]
9//! #
10//! # use crypto_literal::encrypt;
11//! #
12//! let crypto_literal = encrypt!("The quick brown fox jumps over the lazy dog");
13//! ```
14//!
15//! Static usage:
16//!
17//! ```
18//! # #![feature(proc_macro_hygiene)]
19//! #
20//! # use crypto_literal::{encrypt, CryptoLiteral};
21//! # use lazy_static::lazy_static;
22//! #
23//! lazy_static! {
24//!     static ref CRYPTO_LITERAL: CryptoLiteral<str> =
25//!         encrypt!("The quick brown fox jumps over the lazy dog.");
26//! }
27//! ```
28
29#![recursion_limit = "256"]
30
31pub use self::literal::Literal;
32pub use algorithm::Algorithm;
33#[doc(inline)]
34pub use crypto_literal_algorithm as algorithm;
35#[doc(hidden)]
36pub use crypto_literal_macro as r#macro;
37pub use r#macro::{algorithm, encrypt, key};
38
39// use derive_more::{AsRef, Deref, Display, From, Into};
40use derive_more::{AsRef, Display, From, Into};
41use serde::Deserialize;
42use std::{
43    borrow::Cow,
44    fmt::{self, Debug, Formatter},
45    ops::Deref,
46};
47
48/// Crypto literal.
49// TODO: uncomment then derive_more = "0.99.4"
50// #[derive(AsRef, Deref, Display, From, Into)]
51// #[deref(forward)]
52#[derive(AsRef, Display, From, Into)]
53#[as_ref(forward)]
54#[display(fmt = "{}", _0)]
55pub struct CryptoLiteral<T: Literal + ?Sized>(Cow<'static, T>);
56
57impl<T: Literal + ?Sized> CryptoLiteral<T>
58where
59    <T as ToOwned>::Owned: for<'de> Deserialize<'de>,
60{
61    pub fn new(algorithm: Algorithm, mut buffer: Vec<u8>) -> Self {
62        algorithm.decrypt(&mut buffer);
63        let deserialized = bincode::deserialize(&buffer).expect("deserialize literal");
64        Self(Cow::Owned(deserialized))
65    }
66}
67
68impl<T> Debug for CryptoLiteral<T>
69where
70    T: Literal,
71    T: Debug,
72    <T as ToOwned>::Owned: Debug,
73{
74    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
75        f.debug_tuple("CryptoLiteral").field(&self.0).finish()
76    }
77}
78
79impl<T: Literal + ?Sized> Deref for CryptoLiteral<T> {
80    type Target = T;
81
82    fn deref(&self) -> &Self::Target {
83        &*self.0
84    }
85}
86
87mod literal;