From a90d6f65fe639ee0ff6844415d19dfcc0f18a0b2 Mon Sep 17 00:00:00 2001 From: Christoffer L Date: Wed, 1 Oct 2025 15:04:35 +0200 Subject: [PATCH] Adjust try_to_optimize and look_next --- barcode/codex.py | 22 ++++++++++++---------- tests/test_builds.py | 12 ++++++++++++ 2 files changed, 24 insertions(+), 10 deletions(-) diff --git a/barcode/codex.py b/barcode/codex.py index 9a60c31..b1d7fbe 100755 --- a/barcode/codex.py +++ b/barcode/codex.py @@ -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(): @@ -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: diff --git a/tests/test_builds.py b/tests/test_builds.py index aac11eb..0f7a114 100755 --- a/tests/test_builds.py +++ b/tests/test_builds.py @@ -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: @@ -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"]])