Innovenergy_trunk/csharp/Lib/Protocols/DBus/WireFormat/DBusWriter.cs

98 lines
2.4 KiB
C#
Raw Permalink Normal View History

2023-02-16 12:57:06 +00:00
using InnovEnergy.Lib.Protocols.DBus.Protocol.DataTypes;
using InnovEnergy.Lib.Protocols.DBus.Protocol.DataTypes.Signatures;
using static System.Text.Encoding;
namespace InnovEnergy.Lib.Protocols.DBus.WireFormat;
internal abstract class DBusWriter
{
public abstract Int32 BytesWritten { get; }
public abstract void WriteByte(Byte value);
public void Align(Int32 align)
{
while (BytesWritten % align != 0)
WriteNull();
}
private void WriteNull() => WriteByte(0);
private void WriteBytes(IEnumerable<Byte> bytes)
{
foreach (var b in bytes)
WriteByte(b);
}
public void AlignForComposite() => Align(8); // structs/arrays/dict elements are always 8-aligned
public void WriteUInt16(UInt16 value)
{
Align(sizeof(UInt16));
WriteBytes(BitConverter.GetBytes(value));
}
public void WriteInt16(Int16 value)
{
Align(sizeof(Int16));
WriteBytes(BitConverter.GetBytes(value));
}
public void WriteUInt32(UInt32 value)
{
Align(sizeof(UInt32));
WriteBytes(BitConverter.GetBytes(value));
}
public void WriteInt32(Int32 value)
{
Align(sizeof(Int32));
WriteBytes(BitConverter.GetBytes(value));
}
public void WriteUInt64(UInt64 value)
{
Align(sizeof(UInt64));
WriteBytes(BitConverter.GetBytes(value));
}
public void WriteInt64(Int64 value)
{
Align(sizeof(Int64));
WriteBytes(BitConverter.GetBytes(value));
}
public void WriteDouble(Double value)
{
Align(sizeof(Double));
WriteBytes(BitConverter.GetBytes(value));
}
public void WriteBoolean(Boolean value) => WriteUInt32(value ? 1u : 0);
public void WriteString(String value)
{
var str = UTF8.GetBytes(value);
WriteInt32(str.Length);
WriteBytes(str);
WriteNull();
}
public void WriteObjectPath(ObjectPath value) => WriteString(value.Path);
public void WriteSignature(Signature signature)
{
var str = ASCII.GetBytes(signature.ToString()!);
WriteByte((Byte) str.Length);
WriteBytes(str);
WriteNull();
}
public void WriteVariant(Variant variant)
{
var variantSignature = variant.Signature;
WriteSignature(variantSignature);
variantSignature.Write(variant.Value, this);
}
public override String ToString() => $"@{BytesWritten}";
}