Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Avoid zero initialization in Short #202

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 5 additions & 4 deletions src/short.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
use std::mem::MaybeUninit;
use std::{ ptr, str, slice, fmt };
use std::ops::Deref;

Expand All @@ -6,7 +7,7 @@ pub const MAX_LEN: usize = 30;
#[derive(Clone, Copy)]
pub struct Short {
len: u8,
value: [u8; MAX_LEN],
value: [MaybeUninit<u8>; MAX_LEN],
}

/// A `Short` is a small string, up to `MAX_LEN` bytes, that can be managed without
Expand All @@ -23,11 +24,11 @@ impl Short {
#[inline(always)]
pub unsafe fn from_slice(slice: &str) -> Self {
let mut short = Short {
value: [0; MAX_LEN],
value: MaybeUninit::uninit().assume_init(),
len: slice.len() as u8,
};

ptr::copy_nonoverlapping(slice.as_ptr(), short.value.as_mut_ptr(), slice.len());
ptr::copy_nonoverlapping(slice.as_ptr(), short.value.as_mut_ptr() as _, slice.len());

short
}
Expand All @@ -37,7 +38,7 @@ impl Short {
pub fn as_str(&self) -> &str {
unsafe {
str::from_utf8_unchecked(
slice::from_raw_parts(self.value.as_ptr(), self.len as usize)
slice::from_raw_parts(self.value.as_ptr() as _, self.len as usize)
)
}
}
Expand Down