Skip to content

Commit 7a5248c

Browse files
bors[bot]MikailBag
andauthored
Merge #1138
1138: Add Signal::as_str() to get representation as static string r=asomers a=MikailBag # Motivation Currently string representation of signal can be obtained with AsRef<str> impl. But it has downside: returned string's lifetime is bound to lifetime of signal, so &str must be converted to String. This allocation is avoidable, because as_ref() only returns static strings. To fix this problem, my PR adds Signal::as_str() method, which returns static string. Co-authored-by: Mikail Bagishov <[email protected]>
2 parents 2e52ce8 + bacb85e commit 7a5248c

File tree

2 files changed

+16
-3
lines changed

2 files changed

+16
-3
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ This project adheres to [Semantic Versioning](http://semver.org/).
55

66
## [Unreleased] - ReleaseDate
77
### Added
8+
- Added `Signal::as_str()`: returns signal name as `&'static str`
9+
(#[1138](https://github.com/nix-rust/nix/pull/1138))
810

911
- Added `posix_fallocate`.
1012
([#1105](https://github.com/nix-rust/nix/pull/1105))

src/sys/signal.rs

Lines changed: 14 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -112,9 +112,14 @@ impl FromStr for Signal {
112112
}
113113
}
114114

115-
impl AsRef<str> for Signal {
116-
fn as_ref(&self) -> &str {
117-
match *self {
115+
impl Signal {
116+
/// Returns name of signal.
117+
///
118+
/// This function is equivalent to `<Signal as AsRef<str>>::as_ref()`,
119+
/// with difference that returned string is `'static`
120+
/// and not bound to `self`'s lifetime.
121+
pub fn as_str(self) -> &'static str {
122+
match self {
118123
Signal::SIGHUP => "SIGHUP",
119124
Signal::SIGINT => "SIGINT",
120125
Signal::SIGQUIT => "SIGQUIT",
@@ -157,6 +162,12 @@ impl AsRef<str> for Signal {
157162
}
158163
}
159164

165+
impl AsRef<str> for Signal {
166+
fn as_ref(&self) -> &str {
167+
self.as_str()
168+
}
169+
}
170+
160171
impl fmt::Display for Signal {
161172
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
162173
f.write_str(self.as_ref())

0 commit comments

Comments
 (0)