Debian Codegraph @

langref.go

raw symbols SCIP
1 package activitypub
2
3 import (
4 "bytes"
5 "encoding/gob"
6
7 "golang.org/x/text/language"
8 )
9
10 // LangRef is the type for a language reference code, should be an ISO639-1 language specifier.
11 type LangRef language.Tag
12
13 // NilLangRef represents a convention for a nil language reference.
14 // It is used for LangRefValue objects without an explicit language key.
15 var NilLangRef = und
16
17 // DefaultLang represents the default language reference used when using the convenience content generation.
18 var DefaultLang = English
19
20 // Valid
21 func (l LangRef) Valid() bool {
22 return len(l.String()) > 0 && l != LangRef(language.Und)
23 }
24
25 // Equal checks if the language ref is equal to the "other"
26 func (l LangRef) Equal(other LangRef) bool {
27 return (l.Valid() == other.Valid()) || l == other
28 }
29
30 // MakeRef
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 // NOTE(marius): this behaviour diverges from vanilla gob package
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 // UnmarshalJSON decodes an incoming JSON document into the receiver object.
61 func (l *LangRef) UnmarshalJSON(data []byte) error {
62 return l.UnmarshalText(data)
63 }
64
65 // UnmarshalText implements the TextEncoder interface
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 }