Skip to content

Instantly share code, notes, and snippets.

@catid
Created May 27, 2018 03:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save catid/2bd33c0f0c7dced794adc1ed363ec167 to your computer and use it in GitHub Desktop.
Save catid/2bd33c0f0c7dced794adc1ed363ec167 to your computer and use it in GitHub Desktop.
RoughStrCompare
/**
RoughStrCompare()
This does a rough ASCII case-insensitive string comparison. Mainly for fun.
All of the a-z and A-Z ASCII codes are between 0x41 - 0x5A and 0x61 - 0x7A.
The idea here is to mask out 0x20 to make these equivalent (case-insensitive)
but the problem with this idea is that it aliases these characters:
@ with ` [ with { \ with | ] with } ^ with ~
*/
bool RoughStrCompare(
const char* data, ///< Data to search
unsigned data_bytes, ///< Length of data in bytes
const char* key, ///< Key to search for
unsigned key_bytes); ///< Bytes in key
bool RoughStrCompare(
const char* data, ///< Data to search
unsigned data_bytes, ///< Length of data in bytes
const char* key, ///< Key to search for
unsigned key_bytes) ///< Bytes in key
{
// If it would be too long:
if (key_bytes > data_bytes) {
return false;
}
// Do blocks of 8 bytes
while (key_bytes >= 8)
{
uint64_t a = siamese::ReadU64_LE(reinterpret_cast<const uint8_t*>(data));
uint64_t b = siamese::ReadU64_LE(reinterpret_cast<const uint8_t*>(key));
if (a != b)
{
a &= ~((a & 0x4040404040404040ULL) >> 1);
b &= ~((b & 0x4040404040404040ULL) >> 1);
if (a != b) {
return false;
}
}
data += 8, key += 8, key_bytes -= 8;
}
// Do 4 bytes
if (key_bytes >= 4)
{
uint32_t a = siamese::ReadU32_LE(reinterpret_cast<const uint8_t*>(data));
uint32_t b = siamese::ReadU32_LE(reinterpret_cast<const uint8_t*>(key));
if (a != b)
{
a &= ~((a & 0x40404040) >> 1);
b &= ~((b & 0x40404040) >> 1);
if (a != b) {
return false;
}
}
data += 4, key += 4, key_bytes -= 4;
}
// Do remaining 1-3 bytes
while (key_bytes > 0)
{
uint8_t a = data[0];
uint8_t b = key[0];
if (a != b)
{
a &= ~((a & 0x40) >> 1);
b &= ~((b & 0x40) >> 1);
if (a != b) {
return false;
}
}
++data, ++key, --key_bytes;
}
return true;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment