Skip to content

Commit d7d613a

Browse files
committed
NBL-64: Python: Allow signed byte values in ByteArray
This resolves #327
1 parent 21a1008 commit d7d613a

2 files changed

Lines changed: 22 additions & 2 deletions

File tree

pygridgain/datatypes/primitive_arrays.py

Lines changed: 16 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -220,7 +220,22 @@ def from_python(cls, value):
220220
# no need to iterate on bytes or bytearray
221221
# to create ByteArrayObject data buffer
222222
header.length = len(value)
223-
return bytes(bytearray(header) + bytearray(value))
223+
try:
224+
# `value` is a `bytearray` or a sequence of integer values
225+
# in range 0 to 255
226+
value_buffer = bytearray(value)
227+
except ValueError:
228+
# `value` is a sequence of integers in range -128 to 127
229+
value_buffer = bytearray()
230+
for ch in value:
231+
if -128 <= ch <= 255:
232+
value_buffer.append(ctypes.c_ubyte(ch).value)
233+
else:
234+
raise ValueError(
235+
'byte must be in range(-128, 256)!'
236+
) from None
237+
238+
return bytes(bytearray(header) + value_buffer)
224239

225240

226241
class ShortArrayObject(PrimitiveArrayObject):

tests/test_datatypes.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,15 @@
1313
# See the License for the specific language governing permissions and
1414
# limitations under the License.
1515
#
16+
import ctypes
1617
from datetime import datetime, timedelta
1718
import decimal
1819
import pytest
1920
import uuid
2021

2122
from pygridgain.api.key_value import cache_get, cache_put
2223
from pygridgain.datatypes import *
24+
from pygridgain.utils import unsigned
2325

2426

2527
@pytest.mark.parametrize(
@@ -143,6 +145,7 @@ def test_put_get_data(client, cache, value, value_hint):
143145
[
144146
[1, 2, 3, 5],
145147
(7, 8, 13, 18),
148+
(-128, -1, 0, 1, 127, 255),
146149
]
147150
)
148151
def test_bytearray_from_list_or_tuple(client, cache, value):
@@ -160,7 +163,9 @@ def test_bytearray_from_list_or_tuple(client, cache, value):
160163

161164
result = cache_get(conn, cache, 'my_key')
162165
assert result.status == 0
163-
assert result.value == bytearray(value)
166+
assert result.value == bytearray([
167+
unsigned(ch, ctypes.c_ubyte) for ch in value
168+
])
164169

165170

166171
@pytest.mark.parametrize(

0 commit comments

Comments
 (0)