github.com/thanos-io/thanos@v0.32.5/pkg/store/opts.go (about)

     1  // Copyright (c) The Thanos Authors.
     2  // Licensed under the Apache License 2.0.
     3  
     4  package store
     5  
     6  import (
     7  	"strings"
     8  	"unicode/utf8"
     9  )
    10  
    11  // Bitmap used by func isRegexMetaCharacter to check whether a character needs to be escaped.
    12  var regexMetaCharacterBytes [16]byte
    13  
    14  // isRegexMetaCharacter reports whether byte b needs to be escaped.
    15  func isRegexMetaCharacter(b byte) bool {
    16  	return b < utf8.RuneSelf && regexMetaCharacterBytes[b%16]&(1<<(b/16)) != 0
    17  }
    18  
    19  func init() {
    20  	for _, b := range []byte(`.+*?()|[]{}^$`) {
    21  		regexMetaCharacterBytes[b%16] |= 1 << (b / 16)
    22  	}
    23  }
    24  
    25  // Copied from Prometheus querier.go, removed check for Prometheus wrapper.
    26  // Returns list of values that can regex matches.
    27  func findSetMatches(pattern string) []string {
    28  	if len(pattern) == 0 {
    29  		return nil
    30  	}
    31  	escaped := false
    32  	sets := []*strings.Builder{{}}
    33  	init := 0
    34  	end := len(pattern)
    35  	// If the regex is wrapped in a group we can remove the first and last parentheses
    36  	if pattern[init] == '(' && pattern[end-1] == ')' {
    37  		init++
    38  		end--
    39  	}
    40  	for i := init; i < end; i++ {
    41  		if escaped {
    42  			switch {
    43  			case isRegexMetaCharacter(pattern[i]):
    44  				sets[len(sets)-1].WriteByte(pattern[i])
    45  			case pattern[i] == '\\':
    46  				sets[len(sets)-1].WriteByte('\\')
    47  			default:
    48  				return nil
    49  			}
    50  			escaped = false
    51  		} else {
    52  			switch {
    53  			case isRegexMetaCharacter(pattern[i]):
    54  				if pattern[i] == '|' {
    55  					sets = append(sets, &strings.Builder{})
    56  				} else {
    57  					return nil
    58  				}
    59  			case pattern[i] == '\\':
    60  				escaped = true
    61  			default:
    62  				sets[len(sets)-1].WriteByte(pattern[i])
    63  			}
    64  		}
    65  	}
    66  	matches := make([]string, 0, len(sets))
    67  	for _, s := range sets {
    68  		if s.Len() > 0 {
    69  			matches = append(matches, s.String())
    70  		}
    71  	}
    72  	return matches
    73  }