git.sr.ht/~pingoo/stdx@v0.0.0-20240218134121-094174641f6e/barcode/codabar/encoder.go (about) 1 // Package codabar can create Codabar barcodes 2 package codabar 3 4 import ( 5 "fmt" 6 "regexp" 7 8 "git.sr.ht/~pingoo/stdx/barcode" 9 "git.sr.ht/~pingoo/stdx/barcode/utils" 10 ) 11 12 var encodingTable = map[rune][]bool{ 13 '0': []bool{true, false, true, false, true, false, false, true, true}, 14 '1': []bool{true, false, true, false, true, true, false, false, true}, 15 '2': []bool{true, false, true, false, false, true, false, true, true}, 16 '3': []bool{true, true, false, false, true, false, true, false, true}, 17 '4': []bool{true, false, true, true, false, true, false, false, true}, 18 '5': []bool{true, true, false, true, false, true, false, false, true}, 19 '6': []bool{true, false, false, true, false, true, false, true, true}, 20 '7': []bool{true, false, false, true, false, true, true, false, true}, 21 '8': []bool{true, false, false, true, true, false, true, false, true}, 22 '9': []bool{true, true, false, true, false, false, true, false, true}, 23 '-': []bool{true, false, true, false, false, true, true, false, true}, 24 '$': []bool{true, false, true, true, false, false, true, false, true}, 25 ':': []bool{true, true, false, true, false, true, true, false, true, true}, 26 '/': []bool{true, true, false, true, true, false, true, false, true, true}, 27 '.': []bool{true, true, false, true, true, false, true, true, false, true}, 28 '+': []bool{true, false, true, true, false, true, true, false, true, true}, 29 'A': []bool{true, false, true, true, false, false, true, false, false, true}, 30 'B': []bool{true, false, false, true, false, false, true, false, true, true}, 31 'C': []bool{true, false, true, false, false, true, false, false, true, true}, 32 'D': []bool{true, false, true, false, false, true, true, false, false, true}, 33 } 34 35 // Encode creates a codabar barcode for the given content 36 func Encode(content string) (barcode.Barcode, error) { 37 checkValid, _ := regexp.Compile(`[ABCD][0123456789\-\$\:/\.\+]*[ABCD]$`) 38 if content == "!" || checkValid.ReplaceAllString(content, "!") != "!" { 39 return nil, fmt.Errorf("can not encode \"%s\"", content) 40 } 41 resBits := new(utils.BitList) 42 for i, r := range content { 43 if i > 0 { 44 resBits.AddBit(false) 45 } 46 resBits.AddBit(encodingTable[r]...) 47 } 48 return utils.New1DCode(barcode.TypeCodabar, content, resBits), nil 49 }