github.com/thanos-io/thanos@v0.32.5/pkg/strutil/merge.go (about)

     1  // Copyright (c) The Thanos Authors.
     2  // Licensed under the Apache License 2.0.
     3  
     4  package strutil
     5  
     6  import (
     7  	"sort"
     8  	"strings"
     9  )
    10  
    11  // MergeSlices merges a set of sorted string slices into a single ones
    12  // while removing all duplicates.
    13  func MergeSlices(a ...[]string) []string {
    14  	if len(a) == 0 {
    15  		return nil
    16  	}
    17  	if len(a) == 1 {
    18  		return a[0]
    19  	}
    20  	l := len(a) / 2
    21  	return mergeTwoStringSlices(MergeSlices(a[:l]...), MergeSlices(a[l:]...))
    22  }
    23  
    24  // MergeUnsortedSlices behaves like StringSlices but input slices are validated
    25  // for sortedness and are sorted if they are not ordered yet.
    26  func MergeUnsortedSlices(a ...[]string) []string {
    27  	for _, s := range a {
    28  		if !sort.StringsAreSorted(s) {
    29  			sort.Strings(s)
    30  		}
    31  	}
    32  	return MergeSlices(a...)
    33  }
    34  
    35  func mergeTwoStringSlices(a, b []string) []string {
    36  	maxl := len(a)
    37  	if len(b) > len(a) {
    38  		maxl = len(b)
    39  	}
    40  	res := make([]string, 0, maxl*10/9)
    41  
    42  	for len(a) > 0 && len(b) > 0 {
    43  		d := strings.Compare(a[0], b[0])
    44  
    45  		if d == 0 {
    46  			res = append(res, a[0])
    47  			a, b = a[1:], b[1:]
    48  		} else if d < 0 {
    49  			res = append(res, a[0])
    50  			a = a[1:]
    51  		} else if d > 0 {
    52  			res = append(res, b[0])
    53  			b = b[1:]
    54  		}
    55  	}
    56  	// Append all remaining elements.
    57  	res = append(res, a...)
    58  	res = append(res, b...)
    59  	return res
    60  }