From 2b2421afb93a956727a9856a9c9a258a697bcf19 Mon Sep 17 00:00:00 2001 From: Burak Yigit Kaya Date: Thu, 14 Nov 2024 10:55:47 +0000 Subject: [PATCH 1/3] fix: Remove unnecessary string casting of `bytes` --- src/hpack/hpack.py | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/hpack/hpack.py b/src/hpack/hpack.py index cc39bfd..8d72c22 100644 --- a/src/hpack/hpack.py +++ b/src/hpack/hpack.py @@ -147,10 +147,13 @@ def _to_bytes(string): """ Convert string to bytes. """ - if not isinstance(string, basestring): # pragma: no cover - string = str(string) + if isinstance(string, bytes): + return string - return string if isinstance(string, bytes) else string.encode('utf-8') + # Not doing an `isinstance(string, basestring)` check here + # as the cost of it is the same as just running `str()` on + # an object that is already a string + return str(string).encode("utf-8") class Encoder: From 10a3faedcdfc1617840ab5f1fe425d2f2d5b3659 Mon Sep 17 00:00:00 2001 From: Burak Yigit Kaya Date: Fri, 15 Nov 2024 13:38:43 +0000 Subject: [PATCH 2/3] even faster --- src/hpack/hpack.py | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/hpack/hpack.py b/src/hpack/hpack.py index 8d72c22..4f4e2e8 100644 --- a/src/hpack/hpack.py +++ b/src/hpack/hpack.py @@ -147,13 +147,12 @@ def _to_bytes(string): """ Convert string to bytes. """ - if isinstance(string, bytes): + t = type(string) + if t is bytes: return string - - # Not doing an `isinstance(string, basestring)` check here - # as the cost of it is the same as just running `str()` on - # an object that is already a string - return str(string).encode("utf-8") + if t is not str: + string = str(string) + return string.encode("utf-8") class Encoder: From fb65910e49f98b137ea6ae5936980eafc67271cc Mon Sep 17 00:00:00 2001 From: Burak Yigit Kaya Date: Sat, 16 Nov 2024 16:49:36 +0000 Subject: [PATCH 3/3] better naming and comment --- src/hpack/hpack.py | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/hpack/hpack.py b/src/hpack/hpack.py index 4f4e2e8..612bfbd 100644 --- a/src/hpack/hpack.py +++ b/src/hpack/hpack.py @@ -143,16 +143,16 @@ def _dict_to_iterable(header_dict): yield key, header_dict[key] -def _to_bytes(string): +def _to_bytes(value): """ - Convert string to bytes. + Convert anything to bytes through a UTF-8 encoded string """ - t = type(string) + t = type(value) if t is bytes: - return string + return value if t is not str: - string = str(string) - return string.encode("utf-8") + value = str(value) + return value.encode("utf-8") class Encoder: