Skip to content

Commit

Permalink
Merge #1138
Browse files Browse the repository at this point in the history
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 <bagishov.mikail@yandex.ru>
  • Loading branch information
bors[bot] and MikailBag authored Oct 29, 2019
2 parents 2e52ce8 + bacb85e commit 7a5248c
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ This project adheres to [Semantic Versioning](http://semver.org/).

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

- Added `posix_fallocate`.
([#1105](https://github.com/nix-rust/nix/pull/1105))
Expand Down
17 changes: 14 additions & 3 deletions src/sys/signal.rs
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,14 @@ impl FromStr for Signal {
}
}

impl AsRef<str> for Signal {
fn as_ref(&self) -> &str {
match *self {
impl Signal {
/// Returns name of signal.
///
/// This function is equivalent to `<Signal as AsRef<str>>::as_ref()`,
/// with difference that returned string is `'static`
/// and not bound to `self`'s lifetime.
pub fn as_str(self) -> &'static str {
match self {
Signal::SIGHUP => "SIGHUP",
Signal::SIGINT => "SIGINT",
Signal::SIGQUIT => "SIGQUIT",
Expand Down Expand Up @@ -157,6 +162,12 @@ impl AsRef<str> for Signal {
}
}

impl AsRef<str> for Signal {
fn as_ref(&self) -> &str {
self.as_str()
}
}

impl fmt::Display for Signal {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str(self.as_ref())
Expand Down

0 comments on commit 7a5248c

Please sign in to comment.