Skip to content

Commit

Permalink
Merge pull request #104 from hollowness-inside/simplify-cast-to-u8
Browse files Browse the repository at this point in the history
Simplify `From<Tag> for u8` Implementation with Direct Cast
  • Loading branch information
owengage authored Mar 15, 2024
2 parents 614385b + 1bc15a1 commit 47c5fe5
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 33 deletions.
17 changes: 2 additions & 15 deletions fastnbt/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -213,22 +213,9 @@ impl TryFrom<u8> for Tag {
}

impl From<Tag> for u8 {
#[inline(always)]
fn from(tag: Tag) -> Self {
match tag {
Tag::End => 0,
Tag::Byte => 1,
Tag::Short => 2,
Tag::Int => 3,
Tag::Long => 4,
Tag::Float => 5,
Tag::Double => 6,
Tag::ByteArray => 7,
Tag::String => 8,
Tag::List => 9,
Tag::Compound => 10,
Tag::IntArray => 11,
Tag::LongArray => 12,
}
tag as u8
}
}

Expand Down
40 changes: 22 additions & 18 deletions fastnbt/src/test/mod.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::convert::{TryFrom, TryInto};
use std::convert::TryFrom;

use serde::{Deserialize, Serialize};

Expand Down Expand Up @@ -26,27 +26,31 @@ struct Single<T: Serialize> {
#[derive(Serialize, Deserialize)]
struct Wrap<T: Serialize>(T);

fn assert_try_into(tag: Tag) {
assert_eq!(tag, (tag as u8).try_into().unwrap());
macro_rules! check_tags {
{$($tag:ident = $val:literal),* $(,)?} => {
$(
assert_eq!(u8::from(Tag::$tag), $val);
)*
};
}

#[test]
fn exhaustive_tag_check() {
use Tag::*;
assert_try_into(End);
assert_try_into(Byte);
assert_try_into(Short);
assert_try_into(Int);
assert_try_into(Long);
assert_try_into(Float);
assert_try_into(Double);
assert_try_into(ByteArray);
assert_try_into(String);
assert_try_into(List);
assert_try_into(Compound);
assert_try_into(Compound);
assert_try_into(IntArray);
assert_try_into(LongArray);
check_tags! {
End = 0,
Byte = 1,
Short = 2,
Int = 3,
Long = 4,
Float = 5,
Double = 6,
ByteArray = 7,
String = 8,
List = 9,
Compound = 10,
IntArray = 11,
LongArray = 12,
}

for value in 13..=u8::MAX {
assert!(Tag::try_from(value).is_err())
Expand Down

0 comments on commit 47c5fe5

Please sign in to comment.