48 lines
1.5 KiB
C#
48 lines
1.5 KiB
C#
using System;
|
|
using System.Runtime.InteropServices;
|
|
|
|
namespace mbts.co2 {
|
|
[StructLayout(LayoutKind.Explicit)]
|
|
public readonly struct IntPrice : IEquatable<IntPrice> {
|
|
public static readonly IntPrice NaN = new(0,127);
|
|
|
|
[FieldOffset(0)]
|
|
readonly long _mantissa;
|
|
[FieldOffset(7)]
|
|
readonly sbyte _exponent;
|
|
|
|
public IntPrice(long mantissa, sbyte exponent) {
|
|
_mantissa = mantissa;
|
|
_exponent = exponent;
|
|
}
|
|
|
|
public long mantissa => NativePriceHelpers.decode(_mantissa);
|
|
public sbyte exponent => _exponent;
|
|
public bool is_nan => _exponent == NativePriceHelpers.COCONUT_NAN_EXPONENT;
|
|
|
|
public double price() =>
|
|
NativePriceHelpers.to_double(mantissa, exponent);
|
|
|
|
public bool Equals(IntPrice other) =>
|
|
_exponent == other._exponent && _mantissa == other._mantissa;
|
|
|
|
public override bool Equals(object obj) =>
|
|
base.Equals(obj);
|
|
|
|
public override int GetHashCode() =>
|
|
_mantissa.GetHashCode();
|
|
|
|
public override string ToString() =>
|
|
$"{price():0.00}";
|
|
|
|
public static bool operator ==(IntPrice a, IntPrice b) => a.Equals(b);
|
|
public static bool operator !=(IntPrice a, IntPrice b) => !a.Equals(b);
|
|
|
|
public static bool operator < (IntPrice a, IntPrice b) =>
|
|
a.exponent == b.exponent ? a.mantissa < b.mantissa : a.price() < b.price();
|
|
|
|
public static bool operator > (IntPrice a, IntPrice b) =>
|
|
a.exponent == b.exponent ? a.mantissa > b.mantissa : a.price() > b.price();
|
|
}
|
|
}
|