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

Added py_str_or_bytes property #91

Merged
merged 1 commit into from
Oct 21, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading