leodos_libcfs/cfe/es/
counter.rs1use crate::error::{CfsError, OsalError, Result};
7use crate::ffi;
8use crate::cstring;
9use crate::status::check;
10use core::mem::MaybeUninit;
11use heapless::String;
12
13#[derive(Debug)]
18pub struct Counter {
19 id: CounterId,
20}
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub struct CounterId(ffi::CFE_ES_CounterId_t);
25
26impl Counter {
27 pub fn new(name: &str) -> Result<Self> {
34 let c_name = cstring::<{ ffi::OS_MAX_API_NAME as usize }>(name)?;
35
36 let mut counter_id = MaybeUninit::uninit();
37 check(unsafe { ffi::CFE_ES_RegisterGenCounter(counter_id.as_mut_ptr(), c_name.as_ptr()) })?;
38 Ok(Self {
39 id: CounterId(unsafe { counter_id.assume_init() }),
40 })
41 }
42
43 pub fn inc(&self) -> Result<()> {
48 check(unsafe { ffi::CFE_ES_IncrementGenCounter(self.id.0) })?;
49 Ok(())
50 }
51
52 pub fn set(&self, count: u32) -> Result<()> {
54 check(unsafe { ffi::CFE_ES_SetGenCount(self.id.0, count) })?;
55 Ok(())
56 }
57
58 pub fn get(&self) -> Result<u32> {
60 let mut count = 0;
61 check(unsafe { ffi::CFE_ES_GetGenCount(self.id.0, &mut count) })?;
62 Ok(count)
63 }
64
65 pub fn id(&self) -> CounterId {
67 self.id
68 }
69
70 pub fn get_id_by_name(name: &str) -> Result<CounterId> {
72 let c_name = cstring::<{ ffi::OS_MAX_API_NAME as usize }>(name)?;
73
74 let mut counter_id = MaybeUninit::uninit();
75 check(unsafe {
76 ffi::CFE_ES_GetGenCounterIDByName(counter_id.as_mut_ptr(), c_name.as_ptr())
77 })?;
78 Ok(CounterId(unsafe { counter_id.assume_init() }))
79 }
80}
81
82impl Drop for Counter {
83 fn drop(&mut self) {
85 let _ = unsafe { ffi::CFE_ES_DeleteGenCounter(self.id.0) };
86 }
87}
88
89impl CounterId {
90 pub fn name(&self) -> Result<String<{ ffi::OS_MAX_API_NAME as usize }>> {
92 let mut buffer = [0u8; ffi::OS_MAX_API_NAME as usize];
93 check(unsafe {
94 ffi::CFE_ES_GetGenCounterName(
95 buffer.as_mut_ptr() as *mut libc::c_char,
96 self.0,
97 buffer.len(),
98 )
99 })?;
100 let len = buffer.iter().position(|&b| b == 0).unwrap_or(buffer.len());
101 let vec = heapless::Vec::from_slice(&buffer[..len]).map_err(|_| CfsError::Osal(OsalError::NameTooLong))?;
102 String::from_utf8(vec).map_err(|_| CfsError::InvalidString)
103 }
104
105 pub fn to_index(&self) -> Result<u32> {
107 let mut index = MaybeUninit::uninit();
108 check(unsafe { ffi::CFE_ES_CounterID_ToIndex(self.0, index.as_mut_ptr()) })?;
109 Ok(unsafe { index.assume_init() })
110 }
111}