using System.Buffers.Binary;
using System.Text;
namespace Chronos.Core.Metadata;
///
/// Forward-only reader over bytes already in memory. Reading past the end returns zeros and clears ,
/// so a parser can read a whole structure and validate once.
///
internal ref struct SpanReader
{
private readonly ReadOnlySpan _data;
private readonly bool _bigEndian;
private int _position;
public SpanReader(ReadOnlySpan data, bool bigEndian = true)
{
_data = data;
_bigEndian = bigEndian;
Ok = true;
}
public bool Ok { get; private set; }
public readonly int Position => _position;
public readonly int Remaining => _data.Length - _position;
public byte U8() => Take(1) is [var b] ? b : (byte)0;
public ushort U16()
{
var s = Take(2);
return s.Length < 2 ? (ushort)0 : _bigEndian ? BinaryPrimitives.ReadUInt16BigEndian(s) : BinaryPrimitives.ReadUInt16LittleEndian(s);
}
public uint U32()
{
var s = Take(4);
return s.Length < 4 ? 0 : _bigEndian ? BinaryPrimitives.ReadUInt32BigEndian(s) : BinaryPrimitives.ReadUInt32LittleEndian(s);
}
public ulong U64()
{
var s = Take(8);
return s.Length < 8 ? 0 : _bigEndian ? BinaryPrimitives.ReadUInt64BigEndian(s) : BinaryPrimitives.ReadUInt64LittleEndian(s);
}
/// Unsigned integer stored in 0, 4 or 8 bytes (ISO-BMFF iloc field sizes); other sizes fail.
public ulong Sized(int bytes)
{
switch (bytes)
{
case 0: return 0;
case 4: return U32();
case 8: return U64();
default:
Ok = false;
return 0;
}
}
public void Skip(int count) => Take(count);
/// The next bytes; empty (and cleared) when fewer remain.
public ReadOnlySpan Take(int count)
{
if (count < 0 || count > Remaining)
{
Ok = false;
_position = _data.Length;
return default;
}
var s = _data.Slice(_position, count);
_position += count;
return s;
}
/// NUL-terminated UTF-8 string (the terminator is consumed); the rest of the data when unterminated.
public string CString()
{
var rest = _data[_position..];
var end = rest.IndexOf((byte)0);
var length = end < 0 ? rest.Length : end;
_position += end < 0 ? length : length + 1;
return Encoding.UTF8.GetString(rest[..length]);
}
}