github.com/hikaru7719/go@v0.0.0-20181025140707-c8b2ac68906a/src/go/doc/lazyre.go (about) 1 // Copyright 2018 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 doc 6 7 import ( 8 "os" 9 "regexp" 10 "strings" 11 "sync" 12 ) 13 14 type lazyRE struct { 15 str string 16 once sync.Once 17 rx *regexp.Regexp 18 } 19 20 func (r *lazyRE) re() *regexp.Regexp { 21 r.once.Do(r.build) 22 return r.rx 23 } 24 25 func (r *lazyRE) build() { 26 r.rx = regexp.MustCompile(r.str) 27 r.str = "" 28 } 29 30 func (r *lazyRE) FindStringSubmatchIndex(s string) []int { 31 return r.re().FindStringSubmatchIndex(s) 32 } 33 34 func (r *lazyRE) ReplaceAllString(src, repl string) string { 35 return r.re().ReplaceAllString(src, repl) 36 } 37 38 func (r *lazyRE) MatchString(s string) bool { 39 return r.re().MatchString(s) 40 } 41 42 var inTest = len(os.Args) > 0 && strings.HasSuffix(strings.TrimSuffix(os.Args[0], ".exe"), ".test") 43 44 func newLazyRE(str string) *lazyRE { 45 lr := &lazyRE{str: str} 46 if inTest { 47 // In tests, always compile the regexps early. 48 lr.re() 49 } 50 return lr 51 }