github.com/haraldrudell/parl@v0.4.176/pruntime/pruntimelib/parse-created-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 pruntimelib
     7  
     8  import (
     9  	"bytes"
    10  )
    11  
    12  // created by begins lines returned by runtime.Stack if
    13  // the executing thread is a launched goroutine “created by ”
    14  var runtCreatedByPrefix = []byte("created by ")
    15  
    16  // ParseCreatedLine parses the second-to-last line of the stack trace.
    17  // samples:
    18  //   - “created by main.main”
    19  //   - “created by main.(*MyType).goroutine1”
    20  //   - “main.main()”
    21  //   - go1.21.5 231219: “created by codeberg.org/haraldrudell/tools/gact.(*Transcriber).TranscriberThread in goroutine 9”
    22  //   - no allocations
    23  func ParseCreatedLine(createdLine []byte) (funcName, goroutineRef string, IsMainThread bool) {
    24  
    25  	// remove prefix “created by ”
    26  	var remain = bytes.TrimPrefix(createdLine, runtCreatedByPrefix)
    27  
    28  	// if the line did not have this prefix, it is the main thread that launched main.main
    29  	if IsMainThread = len(remain) == len(createdLine); IsMainThread {
    30  		return // main thread: IsMainThread: true funcName zero-value
    31  	}
    32  
    33  	// “codeberg.org/haraldrudell/tools/gact.(*Transcriber).TranscriberThread in goroutine 9”
    34  	if index := bytes.IndexByte(remain, '\x20'); index != -1 {
    35  		funcName = string(remain[:index])
    36  		goroutineRef = string(remain[index+1:])
    37  	} else {
    38  		funcName = string(remain)
    39  	}
    40  
    41  	return
    42  }