44 lines
1.7 KiB
C#
44 lines
1.7 KiB
C#
using System;
|
|
using System.Dynamic;
|
|
using System.IO;
|
|
|
|
namespace ln.bson
|
|
{
|
|
public abstract class BsonValue : DynamicObject
|
|
{
|
|
public BsonType BsonType { get; }
|
|
|
|
protected BsonValue(BsonType bsonType)
|
|
{
|
|
BsonType = bsonType;
|
|
}
|
|
|
|
public abstract object ToNative();
|
|
public abstract Byte[] GetBytes();
|
|
|
|
public virtual T As<T>() => throw new NotImplementedException();
|
|
|
|
public virtual void WriteTo(Stream stream) => stream.Write(GetBytes());
|
|
|
|
public virtual int WriteTo(byte[] buffer, int offset)
|
|
{
|
|
byte[] vBytes = GetBytes();
|
|
Array.Copy(vBytes, 0, buffer, offset, vBytes.Length);
|
|
return vBytes.Length;
|
|
}
|
|
|
|
public override bool Equals(object? obj) => (obj is BsonValue bsonValue) && object.Equals(this.ToNative(), bsonValue.ToNative());
|
|
|
|
|
|
public static implicit operator BsonValue(bool b) => b ? BsonBoolean.True : BsonBoolean.False;
|
|
public static implicit operator BsonValue(String s) => new BsonString(s);
|
|
public static implicit operator BsonValue(double d) => new BsonDouble(d);
|
|
public static implicit operator BsonValue(DateTime dt) => new BsonDateTime(dt);
|
|
public static implicit operator BsonValue(int i) => new BsonInt32(i);
|
|
public static implicit operator BsonValue(long l) => new BsonInt64(l);
|
|
public static implicit operator BsonValue(byte[] b) => new BsonBinary(BsonBinarySubType.Generic, b);
|
|
public static implicit operator BsonValue(Guid guid) => new BsonGuid(guid);
|
|
|
|
public static implicit operator string(BsonValue bsonString) => ((BsonString)bsonString).Value;
|
|
}
|
|
} |