Skip to content

Commit

Permalink
feat: Use Bytes in NbtTag
Browse files Browse the repository at this point in the history
  • Loading branch information
SzczurekYT committed Mar 27, 2024
1 parent 850c0ea commit c05ab22
Showing 1 changed file with 12 additions and 6 deletions.
18 changes: 12 additions & 6 deletions src/nbt/tag.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ pub enum NbtTag {
Long(i64) = LONG_ID,
Float(f32) = FLOAT_ID,
Double(f64) = DOUBLE_ID,
ByteArray(Vec<u8>) = BYTE_ARRAY_ID,
ByteArray(Bytes) = BYTE_ARRAY_ID,
String(String) = STRING_ID,
List(Vec<NbtTag>) = LIST_ID,
Compound(NbtCompound) = COMPOUND_ID,
Expand Down Expand Up @@ -125,9 +125,7 @@ impl NbtTag {
}
BYTE_ARRAY_ID => {
let len = bytes.get_i32() as usize;
let byte_array = bytes[..len].to_vec();
bytes.advance(len);
Ok(NbtTag::ByteArray(byte_array))
Ok(NbtTag::ByteArray(bytes.copy_to_bytes(len)))
}
STRING_ID => Ok(NbtTag::String(get_nbt_string(bytes).unwrap())),
LIST_ID => {
Expand Down Expand Up @@ -206,9 +204,11 @@ impl NbtTag {
}
}

pub fn extract_byte_array(&self) -> Option<&Vec<u8>> {
pub fn extract_byte_array(&self) -> Option<Bytes> {
match self {
NbtTag::ByteArray(byte_array) => Some(byte_array),
// Note: Bytes as a pointer like type
// It's free to clone, so we can hand out an owned type
NbtTag::ByteArray(byte_array) => Some(byte_array.clone()),
_ => None,
}
}
Expand Down Expand Up @@ -254,3 +254,9 @@ impl From<&str> for NbtTag {
NbtTag::String(value.to_string())
}
}

impl From<&[u8]> for NbtTag {
fn from(value: &[u8]) -> Self {
NbtTag::ByteArray(Bytes::copy_from_slice(value))
}
}

0 comments on commit c05ab22

Please sign in to comment.