github.com/keysonzzz/kmg@v0.0.0-20151121023212-05317bfd7d39/kmgGoSource/kmgGoReader/FilePos.go (about)

     1  package kmgGoReader
     2  
     3  import (
     4  	"sort"
     5  	"strconv"
     6  )
     7  
     8  type FilePos struct {
     9  	filePath string
    10  	lines    []int
    11  }
    12  
    13  func NewPosFile(filepath string, content []byte) *FilePos {
    14  	lines := make([]int, 0)
    15  	r := NewReader(content, nil)
    16  	lines = append(lines, 0)
    17  	for {
    18  		r.ReadUntilByte('\n')
    19  		if r.IsEof() {
    20  			break
    21  		}
    22  		lines = append(lines, r.pos)
    23  	}
    24  	return &FilePos{
    25  		filePath: filepath,
    26  		lines:    lines,
    27  	}
    28  }
    29  
    30  func (p *FilePos) PosString(pos int) string {
    31  	if p == nil {
    32  		return "<nil>"
    33  	}
    34  	line := p.GetLineWithPos(pos)
    35  	return p.filePath + ":" + strconv.Itoa(line)
    36  }
    37  
    38  func (p *FilePos) GetLineWithPos(pos int) int {
    39  	return sort.SearchInts(p.lines, pos)
    40  }