Skip to content

Commit 937249b

Browse files
committed
Distinguished between buffered and unbuffered code128 conversion
1 parent 40ab596 commit 937249b

File tree

1 file changed

+24
-1
lines changed

1 file changed

+24
-1
lines changed

barcode/codex.py

Lines changed: 24 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -210,11 +210,32 @@ def look_next() -> bool:
210210
return codes
211211

212212
def _convert(self, char: str) -> int:
213+
"""Convert a character to a code number for the current charset.
214+
215+
NOTE: encoding digits with charset C requires buffering and is not supported
216+
here. Use _convert_or_buffer instead.
217+
"""
213218
if self._charset == "A":
214219
return code128.A[char]
215220
if self._charset == "B":
216221
return code128.B[char]
217222
if self._charset == "C":
223+
if char in ["TO_A", "TO_B"]:
224+
return code128.C[char]
225+
raise RuntimeError("Use _convert_or_buffer for charset C.")
226+
raise RuntimeError(
227+
f"Character {char} could not be converted in charset {self._charset}."
228+
)
229+
230+
def _convert_or_buffer(self, char: str) -> int | None:
231+
"""Convert a character to a code number for the current charset.
232+
233+
If charset C is active then digits are encoded in pairs. When the first digit
234+
is encountered, it is buffered and None is returned.
235+
"""
236+
if self._charset != "C":
237+
return self._convert(char)
238+
else:
218239
if char in code128.C:
219240
return code128.C[char]
220241
if char.isdigit():
@@ -223,6 +244,8 @@ def _convert(self, char: str) -> int:
223244
value = int(self._buffer)
224245
self._buffer = ""
225246
return value
247+
else:
248+
return None
226249
raise RuntimeError(
227250
f"Character {char} could not be converted in charset {self._charset}."
228251
)
@@ -242,7 +265,7 @@ def _build(self) -> list[int]:
242265
encoded: list[int] = [code128.START_CODES[self._charset]]
243266
for i, char in enumerate(self.code):
244267
encoded.extend(self._maybe_switch_charset(i))
245-
code_num = self._convert(char)
268+
code_num = self._convert_or_buffer(char)
246269
if code_num is not None:
247270
encoded.append(code_num)
248271
# Finally look in the buffer

0 commit comments

Comments
 (0)