kythe.io@v0.0.68-0.20240422202219-7225dbc01741/kythe/go/util/sortutil/sortutil.go (about) 1 /* 2 * Copyright 2015 The Kythe Authors. All rights reserved. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 // Package sortutil implements utilities for sorting. 18 package sortutil // import "kythe.io/kythe/go/util/sortutil" 19 20 import "sort" 21 22 // Lesser is an interface to a comparison function. 23 type Lesser interface { 24 // Less returns true if a < b. 25 Less(a, b any) bool 26 } 27 28 // Sort uses l to sort the given slice. 29 func Sort(l Lesser, a []any) { 30 sort.Sort(&ByLesser{ 31 Lesser: l, 32 Slice: a, 33 }) 34 } 35 36 // ByLesser implements the heap.Interface using a Lesser over a slice. 37 type ByLesser struct { 38 Lesser Lesser 39 Slice []any 40 } 41 42 // Clear removes all elements from the underlying slice. 43 func (s *ByLesser) Clear() { s.Slice = nil } 44 45 // Len implements part of the sort.Interface 46 func (s ByLesser) Len() int { return len(s.Slice) } 47 48 // Swap implements part of the sort.Interface 49 func (s ByLesser) Swap(i, j int) { s.Slice[i], s.Slice[j] = s.Slice[j], s.Slice[i] } 50 51 // Less implements part of the sort.Interface 52 func (s ByLesser) Less(i, j int) bool { return s.Lesser.Less(s.Slice[i], s.Slice[j]) } 53 54 // Push implements part of the heap.Interface 55 func (s *ByLesser) Push(v any) { s.Slice = append(s.Slice, v) } 56 57 // Pop implements part of the heap.Interface 58 func (s *ByLesser) Pop() any { 59 n := len(s.Slice) - 1 60 out := s.Slice[n] 61 s.Slice = s.Slice[:n] 62 return out 63 } 64 65 // Peek returns the least element in the heap. nil is returned if the heap is 66 // empty. 67 func (s ByLesser) Peek() any { 68 if len(s.Slice) == 0 { 69 return nil 70 } 71 return s.Slice[0] 72 } 73 74 // LesserFunc implements the Lesser interface using a function. 75 type LesserFunc func(a, b any) bool 76 77 // Less implements the Lesser interface. 78 func (f LesserFunc) Less(a, b any) bool { return f(a, b) }