-
Notifications
You must be signed in to change notification settings - Fork 396
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
angularsen
merged 2 commits into
angularsen:release/v5
from
AndreasLeeb:QuantityValueRework
Jun 3, 2022
Merged
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
} | ||
} | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | ||
|
@@ -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 | ||
|
@@ -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 | ||
} | ||
} | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.