git.sr.ht/~pingoo/stdx@v0.0.0-20240218134121-094174641f6e/barcode/qr/numeric.go (about) 1 package qr 2 3 import ( 4 "errors" 5 "fmt" 6 "strconv" 7 8 "git.sr.ht/~pingoo/stdx/barcode/utils" 9 ) 10 11 func encodeNumeric(content string, ecl ErrorCorrectionLevel) (*utils.BitList, *versionInfo, error) { 12 contentBitCount := (len(content) / 3) * 10 13 switch len(content) % 3 { 14 case 1: 15 contentBitCount += 4 16 case 2: 17 contentBitCount += 7 18 } 19 vi := findSmallestVersionInfo(ecl, numericMode, contentBitCount) 20 if vi == nil { 21 return nil, nil, errors.New("To much data to encode") 22 } 23 res := new(utils.BitList) 24 res.AddBits(int(numericMode), 4) 25 res.AddBits(len(content), vi.charCountBits(numericMode)) 26 27 for pos := 0; pos < len(content); pos += 3 { 28 var curStr string 29 if pos+3 <= len(content) { 30 curStr = content[pos : pos+3] 31 } else { 32 curStr = content[pos:] 33 } 34 35 i, err := strconv.Atoi(curStr) 36 if err != nil || i < 0 { 37 return nil, nil, fmt.Errorf("\"%s\" can not be encoded as %s", content, Numeric) 38 } 39 var bitCnt byte 40 switch len(curStr) % 3 { 41 case 0: 42 bitCnt = 10 43 case 1: 44 bitCnt = 4 45 break 46 case 2: 47 bitCnt = 7 48 break 49 } 50 51 res.AddBits(i, bitCnt) 52 } 53 54 addPaddingAndTerminator(res, vi) 55 return res, vi, nil 56 }