go.tools/go/importer: record low-level encoding format
This avoids confusion when trying to read correctly encoded export data that happens to be encoded in a different format (debug vs product). LGTM=adonovan R=adonovan CC=golang-codereviews https://golang.org/cl/82090043
This commit is contained in:
parent
58edf2a69d
commit
4f89dd6aed
|
|
@ -21,12 +21,21 @@ const (
|
|||
trace = false // print emitted data
|
||||
)
|
||||
|
||||
// format returns a byte indicating the low-level encoding/decoding format
|
||||
// (debug vs product).
|
||||
func format() byte {
|
||||
if debug {
|
||||
return 'd'
|
||||
}
|
||||
return 'p'
|
||||
}
|
||||
|
||||
// ExportData serializes the interface (exported package objects)
|
||||
// of package pkg and returns the corresponding data. The export
|
||||
// format is described elsewhere (TODO).
|
||||
func ExportData(pkg *types.Package) []byte {
|
||||
p := exporter{
|
||||
data: []byte(magic),
|
||||
data: append([]byte(magic), format()),
|
||||
pkgIndex: make(map[*types.Package]int),
|
||||
typIndex: make(map[types.Type]int),
|
||||
}
|
||||
|
|
@ -394,8 +403,8 @@ func (p *exporter) bytes(b []byte) {
|
|||
}
|
||||
|
||||
// marker emits a marker byte and position information which makes
|
||||
// it easy for a reader to detect if it is "out of sync". Used in
|
||||
// debug mode only.
|
||||
// it easy for a reader to detect if it is "out of sync". Used for
|
||||
// debug format only.
|
||||
func (p *exporter) marker(m byte) {
|
||||
if debug {
|
||||
p.data = append(p.data, m)
|
||||
|
|
|
|||
|
|
@ -24,14 +24,29 @@ import (
|
|||
// data.
|
||||
func ImportData(imports map[string]*types.Package, data []byte) (*types.Package, error) {
|
||||
// check magic string
|
||||
if n := len(magic); len(data) < n || string(data[:n]) != magic {
|
||||
return nil, fmt.Errorf("incorrect magic string: got %q; want %q", data[:n], magic)
|
||||
var s string
|
||||
if len(data) >= len(magic) {
|
||||
s = string(data[:len(magic)])
|
||||
data = data[len(magic):]
|
||||
}
|
||||
if s != magic {
|
||||
return nil, fmt.Errorf("incorrect magic string: got %q; want %q", s, magic)
|
||||
}
|
||||
|
||||
// check low-level encoding format
|
||||
var m byte = 'm' // missing format
|
||||
if len(data) > 0 {
|
||||
m = data[0]
|
||||
data = data[1:]
|
||||
}
|
||||
if m != format() {
|
||||
return nil, fmt.Errorf("incorrect low-level encoding format: got %c; want %c", m, format())
|
||||
}
|
||||
|
||||
p := importer{
|
||||
data: data[len(magic):],
|
||||
data: data,
|
||||
imports: imports,
|
||||
consumed: len(magic), // for debugging only
|
||||
consumed: len(magic) + 1, // for debugging only
|
||||
}
|
||||
|
||||
// populate typList with predeclared types
|
||||
|
|
|
|||
Loading…
Reference in New Issue