safe_libc/posix/errno.rs
1//
2// Created: Sat 18 Apr 2020 02:58:32 AM PDT
3// Modified: Sat 18 Apr 2020 02:27:19 PM PDT
4//
5// Copyright (C) 2020 Robert Gill <rtgill82@gmail.com>
6//
7// Permission is hereby granted, free of charge, to any person obtaining a copy
8// of this software and associated documentation files (the "Software"), to
9// deal in the Software without restriction, including without limitation the
10// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
11// sell copies of the Software, and to permit persons to whom the Software is
12// furnished to do so, subject to the following conditions:
13//
14// The above copyright notice and this permission notice shall be included in
15// all copies of the Software, its documentation and marketing & publicity
16// materials, and acknowledgment shall be given in the documentation, materials
17// and software packages that this Software was used.
18//
19// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
20// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
21// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
22// THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
23// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
24// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
25//
26
27#[allow(non_camel_case_types)]
28type __errno_fn = unsafe extern "C" fn() -> *mut i32;
29
30#[allow(non_upper_case_globals)]
31#[cfg(target_os = "linux")]
32const __errno: __errno_fn = libc::__errno_location;
33
34#[allow(non_upper_case_globals)]
35#[cfg(all(not(target_os = "linux")))]
36const __errno: __errno_fn = libc::__errno;
37
38pub fn errno() -> i32 {
39 unsafe { *__errno() }
40}
41
42pub fn zero() {
43 unsafe { *__errno() = 0 };
44}
45
46#[cfg(test)]
47mod tests {
48 use crate::errno;
49 use super::__errno;
50
51 #[test]
52 fn test_errno() {
53 unsafe { *__errno() = libc::EACCES; }
54 assert_eq!(errno::errno(), libc::EACCES);
55 }
56
57 #[test]
58 fn test_zero() {
59 unsafe { *__errno() = libc::EACCES; }
60
61 errno::zero();
62 assert_eq!(errno::errno(), 0);
63 }
64}