unit Myc.Data.Decimal;

interface

type
    TScale = 0..7;

    TDecimal = record
    strict private
        FValue: Int64;
    public
        constructor Create(AValue: Int64; AScale: TScale); overload;
        constructor Create(AValue: Double; AScale: TScale); overload;
        constructor Create(const AValue: TDecimal; ANewScale: TScale); overload;

        class operator Add(const A, B: TDecimal): TDecimal; inline;
        class operator Subtract(const A, B: TDecimal): TDecimal; inline;
        class operator Multiply(const A, B: TDecimal): TDecimal;
        class operator Divide(const A, B: TDecimal): TDecimal;

        class operator Equal(const A, B: TDecimal): Boolean; inline;
        class operator NotEqual(const A, B: TDecimal): Boolean; inline;
        class operator GreaterThan(const A, B: TDecimal): Boolean; inline;
        class operator GreaterThanOrEqual(const A, B: TDecimal): Boolean; inline;
        class operator LessThan(const A, B: TDecimal): Boolean; inline;
        class operator LessThanOrEqual(const A, B: TDecimal): Boolean; inline;
        class operator Negative(const A: TDecimal): TDecimal; inline;
        class operator Round(const A: TDecimal): Int64;
        class operator Trunc(const A: TDecimal): Int64;

        class operator Implicit(const A: Int64): TDecimal; inline;
        class operator Explicit(const A: TDecimal): Double;

        class function MinValue(AScale: TScale): TDecimal; static;
        class function MaxValue(AScale: TScale): TDecimal; static;

        function Sign: Integer; inline;
        function Abs: TDecimal; inline;

        function GetValue: Int64;
        function GetScale: TScale;
        function GetRawValue: Int64; inline;
    end;

implementation

uses
    System.SysUtils,
    System.Math;

const
    SCALE_BITS = 3;
    VALUE_BITS = 61;
    SCALE_MASK = $07;

    // CRITICAL FIX: Cast '1' to Int64 to force 64-bit constant evaluation.
    MIN_VALUE_61BIT = -(Int64(1) shl 60);
    MAX_VALUE_61BIT = (Int64(1) shl 60) - 1;
    SIGN_BIT_61 = Int64(1) shl (VALUE_BITS - 1); // Bit 60 for sign check
    RAW_VALUE_MASK = (Int64(1) shl VALUE_BITS) - 1; // Mask for bits 0..60

    // Use a lookup table for powers of 10 for performance
    PowersOf10: array[TScale] of Int64 = (1, 10, 100, 1000, 10000, 100000, 1000000, 10000000);

{ TDecimal }

constructor TDecimal.Create(AValue: Int64; AScale: TScale);
begin
    // Validate that the incoming value fits within the 61-bit storage.
    if (AValue < MIN_VALUE_61BIT) or (AValue > MAX_VALUE_61BIT) then
        raise EOverflow.Create('Value is out of range for a 61-bit TDecimal.');

    FValue := (Int64(AScale) shl VALUE_BITS) or (AValue and RAW_VALUE_MASK);
end;

constructor TDecimal.Create(const AValue: TDecimal; ANewScale: TScale);
begin
    // Create a new decimal by changing the scale of an existing one.
    var oldScale := AValue.GetScale;
    if oldScale = ANewScale then
    begin
        FValue := AValue.FValue;
        exit;
    end;

    var newValue := AValue.GetValue;
    var scaleDiff := ANewScale - oldScale;

    if scaleDiff > 0 then
    begin
        // Increasing scale: multiply by 10^scaleDiff, checking for overflow at each step.
        for var i := 1 to scaleDiff do
        begin
            if newValue > (MAX_VALUE_61BIT div 10) then
                raise EOverflow.Create('Decimal scale up resulted in an overflow.');
            if newValue < (MIN_VALUE_61BIT div 10) then
                raise EOverflow.Create('Decimal scale up resulted in an overflow.');
            newValue := newValue * 10;
        end;
    end
    else
    begin
        // Decreasing scale: divide by 10^(-scaleDiff). Overflow is not an issue here.
        newValue := newValue div PowersOf10[-scaleDiff];
    end;

    // Pack the new value and scale
    FValue := (Int64(ANewScale) shl VALUE_BITS) or (newValue and RAW_VALUE_MASK);
