| 1 |
// Copyright (c) 2018-2026, Maxime Soulé |
| 2 |
// All rights reserved. |
| 3 |
// |
| 4 |
// This source code is licensed under the BSD-style license found in the |
| 5 |
// LICENSE file in the root directory of this source tree. |
| 6 |
|
| 7 |
package util |
| 8 |
|
| 9 |
import ( |
| 10 |
"fmt" |
| 11 |
"reflect" |
| 12 |
"strings" |
| 13 |
) |
| 14 |
|
| 15 |
// BadParam returns a string noticing a misuse of a function parameter. |
| 16 |
// |
| 17 |
// If kind and param's kind name ≠ param's type name: |
| 18 |
// |
| 19 |
// but received {param type} ({param kind}) as {pos}th parameter |
| 20 |
// |
| 21 |
// else |
| 22 |
// |
| 23 |
// but received {param type} as {pos}th parameter |
| 24 |
func BadParam(param any, pos int, kind bool) string { |
| 25 |
var b strings.Builder |
| 26 |
b.WriteString("but received ") |
| 27 |
|
| 28 |
if param == nil { |
| 29 |
b.WriteString("nil") |
| 30 |
} else { |
| 31 |
t := reflect.TypeOf(param) |
| 32 |
if kind && t.String() != t.Kind().String() { |
| 33 |
fmt.Fprintf(&b, "%s (%s)", t, t.Kind()) |
| 34 |
} else { |
| 35 |
b.WriteString(t.String()) |
| 36 |
} |
| 37 |
} |
| 38 |
asNthParam(&b, pos) |
| 39 |
return b.String() |
| 40 |
} |
| 41 |
|
| 42 |
// AsNthParam returns a string like: |
| 43 |
// |
| 44 |
// " as {pos}th parameter" |
| 45 |
// |
| 46 |
// handling 1st, 2nd and 3rd. |
| 47 |
func AsNthParam(pos int) string { |
| 48 |
var b strings.Builder |
| 49 |
asNthParam(&b, pos) |
| 50 |
return b.String() |
| 51 |
} |
| 52 |
|
| 53 |
func asNthParam(b *strings.Builder, pos int) { |
| 54 |
b.WriteString(" as ") |
| 55 |
switch pos { |
| 56 |
case 1: |
| 57 |
b.WriteString("1st") |
| 58 |
case 2: |
| 59 |
b.WriteString("2nd") |
| 60 |
case 3: |
| 61 |
b.WriteString("3rd") |
| 62 |
default: |
| 63 |
fmt.Fprintf(b, "%dth", pos) |
| 64 |
} |
| 65 |
b.WriteString(" parameter") |
| 66 |
} |
| 67 |
|
| 68 |
// TernRune returns a if cond is true, b otherwise. |
| 69 |
func TernRune(cond bool, a, b rune) rune { |
| 70 |
if cond { |
| 71 |
return a |
| 72 |
} |
| 73 |
return b |
| 74 |
} |