Skip to content

Instantly share code, notes, and snippets.

@xsoheilalizadeh
Last active June 19, 2020 20:50
Show Gist options
  • Select an option

  • Save xsoheilalizadeh/73ae6bd7621b739567b62cf96ea71477 to your computer and use it in GitHub Desktop.

Select an option

Save xsoheilalizadeh/73ae6bd7621b739567b62cf96ea71477 to your computer and use it in GitHub Desktop.
public readonly struct ReadOnlyElement
{
private readonly ReadOnlySpan<byte> LessThanSign => new[] {(byte) '<'};
private readonly ReadOnlySpan<byte> GreaterThanSign => new[] {(byte) '>'};
private readonly ReadOnlySpan<byte> CloseElementSign => new[] {(byte) '<', (byte) '/'};
private readonly ReadOnlySpan<byte> EqualSign => new[] {(byte) '='};
private readonly ReadOnlySpan<byte> DoubleQuote => new[] {(byte) '\"'};
private readonly ReadOnlySpan<byte> WhiteSpace => new[] {(byte) ' '};
public ReadOnlyElement(in ReadOnlyMemory<byte> name, in ReadOnlyMemory<byte> value, IReadOnlyList<ReadOnlyAttr> attributes,
IReadOnlyList<ReadOnlyElement> children)
{
Name = name;
Value = value;
Children = children;
Attributes = attributes;
}
public ReadOnlyElement(in ReadOnlyMemory<byte> name, in ReadOnlyMemory<byte> value, IReadOnlyList<ReadOnlyAttr> attributes) :
this(name, value, attributes,
new List<ReadOnlyElement>())
{
Name = name;
Value = value;
}
public ReadOnlyElement(in ReadOnlyMemory<byte> name, IReadOnlyList<ReadOnlyAttr> attributes) : this(name, ReadOnlyMemory<byte>.Empty, attributes,
new List<ReadOnlyElement>())
{
Name = name;
Attributes = attributes;
}
public ReadOnlyElement(in ReadOnlyMemory<byte> name) : this(name, ReadOnlyMemory<byte>.Empty, new List<ReadOnlyAttr>(),
new List<ReadOnlyElement>())
{
Name = name;
}
public ReadOnlyMemory<byte> Name { get; }
public ReadOnlyMemory<byte> Value { get; }
public IReadOnlyList<ReadOnlyElement> Children { get; }
public IReadOnlyList<ReadOnlyAttr> Attributes { get; }
public void WriteTo(IBufferWriter<byte> writer)
{
WriteElement(writer, Name.Span, Value.Span, Attributes);
foreach (var child in Children)
{
WriteElement(writer, child.Name.Span, child.Value.Span, child.Attributes);
}
}
private void WriteElement(IBufferWriter<byte> writer, in ReadOnlySpan<byte> name, in ReadOnlySpan<byte> value,
IReadOnlyList<ReadOnlyAttr> attributes)
{
writer.Write(LessThanSign);
writer.Write(name);
foreach (var attribute in attributes)
{
writer.Write(WhiteSpace);
writer.Write(attribute.Name.Span);
writer.Write(EqualSign);
writer.Write(DoubleQuote);
writer.Write(attribute.Value.Span);
writer.Write(DoubleQuote);
}
writer.Write(GreaterThanSign);
writer.Write(value);
writer.Write(CloseElementSign);
writer.Write(name);
writer.Write(GreaterThanSign);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment