Last active
May 17, 2017 04:02
-
-
Save Kittoes0124/f9d6e8d9e51d2d6f25d225440a77dcf3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Text; | |
namespace ByteTerrace.CSharp.Data | |
{ | |
public struct AsciiString : IEquatable<AsciiString> | |
{ | |
private readonly byte[] m_data; | |
private readonly uint m_length; | |
private readonly uint m_offset; | |
public static AsciiString Empty => new AsciiString(string.Empty); | |
public ref byte this[int index] => ref Data[checked(Offset + index)]; | |
public byte[] Data => m_data; | |
public int Length => ((int)m_length); | |
public int Offset => ((int)m_offset); | |
[CLSCompliant(false)] | |
public AsciiString(byte[] data, uint offset, uint length) { | |
if (data == null) { throw new ArgumentNullException(paramName: nameof(data)); } | |
if (checked(offset + length) > data.Length) { throw new IndexOutOfRangeException(); } | |
m_data = data; | |
m_length = length; | |
m_offset = offset; | |
} | |
public AsciiString(byte[] data) : this(data, 0, (uint)data.Length) { } | |
public AsciiString(string value) : this(Encoding.ASCII.GetBytes(value)) { } | |
public override int GetHashCode() { | |
var hash = m_data.GetHashCode(); | |
unchecked { | |
hash = ((hash * 486187739) + m_length.GetHashCode()); | |
hash = ((hash * 486187739) + m_offset.GetHashCode()); | |
} | |
return hash; | |
} | |
public override string ToString() { | |
return new string(Encoding.ASCII.GetChars(Data), Offset, Length); | |
} | |
public AsciiString Clear() { | |
ref AsciiString self = ref this; | |
self = Empty; | |
return this; | |
} | |
public AsciiString Copy() { | |
var buffer = new byte[checked(Length - Offset)]; | |
Array.Copy(Data, Offset, buffer, 0, Length); | |
return new AsciiString(buffer); | |
} | |
public bool Equals(AsciiString other) { | |
return other.Data.VectorEquals(Data); | |
} | |
public int IndexOf(byte character, int offset) { | |
return Array.IndexOf(Data, character, checked(Offset + offset)); | |
} | |
[CLSCompliant(false)] | |
public AsciiString SliceLeft(uint length) { | |
ref AsciiString self = ref this; | |
self = Substring(0, length); | |
return this; | |
} | |
[CLSCompliant(false)] | |
public AsciiString SliceRight(uint length) { | |
ref AsciiString self = ref this; | |
self = Substring(checked(m_length - length), length); | |
return this; | |
} | |
[CLSCompliant(false)] | |
public AsciiString Substring(uint offset, uint length) { | |
return new AsciiString(m_data, checked(offset + m_offset), length); | |
} | |
public static implicit operator AsciiString(string value) { | |
return new AsciiString(value); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment