| 1 | package pdf417 |
| 2 | |
| 3 | import ( |
| 4 | "regexp" |
| 5 | "math" |
| 6 | "math/big" |
| 7 | ) |
| 8 | |
| 9 | const NUMBER_SWITCH_CODE_WORD int = 902 |
| 10 | |
| 11 | type NumberEncoder struct { |
| 12 | |
| 13 | } |
| 14 | |
| 15 | func CreateNumberEncoder() *NumberEncoder { |
| 16 | return new(NumberEncoder) |
| 17 | } |
| 18 | |
| 19 | func (encoder NumberEncoder) GetName() string { |
| 20 | return "number" |
| 21 | } |
| 22 | |
| 23 | func (encoder NumberEncoder) CanEncode(char string) bool { |
| 24 | match, err := regexp.MatchString("^[0-9]{1}$", char) |
| 25 | |
| 26 | if err != nil { |
| 27 | return false |
| 28 | } |
| 29 | |
| 30 | return match |
| 31 | } |
| 32 | |
| 33 | func (encoder NumberEncoder) GetSwitchCode(data string) int { |
| 34 | return NUMBER_SWITCH_CODE_WORD |
| 35 | } |
| 36 | |
| 37 | func (encoder NumberEncoder) Encode(digits string, addSwitchCode bool) []int { |
| 38 | digitCount := len(digits) |
| 39 | chunkCount := int(math.Ceil(float64(digitCount) / float64(44))) |
| 40 | |
| 41 | codeWords := []int{} |
| 42 | |
| 43 | if (addSwitchCode) { |
| 44 | codeWords = append(codeWords, NUMBER_SWITCH_CODE_WORD) |
| 45 | } |
| 46 | |
| 47 | for i := 0; i < chunkCount; i++ { |
| 48 | start := i * 44 |
| 49 | end := start + 44 |
| 50 | if end > digitCount { |
| 51 | end = digitCount |
| 52 | } |
| 53 | chunk := digits[start:end] |
| 54 | |
| 55 | cws := encodeChunk(chunk) |
| 56 | |
| 57 | codeWords = append(codeWords, cws...) |
| 58 | } |
| 59 | |
| 60 | return codeWords |
| 61 | } |
| 62 | |
| 63 | func encodeChunk(chunkInput string) []int { |
| 64 | chunk := big.NewInt(0) |
| 65 | |
| 66 | _, ok := chunk.SetString("1" + chunkInput, 10) |
| 67 | |
| 68 | if ! ok { |
| 69 | panic("Failed converting") |
| 70 | } |
| 71 | |
| 72 | cws := []int{} |
| 73 | |
| 74 | for chunk.Cmp(big.NewInt(0)) > 0 { |
| 75 | newChunk, cw := chunk.DivMod( |
| 76 | chunk, |
| 77 | big.NewInt(900), |
| 78 | big.NewInt(0), |
| 79 | ) |
| 80 | |
| 81 | chunk = newChunk |
| 82 | |
| 83 | cws = append([]int{int(cw.Int64())}, cws...) |
| 84 | } |
| 85 | |
| 86 | return cws |
| 87 | } |