github.com/lovishpuri/go-40569/src@v0.0.0-20230519171745-f8623e7c56cf/go/token/serialize_test.go (about) 1 // Copyright 2011 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package token 6 7 import ( 8 "bytes" 9 "encoding/gob" 10 "fmt" 11 "testing" 12 ) 13 14 // equal returns nil if p and q describe the same file set; 15 // otherwise it returns an error describing the discrepancy. 16 func equal(p, q *FileSet) error { 17 if p == q { 18 // avoid deadlock if p == q 19 return nil 20 } 21 22 // not strictly needed for the test 23 p.mutex.Lock() 24 q.mutex.Lock() 25 defer q.mutex.Unlock() 26 defer p.mutex.Unlock() 27 28 if p.base != q.base { 29 return fmt.Errorf("different bases: %d != %d", p.base, q.base) 30 } 31 32 if len(p.files) != len(q.files) { 33 return fmt.Errorf("different number of files: %d != %d", len(p.files), len(q.files)) 34 } 35 36 for i, f := range p.files { 37 g := q.files[i] 38 if f.name != g.name { 39 return fmt.Errorf("different filenames: %q != %q", f.name, g.name) 40 } 41 if f.base != g.base { 42 return fmt.Errorf("different base for %q: %d != %d", f.name, f.base, g.base) 43 } 44 if f.size != g.size { 45 return fmt.Errorf("different size for %q: %d != %d", f.name, f.size, g.size) 46 } 47 for j, l := range f.lines { 48 m := g.lines[j] 49 if l != m { 50 return fmt.Errorf("different offsets for %q", f.name) 51 } 52 } 53 for j, l := range f.infos { 54 m := g.infos[j] 55 if l.Offset != m.Offset || l.Filename != m.Filename || l.Line != m.Line { 56 return fmt.Errorf("different infos for %q", f.name) 57 } 58 } 59 } 60 61 // we don't care about .last - it's just a cache 62 return nil 63 } 64 65 func checkSerialize(t *testing.T, p *FileSet) { 66 var buf bytes.Buffer 67 encode := func(x any) error { 68 return gob.NewEncoder(&buf).Encode(x) 69 } 70 if err := p.Write(encode); err != nil { 71 t.Errorf("writing fileset failed: %s", err) 72 return 73 } 74 q := NewFileSet() 75 decode := func(x any) error { 76 return gob.NewDecoder(&buf).Decode(x) 77 } 78 if err := q.Read(decode); err != nil { 79 t.Errorf("reading fileset failed: %s", err) 80 return 81 } 82 if err := equal(p, q); err != nil { 83 t.Errorf("filesets not identical: %s", err) 84 } 85 } 86 87 func TestSerialization(t *testing.T) { 88 p := NewFileSet() 89 checkSerialize(t, p) 90 // add some files 91 for i := 0; i < 10; i++ { 92 f := p.AddFile(fmt.Sprintf("file%d", i), p.Base()+i, i*100) 93 checkSerialize(t, p) 94 // add some lines and alternative file infos 95 line := 1000 96 for offs := 0; offs < f.Size(); offs += 40 + i { 97 f.AddLine(offs) 98 if offs%7 == 0 { 99 f.AddLineInfo(offs, fmt.Sprintf("file%d", offs), line) 100 line += 33 101 } 102 } 103 checkSerialize(t, p) 104 } 105 }