end;

constructor TDecimal.Create(AValue: Double; AScale: TScale);
begin
    // Scale the double by the specified scale and round it to the nearest integer.
    // Round() will raise an exception if the value exceeds the Int64 range.
    var intValue := Round(AValue * PowersOf10[AScale]);

    // Check if the resulting value fits within the 61-bit storage.
    if (intValue < MIN_VALUE_61BIT) or (intValue > MAX_VALUE_61BIT) then
        raise EOverflow.Create('Double to TDecimal conversion resulted in an overflow.');

    // Pack the value and scale into FValue.
    FValue := (Int64(AScale) shl VALUE_BITS) or (intValue and RAW_VALUE_MASK);
end;

function TDecimal.Abs: TDecimal;
begin
    if GetValue < 0 then
        Result := -Self
    else
        Result := Self;
end;

class operator TDecimal.Add(const A, B: TDecimal): TDecimal;
begin
    var aScale := A.GetScale;
    var bScale := B.GetScale;

    // Fast path for performance when scales are identical
    if aScale = bScale then
    begin
        Result := TDecimal.Create(A.GetValue + B.GetValue, aScale);
        exit;
    end;

    // Slower path for different scales: align scales before operation
    if aScale > bScale then
    begin
        var scaledB := TDecimal.Create(B, aScale);
        Result := TDecimal.Create(A.GetValue + scaledB.GetValue, aScale);
    end
    else
    begin
        var scaledA := TDecimal.Create(A, bScale);
        Result := TDecimal.Create(scaledA.GetValue + B.GetValue, bScale);
    end;
end;

class operator TDecimal.Subtract(const A, B: TDecimal): TDecimal;
begin
    var aScale := A.GetScale;
    var bScale := B.GetScale;

    // Fast path for performance when scales are identical
    if aScale = bScale then
    begin
        Result := TDecimal.Create(A.GetValue - B.GetValue, aScale);
        exit;
    end;

    // Slower path for different scales: align scales before operation
    if aScale > bScale then
    begin
        var scaledB := TDecimal.Create(B, aScale);
        Result := TDecimal.Create(A.GetValue - scaledB.GetValue, aScale);
    end
    else
    begin
        var scaledA := TDecimal.Create(A, bScale);
        Result := TDecimal.Create(scaledA.GetValue - B.GetValue, bScale);
    end;
end;

class operator TDecimal.Multiply(const A, B: TDecimal): TDecimal;
begin
    var scaleA := A.GetScale;
    var scaleB := B.GetScale;

    if scaleA = scaleB then
    begin
        // Fast path for performance when scales are identical
        var resultValue := MulDivInt64(A.GetValue, B.GetValue, PowersOf10[scaleA]);
        Result := TDecimal.Create(resultValue, scaleA);
    end
    else
    begin
        // Slower path for different scales
        var targetScale := Max(scaleA, scaleB);
        var resultValue := MulDivInt64(A.GetValue, B.GetValue, PowersOf10[Min(scaleA, scaleB)]);
        Result := TDecimal.Create(resultValue, targetScale);
    end;
end;

class operator TDecimal.Divide(const A, B: TDecimal): TDecimal;
begin
    var bVal := B.GetValue;
    if bVal = 0 then
        raise EDivByZero.Create('Division by zero');

    var aScale := A.GetScale;
    var bScale := B.GetScale;

    // Fast path for performance when scales are identical
    if aScale = bScale then
    begin
        var resultValue := MulDivInt64(A.GetValue, PowersOf10[aScale], bVal);
        Result := TDecimal.Create(resultValue, aScale);
        exit;
    end;

    // Slower path for different scales: align scales before operation
    if aScale > bScale then
    begin
        var targetScale := aScale;
        var tempB := TDecimal.Create(B, targetScale);
        var resultValue := MulDivInt64(A.GetValue, PowersOf10[targetScale], tempB.GetValue);
        Result := TDecimal.Create(resultValue, targetScale);
    end
    else // bScale > aScale
    begin
        var targetScale := bScale;
        var tempA := TDecimal.Create(A, targetScale);
        var resultValue := MulDivInt64(tempA.GetValue, PowersOf10[targetScale], bVal);
        Result := TDecimal.Create(resultValue, targetScale);
    end;
