MCPcopy Create free account
hub / github.com/Effect-TS/effect / encodeNumeric

Function encodeNumeric

packages/sql/pg/src/PgTypes.ts:660–713  ·  view source on GitHub ↗
(value: unknown)

Source from the content-addressed store, hash-verified

658const numericRegex = /^([+-])?(\d*)(?:\.(\d*))?(?:[eE]([+-]?\d+))?$/
659
660const encodeNumeric = (value: unknown): Uint8Array => {
661 const text = requireString(value, "numeric")
662 if (text === "NaN") return numericSpecial(NUMERIC_NAN)
663 if (text === "Infinity") return numericSpecial(NUMERIC_PINF)
664 if (text === "-Infinity") return numericSpecial(NUMERIC_NINF)
665
666 const match = numericRegex.exec(text)
667 if (match === null || (match[2] ?? "") + (match[3] ?? "") === "") {
668 return fail(`Expected a decimal numeric string, received "${text}"`)
669 }
670 const exponent = match[4] === undefined ? 0 : Number(match[4])
671 let digits = (match[2] ?? "") + (match[3] ?? "")
672 let scale = (match[3] ?? "").length - exponent
673 if (scale < 0) {
674 digits += "0".repeat(-scale)
675 scale = 0
676 }
677 if (scale > 0x3fff) {
678 return fail(`numeric scale ${scale} exceeds the PostgreSQL maximum`)
679 }
680
681 const rightPad = (4 - (scale % 4)) % 4
682 digits += "0".repeat(rightPad)
683 const fractionLength = scale + rightPad
684 const leftPad = (4 - ((digits.length - fractionLength) % 4)) % 4
685 digits = "0".repeat(leftPad) + digits
686
687 // Groups are read out of `digits` on demand rather than collected, so
688 // trimming the leading and trailing zero groups is two moving indices
689 // instead of an array and a `shift` per leading zero.
690 const groupAt = (index: number): number => {
691 const at = index * 4
692 return (digits.charCodeAt(at) - 48) * 1000 + (digits.charCodeAt(at + 1) - 48) * 100 +
693 (digits.charCodeAt(at + 2) - 48) * 10 + (digits.charCodeAt(at + 3) - 48)
694 }
695 const groupCount = digits.length / 4
696 let first = 0
697 while (first < groupCount && groupAt(first) === 0) first++
698 let last = groupCount
699 while (last > first && groupAt(last - 1) === 0) last--
700 const count = last - first
701 const weight = count === 0 ? 0 : (digits.length - fractionLength) / 4 - 1 - first
702
703 const sign = count > 0 && match[1] === "-" ? NUMERIC_NEG : NUMERIC_POS
704 const bytes = new Uint8Array(8 + count * 2)
705 writeInt16(bytes, 0, count)
706 writeInt16(bytes, 2, weight)
707 writeInt16(bytes, 4, sign)
708 writeInt16(bytes, 6, scale)
709 for (let i = 0; i < count; i++) {
710 writeInt16(bytes, 8 + i * 2, groupAt(first + i))
711 }
712 return bytes
713}
714
715const numericSpecial = (sign: number): Uint8Array => {
716 const bytes = new Uint8Array(8)

Callers

nothing calls this directly

Calls 7

requireStringFunction · 0.85
numericSpecialFunction · 0.85
groupAtFunction · 0.85
writeInt16Function · 0.85
failFunction · 0.70
NumberFunction · 0.50
execMethod · 0.45

Tested by

no test coverage detected