wallabag_api/types/
common.rs

1// Copyright 2018 Samuel Walladge <samuel@swalladge.net>
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4use std::fmt;
5use std::ops::Deref;
6
7use serde::{Deserialize, Serialize};
8
9/// The type used as an ID for all data structures. Declared for clarity.
10#[derive(Serialize, Deserialize, Hash, Debug, Clone, Copy, PartialEq, Eq)]
11pub struct ID(pub i64);
12
13impl fmt::Display for ID {
14    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
15        write!(f, "{}", self.0)
16    }
17}
18
19impl ID {
20    pub fn as_int(self) -> i64 {
21        self.0
22    }
23}
24
25/// For convenience.
26impl From<i32> for ID {
27    fn from(x: i32) -> Self {
28        ID(i64::from(x))
29    }
30}
31
32/// For convenience.
33impl From<i64> for ID {
34    fn from(x: i64) -> Self {
35        ID(x)
36    }
37}
38
39/// For convenience. Automatic type coercion means that an `&ID` can be passed
40/// as an argument to a function that takes a `u32`. Hopefully will make it easier
41/// to work with `ID` values in the structs.
42impl Deref for ID {
43    type Target = i64;
44
45    fn deref(&self) -> &i64 {
46        &self.0
47    }
48}
49
50#[cfg(test)]
51mod tests {
52    use super::*;
53
54    fn foo(_arg: &i64) {}
55
56    #[test]
57    fn test_flexible_id() {
58        assert_eq!(*ID(234), 234);
59        assert_eq!(ID(234), 234.into());
60        // test that can be passed to a function as a reference to an i64
61        foo(&ID(234));
62    }
63}