-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathptr.go
More file actions
636 lines (566 loc) · 15.5 KB
/
ptr.go
File metadata and controls
636 lines (566 loc) · 15.5 KB
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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
// Package ptr provides helper functions to create and safely dereference pointers.
//
// This package solves common Go problems with pointers:
// - Go doesn't allow taking the address of literals: &"hello" is invalid
// - Dereferencing nil pointers causes panics
// - Working with optional fields in structs and JSON requires verbose code
//
// The package provides both generic functions that work with any type using Go 1.18+
// generics, and type-specific convenience functions for common types (string, int, bool, etc.)
// for better IDE autocomplete and ergonomics.
//
// Basic usage:
//
// // Create pointers easily
// name := ptr.String("Alice")
// age := ptr.Int(30)
//
// // Safely dereference with zero-value fallback
// fmt.Println(ptr.ToString(name)) // "Alice"
// fmt.Println(ptr.ToInt(nil)) // 0
//
// // Generic functions work with any type
// user := ptr.To(User{Name: "Bob", Age: 25})
// fmt.Println(ptr.From(user))
package ptr
import "time"
// To returns a pointer to the provided value.
// This is useful for creating pointers to literals or values in a single expression.
//
// Example:
//
// s := ptr.To("hello") // *string
// i := ptr.To(42) // *int
func To[T any](v T) *T {
return &v
}
// From dereferences the pointer and returns its value.
// If the pointer is nil, it returns the zero value of type T.
//
// Example:
//
// s := ptr.To("hello")
// v := ptr.From(s) // "hello"
// v = ptr.From[string](nil) // ""
func From[T any](p *T) T {
if p == nil {
var zero T
return zero
}
return *p
}
// FromOr dereferences the pointer and returns its value.
// If the pointer is nil, it returns the provided default value.
//
// Example:
//
// s := ptr.To("hello")
// v := ptr.FromOr(s, "default") // "hello"
// v = ptr.FromOr[string](nil, "default") // "default"
func FromOr[T any](p *T, defaultValue T) T {
if p == nil {
return defaultValue
}
return *p
}
// Equal returns true if both pointers point to equal values.
// Returns true if both pointers are nil.
// Returns false if only one pointer is nil.
//
// Example:
//
// a := ptr.To(42)
// b := ptr.To(42)
// ptr.Equal(a, b) // true
// ptr.Equal[int](nil, nil) // true
func Equal[T comparable](a, b *T) bool {
if a == nil && b == nil {
return true
}
if a == nil || b == nil {
return false
}
return *a == *b
}
// Copy creates a new pointer with a shallow copy of the value.
// For types containing pointers, slices, or maps, only the top-level
// value is copied; nested pointers still reference the same memory.
// Returns nil if the input pointer is nil.
//
// Example:
//
// original := ptr.To(42)
// copy := ptr.Copy(original)
// // copy points to a different memory location
func Copy[T any](p *T) *T {
if p == nil {
return nil
}
v := *p
return &v
}
// IsNil returns true if the pointer is nil.
//
// Example:
//
// s := ptr.To("hello")
// ptr.IsNil(s) // false
// ptr.IsNil[string](nil) // true
func IsNil[T any](p *T) bool {
return p == nil
}
// MustFrom dereferences the pointer and returns its value.
// Panics if the pointer is nil. Use this only when nil is a programming error.
//
// Example:
//
// s := ptr.To("hello")
// v := ptr.MustFrom(s) // "hello"
// v = ptr.MustFrom[string](nil) // panics
func MustFrom[T any](p *T) T {
if p == nil {
panic("ptr: nil pointer passed to MustFrom")
}
return *p
}
// Coalesce returns the first non-nil pointer from the provided list.
// Returns nil if all pointers are nil.
//
// Example:
//
// a := ptr.Coalesce(nil, nil, ptr.To(42), ptr.To(100)) // returns pointer to 42
// b := ptr.Coalesce[int](nil, nil) // returns nil
func Coalesce[T any](ptrs ...*T) *T {
for _, p := range ptrs {
if p != nil {
return p
}
}
return nil
}
// Set sets the value of the pointer. If the pointer is nil, it's a no-op.
// Returns true if the value was set, false if the pointer was nil.
//
// Example:
//
// p := ptr.To(42)
// ptr.Set(p, 100) // *p is now 100, returns true
// ptr.Set[int](nil, 100) // returns false
func Set[T any](p *T, value T) bool {
if p == nil {
return false
}
*p = value
return true
}
// Map applies a transformation function to the pointer value.
// Returns nil if the input pointer is nil.
//
// Example:
//
// s := ptr.To("hello")
// length := ptr.Map(s, func(s string) int { return len(s) }) // pointer to 5
// ptr.Map[string, int](nil, func(s string) int { return len(s) }) // nil
func Map[T, R any](p *T, fn func(T) R) *R {
if p == nil {
return nil
}
result := fn(*p)
return &result
}
// Or returns the first pointer if not nil, otherwise returns the second.
// More ergonomic than Coalesce for the common two-pointer case.
//
// Example:
//
// primary := ptr.To(42)
// fallback := ptr.To(100)
// v := ptr.Or(primary, fallback) // returns primary
// v = ptr.Or[int](nil, fallback) // returns fallback
func Or[T any](a, b *T) *T {
if a != nil {
return a
}
return b
}
// Filter returns the pointer if the predicate is true, otherwise returns nil.
// If the pointer is nil, returns nil without calling the predicate.
//
// Example:
//
// p := ptr.To(42)
// result := ptr.Filter(p, func(v int) bool { return v > 40 }) // returns p
// result = ptr.Filter(p, func(v int) bool { return v > 50 }) // returns nil
func Filter[T any](p *T, predicate func(T) bool) *T {
if p == nil || !predicate(*p) {
return nil
}
return p
}
// FlatMap applies a transformation function that returns a pointer.
// Returns nil if the input pointer is nil or if the function returns nil.
// Useful for chaining operations that might return nil.
//
// Example:
//
// s := ptr.To("42")
// result := ptr.FlatMap(s, func(s string) *int {
// if v, err := strconv.Atoi(s); err == nil {
// return ptr.To(v)
// }
// return nil
// })
func FlatMap[T, R any](p *T, fn func(T) *R) *R {
if p == nil {
return nil
}
return fn(*p)
}
// Apply executes the function if the pointer is not nil.
// Returns true if the function was executed, false if pointer was nil.
//
// Example:
//
// p := ptr.To("hello")
// executed := ptr.Apply(p, func(s string) {
// fmt.Println(s)
// }) // prints "hello", returns true
func Apply[T any](p *T, fn func(T)) bool {
if p == nil {
return false
}
fn(*p)
return true
}
// Modify applies a transformation function to the pointer value in place.
// Returns true if modified, false if pointer was nil.
//
// Example:
//
// p := ptr.To(5)
// ptr.Modify(p, func(v int) int { return v * 2 }) // *p is now 10
func Modify[T any](p *T, fn func(T) T) bool {
if p == nil {
return false
}
*p = fn(*p)
return true
}
// NonZero returns a pointer to the value if it's not the zero value,
// otherwise returns nil. Useful for omitting zero values in JSON/APIs.
//
// Example:
//
// p := ptr.NonZero(42) // returns pointer to 42
// p = ptr.NonZero(0) // returns nil
// p = ptr.NonZero("") // returns nil
func NonZero[T comparable](v T) *T {
var zero T
if v == zero {
return nil
}
return &v
}
// IsZero returns true if the pointer is nil or points to a zero value.
//
// Example:
//
// ptr.IsZero(ptr.To(0)) // true
// ptr.IsZero(ptr.To(42)) // false
// ptr.IsZero[int](nil) // true
func IsZero[T comparable](p *T) bool {
if p == nil {
return true
}
var zero T
return *p == zero
}
// Swap exchanges the values of two pointers.
// Does nothing if either pointer is nil.
//
// Example:
//
// a := ptr.To(1)
// b := ptr.To(2)
// ptr.Swap(a, b) // *a is now 2, *b is now 1
func Swap[T any](a, b *T) {
if a == nil || b == nil {
return
}
*a, *b = *b, *a
}
// Bind applies a function that transforms a pointer to another pointer.
// This is an alias for FlatMap, provided for developers familiar with monadic bind operations.
// Returns nil if the input pointer is nil or if the function returns nil.
//
// Example:
//
// parseToInt := func(s string) *int {
// if v, err := strconv.Atoi(s); err == nil {
// return ptr.To(v)
// }
// return nil
// }
// result := ptr.Bind(ptr.To("42"), parseToInt) // returns pointer to 42
func Bind[T, R any](p *T, fn func(T) *R) *R {
return FlatMap(p, fn)
}
// GetOr returns the value if pointer is non-nil, otherwise returns the default value.
// This is an alias for FromOr with a more intuitive name for configuration use cases.
//
// Example:
//
// timeout := ptr.GetOr(config.Timeout, 30*time.Second)
// maxRetries := ptr.GetOr(config.MaxRetries, 3)
func GetOr[T any](p *T, defaultValue T) T {
return FromOr(p, defaultValue)
}
// ToSlice converts a slice of values to a slice of pointers.
// Returns nil if the input slice is nil.
//
// Example:
//
// values := []int{1, 2, 3}
// ptrs := ptr.ToSlice(values) // []*int with pointers to 1, 2, 3
func ToSlice[T any](values []T) []*T {
if values == nil {
return nil
}
result := make([]*T, len(values))
for i := range values {
result[i] = &values[i]
}
return result
}
// FromSlice converts a slice of pointers to a slice of values.
// Nil pointers are converted to zero values.
// Returns nil if the input slice is nil.
//
// Example:
//
// ptrs := []*int{ptr.To(1), nil, ptr.To(3)}
// values := ptr.FromSlice(ptrs) // []int{1, 0, 3}
func FromSlice[T any](ptrs []*T) []T {
if ptrs == nil {
return nil
}
result := make([]T, len(ptrs))
for i, p := range ptrs {
result[i] = From(p)
}
return result
}
// String returns a pointer to the provided string value.
func String(v string) *string {
return To(v)
}
// ToString dereferences a string pointer and returns its value.
// Returns empty string if the pointer is nil.
func ToString(p *string) string {
return From(p)
}
// Int returns a pointer to the provided int value.
func Int(v int) *int {
return To(v)
}
// ToInt dereferences an int pointer and returns its value.
// Returns 0 if the pointer is nil.
func ToInt(p *int) int {
return From(p)
}
// Int64 returns a pointer to the provided int64 value.
func Int64(v int64) *int64 {
return To(v)
}
// ToInt64 dereferences an int64 pointer and returns its value.
// Returns 0 if the pointer is nil.
func ToInt64(p *int64) int64 {
return From(p)
}
// Bool returns a pointer to the provided bool value.
func Bool(v bool) *bool {
return To(v)
}
// ToBool dereferences a bool pointer and returns its value.
// Returns false if the pointer is nil.
func ToBool(p *bool) bool {
return From(p)
}
// Float64 returns a pointer to the provided float64 value.
func Float64(v float64) *float64 {
return To(v)
}
// ToFloat64 dereferences a float64 pointer and returns its value.
// Returns 0.0 if the pointer is nil.
func ToFloat64(p *float64) float64 {
return From(p)
}
// Int32 returns a pointer to the provided int32 value.
func Int32(v int32) *int32 {
return To(v)
}
// ToInt32 dereferences an int32 pointer and returns its value.
// Returns 0 if the pointer is nil.
func ToInt32(p *int32) int32 {
return From(p)
}
// Int8 returns a pointer to the provided int8 value.
func Int8(v int8) *int8 {
return To(v)
}
// ToInt8 dereferences an int8 pointer and returns its value.
// Returns 0 if the pointer is nil.
func ToInt8(p *int8) int8 {
return From(p)
}
// Int16 returns a pointer to the provided int16 value.
func Int16(v int16) *int16 {
return To(v)
}
// ToInt16 dereferences an int16 pointer and returns its value.
// Returns 0 if the pointer is nil.
func ToInt16(p *int16) int16 {
return From(p)
}
// Uint returns a pointer to the provided uint value.
func Uint(v uint) *uint {
return To(v)
}
// ToUint dereferences a uint pointer and returns its value.
// Returns 0 if the pointer is nil.
func ToUint(p *uint) uint {
return From(p)
}
// Uint8 returns a pointer to the provided uint8 value.
func Uint8(v uint8) *uint8 {
return To(v)
}
// ToUint8 dereferences a uint8 pointer and returns its value.
// Returns 0 if the pointer is nil.
func ToUint8(p *uint8) uint8 {
return From(p)
}
// Uint16 returns a pointer to the provided uint16 value.
func Uint16(v uint16) *uint16 {
return To(v)
}
// ToUint16 dereferences a uint16 pointer and returns its value.
// Returns 0 if the pointer is nil.
func ToUint16(p *uint16) uint16 {
return From(p)
}
// Uint32 returns a pointer to the provided uint32 value.
func Uint32(v uint32) *uint32 {
return To(v)
}
// ToUint32 dereferences a uint32 pointer and returns its value.
// Returns 0 if the pointer is nil.
func ToUint32(p *uint32) uint32 {
return From(p)
}
// Uint64 returns a pointer to the provided uint64 value.
func Uint64(v uint64) *uint64 {
return To(v)
}
// ToUint64 dereferences a uint64 pointer and returns its value.
// Returns 0 if the pointer is nil.
func ToUint64(p *uint64) uint64 {
return From(p)
}
// Float32 returns a pointer to the provided float32 value.
func Float32(v float32) *float32 {
return To(v)
}
// ToFloat32 dereferences a float32 pointer and returns its value.
// Returns 0.0 if the pointer is nil.
func ToFloat32(p *float32) float32 {
return From(p)
}
// Byte returns a pointer to the provided byte value.
func Byte(v byte) *byte {
return To(v)
}
// ToByte dereferences a byte pointer and returns its value.
// Returns 0 if the pointer is nil.
func ToByte(p *byte) byte {
return From(p)
}
// Rune returns a pointer to the provided rune value.
func Rune(v rune) *rune {
return To(v)
}
// ToRune dereferences a rune pointer and returns its value.
// Returns 0 if the pointer is nil.
func ToRune(p *rune) rune {
return From(p)
}
// Time returns a pointer to the provided time.Time value.
func Time(v time.Time) *time.Time {
return To(v)
}
// ToTime dereferences a time.Time pointer and returns its value.
// Returns zero time if the pointer is nil.
func ToTime(p *time.Time) time.Time {
return From(p)
}
// Duration returns a pointer to the provided time.Duration value.
func Duration(v time.Duration) *time.Duration {
return To(v)
}
// ToDuration dereferences a time.Duration pointer and returns its value.
// Returns 0 if the pointer is nil.
func ToDuration(p *time.Duration) time.Duration {
return From(p)
}
// Complex64 returns a pointer to the provided complex64 value.
func Complex64(v complex64) *complex64 {
return To(v)
}
// ToComplex64 dereferences a complex64 pointer and returns its value.
// Returns 0+0i if the pointer is nil.
func ToComplex64(p *complex64) complex64 {
return From(p)
}
// Complex128 returns a pointer to the provided complex128 value.
func Complex128(v complex128) *complex128 {
return To(v)
}
// ToComplex128 dereferences a complex128 pointer and returns its value.
// Returns 0+0i if the pointer is nil.
func ToComplex128(p *complex128) complex128 {
return From(p)
}
// Uintptr returns a pointer to the provided uintptr value.
func Uintptr(v uintptr) *uintptr {
return To(v)
}
// ToUintptr dereferences a uintptr pointer and returns its value.
// Returns 0 if the pointer is nil.
func ToUintptr(p *uintptr) uintptr {
return From(p)
}
// MustString dereferences a string pointer and returns its value.
// Panics if the pointer is nil. Use this only when nil is a programming error.
func MustString(p *string) string {
return MustFrom(p)
}
// MustInt dereferences an int pointer and returns its value.
// Panics if the pointer is nil. Use this only when nil is a programming error.
func MustInt(p *int) int {
return MustFrom(p)
}
// MustInt64 dereferences an int64 pointer and returns its value.
// Panics if the pointer is nil. Use this only when nil is a programming error.
func MustInt64(p *int64) int64 {
return MustFrom(p)
}
// MustBool dereferences a bool pointer and returns its value.
// Panics if the pointer is nil. Use this only when nil is a programming error.
func MustBool(p *bool) bool {
return MustFrom(p)
}
// MustFloat64 dereferences a float64 pointer and returns its value.
// Panics if the pointer is nil. Use this only when nil is a programming error.
func MustFloat64(p *float64) float64 {
return MustFrom(p)
}