package searcher import ( "errors" "unicode/utf8" ) func patternToTarget(pattern string) ([]byte, error) { if len(pattern) > 3 && pattern[0] == '0' { switch pattern[1] { case 'x', 'X': return decodeHexLiteral(pattern) case 'b', 'B': return decodeBinLiteral(pattern) } } return unescapePattern(pattern), nil } func decodeHexLiteral(pattern string) ([]byte, error) { bs := make([]byte, 0, len(pattern)/2+1) var c byte var lower bool for i := 2; i < len(pattern); i++ { if !isHex(pattern[i]) { return nil, errors.New("invalid hex pattern: " + pattern) } c = c<<4 | hexToDigit(pattern[i]) if lower { bs = append(bs, c) c = 0 } lower = !lower } if lower { bs = append(bs, c<<4) } return bs, nil } func decodeBinLiteral(pattern string) ([]byte, error) { bs := make([]byte, 0, len(pattern)/16+1) var c byte var bits int for i := 2; i < len(pattern); i++ { if !isBin(pattern[i]) { return nil, errors.New("invalid bin pattern: " + pattern) } c = c<<1 | hexToDigit(pattern[i]) bits++ if bits == 8 { bits = 0 bs = append(bs, c) c = 0 } } if bits > 0 { bs = append(bs, c<