@@ -7,17 +7,26 @@ import (
77 "strings"
88)
99
10+ // Stack represents a captured stack trace as a sequence of frames.
11+ //
12+ // Use the Capture function to obtain a Stack, and the String method to render it.
13+ //
14+ // Example:
15+ //
16+ // stack := stacktrace.Capture(0, 10)
17+ // fmt.Println(stack)
1018type Stack struct {
11- frames []runtime.Frame `exhaustruct:"optional"`
19+ frames []runtime.Frame
1220}
1321
22+ // NewStack returns a new Stack with preallocated space for the given initial size.
1423func NewStack (initialSize int ) * Stack {
1524 return & Stack {
1625 frames : make ([]runtime.Frame , 0 , initialSize ),
1726 }
1827}
1928
20- // AddCaller adds the caller's frame to the stack.
29+ // AddCaller adds the current caller's frame to the stack.
2130func (s * Stack ) AddCaller () {
2231 pcs := make ([]uintptr , 1 )
2332 runtime .Callers (3 , pcs ) //nolint:mnd
@@ -27,18 +36,19 @@ func (s *Stack) AddCaller() {
2736 s .AddFrame (frame )
2837}
2938
39+ // AddFrame appends the given runtime.Frame to the stack.
3040func (s * Stack ) AddFrame (f runtime.Frame ) {
3141 s .frames = append (s .frames , f )
3242}
3343
34- // Len returns amount of frames contained in stack.
44+ // Len returns the number of frames contained in the stack.
3545func (s * Stack ) Len () int {
3646 return len (s .frames )
3747}
3848
3949// FramesIter returns an iterator over the frames in the stack.
4050//
41- // The iterator yields the frames starting from uppermost (the one added last).
51+ // The iterator yields the frames starting from the most recent (the one added last).
4252func (s * Stack ) FramesIter () iter.Seq2 [int , runtime.Frame ] {
4353 return func (yield func (int , runtime.Frame ) bool ) {
4454 start := len (s .frames ) - 1
@@ -50,6 +60,8 @@ func (s *Stack) FramesIter() iter.Seq2[int, runtime.Frame] {
5060 }
5161}
5262
63+ // String returns a multi-line string representation of the stack trace.
64+ // Each frame is shown with its function name and file:line.
5365func (s * Stack ) String () string {
5466 b := & strings.Builder {}
5567
@@ -64,13 +76,13 @@ func (s *Stack) String() string {
6476 return b .String ()
6577}
6678
67- // WriteFrameToBuffer writes a string representation of the given [ runtime.Frame]
68- // to the provided [ strings.Builder] .
79+ // WriteFrameToBuffer writes a string representation of the given runtime.Frame
80+ // to the provided strings.Builder.
6981//
7082// The format is:
7183//
72- // FunctionName
73- // FilePath :LineNumber
84+ // FunctionName
85+ // \tFilePath :LineNumber
7486func WriteFrameToBuffer (f runtime.Frame , b * strings.Builder ) {
7587 b .WriteString (f .Function )
7688 b .WriteRune ('\n' )
0 commit comments