Files
laatzen/Common/SIRTBroadcaster.Client/Values/Bit.cs
T
2023-08-22 14:58:05 +02:00

78 lines
2.0 KiB
C#

namespace SIRTBroadcaster.Abstraction.Values
{
using System;
using Newtonsoft.Json;
/// <summary>
/// Bit is a custom value type.
/// Is convertable from and to: byte, byte?, bool and bool?.
/// By default returns null.
/// </summary>
[JsonConverter(typeof(JsonBitConverter))]
public struct Bit
{
private readonly byte? bit;
public Bit(byte? bit)
=> this.bit = bit;
public override string ToString()
=> bit?.ToString();
public static implicit operator Bit (byte? bit)
=> new Bit(bit);
public static implicit operator Bit (byte bit)
=> new Bit(bit);
public static implicit operator Bit (bool bit)
=> new Bit((byte?)(bit ? 1 : 0));
public static implicit operator Bit (bool? bit)
=> new Bit(bit == null ? null : (byte?)(bit == true ? 1 : 0));
public static implicit operator byte (Bit bit)
=> bit.bit ?? 0;
public static implicit operator byte? (Bit bit)
=> bit.bit;
public static implicit operator bool? (Bit bit)
{
if (bit.bit.HasValue)
{
return bit.bit == 1;
}
return null;
}
}
public class JsonBitConverter : JsonConverter
{
public override bool CanConvert(Type objectType)
{
return true;
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (existingValue is Bit value)
{
return value;
}
return default(byte);
}
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
if (value is Bit existingValue)
{
writer.WriteValue((byte)existingValue);
}
}
}
}