Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace hashes
- {
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Runtime.Serialization.Formatters.Binary;
- using System.IO;
- using System.Linq;
- [Serializable]
- public class ReadonlyBytes : IEnumerable, IEnumerable<byte>, ICollection, IReadOnlyCollection<byte>
- {
- public int Length => innerBuffer.Length;
- private byte[] innerBuffer;
- private int uID;
- public byte this[int index]
- {
- get
- {
- if (index < 0 || index > int.MaxValue)
- throw new IndexOutOfRangeException($"Invalid index: {index}");
- return innerBuffer[index];
- }
- }
- public ReadonlyBytes(IEnumerable<byte> initializer)
- {
- innerBuffer = initializer.ToArray();
- uID = ComputeHash();
- }
- public ReadonlyBytes(params byte[] initializer) : this(initializer.AsEnumerable())
- {
- }
- public int ComputeHash()
- {
- unchecked
- {
- var fnvPrime = 0x811C9DC5;
- var hash = 0;
- for (var i = 0; i < innerBuffer.Length; i++)
- {
- hash *= (int)fnvPrime;
- hash ^= innerBuffer[i];
- }
- return hash;
- }
- }
- #region Overrided Object methods
- public override bool Equals(object obj)
- {
- if (obj == null)
- return false;
- var knownObj = obj as ReadonlyBytes;
- if (knownObj == null || knownObj.GetType() != typeof(ReadonlyBytes))
- return false;
- if (knownObj.Length != this.Length)
- return false;
- return this.SequenceEqual(knownObj);
- }
- public override int GetHashCode()
- {
- return uID;
- }
- public override string ToString()
- {
- return "[" + string.Join(", ", innerBuffer) + "]";
- }
- #endregion
- #region Cloning
- public new ReadonlyBytes MemberwiseClone() => new ReadonlyBytes(innerBuffer);
- public ReadonlyBytes DeepClone()
- {
- using (var memory = new MemoryStream())
- {
- var formatter = new BinaryFormatter();
- formatter.Serialize(memory, this);
- memory.Position = 0;
- return (ReadonlyBytes)formatter.Deserialize(memory);
- }
- }
- #endregion
- #region Autogenerated Interfaces Implementation
- public int Count => ((ICollection)innerBuffer).Count;
- public object SyncRoot => innerBuffer.SyncRoot;
- public bool IsSynchronized => innerBuffer.IsSynchronized;
- public void CopyTo(Array array, int index)
- {
- innerBuffer.CopyTo(array, index);
- }
- public IEnumerator<byte> GetEnumerator()
- {
- return innerBuffer.AsEnumerable().GetEnumerator();
- }
- IEnumerator IEnumerable.GetEnumerator()
- {
- return GetEnumerator();
- }
- #endregion
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement