├── .editorconfig ├── ValueTest ├── GlobalUsings.cs ├── StoringNull.cs ├── ValueTest.csproj ├── StoringObject.cs ├── Creation.cs ├── StoringDecimal.cs ├── StoringDateTime.cs ├── MemoryWatch.cs ├── StoringArrays.cs ├── StoringDateTimeOffset.cs ├── StoringSByte.cs ├── StoringInt.cs ├── StoringByte.cs ├── StoringChar.cs ├── StoringUInt.cs ├── StoringLong.cs ├── StoringUlong.cs ├── StoringShort.cs ├── StoringUShort.cs ├── StoringFloat.cs ├── StoringDouble.cs ├── StoringBoolean.cs └── StoringEnum.cs ├── ValuePerf ├── GlobalUsings.cs ├── Program.cs ├── StoreEnum.cs ├── ValuePerf.csproj ├── StoreObject.cs ├── StoreLong.cs ├── StoreInteger.cs ├── YieldMany.cs ├── StoreDateTime.cs ├── TypeProperty.cs ├── StoreArray.cs ├── StoreNullableLong.cs └── Table.cs ├── ValuePrototype ├── GlobalUsings.cs ├── Value.StraightCastFlag.cs ├── Value.DateTimeOffsetFlag.cs ├── Value.PackedDateTimeOffsetFlag.cs ├── Value.NullableTemplate.cs ├── ValuePrototype.csproj ├── Value.TypeFlag.cs ├── Value.Union.cs ├── Value.TypeFlags.cs ├── Value.PackedDateTimeOffset.cs ├── OtherPrototypes │ ├── ValueCompact.cs │ └── ValueState.cs └── Value.cs ├── .github └── workflows │ └── dotnet.yml ├── LICENSE ├── README.md ├── .gitattributes ├── ValuePrototype.sln └── .gitignore /.editorconfig: -------------------------------------------------------------------------------- 1 | [*.cs] 2 | 3 | # IDE0290: Use primary constructor 4 | dotnet_diagnostic.IDE0290.severity = none 5 | -------------------------------------------------------------------------------- /ValueTest/GlobalUsings.cs: -------------------------------------------------------------------------------- 1 | global using Xunit; 2 | global using ValuePrototype; 3 | global using System; 4 | global using System.Runtime.CompilerServices; 5 | -------------------------------------------------------------------------------- /ValuePerf/GlobalUsings.cs: -------------------------------------------------------------------------------- 1 | global using System; 2 | global using System.Collections.Generic; 3 | global using BenchmarkDotNet.Attributes; 4 | global using ValuePrototype; 5 | -------------------------------------------------------------------------------- /ValuePerf/Program.cs: -------------------------------------------------------------------------------- 1 | using BenchmarkDotNet.Running; 2 | 3 | class Program 4 | { 5 | static void Main(string[] args) => BenchmarkSwitcher.FromAssembly(typeof(Program).Assembly).Run(args); 6 | } 7 | -------------------------------------------------------------------------------- /ValuePrototype/GlobalUsings.cs: -------------------------------------------------------------------------------- 1 | global using System; 2 | global using System.Diagnostics; 3 | global using System.Diagnostics.CodeAnalysis; 4 | global using System.Runtime.CompilerServices; 5 | global using System.Runtime.InteropServices; 6 | global using System.Text; -------------------------------------------------------------------------------- /ValuePerf/StoreEnum.cs: -------------------------------------------------------------------------------- 1 | namespace ValuePerf; 2 | 3 | [DisassemblyDiagnoser] 4 | public class StoreEnum 5 | { 6 | [Benchmark(Baseline = true)] 7 | public DayOfWeek TryOut() 8 | { 9 | Value value = Value.Create(DayOfWeek.Monday); 10 | value.TryGetValue(out DayOfWeek result); 11 | return result; 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /ValuePrototype/Value.StraightCastFlag.cs: -------------------------------------------------------------------------------- 1 | namespace ValuePrototype; 2 | 3 | public readonly partial struct Value 4 | { 5 | private sealed class StraightCastFlag : TypeFlag 6 | { 7 | public static StraightCastFlag Instance { get; } = new(); 8 | 9 | public override T To(in Value value) 10 | => Unsafe.As(ref Unsafe.AsRef(in value._union)); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /ValuePrototype/Value.DateTimeOffsetFlag.cs: -------------------------------------------------------------------------------- 1 | namespace ValuePrototype; 2 | 3 | public readonly partial struct Value 4 | { 5 | private sealed class DateTimeOffsetFlag : TypeFlag 6 | { 7 | public static DateTimeOffsetFlag Instance { get; } = new(); 8 | 9 | public override DateTimeOffset To(in Value value) 10 | => new(new DateTime(value._union.Ticks, DateTimeKind.Utc)); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /ValuePrototype/Value.PackedDateTimeOffsetFlag.cs: -------------------------------------------------------------------------------- 1 | namespace ValuePrototype; 2 | 3 | public readonly partial struct Value 4 | { 5 | private sealed class PackedDateTimeOffsetFlag : TypeFlag 6 | { 7 | public static PackedDateTimeOffsetFlag Instance { get; } = new(); 8 | 9 | public override DateTimeOffset To(in Value value) 10 | => value._union.PackedDateTimeOffset.Extract(); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /ValuePerf/ValuePerf.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net8.0 6 | enable 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /ValuePrototype/Value.NullableTemplate.cs: -------------------------------------------------------------------------------- 1 | namespace ValuePrototype; 2 | 3 | public readonly partial struct Value 4 | { 5 | [StructLayout(LayoutKind.Sequential)] 6 | private readonly struct NullableTemplate where T : unmanaged 7 | { 8 | public readonly bool _hasValue; 9 | public readonly T _value; 10 | 11 | public NullableTemplate(T value) 12 | { 13 | _value = value; 14 | _hasValue = true; 15 | } 16 | } 17 | } 18 | 19 | -------------------------------------------------------------------------------- /ValuePrototype/ValuePrototype.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | 7 | 8 | 9 | true 10 | 11 | 12 | 13 | true 14 | 15 | 16 | 17 | -------------------------------------------------------------------------------- /.github/workflows/dotnet.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | 9 | jobs: 10 | build: 11 | 12 | runs-on: ubuntu-latest 13 | 14 | steps: 15 | - uses: actions/checkout@v2 16 | - name: Setup .NET 17 | uses: actions/setup-dotnet@v1 18 | with: 19 | dotnet-version: 8.0.x 20 | - name: Restore dependencies 21 | run: dotnet restore 22 | - name: Build 23 | run: dotnet build --no-restore 24 | - name: Test 25 | run: dotnet test --no-build --verbosity normal 26 | -------------------------------------------------------------------------------- /ValueTest/StoringNull.cs: -------------------------------------------------------------------------------- 1 | namespace ValueTest; 2 | 3 | public class StoringNull 4 | { 5 | [Fact] 6 | public void GetIntFromStoredNull() 7 | { 8 | ValueCompact nullValue = new((object?)null); 9 | Assert.Throws(() => _ = nullValue.As()); 10 | 11 | Value nullFastValue = new((object?)null); 12 | Assert.Throws(() => _ = nullFastValue.As()); 13 | 14 | bool success = nullFastValue.TryGetValue(out int result); 15 | Assert.False(success); 16 | 17 | Assert.Equal(default(int), result); 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /ValueTest/ValueTest.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net8.0 5 | enable 6 | 7 | 8 | 9 | 10 | 11 | 12 | all 13 | runtime; build; native; contentfiles; analyzers; buildtransitive 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | -------------------------------------------------------------------------------- /ValuePerf/StoreObject.cs: -------------------------------------------------------------------------------- 1 | namespace ValuePerf; 2 | 3 | [DisassemblyDiagnoser] 4 | public class StoreObject 5 | { 6 | private static A s_A = new(); 7 | private static B s_B = new(); 8 | 9 | [Benchmark(Baseline = true)] 10 | public A TryOut() 11 | { 12 | Value value = new(s_A); 13 | value.TryGetValue(out A result); 14 | return result; 15 | } 16 | 17 | [Benchmark] 18 | public A TryOutAssignable() 19 | { 20 | Value value = new(s_B); 21 | value.TryGetValue(out A result); 22 | return result; 23 | } 24 | 25 | public class A : I { } 26 | public class B : A, I { } 27 | public class C : B, I { } 28 | 29 | public interface I 30 | { 31 | string? ToString(); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /ValuePrototype/Value.TypeFlag.cs: -------------------------------------------------------------------------------- 1 | namespace ValuePrototype; 2 | 3 | public readonly partial struct Value 4 | { 5 | private abstract class TypeFlag 6 | { 7 | public abstract Type Type 8 | { 9 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 10 | get; 11 | } 12 | 13 | public abstract object ToObject(in Value value); 14 | } 15 | 16 | private abstract class TypeFlag : TypeFlag 17 | { 18 | public sealed override Type Type 19 | { 20 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 21 | get => typeof(T); 22 | } 23 | 24 | public sealed override object ToObject(in Value value) => To(value)!; 25 | public abstract T To(in Value value); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /ValuePerf/StoreLong.cs: -------------------------------------------------------------------------------- 1 | namespace ValuePerf; 2 | 3 | [DisassemblyDiagnoser] 4 | public class StoreLong 5 | { 6 | [Benchmark] 7 | public long ValueAsPerf() 8 | { 9 | Value value = new(42L); 10 | return value.As(); 11 | } 12 | 13 | [Benchmark(Baseline = true)] 14 | public long ValueTryPerf() 15 | { 16 | Value value = new(42L); 17 | value.TryGetValue(out long result); 18 | return result; 19 | } 20 | 21 | [Benchmark] 22 | public long ValueCastOutPerf() 23 | { 24 | Value value = new(42L); 25 | return (long)value; 26 | } 27 | 28 | [Benchmark] 29 | public long ValueCastInPerf() 30 | { 31 | Value value = 42L; 32 | value.TryGetValue(out long result); 33 | return result; 34 | } 35 | } 36 | -------------------------------------------------------------------------------- /ValuePerf/StoreInteger.cs: -------------------------------------------------------------------------------- 1 | namespace ValuePerf; 2 | 3 | public class StoreInteger 4 | { 5 | [Benchmark(Baseline = true)] 6 | public int ValueCompactPerf() 7 | { 8 | ValueCompact value = new(42); 9 | return value.As(); 10 | } 11 | 12 | [Benchmark] 13 | public int ValueCompactFastPerf() 14 | { 15 | Value value = new(42); 16 | return value.As(); 17 | } 18 | 19 | [Benchmark] 20 | public int ValueCompactFastTryPerf() 21 | { 22 | Value value = new(42); 23 | value.TryGetValue(out int result); 24 | return result; 25 | } 26 | 27 | [Benchmark] 28 | public int ValueStatePerf() 29 | { 30 | ValueState value = new(42); 31 | value.TryGetValue(out int result); 32 | return result; 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /ValuePerf/YieldMany.cs: -------------------------------------------------------------------------------- 1 | namespace ValuePerf; 2 | 3 | [MemoryDiagnoser] 4 | public class YieldMany 5 | { 6 | private const int Iterations = 1_000_000; 7 | 8 | [Benchmark(Baseline = true)] 9 | public int SumObject() 10 | { 11 | int sum = 0; 12 | foreach (object o in EnumerateObjects()) sum += (int)o; 13 | return sum; 14 | } 15 | 16 | [Benchmark] 17 | public int SumValue() 18 | { 19 | int sum = 0; 20 | foreach (Value v in EnumerateValues()) sum += v.As(); 21 | return sum; 22 | } 23 | 24 | private static IEnumerable EnumerateObjects() 25 | { 26 | for (int i = 0; i < Iterations; i++) yield return (object)1; 27 | } 28 | 29 | private static IEnumerable EnumerateValues() 30 | { 31 | for (int i = 0; i < Iterations; i++) yield return new Value((int)1); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /ValuePerf/StoreDateTime.cs: -------------------------------------------------------------------------------- 1 | namespace ValuePerf; 2 | 3 | public class StoreDateTime 4 | { 5 | private static DateTime s_now = DateTime.Now; 6 | private static DateTimeOffset s_offsetUtc = DateTime.UtcNow; 7 | private static DateTimeOffset s_offset = DateTime.Now; 8 | 9 | [Benchmark(Baseline = true)] 10 | public DateTime InOutDateTime() 11 | { 12 | Value value = new(s_now); 13 | value.TryGetValue(out DateTime result); 14 | return result; 15 | } 16 | 17 | [Benchmark] 18 | public DateTimeOffset InOutDateTimeOffsetUTC() 19 | { 20 | Value value = new(s_offsetUtc); 21 | value.TryGetValue(out DateTimeOffset result); 22 | return result; 23 | } 24 | 25 | [Benchmark] 26 | public DateTimeOffset InOutDateTimeOffset() 27 | { 28 | Value value = new(s_offset); 29 | value.TryGetValue(out DateTimeOffset result); 30 | return result; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /ValuePerf/TypeProperty.cs: -------------------------------------------------------------------------------- 1 | namespace ValuePerf; 2 | 3 | public class TypeProperty 4 | { 5 | private static Value s_int = new(42); 6 | private static Value s_object = new(new object()); 7 | private static Value s_null = new((object?)null); 8 | private static Value s_byteArray = new(new byte[10]); 9 | private static Value s_byteSegment = new(new ArraySegment(new byte[10], 1, 3)); 10 | 11 | [Benchmark(Baseline = true)] 12 | public Type? TypeOfInt() 13 | { 14 | return s_int.Type; 15 | } 16 | 17 | [Benchmark] 18 | public Type? TypeOfObject() 19 | { 20 | return s_object.Type; 21 | } 22 | 23 | [Benchmark] 24 | public Type? TypeOfNull() 25 | { 26 | return s_null.Type; 27 | } 28 | 29 | [Benchmark] 30 | public Type? TypeOfArray() 31 | { 32 | return s_byteArray.Type; 33 | } 34 | 35 | [Benchmark] 36 | public Type? TypeOfArraySegment() 37 | { 38 | return s_byteSegment.Type; 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /ValuePerf/StoreArray.cs: -------------------------------------------------------------------------------- 1 | namespace ValuePerf; 2 | 3 | public class StoreArray 4 | { 5 | private static readonly byte[] s_byteArray = new byte[10]; 6 | private static readonly ArraySegment s_byteSegment = new(s_byteArray); 7 | private static readonly ArraySegment s_emptyByteSegment = new(s_byteArray, 0, 0); 8 | 9 | [Benchmark(Baseline = true)] 10 | public byte[] InOutByteArray() 11 | { 12 | Value value = new(s_byteArray); 13 | value.TryGetValue(out byte[] result); 14 | return result; 15 | } 16 | 17 | [Benchmark] 18 | public ArraySegment InOutByteSegment() 19 | { 20 | Value value = new(s_byteSegment); 21 | value.TryGetValue(out ArraySegment result); 22 | return result; 23 | } 24 | 25 | [Benchmark] 26 | public ArraySegment InOutEmptyByteSegment() 27 | { 28 | Value value = new(s_emptyByteSegment); 29 | value.TryGetValue(out ArraySegment result); 30 | return result; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Jeremy Kuhne 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /ValuePrototype/Value.Union.cs: -------------------------------------------------------------------------------- 1 | namespace ValuePrototype; 2 | 3 | public readonly partial struct Value 4 | { 5 | [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)] 6 | private struct Union 7 | { 8 | [FieldOffset(0)] public byte Byte; 9 | [FieldOffset(0)] public sbyte SByte; 10 | [FieldOffset(0)] public char Char; 11 | [FieldOffset(0)] public bool Boolean; 12 | [FieldOffset(0)] public short Int16; 13 | [FieldOffset(0)] public ushort UInt16; 14 | [FieldOffset(0)] public int Int32; 15 | [FieldOffset(0)] public uint UInt32; 16 | [FieldOffset(0)] public long Int64; 17 | [FieldOffset(0)] public long Ticks; 18 | [FieldOffset(0)] public ulong UInt64; 19 | [FieldOffset(0)] public float Single; // 4 bytes 20 | [FieldOffset(0)] public double Double; // 8 bytes 21 | [FieldOffset(0)] public DateTime DateTime; // 8 bytes (ulong) 22 | [FieldOffset(0)] public PackedDateTimeOffset PackedDateTimeOffset; 23 | [FieldOffset(0)] public (int Offset, int Count) Segment; 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Value Prototype 2 | Wrapping arbitrary values without boxing of common types. 3 | 4 | [![Build](https://github.com/JeremyKuhne/ValuePrototype/actions/workflows/dotnet.yml/badge.svg)](https://github.com/JeremyKuhne/ValuePrototype/actions/workflows/dotnet.yml) 5 | 6 | ### Goals 7 | 8 | - Take any value, including null 9 | - Fit into 64bits of data and an object field (128bits total on x64) 10 | - Do not box any primitive types (`int`, `float`, etc.) [Except for `Decimal`] 11 | - Optimize performance for primitive type storage/retrieval 12 | - Expose `Type` of wrapped type (or `null` for null) 13 | - Allow retrieving as any type that is `AssignableFrom` 14 | - Support nullable intrinsics without boxing (`int?`, `float?`, etc.) [Except for `Decimal`] 15 | - Allow intrinsic to/from nullable intrinsic (except no value to intrinsic) 16 | 17 | #### Additional special support 18 | 19 | - Support `ArraySegment` without boxing 20 | - Support UTC `DateTime` and `DateTimeOffset` without boxing 21 | 22 | This code has been included in [Touki](https://github.com/JeremyKuhne/touki) for both .NET Framework 4.7.2 and .NET 9. 23 | 24 | [As proposed in .NET](https://github.com/dotnet/runtime/issues/28882) 25 | -------------------------------------------------------------------------------- /ValuePerf/StoreNullableLong.cs: -------------------------------------------------------------------------------- 1 | namespace ValuePerf; 2 | 3 | public class StoreNullableLong 4 | { 5 | [Benchmark(Baseline = true)] 6 | public long? InOutNullableLong() 7 | { 8 | long? @long = 42; 9 | Value value = new(@long); 10 | value.TryGetValue(out long? result); 11 | return result; 12 | } 13 | 14 | [Benchmark] 15 | public long? InLongOutNullableLong() 16 | { 17 | long @long = 42; 18 | Value value = new(@long); 19 | value.TryGetValue(out long? result); 20 | return result; 21 | } 22 | 23 | [Benchmark] 24 | public long InNullableLongOutLong() 25 | { 26 | long? @long = 42; 27 | Value value = new(@long); 28 | value.TryGetValue(out long result); 29 | return result; 30 | } 31 | 32 | [Benchmark] 33 | public long? CastInOutNullableLong() 34 | { 35 | long? @long = 42; 36 | Value value = @long; 37 | return (long?)value; 38 | } 39 | 40 | [Benchmark] 41 | public long? CastInLongOutNullableLong() 42 | { 43 | long @long = 42; 44 | Value value = @long; 45 | return (long?)value; 46 | } 47 | 48 | [Benchmark] 49 | public long CastInNullableLongOutLong() 50 | { 51 | long? @long = 42; 52 | Value value = @long; 53 | return (long)value; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /ValueTest/StoringObject.cs: -------------------------------------------------------------------------------- 1 | namespace ValueTest; 2 | 3 | public class StoringObject 4 | { 5 | [Fact] 6 | public void BasicStorage() 7 | { 8 | A a = new(); 9 | Value value = new(a); 10 | Assert.Equal(typeof(A), value.Type); 11 | Assert.Same(a, value.As()); 12 | 13 | bool success = value.TryGetValue(out B result); 14 | Assert.False(success); 15 | Assert.Null(result); 16 | } 17 | 18 | [Fact] 19 | public void DerivedRetrieval() 20 | { 21 | B b = new(); 22 | Value value = new(b); 23 | Assert.Equal(typeof(B), value.Type); 24 | Assert.Same(b, value.As()); 25 | Assert.Same(b, value.As()); 26 | 27 | bool success = value.TryGetValue(out C result); 28 | Assert.False(success); 29 | Assert.Null(result); 30 | 31 | Assert.Throws(() => value.As()); 32 | 33 | A a = new B(); 34 | value = new(a); 35 | Assert.Equal(typeof(B), value.Type); 36 | } 37 | 38 | [Fact] 39 | public void AsInterface() 40 | { 41 | I a = new A(); 42 | Value value = new(a); 43 | Assert.Equal(typeof(A), value.Type); 44 | 45 | Assert.Same(a, value.As()); 46 | Assert.Same(a, value.As()); 47 | } 48 | 49 | private class A : I { } 50 | private class B : A, I { } 51 | private class C : B, I { } 52 | 53 | private interface I 54 | { 55 | string? ToString(); 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /ValuePrototype/Value.TypeFlags.cs: -------------------------------------------------------------------------------- 1 | namespace ValuePrototype; 2 | 3 | public readonly partial struct Value 4 | { 5 | private static class TypeFlags 6 | { 7 | internal static readonly StraightCastFlag Boolean = StraightCastFlag.Instance; 8 | internal static readonly StraightCastFlag Char = StraightCastFlag.Instance; 9 | internal static readonly StraightCastFlag Byte = StraightCastFlag.Instance; 10 | internal static readonly StraightCastFlag SByte = StraightCastFlag.Instance; 11 | internal static readonly StraightCastFlag Int16 = StraightCastFlag.Instance; 12 | internal static readonly StraightCastFlag UInt16 = StraightCastFlag.Instance; 13 | internal static readonly StraightCastFlag Int32 = StraightCastFlag.Instance; 14 | internal static readonly StraightCastFlag UInt32 = StraightCastFlag.Instance; 15 | internal static readonly StraightCastFlag Int64 = StraightCastFlag.Instance; 16 | internal static readonly StraightCastFlag UInt64 = StraightCastFlag.Instance; 17 | internal static readonly StraightCastFlag Single = StraightCastFlag.Instance; 18 | internal static readonly StraightCastFlag Double = StraightCastFlag.Instance; 19 | internal static readonly StraightCastFlag DateTime = StraightCastFlag.Instance; 20 | internal static readonly DateTimeOffsetFlag DateTimeOffset = DateTimeOffsetFlag.Instance; 21 | internal static readonly PackedDateTimeOffsetFlag PackedDateTimeOffset = PackedDateTimeOffsetFlag.Instance; 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /ValueTest/Creation.cs: -------------------------------------------------------------------------------- 1 | namespace ValueTest; 2 | 3 | public class Creation 4 | { 5 | [Fact] 6 | public void CreateIsAllocationFree() 7 | { 8 | var watch = MemoryWatch.Create; 9 | 10 | Value.Create((byte)default); 11 | watch.Validate(); 12 | Value.Create((sbyte)default); 13 | watch.Validate(); 14 | Value.Create((char)default); 15 | watch.Validate(); 16 | Value.Create((double)default); 17 | watch.Validate(); 18 | Value.Create((short)default); 19 | watch.Validate(); 20 | Value.Create((int)default); 21 | watch.Validate(); 22 | Value.Create((long)default); 23 | watch.Validate(); 24 | Value.Create((ushort)default); 25 | watch.Validate(); 26 | Value.Create((uint)default); 27 | watch.Validate(); 28 | Value.Create((ulong)default); 29 | watch.Validate(); 30 | Value.Create((float)default); 31 | watch.Validate(); 32 | Value.Create((double)default); 33 | watch.Validate(); 34 | 35 | Value.Create((bool?)default); 36 | watch.Validate(); 37 | Value.Create((byte?)default); 38 | watch.Validate(); 39 | Value.Create((sbyte?)default); 40 | watch.Validate(); 41 | Value.Create((char?)default); 42 | watch.Validate(); 43 | Value.Create((double?)default); 44 | watch.Validate(); 45 | Value.Create((short?)default); 46 | watch.Validate(); 47 | Value.Create((int?)default); 48 | watch.Validate(); 49 | Value.Create((long?)default); 50 | watch.Validate(); 51 | Value.Create((ushort?)default); 52 | watch.Validate(); 53 | Value.Create((uint?)default); 54 | watch.Validate(); 55 | Value.Create((ulong?)default); 56 | watch.Validate(); 57 | Value.Create((float?)default); 58 | watch.Validate(); 59 | Value.Create((double?)default); 60 | watch.Validate(); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /ValuePerf/Table.cs: -------------------------------------------------------------------------------- 1 | using System.Threading.Tasks; 2 | 3 | namespace ValuePerf; 4 | 5 | [MemoryDiagnoser] 6 | public class Table 7 | { 8 | private const int Rows = 10000; 9 | private const int Columns = 10; 10 | private const int Requests = 1000; 11 | 12 | [Benchmark(Baseline = true)] 13 | public long ObjectTableSum() 14 | { 15 | var tasks = new Task[Requests]; 16 | long sum = 0; 17 | for (int i = 0; i < Requests; i++) 18 | { 19 | var task = Task.Run(() => 20 | { 21 | var table = new ObjectTable(Rows, Columns); 22 | sum += (int)table._rows[823][5]; 23 | }); 24 | tasks[i] = task; 25 | } 26 | 27 | Task.WaitAll(tasks); 28 | return sum; 29 | } 30 | 31 | [Benchmark] 32 | public long ValueTableSum() 33 | { 34 | var tasks = new Task[Requests]; 35 | long sum = 0; 36 | for (int i = 0; i < Requests; i++) 37 | { 38 | var task = Task.Run(() => 39 | { 40 | var table = new ValueTable(Rows, Columns); 41 | sum += (int)table._rows[823][5]; 42 | }); 43 | tasks[i] = task; 44 | } 45 | 46 | Task.WaitAll(tasks); 47 | return sum; 48 | } 49 | 50 | private class ObjectTable 51 | { 52 | public object[][] _rows; 53 | 54 | public ObjectTable(int rows, int columns) 55 | { 56 | _rows = new object[rows][]; 57 | for (int r = 0; r < rows; r++) 58 | { 59 | _rows[r] = new object[columns]; 60 | for (int c = 0; c < columns; c++) 61 | { 62 | _rows[r][c] = 10; 63 | } 64 | } 65 | } 66 | } 67 | 68 | private class ValueTable 69 | { 70 | public Value[][] _rows; 71 | 72 | public ValueTable(int rows, int columns) 73 | { 74 | _rows = new Value[rows][]; 75 | for (int r = 0; r < rows; r++) 76 | { 77 | _rows[r] = new Value[columns]; 78 | for (int c = 0; c < columns; c++) 79 | { 80 | _rows[r][c] = 10; 81 | } 82 | } 83 | } 84 | } 85 | } 86 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /ValuePrototype.sln: -------------------------------------------------------------------------------- 1 | 2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.10.35013.160 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ValuePrototype", "ValuePrototype\ValuePrototype.csproj", "{C4435C96-46F7-4F9B-BA95-17BD2AE8F0AD}" 7 | EndProject 8 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ValuePerf", "ValuePerf\ValuePerf.csproj", "{3AF81060-7A74-4B2C-86C6-6A3EA06216E2}" 9 | EndProject 10 | Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "ValueTest", "ValueTest\ValueTest.csproj", "{90BE1E5B-CDD7-431A-9596-07895860CADD}" 11 | EndProject 12 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SupportFiles", "SupportFiles", "{27252161-1B54-44D3-9106-CB64E356DBE6}" 13 | ProjectSection(SolutionItems) = preProject 14 | README.md = README.md 15 | EndProjectSection 16 | EndProject 17 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{F37A709E-95F7-464B-B769-7FAA10659520}" 18 | ProjectSection(SolutionItems) = preProject 19 | .editorconfig = .editorconfig 20 | .github\workflows\dotnet.yml = .github\workflows\dotnet.yml 21 | EndProjectSection 22 | EndProject 23 | Global 24 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 25 | Debug|Any CPU = Debug|Any CPU 26 | Release|Any CPU = Release|Any CPU 27 | EndGlobalSection 28 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 29 | {C4435C96-46F7-4F9B-BA95-17BD2AE8F0AD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 30 | {C4435C96-46F7-4F9B-BA95-17BD2AE8F0AD}.Debug|Any CPU.Build.0 = Debug|Any CPU 31 | {C4435C96-46F7-4F9B-BA95-17BD2AE8F0AD}.Release|Any CPU.ActiveCfg = Release|Any CPU 32 | {C4435C96-46F7-4F9B-BA95-17BD2AE8F0AD}.Release|Any CPU.Build.0 = Release|Any CPU 33 | {3AF81060-7A74-4B2C-86C6-6A3EA06216E2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 34 | {3AF81060-7A74-4B2C-86C6-6A3EA06216E2}.Debug|Any CPU.Build.0 = Debug|Any CPU 35 | {3AF81060-7A74-4B2C-86C6-6A3EA06216E2}.Release|Any CPU.ActiveCfg = Release|Any CPU 36 | {3AF81060-7A74-4B2C-86C6-6A3EA06216E2}.Release|Any CPU.Build.0 = Release|Any CPU 37 | {90BE1E5B-CDD7-431A-9596-07895860CADD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 38 | {90BE1E5B-CDD7-431A-9596-07895860CADD}.Debug|Any CPU.Build.0 = Debug|Any CPU 39 | {90BE1E5B-CDD7-431A-9596-07895860CADD}.Release|Any CPU.ActiveCfg = Release|Any CPU 40 | {90BE1E5B-CDD7-431A-9596-07895860CADD}.Release|Any CPU.Build.0 = Release|Any CPU 41 | EndGlobalSection 42 | GlobalSection(SolutionProperties) = preSolution 43 | HideSolutionNode = FALSE 44 | EndGlobalSection 45 | GlobalSection(ExtensibilityGlobals) = postSolution 46 | SolutionGuid = {D8E4E9ED-386B-4B64-BC04-C0268F198304} 47 | EndGlobalSection 48 | EndGlobal 49 | -------------------------------------------------------------------------------- /ValuePrototype/Value.PackedDateTimeOffset.cs: -------------------------------------------------------------------------------- 1 | namespace ValuePrototype; 2 | 3 | public readonly partial struct Value 4 | { 5 | private readonly struct PackedDateTimeOffset 6 | { 7 | // HHHHHMMT TTT... 8 | // 9 | // HHHHH - hour bits 1-31 10 | // MM - minutes flag 11 | // T - ticks bit 12 | // 00 - :00 13 | // 01 - :15 14 | // 10 - :30 15 | // 11 - :45 16 | 17 | // Base local tick time 1800 [DateTime(1800, 1, 1).Ticks] 18 | private const ulong BaseTicks = 567709344000000000; 19 | private const ulong MaxTicks = BaseTicks + TickMask; 20 | 21 | // Hours go from -14 to 14. We add 14 to get our number to store. 22 | private const int HourOffset = 14; 23 | 24 | private const ulong TickMask = 0b00000001_11111111_11111111_11111111__11111111_11111111_11111111_11111111; 25 | private const ulong MinuteMask = 0b00000110_00000000_00000000_00000000__00000000_00000000_00000000_00000000; 26 | private const ulong HourMask = 0b11111000_00000000_00000000_00000000__00000000_00000000_00000000_00000000; 27 | 28 | private const int MinuteShift = 57; 29 | private const int HourShift = 59; 30 | 31 | private readonly ulong _data; 32 | 33 | private PackedDateTimeOffset(ulong data) => _data = data; 34 | 35 | public static bool TryCreate(DateTimeOffset dateTime, TimeSpan offset, out PackedDateTimeOffset packed) 36 | { 37 | bool result = false; 38 | packed = default; 39 | 40 | ulong ticks = (ulong)dateTime.Ticks; 41 | if (ticks > BaseTicks && ticks < MaxTicks) 42 | { 43 | int minutes = offset.Minutes; 44 | if (minutes % 15 == 0) 45 | { 46 | ulong data = (ulong)(minutes / 15) << MinuteShift; 47 | int hours = offset.Hours + HourOffset; 48 | 49 | // Only valid offset hours are -14 to 14 50 | Debug.Assert(hours >= 0 && hours <= 28); 51 | data |= (ulong)hours << HourShift; 52 | data |= ticks - BaseTicks; 53 | packed = new(data); 54 | result = true; 55 | } 56 | } 57 | 58 | return result; 59 | } 60 | 61 | public DateTimeOffset Extract() 62 | { 63 | TimeSpan offset = new( 64 | (int)(((_data & HourMask) >> HourShift) - HourOffset), 65 | (int)((_data & MinuteMask) >> MinuteShift), 66 | 0); 67 | 68 | return new((long)((_data & TickMask) + BaseTicks), offset); 69 | } 70 | } 71 | } 72 | 73 | -------------------------------------------------------------------------------- /ValueTest/StoringDecimal.cs: -------------------------------------------------------------------------------- 1 | namespace ValueTest; 2 | 3 | public class StoringDecimal 4 | { 5 | public static TheoryData DecimalData => new() 6 | { 7 | { 42 }, 8 | { decimal.MaxValue }, 9 | { decimal.MinValue } 10 | }; 11 | 12 | [Fact] 13 | public void DecimalImplicit() 14 | { 15 | Value value = (decimal)42.0; 16 | Assert.Equal((decimal)42.0, value.As()); 17 | Assert.Equal(typeof(decimal), value.Type); 18 | 19 | decimal? source = (decimal?)42.0; 20 | value = source; 21 | Assert.Equal(source, value.As()); 22 | Assert.Equal(typeof(decimal), value.Type); 23 | } 24 | 25 | [Theory] 26 | [MemberData(nameof(DecimalData))] 27 | public void DecimalInOut(decimal @decimal) 28 | { 29 | Value value = new(@decimal); 30 | bool success = value.TryGetValue(out decimal result); 31 | Assert.True(success); 32 | Assert.Equal(@decimal, result); 33 | 34 | Assert.Equal(@decimal, value.As()); 35 | Assert.Equal(@decimal, (decimal)value); 36 | } 37 | 38 | [Theory] 39 | [MemberData(nameof(DecimalData))] 40 | public void NullableDecimalInDecimalOut(decimal? @decimal) 41 | { 42 | decimal? source = @decimal; 43 | Value value = new(source); 44 | 45 | bool success = value.TryGetValue(out decimal result); 46 | Assert.True(success); 47 | Assert.Equal(@decimal, result); 48 | 49 | Assert.Equal(@decimal, value.As()); 50 | 51 | Assert.Equal(@decimal, (decimal)value); 52 | } 53 | 54 | [Theory] 55 | [MemberData(nameof(DecimalData))] 56 | public void DecimalInNullableDecimalOut(decimal @decimal) 57 | { 58 | decimal source = @decimal; 59 | Value value = new(source); 60 | bool success = value.TryGetValue(out decimal? result); 61 | Assert.True(success); 62 | Assert.Equal(@decimal, result); 63 | 64 | Assert.Equal(@decimal, (decimal?)value); 65 | } 66 | 67 | [Fact] 68 | public void NullDecimal() 69 | { 70 | decimal? source = null; 71 | Value value = source; 72 | Assert.Null(value.Type); 73 | Assert.Equal(source, value.As()); 74 | Assert.False(value.As().HasValue); 75 | } 76 | 77 | [Theory] 78 | [MemberData(nameof(DecimalData))] 79 | public void OutAsObject(decimal @decimal) 80 | { 81 | Value value = new(@decimal); 82 | object o = value.As(); 83 | Assert.Equal(typeof(decimal), o.GetType()); 84 | Assert.Equal(@decimal, (decimal)o); 85 | 86 | decimal? n = @decimal; 87 | value = new(n); 88 | o = value.As(); 89 | Assert.Equal(typeof(decimal), o.GetType()); 90 | Assert.Equal(@decimal, (decimal)o); 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /ValueTest/StoringDateTime.cs: -------------------------------------------------------------------------------- 1 | namespace ValueTest; 2 | 3 | public class StoringDateTime 4 | { 5 | public static TheoryData DateTimeData => new() 6 | { 7 | { DateTime.Now }, 8 | { DateTime.UtcNow }, 9 | { DateTime.MaxValue }, 10 | { DateTime.MinValue } 11 | }; 12 | 13 | [Theory] 14 | [MemberData(nameof(DateTimeData))] 15 | public void DateTimeImplicit(DateTime @DateTime) 16 | { 17 | Value value = @DateTime; 18 | Assert.Equal(@DateTime, value.As()); 19 | Assert.Equal(typeof(DateTime), value.Type); 20 | 21 | DateTime? source = @DateTime; 22 | value = source; 23 | Assert.Equal(source, value.As()); 24 | Assert.Equal(typeof(DateTime), value.Type); 25 | } 26 | 27 | [Theory] 28 | [MemberData(nameof(DateTimeData))] 29 | public void DateTimeInOut(DateTime @DateTime) 30 | { 31 | Value value = new(@DateTime); 32 | bool success = value.TryGetValue(out DateTime result); 33 | Assert.True(success); 34 | Assert.Equal(@DateTime, result); 35 | 36 | Assert.Equal(@DateTime, value.As()); 37 | Assert.Equal(@DateTime, (DateTime)value); 38 | } 39 | 40 | [Theory] 41 | [MemberData(nameof(DateTimeData))] 42 | public void NullableDateTimeInDateTimeOut(DateTime? @DateTime) 43 | { 44 | DateTime? source = @DateTime; 45 | Value value = new(source); 46 | 47 | bool success = value.TryGetValue(out DateTime result); 48 | Assert.True(success); 49 | Assert.Equal(@DateTime, result); 50 | 51 | Assert.Equal(@DateTime, value.As()); 52 | 53 | Assert.Equal(@DateTime, (DateTime)value); 54 | } 55 | 56 | [Theory] 57 | [MemberData(nameof(DateTimeData))] 58 | public void DateTimeInNullableDateTimeOut(DateTime @DateTime) 59 | { 60 | DateTime source = @DateTime; 61 | Value value = new(source); 62 | bool success = value.TryGetValue(out DateTime? result); 63 | Assert.True(success); 64 | Assert.Equal(@DateTime, result); 65 | 66 | Assert.Equal(@DateTime, (DateTime?)value); 67 | } 68 | 69 | [Fact] 70 | public void NullDateTime() 71 | { 72 | DateTime? source = null; 73 | Value value = source; 74 | Assert.Null(value.Type); 75 | Assert.Equal(source, value.As()); 76 | Assert.False(value.As().HasValue); 77 | } 78 | 79 | [Theory] 80 | [MemberData(nameof(DateTimeData))] 81 | public void OutAsObject(DateTime @DateTime) 82 | { 83 | Value value = new(@DateTime); 84 | object o = value.As(); 85 | Assert.Equal(typeof(DateTime), o.GetType()); 86 | Assert.Equal(@DateTime, (DateTime)o); 87 | 88 | DateTime? n = @DateTime; 89 | value = new(n); 90 | o = value.As(); 91 | Assert.Equal(typeof(DateTime), o.GetType()); 92 | Assert.Equal(@DateTime, (DateTime)o); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /ValueTest/MemoryWatch.cs: -------------------------------------------------------------------------------- 1 | namespace ValueTest; 2 | 3 | public ref struct MemoryWatch 4 | { 5 | private static bool s_jit; 6 | private long _allocations; 7 | 8 | public static void JIT() 9 | { 10 | if (s_jit) 11 | { 12 | return; 13 | } 14 | 15 | // JITing allocates, so make sure we've got all of our methods created. 16 | 17 | Value.Create((bool)default).As(); 18 | Value.Create((byte)default).As(); 19 | Value.Create((sbyte)default).As(); 20 | Value.Create((char)default).As(); 21 | Value.Create((double)default).As(); 22 | Value.Create((short)default).As(); 23 | Value.Create((int)default).As(); 24 | Value.Create((long)default).As(); 25 | Value.Create((ushort)default).As(); 26 | Value.Create((uint)default).As(); 27 | Value.Create((ulong)default).As(); 28 | Value.Create((float)default).As(); 29 | Value.Create((double)default).As(); 30 | Value.Create((DateTime)default).As(); 31 | Value.Create((DateTimeOffset)default).As(); 32 | 33 | Value.Create((bool?)default).As(); 34 | Value.Create((byte?)default).As(); 35 | Value.Create((sbyte?)default).As(); 36 | Value.Create((char?)default).As(); 37 | Value.Create((double?)default).As(); 38 | Value.Create((short?)default).As(); 39 | Value.Create((int?)default).As(); 40 | Value.Create((long?)default).As(); 41 | Value.Create((ushort?)default).As(); 42 | Value.Create((uint?)default).As(); 43 | Value.Create((ulong?)default).As(); 44 | Value.Create((float?)default).As(); 45 | Value.Create((double?)default).As(); 46 | Value.Create((DateTime?)default).As(); 47 | Value.Create((DateTimeOffset?)default).As(); 48 | 49 | Value value = default; 50 | value.TryGetValue(out bool _); 51 | value.TryGetValue(out byte _); 52 | value.TryGetValue(out sbyte _); 53 | value.TryGetValue(out char _); 54 | value.TryGetValue(out double _); 55 | value.TryGetValue(out short _); 56 | value.TryGetValue(out int _); 57 | value.TryGetValue(out long _); 58 | value.TryGetValue(out ushort _); 59 | value.TryGetValue(out uint _); 60 | value.TryGetValue(out ulong _); 61 | value.TryGetValue(out float _); 62 | value.TryGetValue(out double _); 63 | value.TryGetValue(out DateTime _); 64 | value.TryGetValue(out DateTimeOffset _); 65 | 66 | s_jit = true; 67 | } 68 | 69 | public MemoryWatch(long allocations) => _allocations = allocations; 70 | 71 | public static MemoryWatch Create 72 | { 73 | get 74 | { 75 | JIT(); 76 | return new(GC.GetAllocatedBytesForCurrentThread()); 77 | } 78 | } 79 | 80 | public void Dispose() => Validate(); 81 | 82 | public void Validate() 83 | { 84 | Assert.Equal(0, GC.GetAllocatedBytesForCurrentThread() - _allocations); 85 | 86 | // Assert.Equal allocates 87 | _allocations = GC.GetAllocatedBytesForCurrentThread(); 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /ValueTest/StoringArrays.cs: -------------------------------------------------------------------------------- 1 | namespace ValueTest; 2 | 3 | public class StoringArrays 4 | { 5 | [Fact] 6 | public void ByteArray() 7 | { 8 | byte[] b = new byte[10]; 9 | Value value; 10 | 11 | value = Value.Create(b); 12 | Assert.Equal(typeof(byte[]), value.Type); 13 | Assert.Same(b, value.As()); 14 | Assert.Equal(b, (byte[])value.As()); 15 | 16 | Assert.Throws(() => value.As>()); 17 | } 18 | 19 | [Fact] 20 | public void CharArray() 21 | { 22 | char[] b = new char[10]; 23 | Value value; 24 | 25 | value = Value.Create(b); 26 | Assert.Equal(typeof(char[]), value.Type); 27 | Assert.Same(b, value.As()); 28 | Assert.Equal(b, (char[])value.As()); 29 | 30 | Assert.Throws(() => value.As>()); 31 | } 32 | 33 | [Fact] 34 | public void ByteSegment() 35 | { 36 | byte[] b = new byte[10]; 37 | Value value; 38 | 39 | ArraySegment segment = new(b); 40 | value = Value.Create(segment); 41 | Assert.Equal(typeof(ArraySegment), value.Type); 42 | Assert.Equal(segment, value.As>()); 43 | Assert.Equal(segment, (ArraySegment)value.As()); 44 | Assert.Throws(() => value.As()); 45 | 46 | segment = new(b, 0, 0); 47 | value = Value.Create(segment); 48 | Assert.Equal(typeof(ArraySegment), value.Type); 49 | Assert.Equal(segment, value.As>()); 50 | Assert.Equal(segment, (ArraySegment)value.As()); 51 | Assert.Throws(() => value.As()); 52 | 53 | segment = new(b, 1, 1); 54 | value = Value.Create(segment); 55 | Assert.Equal(typeof(ArraySegment), value.Type); 56 | Assert.Equal(segment, value.As>()); 57 | Assert.Equal(segment, (ArraySegment)value.As()); 58 | Assert.Throws(() => value.As()); 59 | } 60 | 61 | [Fact] 62 | public void CharSegment() 63 | { 64 | char[] b = new char[10]; 65 | Value value; 66 | 67 | ArraySegment segment = new(b); 68 | value = Value.Create(segment); 69 | Assert.Equal(typeof(ArraySegment), value.Type); 70 | Assert.Equal(segment, value.As>()); 71 | Assert.Equal(segment, (ArraySegment)value.As()); 72 | Assert.Throws(() => value.As()); 73 | 74 | segment = new(b, 0, 0); 75 | value = Value.Create(segment); 76 | Assert.Equal(typeof(ArraySegment), value.Type); 77 | Assert.Equal(segment, value.As>()); 78 | Assert.Equal(segment, (ArraySegment)value.As()); 79 | Assert.Throws(() => value.As()); 80 | 81 | segment = new(b, 1, 1); 82 | value = Value.Create(segment); 83 | Assert.Equal(typeof(ArraySegment), value.Type); 84 | Assert.Equal(segment, value.As>()); 85 | Assert.Equal(segment, (ArraySegment)value.As()); 86 | Assert.Throws(() => value.As()); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /ValueTest/StoringDateTimeOffset.cs: -------------------------------------------------------------------------------- 1 | namespace ValueTest; 2 | 3 | public class StoringDateTimeOffset 4 | { 5 | public static TheoryData DateTimeOffsetData => new() 6 | { 7 | { DateTimeOffset.Now }, 8 | { DateTimeOffset.UtcNow }, 9 | { DateTimeOffset.MaxValue }, 10 | { DateTimeOffset.MinValue } 11 | }; 12 | 13 | [Theory] 14 | [MemberData(nameof(DateTimeOffsetData))] 15 | public void DateTimeOffsetImplicit(DateTimeOffset @DateTimeOffset) 16 | { 17 | Value value = @DateTimeOffset; 18 | Assert.Equal(@DateTimeOffset, value.As()); 19 | Assert.Equal(typeof(DateTimeOffset), value.Type); 20 | 21 | DateTimeOffset? source = @DateTimeOffset; 22 | value = source; 23 | Assert.Equal(source, value.As()); 24 | Assert.Equal(typeof(DateTimeOffset), value.Type); 25 | } 26 | 27 | [Theory] 28 | [MemberData(nameof(DateTimeOffsetData))] 29 | public void DateTimeOffsetInOut(DateTimeOffset @DateTimeOffset) 30 | { 31 | Value value = new(@DateTimeOffset); 32 | bool success = value.TryGetValue(out DateTimeOffset result); 33 | Assert.True(success); 34 | Assert.Equal(@DateTimeOffset, result); 35 | 36 | Assert.Equal(@DateTimeOffset, value.As()); 37 | Assert.Equal(@DateTimeOffset, (DateTimeOffset)value); 38 | } 39 | 40 | [Theory] 41 | [MemberData(nameof(DateTimeOffsetData))] 42 | public void NullableDateTimeOffsetInDateTimeOffsetOut(DateTimeOffset? @DateTimeOffset) 43 | { 44 | DateTimeOffset? source = @DateTimeOffset; 45 | Value value = new(source); 46 | 47 | bool success = value.TryGetValue(out DateTimeOffset result); 48 | Assert.True(success); 49 | Assert.Equal(@DateTimeOffset, result); 50 | 51 | Assert.Equal(@DateTimeOffset, value.As()); 52 | 53 | Assert.Equal(@DateTimeOffset, (DateTimeOffset)value); 54 | } 55 | 56 | [Theory] 57 | [MemberData(nameof(DateTimeOffsetData))] 58 | public void DateTimeOffsetInNullableDateTimeOffsetOut(DateTimeOffset @DateTimeOffset) 59 | { 60 | DateTimeOffset source = @DateTimeOffset; 61 | Value value = new(source); 62 | bool success = value.TryGetValue(out DateTimeOffset? result); 63 | Assert.True(success); 64 | Assert.Equal(@DateTimeOffset, result); 65 | 66 | Assert.Equal(@DateTimeOffset, (DateTimeOffset?)value); 67 | } 68 | 69 | [Fact] 70 | public void NullDateTimeOffset() 71 | { 72 | DateTimeOffset? source = null; 73 | Value value = source; 74 | Assert.Null(value.Type); 75 | Assert.Equal(source, value.As()); 76 | Assert.False(value.As().HasValue); 77 | } 78 | 79 | [Theory] 80 | [MemberData(nameof(DateTimeOffsetData))] 81 | public void OutAsObject(DateTimeOffset @DateTimeOffset) 82 | { 83 | Value value = new(@DateTimeOffset); 84 | object o = value.As(); 85 | Assert.Equal(typeof(DateTimeOffset), o.GetType()); 86 | Assert.Equal(@DateTimeOffset, (DateTimeOffset)o); 87 | 88 | DateTimeOffset? n = @DateTimeOffset; 89 | value = new(n); 90 | o = value.As(); 91 | Assert.Equal(typeof(DateTimeOffset), o.GetType()); 92 | Assert.Equal(@DateTimeOffset, (DateTimeOffset)o); 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /ValueTest/StoringSByte.cs: -------------------------------------------------------------------------------- 1 | namespace ValueTest; 2 | 3 | public class StoringSByte 4 | { 5 | public static TheoryData SByteData => new() 6 | { 7 | { 0 }, 8 | { 42 }, 9 | { sbyte.MaxValue }, 10 | { sbyte.MinValue } 11 | }; 12 | 13 | [Theory] 14 | [MemberData(nameof(SByteData))] 15 | public void SByteImplicit(sbyte @sbyte) 16 | { 17 | Value value = @sbyte; 18 | Assert.Equal(@sbyte, value.As()); 19 | Assert.Equal(typeof(sbyte), value.Type); 20 | 21 | sbyte? source = @sbyte; 22 | value = source; 23 | Assert.Equal(source, value.As()); 24 | Assert.Equal(typeof(sbyte), value.Type); 25 | } 26 | 27 | [Theory] 28 | [MemberData(nameof(SByteData))] 29 | public void SByteCreate(sbyte @sbyte) 30 | { 31 | Value value; 32 | using (MemoryWatch.Create) 33 | { 34 | value = Value.Create(@sbyte); 35 | } 36 | 37 | Assert.Equal(@sbyte, value.As()); 38 | Assert.Equal(typeof(sbyte), value.Type); 39 | 40 | sbyte? source = @sbyte; 41 | 42 | using (MemoryWatch.Create) 43 | { 44 | value = Value.Create(source); 45 | } 46 | 47 | Assert.Equal(source, value.As()); 48 | Assert.Equal(typeof(sbyte), value.Type); 49 | } 50 | 51 | [Theory] 52 | [MemberData(nameof(SByteData))] 53 | public void SByteInOut(sbyte @sbyte) 54 | { 55 | Value value = new(@sbyte); 56 | bool success = value.TryGetValue(out sbyte result); 57 | Assert.True(success); 58 | Assert.Equal(@sbyte, result); 59 | 60 | Assert.Equal(@sbyte, value.As()); 61 | Assert.Equal(@sbyte, (sbyte)value); 62 | } 63 | 64 | [Theory] 65 | [MemberData(nameof(SByteData))] 66 | public void NullableSByteInSByteOut(sbyte? @sbyte) 67 | { 68 | sbyte? source = @sbyte; 69 | Value value = new(source); 70 | 71 | bool success = value.TryGetValue(out sbyte result); 72 | Assert.True(success); 73 | Assert.Equal(@sbyte, result); 74 | 75 | Assert.Equal(@sbyte, value.As()); 76 | 77 | Assert.Equal(@sbyte, (sbyte)value); 78 | } 79 | 80 | [Theory] 81 | [MemberData(nameof(SByteData))] 82 | public void SByteInNullableSByteOut(sbyte @sbyte) 83 | { 84 | sbyte source = @sbyte; 85 | Value value = new(source); 86 | bool success = value.TryGetValue(out sbyte? result); 87 | Assert.True(success); 88 | Assert.Equal(@sbyte, result); 89 | 90 | Assert.Equal(@sbyte, (sbyte?)value); 91 | } 92 | 93 | [Fact] 94 | public void NullSByte() 95 | { 96 | sbyte? source = null; 97 | Value value = source; 98 | Assert.Null(value.Type); 99 | Assert.Equal(source, value.As()); 100 | Assert.False(value.As().HasValue); 101 | } 102 | 103 | [Theory] 104 | [MemberData(nameof(SByteData))] 105 | public void OutAsObject(sbyte @sbyte) 106 | { 107 | Value value = new(@sbyte); 108 | object o = value.As(); 109 | Assert.Equal(typeof(sbyte), o.GetType()); 110 | Assert.Equal(@sbyte, (sbyte)o); 111 | 112 | sbyte? n = @sbyte; 113 | value = new(n); 114 | o = value.As(); 115 | Assert.Equal(typeof(sbyte), o.GetType()); 116 | Assert.Equal(@sbyte, (sbyte)o); 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /ValueTest/StoringInt.cs: -------------------------------------------------------------------------------- 1 | namespace ValueTest; 2 | 3 | public class StoringInt 4 | { 5 | public static TheoryData IntData => new() 6 | { 7 | { 0 }, 8 | { 42 }, 9 | { int.MaxValue }, 10 | { int.MinValue } 11 | }; 12 | 13 | [Theory] 14 | [MemberData(nameof(IntData))] 15 | public void IntImplicit(int @int) 16 | { 17 | Value value = @int; 18 | Assert.Equal(@int, value.As()); 19 | Assert.Equal(typeof(int), value.Type); 20 | 21 | int? source = @int; 22 | value = source; 23 | Assert.Equal(source, value.As()); 24 | Assert.Equal(typeof(int), value.Type); 25 | } 26 | 27 | [Theory] 28 | [MemberData(nameof(IntData))] 29 | public void IntCreate(int @int) 30 | { 31 | Value value; 32 | using (MemoryWatch.Create) 33 | { 34 | value = Value.Create(@int); 35 | } 36 | 37 | Assert.Equal(@int, value.As()); 38 | Assert.Equal(typeof(int), value.Type); 39 | 40 | int? source = @int; 41 | 42 | using (MemoryWatch.Create) 43 | { 44 | value = Value.Create(source); 45 | } 46 | 47 | Assert.Equal(source, value.As()); 48 | Assert.Equal(typeof(int), value.Type); 49 | } 50 | 51 | [Theory] 52 | [MemberData(nameof(IntData))] 53 | public void IntInOut(int @int) 54 | { 55 | Value value = new(@int); 56 | bool success = value.TryGetValue(out int result); 57 | Assert.True(success); 58 | Assert.Equal(@int, result); 59 | 60 | Assert.Equal(@int, value.As()); 61 | Assert.Equal(@int, (int)value); 62 | } 63 | 64 | [Theory] 65 | [MemberData(nameof(IntData))] 66 | public void NullableIntInIntOut(int? @int) 67 | { 68 | int? source = @int; 69 | Value value = new(source); 70 | 71 | bool success = value.TryGetValue(out int result); 72 | Assert.True(success); 73 | Assert.Equal(@int, result); 74 | 75 | Assert.Equal(@int, value.As()); 76 | 77 | Assert.Equal(@int, (int)value); 78 | } 79 | 80 | [Theory] 81 | [MemberData(nameof(IntData))] 82 | public void IntInNullableIntOut(int @int) 83 | { 84 | int source = @int; 85 | Value value = new(source); 86 | Assert.True(value.TryGetValue(out int? result)); 87 | Assert.Equal(@int, result); 88 | 89 | Assert.Equal(@int, (int?)value); 90 | } 91 | 92 | [Theory] 93 | [MemberData(nameof(IntData))] 94 | public void BoxedInt(int @int) 95 | { 96 | int i = @int; 97 | object o = i; 98 | Value value = new(o); 99 | 100 | Assert.Equal(typeof(int), value.Type); 101 | Assert.True(value.TryGetValue(out int result)); 102 | Assert.Equal(@int, result); 103 | Assert.True(value.TryGetValue(out int? nullableResult)); 104 | Assert.Equal(@int, nullableResult!.Value); 105 | 106 | 107 | int? n = @int; 108 | o = n; 109 | value = new(o); 110 | 111 | Assert.Equal(typeof(int), value.Type); 112 | Assert.True(value.TryGetValue(out result)); 113 | Assert.Equal(@int, result); 114 | Assert.True(value.TryGetValue(out nullableResult)); 115 | Assert.Equal(@int, nullableResult!.Value); 116 | } 117 | 118 | [Fact] 119 | public void NullInt() 120 | { 121 | int? source = null; 122 | Value value = source; 123 | Assert.Null(value.Type); 124 | Assert.Equal(source, value.As()); 125 | Assert.False(value.As().HasValue); 126 | } 127 | 128 | [Theory] 129 | [MemberData(nameof(IntData))] 130 | public void OutAsObject(int @int) 131 | { 132 | Value value = new(@int); 133 | object o = value.As(); 134 | Assert.Equal(typeof(int), o.GetType()); 135 | Assert.Equal(@int, (int)o); 136 | 137 | int? n = @int; 138 | value = new(n); 139 | o = value.As(); 140 | Assert.Equal(typeof(int), o.GetType()); 141 | Assert.Equal(@int, (int)o); 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /ValueTest/StoringByte.cs: -------------------------------------------------------------------------------- 1 | namespace ValueTest; 2 | 3 | public class StoringByte 4 | { 5 | public static TheoryData ByteData => new() 6 | { 7 | { 42 }, 8 | { byte.MaxValue }, 9 | { byte.MinValue } 10 | }; 11 | 12 | [Theory] 13 | [MemberData(nameof(ByteData))] 14 | public void ByteImplicit(byte @byte) 15 | { 16 | Value value = @byte; 17 | Assert.Equal(@byte, value.As()); 18 | Assert.Equal(typeof(byte), value.Type); 19 | 20 | byte? source = @byte; 21 | value = source; 22 | Assert.Equal(source, value.As()); 23 | Assert.Equal(typeof(byte), value.Type); 24 | } 25 | 26 | [Theory] 27 | [MemberData(nameof(ByteData))] 28 | public void ByteCreate(byte @byte) 29 | { 30 | Value value; 31 | using (MemoryWatch.Create) 32 | { 33 | value = Value.Create(@byte); 34 | } 35 | 36 | Assert.Equal(@byte, value.As()); 37 | Assert.Equal(typeof(byte), value.Type); 38 | 39 | byte? source = @byte; 40 | 41 | using (MemoryWatch.Create) 42 | { 43 | value = Value.Create(source); 44 | } 45 | 46 | Assert.Equal(source, value.As()); 47 | Assert.Equal(typeof(byte), value.Type); 48 | } 49 | 50 | [Theory] 51 | [MemberData(nameof(ByteData))] 52 | public void ByteInOut(byte @byte) 53 | { 54 | Value value = new(@byte); 55 | bool success = value.TryGetValue(out byte result); 56 | Assert.True(success); 57 | Assert.Equal(@byte, result); 58 | 59 | Assert.Equal(@byte, value.As()); 60 | Assert.Equal(@byte, (byte)value); 61 | } 62 | 63 | [Theory] 64 | [MemberData(nameof(ByteData))] 65 | public void NullableByteInByteOut(byte? @byte) 66 | { 67 | byte? source = @byte; 68 | Value value = new(source); 69 | 70 | bool success = value.TryGetValue(out byte result); 71 | Assert.True(success); 72 | Assert.Equal(@byte, result); 73 | 74 | Assert.Equal(@byte, value.As()); 75 | 76 | Assert.Equal(@byte, (byte)value); 77 | } 78 | 79 | [Theory] 80 | [MemberData(nameof(ByteData))] 81 | public void ByteInNullableByteOut(byte @byte) 82 | { 83 | byte source = @byte; 84 | Value value = new(source); 85 | bool success = value.TryGetValue(out byte? result); 86 | Assert.True(success); 87 | Assert.Equal(@byte, result); 88 | 89 | Assert.Equal(@byte, (byte?)value); 90 | } 91 | 92 | [Theory] 93 | [MemberData(nameof(ByteData))] 94 | public void BoxedByte(byte @byte) 95 | { 96 | byte i = @byte; 97 | object o = i; 98 | Value value = new(o); 99 | 100 | Assert.Equal(typeof(byte), value.Type); 101 | Assert.True(value.TryGetValue(out byte result)); 102 | Assert.Equal(@byte, result); 103 | Assert.True(value.TryGetValue(out byte? nullableResult)); 104 | Assert.Equal(@byte, nullableResult!.Value); 105 | 106 | 107 | byte? n = @byte; 108 | o = n; 109 | value = new(o); 110 | 111 | Assert.Equal(typeof(byte), value.Type); 112 | Assert.True(value.TryGetValue(out result)); 113 | Assert.Equal(@byte, result); 114 | Assert.True(value.TryGetValue(out nullableResult)); 115 | Assert.Equal(@byte, nullableResult!.Value); 116 | } 117 | 118 | [Fact] 119 | public void NullByte() 120 | { 121 | byte? source = null; 122 | Value value = source; 123 | Assert.Null(value.Type); 124 | Assert.Equal(source, value.As()); 125 | Assert.False(value.As().HasValue); 126 | } 127 | 128 | [Theory] 129 | [MemberData(nameof(ByteData))] 130 | public void OutAsObject(byte @byte) 131 | { 132 | Value value = new(@byte); 133 | object o = value.As(); 134 | Assert.Equal(typeof(byte), o.GetType()); 135 | Assert.Equal(@byte, (byte)o); 136 | 137 | byte? n = @byte; 138 | value = new(n); 139 | o = value.As(); 140 | Assert.Equal(typeof(byte), o.GetType()); 141 | Assert.Equal(@byte, (byte)o); 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /ValueTest/StoringChar.cs: -------------------------------------------------------------------------------- 1 | namespace ValueTest; 2 | 3 | public class StoringChar 4 | { 5 | public static TheoryData CharData => new() 6 | { 7 | { '!' }, 8 | { char.MaxValue }, 9 | { char.MinValue } 10 | }; 11 | 12 | [Theory] 13 | [MemberData(nameof(CharData))] 14 | public void CharImplicit(char @char) 15 | { 16 | Value value = @char; 17 | Assert.Equal(@char, value.As()); 18 | Assert.Equal(typeof(char), value.Type); 19 | 20 | char? source = @char; 21 | value = source; 22 | Assert.Equal(source, value.As()); 23 | Assert.Equal(typeof(char), value.Type); 24 | } 25 | 26 | [Theory] 27 | [MemberData(nameof(CharData))] 28 | public void CharCreate(char @char) 29 | { 30 | Value value; 31 | using (MemoryWatch.Create) 32 | { 33 | value = Value.Create(@char); 34 | } 35 | 36 | Assert.Equal(@char, value.As()); 37 | Assert.Equal(typeof(char), value.Type); 38 | 39 | char? source = @char; 40 | 41 | using (MemoryWatch.Create) 42 | { 43 | value = Value.Create(source); 44 | } 45 | 46 | Assert.Equal(source, value.As()); 47 | Assert.Equal(typeof(char), value.Type); 48 | } 49 | 50 | [Theory] 51 | [MemberData(nameof(CharData))] 52 | public void CharInOut(char @char) 53 | { 54 | Value value = new(@char); 55 | bool success = value.TryGetValue(out char result); 56 | Assert.True(success); 57 | Assert.Equal(@char, result); 58 | 59 | Assert.Equal(@char, value.As()); 60 | Assert.Equal(@char, (char)value); 61 | } 62 | 63 | [Theory] 64 | [MemberData(nameof(CharData))] 65 | public void NullableCharInCharOut(char? @char) 66 | { 67 | char? source = @char; 68 | Value value = new(source); 69 | 70 | bool success = value.TryGetValue(out char result); 71 | Assert.True(success); 72 | Assert.Equal(@char, result); 73 | 74 | Assert.Equal(@char, value.As()); 75 | 76 | Assert.Equal(@char, (char)value); 77 | } 78 | 79 | [Theory] 80 | [MemberData(nameof(CharData))] 81 | public void CharInNullableCharOut(char @char) 82 | { 83 | char source = @char; 84 | Value value = new(source); 85 | bool success = value.TryGetValue(out char? result); 86 | Assert.True(success); 87 | Assert.Equal(@char, result); 88 | 89 | Assert.Equal(@char, (char?)value); 90 | } 91 | 92 | [Theory] 93 | [MemberData(nameof(CharData))] 94 | public void BoxedChar(char @char) 95 | { 96 | char i = @char; 97 | object o = i; 98 | Value value = new(o); 99 | 100 | Assert.Equal(typeof(char), value.Type); 101 | Assert.True(value.TryGetValue(out char result)); 102 | Assert.Equal(@char, result); 103 | Assert.True(value.TryGetValue(out char? nullableResult)); 104 | Assert.Equal(@char, nullableResult!.Value); 105 | 106 | 107 | char? n = @char; 108 | o = n; 109 | value = new(o); 110 | 111 | Assert.Equal(typeof(char), value.Type); 112 | Assert.True(value.TryGetValue(out result)); 113 | Assert.Equal(@char, result); 114 | Assert.True(value.TryGetValue(out nullableResult)); 115 | Assert.Equal(@char, nullableResult!.Value); 116 | } 117 | 118 | [Fact] 119 | public void NullChar() 120 | { 121 | char? source = null; 122 | Value value = source; 123 | Assert.Null(value.Type); 124 | Assert.Equal(source, value.As()); 125 | Assert.False(value.As().HasValue); 126 | } 127 | 128 | [Theory] 129 | [MemberData(nameof(CharData))] 130 | public void OutAsObject(char @char) 131 | { 132 | Value value = new(@char); 133 | object o = value.As(); 134 | Assert.Equal(typeof(char), o.GetType()); 135 | Assert.Equal(@char, (char)o); 136 | 137 | char? n = @char; 138 | value = new(n); 139 | o = value.As(); 140 | Assert.Equal(typeof(char), o.GetType()); 141 | Assert.Equal(@char, (char)o); 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /ValueTest/StoringUInt.cs: -------------------------------------------------------------------------------- 1 | namespace ValueTest; 2 | 3 | public class StoringUInt 4 | { 5 | public static TheoryData UIntData => new() 6 | { 7 | { 42 }, 8 | { uint.MaxValue }, 9 | { uint.MinValue } 10 | }; 11 | 12 | [Theory] 13 | [MemberData(nameof(UIntData))] 14 | public void UIntImplicit(uint @uint) 15 | { 16 | Value value = @uint; 17 | Assert.Equal(@uint, value.As()); 18 | Assert.Equal(typeof(uint), value.Type); 19 | 20 | uint? source = @uint; 21 | value = source; 22 | Assert.Equal(source, value.As()); 23 | Assert.Equal(typeof(uint), value.Type); 24 | } 25 | 26 | [Theory] 27 | [MemberData(nameof(UIntData))] 28 | public void UIntCreate(uint @uint) 29 | { 30 | Value value; 31 | using (MemoryWatch.Create) 32 | { 33 | value = Value.Create(@uint); 34 | } 35 | 36 | Assert.Equal(@uint, value.As()); 37 | Assert.Equal(typeof(uint), value.Type); 38 | 39 | uint? source = @uint; 40 | 41 | using (MemoryWatch.Create) 42 | { 43 | value = Value.Create(source); 44 | } 45 | 46 | Assert.Equal(source, value.As()); 47 | Assert.Equal(typeof(uint), value.Type); 48 | } 49 | 50 | [Theory] 51 | [MemberData(nameof(UIntData))] 52 | public void UIntInOut(uint @uint) 53 | { 54 | Value value = new(@uint); 55 | bool success = value.TryGetValue(out uint result); 56 | Assert.True(success); 57 | Assert.Equal(@uint, result); 58 | 59 | Assert.Equal(@uint, value.As()); 60 | Assert.Equal(@uint, (uint)value); 61 | } 62 | 63 | [Theory] 64 | [MemberData(nameof(UIntData))] 65 | public void NullableUIntInUIntOut(uint? @uint) 66 | { 67 | uint? source = @uint; 68 | Value value = new(source); 69 | 70 | bool success = value.TryGetValue(out uint result); 71 | Assert.True(success); 72 | Assert.Equal(@uint, result); 73 | 74 | Assert.Equal(@uint, value.As()); 75 | 76 | Assert.Equal(@uint, (uint)value); 77 | } 78 | 79 | [Theory] 80 | [MemberData(nameof(UIntData))] 81 | public void UIntInNullableUIntOut(uint @uint) 82 | { 83 | uint source = @uint; 84 | Value value = new(source); 85 | bool success = value.TryGetValue(out uint? result); 86 | Assert.True(success); 87 | Assert.Equal(@uint, result); 88 | 89 | Assert.Equal(@uint, (uint?)value); 90 | } 91 | 92 | [Theory] 93 | [MemberData(nameof(UIntData))] 94 | public void BoxedUInt(uint @uint) 95 | { 96 | uint i = @uint; 97 | object o = i; 98 | Value value = new(o); 99 | 100 | Assert.Equal(typeof(uint), value.Type); 101 | Assert.True(value.TryGetValue(out uint result)); 102 | Assert.Equal(@uint, result); 103 | Assert.True(value.TryGetValue(out uint? nullableResult)); 104 | Assert.Equal(@uint, nullableResult!.Value); 105 | 106 | 107 | uint? n = @uint; 108 | o = n; 109 | value = new(o); 110 | 111 | Assert.Equal(typeof(uint), value.Type); 112 | Assert.True(value.TryGetValue(out result)); 113 | Assert.Equal(@uint, result); 114 | Assert.True(value.TryGetValue(out nullableResult)); 115 | Assert.Equal(@uint, nullableResult!.Value); 116 | } 117 | 118 | [Fact] 119 | public void NullUInt() 120 | { 121 | uint? source = null; 122 | Value value = source; 123 | Assert.Null(value.Type); 124 | Assert.Equal(source, value.As()); 125 | Assert.False(value.As().HasValue); 126 | } 127 | 128 | [Theory] 129 | [MemberData(nameof(UIntData))] 130 | public void OutAsObject(uint @uint) 131 | { 132 | Value value = new(@uint); 133 | object o = value.As(); 134 | Assert.Equal(typeof(uint), o.GetType()); 135 | Assert.Equal(@uint, (uint)o); 136 | 137 | uint? n = @uint; 138 | value = new(n); 139 | o = value.As(); 140 | Assert.Equal(typeof(uint), o.GetType()); 141 | Assert.Equal(@uint, (uint)o); 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /ValueTest/StoringLong.cs: -------------------------------------------------------------------------------- 1 | namespace ValueTest; 2 | 3 | public class StoringLong 4 | { 5 | public static TheoryData LongData => new() 6 | { 7 | { 0 }, 8 | { 42 }, 9 | { long.MaxValue }, 10 | { long.MinValue } 11 | }; 12 | 13 | [Theory] 14 | [MemberData(nameof(LongData))] 15 | public void LongImplicit(long @long) 16 | { 17 | Value value = @long; 18 | Assert.Equal(@long, value.As()); 19 | Assert.Equal(typeof(long), value.Type); 20 | 21 | long? source = @long; 22 | value = source; 23 | Assert.Equal(source, value.As()); 24 | Assert.Equal(typeof(long), value.Type); 25 | } 26 | 27 | [Theory] 28 | [MemberData(nameof(LongData))] 29 | public void LongCreate(long @long) 30 | { 31 | Value value; 32 | using (MemoryWatch.Create) 33 | { 34 | value = Value.Create(@long); 35 | } 36 | 37 | Assert.Equal(@long, value.As()); 38 | Assert.Equal(typeof(long), value.Type); 39 | 40 | long? source = @long; 41 | 42 | using (MemoryWatch.Create) 43 | { 44 | value = Value.Create(source); 45 | } 46 | 47 | Assert.Equal(source, value.As()); 48 | Assert.Equal(typeof(long), value.Type); 49 | } 50 | 51 | [Theory] 52 | [MemberData(nameof(LongData))] 53 | public void LongInOut(long @long) 54 | { 55 | Value value = new(@long); 56 | bool success = value.TryGetValue(out long result); 57 | Assert.True(success); 58 | Assert.Equal(@long, result); 59 | 60 | Assert.Equal(@long, value.As()); 61 | Assert.Equal(@long, (long)value); 62 | } 63 | 64 | [Theory] 65 | [MemberData(nameof(LongData))] 66 | public void NullableLongInLongOut(long? @long) 67 | { 68 | long? source = @long; 69 | Value value = new(source); 70 | 71 | bool success = value.TryGetValue(out long result); 72 | Assert.True(success); 73 | Assert.Equal(@long, result); 74 | 75 | Assert.Equal(@long, value.As()); 76 | 77 | Assert.Equal(@long, (long)value); 78 | } 79 | 80 | [Theory] 81 | [MemberData(nameof(LongData))] 82 | public void LongInNullableLongOut(long @long) 83 | { 84 | long source = @long; 85 | Value value = new(source); 86 | bool success = value.TryGetValue(out long? result); 87 | Assert.True(success); 88 | Assert.Equal(@long, result); 89 | 90 | Assert.Equal(@long, (long?)value); 91 | } 92 | 93 | [Theory] 94 | [MemberData(nameof(LongData))] 95 | public void BoxedLong(long @long) 96 | { 97 | long i = @long; 98 | object o = i; 99 | Value value = new(o); 100 | 101 | Assert.Equal(typeof(long), value.Type); 102 | Assert.True(value.TryGetValue(out long result)); 103 | Assert.Equal(@long, result); 104 | Assert.True(value.TryGetValue(out long? nullableResult)); 105 | Assert.Equal(@long, nullableResult!.Value); 106 | 107 | 108 | long? n = @long; 109 | o = n; 110 | value = new(o); 111 | 112 | Assert.Equal(typeof(long), value.Type); 113 | Assert.True(value.TryGetValue(out result)); 114 | Assert.Equal(@long, result); 115 | Assert.True(value.TryGetValue(out nullableResult)); 116 | Assert.Equal(@long, nullableResult!.Value); 117 | } 118 | 119 | [Fact] 120 | public void NullLong() 121 | { 122 | long? source = null; 123 | Value value = source; 124 | Assert.Null(value.Type); 125 | Assert.Equal(source, value.As()); 126 | Assert.False(value.As().HasValue); 127 | } 128 | 129 | [Theory] 130 | [MemberData(nameof(LongData))] 131 | public void OutAsObject(long @long) 132 | { 133 | Value value = new(@long); 134 | object o = value.As(); 135 | Assert.Equal(typeof(long), o.GetType()); 136 | Assert.Equal(@long, (long)o); 137 | 138 | long? n = @long; 139 | value = new(n); 140 | o = value.As(); 141 | Assert.Equal(typeof(long), o.GetType()); 142 | Assert.Equal(@long, (long)o); 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /ValueTest/StoringUlong.cs: -------------------------------------------------------------------------------- 1 | namespace ValueTest; 2 | 3 | public class StoringULong 4 | { 5 | public static TheoryData ULongData => new() 6 | { 7 | { 42 }, 8 | { ulong.MaxValue }, 9 | { ulong.MinValue } 10 | }; 11 | 12 | [Theory] 13 | [MemberData(nameof(ULongData))] 14 | public void ULongImplicit(ulong @ulong) 15 | { 16 | Value value = @ulong; 17 | Assert.Equal(@ulong, value.As()); 18 | Assert.Equal(typeof(ulong), value.Type); 19 | 20 | ulong? source = @ulong; 21 | value = source; 22 | Assert.Equal(source, value.As()); 23 | Assert.Equal(typeof(ulong), value.Type); 24 | } 25 | 26 | [Theory] 27 | [MemberData(nameof(ULongData))] 28 | public void ULongCreate(ulong @ulong) 29 | { 30 | Value value; 31 | using (MemoryWatch.Create) 32 | { 33 | value = Value.Create(@ulong); 34 | } 35 | 36 | Assert.Equal(@ulong, value.As()); 37 | Assert.Equal(typeof(ulong), value.Type); 38 | 39 | ulong? source = @ulong; 40 | 41 | using (MemoryWatch.Create) 42 | { 43 | value = Value.Create(source); 44 | } 45 | 46 | Assert.Equal(source, value.As()); 47 | Assert.Equal(typeof(ulong), value.Type); 48 | } 49 | 50 | [Theory] 51 | [MemberData(nameof(ULongData))] 52 | public void ULongInOut(ulong @ulong) 53 | { 54 | Value value = new(@ulong); 55 | bool success = value.TryGetValue(out ulong result); 56 | Assert.True(success); 57 | Assert.Equal(@ulong, result); 58 | 59 | Assert.Equal(@ulong, value.As()); 60 | Assert.Equal(@ulong, (ulong)value); 61 | } 62 | 63 | [Theory] 64 | [MemberData(nameof(ULongData))] 65 | public void NullableULongInULongOut(ulong? @ulong) 66 | { 67 | ulong? source = @ulong; 68 | Value value = new(source); 69 | 70 | bool success = value.TryGetValue(out ulong result); 71 | Assert.True(success); 72 | Assert.Equal(@ulong, result); 73 | 74 | Assert.Equal(@ulong, value.As()); 75 | 76 | Assert.Equal(@ulong, (ulong)value); 77 | } 78 | 79 | [Theory] 80 | [MemberData(nameof(ULongData))] 81 | public void ULongInNullableULongOut(ulong @ulong) 82 | { 83 | ulong source = @ulong; 84 | Value value = new(source); 85 | bool success = value.TryGetValue(out ulong? result); 86 | Assert.True(success); 87 | Assert.Equal(@ulong, result); 88 | 89 | Assert.Equal(@ulong, (ulong?)value); 90 | } 91 | 92 | [Theory] 93 | [MemberData(nameof(ULongData))] 94 | public void BoxedULong(ulong @ulong) 95 | { 96 | ulong i = @ulong; 97 | object o = i; 98 | Value value = new(o); 99 | 100 | Assert.Equal(typeof(ulong), value.Type); 101 | Assert.True(value.TryGetValue(out ulong result)); 102 | Assert.Equal(@ulong, result); 103 | Assert.True(value.TryGetValue(out ulong? nullableResult)); 104 | Assert.Equal(@ulong, nullableResult!.Value); 105 | 106 | 107 | ulong? n = @ulong; 108 | o = n; 109 | value = new(o); 110 | 111 | Assert.Equal(typeof(ulong), value.Type); 112 | Assert.True(value.TryGetValue(out result)); 113 | Assert.Equal(@ulong, result); 114 | Assert.True(value.TryGetValue(out nullableResult)); 115 | Assert.Equal(@ulong, nullableResult!.Value); 116 | } 117 | 118 | [Fact] 119 | public void NullULong() 120 | { 121 | ulong? source = null; 122 | Value value = source; 123 | Assert.Null(value.Type); 124 | Assert.Equal(source, value.As()); 125 | Assert.False(value.As().HasValue); 126 | } 127 | 128 | [Theory] 129 | [MemberData(nameof(ULongData))] 130 | public void OutAsObject(ulong @ulong) 131 | { 132 | Value value = new(@ulong); 133 | object o = value.As(); 134 | Assert.Equal(typeof(ulong), o.GetType()); 135 | Assert.Equal(@ulong, (ulong)o); 136 | 137 | ulong? n = @ulong; 138 | value = new(n); 139 | o = value.As(); 140 | Assert.Equal(typeof(ulong), o.GetType()); 141 | Assert.Equal(@ulong, (ulong)o); 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /ValueTest/StoringShort.cs: -------------------------------------------------------------------------------- 1 | namespace ValueTest; 2 | 3 | public class StoringShort 4 | { 5 | public static TheoryData ShortData => new() 6 | { 7 | { 0 }, 8 | { 42 }, 9 | { short.MaxValue }, 10 | { short.MinValue } 11 | }; 12 | 13 | [Theory] 14 | [MemberData(nameof(ShortData))] 15 | public void ShortImplicit(short @short) 16 | { 17 | Value value = @short; 18 | Assert.Equal(@short, value.As()); 19 | Assert.Equal(typeof(short), value.Type); 20 | 21 | short? source = @short; 22 | value = source; 23 | Assert.Equal(source, value.As()); 24 | Assert.Equal(typeof(short), value.Type); 25 | } 26 | 27 | [Theory] 28 | [MemberData(nameof(ShortData))] 29 | public void ShortCreate(short @short) 30 | { 31 | Value value; 32 | using (MemoryWatch.Create) 33 | { 34 | value = Value.Create(@short); 35 | } 36 | 37 | Assert.Equal(@short, value.As()); 38 | Assert.Equal(typeof(short), value.Type); 39 | 40 | short? source = @short; 41 | 42 | using (MemoryWatch.Create) 43 | { 44 | value = Value.Create(source); 45 | } 46 | 47 | Assert.Equal(source, value.As()); 48 | Assert.Equal(typeof(short), value.Type); 49 | } 50 | 51 | [Theory] 52 | [MemberData(nameof(ShortData))] 53 | public void ShortInOut(short @short) 54 | { 55 | Value value = new(@short); 56 | bool success = value.TryGetValue(out short result); 57 | Assert.True(success); 58 | Assert.Equal(@short, result); 59 | 60 | Assert.Equal(@short, value.As()); 61 | Assert.Equal(@short, (short)value); 62 | } 63 | 64 | [Theory] 65 | [MemberData(nameof(ShortData))] 66 | public void NullableShortInShortOut(short? @short) 67 | { 68 | short? source = @short; 69 | Value value = new(source); 70 | 71 | bool success = value.TryGetValue(out short result); 72 | Assert.True(success); 73 | Assert.Equal(@short, result); 74 | 75 | Assert.Equal(@short, value.As()); 76 | 77 | Assert.Equal(@short, (short)value); 78 | } 79 | 80 | [Theory] 81 | [MemberData(nameof(ShortData))] 82 | public void ShortInNullableShortOut(short @short) 83 | { 84 | short source = @short; 85 | Value value = new(source); 86 | bool success = value.TryGetValue(out short? result); 87 | Assert.True(success); 88 | Assert.Equal(@short, result); 89 | 90 | Assert.Equal(@short, (short?)value); 91 | } 92 | 93 | [Theory] 94 | [MemberData(nameof(ShortData))] 95 | public void BoxedShort(short @short) 96 | { 97 | short i = @short; 98 | object o = i; 99 | Value value = new(o); 100 | 101 | Assert.Equal(typeof(short), value.Type); 102 | Assert.True(value.TryGetValue(out short result)); 103 | Assert.Equal(@short, result); 104 | Assert.True(value.TryGetValue(out short? nullableResult)); 105 | Assert.Equal(@short, nullableResult!.Value); 106 | 107 | 108 | short? n = @short; 109 | o = n; 110 | value = new(o); 111 | 112 | Assert.Equal(typeof(short), value.Type); 113 | Assert.True(value.TryGetValue(out result)); 114 | Assert.Equal(@short, result); 115 | Assert.True(value.TryGetValue(out nullableResult)); 116 | Assert.Equal(@short, nullableResult!.Value); 117 | } 118 | 119 | [Fact] 120 | public void NullShort() 121 | { 122 | short? source = null; 123 | Value value = source; 124 | Assert.Null(value.Type); 125 | Assert.Equal(source, value.As()); 126 | Assert.False(value.As().HasValue); 127 | } 128 | 129 | [Theory] 130 | [MemberData(nameof(ShortData))] 131 | public void OutAsObject(short @short) 132 | { 133 | Value value = new(@short); 134 | object o = value.As(); 135 | Assert.Equal(typeof(short), o.GetType()); 136 | Assert.Equal(@short, (short)o); 137 | 138 | short? n = @short; 139 | value = new(n); 140 | o = value.As(); 141 | Assert.Equal(typeof(short), o.GetType()); 142 | Assert.Equal(@short, (short)o); 143 | } 144 | } 145 | -------------------------------------------------------------------------------- /ValueTest/StoringUShort.cs: -------------------------------------------------------------------------------- 1 | namespace ValueTest; 2 | 3 | public class StoringUShort 4 | { 5 | public static TheoryData UShortData => new() 6 | { 7 | { 42 }, 8 | { ushort.MaxValue }, 9 | { ushort.MinValue } 10 | }; 11 | 12 | [Theory] 13 | [MemberData(nameof(UShortData))] 14 | public void UShortImplicit(ushort @ushort) 15 | { 16 | Value value = @ushort; 17 | Assert.Equal(@ushort, value.As()); 18 | Assert.Equal(typeof(ushort), value.Type); 19 | 20 | ushort? source = @ushort; 21 | value = source; 22 | Assert.Equal(source, value.As()); 23 | Assert.Equal(typeof(ushort), value.Type); 24 | } 25 | 26 | [Theory] 27 | [MemberData(nameof(UShortData))] 28 | public void UShortCreate(ushort @ushort) 29 | { 30 | Value value; 31 | using (MemoryWatch.Create) 32 | { 33 | value = Value.Create(@ushort); 34 | } 35 | 36 | Assert.Equal(@ushort, value.As()); 37 | Assert.Equal(typeof(ushort), value.Type); 38 | 39 | ushort? source = @ushort; 40 | 41 | using (MemoryWatch.Create) 42 | { 43 | value = Value.Create(source); 44 | } 45 | 46 | Assert.Equal(source, value.As()); 47 | Assert.Equal(typeof(ushort), value.Type); 48 | } 49 | 50 | [Theory] 51 | [MemberData(nameof(UShortData))] 52 | public void UShortInOut(ushort @ushort) 53 | { 54 | Value value = new(@ushort); 55 | bool success = value.TryGetValue(out ushort result); 56 | Assert.True(success); 57 | Assert.Equal(@ushort, result); 58 | 59 | Assert.Equal(@ushort, value.As()); 60 | Assert.Equal(@ushort, (ushort)value); 61 | } 62 | 63 | [Theory] 64 | [MemberData(nameof(UShortData))] 65 | public void NullableUShortInUShortOut(ushort? @ushort) 66 | { 67 | ushort? source = @ushort; 68 | Value value = new(source); 69 | 70 | bool success = value.TryGetValue(out ushort result); 71 | Assert.True(success); 72 | Assert.Equal(@ushort, result); 73 | 74 | Assert.Equal(@ushort, value.As()); 75 | 76 | Assert.Equal(@ushort, (ushort)value); 77 | } 78 | 79 | [Theory] 80 | [MemberData(nameof(UShortData))] 81 | public void UShortInNullableUShortOut(ushort @ushort) 82 | { 83 | ushort source = @ushort; 84 | Value value = new(source); 85 | bool success = value.TryGetValue(out ushort? result); 86 | Assert.True(success); 87 | Assert.Equal(@ushort, result); 88 | 89 | Assert.Equal(@ushort, (ushort?)value); 90 | } 91 | 92 | [Theory] 93 | [MemberData(nameof(UShortData))] 94 | public void BoxedUShort(ushort @ushort) 95 | { 96 | ushort i = @ushort; 97 | object o = i; 98 | Value value = new(o); 99 | 100 | Assert.Equal(typeof(ushort), value.Type); 101 | Assert.True(value.TryGetValue(out ushort result)); 102 | Assert.Equal(@ushort, result); 103 | Assert.True(value.TryGetValue(out ushort? nullableResult)); 104 | Assert.Equal(@ushort, nullableResult!.Value); 105 | 106 | 107 | ushort? n = @ushort; 108 | o = n; 109 | value = new(o); 110 | 111 | Assert.Equal(typeof(ushort), value.Type); 112 | Assert.True(value.TryGetValue(out result)); 113 | Assert.Equal(@ushort, result); 114 | Assert.True(value.TryGetValue(out nullableResult)); 115 | Assert.Equal(@ushort, nullableResult!.Value); 116 | } 117 | 118 | [Fact] 119 | public void NullUShort() 120 | { 121 | ushort? source = null; 122 | Value value = source; 123 | Assert.Null(value.Type); 124 | Assert.Equal(source, value.As()); 125 | Assert.False(value.As().HasValue); 126 | } 127 | 128 | [Theory] 129 | [MemberData(nameof(UShortData))] 130 | public void OutAsObject(ushort @ushort) 131 | { 132 | Value value = new(@ushort); 133 | object o = value.As(); 134 | Assert.Equal(typeof(ushort), o.GetType()); 135 | Assert.Equal(@ushort, (ushort)o); 136 | 137 | ushort? n = @ushort; 138 | value = new(n); 139 | o = value.As(); 140 | Assert.Equal(typeof(ushort), o.GetType()); 141 | Assert.Equal(@ushort, (ushort)o); 142 | } 143 | } 144 | -------------------------------------------------------------------------------- /ValueTest/StoringFloat.cs: -------------------------------------------------------------------------------- 1 | namespace ValueTest; 2 | 3 | public class StoringFloat 4 | { 5 | public static TheoryData FloatData => new() 6 | { 7 | { 0f }, 8 | { 42f }, 9 | { float.MaxValue }, 10 | { float.MinValue }, 11 | { float.NaN }, 12 | { float.NegativeInfinity }, 13 | { float.PositiveInfinity } 14 | }; 15 | 16 | [Theory] 17 | [MemberData(nameof(FloatData))] 18 | public void FloatImplicit(float @float) 19 | { 20 | Value value = @float; 21 | Assert.Equal(@float, value.As()); 22 | Assert.Equal(typeof(float), value.Type); 23 | 24 | float? source = @float; 25 | value = source; 26 | Assert.Equal(source, value.As()); 27 | Assert.Equal(typeof(float), value.Type); 28 | } 29 | 30 | [Theory] 31 | [MemberData(nameof(FloatData))] 32 | public void FloatCreate(float @float) 33 | { 34 | Value value; 35 | using (MemoryWatch.Create) 36 | { 37 | value = Value.Create(@float); 38 | } 39 | 40 | Assert.Equal(@float, value.As()); 41 | Assert.Equal(typeof(float), value.Type); 42 | 43 | float? source = @float; 44 | 45 | using (MemoryWatch.Create) 46 | { 47 | value = Value.Create(source); 48 | } 49 | 50 | Assert.Equal(source, value.As()); 51 | Assert.Equal(typeof(float), value.Type); 52 | } 53 | 54 | [Theory] 55 | [MemberData(nameof(FloatData))] 56 | public void FloatInOut(float @float) 57 | { 58 | Value value = new(@float); 59 | bool success = value.TryGetValue(out float result); 60 | Assert.True(success); 61 | Assert.Equal(@float, result); 62 | 63 | Assert.Equal(@float, value.As()); 64 | Assert.Equal(@float, (float)value); 65 | } 66 | 67 | [Theory] 68 | [MemberData(nameof(FloatData))] 69 | public void NullableFloatInFloatOut(float? @float) 70 | { 71 | float? source = @float; 72 | Value value = new(source); 73 | 74 | bool success = value.TryGetValue(out float result); 75 | Assert.True(success); 76 | Assert.Equal(@float, result); 77 | 78 | Assert.Equal(@float, value.As()); 79 | 80 | Assert.Equal(@float, (float)value); 81 | } 82 | 83 | [Theory] 84 | [MemberData(nameof(FloatData))] 85 | public void FloatInNullableFloatOut(float @float) 86 | { 87 | float source = @float; 88 | Value value = new(source); 89 | bool success = value.TryGetValue(out float? result); 90 | Assert.True(success); 91 | Assert.Equal(@float, result); 92 | 93 | Assert.Equal(@float, (float?)value); 94 | } 95 | 96 | [Theory] 97 | [MemberData(nameof(FloatData))] 98 | public void BoxedFloat(float @float) 99 | { 100 | float i = @float; 101 | object o = i; 102 | Value value = new(o); 103 | 104 | Assert.Equal(typeof(float), value.Type); 105 | Assert.True(value.TryGetValue(out float result)); 106 | Assert.Equal(@float, result); 107 | Assert.True(value.TryGetValue(out float? nullableResult)); 108 | Assert.Equal(@float, nullableResult!.Value); 109 | 110 | 111 | float? n = @float; 112 | o = n; 113 | value = new(o); 114 | 115 | Assert.Equal(typeof(float), value.Type); 116 | Assert.True(value.TryGetValue(out result)); 117 | Assert.Equal(@float, result); 118 | Assert.True(value.TryGetValue(out nullableResult)); 119 | Assert.Equal(@float, nullableResult!.Value); 120 | } 121 | 122 | [Fact] 123 | public void NullFloat() 124 | { 125 | float? source = null; 126 | Value value = source; 127 | Assert.Null(value.Type); 128 | Assert.Equal(source, value.As()); 129 | Assert.False(value.As().HasValue); 130 | } 131 | 132 | [Theory] 133 | [MemberData(nameof(FloatData))] 134 | public void OutAsObject(float @float) 135 | { 136 | Value value = new(@float); 137 | object o = value.As(); 138 | Assert.Equal(typeof(float), o.GetType()); 139 | Assert.Equal(@float, (float)o); 140 | 141 | float? n = @float; 142 | value = new(n); 143 | o = value.As(); 144 | Assert.Equal(typeof(float), o.GetType()); 145 | Assert.Equal(@float, (float)o); 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /ValueTest/StoringDouble.cs: -------------------------------------------------------------------------------- 1 | namespace ValueTest; 2 | 3 | public class StoringDouble 4 | { 5 | public static TheoryData DoubleData => new() 6 | { 7 | { 0d }, 8 | { 42d }, 9 | { double.MaxValue }, 10 | { double.MinValue }, 11 | { double.NaN }, 12 | { double.NegativeInfinity }, 13 | { double.PositiveInfinity } 14 | }; 15 | 16 | [Theory] 17 | [MemberData(nameof(DoubleData))] 18 | public void DoubleImplicit(double @double) 19 | { 20 | Value value = @double; 21 | Assert.Equal(@double, value.As()); 22 | Assert.Equal(typeof(double), value.Type); 23 | 24 | double? source = @double; 25 | value = source; 26 | Assert.Equal(source, value.As()); 27 | Assert.Equal(typeof(double), value.Type); 28 | } 29 | 30 | [Theory] 31 | [MemberData(nameof(DoubleData))] 32 | public void DoubleCreate(double @double) 33 | { 34 | Value value; 35 | using (MemoryWatch.Create) 36 | { 37 | value = Value.Create(@double); 38 | } 39 | 40 | Assert.Equal(@double, value.As()); 41 | Assert.Equal(typeof(double), value.Type); 42 | 43 | double? source = @double; 44 | 45 | using (MemoryWatch.Create) 46 | { 47 | value = Value.Create(source); 48 | } 49 | 50 | Assert.Equal(source, value.As()); 51 | Assert.Equal(typeof(double), value.Type); 52 | } 53 | 54 | [Theory] 55 | [MemberData(nameof(DoubleData))] 56 | public void DoubleInOut(double @double) 57 | { 58 | Value value = new(@double); 59 | bool success = value.TryGetValue(out double result); 60 | Assert.True(success); 61 | Assert.Equal(@double, result); 62 | 63 | Assert.Equal(@double, value.As()); 64 | Assert.Equal(@double, (double)value); 65 | } 66 | 67 | [Theory] 68 | [MemberData(nameof(DoubleData))] 69 | public void NullableDoubleInDoubleOut(double? @double) 70 | { 71 | double? source = @double; 72 | Value value = new(source); 73 | 74 | bool success = value.TryGetValue(out double result); 75 | Assert.True(success); 76 | Assert.Equal(@double, result); 77 | 78 | Assert.Equal(@double, value.As()); 79 | 80 | Assert.Equal(@double, (double)value); 81 | } 82 | 83 | [Theory] 84 | [MemberData(nameof(DoubleData))] 85 | public void DoubleInNullableDoubleOut(double @double) 86 | { 87 | double source = @double; 88 | Value value = new(source); 89 | bool success = value.TryGetValue(out double? result); 90 | Assert.True(success); 91 | Assert.Equal(@double, result); 92 | 93 | Assert.Equal(@double, (double)value); 94 | } 95 | 96 | [Theory] 97 | [MemberData(nameof(DoubleData))] 98 | public void BoxedDouble(double @double) 99 | { 100 | double i = @double; 101 | object o = i; 102 | Value value = new(o); 103 | 104 | Assert.Equal(typeof(double), value.Type); 105 | Assert.True(value.TryGetValue(out double result)); 106 | Assert.Equal(@double, result); 107 | Assert.True(value.TryGetValue(out double? nullableResult)); 108 | Assert.Equal(@double, nullableResult!.Value); 109 | 110 | 111 | double? n = @double; 112 | o = n; 113 | value = new(o); 114 | 115 | Assert.Equal(typeof(double), value.Type); 116 | Assert.True(value.TryGetValue(out result)); 117 | Assert.Equal(@double, result); 118 | Assert.True(value.TryGetValue(out nullableResult)); 119 | Assert.Equal(@double, nullableResult!.Value); 120 | } 121 | 122 | [Fact] 123 | public void NullDouble() 124 | { 125 | double? source = null; 126 | Value value = source; 127 | Assert.Null(value.Type); 128 | Assert.Equal(source, value.As()); 129 | Assert.False(value.As().HasValue); 130 | } 131 | 132 | [Theory] 133 | [MemberData(nameof(DoubleData))] 134 | public void OutAsObject(double @double) 135 | { 136 | Value value = new(@double); 137 | object o = value.As(); 138 | Assert.Equal(typeof(double), o.GetType()); 139 | Assert.Equal(@double, (double)o); 140 | 141 | double? n = @double; 142 | value = new(n); 143 | o = value.As(); 144 | Assert.Equal(typeof(double), o.GetType()); 145 | Assert.Equal(@double, (double)o); 146 | } 147 | } 148 | -------------------------------------------------------------------------------- /ValueTest/StoringBoolean.cs: -------------------------------------------------------------------------------- 1 | namespace ValueTest; 2 | 3 | public class StoringBoolean 4 | { 5 | public static TheoryData BoolData => new() 6 | { 7 | { true }, 8 | { false } 9 | }; 10 | 11 | [Theory] 12 | [MemberData(nameof(BoolData))] 13 | public void BooleanImplicit(bool @bool) 14 | { 15 | Value value; 16 | using (MemoryWatch.Create) 17 | { 18 | value = @bool; 19 | } 20 | 21 | Assert.Equal(@bool, value.As()); 22 | Assert.Equal(typeof(bool), value.Type); 23 | 24 | bool? source = @bool; 25 | using (MemoryWatch.Create) 26 | { 27 | value = source; 28 | } 29 | Assert.Equal(source, value.As()); 30 | Assert.Equal(typeof(bool), value.Type); 31 | } 32 | 33 | [Theory] 34 | [MemberData(nameof(BoolData))] 35 | public void BooleanCreate(bool @bool) 36 | { 37 | Value value; 38 | using (MemoryWatch.Create) 39 | { 40 | value = Value.Create(@bool); 41 | } 42 | 43 | Assert.Equal(@bool, value.As()); 44 | Assert.Equal(typeof(bool), value.Type); 45 | 46 | bool? source = @bool; 47 | 48 | using (MemoryWatch.Create) 49 | { 50 | value = Value.Create(source); 51 | } 52 | 53 | Assert.Equal(source, value.As()); 54 | Assert.Equal(typeof(bool), value.Type); 55 | } 56 | 57 | [Theory] 58 | [MemberData(nameof(BoolData))] 59 | public void BooleanInOut(bool @bool) 60 | { 61 | Value value; 62 | bool success; 63 | bool result; 64 | 65 | using (MemoryWatch.Create) 66 | { 67 | value = new(@bool); 68 | success = value.TryGetValue(out result); 69 | } 70 | 71 | Assert.True(success); 72 | Assert.Equal(@bool, result); 73 | 74 | Assert.Equal(@bool, value.As()); 75 | Assert.Equal(@bool, (bool)value); 76 | } 77 | 78 | [Theory] 79 | [MemberData(nameof(BoolData))] 80 | public void NullableBooleanInBooleanOut(bool? @bool) 81 | { 82 | bool? source = @bool; 83 | Value value; 84 | bool success; 85 | bool result; 86 | 87 | using (MemoryWatch.Create) 88 | { 89 | value = new(source); 90 | success = value.TryGetValue(out result); 91 | } 92 | 93 | Assert.True(success); 94 | Assert.Equal(@bool, result); 95 | 96 | Assert.Equal(@bool, value.As()); 97 | 98 | Assert.Equal(@bool, (bool)value); 99 | } 100 | 101 | [Theory] 102 | [MemberData(nameof(BoolData))] 103 | public void BooleanInNullableBooleanOut(bool @bool) 104 | { 105 | bool source = @bool; 106 | Value value = new(source); 107 | bool success = value.TryGetValue(out bool? result); 108 | Assert.True(success); 109 | Assert.Equal(@bool, result); 110 | 111 | Assert.Equal(@bool, (bool?)value); 112 | } 113 | 114 | [Theory] 115 | [MemberData(nameof(BoolData))] 116 | public void BoxedBoolean(bool @bool) 117 | { 118 | bool i = @bool; 119 | object o = i; 120 | Value value = new(o); 121 | 122 | Assert.Equal(typeof(bool), value.Type); 123 | Assert.True(value.TryGetValue(out bool result)); 124 | Assert.Equal(@bool, result); 125 | Assert.True(value.TryGetValue(out bool? nullableResult)); 126 | Assert.Equal(@bool, nullableResult!.Value); 127 | 128 | 129 | bool? n = @bool; 130 | o = n; 131 | value = new(o); 132 | 133 | Assert.Equal(typeof(bool), value.Type); 134 | Assert.True(value.TryGetValue(out result)); 135 | Assert.Equal(@bool, result); 136 | Assert.True(value.TryGetValue(out nullableResult)); 137 | Assert.Equal(@bool, nullableResult!.Value); 138 | } 139 | 140 | [Fact] 141 | public void NullBoolean() 142 | { 143 | bool? source = null; 144 | Value value; 145 | 146 | using (MemoryWatch.Create) 147 | { 148 | value = source; 149 | } 150 | 151 | Assert.Null(value.Type); 152 | Assert.Equal(source, value.As()); 153 | Assert.False(value.As().HasValue); 154 | } 155 | 156 | [Theory] 157 | [MemberData(nameof(BoolData))] 158 | public void OutAsObject(bool @bool) 159 | { 160 | Value value = new(@bool); 161 | object o = value.As(); 162 | Assert.Equal(typeof(bool), o.GetType()); 163 | Assert.Equal(@bool, (bool)o); 164 | 165 | bool? n = @bool; 166 | value = new(n); 167 | o = value.As(); 168 | Assert.Equal(typeof(bool), o.GetType()); 169 | Assert.Equal(@bool, (bool)o); 170 | } 171 | } 172 | -------------------------------------------------------------------------------- /ValueTest/StoringEnum.cs: -------------------------------------------------------------------------------- 1 | namespace ValueTest; 2 | 3 | public class StoringEnum 4 | { 5 | [Fact] 6 | public void BasicFunctionality() 7 | { 8 | InitType(); 9 | DayOfWeek day = DayOfWeek.Monday; 10 | 11 | MemoryWatch watch = MemoryWatch.Create; 12 | Value value = Value.Create(day); 13 | DayOfWeek outDay = value.As(); 14 | watch.Validate(); 15 | 16 | Assert.Equal(day, outDay); 17 | Assert.Equal(typeof(DayOfWeek), value.Type); 18 | } 19 | 20 | [Fact] 21 | public void NullableEnum() 22 | { 23 | DayOfWeek? day = DayOfWeek.Monday; 24 | 25 | Value value = Value.Create(day); 26 | DayOfWeek outDay = value.As(); 27 | 28 | Assert.Equal(day.Value, outDay); 29 | Assert.Equal(typeof(DayOfWeek), value.Type); 30 | } 31 | 32 | [Fact] 33 | public void ToFromNullableEnum() 34 | { 35 | DayOfWeek day = DayOfWeek.Monday; 36 | Value value = Value.Create(day); 37 | Assert.True(value.TryGetValue(out DayOfWeek? nullDay)); 38 | Assert.Equal(day, nullDay); 39 | 40 | value = Value.Create((DayOfWeek?)day); 41 | Assert.True(value.TryGetValue(out DayOfWeek outDay)); 42 | Assert.Equal(day, outDay); 43 | } 44 | 45 | [Fact] 46 | public void BoxedEnum() 47 | { 48 | DayOfWeek day = DayOfWeek.Monday; 49 | Value value = new(day); 50 | Assert.True(value.TryGetValue(out DayOfWeek? nullDay)); 51 | Assert.Equal(day, nullDay); 52 | 53 | value = new((DayOfWeek?)day); 54 | Assert.True(value.TryGetValue(out DayOfWeek outDay)); 55 | Assert.Equal(day, outDay); 56 | } 57 | 58 | [Theory] 59 | [InlineData(ByteEnum.MinValue)] 60 | [InlineData(ByteEnum.MaxValue)] 61 | public void ByteSize(ByteEnum @enum) 62 | { 63 | Value value = Value.Create(@enum); 64 | Assert.True(value.TryGetValue(out ByteEnum result)); 65 | Assert.Equal(@enum, result); 66 | Assert.True(value.TryGetValue(out ByteEnum? nullResult)); 67 | Assert.Equal(@enum, nullResult!.Value); 68 | value = Value.Create((ByteEnum?)@enum); 69 | Assert.True(value.TryGetValue(out result)); 70 | Assert.Equal(@enum, result); 71 | Assert.True(value.TryGetValue(out nullResult)); 72 | Assert.Equal(@enum, nullResult!.Value); 73 | 74 | // Create boxed 75 | value = new(@enum); 76 | Assert.True(value.TryGetValue(out result)); 77 | Assert.Equal(@enum, result); 78 | Assert.True(value.TryGetValue(out nullResult)); 79 | Assert.Equal(@enum, nullResult!.Value); 80 | value = new((ByteEnum?)@enum); 81 | Assert.True(value.TryGetValue(out result)); 82 | Assert.Equal(@enum, result); 83 | Assert.True(value.TryGetValue(out nullResult)); 84 | Assert.Equal(@enum, nullResult!.Value); 85 | } 86 | 87 | [Theory] 88 | [InlineData(ShortEnum.MinValue)] 89 | [InlineData(ShortEnum.MaxValue)] 90 | public void ShortSize(ShortEnum @enum) 91 | { 92 | Value value = Value.Create(@enum); 93 | Assert.True(value.TryGetValue(out ShortEnum result)); 94 | Assert.Equal(@enum, result); 95 | Assert.True(value.TryGetValue(out ShortEnum? nullResult)); 96 | Assert.Equal(@enum, nullResult!.Value); 97 | value = Value.Create((ShortEnum?)@enum); 98 | Assert.True(value.TryGetValue(out result)); 99 | Assert.Equal(@enum, result); 100 | Assert.True(value.TryGetValue(out nullResult)); 101 | Assert.Equal(@enum, nullResult!.Value); 102 | 103 | // Create boxed 104 | value = new(@enum); 105 | Assert.True(value.TryGetValue(out result)); 106 | Assert.Equal(@enum, result); 107 | Assert.True(value.TryGetValue(out nullResult)); 108 | Assert.Equal(@enum, nullResult!.Value); 109 | value = new((ShortEnum?)@enum); 110 | Assert.True(value.TryGetValue(out result)); 111 | Assert.Equal(@enum, result); 112 | Assert.True(value.TryGetValue(out nullResult)); 113 | Assert.Equal(@enum, nullResult!.Value); 114 | } 115 | 116 | [Theory] 117 | [InlineData(LongEnum.MinValue)] 118 | [InlineData(LongEnum.MaxValue)] 119 | public void LongSize(LongEnum @enum) 120 | { 121 | Value value = Value.Create(@enum); 122 | Assert.True(value.TryGetValue(out LongEnum result)); 123 | Assert.Equal(@enum, result); 124 | Assert.True(value.TryGetValue(out LongEnum? nullResult)); 125 | Assert.Equal(@enum, nullResult!.Value); 126 | value = Value.Create((LongEnum?)@enum); 127 | Assert.True(value.TryGetValue(out result)); 128 | Assert.Equal(@enum, result); 129 | Assert.True(value.TryGetValue(out nullResult)); 130 | Assert.Equal(@enum, nullResult!.Value); 131 | 132 | // Create boxed 133 | value = new(@enum); 134 | Assert.True(value.TryGetValue(out result)); 135 | Assert.Equal(@enum, result); 136 | Assert.True(value.TryGetValue(out nullResult)); 137 | Assert.Equal(@enum, nullResult!.Value); 138 | value = new((LongEnum?)@enum); 139 | Assert.True(value.TryGetValue(out result)); 140 | Assert.Equal(@enum, result); 141 | Assert.True(value.TryGetValue(out nullResult)); 142 | Assert.Equal(@enum, nullResult!.Value); 143 | } 144 | 145 | [MethodImpl(MethodImplOptions.NoOptimization | MethodImplOptions.NoInlining)] 146 | internal DayOfWeek InitType() 147 | { 148 | DayOfWeek day = DayOfWeek.Monday; 149 | return Value.Create(day).As(); 150 | } 151 | 152 | public enum ByteEnum : byte 153 | { 154 | MinValue = byte.MinValue, 155 | MaxValue = byte.MaxValue 156 | } 157 | 158 | public enum ShortEnum : short 159 | { 160 | MinValue = short.MinValue, 161 | MaxValue = short.MaxValue 162 | } 163 | 164 | public enum LongEnum : long 165 | { 166 | MinValue = long.MinValue, 167 | MaxValue = long.MaxValue 168 | } 169 | } 170 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Oo]ut/ 33 | [Ll]og/ 34 | [Ll]ogs/ 35 | 36 | # Visual Studio 2015/2017 cache/options directory 37 | .vs/ 38 | # Uncomment if you have tasks that create the project's static files in wwwroot 39 | #wwwroot/ 40 | 41 | # Visual Studio 2017 auto generated files 42 | Generated\ Files/ 43 | 44 | # MSTest test Results 45 | [Tt]est[Rr]esult*/ 46 | [Bb]uild[Ll]og.* 47 | 48 | # NUnit 49 | *.VisualState.xml 50 | TestResult.xml 51 | nunit-*.xml 52 | 53 | # Build Results of an ATL Project 54 | [Dd]ebugPS/ 55 | [Rr]eleasePS/ 56 | dlldata.c 57 | 58 | # Benchmark Results 59 | BenchmarkDotNet.Artifacts/ 60 | 61 | # .NET Core 62 | project.lock.json 63 | project.fragment.lock.json 64 | artifacts/ 65 | 66 | # ASP.NET Scaffolding 67 | ScaffoldingReadMe.txt 68 | 69 | # StyleCop 70 | StyleCopReport.xml 71 | 72 | # Files built by Visual Studio 73 | *_i.c 74 | *_p.c 75 | *_h.h 76 | *.ilk 77 | *.meta 78 | *.obj 79 | *.iobj 80 | *.pch 81 | *.pdb 82 | *.ipdb 83 | *.pgc 84 | *.pgd 85 | *.rsp 86 | *.sbr 87 | *.tlb 88 | *.tli 89 | *.tlh 90 | *.tmp 91 | *.tmp_proj 92 | *_wpftmp.csproj 93 | *.log 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio LightSwitch build output 298 | **/*.HTMLClient/GeneratedArtifacts 299 | **/*.DesktopClient/GeneratedArtifacts 300 | **/*.DesktopClient/ModelManifest.xml 301 | **/*.Server/GeneratedArtifacts 302 | **/*.Server/ModelManifest.xml 303 | _Pvt_Extensions 304 | 305 | # Paket dependency manager 306 | .paket/paket.exe 307 | paket-files/ 308 | 309 | # FAKE - F# Make 310 | .fake/ 311 | 312 | # CodeRush personal settings 313 | .cr/personal 314 | 315 | # Python Tools for Visual Studio (PTVS) 316 | __pycache__/ 317 | *.pyc 318 | 319 | # Cake - Uncomment if you are using it 320 | # tools/** 321 | # !tools/packages.config 322 | 323 | # Tabs Studio 324 | *.tss 325 | 326 | # Telerik's JustMock configuration file 327 | *.jmconfig 328 | 329 | # BizTalk build output 330 | *.btp.cs 331 | *.btm.cs 332 | *.odx.cs 333 | *.xsd.cs 334 | 335 | # OpenCover UI analysis results 336 | OpenCover/ 337 | 338 | # Azure Stream Analytics local run output 339 | ASALocalRun/ 340 | 341 | # MSBuild Binary and Structured Log 342 | *.binlog 343 | 344 | # NVidia Nsight GPU debugger configuration file 345 | *.nvuser 346 | 347 | # MFractors (Xamarin productivity tool) working folder 348 | .mfractor/ 349 | 350 | # Local History for Visual Studio 351 | .localhistory/ 352 | 353 | # BeatPulse healthcheck temp database 354 | healthchecksdb 355 | 356 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 357 | MigrationBackup/ 358 | 359 | # Ionide (cross platform F# VS Code tools) working folder 360 | .ionide/ 361 | 362 | # Fody - auto-generated XML schema 363 | FodyWeavers.xsd -------------------------------------------------------------------------------- /ValuePrototype/OtherPrototypes/ValueCompact.cs: -------------------------------------------------------------------------------- 1 | #pragma warning disable CS0252 // Possible unintended reference comparison; left hand side needs cast 2 | 3 | namespace ValuePrototype; 4 | 5 | public readonly struct ValueCompact 6 | { 7 | private static readonly object NullInt32 = new(); 8 | 9 | private readonly long _i64; 10 | private readonly object? _obj; 11 | 12 | public ValueCompact(object? obj) 13 | { 14 | Debug.Assert(obj is null || obj.GetType() != typeof(Type)); 15 | _obj = obj; 16 | _i64 = 0; 17 | } 18 | 19 | public Type? Type 20 | { 21 | get 22 | { 23 | if (_obj is null) 24 | { 25 | return null; 26 | } 27 | 28 | var type = _obj as Type; 29 | if (type != null) return type; 30 | 31 | type = _obj.GetType(); 32 | 33 | if (type == typeof(byte[])) return typeof(string); 34 | if (type == typeof(object)) 35 | { 36 | if (_obj == NullInt32) return typeof(int?); 37 | } 38 | if (type == typeof(TypeBox)) return typeof(Type); 39 | 40 | return type; 41 | } 42 | } 43 | 44 | #region Int32 45 | public ValueCompact(int value) 46 | { 47 | _obj = typeof(int); 48 | _i64 = value; 49 | } 50 | 51 | public static implicit operator ValueCompact(int value) 52 | { 53 | return new ValueCompact(value); 54 | } 55 | 56 | public static explicit operator int(ValueCompact variant) 57 | { 58 | if (variant._obj is null || !variant._obj.Equals(typeof(int))) throw new InvalidCastException(); 59 | return (int)variant._i64; 60 | } 61 | 62 | #endregion 63 | 64 | #region Nullable 65 | public ValueCompact(int? value) 66 | { 67 | if (value.HasValue) 68 | { 69 | _obj = typeof(int?); 70 | _i64 = value.Value; 71 | } 72 | else 73 | { 74 | _obj = NullInt32; 75 | _i64 = default; 76 | } 77 | } 78 | 79 | public static implicit operator ValueCompact(int? value) 80 | { 81 | return new ValueCompact(value); 82 | } 83 | 84 | public static explicit operator int?(ValueCompact variant) 85 | { 86 | if (variant._obj == NullInt32) return null; 87 | if (variant._obj is not null && variant._obj.Equals(typeof(int?))) return (int)variant._i64; 88 | throw new InvalidCastException(); 89 | } 90 | 91 | #endregion 92 | 93 | #region Double 94 | public ValueCompact(double value) 95 | { 96 | _obj = typeof(double); 97 | _i64 = Unsafe.As(ref value); 98 | } 99 | 100 | public static implicit operator ValueCompact(double value) 101 | { 102 | return new ValueCompact(value); 103 | } 104 | 105 | public static explicit operator double(ValueCompact variant) 106 | { 107 | if (variant._obj is null || !variant._obj.Equals(typeof(double))) throw new InvalidCastException(); 108 | var representation = variant._i64; 109 | return Unsafe.As(ref representation); 110 | } 111 | #endregion 112 | 113 | #region String 114 | public ValueCompact(string value) 115 | { 116 | _obj = value; 117 | _i64 = default; 118 | } 119 | 120 | public static implicit operator ValueCompact(string value) 121 | { 122 | return new ValueCompact(value); 123 | } 124 | 125 | public ValueCompact(byte[] utf8, int index, int count) 126 | { 127 | _obj = utf8; 128 | _i64 = index << 32 | count; 129 | } 130 | 131 | public static explicit operator string(ValueCompact variant) 132 | { 133 | string? str = variant._obj as string; 134 | if (str is not null) 135 | { 136 | return str; 137 | } 138 | 139 | byte[]? utf8 = variant._obj as byte[]; 140 | if (utf8 is not null) 141 | { 142 | var decoded = Encoding.UTF8.GetString(utf8, (int)(variant._i64 << 32), (int)variant._i64); 143 | return decoded; 144 | } 145 | 146 | throw new InvalidCastException(); 147 | } 148 | #endregion 149 | 150 | #region DateTimeOffset 151 | public ValueCompact(DateTimeOffset value) 152 | { 153 | if (value.Offset.Ticks == 0) 154 | { 155 | _i64 = value.Ticks; 156 | _obj = typeof(DateTimeOffset); 157 | } 158 | else 159 | { 160 | _obj = value; 161 | _i64 = 0; 162 | } 163 | } 164 | 165 | public static implicit operator ValueCompact(DateTimeOffset value) 166 | { 167 | return new ValueCompact(value); 168 | } 169 | 170 | public static explicit operator DateTimeOffset(ValueCompact variant) 171 | { 172 | if (variant._obj?.Equals(typeof(DateTimeOffset)) == true) 173 | { 174 | return new DateTimeOffset(variant._i64, TimeSpan.Zero); 175 | } 176 | 177 | if (variant._obj is DateTimeOffset dto) 178 | { 179 | return dto; 180 | } 181 | 182 | throw new InvalidCastException(); 183 | } 184 | #endregion 185 | 186 | #region DateTime 187 | public ValueCompact(DateTime value) 188 | { 189 | if (value.Kind == DateTimeKind.Utc) 190 | { 191 | _i64 = value.Ticks; 192 | _obj = typeof(DateTime); 193 | } 194 | else 195 | { 196 | _obj = value; 197 | _i64 = 0; 198 | } 199 | } 200 | 201 | public static implicit operator ValueCompact(DateTime value) 202 | { 203 | return new ValueCompact(value); 204 | } 205 | 206 | public static explicit operator DateTime(ValueCompact variant) 207 | { 208 | if (variant._obj?.Equals(typeof(DateTime)) == true) 209 | { 210 | return new DateTime(variant._i64, DateTimeKind.Utc); 211 | } 212 | 213 | if (variant._obj is DateTime dto) 214 | { 215 | return dto; 216 | } 217 | 218 | throw new InvalidCastException(); 219 | } 220 | #endregion 221 | 222 | #region Decimal 223 | public ValueCompact(decimal value) 224 | { 225 | _obj = value; 226 | _i64 = default; 227 | } 228 | 229 | public static implicit operator ValueCompact(decimal value) 230 | { 231 | return new ValueCompact(value); 232 | } 233 | 234 | public static explicit operator decimal(ValueCompact variant) 235 | { 236 | if (variant._obj is decimal value) 237 | { 238 | return value; 239 | } 240 | 241 | throw new InvalidCastException(); 242 | } 243 | #endregion 244 | 245 | #region T 246 | public static ValueCompact Create(T value) 247 | { 248 | var type = value as Type; 249 | if (type != null) 250 | { 251 | return new ValueCompact(new TypeBox(type)); 252 | } 253 | 254 | if (value is int i32) return new ValueCompact(i32); 255 | if (value is double d) return new ValueCompact(d); 256 | 257 | return new ValueCompact(value); 258 | } 259 | 260 | public T? As() 261 | { 262 | // if value is stored in _i64 field 263 | if (_obj == typeof(T)) 264 | { 265 | if (_obj.Equals(typeof(int))) 266 | { 267 | return CastTo(); 268 | } 269 | else 270 | { 271 | throw new NotImplementedException(); 272 | } 273 | } 274 | 275 | // if value is stored in _obj field 276 | if (_obj?.GetType() == typeof(T)) return (T)_obj; 277 | 278 | // if value is stored in a "box" 279 | if (typeof(T) == typeof(Type) && _obj is TypeBox box) 280 | { 281 | return (T)(object)box.Value; 282 | } 283 | 284 | if (_obj is null && !typeof(T).IsValueType) 285 | { 286 | return default; 287 | } 288 | 289 | if (typeof(T) == typeof(int) && _obj == typeof(int?)) 290 | { 291 | return CastTo(); 292 | } 293 | 294 | throw new InvalidCastException(); 295 | } 296 | #endregion 297 | 298 | private class TypeBox 299 | { 300 | private readonly Type _value; 301 | 302 | public TypeBox(Type value) => _value = value; 303 | 304 | public Type Value => _value; 305 | } 306 | 307 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 308 | private T CastTo() 309 | { 310 | Debug.Assert(typeof(T).IsPrimitive); 311 | T value = Unsafe.As(ref Unsafe.AsRef(in _i64)); 312 | return value; 313 | } 314 | } 315 | 316 | #pragma warning restore CS0252 // Possible unintended reference comparison; left hand side needs cast 317 | -------------------------------------------------------------------------------- /ValuePrototype/OtherPrototypes/ValueState.cs: -------------------------------------------------------------------------------- 1 | namespace ValuePrototype; 2 | 3 | /// 4 | /// is a wrapper that avoids boxing common value types. 5 | /// 6 | public readonly struct ValueState 7 | { 8 | private readonly Union _union; 9 | private readonly object? _object; 10 | private readonly State _state; 11 | 12 | /// 13 | /// Get the value as an object if the value is stored as an object. 14 | /// 15 | /// The value, if an object, or null. 16 | /// True if the value is actually an object. 17 | public bool TryGetValue(out object? value) 18 | { 19 | bool isObject = _state == State.Object; 20 | value = isObject ? _object : null; 21 | return isObject; 22 | } 23 | 24 | /// 25 | /// Get the value as the requested type if actually stored as that type. 26 | /// 27 | /// The value if stored as (T), or default. 28 | /// True if the is of the requested type. 29 | public unsafe bool TryGetValue(out T value) where T : unmanaged 30 | { 31 | value = default; 32 | bool success = false; 33 | 34 | // Checking the type gets all of the non-relevant compares elided by the JIT 35 | if ((typeof(T) == typeof(bool) && _state == State.Boolean) 36 | || (typeof(T) == typeof(byte) && _state == State.Byte) 37 | || (typeof(T) == typeof(char) && _state == State.Char) 38 | || (typeof(T) == typeof(DateTime) && _state == State.DateTime) 39 | || (typeof(T) == typeof(DateTimeOffset) && _state == State.DateTimeOffset) 40 | || (typeof(T) == typeof(decimal) && _state == State.Decimal) 41 | || (typeof(T) == typeof(double) && _state == State.Double) 42 | || (typeof(T) == typeof(Guid) && _state == State.Guid) 43 | || (typeof(T) == typeof(short) && _state == State.Int16) 44 | || (typeof(T) == typeof(int) && _state == State.Int32) 45 | || (typeof(T) == typeof(long) && _state == State.Int64) 46 | || (typeof(T) == typeof(sbyte) && _state == State.SByte) 47 | || (typeof(T) == typeof(float) && _state == State.Single) 48 | || (typeof(T) == typeof(TimeSpan) && _state == State.TimeSpan) 49 | || (typeof(T) == typeof(ushort) && _state == State.UInt16) 50 | || (typeof(T) == typeof(uint) && _state == State.UInt32) 51 | || (typeof(T) == typeof(ulong) && _state == State.UInt64)) 52 | { 53 | value = CastTo(); 54 | success = true; 55 | } 56 | 57 | return success; 58 | } 59 | 60 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 61 | private T CastTo() where T : unmanaged 62 | { 63 | T value = Unsafe.As(ref Unsafe.AsRef(in _union)); 64 | return value; 65 | } 66 | 67 | // We have explicit constructors for each of the supported types for performance 68 | // and to restrict Variant to "safe" types. Allowing any struct that would fit 69 | // into the Union would expose users to issues where bad struct state could cause 70 | // hard failures like buffer overruns etc. 71 | 72 | // Setting this = default is a bit simpler than setting _object and _union to 73 | // default and generates less assembly / faster construction. 74 | 75 | public ValueState(bool value) 76 | { 77 | this = default; 78 | _union.Boolean = value; 79 | _state = State.Boolean; 80 | } 81 | 82 | public ValueState(byte value) 83 | { 84 | this = default; 85 | _union.Byte = value; 86 | _state = State.Byte; 87 | } 88 | 89 | public ValueState(sbyte value) 90 | { 91 | this = default; 92 | _union.SByte = value; 93 | _state = State.SByte; 94 | } 95 | 96 | public ValueState(short value) 97 | { 98 | this = default; 99 | _union.Int16 = value; 100 | _state = State.Int16; 101 | } 102 | 103 | public ValueState(ushort value) 104 | { 105 | this = default; 106 | _union.UInt16 = value; 107 | _state = State.UInt16; 108 | } 109 | 110 | public ValueState(int value) 111 | { 112 | this = default; 113 | _union.Int32 = value; 114 | _state = State.Int32; 115 | } 116 | 117 | public ValueState(uint value) 118 | { 119 | this = default; 120 | _union.UInt32 = value; 121 | _state = State.UInt32; 122 | } 123 | 124 | public ValueState(long value) 125 | { 126 | this = default; 127 | _union.Int64 = value; 128 | _state = State.Int64; 129 | } 130 | 131 | public ValueState(ulong value) 132 | { 133 | this = default; 134 | _union.UInt64 = value; 135 | _state = State.UInt64; 136 | } 137 | 138 | public ValueState(float value) 139 | { 140 | this = default; 141 | _union.Single = value; 142 | _state = State.Single; 143 | } 144 | 145 | public ValueState(double value) 146 | { 147 | this = default; 148 | _union.Double = value; 149 | _state = State.Double; 150 | } 151 | 152 | public ValueState(decimal value) 153 | { 154 | this = default; 155 | _union.Decimal = value; 156 | _state = State.Decimal; 157 | } 158 | 159 | public ValueState(DateTime value) 160 | { 161 | this = default; 162 | _union.DateTime = value; 163 | _state = State.DateTime; 164 | } 165 | 166 | public ValueState(DateTimeOffset value) 167 | { 168 | this = default; 169 | _union.DateTimeOffset = value; 170 | _state = State.DateTimeOffset; 171 | } 172 | 173 | public ValueState(Guid value) 174 | { 175 | this = default; 176 | _union.Guid = value; 177 | _state = State.Guid; 178 | } 179 | 180 | public ValueState(object value) 181 | { 182 | this = default; 183 | _object = value; 184 | _state = State.Object; 185 | } 186 | 187 | // The Variant struct gets laid out as follows on x64: 188 | // 189 | // | 4 bytes | 4 bytes | 16 bytes | 8 bytes | 190 | // |---------|---------|---------------------------------------|-------------------| 191 | // | Type | Unused | Union | Object | 192 | // 193 | // Layout of the struct is automatic and cannot be modified via [StructLayout]. 194 | // Alignment requirements force Variant to be a multiple of 8 bytes. We could 195 | // shrink from 32 to 24 bytes by either dropping the 16 byte types (DateTimeOffset, 196 | // Decimal, and Guid) or stashing the flags in the Union and leveraging flag objects 197 | // for the types that exceed 8 bytes. (DateTimeOffset might fit in 12, need to test.) 198 | // 199 | // We could theoretically do sneaky things with unused bits in the object pointer, much 200 | // like ATOMs in Window handles (lowest 64K values). Presumably that isn't doable 201 | // without runtime support though (putting "bad" values in an object pointer)? 202 | // 203 | // We could also allow storing arbitrary "unmanaged" values that would fit into 16 bytes. 204 | // In that case we could store the typeof(T) in the _object field. That probably is only 205 | // particularly useful for something like enums. I think we can avoid boxing, would need 206 | // to expose a static entry point for formatting on System.Enum. Something like: 207 | // 208 | // public static string Format(Type enumType, ulong value) 209 | // { 210 | // RuntimeType rtType = enumType as RuntimeType; 211 | // if (rtType == null) 212 | // throw new ArgumentException(SR.Arg_MustBeType, nameof(enumType)); 213 | // 214 | // if (!enumType.IsEnum) 215 | // throw new ArgumentException(SR.Arg_MustBeEnum, nameof(enumType)); 216 | // 217 | // return Enum.InternalFormat(rtType, ulong) ?? ulong.ToString(); 218 | // } 219 | // 220 | // That is the minbar- as the string values are cached it would be a positive. We can 221 | // obviously do even better if we expose a TryFormat that takes an input span. There 222 | // is a little bit more to that, but nothing serious. 223 | 224 | [StructLayout(LayoutKind.Explicit, CharSet = CharSet.Unicode)] 225 | private struct Union 226 | { 227 | [FieldOffset(0)] public byte Byte; 228 | [FieldOffset(0)] public sbyte SByte; 229 | [FieldOffset(0)] public char Char; 230 | [FieldOffset(0)] public bool Boolean; 231 | [FieldOffset(0)] public short Int16; 232 | [FieldOffset(0)] public ushort UInt16; 233 | [FieldOffset(0)] public int Int32; 234 | [FieldOffset(0)] public uint UInt32; 235 | [FieldOffset(0)] public long Int64; 236 | [FieldOffset(0)] public ulong UInt64; 237 | [FieldOffset(0)] public float Single; // 4 bytes 238 | [FieldOffset(0)] public double Double; // 8 bytes 239 | [FieldOffset(0)] public DateTime DateTime; // 8 bytes (ulong) 240 | [FieldOffset(0)] public DateTimeOffset DateTimeOffset; // 16 bytes (DateTime & short) 241 | [FieldOffset(0)] public decimal Decimal; // 16 bytes (4 ints) 242 | [FieldOffset(0)] public Guid Guid; // 16 bytes (int, 2 shorts, 8 bytes) 243 | } 244 | 245 | /// 246 | /// Get the value as an object, boxing if necessary. 247 | /// 248 | public object? Box() 249 | { 250 | return _state switch 251 | { 252 | State.Boolean => CastTo(), 253 | State.Byte => CastTo(), 254 | State.Char => CastTo(), 255 | State.DateTime => CastTo(), 256 | State.DateTimeOffset => CastTo(), 257 | State.Decimal => CastTo(), 258 | State.Double => CastTo(), 259 | State.Guid => CastTo(), 260 | State.Int16 => CastTo(), 261 | State.Int32 => CastTo(), 262 | State.Int64 => CastTo(), 263 | State.Object => _object, 264 | State.SByte => CastTo(), 265 | State.Single => CastTo(), 266 | State.TimeSpan => CastTo(), 267 | State.UInt16 => CastTo(), 268 | State.UInt32 => CastTo(), 269 | State.UInt64 => CastTo(), 270 | _ => throw new InvalidOperationException(), 271 | }; 272 | } 273 | 274 | // Idea is that you can cast to whatever supported type you want if you're explicit. 275 | // Worst case is you get default or nonsense values. 276 | 277 | public static explicit operator bool(in ValueState variant) => variant.CastTo(); 278 | public static explicit operator byte(in ValueState variant) => variant.CastTo(); 279 | public static explicit operator char(in ValueState variant) => variant.CastTo(); 280 | public static explicit operator DateTime(in ValueState variant) => variant.CastTo(); 281 | public static explicit operator DateTimeOffset(in ValueState variant) => variant.CastTo(); 282 | public static explicit operator decimal(in ValueState variant) => variant.CastTo(); 283 | public static explicit operator double(in ValueState variant) => variant.CastTo(); 284 | public static explicit operator Guid(in ValueState variant) => variant.CastTo(); 285 | public static explicit operator short(in ValueState variant) => variant.CastTo(); 286 | public static explicit operator int(in ValueState variant) => variant.CastTo(); 287 | public static explicit operator long(in ValueState variant) => variant.CastTo(); 288 | public static explicit operator sbyte(in ValueState variant) => variant.CastTo(); 289 | public static explicit operator float(in ValueState variant) => variant.CastTo(); 290 | public static explicit operator TimeSpan(in ValueState variant) => variant.CastTo(); 291 | public static explicit operator ushort(in ValueState variant) => variant.CastTo(); 292 | public static explicit operator uint(in ValueState variant) => variant.CastTo(); 293 | public static explicit operator ulong(in ValueState variant) => variant.CastTo(); 294 | 295 | public static implicit operator ValueState(bool value) => new(value); 296 | public static implicit operator ValueState(byte value) => new(value); 297 | public static implicit operator ValueState(char value) => new(value); 298 | public static implicit operator ValueState(DateTime value) => new(value); 299 | public static implicit operator ValueState(DateTimeOffset value) => new(value); 300 | public static implicit operator ValueState(decimal value) => new(value); 301 | public static implicit operator ValueState(double value) => new(value); 302 | public static implicit operator ValueState(Guid value) => new(value); 303 | public static implicit operator ValueState(short value) => new(value); 304 | public static implicit operator ValueState(int value) => new(value); 305 | public static implicit operator ValueState(long value) => new(value); 306 | public static implicit operator ValueState(sbyte value) => new(value); 307 | public static implicit operator ValueState(float value) => new(value); 308 | public static implicit operator ValueState(TimeSpan value) => new(value); 309 | public static implicit operator ValueState(ushort value) => new(value); 310 | public static implicit operator ValueState(uint value) => new(value); 311 | public static implicit operator ValueState(ulong value) => new(value); 312 | 313 | // Common object types 314 | public static implicit operator ValueState(string value) => new(value); 315 | 316 | public static ValueState Create(in ValueState variant) => variant; 317 | //public static Variant2 Create(in Value first, in Value second) => new Variant2(in first, in second); 318 | //public static Variant3 Create(in Value first, in Value second, in Value third) => new Variant3(in first, in second, in third); 319 | 320 | public enum State 321 | { 322 | Object, 323 | Byte, 324 | SByte, 325 | Char, 326 | Boolean, 327 | Int16, 328 | UInt16, 329 | Int32, 330 | UInt32, 331 | Int64, 332 | UInt64, 333 | DateTime, 334 | DateTimeOffset, 335 | TimeSpan, 336 | Single, 337 | Double, 338 | Decimal, 339 | Guid 340 | 341 | // TODO: 342 | // 343 | // We can support arbitrary enums, see comments near the Union definition. 344 | // 345 | // We should also support Memory. This would require access to the internals 346 | // so that we can save the object and the offset/index. (Memory is object/int/int). 347 | // 348 | // Supporting Span would require making Variant a ref struct and access to 349 | // internals at the very least. It isn't clear if we could simply stick a ByReference 350 | // in here or if there would be additional need for runtime changes. 351 | // 352 | // A significant drawback of making Variant a ref struct is that you would no longer be 353 | // able to create Variant[] or Span. 354 | } 355 | } 356 | -------------------------------------------------------------------------------- /ValuePrototype/Value.cs: -------------------------------------------------------------------------------- 1 | namespace ValuePrototype; 2 | 3 | public readonly partial struct Value 4 | { 5 | private readonly Union _union; 6 | private readonly object? _object; 7 | 8 | public Value(object? value) 9 | { 10 | _object = value; 11 | _union = default; 12 | } 13 | 14 | public readonly Type? Type 15 | { 16 | get 17 | { 18 | Type? type; 19 | if (_object is null) 20 | { 21 | type = null; 22 | } 23 | else if (_object is TypeFlag typeFlag) 24 | { 25 | type = typeFlag.Type; 26 | } 27 | else 28 | { 29 | type = _object.GetType(); 30 | 31 | if (_union.UInt64 != 0) 32 | { 33 | Debug.Assert(type.IsArray); 34 | 35 | // We have an ArraySegment 36 | if (type == typeof(byte[])) 37 | { 38 | type = typeof(ArraySegment); 39 | } 40 | else if (type == typeof(char[])) 41 | { 42 | type = typeof(ArraySegment); 43 | } 44 | else 45 | { 46 | Debug.Fail($"Unexpected type {type.Name}."); 47 | } 48 | } 49 | } 50 | 51 | return type; 52 | } 53 | } 54 | 55 | [DoesNotReturn] 56 | private static void ThrowInvalidCast() => throw new InvalidCastException(); 57 | 58 | [DoesNotReturn] 59 | private static void ThrowArgumentNull(string paramName) => throw new ArgumentNullException(paramName); 60 | 61 | [DoesNotReturn] 62 | private static void ThrowInvalidOperation() => throw new InvalidOperationException(); 63 | 64 | #region Byte 65 | public Value(byte value) 66 | { 67 | _object = TypeFlags.Byte; 68 | _union.Byte = value; 69 | } 70 | 71 | public Value(byte? value) 72 | { 73 | if (value.HasValue) 74 | { 75 | _object = TypeFlags.Byte; 76 | _union.Byte = value.Value; 77 | } 78 | else 79 | { 80 | _object = null; 81 | } 82 | } 83 | 84 | public static implicit operator Value(byte value) => new(value); 85 | public static explicit operator byte(in Value value) => value.As(); 86 | public static implicit operator Value(byte? value) => new(value); 87 | public static explicit operator byte?(in Value value) => value.As(); 88 | #endregion 89 | 90 | #region SByte 91 | public Value(sbyte value) 92 | { 93 | _object = TypeFlags.SByte; 94 | _union.SByte = value; 95 | } 96 | 97 | public Value(sbyte? value) 98 | { 99 | if (value.HasValue) 100 | { 101 | _object = TypeFlags.SByte; 102 | _union.SByte = value.Value; 103 | } 104 | else 105 | { 106 | _object = null; 107 | } 108 | } 109 | 110 | public static implicit operator Value(sbyte value) => new(value); 111 | public static explicit operator sbyte(in Value value) => value.As(); 112 | public static implicit operator Value(sbyte? value) => new(value); 113 | public static explicit operator sbyte?(in Value value) => value.As(); 114 | #endregion 115 | 116 | #region Boolean 117 | public Value(bool value) 118 | { 119 | _object = TypeFlags.Boolean; 120 | _union.Boolean = value; 121 | } 122 | 123 | public Value(bool? value) 124 | { 125 | if (value.HasValue) 126 | { 127 | _object = TypeFlags.Boolean; 128 | _union.Boolean = value.Value; 129 | } 130 | else 131 | { 132 | _object = null; 133 | } 134 | } 135 | 136 | public static implicit operator Value(bool value) => new(value); 137 | public static explicit operator bool(in Value value) => value.As(); 138 | public static implicit operator Value(bool? value) => new(value); 139 | public static explicit operator bool?(in Value value) => value.As(); 140 | #endregion 141 | 142 | #region Char 143 | public Value(char value) 144 | { 145 | _object = TypeFlags.Char; 146 | _union.Char = value; 147 | } 148 | 149 | public Value(char? value) 150 | { 151 | if (value.HasValue) 152 | { 153 | _object = TypeFlags.Char; 154 | _union.Char = value.Value; 155 | } 156 | else 157 | { 158 | _object = null; 159 | } 160 | } 161 | 162 | public static implicit operator Value(char value) => new(value); 163 | public static explicit operator char(in Value value) => value.As(); 164 | public static implicit operator Value(char? value) => new(value); 165 | public static explicit operator char?(in Value value) => value.As(); 166 | #endregion 167 | 168 | #region Int16 169 | public Value(short value) 170 | { 171 | _object = TypeFlags.Int16; 172 | _union.Int16 = value; 173 | } 174 | 175 | public Value(short? value) 176 | { 177 | if (value.HasValue) 178 | { 179 | _object = TypeFlags.Int16; 180 | _union.Int16 = value.Value; 181 | } 182 | else 183 | { 184 | _object = null; 185 | } 186 | } 187 | 188 | public static implicit operator Value(short value) => new(value); 189 | public static explicit operator short(in Value value) => value.As(); 190 | public static implicit operator Value(short? value) => new(value); 191 | public static explicit operator short?(in Value value) => value.As(); 192 | #endregion 193 | 194 | #region Int32 195 | public Value(int value) 196 | { 197 | _object = TypeFlags.Int32; 198 | _union.Int32 = value; 199 | } 200 | 201 | public Value(int? value) 202 | { 203 | if (value.HasValue) 204 | { 205 | _object = TypeFlags.Int32; 206 | _union.Int32 = value.Value; 207 | } 208 | else 209 | { 210 | _object = null; 211 | } 212 | } 213 | 214 | public static implicit operator Value(int value) => new(value); 215 | public static explicit operator int(in Value value) => value.As(); 216 | public static implicit operator Value(int? value) => new(value); 217 | public static explicit operator int?(in Value value) => value.As(); 218 | #endregion 219 | 220 | #region Int64 221 | public Value(long value) 222 | { 223 | _object = TypeFlags.Int64; 224 | _union.Int64 = value; 225 | } 226 | 227 | public Value(long? value) 228 | { 229 | if (value.HasValue) 230 | { 231 | _object = TypeFlags.Int64; 232 | _union.Int64 = value.Value; 233 | } 234 | else 235 | { 236 | _object = null; 237 | } 238 | } 239 | 240 | public static implicit operator Value(long value) => new(value); 241 | public static explicit operator long(in Value value) => value.As(); 242 | public static implicit operator Value(long? value) => new(value); 243 | public static explicit operator long?(in Value value) => value.As(); 244 | #endregion 245 | 246 | #region UInt16 247 | public Value(ushort value) 248 | { 249 | _object = TypeFlags.UInt16; 250 | _union.UInt16 = value; 251 | } 252 | 253 | public Value(ushort? value) 254 | { 255 | if (value.HasValue) 256 | { 257 | _object = TypeFlags.UInt16; 258 | _union.UInt16 = value.Value; 259 | } 260 | else 261 | { 262 | _object = null; 263 | } 264 | } 265 | 266 | public static implicit operator Value(ushort value) => new(value); 267 | public static explicit operator ushort(in Value value) => value.As(); 268 | public static implicit operator Value(ushort? value) => new(value); 269 | public static explicit operator ushort?(in Value value) => value.As(); 270 | #endregion 271 | 272 | #region UInt32 273 | public Value(uint value) 274 | { 275 | _object = TypeFlags.UInt32; 276 | _union.UInt32 = value; 277 | } 278 | 279 | public Value(uint? value) 280 | { 281 | if (value.HasValue) 282 | { 283 | _object = TypeFlags.UInt32; 284 | _union.UInt32 = value.Value; 285 | } 286 | else 287 | { 288 | _object = null; 289 | } 290 | } 291 | 292 | public static implicit operator Value(uint value) => new(value); 293 | public static explicit operator uint(in Value value) => value.As(); 294 | public static implicit operator Value(uint? value) => new(value); 295 | public static explicit operator uint?(in Value value) => value.As(); 296 | #endregion 297 | 298 | #region UInt64 299 | public Value(ulong value) 300 | { 301 | _object = TypeFlags.UInt64; 302 | _union.UInt64 = value; 303 | } 304 | 305 | public Value(ulong? value) 306 | { 307 | if (value.HasValue) 308 | { 309 | _object = TypeFlags.UInt64; 310 | _union.UInt64 = value.Value; 311 | } 312 | else 313 | { 314 | _object = null; 315 | } 316 | } 317 | 318 | public static implicit operator Value(ulong value) => new(value); 319 | public static explicit operator ulong(in Value value) => value.As(); 320 | public static implicit operator Value(ulong? value) => new(value); 321 | public static explicit operator ulong?(in Value value) => value.As(); 322 | #endregion 323 | 324 | #region Single 325 | public Value(float value) 326 | { 327 | _object = TypeFlags.Single; 328 | _union.Single = value; 329 | } 330 | 331 | public Value(float? value) 332 | { 333 | if (value.HasValue) 334 | { 335 | _object = TypeFlags.Single; 336 | _union.Single = value.Value; 337 | } 338 | else 339 | { 340 | _object = null; 341 | } 342 | } 343 | 344 | public static implicit operator Value(float value) => new(value); 345 | public static explicit operator float(in Value value) => value.As(); 346 | public static implicit operator Value(float? value) => new(value); 347 | public static explicit operator float?(in Value value) => value.As(); 348 | #endregion 349 | 350 | #region Double 351 | public Value(double value) 352 | { 353 | _object = TypeFlags.Double; 354 | _union.Double = value; 355 | } 356 | 357 | public Value(double? value) 358 | { 359 | if (value.HasValue) 360 | { 361 | _object = TypeFlags.Double; 362 | _union.Double = value.Value; 363 | } 364 | else 365 | { 366 | _object = null; 367 | } 368 | } 369 | 370 | public static implicit operator Value(double value) => new(value); 371 | public static explicit operator double(in Value value) => value.As(); 372 | public static implicit operator Value(double? value) => new(value); 373 | public static explicit operator double?(in Value value) => value.As(); 374 | #endregion 375 | 376 | #region DateTimeOffset 377 | public Value(DateTimeOffset value) 378 | { 379 | TimeSpan offset = value.Offset; 380 | if (offset.Ticks == 0) 381 | { 382 | // This is a UTC time 383 | _union.Ticks = value.Ticks; 384 | _object = TypeFlags.DateTimeOffset; 385 | } 386 | else if (PackedDateTimeOffset.TryCreate(value, offset, out var packed)) 387 | { 388 | _union.PackedDateTimeOffset = packed; 389 | _object = TypeFlags.PackedDateTimeOffset; 390 | } 391 | else 392 | { 393 | _object = value; 394 | } 395 | } 396 | 397 | public Value(DateTimeOffset? value) 398 | { 399 | if (!value.HasValue) 400 | { 401 | _object = null; 402 | } 403 | else 404 | { 405 | this = new(value.Value); 406 | } 407 | } 408 | 409 | public static implicit operator Value(DateTimeOffset value) => new(value); 410 | public static explicit operator DateTimeOffset(in Value value) => value.As(); 411 | public static implicit operator Value(DateTimeOffset? value) => new(value); 412 | public static explicit operator DateTimeOffset?(in Value value) => value.As(); 413 | #endregion 414 | 415 | #region DateTime 416 | public Value(DateTime value) 417 | { 418 | _union.DateTime = value; 419 | _object = TypeFlags.DateTime; 420 | } 421 | 422 | public Value(DateTime? value) 423 | { 424 | if (value.HasValue) 425 | { 426 | _object = TypeFlags.DateTime; 427 | _union.DateTime = value.Value; 428 | } 429 | else 430 | { 431 | _object = value; 432 | } 433 | } 434 | 435 | public static implicit operator Value(DateTime value) => new(value); 436 | public static explicit operator DateTime(in Value value) => value.As(); 437 | public static implicit operator Value(DateTime? value) => new(value); 438 | public static explicit operator DateTime?(in Value value) => value.As(); 439 | #endregion 440 | 441 | #region ArraySegment 442 | public Value(ArraySegment segment) 443 | { 444 | byte[]? array = segment.Array; 445 | if (array is null) 446 | { 447 | ThrowArgumentNull(nameof(segment)); 448 | } 449 | 450 | _object = array; 451 | if (segment.Offset == 0 && segment.Count == 0) 452 | { 453 | _union.UInt64 = ulong.MaxValue; 454 | } 455 | else 456 | { 457 | _union.Segment = (segment.Offset, segment.Count); 458 | } 459 | } 460 | 461 | public static implicit operator Value(ArraySegment value) => new(value); 462 | public static explicit operator ArraySegment(in Value value) => value.As>(); 463 | 464 | public Value(ArraySegment segment) 465 | { 466 | char[]? array = segment.Array; 467 | if (array is null) 468 | { 469 | ThrowArgumentNull(nameof(segment)); 470 | } 471 | 472 | _object = array; 473 | if (segment.Offset == 0 && segment.Count == 0) 474 | { 475 | _union.UInt64 = ulong.MaxValue; 476 | } 477 | else 478 | { 479 | _union.Segment = (segment.Offset, segment.Count); 480 | } 481 | } 482 | 483 | public static implicit operator Value(ArraySegment value) => new(value); 484 | public static explicit operator ArraySegment(in Value value) => value.As>(); 485 | #endregion 486 | 487 | #region Decimal 488 | public static implicit operator Value(decimal value) => new(value); 489 | public static explicit operator decimal(in Value value) => value.As(); 490 | public static implicit operator Value(decimal? value) => value.HasValue ? new(value.Value) : new(value); 491 | public static explicit operator decimal?(in Value value) => value.As(); 492 | #endregion 493 | 494 | #region T 495 | public static Value Create(T value) 496 | { 497 | // Explicit cast for types we don't box 498 | if (typeof(T) == typeof(bool)) return new(Unsafe.As(ref Unsafe.AsRef(in value))); 499 | if (typeof(T) == typeof(byte)) return new(Unsafe.As(ref Unsafe.AsRef(in value))); 500 | if (typeof(T) == typeof(sbyte)) return new(Unsafe.As(ref Unsafe.AsRef(in value))); 501 | if (typeof(T) == typeof(char)) return new(Unsafe.As(ref Unsafe.AsRef(in value))); 502 | if (typeof(T) == typeof(short)) return new(Unsafe.As(ref Unsafe.AsRef(in value))); 503 | if (typeof(T) == typeof(int)) return new(Unsafe.As(ref Unsafe.AsRef(in value))); 504 | if (typeof(T) == typeof(long)) return new(Unsafe.As(ref Unsafe.AsRef(in value))); 505 | if (typeof(T) == typeof(ushort)) return new(Unsafe.As(ref Unsafe.AsRef(in value))); 506 | if (typeof(T) == typeof(uint)) return new(Unsafe.As(ref Unsafe.AsRef(in value))); 507 | if (typeof(T) == typeof(ulong)) return new(Unsafe.As(ref Unsafe.AsRef(in value))); 508 | if (typeof(T) == typeof(float)) return new(Unsafe.As(ref Unsafe.AsRef(in value))); 509 | if (typeof(T) == typeof(double)) return new(Unsafe.As(ref Unsafe.AsRef(in value))); 510 | if (typeof(T) == typeof(DateTime)) return new(Unsafe.As(ref Unsafe.AsRef(in value))); 511 | if (typeof(T) == typeof(DateTimeOffset)) return new(Unsafe.As(ref Unsafe.AsRef(in value))); 512 | 513 | if (typeof(T) == typeof(bool?)) return new(Unsafe.As(ref Unsafe.AsRef(in value))); 514 | if (typeof(T) == typeof(byte?)) return new(Unsafe.As(ref Unsafe.AsRef(in value))); 515 | if (typeof(T) == typeof(sbyte?)) return new(Unsafe.As(ref Unsafe.AsRef(in value))); 516 | if (typeof(T) == typeof(char?)) return new(Unsafe.As(ref Unsafe.AsRef(in value))); 517 | if (typeof(T) == typeof(short?)) return new(Unsafe.As(ref Unsafe.AsRef(in value))); 518 | if (typeof(T) == typeof(int?)) return new(Unsafe.As(ref Unsafe.AsRef(in value))); 519 | if (typeof(T) == typeof(long?)) return new(Unsafe.As(ref Unsafe.AsRef(in value))); 520 | if (typeof(T) == typeof(ushort?)) return new(Unsafe.As(ref Unsafe.AsRef(in value))); 521 | if (typeof(T) == typeof(uint?)) return new(Unsafe.As(ref Unsafe.AsRef(in value))); 522 | if (typeof(T) == typeof(ulong?)) return new(Unsafe.As(ref Unsafe.AsRef(in value))); 523 | if (typeof(T) == typeof(float?)) return new(Unsafe.As(ref Unsafe.AsRef(in value))); 524 | if (typeof(T) == typeof(double?)) return new(Unsafe.As(ref Unsafe.AsRef(in value))); 525 | if (typeof(T) == typeof(DateTime?)) return new(Unsafe.As(ref Unsafe.AsRef(in value))); 526 | if (typeof(T) == typeof(DateTimeOffset?)) return new(Unsafe.As(ref Unsafe.AsRef(in value))); 527 | 528 | if (typeof(T) == typeof(ArraySegment)) return new(Unsafe.As>(ref Unsafe.AsRef(in value))); 529 | if (typeof(T) == typeof(ArraySegment)) return new(Unsafe.As>(ref Unsafe.AsRef(in value))); 530 | 531 | if (typeof(T).IsEnum) 532 | { 533 | Debug.Assert(Unsafe.SizeOf() <= sizeof(ulong)); 534 | return new Value(StraightCastFlag.Instance, Unsafe.As(ref value)); 535 | } 536 | 537 | return new Value(value); 538 | } 539 | 540 | [SkipLocalsInit] 541 | private Value(object o, ulong u) 542 | { 543 | Unsafe.SkipInit(out _union); 544 | _object = o; 545 | _union.UInt64 = u; 546 | } 547 | 548 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 549 | public readonly unsafe bool TryGetValue(out T value) 550 | { 551 | bool success; 552 | 553 | // Checking the type gets all of the non-relevant compares elided by the JIT 554 | if (_object is not null && ((typeof(T) == typeof(bool) && _object == TypeFlags.Boolean) 555 | || (typeof(T) == typeof(byte) && _object == TypeFlags.Byte) 556 | || (typeof(T) == typeof(char) && _object == TypeFlags.Char) 557 | || (typeof(T) == typeof(double) && _object == TypeFlags.Double) 558 | || (typeof(T) == typeof(short) && _object == TypeFlags.Int16) 559 | || (typeof(T) == typeof(int) && _object == TypeFlags.Int32) 560 | || (typeof(T) == typeof(long) && _object == TypeFlags.Int64) 561 | || (typeof(T) == typeof(sbyte) && _object == TypeFlags.SByte) 562 | || (typeof(T) == typeof(float) && _object == TypeFlags.Single) 563 | || (typeof(T) == typeof(ushort) && _object == TypeFlags.UInt16) 564 | || (typeof(T) == typeof(uint) && _object == TypeFlags.UInt32) 565 | || (typeof(T) == typeof(ulong) && _object == TypeFlags.UInt64))) 566 | { 567 | value = Unsafe.As(ref Unsafe.AsRef(in _union)); 568 | success = true; 569 | } 570 | else if (typeof(T) == typeof(DateTime) && _object == TypeFlags.DateTime) 571 | { 572 | value = Unsafe.As(ref Unsafe.AsRef(in _union.DateTime)); 573 | success = true; 574 | } 575 | else if (typeof(T) == typeof(DateTimeOffset) && _object == TypeFlags.DateTimeOffset) 576 | { 577 | DateTimeOffset dto = new(_union.Ticks, TimeSpan.Zero); 578 | value = Unsafe.As(ref Unsafe.AsRef(in dto)); 579 | success = true; 580 | } 581 | else if (typeof(T) == typeof(DateTimeOffset) && _object == TypeFlags.PackedDateTimeOffset) 582 | { 583 | DateTimeOffset dto = _union.PackedDateTimeOffset.Extract(); 584 | value = Unsafe.As(ref Unsafe.AsRef(in dto)); 585 | success = true; 586 | } 587 | else if (typeof(T).IsValueType) 588 | { 589 | success = TryGetValueSlow(out value); 590 | } 591 | else 592 | { 593 | success = TryGetObjectSlow(out value); 594 | } 595 | 596 | return success; 597 | } 598 | 599 | private readonly bool TryGetValueSlow(out T value) 600 | { 601 | // Single return has a significant performance benefit. 602 | 603 | bool result = false; 604 | 605 | if (_object is null) 606 | { 607 | // A null is stored, it can only be assigned to a reference type or nullable. 608 | value = default!; 609 | result = Nullable.GetUnderlyingType(typeof(T)) is not null; 610 | } 611 | else if (typeof(T).IsEnum && _object is TypeFlag typeFlag) 612 | { 613 | value = typeFlag.To(in this); 614 | result = true; 615 | } 616 | else if (_object is T t) 617 | { 618 | value = t; 619 | result = true; 620 | } 621 | else if (typeof(T) == typeof(ArraySegment)) 622 | { 623 | ulong bits = _union.UInt64; 624 | if (bits != 0 && _object is byte[] byteArray) 625 | { 626 | ArraySegment segment = bits != ulong.MaxValue 627 | ? new(byteArray, _union.Segment.Offset, _union.Segment.Count) 628 | : new(byteArray, 0, 0); 629 | value = Unsafe.As, T>(ref segment); 630 | result = true; 631 | } 632 | else 633 | { 634 | value = default!; 635 | } 636 | } 637 | else if (typeof(T) == typeof(ArraySegment)) 638 | { 639 | ulong bits = _union.UInt64; 640 | if (bits != 0 && _object is char[] charArray) 641 | { 642 | ArraySegment segment = bits != ulong.MaxValue 643 | ? new(charArray, _union.Segment.Offset, _union.Segment.Count) 644 | : new(charArray, 0, 0); 645 | value = Unsafe.As, T>(ref segment); 646 | result = true; 647 | } 648 | else 649 | { 650 | value = default!; 651 | } 652 | } 653 | else if (typeof(T) == typeof(int?) && _object == TypeFlags.Int32) 654 | { 655 | int? @int = _union.Int32; 656 | value = Unsafe.As(ref Unsafe.AsRef(in @int)); 657 | result = true; 658 | } 659 | else if (typeof(T) == typeof(long?) && _object == TypeFlags.Int64) 660 | { 661 | long? @long = _union.Int64; 662 | value = Unsafe.As(ref Unsafe.AsRef(in @long)); 663 | result = true; 664 | } 665 | else if (typeof(T) == typeof(bool?) && _object == TypeFlags.Boolean) 666 | { 667 | bool? @bool = _union.Boolean; 668 | value = Unsafe.As(ref Unsafe.AsRef(in @bool)); 669 | result = true; 670 | } 671 | else if (typeof(T) == typeof(float?) && _object == TypeFlags.Single) 672 | { 673 | float? single = _union.Single; 674 | value = Unsafe.As(ref Unsafe.AsRef(in single)); 675 | result = true; 676 | } 677 | else if (typeof(T) == typeof(double?) && _object == TypeFlags.Double) 678 | { 679 | double? @double = _union.Double; 680 | value = Unsafe.As(ref Unsafe.AsRef(in @double)); 681 | result = true; 682 | } 683 | else if (typeof(T) == typeof(uint?) && _object == TypeFlags.UInt32) 684 | { 685 | uint? @uint = _union.UInt32; 686 | value = Unsafe.As(ref Unsafe.AsRef(in @uint)); 687 | result = true; 688 | } 689 | else if (typeof(T) == typeof(ulong?) && _object == TypeFlags.UInt64) 690 | { 691 | ulong? @ulong = _union.UInt64; 692 | value = Unsafe.As(ref Unsafe.AsRef(in @ulong)); 693 | result = true; 694 | } 695 | else if (typeof(T) == typeof(char?) && _object == TypeFlags.Char) 696 | { 697 | char? @char = _union.Char; 698 | value = Unsafe.As(ref Unsafe.AsRef(in @char)); 699 | result = true; 700 | } 701 | else if (typeof(T) == typeof(short?) && _object == TypeFlags.Int16) 702 | { 703 | short? @short = _union.Int16; 704 | value = Unsafe.As(ref Unsafe.AsRef(in @short)); 705 | result = true; 706 | } 707 | else if (typeof(T) == typeof(ushort?) && _object == TypeFlags.UInt16) 708 | { 709 | ushort? @ushort = _union.UInt16; 710 | value = Unsafe.As(ref Unsafe.AsRef(in @ushort)); 711 | result = true; 712 | } 713 | else if (typeof(T) == typeof(byte?) && _object == TypeFlags.Byte) 714 | { 715 | byte? @byte = _union.Byte; 716 | value = Unsafe.As(ref Unsafe.AsRef(in @byte)); 717 | result = true; 718 | } 719 | else if (typeof(T) == typeof(sbyte?) && _object == TypeFlags.SByte) 720 | { 721 | sbyte? @sbyte = _union.SByte; 722 | value = Unsafe.As(ref Unsafe.AsRef(in @sbyte)); 723 | result = true; 724 | } 725 | else if (typeof(T) == typeof(DateTime?) && _object == TypeFlags.DateTime) 726 | { 727 | DateTime? dateTime = _union.DateTime; 728 | value = Unsafe.As(ref Unsafe.AsRef(in dateTime)); 729 | result = true; 730 | } 731 | else if (typeof(T) == typeof(DateTimeOffset?) && _object == TypeFlags.DateTimeOffset) 732 | { 733 | DateTimeOffset? dto = new DateTimeOffset(_union.Ticks, TimeSpan.Zero); 734 | value = Unsafe.As(ref Unsafe.AsRef(in dto)); 735 | result = true; 736 | } 737 | else if (typeof(T) == typeof(DateTimeOffset?) && _object == TypeFlags.PackedDateTimeOffset) 738 | { 739 | DateTimeOffset? dto = _union.PackedDateTimeOffset.Extract(); 740 | value = Unsafe.As(ref Unsafe.AsRef(in dto)); 741 | result = true; 742 | } 743 | else if (Nullable.GetUnderlyingType(typeof(T)) is Type underlyingType 744 | && underlyingType.IsEnum 745 | && _object is TypeFlag underlyingTypeFlag 746 | && underlyingTypeFlag.Type == underlyingType) 747 | { 748 | // Asked for a nullable enum and we've got that type. 749 | 750 | // We've got multiple layouts, depending on the size of the enum backing field. We can't use the 751 | // nullable itself (e.g. default(T)) as a template as it gets treated specially by the runtime. 752 | 753 | int size = Unsafe.SizeOf(); 754 | 755 | switch (size) 756 | { 757 | case (2): 758 | NullableTemplate byteTemplate = new(_union.Byte); 759 | value = Unsafe.As, T>(ref Unsafe.AsRef(in byteTemplate)); 760 | result = true; 761 | break; 762 | case (4): 763 | NullableTemplate ushortTemplate = new(_union.UInt16); 764 | value = Unsafe.As, T>(ref Unsafe.AsRef(in ushortTemplate)); 765 | result = true; 766 | break; 767 | case (8): 768 | NullableTemplate uintTemplate = new(_union.UInt32); 769 | value = Unsafe.As, T>(ref Unsafe.AsRef(in uintTemplate)); 770 | result = true; 771 | break; 772 | case (16): 773 | NullableTemplate ulongTemplate = new(_union.UInt64); 774 | value = Unsafe.As, T>(ref Unsafe.AsRef(in ulongTemplate)); 775 | result = true; 776 | break; 777 | default: 778 | ThrowInvalidOperation(); 779 | value = default!; 780 | result = false; 781 | break; 782 | } 783 | } 784 | else 785 | { 786 | value = default!; 787 | result = false; 788 | } 789 | 790 | return result; 791 | } 792 | 793 | private readonly bool TryGetObjectSlow(out T value) 794 | { 795 | // Single return has a significant performance benefit. 796 | 797 | bool result = false; 798 | 799 | if (_object is null) 800 | { 801 | value = default!; 802 | } 803 | else if (typeof(T) == typeof(char[])) 804 | { 805 | if (_union.UInt64 == 0 && _object is char[]) 806 | { 807 | value = (T)_object; 808 | result = true; 809 | } 810 | else 811 | { 812 | // Don't allow "implicit" cast to array if we stored a segment. 813 | value = default!; 814 | result = false; 815 | } 816 | } 817 | else if (typeof(T) == typeof(byte[])) 818 | { 819 | if (_union.UInt64 == 0 && _object is byte[]) 820 | { 821 | value = (T)_object; 822 | result = true; 823 | } 824 | else 825 | { 826 | // Don't allow "implicit" cast to array if we stored a segment. 827 | value = default!; 828 | result = false; 829 | } 830 | } 831 | else if (typeof(T) == typeof(object)) 832 | { 833 | // This case must also come before the _object is T case to make sure we don't leak our flags. 834 | if (_object is TypeFlag flag) 835 | { 836 | value = (T)flag.ToObject(this); 837 | result = true; 838 | } 839 | else if (_union.UInt64 != 0 && _object is char[] chars) 840 | { 841 | value = _union.UInt64 != ulong.MaxValue 842 | ? (T)(object)new ArraySegment(chars, _union.Segment.Offset, _union.Segment.Count) 843 | : (T)(object)new ArraySegment(chars, 0, 0); 844 | result = true; 845 | } 846 | else if (_union.UInt64 != 0 && _object is byte[] bytes) 847 | { 848 | value = _union.UInt64 != ulong.MaxValue 849 | ? (T)(object)new ArraySegment(bytes, _union.Segment.Offset, _union.Segment.Count) 850 | : (T)(object)new ArraySegment(bytes, 0, 0); 851 | result = true; 852 | } 853 | else 854 | { 855 | value = (T)_object; 856 | result = true; 857 | } 858 | } 859 | else if (_object is T t) 860 | { 861 | value = t; 862 | result = true; 863 | } 864 | else 865 | { 866 | value = default!; 867 | result = false; 868 | } 869 | 870 | return result; 871 | } 872 | 873 | [MethodImpl(MethodImplOptions.AggressiveInlining)] 874 | public readonly T As() 875 | { 876 | if (!TryGetValue(out T value)) 877 | { 878 | ThrowInvalidCast(); 879 | } 880 | 881 | return value; 882 | } 883 | #endregion 884 | } 885 | 886 | --------------------------------------------------------------------------------