]> Cypherpunks repositories - gostls13.git/commitdiff
gob: isZero for struct values
authorRob Pike <r@golang.org>
Fri, 16 Dec 2011 19:33:57 +0000 (11:33 -0800)
committerRob Pike <r@golang.org>
Fri, 16 Dec 2011 19:33:57 +0000 (11:33 -0800)
Fixes #2577.

R=golang-dev, r, gri
CC=golang-dev
https://golang.org/cl/5492058

src/pkg/encoding/gob/encode.go
src/pkg/encoding/gob/gobencdec_test.go

index c7e48230c5306ebebd1cec9417ac24792ffe75c5..11afa02ea5aa4a42a4b7edb45544364e83d3fe56 100644 (file)
@@ -483,6 +483,13 @@ func isZero(val reflect.Value) bool {
                return val.Float() == 0
        case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
                return val.Uint() == 0
+       case reflect.Struct:
+               for i := 0; i < val.NumField(); i++ {
+                       if !isZero(val.Field(i)) {
+                               return false
+                       }
+               }
+               return true
        }
        panic("unknown type in isZero " + val.Type().String())
 }
index eacfd842db383cd4997ed9ec623e662277f078db..5cab4115919bfb44486000cc1635e0d4bc83567c 100644 (file)
@@ -13,6 +13,7 @@ import (
        "io"
        "strings"
        "testing"
+       "time"
 )
 
 // Types that implement the GobEncoder/Decoder interfaces.
@@ -526,3 +527,30 @@ func TestGobEncoderExtraIndirect(t *testing.T) {
                t.Errorf("got = %q, want %q", got, gdb)
        }
 }
+
+// Another bug: this caused a crash with the new Go1 Time type.
+
+type TimeBug struct {
+       T time.Time
+       S string
+       I int
+}
+
+func TestGobEncodeTime(t *testing.T) {
+       x := TimeBug{time.Now(), "hello", -55}
+       b := new(bytes.Buffer)
+       enc := NewEncoder(b)
+       err := enc.Encode(x)
+       if err != nil {
+               t.Fatal("encode:", err)
+       }
+       var y TimeBug
+       dec := NewDecoder(b)
+       err = dec.Decode(&y)
+       if err != nil {
+               t.Fatal("decode:", err)
+       }
+       if x != y {
+               t.Fatal("%v != %v", x, y)
+       }
+}