decodeNumeric decodes PostgreSQL binary numeric format into a string.
(data []byte)
| 984 | |
| 985 | // decodeNumeric decodes PostgreSQL binary numeric format into a string. |
| 986 | func decodeNumeric(data []byte) (string, error) { |
| 987 | if len(data) < 8 { |
| 988 | return "", fmt.Errorf("insufficient data for numeric: got %d bytes, need at least 8", len(data)) |
| 989 | } |
| 990 | |
| 991 | ndigits := int(binary.BigEndian.Uint16(data[0:])) |
| 992 | weight := int16(binary.BigEndian.Uint16(data[2:])) |
| 993 | sign := binary.BigEndian.Uint16(data[4:]) |
| 994 | dscale := int(binary.BigEndian.Uint16(data[6:])) |
| 995 | |
| 996 | if len(data) < 8+2*ndigits { |
| 997 | return "", fmt.Errorf("insufficient data for numeric digits: got %d bytes, need %d", len(data), 8+2*ndigits) |
| 998 | } |
| 999 | |
| 1000 | // Special values |
| 1001 | if sign == 0xC000 { |
| 1002 | return "NaN", nil |
| 1003 | } |
| 1004 | |
| 1005 | // Read base-10000 digits |
| 1006 | digits := make([]int16, ndigits) |
| 1007 | for i := 0; i < ndigits; i++ { |
| 1008 | digits[i] = int16(binary.BigEndian.Uint16(data[8+2*i:])) |
| 1009 | } |
| 1010 | |
| 1011 | // Reconstruct the unscaled value |
| 1012 | val := new(big.Int) |
| 1013 | base := big.NewInt(10000) |
| 1014 | for _, d := range digits { |
| 1015 | val.Mul(val, base) |
| 1016 | val.Add(val, big.NewInt(int64(d))) |
| 1017 | } |
| 1018 | |
| 1019 | // The digits represent: sum(digits[i] * 10000^(weight-i)) |
| 1020 | // After reading all ndigits groups, we have val * 10000^(weight - ndigits + 1) |
| 1021 | // We need to convert to a fixed-point number with dscale decimal places. |
| 1022 | // Exponent in terms of decimal digits: 4 * (weight - ndigits + 1) |
| 1023 | exp := 4 * (int(weight) - ndigits + 1) |
| 1024 | |
| 1025 | // We want the value as: val * 10^exp, displayed with dscale decimal places. |
| 1026 | // Shift so we have dscale fractional digits: multiply by 10^(dscale + exp) |
| 1027 | shift := dscale + exp |
| 1028 | if shift > 0 { |
| 1029 | factor := new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(shift)), nil) |
| 1030 | val.Mul(val, factor) |
| 1031 | } else if shift < 0 { |
| 1032 | factor := new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(-shift)), nil) |
| 1033 | val.Div(val, factor) |
| 1034 | } |
| 1035 | |
| 1036 | // Now val is the unscaled integer with dscale implied decimal places |
| 1037 | negative := sign == 0x4000 |
| 1038 | if negative { |
| 1039 | val.Neg(val) |
| 1040 | } |
| 1041 | |
| 1042 | // Format as decimal string |
| 1043 | str := val.String() |