github.com/haraldrudell/parl@v0.4.176/pruntime/first-stack-line.go (about)

     1  /*
     2  © 2022–present Harald Rudell <harald.rudell@gmail.com> (https://haraldrudell.github.io/haraldrudell/)
     3  ISC License
     4  */
     5  
     6  package pruntime
     7  
     8  import (
     9  	"bytes"
    10  	"runtime"
    11  )
    12  
    13  const (
    14  	stackBufferSize               = 100
    15  	runtimeStackOnlyThisGoroutine = false
    16  	newlineByte                   = 10
    17  )
    18  
    19  // FirstStackLine efficiently obtains the first line of a [runtime.Stack]
    20  //   - "goroutine 34 [running]:\n…"
    21  //   - interning the first line as a string will cost about 25 bytes
    22  func FirstStackLine() (firstStackLine []byte) {
    23  
    24  	// beginning of a stack trace in a small buffer
    25  	var buffer = make([]byte, stackBufferSize)
    26  	runtime.Stack(buffer, runtimeStackOnlyThisGoroutine)
    27  	if index := bytes.IndexByte(buffer, newlineByte); index != -1 {
    28  		buffer = buffer[:index]
    29  	}
    30  
    31  	// byte sequence of 25 characters or so
    32  	//	- interning large strings is temporary memory leak
    33  	firstStackLine = buffer
    34  
    35  	return
    36  }