Skip to content

Commit

Permalink
Added py_str_or_bytes property (#91)
Browse files Browse the repository at this point in the history
This will try and decoded the payload using UTF-8 and if that fails returns it as bytes.
  • Loading branch information
gentlegiantJGC authored Oct 21, 2024
1 parent fd4f246 commit 9fdf030
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/amulet_nbt/__init__.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -313,6 +313,10 @@ class StringTag(AbstractBaseImmutableTag):
def py_bytes(self) -> bytes:
"""The bytes stored in the class."""

@property
def py_str_or_bytes(self) -> str | bytes:
"""If the payload is UTF-8 returns a string else returns bytes."""

def __ge__(self, other: Any) -> bool:
"""Check if the tag is greater than or equal to another tag."""

Expand Down
11 changes: 11 additions & 0 deletions src/amulet_nbt/pybind/tag/py_string_tag.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,17 @@ void init_string(py::module& m) {
"The bytes stored in the class."
)
);
StringTag.def_property_readonly(
"py_str_or_bytes",
[](const AmuletNBT::StringTag& self) -> std::variant<py::str, py::bytes> {
try {
return py::str(self);
} catch (py::error_already_set&){
return py::bytes(self);
}
},
py::doc("If the payload is UTF-8 returns a string else returns bytes.")
);
StringTag.def_property_readonly(
"py_data",
[](const AmuletNBT::StringTag& self){
Expand Down
7 changes: 7 additions & 0 deletions tests/test_amulet_nbt/test_tag/test_string.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,13 @@ def test_py_data(self) -> None:

self.assertEqual(b"value", StringTag("value").py_bytes)

self.assertIsInstance(StringTag("test").py_str_or_bytes, str)
self.assertEqual("test", StringTag("test").py_str_or_bytes)
self.assertIsInstance(StringTag("test").py_str_or_bytes, str)
self.assertEqual("test", StringTag("test").py_str_or_bytes)
self.assertIsInstance(StringTag(b"test\xFF").py_str_or_bytes, bytes)
self.assertEqual(b"test\xFF", StringTag(b"test\xFF").py_str_or_bytes)

def test_repr(self) -> None:
self.assertEqual("StringTag('')", repr(StringTag()))
self.assertEqual("StringTag('value')", repr(StringTag("value")))
Expand Down

0 comments on commit 9fdf030

Please sign in to comment.