-
-
Notifications
You must be signed in to change notification settings - Fork 260
Expand file tree
/
Copy pathtype_format.go
More file actions
executable file
·90 lines (81 loc) · 2.03 KB
/
type_format.go
File metadata and controls
executable file
·90 lines (81 loc) · 2.03 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
package carbon
import (
"bytes"
"database/sql/driver"
)
// FormatType defines a FormatType generic struct.
type FormatType[T FormatTyper] struct {
*Carbon
}
// NewFormatType returns a new FormatType generic instance.
func NewFormatType[T FormatTyper](c *Carbon) *FormatType[T] {
return &FormatType[T]{
Carbon: c,
}
}
// Scan implements "driver.Scanner" interface for FormatType generic struct.
func (t *FormatType[T]) Scan(src any) error {
var c *Carbon
switch v := src.(type) {
case nil:
return nil
case []byte:
c = Parse(string(v))
case string:
c = Parse(v)
case StdTime:
c = CreateFromStdTime(v)
case *StdTime:
c = CreateFromStdTime(*v)
default:
return ErrFailedScan(v)
}
*t = *NewFormatType[T](c)
return t.Error
}
// Value implements "driver.Valuer" interface for FormatType generic struct.
func (t FormatType[T]) Value() (driver.Value, error) {
if t.IsNil() || t.IsZero() || t.IsEmpty() {
return nil, nil
}
if t.HasError() {
return nil, t.Error
}
return t.StdTime(), nil
}
// MarshalJSON implements "json.Marshaler" interface for FormatType generic struct.
func (t FormatType[T]) MarshalJSON() ([]byte, error) {
if t.IsNil() || t.IsZero() || t.IsEmpty() {
return []byte(`null`), nil
}
if t.HasError() {
return []byte(`null`), t.Error
}
v := t.Format(t.getFormat())
b := make([]byte, 0, len(v)+2)
b = append(b, '"')
b = append(b, v...)
b = append(b, '"')
return b, nil
}
// UnmarshalJSON implements "json.Unmarshaler" interface for FormatType generic struct.
func (t *FormatType[T]) UnmarshalJSON(src []byte) error {
v := string(bytes.Trim(src, `"`))
if v == "" || v == "null" {
return nil
}
*t = *NewFormatType[T](ParseByFormat(v, t.getFormat()))
return t.Error
}
// String implements "Stringer" interface for FormatType generic struct.
func (t *FormatType[T]) String() string {
if t == nil || t.IsInvalid() {
return ""
}
return t.Format(t.getFormat())
}
// getFormat returns the format of FormatType generic struct.
func (t *FormatType[T]) getFormat() string {
var typer T
return typer.Format()
}