Source file src/internal/trace/writer.go

     1  // Copyright 2017 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 trace
     6  
     7  import "bytes"
     8  
     9  // Writer is a test trace writer.
    10  type Writer struct {
    11  	bytes.Buffer
    12  }
    13  
    14  func NewWriter() *Writer {
    15  	w := new(Writer)
    16  	w.Write([]byte("go 1.9 trace\x00\x00\x00\x00"))
    17  	return w
    18  }
    19  
    20  // Emit writes an event record to the trace.
    21  // See Event types for valid types and required arguments.
    22  func (w *Writer) Emit(typ byte, args ...uint64) {
    23  	nargs := byte(len(args)) - 1
    24  	if nargs > 3 {
    25  		nargs = 3
    26  	}
    27  	buf := []byte{typ | nargs<<6}
    28  	if nargs == 3 {
    29  		buf = append(buf, 0)
    30  	}
    31  	for _, a := range args {
    32  		buf = appendVarint(buf, a)
    33  	}
    34  	if nargs == 3 {
    35  		buf[1] = byte(len(buf) - 2)
    36  	}
    37  	n, err := w.Write(buf)
    38  	if n != len(buf) || err != nil {
    39  		panic("failed to write")
    40  	}
    41  }
    42  
    43  func appendVarint(buf []byte, v uint64) []byte {
    44  	for ; v >= 0x80; v >>= 7 {
    45  		buf = append(buf, 0x80|byte(v))
    46  	}
    47  	buf = append(buf, byte(v))
    48  	return buf
    49  }
    50  

View as plain text