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
//! Sentry user implementation.

use crate::{Object, Value};
use std::{
    collections::BTreeMap,
    ops::{Deref, DerefMut},
};

/// A Sentry user.
///
/// # Examples
/// ```
/// # use sentry_contrib_native::User;
/// let mut user = User::new();
/// user.insert("id", 1);
/// user.set();
/// ```
#[derive(Clone, Debug, PartialEq, PartialOrd)]
pub struct User(BTreeMap<String, Value>);

impl Default for User {
    fn default() -> Self {
        Self::new()
    }
}

impl Object for User {
    fn into_parts(self) -> (sys::Value, BTreeMap<String, Value>) {
        (unsafe { sys::value_new_object() }, self.0)
    }
}

impl Deref for User {
    type Target = BTreeMap<String, Value>;

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

impl DerefMut for User {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl User {
    /// Creates a new user.
    ///
    /// # Examples
    /// ```
    /// # use sentry_contrib_native::User;
    /// let mut user = User::new();
    /// ```
    #[must_use]
    #[allow(clippy::missing_const_for_fn)]
    pub fn new() -> Self {
        Self(BTreeMap::new())
    }

    /// Inserts a key-value pair into the [`User`].
    ///
    /// # Examples
    /// ```
    /// # use sentry_contrib_native::User;
    /// let mut user = User::new();
    /// user.insert("id", 1);
    /// ```
    pub fn insert<S: Into<String>, V: Into<Value>>(&mut self, key: S, value: V) {
        self.deref_mut().insert(key.into(), value.into());
    }

    /// Sets the specified user.
    ///
    /// # Examples
    /// ```
    /// # use sentry_contrib_native::User;
    /// let mut user = User::new();
    /// user.insert("id", 1);
    /// user.set();
    /// ```
    pub fn set(self) {
        let user = self.into_raw();
        unsafe { sys::set_user(user) }
    }
}

#[test]
fn user() {
    User::new().set();

    let mut user = User::new();
    user.insert("test", "test");
    user.set()
}