encode.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // Package code128 can create Code128 barcodes
  2. package code128
  3. import (
  4. "fmt"
  5. "strings"
  6. "unicode/utf8"
  7. "github.com/boombuler/barcode"
  8. "github.com/boombuler/barcode/utils"
  9. )
  10. func strToRunes(str string) []rune {
  11. result := make([]rune, utf8.RuneCountInString(str))
  12. i := 0
  13. for _, r := range str {
  14. result[i] = r
  15. i++
  16. }
  17. return result
  18. }
  19. func shouldUseCTable(nextRunes []rune, curEncoding byte) bool {
  20. requiredDigits := 4
  21. if curEncoding == startCSymbol {
  22. requiredDigits = 2
  23. }
  24. if len(nextRunes) < requiredDigits {
  25. return false
  26. }
  27. for i := 0; i < requiredDigits; i++ {
  28. if nextRunes[i] < '0' || nextRunes[i] > '9' {
  29. return false
  30. }
  31. }
  32. return true
  33. }
  34. func getCodeIndexList(content []rune) *utils.BitList {
  35. result := new(utils.BitList)
  36. curEncoding := byte(0)
  37. for i := 0; i < len(content); i++ {
  38. if shouldUseCTable(content[i:], curEncoding) {
  39. if curEncoding != startCSymbol {
  40. result.AddByte(startCSymbol)
  41. curEncoding = startCSymbol
  42. }
  43. idx := (content[i] - '0') * 10
  44. i++
  45. idx = idx + (content[i] - '0')
  46. result.AddByte(byte(idx))
  47. } else {
  48. if curEncoding != startBSymbol {
  49. result.AddByte(startBSymbol)
  50. curEncoding = startBSymbol
  51. }
  52. idx := strings.IndexRune(bTable, content[i])
  53. if idx < 0 {
  54. return nil
  55. }
  56. result.AddByte(byte(idx))
  57. }
  58. }
  59. fmt.Println(result.GetBytes())
  60. return result
  61. }
  62. // Encode creates a Code 128 barcode for the given content
  63. func Encode(content string) (barcode.Barcode, error) {
  64. contentRunes := strToRunes(content)
  65. if len(contentRunes) < 0 || len(contentRunes) > 80 {
  66. return nil, fmt.Errorf("content length should be between 1 and 80 runes but got %d", len(contentRunes))
  67. }
  68. idxList := getCodeIndexList(contentRunes)
  69. if idxList == nil {
  70. return nil, fmt.Errorf("\"%s\" could not be encoded", content)
  71. }
  72. result := new(utils.BitList)
  73. sum := 0
  74. for i, idx := range idxList.GetBytes() {
  75. if i == 0 {
  76. sum = int(idx)
  77. } else {
  78. sum += i * int(idx)
  79. }
  80. result.AddBit(encodingTable[idx]...)
  81. }
  82. result.AddBit(encodingTable[sum%103]...)
  83. result.AddBit(encodingTable[stopSymbol]...)
  84. return utils.New1DCode("Code 128", content, result), nil
  85. }