github.com/primecitizens/pcz/std@v0.2.1/core/cmp/slice.go (about) 1 // SPDX-License-Identifier: Apache-2.0 2 // Copyright 2023 The Prime Citizens 3 // 4 // Copyright 2021 The Go Authors. All rights reserved. 5 // Use of this source code is governed by a BSD-style 6 // license that can be found in the LICENSE file. 7 8 package cmp 9 10 import ( 11 "github.com/primecitizens/pcz/std/core/mark" 12 ) 13 14 type Context[T any] struct { 15 A, B T 16 } 17 18 // Compare compares the elements of a and b, using cmp on each pair 19 // of elements. The elements are compared sequentially, starting at index 0, 20 // until one element is not equal to the other. 21 // 22 // The result of comparing the first non-matching elements is returned. 23 // If both slices are equal until one of them ends, the shorter slice is 24 // considered less than the longer one. 25 // The result is 0 if a == b, -1 if a < b, and +1 if a > b. 26 func Slice[E any](a, b []E, cmp func(ctx *Context[[]E], i int) int) int { 27 ctx := Context[[]E]{ 28 A: a, 29 B: b, 30 } 31 32 for i := 0; i < len(a); i++ { 33 if i >= len(b) { 34 return +1 35 } 36 if c := cmp(mark.NoEscape(&ctx), i); c != 0 { 37 return c 38 } 39 } 40 if len(a) < len(b) { 41 return -1 42 } 43 return 0 44 } 45 46 // SliceEx is like [Slice], but takes an extra arg. 47 func SliceEx[E, T any](a, b []E, arg T, cmp func(arg T, ctx *Context[[]E], i int) int) int { 48 ctx := Context[[]E]{ 49 A: a, 50 B: b, 51 } 52 53 for i := 0; i < len(a); i++ { 54 if i >= len(b) { 55 return +1 56 } 57 if c := cmp(arg, mark.NoEscape(&ctx), i); c != 0 { 58 return c 59 } 60 } 61 if len(a) < len(b) { 62 return -1 63 } 64 65 return 0 66 }