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