end;

class operator TDecimal.Equal(const A, B: TDecimal): Boolean;
begin
    var aScale := A.GetScale;
    var bScale := B.GetScale;

    // Fast path for identical scales
    if aScale = bScale then
    begin
        Result := (A.GetValue = B.GetValue);
        exit;
    end;

    // Slower path: align scales before comparing values
    if aScale > bScale then
    begin
        var scaledB := TDecimal.Create(B, aScale);
        Result := (A.GetValue = scaledB.GetValue);
    end
    else // bScale > aScale
    begin
        var scaledA := TDecimal.Create(A, bScale);
        Result := (scaledA.GetValue = B.GetValue);
    end;
end;

class operator TDecimal.NotEqual(const A, B: TDecimal): Boolean;
begin
    Result := not (A = B);
end;

class operator TDecimal.GreaterThan(const A, B: TDecimal): Boolean;
begin
    var aScale := A.GetScale;
    var bScale := B.GetScale;

    // Fast path for identical scales
    if aScale = bScale then
    begin
        Result := (A.GetValue > B.GetValue);
        exit;
    end;

    // Slower path: align scales before comparing values
    if aScale > bScale then
    begin
        var scaledB := TDecimal.Create(B, aScale);
        Result := (A.GetValue > scaledB.GetValue);
    end
    else // bScale > aScale
    begin
        var scaledA := TDecimal.Create(A, bScale);
        Result := (scaledA.GetValue > B.GetValue);
    end;
end;

class operator TDecimal.GreaterThanOrEqual(const A, B: TDecimal): Boolean;
begin
    // Reuse existing operators for consistency
    Result := not (A < B);
end;

class operator TDecimal.LessThan(const A, B: TDecimal): Boolean;
begin
    // Reuse existing operators for consistency
    Result := (B > A);
end;

class operator TDecimal.LessThanOrEqual(const A, B: TDecimal): Boolean;
begin
    // Reuse existing operators for consistency
    Result := not (A > B);
end;

class operator TDecimal.Negative(const A: TDecimal): TDecimal;
begin
    // Negate the value, keep the scale
    Result := TDecimal.Create(-A.GetValue, A.GetScale);
end;

class operator TDecimal.Round(const A: TDecimal): Int64;
var
    value: Int64;
    divisor: Int64;
begin
    value := A.GetValue;
    divisor := PowersOf10[A.GetScale];
    if value >= 0 then
        Result := (value + divisor div 2) div divisor
    else
        Result := (value - divisor div 2) div divisor;
end;

class operator TDecimal.Trunc(const A: TDecimal): Int64;
begin
    Result := A.GetValue div PowersOf10[A.GetScale];
end;

class operator TDecimal.Implicit(const A: Int64): TDecimal;
begin
    // Correctly create a TDecimal with scale 0
    Result := TDecimal.Create(A, 0);
end;

class operator TDecimal.Explicit(const A: TDecimal): Double;
begin
    Result := A.GetValue / PowersOf10[A.GetScale];
end;

class function TDecimal.MaxValue(AScale: TScale): TDecimal;
begin
    Result := TDecimal.Create(MAX_VALUE_61BIT, AScale);
end;

class function TDecimal.MinValue(AScale: TScale): TDecimal;
begin
    Result := TDecimal.Create(MIN_VALUE_61BIT, AScale);
end;

function TDecimal.GetValue: Int64;
var
    value: Int64;
begin
    value := FValue and RAW_VALUE_MASK;
    // Perform sign extension from 61 to 64 bits
    if (value and SIGN_BIT_61) <> 0 then
        Result := value or (not RAW_VALUE_MASK)
    else
        Result := value;
end;

function TDecimal.GetScale: TScale;
begin
    Result := TScale((FValue shr VALUE_BITS) and SCALE_MASK);
end;

function TDecimal.GetRawValue: Int64;
begin
    Result := FValue;
end;

function TDecimal.Sign: Integer;
begin
    var val := GetValue;
    if val < 0 then
        exit(-1);
    if val > 0 then
        exit(-1);
    exit(0);
end;

end.
