aboutsummaryrefslogtreecommitdiff
path: root/src/mail/unique_ident.rs
blob: 0e629dbac2e0a5d9be1de569a823f83f0ff49747 (plain) (blame)
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
use std::str::FromStr;
use std::sync::atomic::{AtomicU64, Ordering};

use lazy_static::lazy_static;
use rand::prelude::*;
use serde::{de::Error, Deserialize, Deserializer, Serialize, Serializer};

use crate::timestamp::now_msec;

/// An internal Mail Identifier is composed of two components:
/// - a process identifier, 128 bits, itself composed of:
///   - the timestamp of when the process started, 64 bits
///   - a 64-bit random number
/// - a sequence number, 64 bits
/// They are not part of the protocol but an internal representation
/// required by Aerogramme.
/// Their main property is to be unique without having to rely
/// on synchronization between IMAP processes.
#[derive(Clone, Copy, PartialOrd, Ord, PartialEq, Eq, Hash)]
pub struct UniqueIdent(pub [u8; 24]);

struct IdentGenerator {
    pid: u128,
    sn: AtomicU64,
}

impl IdentGenerator {
    fn new() -> Self {
        let time = now_msec() as u128;
        let rand = thread_rng().gen::<u64>() as u128;
        Self {
            pid: (time << 64) | rand,
            sn: AtomicU64::new(0),
        }
    }

    fn gen(&self) -> UniqueIdent {
        let sn = self.sn.fetch_add(1, Ordering::Relaxed);
        let mut res = [0u8; 24];
        res[0..16].copy_from_slice(&u128::to_be_bytes(self.pid));
        res[16..24].copy_from_slice(&u64::to_be_bytes(sn));
        UniqueIdent(res)
    }
}

lazy_static! {
    static ref GENERATOR: IdentGenerator = IdentGenerator::new();
}

pub fn gen_ident() -> UniqueIdent {
    GENERATOR.gen()
}

// -- serde --

impl<'de> Deserialize<'de> for UniqueIdent {
    fn deserialize<D>(d: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let v = String::deserialize(d)?;
        UniqueIdent::from_str(&v).map_err(D::Error::custom)
    }
}

impl Serialize for UniqueIdent {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.to_string())
    }
}

impl std::fmt::Display for UniqueIdent {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", hex::encode(self.0))
    }
}

impl std::fmt::Debug for UniqueIdent {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", hex::encode(self.0))
    }
}

impl FromStr for UniqueIdent {
    type Err = &'static str;

    fn from_str(s: &str) -> Result<UniqueIdent, &'static str> {
        let bytes = hex::decode(s).map_err(|_| "invalid hex")?;

        if bytes.len() != 24 {
            return Err("bad length");
        }

        let mut tmp = [0u8; 24];
        tmp[..].copy_from_slice(&bytes);
        Ok(UniqueIdent(tmp))
    }
}