summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorBenjamin Peterson <benjamin@python.org>2013-06-02 22:19:26 -0700
committerBenjamin Peterson <benjamin@python.org>2013-06-02 22:19:26 -0700
commitfd2d224e3f99ddd65859f11583380746bffd20fa (patch)
tree2b0ecac5f309e083917cc1e9aac5c2008a7ebe8c
parent023bffc477711dc659a4195f02b2087989e3d3ff (diff)
downloadsix-git-fd2d224e3f99ddd65859f11583380746bffd20fa.tar.gz
add byte2int (fixes #26)
-rw-r--r--CHANGES2
-rw-r--r--documentation/index.rst6
-rw-r--r--six.py3
-rw-r--r--test_six.py6
4 files changed, 17 insertions, 0 deletions
diff --git a/CHANGES b/CHANGES
index 9387ce6..f721a40 100644
--- a/CHANGES
+++ b/CHANGES
@@ -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
diff --git a/six.py b/six.py
index 127036e..831d5f7 100644
--- a/six.py
+++ b/six.py
@@ -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")