github.com/haraldrudell/parl@v0.4.176/pruntime/pruntimelib/parse-first-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  	"fmt"
    11  	"regexp"
    12  	"strconv"
    13  )
    14  
    15  const (
    16  	// debug.Stack uses this prefix in the first line of the result
    17  	runFirstRexpT = "^goroutine ([[:digit:]]+) [[]([^]]+)[]]:$"
    18  )
    19  
    20  var firstRexp = regexp.MustCompile(runFirstRexpT)
    21  
    22  // getID obtains gorutine ID, as of go1.18 a numeric string "1"…
    23  func ParseFirstLine(debugStack []byte) (ID uint64, status string, err error) {
    24  
    25  	// remove possible lines 2…
    26  	if index := bytes.IndexByte(debugStack, '\n'); index != -1 {
    27  		debugStack = debugStack[:index]
    28  	}
    29  
    30  	// find ID and status
    31  	var matches = firstRexp.FindAllSubmatch(debugStack, -1)
    32  	if matches == nil {
    33  		err = fmt.Errorf("goid.ParseFirstStackLine failed to parse: %q", string(debugStack))
    34  		return
    35  	}
    36  
    37  	// return values
    38  	var values = matches[0][1:]
    39  	if ID, err = strconv.ParseUint(string(values[0]), 10, 64); err != nil {
    40  		return
    41  	}
    42  	status = string(values[1])
    43  
    44  	return
    45  }