~gioverse/chat

4e3a64cc82cf38c0360b79e98339b986327e7ce8 — Chris Waldon 4 months ago c86e075
debug: add function to trace code paths

Signed-off-by: Chris Waldon <christopher.waldon.dev@gmail.com>
1 files changed, 24 insertions(+), 0 deletions(-)

M debug/debug.go
M debug/debug.go => debug/debug.go +24 -0
@@ 6,9 6,11 @@ package debug
import (
	"bytes"
	"encoding/json"
	"fmt"
	"image/color"
	"io"
	"os"
	"runtime"

	"gioui.org/layout"
	"gioui.org/unit"


@@ 34,3 36,25 @@ func Dump(v interface{}) {
	b = append(b, []byte("\n")...)
	io.Copy(os.Stderr, bytes.NewBuffer(b))
}

// Caller returns the function nFrames above it on the call stack.
// Passing 3 as nFrames will return the details of the function
// invoking the function in which caller was invoked. This can help
// determine which of several code paths were taken to reach a
// particular place in the code.
func Caller(nFrames int) string {
	fpcs := make([]uintptr, 1)
	n := runtime.Callers(nFrames, fpcs)
	if n == 0 {
		return "NO CALLER"
	}

	caller := runtime.FuncForPC(fpcs[0] - 1)
	if caller == nil {
		return "MSG CALLER WAS NIL"
	}

	// Print the file name and line number
	file, line := caller.FileLine(fpcs[0] - 1)
	return fmt.Sprintf("%s:%d", file, line)
}