Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 12 additions & 10 deletions barcode/codex.py
Original file line number Diff line number Diff line change
Expand Up @@ -191,16 +191,14 @@ def _is_char_fnc1_char(self, char):

def _maybe_switch_charset(self, pos: int) -> list[int]:
char = self.code[pos]
next_ = self.code[pos : pos + 10]

def look_next() -> bool:
digits = 0
for c in next_:
if c.isdigit():
digits += 1
else:
break
return digits > 3
if pos == 0 and self._is_char_fnc1_char(self.code[0]):
return True

minimum_sequential_digits = 4
code_slice = self.code[pos : pos + minimum_sequential_digits]
return len(code_slice) == minimum_sequential_digits and code_slice.isdigit()

codes: list[int] = []
if self._charset == "C" and not char.isdigit():
Expand Down Expand Up @@ -267,8 +265,12 @@ def _convert_or_buffer(self, char: str) -> int | None:
raise RuntimeError(f"Character {char} could not be converted in charset C.")

def _try_to_optimize(self, encoded: list[int]) -> list[int]:
if encoded[1] in code128.TO:
encoded[:2] = [code128.TO[encoded[1]]]
if len(encoded) < 2 or encoded[0] not in (code128.START_CODES["A"], code128.START_CODES["B"], code128.START_CODES["C"]):
return encoded

if encoded[1] in code128.TO and not ((encoded[0] == code128.START_CODES["C"]) and (encoded[1] < 100)):
return [code128.TO[encoded[1]]] + encoded[2:]

return encoded

def _calculate_checksum(self, encoded: list[int]) -> int:
Expand Down
12 changes: 12 additions & 0 deletions tests/test_builds.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

from barcode import get_barcode
from barcode.charsets.code128 import START_CODES, CODES


def test_ean8_builds() -> None:
Expand All @@ -15,3 +16,14 @@ def test_ean8_builds_with_longer_bars() -> None:
ean = get_barcode("ean8", "40267708", options={"guardbar": True})
bc = ean.build()
assert ref == bc[0]


def test_code128_builds() -> None:
gen_000000 = get_barcode("code128", "000000")
code_000000 = gen_000000.build()
gen_999999 = get_barcode("code128", "999999")
gen_999999._charset = "B" ## this will be swapped to C.
code_999999 = gen_999999.build()
assert gen_999999._charset == "C"
assert len(code_000000[0]) == len(code_999999[0])
assert code_000000[0].startswith(CODES[START_CODES["C"]])