Source file src/go/token/serialize.go

Documentation: go/token

     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  type serializedFile struct {
     8  	// fields correspond 1:1 to fields with same (lower-case) name in File
     9  	Name  string
    10  	Base  int
    11  	Size  int
    12  	Lines []int
    13  	Infos []lineInfo
    14  }
    15  
    16  type serializedFileSet struct {
    17  	Base  int
    18  	Files []serializedFile
    19  }
    20  
    21  // Read calls decode to deserialize a file set into s; s must not be nil.
    22  func (s *FileSet) Read(decode func(interface{}) error) error {
    23  	var ss serializedFileSet
    24  	if err := decode(&ss); err != nil {
    25  		return err
    26  	}
    27  
    28  	s.mutex.Lock()
    29  	s.base = ss.Base
    30  	files := make([]*File, len(ss.Files))
    31  	for i := 0; i < len(ss.Files); i++ {
    32  		f := &ss.Files[i]
    33  		files[i] = &File{
    34  			set:   s,
    35  			name:  f.Name,
    36  			base:  f.Base,
    37  			size:  f.Size,
    38  			lines: f.Lines,
    39  			infos: f.Infos,
    40  		}
    41  	}
    42  	s.files = files
    43  	s.last = nil
    44  	s.mutex.Unlock()
    45  
    46  	return nil
    47  }
    48  
    49  // Write calls encode to serialize the file set s.
    50  func (s *FileSet) Write(encode func(interface{}) error) error {
    51  	var ss serializedFileSet
    52  
    53  	s.mutex.Lock()
    54  	ss.Base = s.base
    55  	files := make([]serializedFile, len(s.files))
    56  	for i, f := range s.files {
    57  		f.mutex.Lock()
    58  		files[i] = serializedFile{
    59  			Name:  f.name,
    60  			Base:  f.base,
    61  			Size:  f.size,
    62  			Lines: append([]int(nil), f.lines...),
    63  			Infos: append([]lineInfo(nil), f.infos...),
    64  		}
    65  		f.mutex.Unlock()
    66  	}
    67  	ss.Files = files
    68  	s.mutex.Unlock()
    69  
    70  	return encode(ss)
    71  }
    72  

View as plain text