File: utils.go

package info (click to toggle)
golang-github-gcla-gowid 1.4.0-1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 1,456 kB
  • sloc: makefile: 4
file content (387 lines) | stat: -rw-r--r-- 7,895 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
// Copyright 2019-2022 Graham Clark. All rights reserved.  Use of this source code is governed by the MIT license
// that can be found in the LICENSE file.

// Package gwutil provides general-purpose utilities that are not used by
// the core of gowid but that have proved useful for several pre-canned
// widgets.
package gwutil

import (
	"errors"
	"fmt"
	"math"
	"os"
	"runtime/pprof"
	"sort"

	log "github.com/sirupsen/logrus"
)

//======================================================================

// Min returns the smaller of >1 integer arguments.
func Min(i int, js ...int) int {
	res := i
	for _, j := range js {
		if j < res {
			res = j
		}
	}
	return res
}

// Min returns the larger of >1 integer arguments.
func Max(i int, js ...int) int {
	res := i
	for _, j := range js {
		if j > res {
			res = j
		}
	}
	return res
}

// LimitTo is a one-liner that uses Min and Max to bound a value. Assumes
// a <= b.
func LimitTo(a, v, b int) int {
	if v < a {
		return a
	}
	if v > b {
		return b
	}
	return v
}

// StringOfLength returns a string consisting of n runes.
func StringOfLength(r rune, n int) string {
	res := make([]rune, n)
	for i := 0; i < n; i++ {
		res[i] = r
	}
	return string(res)
}

// Map is the traditional functional map function for strings.
func Map(vs []string, f func(string) string) []string {
	vsm := make([]string, len(vs))
	for i, v := range vs {
		vsm[i] = f(v)
	}
	return vsm
}

// IPow returns a raised to the bth power.
func IPow(a, b int) int {
	var result int = 1

	for 0 != b {
		if 0 != (b & 1) {
			result *= a
		}
		b >>= 1
		a *= a
	}

	return result
}

// Sum is a variadic function that returns the sum of its integer arguments.
func Sum(input ...int) int {
	sum := 0
	for i := range input {
		sum += input[i]
	}
	return sum
}

//======================================================================

type fract struct {
	fp  float64
	idx int
}

type fractlist []fract

func (slice fractlist) Len() int {
	return len(slice)
}

// Note > to skip the reverse
func (slice fractlist) Less(i, j int) bool {
	return slice[i].fp > slice[j].fp
}

func (slice fractlist) Swap(i, j int) {
	slice[i], slice[j] = slice[j], slice[i]
}

// HamiltonAllocation implements the Hamilton Method (Largest remainder method) to calculate
// integral ratios. (Like it is used in some elections.)
//
// This is shamelessly cribbed from https://excess.org/svn/urwid/contrib/trunk/rbreu_scrollbar.py
//
// counts -- list of integers ('votes per party')
// alloc -- total amount to be allocated ('total amount of seats')
//
func HamiltonAllocation(counts []int, alloc int) []int {

	totalCounts := Sum(counts...)

	if totalCounts == 0 {
		return counts
	}

	res := make([]int, len(counts))
	quotas := make([]float64, len(counts))
	fracts := fractlist(make([]fract, len(counts)))

	for i, c := range counts {
		quotas[i] = (float64(c) * float64(alloc)) / float64(totalCounts)
	}

	for i, fp := range quotas {
		_, f := math.Modf(fp)
		fracts[i] = fract{fp: f, idx: i}
	}

	sort.Sort(fracts)

	for i, fp := range quotas {
		n, _ := math.Modf(fp)
		res[i] = int(n)
	}

	remainder := alloc - Sum(res...)

	for i := 0; i < remainder; i++ {
		res[fracts[i].idx] += 1
	}

	return res
}

//======================================================================

// LStripByte returns a slice of its first argument which contains all
// bytes up to but not including its second argument.
func LStripByte(data []byte, s byte) []byte {
	var i int
	for i = 0; i < len(data); i++ {
		if data[i] != s {
			break
		}
	}
	return data[i:]
}

//======================================================================

type IOption interface {
	IsNone() bool
	Value() interface{}
}

