fork of https://github.com/sourcegraph/zoekt
1// Copyright 2016 Google Inc. All rights reserved.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package zoekt
16
17import (
18 "context"
19 "fmt"
20 "log"
21 "regexp/syntax"
22 "sort"
23 "strings"
24 "time"
25
26 enry_data "github.com/go-enry/go-enry/v2/data"
27 "github.com/grafana/regexp"
28
29 "github.com/sourcegraph/zoekt/query"
30)
31
32// simplifyMultiRepo takes a query and a predicate. It returns Const(true) if all
33// repository names fulfill the predicate, Const(false) if none of them do, and q
34// otherwise.
35func (d *indexData) simplifyMultiRepo(q query.Q, predicate func(*Repository) bool) query.Q {
36 count := 0
37 alive := len(d.repoMetaData)
38 for i := range d.repoMetaData {
39 if d.repoMetaData[i].Tombstone {
40 alive--
41 } else if predicate(&d.repoMetaData[i]) {
42 count++
43 }
44 }
45 if count == alive {
46 return &query.Const{Value: true}
47 }
48 if count > 0 {
49 return q
50 }
51 return &query.Const{Value: false}
52}
53
54func (d *indexData) simplify(in query.Q) query.Q {
55 eval := query.Map(in, func(q query.Q) query.Q {
56 switch r := q.(type) {
57 case *query.Repo:
58 return d.simplifyMultiRepo(q, func(repo *Repository) bool {
59 return r.Regexp.MatchString(repo.Name)
60 })
61 case *query.RepoRegexp:
62 return d.simplifyMultiRepo(q, func(repo *Repository) bool {
63 return r.Regexp.MatchString(repo.Name)
64 })
65 case *query.BranchesRepos:
66 for i := range d.repoMetaData {
67 for _, br := range r.List {
68 if br.Repos.Contains(d.repoMetaData[i].ID) {
69 return q
70 }
71 }
72 }
73 return &query.Const{Value: false}
74 case *query.RepoSet:
75 return d.simplifyMultiRepo(q, func(repo *Repository) bool {
76 return r.Set[repo.Name]
77 })
78 case *query.RepoIDs:
79 return d.simplifyMultiRepo(q, func(repo *Repository) bool {
80 return r.Repos.Contains(repo.ID)
81 })
82 case *query.Language:
83 _, has := d.metaData.LanguageMap[r.Language]
84 if !has && d.metaData.IndexFeatureVersion < 12 {
85 // For index files that haven't been re-indexed by go-enry,
86 // fall back to file-based matching and continue even if this
87 // repo doesn't have the specific language present.
88 extsForLang := enry_data.ExtensionsByLanguage[r.Language]
89 if extsForLang != nil {
90 extFrags := make([]string, 0, len(extsForLang))
91 for _, ext := range extsForLang {
92 extFrags = append(extFrags, regexp.QuoteMeta(ext))
93 }
94 if len(extFrags) > 0 {
95 pattern := fmt.Sprintf("(?i)(%s)$", strings.Join(extFrags, "|"))
96 // inlined copy of query.regexpQuery
97 re, err := syntax.Parse(pattern, syntax.Perl)
98 if err != nil {
99 return &query.Const{Value: false}
100 }
101 if re.Op == syntax.OpLiteral {
102 return &query.Substring{
103 Pattern: string(re.Rune),
104 FileName: true,
105 }
106 }
107 return &query.Regexp{
108 Regexp: re,
109 FileName: true,
110 }
111 }
112 }
113 }
114 if !has {
115 return &query.Const{Value: false}
116 }
117 }
118 return q
119 })
120 return query.Simplify(eval)
121}
122
123func (o *SearchOptions) SetDefaults() {
124 if o.ShardMaxMatchCount == 0 {
125 // We cap the total number of matches, so overly broad
126 // searches don't crash the machine.
127 o.ShardMaxMatchCount = 100000
128 }
129 if o.TotalMaxMatchCount == 0 {
130 o.TotalMaxMatchCount = 10 * o.ShardMaxMatchCount
131 }
132}
133
134func (d *indexData) Search(ctx context.Context, q query.Q, opts *SearchOptions) (sr *SearchResult, err error) {
135 timer := newTimer()
136
137 copyOpts := *opts
138 opts = ©Opts
139 opts.SetDefaults()
140
141 var res SearchResult
142 if len(d.fileNameIndex) == 0 {
143 return &res, nil
144 }
145
146 select {
147 case <-ctx.Done():
148 res.Stats.ShardsSkipped++
149 return &res, nil
150 default:
151 }
152
153 q = d.simplify(q)
154 if c, ok := q.(*query.Const); ok && !c.Value {
155 return &res, nil
156 }
157
158 if opts.EstimateDocCount {
159 res.Stats.ShardFilesConsidered = len(d.fileBranchMasks)
160 return &res, nil
161 }
162
163 q = query.Map(q, query.ExpandFileContent)
164
165 mt, err := d.newMatchTree(q, matchTreeOpt{})
166 if err != nil {
167 return nil, err
168 }
169
170 // Capture the costs of construction before pruning
171 updateMatchTreeStats(mt, &res.Stats)
172
173 mt, err = pruneMatchTree(mt)
174 if err != nil {
175 return nil, err
176 }
177 res.Stats.MatchTreeConstruction = timer.Elapsed()
178 if mt == nil {
179 res.Stats.ShardsSkippedFilter++
180 return &res, nil
181 }
182
183 res.Stats.ShardsScanned++
184
185 cp := &contentProvider{
186 id: d,
187 stats: &res.Stats,
188 }
189
190 // Track the number of documents found in a repository for
191 // ShardRepoMaxMatchCount
192 var (
193 lastRepoID uint16
194 repoMatchCount int
195 )
196
197 docCount := uint32(len(d.fileBranchMasks))
198 lastDoc := int(-1)
199
200nextFileMatch:
201 for {
202 canceled := false
203 select {
204 case <-ctx.Done():
205 canceled = true
206 default:
207 }
208
209 nextDoc := mt.nextDoc()
210 if int(nextDoc) <= lastDoc {
211 nextDoc = uint32(lastDoc + 1)
212 }
213
214 for ; nextDoc < docCount; nextDoc++ {
215 repoID := d.repos[nextDoc]
216 repoMetadata := &d.repoMetaData[repoID]
217
218 // Skip tombstoned repositories
219 if repoMetadata.Tombstone {
220 continue
221 }
222
223 // Skip documents that are tombstoned
224 if len(repoMetadata.FileTombstones) > 0 {
225 if _, tombstoned := repoMetadata.FileTombstones[string(d.fileName(nextDoc))]; tombstoned {
226 continue
227 }
228 }
229
230 // Skip documents over ShardRepoMaxMatchCount if specified.
231 if opts.ShardRepoMaxMatchCount > 0 {
232 if repoMatchCount >= opts.ShardRepoMaxMatchCount && repoID == lastRepoID {
233 res.Stats.FilesSkipped++
234 continue
235 }
236 }
237
238 break
239 }
240
241 if nextDoc >= docCount {
242 break
243 }
244
245 lastDoc = int(nextDoc)
246
247 // We track lastRepoID for ShardRepoMaxMatchCount
248 if lastRepoID != d.repos[nextDoc] {
249 lastRepoID = d.repos[nextDoc]
250 repoMatchCount = 0
251 }
252
253 if canceled || (res.Stats.MatchCount >= opts.ShardMaxMatchCount && opts.ShardMaxMatchCount > 0) {
254 res.Stats.FilesSkipped += int(docCount - nextDoc)
255 break
256 }
257
258 res.Stats.FilesConsidered++
259 mt.prepare(nextDoc)
260
261 cp.setDocument(nextDoc)
262
263 known := make(map[matchTree]bool)
264 md := d.repoMetaData[d.repos[nextDoc]]
265
266 for cost := costMin; cost <= costMax; cost++ {
267 switch evalMatchTree(cp, cost, known, mt) {
268 case matchesRequiresHigherCost:
269 if cost == costMax {
270 log.Panicf("did not decide. Repo %s, doc %d, known %v",
271 md.Name, nextDoc, known)
272 }
273 case matchesFound:
274 // could short-circuit now, but we want to run higher costs to
275 // potentially find higher ranked matches.
276 case matchesNone:
277 continue nextFileMatch
278 }
279 }
280
281 fileMatch := FileMatch{
282 Repository: md.Name,
283 RepositoryID: md.ID,
284 RepositoryPriority: md.priority,
285 FileName: string(d.fileName(nextDoc)),
286 Checksum: d.getChecksum(nextDoc),
287 Language: d.languageMap[d.getLanguage(nextDoc)],
288 }
289
290 if s := d.subRepos[nextDoc]; s > 0 {
291 if s >= uint32(len(d.subRepoPaths[d.repos[nextDoc]])) {
292 log.Panicf("corrupt index: subrepo %d beyond %v", s, d.subRepoPaths)
293 }
294 path := d.subRepoPaths[d.repos[nextDoc]][s]
295 fileMatch.SubRepositoryPath = path
296 sr := md.SubRepoMap[path]
297 fileMatch.SubRepositoryName = sr.Name
298 if idx := d.branchIndex(nextDoc); idx >= 0 {
299 fileMatch.Version = sr.Branches[idx].Version
300 }
301 } else {
302 idx := d.branchIndex(nextDoc)
303 if idx >= 0 {
304 fileMatch.Version = md.Branches[idx].Version
305 }
306 }
307
308 // Important invariant for performance: finalCands is sorted by offset and
309 // non-overlapping. gatherMatches respects this invariant and all later
310 // transformations respect this.
311 shouldMergeMatches := !opts.ChunkMatches
312 finalCands := d.gatherMatches(nextDoc, mt, known, shouldMergeMatches)
313
314 if opts.ChunkMatches {
315 fileMatch.ChunkMatches = cp.fillChunkMatches(finalCands, opts.NumContextLines, fileMatch.Language, opts.DebugScore)
316 } else {
317 fileMatch.LineMatches = cp.fillMatches(finalCands, opts.NumContextLines, fileMatch.Language, opts.DebugScore)
318 }
319
320 if opts.UseKeywordScoring {
321 d.scoreFileUsingBM25(&fileMatch, nextDoc, finalCands, opts)
322 } else {
323 // Use the standard, non-experimental scoring method by default
324 d.scoreFile(&fileMatch, nextDoc, mt, known, opts)
325 }
326
327 fileMatch.Branches = d.gatherBranches(nextDoc, mt, known)
328 sortMatchesByScore(fileMatch.LineMatches)
329 sortChunkMatchesByScore(fileMatch.ChunkMatches)
330 if opts.Whole {
331 fileMatch.Content = cp.data(false)
332 }
333
334 matchedChunkRanges := 0
335 for _, cm := range fileMatch.ChunkMatches {
336 matchedChunkRanges += len(cm.Ranges)
337 }
338
339 repoMatchCount += len(fileMatch.LineMatches)
340 repoMatchCount += matchedChunkRanges
341
342 if opts.DebugScore {
343 fileMatch.Debug = fmt.Sprintf("score:%.2f <- %s", fileMatch.Score, fileMatch.Debug)
344 }
345
346 res.Files = append(res.Files, fileMatch)
347 res.Stats.MatchCount += len(fileMatch.LineMatches)
348 res.Stats.MatchCount += matchedChunkRanges
349 res.Stats.FileCount++
350 }
351
352 for _, md := range d.repoMetaData {
353 r := md
354 addRepo(&res, &r)
355 for _, v := range r.SubRepoMap {
356 addRepo(&res, v)
357 }
358 }
359
360 // Update stats based on work done during document search.
361 updateMatchTreeStats(mt, &res.Stats)
362
363 // If document ranking is enabled, then we can rank and truncate the files to save memory.
364 if opts.UseDocumentRanks {
365 res.Files = SortAndTruncateFiles(res.Files, opts)
366 }
367
368 res.Stats.MatchTreeSearch = timer.Elapsed()
369
370 return &res, nil
371}
372
373func addRepo(res *SearchResult, repo *Repository) {
374 if res.RepoURLs == nil {
375 res.RepoURLs = map[string]string{}
376 }
377 res.RepoURLs[repo.Name] = repo.FileURLTemplate
378
379 if res.LineFragments == nil {
380 res.LineFragments = map[string]string{}
381 }
382 res.LineFragments[repo.Name] = repo.LineFragmentTemplate
383}
384
385// Gather matches from this document. This never returns a mixture of
386// filename/content matches: if there are content matches, all
387// filename matches are trimmed from the result. The matches are
388// returned in document order and are non-overlapping.
389//
390// If `merge` is set, overlapping and adjacent matches will be merged
391// into a single match. Otherwise, overlapping matches will be removed,
392// but adjacent matches will remain.
393func (d *indexData) gatherMatches(nextDoc uint32, mt matchTree, known map[matchTree]bool, merge bool) []*candidateMatch {
394 var cands []*candidateMatch
395 visitMatches(mt, known, 1, func(mt matchTree, scoreWeight float64) {
396 if smt, ok := mt.(*substrMatchTree); ok {
397 cands = append(cands, setScoreWeight(scoreWeight, smt.current)...)
398 }
399 if rmt, ok := mt.(*regexpMatchTree); ok {
400 cands = append(cands, setScoreWeight(scoreWeight, rmt.found)...)
401 }
402 if rmt, ok := mt.(*wordMatchTree); ok {
403 cands = append(cands, setScoreWeight(scoreWeight, rmt.found)...)
404 }
405 if smt, ok := mt.(*symbolRegexpMatchTree); ok {
406 cands = append(cands, setScoreWeight(scoreWeight, smt.found)...)
407 }
408 })
409
410 // If there are content matches, trim all filename matches.
411 foundContentMatch := false
412 for _, c := range cands {
413 if !c.fileName {
414 foundContentMatch = true
415 break
416 }
417 }
418
419 res := cands[:0]
420 for _, c := range cands {
421 if !foundContentMatch || !c.fileName {
422 res = append(res, c)
423 }
424 }
425 cands = res
426
427 // If we found no candidate matches at all, assume there must have been a match on filename.
428 if len(cands) == 0 {
429 nm := d.fileName(nextDoc)
430 return []*candidateMatch{{
431 caseSensitive: false,
432 fileName: true,
433 substrBytes: nm,
434 substrLowered: nm,
435 file: nextDoc,
436 runeOffset: 0,
437 byteOffset: 0,
438 byteMatchSz: uint32(len(nm)),
439 }}
440 }
441
442 if merge {
443 // Merge adjacent candidates. This guarantees that the matches
444 // are non-overlapping.
445 sort.Sort((sortByOffsetSlice)(cands))
446 res = cands[:0]
447 mergeRun := 1
448 for i, c := range cands {
449 if i == 0 {
450 res = append(res, c)
451 continue
452 }
453 last := res[len(res)-1]
454 lastEnd := last.byteOffset + last.byteMatchSz
455 end := c.byteOffset + c.byteMatchSz
456 if lastEnd >= c.byteOffset {
457 mergeRun++
458
459 // Average out the score across the merged candidates. Only do it if
460 // we are boosting to avoid floating point funkiness in the normal
461 // case.
462 if !(epsilonEqualsOne(last.scoreWeight) && epsilonEqualsOne(c.scoreWeight)) {
463 last.scoreWeight = ((last.scoreWeight * float64(mergeRun-1)) + c.scoreWeight) / float64(mergeRun)
464 }
465
466 // latest candidate goes further, update our end
467 if end > lastEnd {
468 last.byteMatchSz = end - last.byteOffset
469 }
470
471 continue
472 } else {
473 mergeRun = 1
474 }
475
476 res = append(res, c)
477 }
478 } else {
479 // Remove overlapping candidates. This guarantees that the matches
480 // are non-overlapping, but also preserves expected match counts.
481 sort.Sort((sortByOffsetSlice)(cands))
482 res = cands[:0]
483 for i, c := range cands {
484 if i == 0 {
485 res = append(res, c)
486 continue
487 }
488 last := res[len(res)-1]
489 lastEnd := last.byteOffset + last.byteMatchSz
490 if lastEnd > c.byteOffset {
491 continue
492 }
493
494 res = append(res, c)
495 }
496 }
497 return res
498}
499
500type sortByOffsetSlice []*candidateMatch
501
502func (m sortByOffsetSlice) Len() int { return len(m) }
503func (m sortByOffsetSlice) Swap(i, j int) { m[i], m[j] = m[j], m[i] }
504func (m sortByOffsetSlice) Less(i, j int) bool {
505 if m[i].byteOffset == m[j].byteOffset { // tie break if same offset
506 // Prefer longer candidates if starting at same position
507 return m[i].byteMatchSz > m[j].byteMatchSz
508 }
509 return m[i].byteOffset < m[j].byteOffset
510}
511
512// setScoreWeight is a helper used by gatherMatches to set the weight based on
513// the score weight of the matchTree.
514func setScoreWeight(scoreWeight float64, cm []*candidateMatch) []*candidateMatch {
515 for _, m := range cm {
516 m.scoreWeight = scoreWeight
517 }
518 return cm
519}
520
521func (d *indexData) branchIndex(docID uint32) int {
522 mask := d.fileBranchMasks[docID]
523 idx := 0
524 for mask != 0 {
525 if mask&0x1 != 0 {
526 return idx
527 }
528 idx++
529 mask >>= 1
530 }
531 return -1
532}
533
534// gatherBranches returns a list of branch names taking into account any branch
535// filters in the query. If the query contains a branch filter, it returns all
536// branches containing the docID and matching the branch filter. Otherwise, it
537// returns all branches containing docID.
538func (d *indexData) gatherBranches(docID uint32, mt matchTree, known map[matchTree]bool) []string {
539 var mask uint64
540 visitMatchAtoms(mt, known, func(mt matchTree) {
541 bq, ok := mt.(*branchQueryMatchTree)
542 if !ok {
543 return
544 }
545
546 mask = mask | bq.branchMask()
547 })
548
549 if mask == 0 {
550 mask = d.fileBranchMasks[docID]
551 }
552
553 var branches []string
554 id := uint32(1)
555 branchNames := d.branchNames[d.repos[docID]]
556 for mask != 0 {
557 if mask&0x1 != 0 {
558 branches = append(branches, branchNames[uint(id)])
559 }
560 id <<= 1
561 mask >>= 1
562 }
563
564 return branches
565}
566
567func (d *indexData) List(ctx context.Context, q query.Q, opts *ListOptions) (rl *RepoList, err error) {
568 var include func(rle *RepoListEntry) bool
569
570 q = d.simplify(q)
571 if c, ok := q.(*query.Const); ok {
572 if !c.Value {
573 return &RepoList{}, nil
574 }
575 include = func(rle *RepoListEntry) bool {
576 return true
577 }
578 } else {
579 sr, err := d.Search(ctx, q, &SearchOptions{
580 ShardRepoMaxMatchCount: 1,
581 })
582 if err != nil {
583 return nil, err
584 }
585
586 foundRepos := make(map[string]struct{}, len(sr.Files))
587 for _, file := range sr.Files {
588 foundRepos[file.Repository] = struct{}{}
589 }
590
591 include = func(rle *RepoListEntry) bool {
592 _, ok := foundRepos[rle.Repository.Name]
593 return ok
594 }
595 }
596
597 var l RepoList
598
599 field, err := opts.GetField()
600 if err != nil {
601 return nil, err
602 }
603 switch field {
604 case RepoListFieldRepos:
605 l.Repos = make([]*RepoListEntry, 0, len(d.repoListEntry))
606 case RepoListFieldReposMap:
607 l.ReposMap = make(ReposMap, len(d.repoListEntry))
608 }
609
610 for i := range d.repoListEntry {
611 if d.repoMetaData[i].Tombstone {
612 continue
613 }
614 rle := &d.repoListEntry[i]
615 if !include(rle) {
616 continue
617 }
618
619 l.Stats.Add(&rle.Stats)
620
621 // Backwards compat for when ID is missing
622 if rle.Repository.ID == 0 {
623 l.Repos = append(l.Repos, rle)
624 continue
625 }
626
627 switch field {
628 case RepoListFieldRepos:
629 l.Repos = append(l.Repos, rle)
630 case RepoListFieldReposMap:
631 l.ReposMap[rle.Repository.ID] = MinimalRepoListEntry{
632 HasSymbols: rle.Repository.HasSymbols,
633 Branches: rle.Repository.Branches,
634 IndexTimeUnix: rle.IndexMetadata.IndexTime.Unix(),
635 }
636 }
637
638 }
639
640 // Only one of these fields is populated and in all cases the size of that
641 // field is the number of Repos in this shard.
642 l.Stats.Repos = len(l.Repos) + len(l.ReposMap)
643
644 return &l, nil
645}
646
647// regexpToMatchTreeRecursive converts a regular expression to a matchTree mt. If
648// mt is equivalent to the input r, isEqual = true and the matchTree can be used
649// in place of the regex r. If singleLine = true, then the matchTree and all
650// its children only match terms on the same line. singleLine is used during
651// recursion to decide whether to return an andLineMatchTree (singleLine = true)
652// or a andMatchTree (singleLine = false).
653func (d *indexData) regexpToMatchTreeRecursive(r *syntax.Regexp, minTextSize int, fileName bool, caseSensitive bool) (mt matchTree, isEqual bool, singleLine bool, err error) {
654 // TODO - we could perhaps transform Begin/EndText in '\n'?
655 // TODO - we could perhaps transform CharClass in (OrQuery )
656 // if there are just a few runes, and part of a OpConcat?
657 switch r.Op {
658 case syntax.OpLiteral:
659 s := string(r.Rune)
660 if len(s) >= minTextSize {
661 mt, err := d.newSubstringMatchTree(&query.Substring{Pattern: s, FileName: fileName, CaseSensitive: caseSensitive})
662 return mt, true, !strings.Contains(s, "\n"), err
663 }
664 case syntax.OpCapture:
665 return d.regexpToMatchTreeRecursive(r.Sub[0], minTextSize, fileName, caseSensitive)
666
667 case syntax.OpPlus:
668 return d.regexpToMatchTreeRecursive(r.Sub[0], minTextSize, fileName, caseSensitive)
669
670 case syntax.OpRepeat:
671 if r.Min == 1 {
672 return d.regexpToMatchTreeRecursive(r.Sub[0], minTextSize, fileName, caseSensitive)
673 } else if r.Min > 1 {
674 // (x){2,} can't be expressed precisely by the matchTree
675 mt, _, singleLine, err := d.regexpToMatchTreeRecursive(r.Sub[0], minTextSize, fileName, caseSensitive)
676 return mt, false, singleLine, err
677 }
678 case syntax.OpConcat, syntax.OpAlternate:
679 var qs []matchTree
680 isEq := true
681 singleLine = true
682 for _, sr := range r.Sub {
683 if sq, subIsEq, subSingleLine, err := d.regexpToMatchTreeRecursive(sr, minTextSize, fileName, caseSensitive); sq != nil {
684 if err != nil {
685 return nil, false, false, err
686 }
687 isEq = isEq && subIsEq
688 singleLine = singleLine && subSingleLine
689 qs = append(qs, sq)
690 }
691 }
692 if r.Op == syntax.OpConcat {
693 if len(qs) > 1 {
694 isEq = false
695 }
696 newQs := make([]matchTree, 0, len(qs))
697 for _, q := range qs {
698 if _, ok := q.(*bruteForceMatchTree); ok {
699 continue
700 }
701 newQs = append(newQs, q)
702 }
703 if len(newQs) == 1 {
704 return newQs[0], isEq, singleLine, nil
705 }
706 if len(newQs) == 0 {
707 return &bruteForceMatchTree{}, isEq, singleLine, nil
708 }
709 if singleLine {
710 return &andLineMatchTree{andMatchTree{children: newQs}}, isEq, singleLine, nil
711 }
712 return &andMatchTree{newQs}, isEq, singleLine, nil
713 }
714 for _, q := range qs {
715 if _, ok := q.(*bruteForceMatchTree); ok {
716 return q, isEq, false, nil
717 }
718 }
719 if len(qs) == 0 {
720 return &noMatchTree{Why: "const"}, isEq, false, nil
721 }
722 return &orMatchTree{qs}, isEq, false, nil
723 case syntax.OpStar:
724 if r.Sub[0].Op == syntax.OpAnyCharNotNL {
725 return &bruteForceMatchTree{}, false, true, nil
726 }
727 }
728 return &bruteForceMatchTree{}, false, false, nil
729}
730
731type timer struct {
732 last time.Time
733}
734
735func newTimer() *timer {
736 return &timer{
737 last: time.Now(),
738 }
739}
740
741func (t *timer) Elapsed() time.Duration {
742 now := time.Now()
743 d := now.Sub(t.last)
744 t.last = now
745 return d
746}