machine_id/
lib.rs

1// Distributed under the OSI-approved BSD 3-Clause License.
2// See accompanying LICENSE file for details.
3
4use std::fmt;
5
6use lazy_static::lazy_static;
7use uuid::Uuid;
8
9#[cfg(unix)]
10mod imp {
11    mod unix;
12    pub use self::unix::get_machine_id;
13}
14
15#[cfg(not(any(unix)))]
16mod imp {
17    fn get_machine_id() -> Option<Uuid> {
18        None
19    }
20}
21
22/// A machine-specific ID.
23#[derive(PartialEq, Eq, Debug, Clone, Copy)]
24pub struct MachineId {
25    uuid: Uuid,
26}
27
28lazy_static! {
29    static ref GENERATED_ID: Uuid = Uuid::new_v4();
30    static ref GLOBAL_ID: Option<Uuid> = imp::get_machine_id();
31}
32
33impl MachineId {
34    /// Retrieves or generates the machine-specific ID.
35    pub fn get() -> MachineId {
36        MachineId {
37            uuid: GLOBAL_ID.unwrap_or(*GENERATED_ID),
38        }
39    }
40}
41
42impl fmt::Display for MachineId {
43    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
44        write!(f, "{}", self.uuid)
45    }
46}
47
48impl From<MachineId> for Uuid {
49    fn from(mid: MachineId) -> Uuid {
50        mid.uuid
51    }
52}
53
54#[test]
55fn test_idempotent() {
56    let fst = MachineId::get();
57    let snd = MachineId::get();
58
59    assert_eq!(fst, snd);
60}
61
62#[test]
63fn test_can_print() {
64    let mid = MachineId::get();
65
66    println!("{}", mid);
67}