// For fmt.Stringer
func OptionString(opt IOption) string {
	if opt.IsNone() {
		return "None"
	} else {
		return fmt.Sprintf("%v", opt.Value())
	}
}

//======================================================================

// IntOption is intended to represent an Option[int]
type IntOption struct {
	some bool
	val  int
}

var _ fmt.Stringer = IntOption{}
var _ IOption = IntOption{}

func SomeInt(x int) IntOption {
	return IntOption{true, x}
}

func NoneInt() IntOption {
	return IntOption{}
}

func (i IntOption) IsNone() bool {
	return !i.some
}

func (i IntOption) Value() interface{} {
	return i.Val()
}

func (i IntOption) Val() int {
	if i.IsNone() {
		panic(errors.New("Called Val on empty IntOption"))
	}
	return i.val
}

// For fmt.Stringer
func (i IntOption) String() string {
	return OptionString(i)
}

//======================================================================

// Int64Option is intended to represent an Option[int]
type Int64Option struct {
	some bool
	val  int64
}

var _ fmt.Stringer = Int64Option{}
var _ IOption = Int64Option{}

func SomeInt64(x int64) Int64Option {
	return Int64Option{true, x}
}

func NoneInt64() Int64Option {
	return Int64Option{}
}

func (i Int64Option) IsNone() bool {
	return !i.some
}

func (i Int64Option) Value() interface{} {
	return i.Val()
}

func (i Int64Option) Val() int64 {
	if i.IsNone() {
		panic(errors.New("Called Val on empty Int64Option"))
	}
	return i.val
}

// For fmt.Stringer
func (i Int64Option) String() string {
	return OptionString(i)
}

//======================================================================

// RuneOption is intended to represent an Option[rune]
type RuneOption struct {
	some bool
	val  rune
}

var _ fmt.Stringer = RuneOption{}
var _ IOption = RuneOption{}

func SomeRune(x rune) RuneOption {
	return RuneOption{true, x}
}

func NoneRune() RuneOption {
	return RuneOption{}
}

func (i RuneOption) IsNone() bool {
	return !i.some
}

func (i RuneOption) Value() interface{} {
	return i.Val()
}

func (i RuneOption) Val() rune {
	if i.IsNone() {
		panic(errors.New("Called Val on empty ByteOption"))
	}
	return i.val
}

func (i RuneOption) String() string {
	return OptionString(i)
}

//======================================================================

const float64EqualityThreshold = 1e-5

// AlmostEqual returns true if its two arguments are within 1e-5 of each other.
func AlmostEqual(a, b float64) bool {
	return math.Abs(a-b) <= float64EqualityThreshold
}

// Round returns a float64 representing the closest whole number
// to the supplied float64 argument.
func Round(f float64) float64 {
	if f < 0 {
		return math.Ceil(f - 0.5)
	} else {
		return math.Floor(f + 0.5)
	}
}

// RoundFloatToInt returns an int representing the closest int to the
// supplied float, rounding up or down.
func RoundFloatToInt(val float32) int {
	if val < 0 {
		return int(val - 0.5)
	}
	return int(val + 0.5)
}

//======================================================================

// If is a convenience function for mimicking a ternary operator e.g. If(x<y, x, y).(int)
func If(statement bool, a, b interface{}) interface{} {
	if statement {
		return a
	}
	return b
}

//======================================================================

// StartProfilingCPU is a function I used when debugging and optimizing gowid. It starts
// the Go-profiler with output going to the specified file.
func StartProfilingCPU(filename string) {
	f, err := os.Create(filename)
	if err != nil {
		log.Fatal(err)
	}
	if err = pprof.StartCPUProfile(f); err != nil {
		panic(err)
	}
}

// StopProfilingCPU will stop the CPU profiler.
func StopProfilingCPU() {
	pprof.StopCPUProfile()
}

//======================================================================

// ProfileHeap is a function I used when debugging and optimizing gowid. It
// writes a Go-heap-profile to the filename specified.
func ProfileHeap(filename string) {
	f, err := os.Create(filename)
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()
	if err = pprof.WriteHeapProfile(f); err != nil {
		panic(err)
	}
}

//======================================================================
// Local Variables:
// mode: Go
// fill-column: 110
// End: