golang.org/x/arch@v0.17.0/x86/xeddata/pattern_set.go (about) 1 // Copyright 2018 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package xeddata 6 7 import ( 8 "sort" 9 "strings" 10 ) 11 12 // PatternSet wraps instruction PATTERN properties providing set operations on them. 13 type PatternSet map[string]bool 14 15 // NewPatternSet decodes pattern string into PatternSet. 16 func NewPatternSet(pattern string) PatternSet { 17 pset := make(PatternSet) 18 for _, f := range strings.Fields(pattern) { 19 pset[f] = true 20 } 21 return pset 22 } 23 24 // PatternAliases is extendable map of pattern keys aliases. 25 // Maps human-readable key to XED property. 26 // 27 // Used in PatternSet.Is. 28 var PatternAliases = map[string]string{ 29 "VEX": "VEXVALID=1", 30 "EVEX": "VEXVALID=2", 31 "XOP": "VEXVALID=3", 32 "MemOnly": "MOD!=3", 33 "RegOnly": "MOD=3", 34 } 35 36 // String returns pattern printer representation. 37 // All properties are sorted. 38 func (pset PatternSet) String() string { 39 var keys []string 40 for k := range pset { 41 keys = append(keys, k) 42 } 43 sort.Strings(keys) 44 return strings.Join(keys, " ") 45 } 46 47 // Is reports whether set contains key k. 48 // In contrast with direct pattern set lookup, it does 49 // check if PatternAliases[k] is available to be used instead of k in lookup. 50 func (pset PatternSet) Is(k string) bool { 51 if alias := PatternAliases[k]; alias != "" { 52 return pset[alias] 53 } 54 return pset[k] 55 } 56 57 // Replace inserts newKey if oldKey is defined. 58 // oldKey is removed if insertion is performed. 59 func (pset PatternSet) Replace(oldKey, newKey string) { 60 if pset[oldKey] { 61 pset[newKey] = true 62 delete(pset, oldKey) 63 } 64 } 65 66 // Index returns index from keys of first matching key. 67 // Returns -1 if does not contain any of given keys. 68 func (pset PatternSet) Index(keys ...string) int { 69 for i, k := range keys { 70 if pset[k] { 71 return i 72 } 73 } 74 return -1 75 } 76 77 // Match is like MatchOrDefault("", keyval...). 78 func (pset PatternSet) Match(keyval ...string) string { 79 return pset.MatchOrDefault("", keyval...) 80 } 81 82 // MatchOrDefault returns first matching key associated value. 83 // Returns defaultValue if no match is found. 84 // 85 // Keyval structure can be described as {"k1", "v1", ..., "kN", "vN"}. 86 func (pset PatternSet) MatchOrDefault(defaultValue string, keyval ...string) string { 87 for i := 0; i < len(keyval); i += 2 { 88 key := keyval[i+0] 89 val := keyval[i+1] 90 if pset[key] { 91 return val 92 } 93 } 94 return defaultValue 95 }