|
| 1 | +// Package decimal implements methods to encode and decode BCD. |
| 2 | +// |
| 3 | +// BCD (Binary-Coded Decimal) is a sequence of bytes representing decimal |
| 4 | +// digits of the encoded number (each byte has two decimal digits each encoded |
| 5 | +// using 4-bit nibbles), so byte >> 4 is the first digit and byte & 0x0f is the |
| 6 | +// second digit. The leftmost digit in the array is the most significant. The |
| 7 | +// rightmost digit in the array is the least significant. |
| 8 | +// |
| 9 | +// The first byte of the BCD array contains the first digit of the number, |
| 10 | +// represented as follows: |
| 11 | +// |
| 12 | +// | 4 bits | 4 bits | |
| 13 | +// = 0x = the 1st digit |
| 14 | +// |
| 15 | +// (The first nibble contains 0 if the decimal number has an even number of |
| 16 | +// digits). The last byte of the BCD array contains the last digit of the |
| 17 | +// number and the final nibble, represented as follows: |
| 18 | +// |
| 19 | +// | 4 bits | 4 bits | |
| 20 | +// = the last digit = nibble |
| 21 | +// |
| 22 | +// The final nibble represents the number's sign: 0x0a, 0x0c, 0x0e, 0x0f stand |
| 23 | +// for plus, 0x0b and 0x0d stand for minus. |
| 24 | +// |
| 25 | +// Examples: |
| 26 | +// |
| 27 | +// The decimal -12.34 will be encoded as 0xd6, 0x01, 0x02, 0x01, 0x23, 0x4d: |
| 28 | +// |
| 29 | +// |MP_EXT (fixext 4) | MP_DECIMAL | scale | 1 | 2,3 | 4 (minus) | |
| 30 | +// | 0xd6 | 0x01 | 0x02 | 0x01 | 0x23 | 0x4d | |
| 31 | +// |
| 32 | +// The decimal 0.000000000000000000000000000000000010 will be encoded as |
| 33 | +// 0xc7, 0x03, 0x01, 0x24, 0x01, 0x0c: |
| 34 | +// |
| 35 | +// | MP_EXT (ext 8) | length | MP_DECIMAL | scale | 1 | 0 (plus) | |
| 36 | +// | 0xc7 | 0x03 | 0x01 | 0x24 | 0x01 | 0x0c | |
| 37 | +// |
| 38 | +// See also: |
| 39 | +// |
| 40 | +// * MessagePack extensions https://www.tarantool.io/en/doc/latest/dev_guide/internals/msgpack_extensions/ |
| 41 | +// |
| 42 | +// * An implementation in C language https://github.com/tarantool/decNumber/blob/master/decPacked.c |
| 43 | +package decimal |
| 44 | + |
| 45 | +import ( |
| 46 | + "fmt" |
| 47 | + "strings" |
| 48 | +) |
| 49 | + |
| 50 | +const ( |
| 51 | + bytePlus = byte(0x0c) |
| 52 | + byteMinus = byte(0x0d) |
| 53 | +) |
| 54 | + |
| 55 | +var isNegative = map[byte]bool{ |
| 56 | + 0x0a: false, |
| 57 | + 0x0b: true, |
| 58 | + 0x0c: false, |
| 59 | + 0x0d: true, |
| 60 | + 0x0e: false, |
| 61 | + 0x0f: false, |
| 62 | +} |
| 63 | + |
| 64 | +// Calculate a number of digits in a buffer with decimal number. |
| 65 | +// |
| 66 | +// Plus, minus, point and leading zeros do not count. |
| 67 | +// Contains a quirk for a zero - returns 1. |
| 68 | +// |
| 69 | +// Examples (see more examples in tests): |
| 70 | +// |
| 71 | +// - 0.0000000000000001 - 1 digit |
| 72 | +// |
| 73 | +// - 00012.34 - 4 digits |
| 74 | +// |
| 75 | +// - 0.340 - 3 digits |
| 76 | +// |
| 77 | +// - 0 - 1 digit |
| 78 | +func GetNumberLength(buf string) int { |
| 79 | + if len(buf) == 0 { |
| 80 | + return 0 |
| 81 | + } |
| 82 | + n := 0 |
| 83 | + for _, ch := range []byte(buf) { |
| 84 | + if ch == '0' && n != 0 { |
| 85 | + n += 1 |
| 86 | + continue |
| 87 | + } |
| 88 | + if ch >= '1' && ch <= '9' { |
| 89 | + n += 1 |
| 90 | + } |
| 91 | + } |
| 92 | + |
| 93 | + // Fix a case with a single 0. |
| 94 | + if n == 0 { |
| 95 | + n = 1 |
| 96 | + } |
| 97 | + |
| 98 | + return n |
| 99 | +} |
| 100 | + |
| 101 | +// EncodeStringToBCD converts a string buffer to BCD Packed Decimal. |
| 102 | +// |
| 103 | +// The number is converted to a BCD packed decimal byte array, right aligned in |
| 104 | +// the BCD array, whose length is indicated by the second parameter. The final |
| 105 | +// 4-bit nibble in the array will be a sign nibble, 0x0c for "+" and 0x0d for |
| 106 | +// "-". Unused bytes and nibbles to the left of the number are set to 0. scale |
| 107 | +// is set to the scale of the number (this is the exponent, negated). |
| 108 | +func EncodeStringToBCD(buf string) ([]byte, error) { |
| 109 | + if len(buf) == 0 { |
| 110 | + return nil, fmt.Errorf("Length of number is zero") |
| 111 | + } |
| 112 | + signByte := bytePlus // By default number is positive. |
| 113 | + if buf[0] == '-' { |
| 114 | + signByte = byteMinus |
| 115 | + } |
| 116 | + |
| 117 | + // The first nibble should contain 0, if the decimal number has an even |
| 118 | + // number of digits. Therefore highNibble is false when decimal number |
| 119 | + // is even. |
| 120 | + highNibble := true |
| 121 | + l := GetNumberLength(buf) |
| 122 | + if l%2 == 0 { |
| 123 | + highNibble = false |
| 124 | + } |
| 125 | + scale := 0 // By default decimal number is integer. |
| 126 | + var byteBuf []byte |
| 127 | + for i, ch := range []byte(buf) { |
| 128 | + // Skip leading zeros. |
| 129 | + if (len(byteBuf) == 0) && ch == '0' { |
| 130 | + continue |
| 131 | + } |
| 132 | + if (i == 0) && (ch == '-' || ch == '+') { |
| 133 | + continue |
| 134 | + } |
| 135 | + if ch == '.' && scale != 0 { |
| 136 | + return nil, fmt.Errorf("Number contains more than one point") |
| 137 | + } |
| 138 | + // Calculate a number of digits after the decimal point. |
| 139 | + if ch == '.' { |
| 140 | + scale = len(buf) - i - 1 |
| 141 | + continue |
| 142 | + } |
| 143 | + |
| 144 | + if ch < '0' || ch > '9' { |
| 145 | + return nil, fmt.Errorf("Failed to convert symbol '%c' to a digit", ch) |
| 146 | + } |
| 147 | + digit := byte(ch - '0') |
| 148 | + if highNibble { |
| 149 | + // Add a digit to a high nibble. |
| 150 | + digit = digit << 4 |
| 151 | + byteBuf = append(byteBuf, digit) |
| 152 | + highNibble = false |
| 153 | + } else { |
| 154 | + if len(byteBuf) == 0 { |
| 155 | + byteBuf = make([]byte, 1) |
| 156 | + } |
| 157 | + // Add a digit to a low nibble. |
| 158 | + lowByteIdx := len(byteBuf) - 1 |
| 159 | + byteBuf[lowByteIdx] = byteBuf[lowByteIdx] | digit |
| 160 | + highNibble = true |
| 161 | + } |
| 162 | + } |
| 163 | + if highNibble { |
| 164 | + // Put a sign to a high nibble. |
| 165 | + byteBuf = append(byteBuf, signByte) |
| 166 | + } else { |
| 167 | + // Put a sign to a low nibble. |
| 168 | + lowByteIdx := len(byteBuf) - 1 |
| 169 | + byteBuf[lowByteIdx] = byteBuf[lowByteIdx] | signByte |
| 170 | + } |
| 171 | + byteBuf = append([]byte{byte(scale)}, byteBuf...) |
| 172 | + |
| 173 | + return byteBuf, nil |
| 174 | +} |
| 175 | + |
| 176 | +// DecodeStringFromBCD converts a BCD Packed Decimal to a string buffer. |
| 177 | +// |
| 178 | +// The BCD packed decimal byte array, together with an associated scale, is |
| 179 | +// converted to a string. The BCD array is assumed full of digits, and must be |
| 180 | +// ended by a 4-bit sign nibble in the least significant four bits of the final |
| 181 | +// byte. The scale is used (negated) as the exponent of the decimal number. |
| 182 | +// Note that zeros may have a sign and/or a scale. |
| 183 | +func DecodeStringFromBCD(bcdBuf []byte) (string, error) { |
| 184 | + const scaleIdx = 0 // Index of a byte with scale. |
| 185 | + scale := int(bcdBuf[scaleIdx]) |
| 186 | + // Get a BCD buffer without a byte with scale. |
| 187 | + bcdBuf = bcdBuf[scaleIdx+1:] |
| 188 | + length := len(bcdBuf) |
| 189 | + var digits []string |
| 190 | + for i, bcdByte := range bcdBuf { |
| 191 | + highNibble := bcdByte >> 4 |
| 192 | + digits = append(digits, string('0'+highNibble)) |
| 193 | + lowNibble := bcdByte & 0x0f |
| 194 | + // lowNibble of last byte is ignored because it contains a |
| 195 | + // sign. |
| 196 | + if i != length-1 { |
| 197 | + digits = append(digits, string('0'+lowNibble)) |
| 198 | + } |
| 199 | + } |
| 200 | + |
| 201 | + // Add missing zeros when scale is less than current length. |
| 202 | + l := len(digits) |
| 203 | + if scale >= l { |
| 204 | + var zeros []string |
| 205 | + for i := 0; i <= scale-l; i++ { |
| 206 | + zeros = append(zeros, "0") |
| 207 | + } |
| 208 | + digits = append(zeros, digits...) |
| 209 | + } |
| 210 | + |
| 211 | + // Add a dot when number is fractional. |
| 212 | + if scale != 0 { |
| 213 | + idx := len(digits) - scale |
| 214 | + digits = append(digits, "X") // [1 2 3 X] |
| 215 | + copy(digits[idx:], digits[idx-1:]) // [1 2 2 3] |
| 216 | + digits[idx] = "." // [1 . 2 3] |
| 217 | + } |
| 218 | + |
| 219 | + // Add a sign, it is encoded in a low nibble of a last byte. |
| 220 | + lastByte := bcdBuf[length-1] |
| 221 | + sign := lastByte & 0x0f |
| 222 | + if isNegative[sign] { |
| 223 | + digits = append([]string{"-"}, digits...) |
| 224 | + } |
| 225 | + |
| 226 | + // Merge slice to a single string. |
| 227 | + str := strings.Join(digits, "") |
| 228 | + |
| 229 | + return str, nil |
| 230 | +} |
0 commit comments