| 1 |
package activitypub |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"encoding/gob" |
| 6 |
|
| 7 |
"golang.org/x/text/language" |
| 8 |
) |
| 9 |
|
| 10 |
|
| 11 |
type LangRef language.Tag |
| 12 |
|
| 13 |
|
| 14 |
|
| 15 |
var NilLangRef = und |
| 16 |
|
| 17 |
|
| 18 |
var DefaultLang = English |
| 19 |
|
| 20 |
|
| 21 |
func (l LangRef) Valid() bool { |
| 22 |
return len(l.String()) > 0 && l != LangRef(language.Und) |
| 23 |
} |
| 24 |
|
| 25 |
|
| 26 |
func (l LangRef) Equal(other LangRef) bool { |
| 27 |
return (l.Valid() == other.Valid()) || l == other |
| 28 |
} |
| 29 |
|
| 30 |
|
| 31 |
func MakeRef(raw []byte) LangRef { |
| 32 |
return LangRef(language.Make(string(raw))) |
| 33 |
} |
| 34 |
|
| 35 |
func (l LangRef) GobEncode() ([]byte, error) { |
| 36 |
if len(l.String()) == 0 { |
| 37 |
return []byte{}, nil |
| 38 |
} |
| 39 |
b := new(bytes.Buffer) |
| 40 |
gg := gob.NewEncoder(b) |
| 41 |
if err := gobEncodeStringLikeType(gg, []byte(l.String())); err != nil { |
| 42 |
return nil, err |
| 43 |
} |
| 44 |
return b.Bytes(), nil |
| 45 |
} |
| 46 |
|
| 47 |
func (l *LangRef) GobDecode(data []byte) error { |
| 48 |
if len(data) == 0 { |
| 49 |
|
| 50 |
return nil |
| 51 |
} |
| 52 |
var bb []byte |
| 53 |
if err := gob.NewDecoder(bytes.NewReader(data)).Decode(&bb); err != nil { |
| 54 |
return err |
| 55 |
} |
| 56 |
*l = MakeRef(bb) |
| 57 |
return nil |
| 58 |
} |
| 59 |
|
| 60 |
|
| 61 |
func (l *LangRef) UnmarshalJSON(data []byte) error { |
| 62 |
return l.UnmarshalText(data) |
| 63 |
} |
| 64 |
|
| 65 |
|
| 66 |
func (l *LangRef) UnmarshalText(data []byte) error { |
| 67 |
*l = NilLangRef |
| 68 |
if len(data) == 0 { |
| 69 |
return nil |
| 70 |
} |
| 71 |
if len(data) > 2 { |
| 72 |
if data[0] == '"' && data[len(data)-1] == '"' { |
| 73 |
*l = MakeRef(data[1 : len(data)-1]) |
| 74 |
} |
| 75 |
} else { |
| 76 |
*l = MakeRef(data) |
| 77 |
} |
| 78 |
return nil |
| 79 |
} |
| 80 |
|
| 81 |
func (l LangRef) String() string { |
| 82 |
return language.Tag(l).String() |
| 83 |
} |