1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
//! Crypto literal
//!
//! # Examples
//!
//! Basic usage:
//!
//! ```
//! # #![feature(proc_macro_hygiene)]
//! #
//! # use crypto_literal::encrypt;
//! #
//! let crypto_literal = encrypt!("The quick brown fox jumps over the lazy dog");
//! ```
//!
//! Static usage:
//!
//! ```
//! # #![feature(proc_macro_hygiene)]
//! #
//! # use crypto_literal::{encrypt, CryptoLiteral};
//! # use lazy_static::lazy_static;
//! #
//! lazy_static! {
//!     static ref CRYPTO_LITERAL: CryptoLiteral<str> =
//!         encrypt!("The quick brown fox jumps over the lazy dog.");
//! }
//! ```

#![recursion_limit = "256"]

pub use self::literal::Literal;
pub use algorithm::Algorithm;
#[doc(inline)]
pub use crypto_literal_algorithm as algorithm;
#[doc(hidden)]
pub use crypto_literal_macro as r#macro;
pub use r#macro::{algorithm, encrypt, key};

// use derive_more::{AsRef, Deref, Display, From, Into};
use derive_more::{AsRef, Display, From, Into};
use serde::Deserialize;
use std::{
    borrow::Cow,
    fmt::{self, Debug, Formatter},
    ops::Deref,
};

/// Crypto literal.
// TODO: uncomment then derive_more = "0.99.4"
// #[derive(AsRef, Deref, Display, From, Into)]
// #[deref(forward)]
#[derive(AsRef, Display, From, Into)]
#[as_ref(forward)]
#[display(fmt = "{}", _0)]
pub struct CryptoLiteral<T: Literal + ?Sized>(Cow<'static, T>);

impl<T: Literal + ?Sized> CryptoLiteral<T>
where
    <T as ToOwned>::Owned: for<'de> Deserialize<'de>,
{
    pub fn new(algorithm: Algorithm, mut buffer: Vec<u8>) -> Self {
        algorithm.decrypt(&mut buffer);
        let deserialized = bincode::deserialize(&buffer).expect("deserialize literal");
        Self(Cow::Owned(deserialized))
    }
}

impl<T> Debug for CryptoLiteral<T>
where
    T: Literal,
    T: Debug,
    <T as ToOwned>::Owned: Debug,
{
    fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
        f.debug_tuple("CryptoLiteral").field(&self.0).finish()
    }
}

impl<T: Literal + ?Sized> Deref for CryptoLiteral<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &*self.0
    }
}

mod literal;