Skip to content

Instantly share code, notes, and snippets.

@lunasorcery
Last active December 17, 2015 01:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save lunasorcery/5529542 to your computer and use it in GitHub Desktop.
Save lunasorcery/5529542 to your computer and use it in GitHub Desktop.
static class ByteArrayExtensions
{
public static bool Contains(this byte[] src, byte query)
{
return src.IndexOf(query) >= 0;
}
public static bool Contains(this byte[] src, byte[] query)
{
return src.IndexOf(query) >= 0;
}
public static bool EndsWith(this byte[] src, byte query)
{
if (src.Length == 0)
{
return false;
}
return (src[src.Length - 1] == query);
}
public static bool EndsWith(this byte[] src, byte[] query)
{
if (src.Length == 0 || query.Length == 0 || query.Length > src.Length)
{
return false;
}
for (int i = 0; i < query.Length; i++)
{
if (src[src.Length - query.Length + i] != query[i])
{
return false;
}
}
return true;
}
public static int IndexOf(this byte[] src, byte query)
{
for (int i = 0; i < src.Length; i++)
{
if (src[i] == query)
{
return i;
}
}
return -1;
}
public static int IndexOf(this byte[] src, byte[] query)
{
if (src.Length == 0 || query.Length == 0 || query.Length > src.Length)
{
return -1;
}
bool flag;
for (int i = 0; i <= src.Length - query.Length; i++)
{
flag = true;
for (int j = 0; j < query.Length; j++)
{
if (src[i + j] != query[j])
{
flag = false;
break;
}
}
if (flag)
{
return i;
}
}
return -1;
}
public static int LastIndexOf(this byte[] src, byte query)
{
//for (int i = src.Length; i --> 0; ) // most visually pleasing decrementation method ever. Figure it out.
for (int i = src.Length - 1; i >= 0; i--)
{
if (src[i] == query)
{
return i;
}
}
return -1;
}
public static int LastIndexOf(this byte[] src, byte[] query)
{
if (src.Length == 0 || query.Length == 0 || query.Length > src.Length)
{
return -1;
}
bool flag;
for (int i = src.Length - query.Length; i >= 0; i--)
{
flag = true;
for (int j = 0; j < query.Length; j++)
{
if (src[i + j] != query[j])
{
flag = false;
break;
}
}
if (flag)
{
return i;
}
}
return -1;
}
public static bool Matches(this byte[] src, byte[] query)
{
if (src.Length != query.Length)
{
return false;
}
for (int i = 0; i < src.Length; i++)
{
if (src[i] != query[i])
{
return false;
}
}
return true;
}
public static bool StartsWith(this byte[] src, byte query)
{
if (src.Length == 0)
{
return false;
}
return (src[0] == query);
}
public static bool StartsWith(this byte[] src, byte[] query)
{
if (src.Length == 0 || query.Length == 0 || query.Length > src.Length)
{
return false;
}
for (int i = 0; i < query.Length; i++)
{
if (src[i] != query[i])
{
return false;
}
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment