Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/Arrow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,7 @@ import * as util_math_ from './util/math.js';
import * as util_buffer_ from './util/buffer.js';
import * as util_vector_ from './util/vector.js';
import * as util_pretty_ from './util/pretty.js';
import * as util_decimal_ from './util/decimal.js';

import * as util_interval_ from './util/interval.js';
export type * from './util/interval.js';
Expand All @@ -122,6 +123,7 @@ export const util = {
...util_buffer_,
...util_vector_,
...util_pretty_,
...util_decimal_,
...util_interval_,
compareSchemas,
compareFields,
Expand Down
226 changes: 226 additions & 0 deletions src/util/decimal.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,226 @@
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.

/**
* Determine if a decimal value is negative by checking the sign bit.
* Follows the two's complement representation used in Arrow decimals.
* @param value The Uint32Array representing the decimal value
* @returns true if the value is negative, false otherwise
* @ignore
*/
export function isNegativeDecimal(value: Uint32Array): boolean {
// Check the sign bit of the most significant 32-bit word
// This follows the Arrow C++ implementation:
// https://github.com/apache/arrow/blob/main/cpp/src/arrow/util/basic_decimal.h
const MAX_INT32 = 2 ** 31 - 1;
return value.at(-1)! > MAX_INT32;
}

/**
* Negate a decimal value in-place using two's complement arithmetic.
* @param value The Uint32Array to negate
* @returns The negated value (modified in-place for efficiency)
* @ignore
*/
export function negateDecimal(value: Uint32Array): Uint32Array {
// Two's complement negation: flip all bits and add 1
// Follows the Arrow C++ implementation:
// https://github.com/apache/arrow/blob/main/cpp/src/arrow/util/basic_decimal.cc
let carry = 1;
for (let i = 0; i < value.length; i++) {
const elem = value[i];
const updated = ~elem + carry;
value[i] = updated >>> 0; // Ensure 32-bit unsigned
carry &= elem === 0 ? 1 : 0;
}
return value;
}

/**
* Convert a decimal value to a formatted string representation.
* Handles both Decimal128 (128-bit) and Decimal256 (256-bit) values.
*
* @param value The Uint32Array representing the decimal value
* @param scale The number of decimal places (digits after the decimal point)
* @returns A string representation of the decimal value
*
* @example
* ```ts
* import { toDecimalString } from 'apache-arrow';
*
* const value = new Uint32Array([1, 0, 0, 0]);
* const result = toDecimalString(value, 2);
* // Returns: "0.01"
* ```
* @ignore
*/
export function toDecimalString(value: Uint32Array, scale: number): string {
// Build BigInt from little-endian 4x Uint32 words
const toBigIntLE = (words: Uint32Array) => {
return (BigInt(words[3]) << BigInt(96)) |
(BigInt(words[2]) << BigInt(64)) |
(BigInt(words[1]) << BigInt(32)) |
BigInt(words[0]);
};

// Detect sign via MSB of most-significant word
const isNegative = (value[3] & 0x80000000) !== 0;
const mask128 = (BigInt(1) << BigInt(128)) - BigInt(1);

const n = toBigIntLE(value);

// If negative, convert two's complement to magnitude:
// magnitude = (~n + 1) & mask128
const magnitude: bigint = isNegative ? (((~n) + BigInt(1)) & mask128) : n;

// Magnitude as decimal string
const digits = magnitude.toString(10);

// Special-case: zero
if (magnitude === BigInt(0)) {
if (scale === 0) {
return '0';
}
// Tests expect "0.0" for zero with any positive scale
return '0.0';
}

if (scale === 0) {
const res = digits;
return isNegative ? '-' + res : res;
}

// Ensure we have at least scale digits for fractional part
let integerPart: string;
let fracPart: string;
if (digits.length <= scale) {
integerPart = '0';
fracPart = digits.padStart(scale, '0');
} else {
const split = digits.length - scale;
integerPart = digits.slice(0, split);
fracPart = digits.slice(split);
}

// Trim trailing zeros in fractional part
fracPart = fracPart.replace(/0+$/, '');

const result = fracPart === '' ? integerPart : integerPart + '.' + fracPart;
return isNegative ? '-' + result : result;
}

/**
* Convert a decimal value to a number.
* Note: This may lose precision for very large decimal values
* that exceed JavaScript's 53-bit integer precision.
*
* @param value The Uint32Array representing the decimal value
* @param scale The number of decimal places
* @returns A number representation of the decimal value
* @ignore
*/
export function toDecimalNumber(value: Uint32Array, scale: number): number {
const negative = isNegativeDecimal(value);

// Create a copy to avoid modifying the original
const valueCopy = new Uint32Array(value);
if (negative) {
negateDecimal(valueCopy);
}

// Convert to BigInt for calculation
let num = BigInt(0);
for (let i = valueCopy.length - 1; i >= 0; i--) {
num = (num << BigInt(32)) | BigInt(valueCopy[i]);
}

if (negative) {
num = -num;
}

// Apply scale
if (scale === 0) {
return Number(num);
}

// Calculate divisor as 10^scale
// Using a loop instead of BigInt exponentiation (**) for ES2015 compatibility
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we bump to something beyond es2015 for better code?

let divisor = BigInt(1);
for (let i = 0; i < scale; i++) {
divisor *= BigInt(10);
}
return Number(num) / Number(divisor);
}

/**
* Create a Decimal128 value from a string representation.
* @param str String representation (e.g., "123.45")
* @param scale The scale (number of decimal places) to use
* @returns Uint32Array representing the decimal value
*
* @example
* ```ts
* import { fromDecimalString } from 'apache-arrow';
*
* const value = fromDecimalString("123.45", 2);
* // Returns Uint32Array representing 12345 with scale 2
* ```
* @ignore
*/
export function fromDecimalString(str: string, scale: number): Uint32Array {
// Remove leading/trailing whitespace
str = str.trim();

// Detect negative
const negative = str.startsWith('-');
if (negative) {
str = str.slice(1);
}

// Split on decimal point
const [wholePart = '0', fracPart = ''] = str.split('.');

// Pad or truncate fractional part to match scale
const adjustedFrac = (fracPart + '0'.repeat(scale)).slice(0, scale);
const intStr = wholePart + adjustedFrac;

// Convert string to BigInt
let num = BigInt(intStr);

// Apply negative if needed
if (negative) {
num = -num;
}

// Convert BigInt to Uint32Array (Decimal128 = 4 x Uint32)
const result = new Uint32Array(4);

if (negative && num !== BigInt(0)) {
// Use two's complement for negative numbers
num = -(num + BigInt(1));
for (let i = 0; i < 4; i++) {
result[i] = Number((num >> BigInt(i * 32)) & BigInt(0xFFFFFFFF));
result[i] = ~result[i];
}
} else {
for (let i = 0; i < 4; i++) {
result[i] = Number((num >> BigInt(i * 32)) & BigInt(0xFFFFFFFF));
}
}

return result;
}
1 change: 1 addition & 0 deletions test/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"compilerOptions": {
"target": "ESNext",
"module": "NodeNext",
"moduleResolution": "NodeNext",
"rootDir": "../",
"allowJs": true,
"declaration": false,
Expand Down
Loading