github.com/april1989/origin-go-tools@v0.0.32/internal/span/token111.go (about)

     1  // Copyright 2019 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  // +build !go1.12
     6  
     7  package span
     8  
     9  import (
    10  	"go/token"
    11  )
    12  
    13  // lineStart is the pre-Go 1.12 version of (*token.File).LineStart. For Go
    14  // versions <= 1.11, we borrow logic from the analysisutil package.
    15  // TODO(rstambler): Delete this file when we no longer support Go 1.11.
    16  func lineStart(f *token.File, line int) token.Pos {
    17  	// Use binary search to find the start offset of this line.
    18  
    19  	min := 0        // inclusive
    20  	max := f.Size() // exclusive
    21  	for {
    22  		offset := (min + max) / 2
    23  		pos := f.Pos(offset)
    24  		posn := f.Position(pos)
    25  		if posn.Line == line {
    26  			return pos - (token.Pos(posn.Column) - 1)
    27  		}
    28  
    29  		if min+1 >= max {
    30  			return token.NoPos
    31  		}
    32  
    33  		if posn.Line < line {
    34  			min = offset
    35  		} else {
    36  			max = offset
    37  		}
    38  	}
    39  }