...

Source file src/go.opencensus.io/internal/tagencoding/tagencoding.go

Documentation: go.opencensus.io/internal/tagencoding

     1  // Copyright 2017, OpenCensus Authors
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  //
    15  
    16  // Package tagencoding contains the tag encoding
    17  // used interally by the stats collector.
    18  package tagencoding // import "go.opencensus.io/internal/tagencoding"
    19  
    20  // Values represent the encoded buffer for the values.
    21  type Values struct {
    22  	Buffer     []byte
    23  	WriteIndex int
    24  	ReadIndex  int
    25  }
    26  
    27  func (vb *Values) growIfRequired(expected int) {
    28  	if len(vb.Buffer)-vb.WriteIndex < expected {
    29  		tmp := make([]byte, 2*(len(vb.Buffer)+1)+expected)
    30  		copy(tmp, vb.Buffer)
    31  		vb.Buffer = tmp
    32  	}
    33  }
    34  
    35  // WriteValue is the helper method to encode Values from map[Key][]byte.
    36  func (vb *Values) WriteValue(v []byte) {
    37  	length := len(v) & 0xff
    38  	vb.growIfRequired(1 + length)
    39  
    40  	// writing length of v
    41  	vb.Buffer[vb.WriteIndex] = byte(length)
    42  	vb.WriteIndex++
    43  
    44  	if length == 0 {
    45  		// No value was encoded for this key
    46  		return
    47  	}
    48  
    49  	// writing v
    50  	copy(vb.Buffer[vb.WriteIndex:], v[:length])
    51  	vb.WriteIndex += length
    52  }
    53  
    54  // ReadValue is the helper method to decode Values to a map[Key][]byte.
    55  func (vb *Values) ReadValue() []byte {
    56  	// read length of v
    57  	length := int(vb.Buffer[vb.ReadIndex])
    58  	vb.ReadIndex++
    59  	if length == 0 {
    60  		// No value was encoded for this key
    61  		return nil
    62  	}
    63  
    64  	// read value of v
    65  	v := make([]byte, length)
    66  	endIdx := vb.ReadIndex + length
    67  	copy(v, vb.Buffer[vb.ReadIndex:endIdx])
    68  	vb.ReadIndex = endIdx
    69  	return v
    70  }
    71  
    72  // Bytes returns a reference to already written bytes in the Buffer.
    73  func (vb *Values) Bytes() []byte {
    74  	return vb.Buffer[:vb.WriteIndex]
    75  }
    76  

View as plain text