Skip to content

Commit

Permalink
refactoring of stack.Record
Browse files Browse the repository at this point in the history
  • Loading branch information
asmyasnikov committed Nov 8, 2023
1 parent 36f3718 commit b9aa919
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 4 deletions.
27 changes: 23 additions & 4 deletions internal/stack/record.go
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,18 @@ func PackagePath(b bool) recordOption {
}
}

func Record(depth int, opts ...recordOption) string {
type call struct {
function uintptr
file string
line int
}

func Call(depth int) (call call) {
call.function, call.file, call.line, _ = runtime.Caller(depth + 1)
return call
}

func (call call) Record(opts ...recordOption) string {
optionsHolder := recordOptions{
packagePath: true,
packageName: true,
Expand All @@ -75,13 +86,13 @@ func Record(depth int, opts ...recordOption) string {
for _, opt := range opts {
opt(&optionsHolder)
}
function, file, line, _ := runtime.Caller(depth + 1)
name := runtime.FuncForPC(function).Name()
name := runtime.FuncForPC(call.function).Name()
var (
pkgPath string
pkgName string
structName string
funcName string
file = call.file
)
if i := strings.LastIndex(file, "/"); i > -1 {
file = file[i+1:]
Expand Down Expand Up @@ -147,11 +158,19 @@ func Record(depth int, opts ...recordOption) string {
buffer.WriteString(file)
if optionsHolder.line {
buffer.WriteByte(':')
fmt.Fprintf(buffer, "%d", line)
fmt.Fprintf(buffer, "%d", call.line)
}
if closeBrace {
buffer.WriteByte(')')
}
}
return buffer.String()
}

func (call call) FunctionID() string {
return call.Record(Lambda(false), FileName(false))
}

func Record(depth int, opts ...recordOption) string {
return Call(depth + 1).Record(opts...)
}
28 changes: 28 additions & 0 deletions internal/stack/record_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -256,3 +256,31 @@ func TestRecord(t *testing.T) {
})
}
}

func BenchmarkCall(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_ = Call(0)
}
}

func BenchmarkRecord(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_ = Record(0)
}
}

func BenchmarkCallRecord(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_ = Call(0).Record()
}
}

func BenchmarkCallFuncionID(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
_ = Call(0).FunctionID()
}
}

0 comments on commit b9aa919

Please sign in to comment.