Skip to content

Instantly share code, notes, and snippets.

@gobwas
Created February 1, 2017 14:09
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 gobwas/c8a1bc347deb2ea88c52999fe47da3b6 to your computer and use it in GitHub Desktop.
Save gobwas/c8a1bc347deb2ea88c52999fe47da3b6 to your computer and use it in GitHub Desktop.
Contains uint64 sybmol
// Say you want to search 0x22 symbol in two bytes of 0x2122
// you make mask for your search as 0x2222
// then:
//
// 00100001 00100010
// ^ 00100010 00100010
// -------------------
// 00000011 00000000 00000011 00000000
// & 01111111 11111111 (cut topmost bit) & 10000000 10000000 (save restore mask)
// ------------------- -------------------
// 00000011 00000000 00000000 00000000
// + 01111111 01111111
// -------------------
// 10000010 01111111
// | 00000000 00000000 (restore topmost bit)
// -------------------
// 10000010 01111111
// | 01111111 01111111
// -------------------
// 11111111 01111111
// ^ -----------------
// 00000000 10000000 != 0, then it contains string
//
// We do not make safe checks for bits overflow, cause ascii symbol is at most 0x7f.
func contains(a, b uint64) bool {
const topmost = 0x7f7f7f7f7f7f7f7f
const restore = &topmost
v := a ^ b
safe := v & topmost // cut top most bit preventing overflow
rest := v & restore // save top most bit restore mask
v = safe + topmost
v &= rest // restore bits
v |= topmost
return ^v != 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment