Merge pull request #1593 from Shnatsel/one-less-unsafe

Drop unnecessary `unsafe`
This commit is contained in:
Dylan DPC 2019-11-06 15:55:12 +01:00 committed by GitHub
commit 92c2b5df3f
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -459,34 +459,39 @@ macro_rules! crate_version {
macro_rules! crate_authors { macro_rules! crate_authors {
($sep:expr) => {{ ($sep:expr) => {{
use std::ops::Deref; use std::ops::Deref;
use std::sync::Once; use std::boxed::Box;
use std::cell::Cell;
#[allow(missing_copy_implementations)] #[allow(missing_copy_implementations)]
#[allow(dead_code)] #[allow(dead_code)]
struct CargoAuthors { struct CargoAuthors {
authors: Cell<Option<&'static str>>,
__private_field: (), __private_field: (),
}; };
impl Deref for CargoAuthors { impl Deref for CargoAuthors {
type Target = str; type Target = str;
#[allow(unsafe_code)]
fn deref(&self) -> &'static str { fn deref(&self) -> &'static str {
static ONCE: Once = Once::new(); let authors = self.authors.take();
static mut VALUE: *const String = 0 as *const String; if authors.is_some() {
let unwrapped_authors = authors.unwrap();
unsafe { self.authors.replace(Some(unwrapped_authors));
ONCE.call_once(|| { unwrapped_authors
let s = env!("CARGO_PKG_AUTHORS").replace(':', $sep); } else {
VALUE = Box::into_raw(Box::new(s)); // This caches the result for subsequent invocations of the same instance of the macro
}); // to avoid performing one memory allocation per call.
// If performance ever becomes a problem for this code, it should be moved to build.rs
&(*VALUE)[..] let s: Box<String> = Box::new(env!("CARGO_PKG_AUTHORS").replace(':', $sep));
let static_string = Box::leak(s);
self.authors.replace(Some(&*static_string));
&*static_string // weird but compiler-suggested way to turn a String into &str
} }
} }
} }
&*CargoAuthors { &*CargoAuthors {
authors: std::cell::Cell::new(Option::None),
__private_field: (), __private_field: (),
} }
}}; }};