// struct HkdfLabel {
//    uint16 length;
//    opaque label<9..255>;
//    opaque hash_value<0..255>;
// };
765103
func hkdfEncodeLabel(labelIn string, hashValue []byte, outLen int) []byte {
	label := "tls13 " + labelIn

	labelLen := len(label)
	hashLen := len(hashValue)
	hkdfLabel := make([]byte, 2+1+labelLen+1+hashLen)
	hkdfLabel[0] = byte(outLen >> 8)
	hkdfLabel[1] = byte(outLen)
	hkdfLabel[2] = byte(labelLen)
	copy(hkdfLabel[3:3+labelLen], []byte(label))
	hkdfLabel[3+labelLen] = byte(hashLen)
	copy(hkdfLabel[3+labelLen+1:], hashValue)

	return hkdfLabel
}
946220
func structToMapString(i interface{}) map[string][]string {
	ms := map[string][]string{}
	iv := reflect.ValueOf(i).Elem()
	tp := iv.Type()

	for i := 0; i < iv.NumField(); i++ {
		k := tp.Field(i).Name
		f := iv.Field(i)
		ms[k] = valueToString(f)
	}

	return ms
}
535580
func generateLabelString(source, key, value string) string {
	return fmt.Sprintf("%s:%s=%s", source, key, value)
}
891295
func ToStringSigBytesPerKB(n int64, sig, bytesPerKB float64) string {
	var f = float64(n)
	var i int
	for i, _ = range scaleStrings {
		if f < bytesPerKB {
			break
		}
		f = f / bytesPerKB
	}
	f = ToPrecision(f, sig)
	if f == bytesPerKB {
		return strconv.FormatFloat(f/bytesPerKB, 'f', 0, 64) + toCase(scaleStrings[i+1])
	}
	return strconv.FormatFloat(f, 'f', -1, 64) + toCase(scaleStrings[i])
}
1153591
func LabelsToSignature(labels map[string]string) uint64 {
	if len(labels) == 0 {
		return emptyLabelSignature
	}

	labelNames := make([]string, 0, len(labels))
	for labelName := range labels {
		labelNames = append(labelNames, labelName)
	}
	sort.Strings(labelNames)

	sum := hashNew()
	for _, labelName := range labelNames {
		sum = hashAdd(sum, labelName)
		sum = hashAddByte(sum, SeparatorByte)
		sum = hashAdd(sum, labels[labelName])
		sum = hashAddByte(sum, SeparatorByte)
	}
	return sum
}
332350
func IPStringToLabel(IP string) (labels.Label, error) {
	_, parsedPrefix, err := net.ParseCIDR(IP)
	if err != nil {
		parsedIP := net.ParseIP(IP)
		if parsedIP == nil {
			return labels.Label{}, fmt.Errorf("Not an IP address or CIDR: %s", IP)
		}
		bits := net.IPv6len * 8
		if parsedIP.To4() != nil {
			bits = net.IPv4len * 8
		}
		parsedPrefix = &net.IPNet{IP: parsedIP, Mask: net.CIDRMask(bits, bits)}
	}

	return ipNetToLabel(parsedPrefix), nil
}
1081727
func byteSliceAsUint16Slice(slice []byte) []uint16 {
	if len(slice)%2 != 0 {
		panic("Slice size should be divisible by 2")
	}

	// make a new slice header
	header := *(*reflect.SliceHeader)(unsafe.Pointer(&slice))

	// update its capacity and length
	header.Len /= 2
	header.Cap /= 2

	// return it
	return *(*[]uint16)(unsafe.Pointer(&header))
}
412346
func ReadLabels(fn string, n int) ([]Labels, error) {
	f, err := os.Open(fn)
	if err != nil {
		return nil, err
	}
	defer f.Close()

	scanner := bufio.NewScanner(f)

	var mets []Labels
	hashes := map[uint64]struct{}{}
	i := 0

	for scanner.Scan() && i < n {
		m := make(Labels, 0, 10)

		r := strings.NewReplacer("\"", "", "{", "", "}", "")
		s := r.Replace(scanner.Text())

		labelChunks := strings.Split(s, ",")
		for _, labelChunk := range labelChunks {
			split := strings.Split(labelChunk, ":")
			m = append(m, Label{Name: split[0], Value: split[1]})
		}
		// Order of the k/v labels matters, don't assume we'll always receive them already sorted.
		sort.Sort(m)

		h := m.Hash()
		if _, ok := hashes[h]; ok {
			continue
		}
		mets = append(mets, m)
		hashes[h] = struct{}{}
		i++
	}

	if i != n {
		return mets, errors.Errorf("requested %d metrics but found %d", n, i)
	}
	return mets, nil
}
455939
func (f paramFiller) paramsStructStruct(value map[string]interface{}, shape *Shape) string {
	out := "&" + f.typeName(shape)[1:] + "{\n"
	for _, n := range shape.MemberNames() {
		ref := shape.MemberRefs[n]
		name := findParamMember(value, n)

		if val := f.paramsStructAny(value[name], ref.Shape); val != "" {
			out += fmt.Sprintf("%s: %s,\n", n, val)
		}
	}
	out += "}"
	return out
}
268940
func IsDNS1123Label(value string) []string {
	var errs []string
	if len(value) > DNS1123LabelMaxLength {
		errs = append(errs, MaxLenError(DNS1123LabelMaxLength))
	}
	if !dns1123LabelRegexp.MatchString(value) {
		errs = append(errs, RegexError(dns1123LabelErrMsg, dns1123LabelFmt, "my-name", "123-abc"))
	}
	return errs
}
506356
func StructsToMaps(Structs interface{}, Maps *[]map[string]interface{}, tag string) {
	sliceType := reflect.TypeOf(Structs)
	if sliceType.Kind() != reflect.Slice {
		panic(fmt.Errorf("Expected slice of structs as first argument, got %s", sliceType.Kind()))
	}

	structType := sliceType.Elem()
	if structType.Kind() != reflect.Struct {
		panic(fmt.Errorf("Expected slice of structs as first argument, got slice of %s", structType.Kind()))
	}

	structs := reflect.ValueOf(Structs)
	l := structs.Len()
	maps := reflect.MakeSlice(reflect.TypeOf([]map[string]interface{}{}), 0, l)

	for i := 0; i < l; i++ {
		m := make(map[string]interface{})
		StructValueToMap(structs.Index(i).Interface(), m, tag)
		maps = reflect.Append(maps, reflect.ValueOf(m))
	}

	reflect.ValueOf(Maps).Elem().Set(maps)
}
1129491
func (r *Reader) LabelValues(names ...string) (StringTuples, error) {

	key := strings.Join(names, labelNameSeperator)
	off, ok := r.labels[key]
	if !ok {
		// XXX(fabxc): hot fix. Should return a partial data error and handle cases
		// where the entire block has no data gracefully.
		return emptyStringTuples{}, nil
		//return nil, fmt.Errorf("label index doesn't exist")
	}

	d := encoding.NewDecbufAt(r.b, int(off), castagnoliTable)

	nc := d.Be32int()
	d.Be32() // consume unused value entry count.

	if d.Err() != nil {
		return nil, errors.Wrap(d.Err(), "read label value index")
	}
	st := &serializedStringTuples{
		idsCount: nc,
		idsBytes: d.Get(),
		lookup:   r.lookupSymbol,
	}
	return st, nil
}
985471
func chunkLabels(labels map[string]string, chunkSize int) [][]string {
	// First sort labels so they always occur in the same order.
	sorted := make([]string, 0, len(labels))
	for k, v := range labels {
		sorted = append(sorted, fmt.Sprintf("%v=%v", k, v))
	}
	sort.Slice(sorted, func(i, j int) bool { return sorted[i] < sorted[j] })

	// Then chunk labels into sized chunks.
	var chunks [][]string
	for chunkSize < len(sorted) {
		sorted, chunks = sorted[chunkSize:], append(chunks, sorted[0:chunkSize:chunkSize])
	}
	chunks = append(chunks, sorted)

	return chunks
}
206566
func SignatureWithoutLabels(m Metric, labels map[LabelName]struct{}) uint64 {
	if len(m) == 0 {
		return emptyLabelSignature
	}

	labelNames := make(LabelNames, 0, len(m))
	for labelName := range m {
		if _, exclude := labels[labelName]; !exclude {
			labelNames = append(labelNames, labelName)
		}
	}
	if len(labelNames) == 0 {
		return emptyLabelSignature
	}
	sort.Sort(labelNames)

	sum := hashNew()
	for _, labelName := range labelNames {
		sum = hashAdd(sum, string(labelName))
		sum = hashAddByte(sum, SeparatorByte)
		sum = hashAdd(sum, string(m[labelName]))
		sum = hashAddByte(sum, SeparatorByte)
	}
	return sum
}
184494
func (c CidStruct) Bytes() []byte {
	switch c.version {
	case 0:
		return []byte(c.hash)
	case 1:
		// two 8 bytes (max) numbers plus hash
		buf := make([]byte, 2*binary.MaxVarintLen64+len(c.hash))
		n := binary.PutUvarint(buf, c.version)
		n += binary.PutUvarint(buf[n:], c.codec)
		cn := copy(buf[n:], c.hash)
		if cn != len(c.hash) {
			panic("copy hash length is inconsistent")
		}
		return buf[:n+len(c.hash)]
	default:
		panic("not possible to reach this point")
	}
}
247988
func valueDescriptorByLabelHandler(w http.ResponseWriter, r *http.Request) {
	defer r.Body.Close()

	vars := mux.Vars(r)
	label, err := url.QueryUnescape(vars["label"])

	// Problem unescaping
	if err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		LoggingClient.Error("Error unescaping label for the value descriptor: " + err.Error())
		return
	}

	switch r.Method {
	case http.MethodGet:
		v, err := getValueDescriptorsByLabel(label)
		if err != nil {
			switch err.(type) {
			case *errors.ErrDbNotFound:
				http.Error(w, err.Error(), http.StatusNotFound)
				return
			default:
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
		}

		encode(v, w)
	}
}
880106
func (p *Pod) AddLabel(key, value string) *Pod {
	p.Labels[key] = value
	return p
}