using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Sarand.Net.Standard.Base.Data { //======================================================================= public class SacsData { //------------------------------------------------------------------- // Data members. //------------------------------------------------------------------- // Construction. /// Construction - Empty data. public SacsData () { } /// Construction - Data from byte array. public SacsData (byte[] data) { DataBuffer = new byte[data?.Length ?? 0]; DataLength = data?.Length ?? 0; if (DataLength > 0) Array.Copy(data, 0, DataBuffer, 0, DataLength); CheckForNull(); } /// /// Construction - Data from string. /// Encoding: ASCII /// public SacsData (string data) : this(data, Encoding.ASCII) { } /// Construction - Data from string with specific encoding. public SacsData (string data, Encoding encoding) : this(encoding.GetBytes(data)) { StringEncoding = encoding; } /// Copy construction. public SacsData (SacsData data) : this(data.DataBuffer) { StringEncoding = data.StringEncoding; } //------------------------------------------------------------------- // Properties. /// Data buffer - cannot be replaced but individual entries can be amended. public byte[] DataBuffer { get; protected set; } = new byte[0]; /// Length of data may be less than the buffer length. public int DataLength { get; protected set; } /// Encoding used to convert data to String. public Encoding StringEncoding { get; set; } = Encoding.ASCII; /// Does the data contain null (0x00) values?In which case conversion to String will be invalid. public bool ContainsNull { get; protected set; } //------------------------------------------------------------------- // Utilities. private void CheckForNull() { ContainsNull = Array.Exists(DataBuffer, item => item == 0); } //------------------------------------------------------------------- // Conversion to String. public override String ToString () { return String.Format(GetType().Name + " [Length: {0}]", DataLength); } public static implicit operator String (SacsData data) { return data.StringEncoding.GetString(data.DataBuffer); } public String NullTerminatedString { get { int nullIdx = Array.IndexOf(DataBuffer,(byte)0); if (nullIdx >= 0) return StringEncoding.GetString(DataBuffer.Take(nullIdx).ToArray()); return StringEncoding.GetString(DataBuffer); } } //------------------------------------------------------------------- // Append data. //------------------------------------------------------------------- } //======================================================================= }