Skip to content

QuantityValue: 16 bytes instead of 40 bytes #1084

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Jun 3, 2022
Merged
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
40 changes: 40 additions & 0 deletions UnitsNet/InternalHelpers/BytesUtility.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
// Licensed under MIT No Attribution, see LICENSE file at the root.
// Copyright 2013 Andreas Gullberg Larsen ([email protected]). Maintained at https://github.com/angularsen/UnitsNet.

using System;
using System.Runtime.InteropServices;

namespace UnitsNet.InternalHelpers
{
/// <summary>
/// Utility methods for working with the byte representation of structs.
/// </summary>
internal static class BytesUtility
{
/// <summary>
/// Converts the given <paramref name="value"/> to an array of its underlying bytes.
/// </summary>
/// <typeparam name="T">The struct type.</typeparam>
/// <param name="value">The struct value to convert.</param>
/// <returns>A byte array representing a copy of <paramref name="value"/>s bytes.</returns>
internal static byte[] GetBytes<T>(T value) where T : struct
{
int size = Marshal.SizeOf(value);
byte[] array = new byte[size];

IntPtr ptr = Marshal.AllocHGlobal(size);

try
{
Marshal.StructureToPtr(value, ptr, true);
Marshal.Copy(ptr, array, 0, size);
}
finally
{
Marshal.FreeHGlobal(ptr);
}

return array;
}
}
}
92 changes: 70 additions & 22 deletions UnitsNet/QuantityValue.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
// Licensed under MIT No Attribution, see LICENSE file at the root.
// Copyright 2013 Andreas Gullberg Larsen ([email protected]). Maintained at https://github.com/angularsen/UnitsNet.


using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
using UnitsNet.InternalHelpers;

namespace UnitsNet
Expand All @@ -16,35 +19,49 @@ namespace UnitsNet
/// </list>
/// </summary>
/// <remarks>
/// At the time of this writing, this reduces the number of From(value, unit) overloads to 1/4th:
/// <para>At the time of this writing, this reduces the number of From(value, unit) overloads to 1/4th:
/// From 8 (int, long, double, decimal + each nullable) down to 2 (QuantityValue and QuantityValue?).
/// This also adds more numeric types with no extra overhead, such as float, short and byte.
/// This also adds more numeric types with no extra overhead, such as float, short and byte.</para>
/// <para>So far, the internal representation can be either <see cref="double"/> or <see cref="decimal"/>,
/// but as this struct is realized as a union struct with overlapping fields, only the amount of memory of the largest data type is used.
/// This allows for adding support for smaller data types without increasing the overall size.</para>
/// </remarks>
public struct QuantityValue
[StructLayout(LayoutKind.Explicit)]
[DebuggerDisplay("{GetDebugRepresentation()}")]
public readonly struct QuantityValue
{
/// <summary>
/// Value assigned when implicitly casting from all numeric types except <see cref="decimal" />, since
/// <see cref="double" /> has the greatest range and is 64 bits versus 128 bits for <see cref="decimal"/>.
/// <see cref="double" /> has the greatest range.
/// </summary>
private readonly double? _value;
[FieldOffset(8)] // so that it does not interfere with the Type field
private readonly double _doubleValue;

/// <summary>
/// Value assigned when implicitly casting from <see cref="decimal" /> type, since it has a greater precision than
/// <see cref="double"/> and we want to preserve that when constructing quantities that use <see cref="decimal"/>
/// as their value type.
/// </summary>
private readonly decimal? _valueDecimal;
[FieldOffset(0)]
// bytes layout: 0-1 unused, 2 exponent, 3 sign (only highest bit), 4-15 number
private readonly decimal _decimalValue;

/// <summary>
/// Determines the underlying type of this <see cref="QuantityValue"/>.
/// </summary>
[FieldOffset(0)] // using unused byte for storing type
public readonly UnderlyingDataType Type;

private QuantityValue(double val)
private QuantityValue(double val) : this()
{
_value = Guard.EnsureValidNumber(val, nameof(val));
_valueDecimal = null;
_doubleValue = Guard.EnsureValidNumber(val, nameof(val));
Type = UnderlyingDataType.Double;
}

private QuantityValue(decimal val)
private QuantityValue(decimal val) : this()
{
_valueDecimal = val;
_value = null;
_decimalValue = val;
Type = UnderlyingDataType.Decimal;
}

#region To QuantityValue
Expand Down Expand Up @@ -72,28 +89,59 @@ private QuantityValue(decimal val)

/// <summary>Explicit cast from <see cref="QuantityValue"/> to <see cref="double"/>.</summary>
public static explicit operator double(QuantityValue number)
{
// double -> decimal -> zero (since we can't implement the default struct ctor)
return number._value ?? (double) number._valueDecimal.GetValueOrDefault();
}
=> number.Type switch
{
UnderlyingDataType.Decimal => (double)number._decimalValue,
UnderlyingDataType.Double => number._doubleValue,
_ => throw new NotImplementedException()
};

#endregion

#region To decimal

/// <summary>Explicit cast from <see cref="QuantityValue"/> to <see cref="decimal"/>.</summary>
public static explicit operator decimal(QuantityValue number)
{
// decimal -> double -> zero (since we can't implement the default struct ctor)
return number._valueDecimal ?? (decimal) number._value.GetValueOrDefault();
}
=> number.Type switch
{
UnderlyingDataType.Decimal => number._decimalValue,
UnderlyingDataType.Double => (decimal)number._doubleValue,
_ => throw new NotImplementedException()
};

#endregion

/// <summary>Returns the string representation of the numeric value.</summary>
public override string ToString()
=> Type switch
{
UnderlyingDataType.Decimal => _decimalValue.ToString(),
UnderlyingDataType.Double => _doubleValue.ToString(),
_ => throw new NotImplementedException()
};

private string GetDebugRepresentation()
{
StringBuilder builder = new($"{Type} {ToString()} Hex:");

byte[] bytes = BytesUtility.GetBytes(this);
for (int i = bytes.Length - 1; i >= 0; i--)
{
builder.Append($" {bytes[i]:X2}");
}

return builder.ToString();
}

/// <summary>
/// Describes the underlying type of a <see cref="QuantityValue"/>.
/// </summary>
public enum UnderlyingDataType : byte
{
return _value.HasValue ? _value.ToString() : _valueDecimal.ToString();
/// <summary><see cref="Decimal"/> must have the value 0 due to the bit structure of <see cref="decimal"/>.</summary>
Decimal = 0,
/// <inheritdoc cref="double"/>
Double = 1
}
}
}