diff options
author | Benjamin Peterson <benjamin@python.org> | 2013-06-02 22:19:26 -0700 |
---|---|---|
committer | Benjamin Peterson <benjamin@python.org> | 2013-06-02 22:19:26 -0700 |
commit | fd2d224e3f99ddd65859f11583380746bffd20fa (patch) | |
tree | 2b0ecac5f309e083917cc1e9aac5c2008a7ebe8c | |
parent | 023bffc477711dc659a4195f02b2087989e3d3ff (diff) | |
download | six-git-fd2d224e3f99ddd65859f11583380746bffd20fa.tar.gz |
add byte2int (fixes #26)
-rw-r--r-- | CHANGES | 2 | ||||
-rw-r--r-- | documentation/index.rst | 6 | ||||
-rw-r--r-- | six.py | 3 | ||||
-rw-r--r-- | test_six.py | 6 |
4 files changed, 17 insertions, 0 deletions
@@ -6,6 +6,8 @@ This file lists the changes in each six version. Development version ------------------- +- Issue #26: Add byte2int function which complements int2byte. + - Add a PY2 constant with obvious semantics. - Add helpers for indexing and iterating over bytes: iterbytes and indexbytes. diff --git a/documentation/index.rst b/documentation/index.rst index d60328a..3755d52 100644 --- a/documentation/index.rst +++ b/documentation/index.rst @@ -330,6 +330,12 @@ string data in all Python versions. equivalent to :func:`py2:chr` in Python 2 and ``bytes((i,))`` in Python 3. +.. function:: byte2int(bs) + + Converts the first byte of *bs* to an integer. This is equivalent to + ``ord(bs[0])`` on Python 2 and ``bs[0]`` on Python 3. + + .. function:: indexbytes(buf, i) Return the byte at index *i* of *buf* as an integer. This is equivalent to @@ -311,6 +311,7 @@ if PY3: else: # This is about 2x faster than the implementation above on 3.2+ int2byte = operator.methodcaller("to_bytes", 1, "big") + byte2int = operator.itemgetter(0) indexbytes = operator.getitem iterbytes = iter import io @@ -322,6 +323,8 @@ else: def u(s): return unicode(s, "unicode_escape") int2byte = chr + def byte2int(bs): + return ord(bs[0]) def indexbytes(buf, i): return ord(buf[i]) def iterbytes(buf): diff --git a/test_six.py b/test_six.py index 7e15a1c..3983528 100644 --- a/test_six.py +++ b/test_six.py @@ -356,6 +356,12 @@ def test_int2byte(): py.test.raises((OverflowError, ValueError), six.int2byte, 256) +def test_byte2int(): + assert six.byte2int(six.b("\x03")) == 3 + assert six.byte2int(six.b("\x03\x04")) == 3 + py.test.raises(IndexError, six.byte2int, six.b("")) + + def test_bytesindex(): assert six.indexbytes(six.b("hello"), 3) == ord("l") |