...

Source file src/index/suffixarray/suffixarray.go

Documentation: index/suffixarray

     1  // Copyright 2010 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 suffixarray implements substring search in logarithmic time using
     6  // an in-memory suffix array.
     7  //
     8  // Example use:
     9  //
    10  //	// create index for some data
    11  //	index := suffixarray.New(data)
    12  //
    13  //	// lookup byte slice s
    14  //	offsets1 := index.Lookup(s, -1) // the list of all indices where s occurs in data
    15  //	offsets2 := index.Lookup(s, 3)  // the list of at most 3 indices where s occurs in data
    16  package suffixarray
    17  
    18  import (
    19  	"bytes"
    20  	"encoding/binary"
    21  	"errors"
    22  	"io"
    23  	"math"
    24  	"regexp"
    25  	"slices"
    26  	"sort"
    27  )
    28  
    29  // Can change for testing
    30  var maxData32 int = realMaxData32
    31  
    32  const realMaxData32 = math.MaxInt32
    33  
    34  // Index implements a suffix array for fast substring search.
    35  type Index struct {
    36  	data []byte
    37  	sa   ints // suffix array for data; sa.len() == len(data)
    38  }
    39  
    40  // An ints is either an []int32 or an []int64.
    41  // That is, one of them is empty, and one is the real data.
    42  // The int64 form is used when len(data) > maxData32
    43  type ints struct {
    44  	int32 []int32
    45  	int64 []int64
    46  }
    47  
    48  func (a *ints) len() int {
    49  	return len(a.int32) + len(a.int64)
    50  }
    51  
    52  func (a *ints) get(i int) int64 {
    53  	if a.int32 != nil {
    54  		return int64(a.int32[i])
    55  	}
    56  	return a.int64[i]
    57  }
    58  
    59  func (a *ints) set(i int, v int64) {
    60  	if a.int32 != nil {
    61  		a.int32[i] = int32(v)
    62  	} else {
    63  		a.int64[i] = v
    64  	}
    65  }
    66  
    67  func (a *ints) slice(i, j int) ints {
    68  	if a.int32 != nil {
    69  		return ints{a.int32[i:j], nil}
    70  	}
    71  	return ints{nil, a.int64[i:j]}
    72  }
    73  
    74  // New creates a new [Index] for data.
    75  // [Index] creation time is O(N) for N = len(data).
    76  func New(data []byte) *Index {
    77  	ix := &Index{data: data}
    78  	if len(data) <= maxData32 {
    79  		ix.sa.int32 = make([]int32, len(data))
    80  		text_32(data, ix.sa.int32)
    81  	} else {
    82  		ix.sa.int64 = make([]int64, len(data))
    83  		text_64(data, ix.sa.int64)
    84  	}
    85  	return ix
    86  }
    87  
    88  // writeInt writes an int x to w using buf to buffer the write.
    89  func writeInt(w io.Writer, buf []byte, x int) error {
    90  	binary.PutVarint(buf, int64(x))
    91  	_, err := w.Write(buf[0:binary.MaxVarintLen64])
    92  	return err
    93  }
    94  
    95  // readInt reads an int x from r using buf to buffer the read and returns x.
    96  func readInt(r io.Reader, buf []byte) (int64, error) {
    97  	_, err := io.ReadFull(r, buf[0:binary.MaxVarintLen64]) // ok to continue with error
    98  	x, _ := binary.Varint(buf)
    99  	return x, err
   100  }
   101  
   102  // writeSlice writes data[:n] to w and returns n.
   103  // It uses buf to buffer the write.
   104  func writeSlice(w io.Writer, buf []byte, data ints) (n int, err error) {
   105  	// encode as many elements as fit into buf
   106  	p := binary.MaxVarintLen64
   107  	m := data.len()
   108  	for ; n < m && p+binary.MaxVarintLen64 <= len(buf); n++ {
   109  		p += binary.PutUvarint(buf[p:], uint64(data.get(n)))
   110  	}
   111  
   112  	// update buffer size
   113  	binary.PutVarint(buf, int64(p))
   114  
   115  	// write buffer
   116  	_, err = w.Write(buf[0:p])
   117  	return
   118  }
   119  
   120  var errCorrupted = errors.New("suffixarray: data corrupted")
   121  
   122  // readSlice reads data[:n] from r and returns n; maxIndex is the length of the suffix array.
   123  // It uses buf to buffer the read.
   124  func readSlice(r io.Reader, buf []byte, data ints, maxIndex uint64) (n int, err error) {
   125  	// read buffer size
   126  	var size64 int64
   127  	size64, err = readInt(r, buf)
   128  	if err != nil {
   129  		return
   130  	}
   131  	if int64(int(size64)) != size64 || int(size64) < 0 {
   132  		// We never write chunks this big anyway.
   133  		return 0, errCorrupted
   134  	}
   135  	size := int(size64)
   136  
   137  	// read buffer w/o the size
   138  	if _, err = io.ReadFull(r, buf[binary.MaxVarintLen64:size]); err != nil {
   139  		return
   140  	}
   141  
   142  	// decode as many elements as present in buf
   143  	len := data.len()
   144  	for p := binary.MaxVarintLen64; p < size; n++ {
   145  		x, w := binary.Uvarint(buf[p:])
   146  		// - prevent index-out-of-bounds panic if there are more indices than expected
   147  		// (was go.dev/issue/53352)
   148  		// - prevent index-out-of-bounds panic in a future Lookup
   149  		// by ensuring all indices x satisfy x < maxIndex
   150  		if n >= len || x >= maxIndex {
   151  			return n, errCorrupted
   152  		}
   153  		data.set(n, int64(x))
   154  		p += w
   155  	}
   156  
   157  	return
   158  }
   159  
   160  const bufSize = 16 << 10 // reasonable for BenchmarkSaveRestore
   161  
   162  // Read reads the index from r into x; x must not be nil.
   163  func (x *Index) Read(r io.Reader) error {
   164  	// buffer for all reads
   165  	buf := make([]byte, bufSize)
   166  
   167  	// read length
   168  	n64, err := readInt(r, buf)
   169  	if err != nil {
   170  		return err
   171  	}
   172  	if int64(int(n64)) != n64 || int(n64) < 0 {
   173  		return errCorrupted
   174  	}
   175  	n := int(n64)
   176  
   177  	// allocate space
   178  	if 2*n < cap(x.data) || cap(x.data) < n || x.sa.int32 != nil && n > maxData32 || x.sa.int64 != nil && n <= maxData32 {
   179  		// new data is significantly smaller or larger than
   180  		// existing buffers - allocate new ones
   181  		x.data = make([]byte, n)
   182  		x.sa.int32 = nil
   183  		x.sa.int64 = nil
   184  		if n <= maxData32 {
   185  			x.sa.int32 = make([]int32, n)
   186  		} else {
   187  			x.sa.int64 = make([]int64, n)
   188  		}
   189  	} else {
   190  		// re-use existing buffers
   191  		x.data = x.data[0:n]
   192  		x.sa = x.sa.slice(0, n)
   193  	}
   194  
   195  	// read data
   196  	if _, err := io.ReadFull(r, x.data); err != nil {
   197  		return err
   198  	}
   199  
   200  	// read index
   201  	sa := x.sa
   202  	for sa.len() > 0 {
   203  		n, err := readSlice(r, buf, sa, uint64(n))
   204  		if err != nil {
   205  			return err
   206  		}
   207  		sa = sa.slice(n, sa.len())
   208  	}
   209  	return nil
   210  }
   211  
   212  // Write writes the index x to w.
   213  func (x *Index) Write(w io.Writer) error {
   214  	// buffer for all writes
   215  	buf := make([]byte, bufSize)
   216  
   217  	// write length
   218  	if err := writeInt(w, buf, len(x.data)); err != nil {
   219  		return err
   220  	}
   221  
   222  	// write data
   223  	if _, err := w.Write(x.data); err != nil {
   224  		return err
   225  	}
   226  
   227  	// write index
   228  	sa := x.sa
   229  	for sa.len() > 0 {
   230  		n, err := writeSlice(w, buf, sa)
   231  		if err != nil {
   232  			return err
   233  		}
   234  		sa = sa.slice(n, sa.len())
   235  	}
   236  	return nil
   237  }
   238  
   239  // Bytes returns the data over which the index was created.
   240  // It must not be modified.
   241  func (x *Index) Bytes() []byte {
   242  	return x.data
   243  }
   244  
   245  func (x *Index) at(i int) []byte {
   246  	return x.data[x.sa.get(i):]
   247  }
   248  
   249  // lookupAll returns a slice into the matching region of the index.
   250  // The runtime is O(log(N)*len(s)).
   251  func (x *Index) lookupAll(s []byte) ints {
   252  	// find matching suffix index range [i:j]
   253  	// find the first index where s would be the prefix
   254  	i := sort.Search(x.sa.len(), func(i int) bool { return bytes.Compare(x.at(i), s) >= 0 })
   255  	// starting at i, find the first index at which s is not a prefix
   256  	j := i + sort.Search(x.sa.len()-i, func(j int) bool { return !bytes.HasPrefix(x.at(j+i), s) })
   257  	return x.sa.slice(i, j)
   258  }
   259  
   260  // Lookup returns an unsorted list of at most n indices where the byte string s
   261  // occurs in the indexed data. If n < 0, all occurrences are returned.
   262  // The result is nil if s is empty, s is not found, or n == 0.
   263  // Lookup time is O(log(N)*len(s) + len(result)) where N is the
   264  // size of the indexed data.
   265  func (x *Index) Lookup(s []byte, n int) (result []int) {
   266  	if len(s) > 0 && n != 0 {
   267  		matches := x.lookupAll(s)
   268  		count := matches.len()
   269  		if n < 0 || count < n {
   270  			n = count
   271  		}
   272  		// 0 <= n <= count
   273  		if n > 0 {
   274  			result = make([]int, n)
   275  			if matches.int32 != nil {
   276  				for i := range result {
   277  					result[i] = int(matches.int32[i])
   278  				}
   279  			} else {
   280  				for i := range result {
   281  					result[i] = int(matches.int64[i])
   282  				}
   283  			}
   284  		}
   285  	}
   286  	return
   287  }
   288  
   289  // FindAllIndex returns a sorted list of non-overlapping matches of the
   290  // regular expression r, where a match is a pair of indices specifying
   291  // the matched slice of x.Bytes(). If n < 0, all matches are returned
   292  // in successive order. Otherwise, at most n matches are returned and
   293  // they may not be successive. The result is nil if there are no matches,
   294  // or if n == 0.
   295  func (x *Index) FindAllIndex(r *regexp.Regexp, n int) (result [][]int) {
   296  	// a non-empty literal prefix is used to determine possible
   297  	// match start indices with Lookup
   298  	prefix, complete := r.LiteralPrefix()
   299  	lit := []byte(prefix)
   300  
   301  	// worst-case scenario: no literal prefix
   302  	if prefix == "" {
   303  		return r.FindAllIndex(x.data, n)
   304  	}
   305  
   306  	// if regexp is a literal just use Lookup and convert its
   307  	// result into match pairs
   308  	if complete {
   309  		// Lookup returns indices that may belong to overlapping matches.
   310  		// After eliminating them, we may end up with fewer than n matches.
   311  		// If we don't have enough at the end, redo the search with an
   312  		// increased value n1, but only if Lookup returned all the requested
   313  		// indices in the first place (if it returned fewer than that then
   314  		// there cannot be more).
   315  		for n1 := n; ; n1 += 2 * (n - len(result)) /* overflow ok */ {
   316  			indices := x.Lookup(lit, n1)
   317  			if len(indices) == 0 {
   318  				return
   319  			}
   320  			slices.Sort(indices)
   321  			pairs := make([]int, 2*len(indices))
   322  			result = make([][]int, len(indices))
   323  			count := 0
   324  			prev := 0
   325  			for _, i := range indices {
   326  				if count == n {
   327  					break
   328  				}
   329  				// ignore indices leading to overlapping matches
   330  				if prev <= i {
   331  					j := 2 * count
   332  					pairs[j+0] = i
   333  					pairs[j+1] = i + len(lit)
   334  					result[count] = pairs[j : j+2]
   335  					count++
   336  					prev = i + len(lit)
   337  				}
   338  			}
   339  			result = result[0:count]
   340  			if len(result) >= n || len(indices) != n1 {
   341  				// found all matches or there's no chance to find more
   342  				// (n and n1 can be negative)
   343  				break
   344  			}
   345  		}
   346  		if len(result) == 0 {
   347  			result = nil
   348  		}
   349  		return
   350  	}
   351  
   352  	// regexp has a non-empty literal prefix; Lookup(lit) computes
   353  	// the indices of possible complete matches; use these as starting
   354  	// points for anchored searches
   355  	// (regexp "^" matches beginning of input, not beginning of line)
   356  	r = regexp.MustCompile("^" + r.String()) // compiles because r compiled
   357  
   358  	// same comment about Lookup applies here as in the loop above
   359  	for n1 := n; ; n1 += 2 * (n - len(result)) /* overflow ok */ {
   360  		indices := x.Lookup(lit, n1)
   361  		if len(indices) == 0 {
   362  			return
   363  		}
   364  		slices.Sort(indices)
   365  		result = result[0:0]
   366  		prev := 0
   367  		for _, i := range indices {
   368  			if len(result) == n {
   369  				break
   370  			}
   371  			m := r.FindIndex(x.data[i:]) // anchored search - will not run off
   372  			// ignore indices leading to overlapping matches
   373  			if m != nil && prev <= i {
   374  				m[0] = i // correct m
   375  				m[1] += i
   376  				result = append(result, m)
   377  				prev = m[1]
   378  			}
   379  		}
   380  		if len(result) >= n || len(indices) != n1 {
   381  			// found all matches or there's no chance to find more
   382  			// (n and n1 can be negative)
   383  			break
   384  		}
   385  	}
   386  	if len(result) == 0 {
   387  		result = nil
   388  	}
   389  	return
   390  }
   391  

View as plain text