// Fixes the first args many segments as the prefix of a new KeyFormat by using the args to generate a key that becomes
// that prefix. Any remaining unassigned segments become the layout of the new KeyFormat.
778995
func (kf *KeyFormat) Fix(args ...interface{}) (*KeyFormat, error) {
	key, err := kf.Key(args...)
	if err != nil {
		return nil, err
	}
	return NewKeyFormat(string(key), kf.layout[len(args):]...)
}
347327
func GenTableIndexPrefix(tableID int64) kv.Key {
	buf := make([]byte, 0, len(tablePrefix)+8+len(indexPrefixSep))
	return appendTableIndexPrefix(buf, tableID)
}
1372916
func (l Labels) AppendPrefixInKey(prefix string) Labels {
	newLabels := Labels{}
	for k, v := range l {
		newLabels[prefix+k] = Label{
			Key:    prefix + v.Key,
			Value:  v.Value,
			Source: v.Source,
		}
	}
	return newLabels
}
1262739
func processKeys(keys map[rune]kb.Key) ([]byte, []byte, error) {
	// order rune keys
	idx := make([]rune, len(keys))
	var i int
	for c := range keys {
		idx[i] = c
		i++
	}
	sort.Slice(idx, func(a, b int) bool {
		return idx[a] < idx[b]
	})

	// process
	var constBuf, mapBuf bytes.Buffer
	for _, c := range idx {
		key := keys[c]

		g, isGoCode := goCodes[c]
		s := fmt.Sprintf("\\u%04x", c)
		if isGoCode {
			s = g
		} else if key.Print {
			s = fmt.Sprintf("%c", c)
		}

		// add key definition
		v := strings.TrimPrefix(fmt.Sprintf("%#v", key), "kb.")
		v = nameRE.ReplaceAllString(v, "")
		mapBuf.WriteString(fmt.Sprintf("'%s': &%s,\n", s, v))

		// fix 'Quote' const
		if s == `\'` {
			s = `'`
		}

		// add const definition
		if (isGoCode && c != '\n') || !key.Print {
			n := strings.TrimPrefix(key.Key, ".")
			if n == `'` || n == `\` {
				n = key.Code
			}

			constBuf.WriteString(fmt.Sprintf("%s = \"%s\"\n", n, s))
		}
	}

	return constBuf.Bytes(), mapBuf.Bytes(), nil
}
332906
func (t *Trie) Allprefixed(prefix []byte, handle func(key []byte, value interface{}) bool) bool {
	// an empty tree
	if t.size == 0 {
		return true
	}

	// walk tree, maintaining top pointer
	p := &t.root
	top := p
	if len(prefix) > 0 {
		for q := p.internal; q != nil; q = p.internal {
			p = &q.child[q.direction(prefix)]
			if q.offset < len(prefix) {
				top = p
			}
		}

		// check prefix
		if !bytes.Contains(p.external.key, prefix) {
			return true
		}
	}

	return allprefixed(top, handle)
}
584377
func (a *segment) buildIndex(quota int, minKeyBytes int) {
	if int(a.totKeyByte) < minKeyBytes {
		// Build the index only if the total key bytes is greater
		// than or equal to the SegmentKeysIndexMinKeyBytes.
		return
	}

	keyCount := a.Len()
	if keyCount == 0 {
		return // No keys to index.
	}

	keyAvgSize := int(a.totKeyByte) / keyCount

	sindex := newSegmentKeysIndex(quota, keyCount, keyAvgSize)
	if sindex == nil {
		return
	}

	scursor := &segmentCursor{
		s:   a,
		end: a.Len(),
	}

	for {
		keyIdx, key := scursor.currentKey()
		if key == nil {
			break
		}

		if !sindex.add(keyIdx, key) {
			break // Out of space.
		}

		err := scursor.nextDelta(sindex.hop)
		if err != nil {
			break
		}
	}

	a.index = sindex
}
1051382
func (e Error) formatParams() string {
	if e.Params == nil || len(e.Params) == 0 {
		return "[]"
	}

	var keyValuePairs []struct {
		key   string
		value string
	}

	for k, v := range e.Params {
		keyValuePairs = append(keyValuePairs, struct {
			key   string
			value string
		}{
			key:   k,
			value: v,
		})
	}
	sort.Slice(keyValuePairs, func(i, j int) bool {
		return keyValuePairs[i].key < keyValuePairs[j].key
	})

	result := "["
	l := len(keyValuePairs)
	for i, kvp := range keyValuePairs {
		result += kvp.key + ":" + kvp.value
		if i < l-1 {
			result += ", "
		}
	}
	result += "]"
	return result
}
157764
func (a *API) fixStutterNames() {
	str, end := a.StructName(), ""
	if len(str) > 1 {
		l := len(str) - 1
		str, end = str[0:l], str[l:]
	}
	re := regexp.MustCompile(fmt.Sprintf(`\A(?i:%s)%s`, str, end))

	for name, op := range a.Operations {
		newName := re.ReplaceAllString(name, "")
		if newName != name && len(newName) > 0 {
			delete(a.Operations, name)
			a.Operations[newName] = op
		}
		op.ExportedName = newName
	}

	for k, s := range a.Shapes {
		newName := re.ReplaceAllString(k, "")
		if newName != s.ShapeName && len(newName) > 0 {
			s.Rename(newName)
		}
	}
}
226435
func parseArgument(arg string) (string, string, error) {
	if !strings.HasPrefix(arg, "--") {
		return "", "", errors.New("the argument should start with '--'")
	}
	if !strings.Contains(arg, "=") {
		return "", "", errors.New("the argument should have a '=' between the flag and the value")
	}
	// Remove the starting --
	arg = strings.TrimPrefix(arg, "--")
	// Split the string on =. Return only two substrings, since we want only key/value, but the value can include '=' as well
	keyvalSlice := strings.SplitN(arg, "=", 2)

	// Make sure both a key and value is present
	if len(keyvalSlice) != 2 {
		return "", "", errors.New("the argument must have both a key and a value")
	}
	if len(keyvalSlice[0]) == 0 {
		return "", "", errors.New("the argument must have a key")
	}

	return keyvalSlice[0], keyvalSlice[1], nil
}
521363
func (aSpace *addrSpace) KeyPrefix() []string {
	aSpace.Lock()
	defer aSpace.Unlock()
	return []string{dsConfigKey}
}
221189
func Keys(in ...map[string]interface{}) ([]string, error) {
	if len(in) == 0 {
		return nil, fmt.Errorf("need at least one argument")
	}
	keys := []string{}
	for _, m := range in {
		k, _ := splitMap(m)
		keys = append(keys, k...)
	}
	return keys, nil
}
497603
func (ndb *nodeDB) traversePrefix(prefix []byte, fn func(k, v []byte)) {
	itr := dbm.IteratePrefix(ndb.db, prefix)
	defer itr.Close()

	for ; itr.Valid(); itr.Next() {
		fn(itr.Key(), itr.Value())
	}
}
1283491
func (kf *KeyFormat) ScanNoPrefix(key []byte, args ...interface{}) error {
	// Just pad by the length of the prefix
	paddedKey := make([]byte, len(kf.prefix)+len(key))
	copy(paddedKey[len(kf.prefix):], key)
	return kf.Scan(paddedKey, args...)
}
1010724
func Fix(args []string) []string {
	// Find the first flag argument or '--'.
	flagIdx := -1
	for i, arg := range args {
		if strings.HasPrefix(arg, "-") {
			flagIdx = i
			break
		}
	}

	if flagIdx == -1 {
		return args // no arguments at all or only positional arguments
	}

	// Move positional arguments after the flags.
	buf := make([]string, 0, len(args))
	return append(append(buf, args[flagIdx:]...), args[:flagIdx]...)
}
346777
func ArgsWithPrefix(args map[string][]string, prefix string) map[string][]string {
	filtered := map[string][]string{}
	for key, slice := range args {
		if !strings.HasPrefix(key, prefix) {
			continue
		}
		for _, val := range slice {
			filtered[key] = append(filtered[key], val)
		}
	}
	return filtered
}
806714
func NewKeyRenamer(patternKeys ...string) (KeyRenamer, error) {
	var renames []keyRename
	for i := 0; i < len(patternKeys); i += 2 {
		g, err := glob.Compile(strings.ToLower(patternKeys[i]), '/')
		if err != nil {
			return KeyRenamer{}, err
		}
		renames = append(renames, keyRename{pattern: g, newKey: patternKeys[i+1]})
	}

	return KeyRenamer{renames: renames}, nil
}
63180
func NewKeysFromStrings(strings []string) Keys {
	list := make(Keys, len(strings))
	for i := range strings {
		list[i] = StringKey(strings[i])
	}
	return list
}