glean_core/metrics/
memory_unit.rs

1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5use serde::{Deserialize, Serialize};
6
7use crate::error::{Error, ErrorKind};
8
9/// Different resolutions supported by the memory related metric types (e.g.
10/// MemoryDistributionMetric).
11#[derive(Copy, Clone, Debug, Deserialize, Serialize)]
12#[serde(rename_all = "lowercase")]
13#[repr(i32)] // use i32 to be compatible with our JNA definition
14pub enum MemoryUnit {
15    /// 1 byte
16    Byte,
17    /// 2^10 bytes
18    Kilobyte,
19    /// 2^20 bytes
20    Megabyte,
21    /// 2^30 bytes
22    Gigabyte,
23}
24
25impl MemoryUnit {
26    /// Converts a value in the given unit to bytes.
27    ///
28    /// # Arguments
29    ///
30    /// * `value` - the value to convert.
31    ///
32    /// # Returns
33    ///
34    /// The integer representation of the byte value.
35    pub fn as_bytes(self, value: u64) -> u64 {
36        use MemoryUnit::*;
37        match self {
38            Byte => value,
39            Kilobyte => value << 10,
40            Megabyte => value << 20,
41            Gigabyte => value << 30,
42        }
43    }
44}
45
46/// Trait implementation for converting an integer value
47/// to a [`MemoryUnit`]. This is used in the FFI code. Please
48/// note that values should match the ordering of the platform
49/// specific side of things (e.g. Kotlin implementation).
50impl TryFrom<i32> for MemoryUnit {
51    type Error = Error;
52
53    fn try_from(value: i32) -> Result<MemoryUnit, Self::Error> {
54        match value {
55            0 => Ok(MemoryUnit::Byte),
56            1 => Ok(MemoryUnit::Kilobyte),
57            2 => Ok(MemoryUnit::Megabyte),
58            3 => Ok(MemoryUnit::Gigabyte),
59            e => Err(ErrorKind::MemoryUnit(e).into()),
60        }
61    }
62}