Skip to content

Commit 2bbb935

Browse files
committed
Distinguish between buffered and unbuffered code128 conversion
1 parent 06eb1a7 commit 2bbb935

File tree

1 file changed

+23
-2
lines changed

1 file changed

+23
-2
lines changed

barcode/codex.py

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -197,12 +197,33 @@ def look_next():
197197
codes = self._new_charset("B")
198198
return codes
199199

200-
def _convert(self, char):
200+
def _convert(self, char: str) -> int:
201+
"""Convert a character to a code number for the current charset.
202+
203+
NOTE: encoding digits with charset C requires buffering and is not supported
204+
here. Use _convert_or_buffer instead.
205+
"""
201206
if self._charset == "A":
202207
return code128.A[char]
203208
if self._charset == "B":
204209
return code128.B[char]
205210
if self._charset == "C":
211+
if char in ["TO_A", "TO_B"]:
212+
return code128.C[char]
213+
raise RuntimeError("Use _convert_or_buffer for charset C.")
214+
raise RuntimeError(
215+
f"Character {char} could not be converted in charset {self._charset}."
216+
)
217+
218+
def _convert_or_buffer(self, char: str) -> int | None:
219+
"""Convert a character to a code number for the current charset.
220+
221+
If charset C is active then digits are encoded in pairs. When the first digit
222+
is encountered, it is buffered and None is returned.
223+
"""
224+
if self._charset != "C":
225+
return self._convert(char)
226+
else:
206227
if char in code128.C:
207228
return code128.C[char]
208229
if char.isdigit():
@@ -230,7 +251,7 @@ def _build(self):
230251
encoded = [code128.START_CODES[self._charset]]
231252
for i, char in enumerate(self.code):
232253
encoded.extend(self._maybe_switch_charset(i))
233-
code_num = self._convert(char)
254+
code_num = self._convert_or_buffer(char)
234255
if code_num is not None:
235256
encoded.append(code_num)
236257
# Finally look in the buffer

0 commit comments

Comments
 (0)