using System;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
namespace SabreTools.Skippers.Tests
{
///
/// Test that checks data matches
///
[XmlType("data")]
public class DataTest : Test
{
#region Fields
///
/// File offset to run the test
///
/// Either numeric or the literal "EOF"
[XmlAttribute("offset")]
public string? Offset
{
get => _offset == null ? "EOF" : _offset.Value.ToString();
set
{
if (value == null || value.ToLowerInvariant() == "eof")
_offset = null;
else
_offset = Convert.ToInt64(value, fromBase: 16);
}
}
///
/// Static value to be checked at the offset
///
/// Hex string representation of a byte array
[XmlAttribute("value")]
public string? Value
{
get => _value == null ? string.Empty : BitConverter.ToString(_value).Replace("-", string.Empty);
set => _value = ParseByteArrayFromHex(value);
}
///
/// Determines whether a pass or failure is expected
///
[XmlAttribute("result")]
public bool Result { get; set; } = true;
#endregion
#region Private instance variables
///
/// File offset to run the test
///
/// null is EOF
private long? _offset;
///
/// Static value to be checked at the offset
///
private byte[]? _value;
#endregion
///
public override bool Passes(Stream input)
{
// If we have an invalid value
if (_value == null || _value.Length == 0)
return false;
// Seek to the correct position, if possible
if (!Seek(input, _offset))
return false;
// Then read and compare bytewise
bool result = true;
for (int i = 0; i < _value.Length; i++)
{
try
{
if (input.ReadByte() != _value[i])
{
result = false;
break;
}
}
catch
{
result = false;
break;
}
}
// Return if the expected and actual results match
return result == Result;
}
}
}