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
use crate::error::PinRegisterError;
use crate::error::StorageError;
use crate::hal_pin::PinDirection;
use linuxcnc_hal_sys::hal_malloc;
use std::{convert::TryInto, mem};
fn is_aligned_to<T: ?Sized>(ptr: *const T, align: usize) -> bool {
assert!(align.is_power_of_two());
let ptr = ptr as *const u8 as usize;
let mask = align.wrapping_sub(1);
(ptr & mask) == 0
}
pub trait HalPin: Sized {
type Storage: std::fmt::Debug;
fn allocate_storage() -> Result<*mut *mut Self::Storage, StorageError> {
let storage_ptr = unsafe {
let size = mem::size_of::<Self::Storage>();
debug!("Allocating {} bytes", size);
let ptr = hal_malloc(size.try_into().unwrap()) as *mut Self::Storage;
if ptr.is_null() {
return Err(StorageError::Null);
}
if !is_aligned_to(ptr, size) {
return Err(StorageError::Alignment);
}
debug!("Allocated value {:?} at {:?}", *ptr, ptr);
ptr as *mut *mut Self::Storage
};
Ok(storage_ptr)
}
fn name(&self) -> &str;
fn storage(&self) -> Result<&mut Self::Storage, StorageError>;
fn register_pin(
full_pin_name: &str,
direction: PinDirection,
component_id: i32,
) -> Result<Self, PinRegisterError>;
}