Skip to content

Commit 52fd0f4

Browse files
committed
traits: code improvement
1 parent 3e3950d commit 52fd0f4

File tree

2 files changed

+9
-12
lines changed

2 files changed

+9
-12
lines changed

multiboot2-header/src/builder/traits.rs

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ use crate::{
55
EntryAddressHeaderTag, EntryEfi32HeaderTag, EntryEfi64HeaderTag, FramebufferHeaderTag,
66
InformationRequestHeaderTag, ModuleAlignHeaderTag, Multiboot2BasicHeader, RelocatableHeaderTag,
77
};
8+
use alloc::vec::Vec;
89
use core::mem::size_of;
910

1011
/// Trait for all tags that helps to create a byte array from the tag.
@@ -24,13 +25,10 @@ pub(crate) trait StructAsBytes: Sized {
2425

2526
/// Returns the structure as a vector of its bytes.
2627
/// The length is determined by [`Self::byte_size`].
27-
fn struct_as_bytes(&self) -> alloc::vec::Vec<u8> {
28+
fn struct_as_bytes(&self) -> Vec<u8> {
2829
let ptr = self.as_ptr();
29-
let mut vec = alloc::vec::Vec::with_capacity(self.byte_size());
30-
for i in 0..self.byte_size() {
31-
vec.push(unsafe { *ptr.add(i) })
32-
}
33-
vec
30+
let bytes = unsafe { core::slice::from_raw_parts(ptr, self.byte_size()) };
31+
Vec::from(bytes)
3432
}
3533
}
3634

multiboot2/src/builder/traits.rs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
//! Module for the helper trait [`StructAsBytes`].
22
3+
use alloc::vec::Vec;
4+
35
/// Trait for all tags that helps to create a byte array from the tag.
46
/// Useful in builders to construct a byte vector that
57
/// represents the Multiboot2 information with all its tags.
@@ -16,12 +18,9 @@ pub(crate) trait StructAsBytes {
1618

1719
/// Returns the structure as a vector of its bytes.
1820
/// The length is determined by [`Self::byte_size`].
19-
fn struct_as_bytes(&self) -> alloc::vec::Vec<u8> {
21+
fn struct_as_bytes(&self) -> Vec<u8> {
2022
let ptr = self.as_ptr();
21-
let mut vec = alloc::vec::Vec::with_capacity(self.byte_size());
22-
for i in 0..self.byte_size() {
23-
vec.push(unsafe { *ptr.add(i) })
24-
}
25-
vec
23+
let bytes = unsafe { core::slice::from_raw_parts(ptr, self.byte_size()) };
24+
Vec::from(bytes)
2625
}
2726
}

0 commit comments

Comments
 (0)