Skip to content

Commit f4af12a

Browse files
committed
Distinguish between buffered and unbuffered code128 conversion
1 parent 980f3ff commit f4af12a

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
@@ -209,12 +209,33 @@ def look_next() -> bool:
209209
codes = self._new_charset("B")
210210
return codes
211211

212-
def _convert(self, char: str):
212+
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():
@@ -243,7 +264,7 @@ def _build(self) -> list[int]:
243264
encoded: list[int] = [code128.START_CODES[self._charset]]
244265
for i, char in enumerate(self.code):
245266
encoded.extend(self._maybe_switch_charset(i))
246-
code_num = self._convert(char)
267+
code_num = self._convert_or_buffer(char)
247268
if code_num is not None:
248269
encoded.append(code_num)
249270
# Finally look in the buffer

0 commit comments

Comments
 (0)