From 28073b7d05c0a065d62d5addf2ff8e7549fc9592 Mon Sep 17 00:00:00 2001 From: Carlos Date: Wed, 1 Nov 2017 16:05:21 -0200 Subject: [PATCH] create function Bytes.partition --- python/common/org/python/types/Bytes.java | 21 +++++++++++++++++---- tests/datatypes/test_bytes.py | 14 ++++++++++++++ 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/python/common/org/python/types/Bytes.java b/python/common/org/python/types/Bytes.java index a6c3e8ebd8..c06d51bb03 100644 --- a/python/common/org/python/types/Bytes.java +++ b/python/common/org/python/types/Bytes.java @@ -1173,10 +1173,23 @@ public org.python.Object maketrans(java.util.List args, java. } @org.python.Method( - __doc__ = "B.partition(sep) -> (head, sep, tail)\n\nSearch for the separator sep in B, and return the part before it,\nthe separator itself, and the part after it. If the separator is not\nfound, returns B and two empty bytes objects." - ) - public org.python.Object partition(java.util.List args, java.util.Map kwargs, java.util.List default_args, java.util.Map default_kwargs) { - throw new org.python.exceptions.NotImplementedError("bytes.partition has not been implemented."); + __doc__ = "B.partition(sep) -> (head, sep, tail)\n\nSearch for the separator sep in B, and return the part before it,\nthe separator itself, and the part after it. If the separator is not\nfound, returns B and two empty bytes objects.", + args = {"sep"} + ) + public org.python.Object partition(org.python.Object sep) { + Tuple result = new Tuple(); + int pos = (int) this.find(sep, null, null).value; + if (pos < 0) { + result.value.add(this); + result.value.add(new Bytes("")); + result.value.add(new Bytes("")); + } + else { + result.value.add(new Bytes(Arrays.copyOfRange(this.value, 0, pos))); + result.value.add(sep); + result.value.add(new Bytes(Arrays.copyOfRange(this.value, pos + ((Bytes)sep).value.length, this.value.length))); + } + return result; } @org.python.Method( diff --git a/tests/datatypes/test_bytes.py b/tests/datatypes/test_bytes.py index 9bd63aa526..4811cc49d4 100644 --- a/tests/datatypes/test_bytes.py +++ b/tests/datatypes/test_bytes.py @@ -55,6 +55,20 @@ def test_capitalize(self): print(b'\xc8'.capitalize()) """) + def test_partition(self): + self.assertCodeExecution(r""" + print(b'hello, world'.partition(b',')) + print(b'hello, world'.partition(b'h')) + print(b'hello, world'.partition(b'd')) + print(b'hello, world'.partition(b', ')) + print(b'hello, world'.partition(b'l')) + print(b'2015638687'.partition(b'a')) + print(b'\xc8'.partition(b' ')) + """) + # self.assertCodeExecution(r""" + # print(b'hello, world'.partition(None)) + # """, exits_early=True) + def test_repr(self): self.assertCodeExecution(r""" print(repr(b'\xc8'))