Skip to content

Commit

Permalink
Merge pull request #11 from m-mizutani/fix/copy-time
Browse files Browse the repository at this point in the history
fix(clone): Copy scalar (not CanAddr) values properly
  • Loading branch information
m-mizutani authored Sep 17, 2023
2 parents 58307ed + 2a9e268 commit 4af3faf
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 1 deletion.
16 changes: 15 additions & 1 deletion clone.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,12 +45,26 @@ func (x *masq) clone(fieldName string, src reflect.Value, tag string) reflect.Va
dstValue := dst.Elem().Field(i)

if !srcValue.CanInterface() {
dstValue = reflect.NewAt(dstValue.Type(), unsafe.Pointer(dstValue.UnsafeAddr())).Elem()

if !srcValue.CanAddr() {
switch {
case srcValue.CanInt():
dstValue.SetInt(srcValue.Int())
case srcValue.CanUint():
dstValue.SetUint(srcValue.Uint())
case srcValue.CanFloat():
dstValue.SetFloat(srcValue.Float())
case srcValue.CanComplex():
dstValue.SetComplex(srcValue.Complex())
case srcValue.Kind() == reflect.Bool:
dstValue.SetBool(srcValue.Bool())
}

continue
}

srcValue = reflect.NewAt(srcValue.Type(), unsafe.Pointer(srcValue.UnsafeAddr())).Elem()
dstValue = reflect.NewAt(dstValue.Type(), unsafe.Pointer(dstValue.UnsafeAddr())).Elem()
}

tagValue := f.Tag.Get("masq")
Expand Down
21 changes: 21 additions & 0 deletions clone_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
package masq_test

import (
"bytes"
"encoding/json"
"log/slog"
"strings"
"testing"
"time"

Expand Down Expand Up @@ -280,3 +284,20 @@ func TestDoublePointer(t *testing.T) {
copied := gt.MustCast[*myStruct](t, c.Redact(data)).NotNil()
gt.V(t, (*copied.c).Name).Equal("orange")
}

func TestTime(t *testing.T) {
ts := time.Now()
buf := &bytes.Buffer{}
logger := slog.New(slog.NewJSONHandler(buf, &slog.HandlerOptions{
AddSource: true,
ReplaceAttr: masq.New(),
}))
logger.Info("hello")

var out map[string]any
gt.Error(t, json.Unmarshal(buf.Bytes(), &out)).Pass()

tv, ok := out["time"].(string)
gt.B(t, ok).True()
gt.B(t, strings.Contains(tv, ts.Format("2006-01-02"))).True()
}

0 comments on commit 4af3faf

Please sign in to comment.