wpilib_sys/hal_call.rs
1/* PORTIONS OF THIS FILE WERE ORIGINALLY DISTRIBUTED WITH THE FOLLOWING LICENSE
2
3"""
4MIT License
5Copyright (c) 2017 Rust for Robotics Developers
6Permission is hereby granted, free of charge, to any person obtaining a copy
7of this software and associated documentation files (the "Software"), to deal
8in the Software without restriction, including without limitation the rights
9to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10copies of the Software, and to permit persons to whom the Software is
11furnished to do so, subject to the following conditions:
12
13The above copyright notice and this permission notice shall be included in all
14copies or substantial portions of the Software.
15
16THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22SOFTWARE.
23"""
24
25Copyright 2018 First Rust Competition Developers.
26Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
27http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
28<LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
29option. This file may not be copied, modified, or distributed
30except according to those terms.
31*/
32
33#![macro_use]
34
35use super::bindings::*;
36use std::{borrow::Cow, error::Error, ffi::CStr, fmt};
37
38#[derive(Copy, Clone)]
39pub struct HalError(pub i32);
40
41impl HalError {
42 /// Get the HAL error message associated with this error code.
43 /// In traditional WPILib, this would be printed the the driver
44 /// station whenever an error occured. The resulting string may
45 /// not be valid UTF-8.
46 pub fn message(&self) -> Cow<str> {
47 let const_char_ptr = unsafe { HAL_GetErrorMessage(self.0) };
48 let c_str = unsafe { CStr::from_ptr(const_char_ptr) };
49 c_str.to_string_lossy()
50 }
51}
52
53impl fmt::Debug for HalError {
54 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
55 write!(f, "HalError {{ {} }}", self.message())
56 }
57}
58
59impl fmt::Display for HalError {
60 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
61 write!(f, "Error: \"{}\"!", self.message())
62 }
63}
64
65impl Error for HalError {
66 fn description(&self) -> &str {
67 "Error in the HAL"
68 }
69}
70
71impl From<i32> for HalError {
72 fn from(code: i32) -> Self {
73 HalError(code)
74 }
75}
76
77pub type HalResult<T> = Result<T, HalError>;
78
79/// Represents the result of a function call that could error,
80/// but even if it does, the result is still usable.
81/// Like `HalResult<T>`, `HalMaybe<T>` must be used.
82#[must_use]
83#[derive(Copy, Clone, Debug)]
84pub struct HalMaybe<T> {
85 ret: T,
86 err: Option<HalError>,
87}
88
89impl<T> HalMaybe<T> {
90 pub fn new(ret: T, err: Option<HalError>) -> HalMaybe<T> {
91 HalMaybe { ret, err }
92 }
93
94 /// Ignore the possible error, and consume the `HalMaybe` into
95 /// its return value.
96 pub fn ok(self) -> T {
97 self.ret
98 }
99
100 /// Returns true if there is an error
101 pub fn has_err(&self) -> bool {
102 self.err.is_some()
103 }
104
105 /// Access the potential error.
106 pub fn err(&self) -> Option<HalError> {
107 self.err
108 }
109
110 /// Convert the `HalMaybe` into a `Result`, discarding the return
111 /// value if there is an error. This is useful for accessing
112 /// the many methods on `Result`, including `?` error raising.
113 pub fn into_res(self) -> Result<T, HalError> {
114 if let Some(x) = self.err {
115 Err(x)
116 } else {
117 Ok(self.ret)
118 }
119 }
120}
121
122/// Wraps a C/C++ HAL function call that looks like `T foo(arg1, arg2, arg3, ... , int32_t* status)`
123/// and turns that status into a `HALResult<T>`, with a non-zero status code returning in
124/// the `Err` variant.
125#[macro_export]
126macro_rules! hal_call {
127 ($function:ident($($arg:expr),*)) => {{
128 let mut status = 0;
129 let result = unsafe { $function($(
130 $arg,
131 )* &mut status as *mut i32) };
132 if status == 0 { Ok(result) } else { Err(HalError::from(status)) }
133 }};
134 ($namespace:path, $function:ident($($arg:expr),*)) => {{
135 let mut status = 0;
136 let result = unsafe { $namespace::$function($(
137 $arg,
138 )* &mut status as *mut i32) };
139 if status == 0 { Ok(result) } else { Err(HalError::from(status)) }
140 }};
141}
142
143/// Like `hal_call!`, but ignores the status code and returns the functions result anyway.
144/// This sounds bad, but WPILibC does it in some places, and there isn't really a reason to
145/// needlessly complicate the public interface.
146#[macro_export]
147macro_rules! maybe_hal_call {
148 ($function:ident($($arg:expr),*)) => {{
149 let mut status = 0;
150 let result = unsafe { $function($(
151 $arg,
152 )* &mut status as *mut i32) };
153 HalMaybe::new(
154 result,
155 if status == 0 {
156 None
157 } else {
158 Some(HalError::from(status))
159 }
160 )
161 }};
162 ($namespace:path, $function:ident($($arg:expr),*)) => {{
163 let mut status = 0;
164 let result = unsafe { $namespace::$function($(
165 $arg,
166 )* &mut status as *mut i32) };
167 HalMaybe::new(
168 result,
169 if status == 0 {
170 None
171 } else {
172 Some(HalError::from(status))
173 }
174 )
175 }};
176}