MCPcopy Create free account
hub / github.com/Moddable-OpenSource/moddable / calcSegmentBitLength

Function calcSegmentBitLength

modules/data/qrcode/qrcodegen.c:732–771  ·  view source on GitHub ↗

Returns the number of data bits needed to represent a segment containing the given number of characters using the given mode. Notes: - Returns -1 on failure, i.e. numChars > INT16_MAX or the number of needed bits exceeds INT16_MAX (i.e. 32767). - Otherwise, all valid results are in the range [0, INT16_MAX]. - For byte mode, numChars measures the number of bytes, not Unicode code points. - For ECI

Source from the content-addressed store, hash-verified

730// - For ECI mode, numChars must be 0, and the worst-case number of bits is returned.
731// An actual ECI segment can have shorter data. For non-ECI modes, the result is exact.
732testable int calcSegmentBitLength(enum qrcodegen_Mode mode, size_t numChars) {
733 const int LIMIT = INT16_MAX; // Can be configured as high as INT_MAX
734 if (numChars > (unsigned int)LIMIT)
735 return -1;
736 int n = (int)numChars;
737
738 int result = -2;
739 if (mode == qrcodegen_Mode_NUMERIC) {
740 // n * 3 + ceil(n / 3)
741 if (n > LIMIT / 3)
742 goto overflow;
743 result = n * 3;
744 int temp = n / 3 + (n % 3 == 0 ? 0 : 1);
745 if (temp > LIMIT - result)
746 goto overflow;
747 result += temp;
748 } else if (mode == qrcodegen_Mode_ALPHANUMERIC) {
749 // n * 5 + ceil(n / 2)
750 if (n > LIMIT / 5)
751 goto overflow;
752 result = n * 5;
753 int temp = n / 2 + n % 2;
754 if (temp > LIMIT - result)
755 goto overflow;
756 result += temp;
757 } else if (mode == qrcodegen_Mode_BYTE) {
758 if (n > LIMIT / 8)
759 goto overflow;
760 result = n * 8;
761 } else if (mode == qrcodegen_Mode_KANJI) {
762 if (n > LIMIT / 13)
763 goto overflow;
764 result = n * 13;
765 } else if (mode == qrcodegen_Mode_ECI && numChars == 0)
766 result = 3 * 8;
767 assert(0 <= result && result <= LIMIT);
768 return result;
769overflow:
770 return -1;
771}
772
773
774// Public function - see documentation comment in header file.

Callers 6

qrcodegen_encodeTextFunction · 0.85
qrcodegen_encodeBinaryFunction · 0.85
qrcodegen_makeBytesFunction · 0.85
qrcodegen_makeNumericFunction · 0.85

Calls 1

assertFunction · 0.50

Tested by

no test coverage detected