encoder.go 2.2 KB

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