Created
November 1, 2019 14:08
-
-
Save jigargandhi/abc768bb62fb1e6f184d83cc27ea5f2d to your computer and use it in GitHub Desktop.
CharMemoryHolder
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
public struct CharMemoryHolder | |
{ | |
public ReadOnlyMemory<char> Value; | |
public override int GetHashCode() | |
{ | |
// Murmur hash | |
uint c1 = 0xcc9e2d51; | |
uint c2 = 0x1b873593; | |
uint m = 5; | |
uint n = 0xe6546b64; | |
uint hash = 42; | |
foreach (var charItem in Value.Span) | |
{ | |
uint k = (uint)charItem; | |
k *= c1; | |
k = (k << 15) | (k >> 17); | |
k *= c2; | |
hash ^= k; | |
hash = (hash << 13) | (hash >> 19); | |
hash = (hash * m) + n; | |
} | |
hash ^= (uint)Value.Length; | |
hash ^= (hash >> 16); | |
hash *= 0x85ebca6b; | |
hash ^= (hash >> 13); | |
hash *= 0xc2b2ae35; | |
hash ^= (hash >> 16); | |
return (int)hash; | |
} | |
public static implicit operator CharMemoryHolder(string stringValue) | |
{ | |
return new CharMemoryHolder() | |
{ | |
Value = stringValue.AsMemory() | |
}; | |
} | |
public static implicit operator CharMemoryHolder(ReadOnlyMemory<char> readOnlyMemory) | |
{ | |
return new CharMemoryHolder() | |
{ | |
Value = readOnlyMemory | |
}; | |
} | |
public IEnumerable<CharMemoryHolder> Split(char split) | |
{ | |
int oldIndex = 0; | |
for (int i = 0; i < Value.Span.Length; i++) | |
{ | |
if (split == Value.Span[i]) | |
{ | |
var slicedSpan = Value.Slice(oldIndex, i - oldIndex + 1); | |
oldIndex = i + 1; | |
yield return slicedSpan; | |
} | |
} | |
//return sliceSpanOfSpan; | |
} | |
public void Split<T>(char split, T state, Action<ReadOnlyMemory<char>, T> action) | |
{ | |
int oldIndex = 0; | |
for (int i = 0; i < Value.Span.Length; i++) | |
{ | |
if (split == Value.Span[i]) | |
{ | |
var slicedSpan = Value.Slice(oldIndex, i - oldIndex + 1); | |
oldIndex = i + 1; | |
action(slicedSpan, state); | |
} | |
} | |
} | |
} | |
public class CharMemoryComparer : EqualityComparer<CharMemoryHolder> | |
{ | |
public override bool Equals([AllowNull] CharMemoryHolder x, [AllowNull] CharMemoryHolder y) | |
{ | |
return x.Value.Equals(y.Value); | |
} | |
public override int GetHashCode([DisallowNull] CharMemoryHolder obj) | |
{ | |
return obj.GetHashCode(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment