zaphyra's git: airpodsctl

Control and monitor your AirPods

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 
package types

import (
	"bytes"
	"encoding/json"
)

type Option[T any] struct {
	Set   bool
	Valid bool
	Value T
}

func (s Option[T]) MarshalJSON() ([]byte, error) {
	if !s.Valid {
		return []byte("null"), nil
	}
	return json.Marshal(s.Value)
}

func (s *Option[T]) UnmarshalJSON(data []byte) error {
	s.Set = true
	s.Valid = false

	if bytes.Equal(data, []byte("null")) {
		// The key was set to null, set value to zero/default value
		var zero T
		s.Value = zero
		return nil
	}

	// The key isn't set to null
	var v T
	if err := json.Unmarshal(data, &v); err != nil {
		return err
	}
	s.Value = v
	s.Valid = true
	return nil
}