rlimit/resource/mod.rs
1mod generated;
2
3use crate::{getrlimit, setrlimit};
4
5use std::fmt;
6use std::io;
7
8/// A kind of resource.
9///
10/// All resource constants are available on all unix platforms.
11/// Passing an unsupported resource to `[set|get|p]rlimit` will
12/// result in a custom IO error.
13///
14/// **Be careful**: The documentation of [`Resource`](Resource) constants are based on a few systems.
15///
16/// It may be inconsistent with other platforms.
17///
18/// ## References
19///
20/// Linux: <https://man7.org/linux/man-pages/man2/getrlimit.2.html>
21///
22/// FreeBSD: <https://www.freebsd.org/cgi/man.cgi?query=getrlimit>
23///
24/// NetBSD: <https://man.netbsd.org/getrlimit.2>
25///
26/// AIX: <https://www.ibm.com/docs/en/aix/7.3?topic=g-getrlimit-getrlimit64-setrlimit-setrlimit64-vlimit-subroutine>
27#[derive(Clone, Copy, PartialEq, Eq, Hash)]
28pub struct Resource {
29 tag: u8,
30 value: u8,
31}
32
33impl fmt::Debug for Resource {
34 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35 match Self::find_ident_by_tag(self.tag) {
36 Some(ident) => write!(f, "Resource::{ident}"),
37 None => unreachable!(),
38 }
39 }
40}
41
42/// An error returned when `Resource::from_str` fails
43#[derive(Debug, Clone, PartialEq, Eq)]
44pub struct ParseResourceError(());
45
46impl fmt::Display for ParseResourceError {
47 #[inline]
48 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
49 write!(f, "Failed to parse Resource")
50 }
51}
52
53impl std::error::Error for ParseResourceError {}
54
55impl Resource {
56 /// Set resource limits.
57 /// # Errors
58 /// See [`setrlimit`]
59 #[inline]
60 pub fn set(self, soft: u64, hard: u64) -> io::Result<()> {
61 setrlimit(self, soft, hard)
62 }
63
64 /// Get resource limits.
65 /// # Errors
66 /// See [`getrlimit`]
67 #[inline]
68 pub fn get(self) -> io::Result<(u64, u64)> {
69 getrlimit(self)
70 }
71
72 /// Get soft resource limit (`rlim_cur`)
73 /// # Errors
74 /// See [`getrlimit`]
75 pub fn get_soft(self) -> io::Result<u64> {
76 self.get().map(|(soft, _)| soft)
77 }
78
79 /// Get hard resource limit (`rlim_max`)
80 /// # Errors
81 /// See [`getrlimit`]
82 pub fn get_hard(self) -> io::Result<u64> {
83 self.get().map(|(_, hard)| hard)
84 }
85
86 /// Returns the name of the resource.
87 ///
88 /// # Example
89 /// ```
90 /// # #[cfg(unix)]
91 /// # {
92 /// # use rlimit::Resource;
93 /// assert_eq!(Resource::NOFILE.as_name(), "RLIMIT_NOFILE");
94 /// # }
95 /// ```
96 #[must_use]
97 pub fn as_name(self) -> &'static str {
98 match Self::find_name_by_tag(self.tag) {
99 Some(name) => name,
100 None => unreachable!(),
101 }
102 }
103
104 /// Returns true if the current platform supports this resource.
105 #[must_use]
106 pub const fn is_supported(self) -> bool {
107 self.value != u8::MAX
108 }
109
110 /// `u8::MAX` indicates unsupported resource.
111 #[inline]
112 #[must_use]
113 pub(crate) const fn as_raw(self) -> u8 {
114 self.value
115 }
116}