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

Remove unsafe from impl Compact for ClientVersion #11318

Open
wants to merge 9 commits into
base: main
Choose a base branch
from
15 changes: 15 additions & 0 deletions crates/storage/codecs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,21 @@ pub trait Compact: Sized {
}
}

impl Compact for String {
fn to_compact<B>(&self, buf: &mut B) -> usize
where
B: bytes::BufMut + AsMut<[u8]>,
{
self.as_bytes().to_compact(buf)
}

fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) {
let (vec, buf) = Vec::<u8>::from_compact(buf, len);
let string = String::from_utf8(vec).unwrap(); // Safe conversion
(string, buf)
}
}

impl<T: Compact> Compact for &T {
fn to_compact<B>(&self, buf: &mut B) -> usize
where
Expand Down
18 changes: 7 additions & 11 deletions crates/storage/db-models/src/client_version.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,20 +28,16 @@ impl Compact for ClientVersion {
where
B: bytes::BufMut + AsMut<[u8]>,
{
self.version.as_bytes().to_compact(buf);
self.git_sha.as_bytes().to_compact(buf);
self.build_timestamp.as_bytes().to_compact(buf)
self.version.to_compact(buf);
self.git_sha.to_compact(buf);
self.build_timestamp.to_compact(buf)
}

fn from_compact(buf: &[u8], len: usize) -> (Self, &[u8]) {
let (version, buf) = Vec::<u8>::from_compact(buf, len);
let (git_sha, buf) = Vec::<u8>::from_compact(buf, len);
let (build_timestamp, buf) = Vec::<u8>::from_compact(buf, len);
let client_version = Self {
version: unsafe { String::from_utf8_unchecked(version) },
git_sha: unsafe { String::from_utf8_unchecked(git_sha) },
build_timestamp: unsafe { String::from_utf8_unchecked(build_timestamp) },
};
let (version, buf) = String::from_compact(buf, len);
let (git_sha, buf) = String::from_compact(buf, len);
let (build_timestamp, buf) = String::from_compact(buf, len);
let client_version = Self { version, git_sha, build_timestamp };
(client_version, buf)
}
}
Loading