Skip to main content

nvml_wrapper/struct_wrappers/
gpm.rs

1use std::convert::TryFrom;
2use std::ffi::CStr;
3
4use crate::enums::gpm::GpmMetricId;
5use crate::error::{nvml_try, NvmlError};
6use crate::ffi::bindings::*;
7#[cfg(feature = "serde")]
8use serde_derive::{Deserialize, Serialize};
9
10/// Descriptive information about a GPM metric.
11#[derive(Debug, Clone, Eq, PartialEq, Hash)]
12#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
13pub struct GpmMetricInfo {
14    pub short_name: String,
15    pub long_name: String,
16    pub unit: String,
17}
18
19impl GpmMetricInfo {
20    /// Construct from the C inner type with null-pointer safety.
21    ///
22    /// # Safety
23    ///
24    /// The pointers in `info` must either be null or point to valid
25    /// null-terminated C strings.
26    pub(crate) unsafe fn from_c(info: &nvmlGpmMetric_t__bindgen_ty_1) -> Result<Self, NvmlError> {
27        let short_name = if info.shortName.is_null() {
28            String::new()
29        } else {
30            CStr::from_ptr(info.shortName).to_str()?.into()
31        };
32
33        let long_name = if info.longName.is_null() {
34            String::new()
35        } else {
36            CStr::from_ptr(info.longName).to_str()?.into()
37        };
38
39        let unit = if info.unit.is_null() {
40            String::new()
41        } else {
42            CStr::from_ptr(info.unit).to_str()?.into()
43        };
44
45        Ok(Self {
46            short_name,
47            long_name,
48            unit,
49        })
50    }
51}
52
53/// The result of a single GPM metric query.
54#[derive(Debug, Clone, PartialEq)]
55#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
56pub struct GpmMetricResult {
57    pub metric_id: GpmMetricId,
58    pub value: f64,
59    pub metric_info: GpmMetricInfo,
60}
61
62impl GpmMetricResult {
63    /// Construct from the C type, checking the per-metric return code.
64    ///
65    /// # Safety
66    ///
67    /// The string pointers within `metric.metricInfo` must be valid.
68    pub(crate) unsafe fn try_from_c(metric: &nvmlGpmMetric_t) -> Result<Self, NvmlError> {
69        nvml_try(metric.nvmlReturn)?;
70
71        let metric_id = GpmMetricId::try_from(metric.metricId)?;
72        let metric_info = GpmMetricInfo::from_c(&metric.metricInfo)?;
73
74        Ok(Self {
75            metric_id,
76            value: metric.value,
77            metric_info,
78        })
79    }
80}