| 1 | import pytest |
| 2 | import struct |
| 3 | from rpython.rtyper.lltypesystem import lltype, rffi |
| 4 | from rpython.rlib.mutbuffer import MutableStringBuffer |
| 5 | |
| 6 | class TestMutableStringBuffer(object): |
| 7 | |
| 8 | def test_finish(self): |
| 9 | buf = MutableStringBuffer(4) |
| 10 | buf.setzeros(0, 4) |
| 11 | pytest.raises(ValueError, "buf.as_str()") |
| 12 | s = buf.finish() |
| 13 | assert s == '\x00' * 4 |
| 14 | pytest.raises(ValueError, "buf.finish()") |
| 15 | |
| 16 | def test_setitem(self): |
| 17 | buf = MutableStringBuffer(4) |
| 18 | buf.setitem(0, 'A') |
| 19 | buf.setitem(1, 'B') |
| 20 | buf.setitem(2, 'C') |
| 21 | buf.setitem(3, 'D') |
| 22 | assert buf.finish() == 'ABCD' |
| 23 | |
| 24 | def test_setslice(self): |
| 25 | buf = MutableStringBuffer(6) |
| 26 | buf.setzeros(0, 6) |
| 27 | buf.setslice(2, 'ABCD') |
| 28 | assert buf.finish() == '\x00\x00ABCD' |
| 29 | |
| 30 | def test_setzeros(self): |
| 31 | buf = MutableStringBuffer(8) |
| 32 | buf.setslice(0, 'ABCDEFGH') |
| 33 | buf.setzeros(2, 3) |
| 34 | assert buf.finish() == 'AB\x00\x00\x00FGH' |
| 35 | |
| 36 | def test_typed_write(self): |
| 37 | expected = struct.pack('ifqd', 0x1234, 123.456, 0x12345678, 789.123) |
| 38 | buf = MutableStringBuffer(24) |
| 39 | buf.typed_write(rffi.INT, 0, 0x1234) |
| 40 | buf.typed_write(rffi.FLOAT, 4, 123.456) |
| 41 | buf.typed_write(rffi.LONGLONG, 8, 0x12345678) |
| 42 | buf.typed_write(rffi.DOUBLE, 16, 789.123) |
| 43 | s = buf.finish() |
| 44 | assert s == expected |