Debian Codegraph @

natural_language_values.go

raw symbols SCIP
1 package activitypub
2
3 import (
4 "bytes"
5 "encoding/gob"
6 "fmt"
7 "io"
8 "strings"
9 "unicode/utf8"
10
11 "github.com/go-ap/errors"
12 "github.com/valyala/fastjson"
13 )
14
15 type (
16 Content []byte
17
18 // LangRefValue is a type for storing per language values
19 LangRefValue struct {
20 Ref LangRef
21 Value Content
22 }
23 // NaturalLanguageValues is a mapping for multiple language values
24 NaturalLanguageValues map[LangRef]Content
25 )
26
27 func RefValue[T ~string](l LangRef, v T) LangRefValue {
28 return LangRefValue{l, []byte(v)}
29 }
30
31 func NaturalLanguageValuesNew(values ...LangRefValue) NaturalLanguageValues {
32 n := make(NaturalLanguageValues)
33 for _, val := range values {
34 n[val.Ref] = val.Value
35 }
36 return n
37 }
38
39 func DefaultNaturalLanguage[T ~string](content T) NaturalLanguageValues {
40 return NaturalLanguageValuesNew(DefaultLangRef(content))
41 }
42
43 func (n NaturalLanguageValues) String() string {
44 cnt := len(n)
45 if cnt == 1 {
46 return n.First().String()
47 }
48 first := true
49 s := strings.Builder{}
50 s.Write([]byte{'['})
51 for k, v := range n {
52 if !first {
53 s.Write([]byte{','})
54 }
55 s.WriteString(v.String())
56 if k != NilLangRef {
57 s.WriteString("[")
58 s.WriteString(k.String())
59 s.WriteString("]")
60 }
61 first = false
62 }
63 s.Write([]byte{']'})
64 return s.String()
65 }
66
67 func (n NaturalLanguageValues) Get(ref LangRef) Content {
68 for k, val := range n {
69 if k == ref {
70 return val
71 }
72 }
73 return nil
74 }
75
76 // Set sets a language, value pair in a NaturalLanguageValues array
77 func (n *NaturalLanguageValues) Set(ref LangRef, v Content) error {
78 (*n)[ref] = v
79 return nil
80 }
81
82 var hex = "0123456789abcdef"
83
84 // safeSet holds the value true if the ASCII character with the given array
85 // position can be represented inside a JSON string without any further
86 // escaping.
87 //
88 // All values are true except for the ASCII control characters (0-31), the
89 // double quote ("), and the backslash character ("\").
90 var safeSet = [utf8.RuneSelf]bool{
91 ' ': true,
92 '!': true,
93 '"': false,
94 '#': true,
95 '$': true,
96 '%': true,
97 '&': true,
98 '\'': true,
99 '(': true,
100 ')': true,
101 '*': true,
102 '+': true,
103 ',': true,
104 '-': true,
105 '.': true,
106 '/': true,
107 '0': true,
108 '1': true,
109 '2': true,
110 '3': true,
111 '4': true,
112 '5': true,
113 '6': true,
114 '7': true,
115 '8': true,
116 '9': true,
117 ':': true,
118 ';': true,
119 '<': true,
120 '=': true,
121 '>': true,
122 '?': true,
123 '@': true,
124 'A': true,
125 'B': true,
126 'C': true,
127 'D': true,
128 'E': true,
129 'F': true,
130 'G': true,
131 'H': true,
132 'I': true,
133 'J': true,
134 'K': true,
135 'L': true,
136 'M': true,
137 'N': true,
138 'O': true,
139 'P': true,
140 'Q': true,
141 'R': true,
142 'S': true,
143 'T': true,
144 'U': true,
145 'V': true,
146 'W': true,
147 'X': true,
148 'Y': true,
149 'Z': true,
150 '[': true,
151 '\\': false,
152 ']': true,
153 '^': true,
154 '_': true,
155 '`': true,
156 'a': true,
157 'b': true,
158 'c': true,
159 'd': true,
160 'e': true,
161 'f': true,
162 'g': true,
163 'h': true,
164 'i': true,
165 'j': true,
166 'k': true,
167 'l': true,
168 'm': true,
169 'n': true,
170 'o': true,
171 'p': true,
172 'q': true,
173 'r': true,
174 's': true,
175 't': true,
176 'u': true,
177 'v': true,
178 'w': true,
179 'x': true,
180 'y': true,
181 'z': true,
182 '{': true,
183 '|': true,
184 '}': true,
185 '~': true,
186 '\u007f': true,
187 }
188
189 // htmlSafeSet holds the value true if the ASCII character with the given
190 // array position can be safely represented inside a JSON string, embedded
191 // inside of HTML <script> tags, without any additional escaping.
192 //
193 // All values are true except for the ASCII control characters (0-31), the
194 // double quote ("), the backslash character ("\"), HTML opening and closing
195 // tags ("<" and ">"), and the ampersand ("&").
196 var htmlSafeSet = [utf8.RuneSelf]bool{
197 ' ': true,
198 '!': true,
199 '"': false,
200 '#': true,
201 '$': true,
202 '%': true,
203 '&': false,
204 '\'': true,
205 '(': true,
206 ')': true,
207 '*': true,
208 '+': true,
209 ',': true,
210 '-': true,
211 '.': true,
212 '/': true,
213 '0': true,
214 '1': true,
215 '2': true,
216 '3': true,
217 '4': true,
218 '5': true,
219 '6': true,
220 '7': true,
221 '8': true,
222 '9': true,
223 ':': true,
224 ';': true,
225 '<': false,
226 '=': true,
227 '>': false,
228 '?': true,
229 '@': true,
230 'A': true,
231 'B': true,
232 'C': true,
233 'D': true,
234 'E': true,
235 'F': true,
236 'G': true,
237 'H': true,
238 'I': true,
239 'J': true,
240 'K': true,
241 'L': true,
242 'M': true,
243 'N': true,
244 'O': true,
245 'P': true,
246 'Q': true,
247 'R': true,
248 'S': true,
249 'T': true,
250 'U': true,
251 'V': true,
252 'W': true,
253 'X': true,
254 'Y': true,
255 'Z': true,
256 '[': true,
257 '\\': false,
258 ']': true,
259 '^': true,
260 '_': true,
261 '`': true,
262 'a': true,
263 'b': true,
264 'c': true,
265 'd': true,
266 'e': true,
267 'f': true,
268 'g': true,
269 'h': true,
270 'i': true,
271 'j': true,
272 'k': true,
273 'l': true,
274 'm': true,
275 'n': true,
276 'o': true,
277 'p': true,
278 'q': true,
279 'r': true,
280 's': true,
281 't': true,
282 'u': true,
283 'v': true,
284 'w': true,
285 'x': true,
286 'y': true,
287 'z': true,
288 '{': true,
289 '|': true,
290 '}': true,
291 '~': true,
292 '\u007f': true,
293 }
294
295 // NOTE: keep in sync with string above.
296 func stringBytes(e *bytes.Buffer, s []byte, escapeHTML bool) {
297 e.WriteRune('"')
298 start := 0
299 for i := 0; i < len(s); {
300 if b := s[i]; b < utf8.RuneSelf {
301 if htmlSafeSet[b] || (!escapeHTML && safeSet[b]) {
302 i++
303 continue
304 }
305 if start < i {
306 e.Write(s[start:i])
307 }
308 e.WriteRune('\\')
309 switch b {
310 case '\\', '"':
311 e.WriteRune(rune(b))
312 case '\n':
313 e.WriteRune('n')
314 case '\r':
315 e.WriteRune('r')
316 case '\t':
317 e.WriteRune('t')
318 default:
319 // This encodes bytes < 0x20 except for \t, \n and \r.
320 // If escapeHTML is set, it also escapes <, >, and &
321 // because they can lead to security holes when
322 // user-controlled strings are rendered into JSON
323 // and served to some browsers.
324 e.WriteString(`u00`)
325 e.WriteByte(hex[b>>4])
326 e.WriteByte(hex[b&0xF])
327 }
328 i++
329 start = i
330 continue
331 }
332 c, size := utf8.DecodeRune(s[i:])
333 if c == utf8.RuneError && size == 1 {
334 if start < i {
335 e.Write(s[start:i])
336 }
337 e.WriteString(`\ufffd`)
338 i += size
339 start = i
340 continue
341 }
342 // U+2028 is LINE SEPARATOR.
343 // U+2029 is PARAGRAPH SEPARATOR.
344 // They are both technically valid characters in JSON strings,
345 // but don't work in JSONP, which has to be evaluated as JavaScript,
346 // and can lead to security holes there. It is valid JSON to
347 // escape them, so we do so unconditionally.
348 // See http://timelessrepo.com/json-isnt-a-javascript-subset for discussion.
349 if c == '\u2028' || c == '\u2029' {
350 if start < i {
351 e.Write(s[start:i])
352 }
353 e.WriteString(`\u202`)
354 e.WriteByte(hex[c&0xF])
355 i += size
356 start = i
357 continue
358 }
359 i += size
360 }
361 if start < len(s) {
362 e.Write(s[start:])
363 }
364 e.WriteByte('"')
365 }
366
367 // MarshalJSON encodes the receiver object to a JSON document.
368 func (n NaturalLanguageValues) MarshalJSON() ([]byte, error) {
369 l := len(n)
370 if l <= 0 {
371 return nil, nil
372 }
373
374 b := bytes.Buffer{}
375 if l == 1 {
376 val := n.First()
377 if len(val) > 0 {
378 val = unescape(val)
379 stringBytes(&b, val, false)
380 return b.Bytes(), nil
381 }
382 }
383 b.Write([]byte{'{'})
384 empty := true
385 for ref, val := range n {
386 if len(val) == 0 {
387 continue
388 }
389 if !empty {
390 b.Write([]byte{','})
391 }
392 if ref.Valid() {
393 stringBytes(&b, []byte(ref.String()), false)
394 b.Write([]byte{':'})
395 }
396 stringBytes(&b, val, false)
397 empty = len(val) == 0
398 }
399 b.Write([]byte{'}'})
400 if !empty {
401 return b.Bytes(), nil
402 }
403 return nil, nil
404 }
405
406 // First returns the first element in the map
407 func (n NaturalLanguageValues) First() Content {
408 for _, v := range n {
409 return v
410 }
411 return nil
412 }
413
414 // Default returns the default NaturalLanguageValue
415 func (n NaturalLanguageValues) Default() Content {
416 v, _ := n[DefaultLang]
417 return v
418 }
419
420 // MarshalText serializes the NaturalLanguageValues into Text
421 func (n NaturalLanguageValues) MarshalText() ([]byte, error) {
422 bb := bytes.Buffer{}
423 first := true
424 for ref, val := range n {
425 if !first {
426 bb.WriteString(",")
427 }
428 bb.Write(val)
429 if ref.Valid() {
430 bb.WriteString("[")
431 bb.WriteString(ref.String())
432 bb.WriteString("]")
433 }
434 first = false
435 }
436 return bb.Bytes(), nil
437 }
438
439 func (n NaturalLanguageValues) Format(s fmt.State, verb rune) {
440 switch verb {
441 case 's', 'q':
442 _, _ = io.WriteString(s, "[")
443 for _, nn := range n {
444 nn.Format(s, verb)
445 }
446 _, _ = io.WriteString(s, "]")
447 case 'v':
448 _, _ = io.WriteString(s, "[")
449 for _, nn := range n {
450 nn.Format(s, verb)
451 }
452 _, _ = io.WriteString(s, "]")
453 }
454 }
455
456 // Append is syntactic sugar for resizing the NaturalLanguageValues map
457 // and appending an element
458 func (n *NaturalLanguageValues) Append(lang LangRef, value Content) error {
459 //*n = append(*n, LangRefValue{lang, value})
460 (*n)[lang] = value
461 return nil
462 }
463
464 // Count returns the length of Items in the item collection
465 func (n *NaturalLanguageValues) Count() uint {
466 if n == nil {
467 return 0
468 }
469 return uint(len(*n))
470 }
471
472 // String adds support for Stringer interface. It returns the Value[LangRef] text or just Value if LangRef is NIL
473 func (l LangRefValue) String() string {
474 if l.Ref == NilLangRef || !l.Ref.Valid() {
475 return l.Value.String()
476 }
477 return fmt.Sprintf("%s[%s]", l.Value, l.Ref)
478 }
479
480 func DefaultLangRef[T ~string](value T) LangRefValue {
481 return RefValue(DefaultLang, value)
482 }
483
484 func (l LangRefValue) Format(s fmt.State, verb rune) {
485 switch verb {
486 case 's', 'q':
487 if l.Ref == NilLangRef {
488 _, _ = io.WriteString(s, string(l.Value))
489 } else {
490 _, _ = fmt.Fprintf(s, "%q[%s]", l.Value, l.Ref)
491 }
492 case 'v':
493 if l.Ref == NilLangRef {
494 _, _ = fmt.Fprintf(s, "%q", string(l.Value))
495 } else {
496 _, _ = fmt.Fprintf(s, "%q[%s]", string(l.Value), l.Ref)
497 }
498 }
499 }
500
501 // UnmarshalJSON decodes an incoming JSON document into the receiver object.
502 func (l *LangRefValue) UnmarshalJSON(data []byte) error {
503 p := fastjson.Parser{}
504 val, err := p.ParseBytes(data)
505 if err != nil {
506 l.Ref = NilLangRef
507 l.Value = unescape(data)
508 return nil
509 }
510 switch val.Type() {
511 case fastjson.TypeObject:
512 o, _ := val.Object()
513 o.Visit(func(key []byte, v *fastjson.Value) {
514 l.Ref = MakeRef(key)
515 l.Value = unescape(v.GetStringBytes())
516 })
517 case fastjson.TypeString:
518 l.Ref = NilLangRef
519 l.Value = unescape(val.GetStringBytes())
520 }
521
522 return nil
523 }
524
525 // UnmarshalText implements the TextEncoder interface
526 func (l *LangRefValue) UnmarshalText(data []byte) error {
527 l.Ref = NilLangRef
528 l.Value = unescape(data)
529 return nil
530 }
531
532 // MarshalJSON encodes the receiver object to a JSON document.
533 func (l LangRefValue) MarshalJSON() ([]byte, error) {
534 buf := bytes.Buffer{}
535 if l.Ref != NilLangRef && l.Ref.Valid() {
536 if l.Value.Equal(Content("")) {
537 return nil, nil
538 }
539 stringBytes(&buf, []byte(l.Ref.String()), false)
540 buf.Write([]byte{':'})
541 }
542 stringBytes(&buf, l.Value, false)
543 return buf.Bytes(), nil
544 }
545
546 // MarshalText serializes the LangRefValue into JSON
547 func (l LangRefValue) MarshalText() ([]byte, error) {
548 if l.Ref != NilLangRef && l.Value.Equal(Content("")) {
549 return nil, nil
550 }
551 buf := bytes.Buffer{}
552 buf.WriteString(l.Value.String())
553 if l.Ref != NilLangRef {
554 buf.WriteByte('[')
555 buf.WriteString(l.Ref.String())
556 buf.WriteByte(']')
557 }
558 return buf.Bytes(), nil
559 }
560
561 type kv struct {
562 K []byte
563 V []byte
564 }
565
566 func (l LangRefValue) GobEncode() ([]byte, error) {
567 if len(l.Value) == 0 && !l.Ref.Valid() {
568 return []byte{}, nil
569 }
570 b := new(bytes.Buffer)
571 gg := gob.NewEncoder(b)
572 mm := kv{
573 K: []byte(l.Ref.String()),
574 V: []byte(l.Value),
575 }
576 if err := gg.Encode(mm); err != nil {
577 return nil, err
578 }
579 return b.Bytes(), nil
580 }
581
582 func (l *LangRefValue) GobDecode(data []byte) error {
583 if len(data) == 0 {
584 // NOTE(marius): this behaviour diverges from vanilla gob package
585 return nil
586 }
587 mm := kv{}
588 if err := gob.NewDecoder(bytes.NewReader(data)).Decode(&mm); err != nil {
589 return err
590 }
591 l.Ref = MakeRef(mm.K)
592 l.Value = mm.V
593 return nil
594 }
595
596 func (l LangRefValue) Equal(other LangRefValue) bool {
597 return l.Ref == other.Ref && l.Value.Equal(other.Value)
598 }
599
600 func (c *Content) UnmarshalJSON(data []byte) error {
601 if len(data) == 0 {
602 return nil
603 }
604 if len(data) >= 2 && data[0] == '"' && data[len(data)-1] == '"' {
605 return c.UnmarshalText(data[1 : len(data)-1])
606 }
607 return errors.Newf("unquoted string value when unmarshaling Content type")
608 }
609
610 func (c *Content) UnmarshalText(data []byte) error {
611 if len(data) == 0 {
612 return nil
613 }
614 *c = data
615 return nil
616 }
617
618 func (c Content) GobEncode() ([]byte, error) {
619 if len(c) == 0 {
620 return []byte{}, nil
621 }
622 b := new(bytes.Buffer)
623 gg := gob.NewEncoder(b)
624 if err := gobEncodeStringLikeType(gg, c); err != nil {
625 return nil, err
626 }
627 return b.Bytes(), nil
628 }
629
630 func (c *Content) GobDecode(data []byte) error {
631 if len(data) == 0 {
632 // NOTE(marius): this behaviour diverges from vanilla gob package
633 return nil
634 }
635 bb := make([]byte, 0)
636 if err := gob.NewDecoder(bytes.NewReader(data)).Decode(&bb); err != nil {
637 return err
638 }
639 *c = bb
640 return nil
641 }
642
643 func (c Content) String() string {
644 return string(c)
645 }
646
647 func (c Content) Equal(other Content) bool {
648 return bytes.Equal(c, other)
649 }
650
651 func (c Content) Format(s fmt.State, verb rune) {
652 switch verb {
653 case 's', 'q':
654 _, _ = io.WriteString(s, string(c))
655 case 'v':
656 _, _ = fmt.Fprintf(s, "%q", string(c))
657 }
658 }
659
660 func unescape(b []byte) []byte {
661 // FIXME(marius): I feel like I'm missing something really obvious about encoding/decoding from Json regarding
662 // escape characters, and that this function is just a hack. Be better future Marius, find the real problem!
663 b = bytes.ReplaceAll(b, []byte{'\\', 'a'}, []byte{'\a'})
664 b = bytes.ReplaceAll(b, []byte{'\\', 'f'}, []byte{'\f'})
665 b = bytes.ReplaceAll(b, []byte{'\\', 'n'}, []byte{'\n'})
666 b = bytes.ReplaceAll(b, []byte{'\\', 'r'}, []byte{'\r'})
667 b = bytes.ReplaceAll(b, []byte{'\\', 't'}, []byte{'\t'})
668 b = bytes.ReplaceAll(b, []byte{'\\', 'v'}, []byte{'\v'})
669 b = bytes.ReplaceAll(b, []byte{'\\', '"'}, []byte{'"'})
670 b = bytes.ReplaceAll(b, []byte{'\\', '\\'}, []byte{'\\'}) // this should cover the case of \\u -> \u
671 return b
672 }
673
674 // UnmarshalJSON decodes an incoming JSON document into the receiver object.
675 func (n *NaturalLanguageValues) UnmarshalJSON(data []byte) error {
676 if n == nil {
677 return errors.Newf("nil %T value to unmarshal to", n)
678 }
679 if len(data) == 0 {
680 return nil
681 }
682 p := fastjson.Parser{}
683 val, err := p.ParseBytes(data)
684 if err != nil {
685 // try our luck if data contains an unquoted string
686 cont := Content{}
687 if err := cont.UnmarshalJSON(data); err != nil {
688 return err
689 }
690 return n.Append(NilLangRef, cont)
691 }
692 switch val.Type() {
693 case fastjson.TypeObject:
694 ob, _ := val.Object()
695 ob.Visit(func(key []byte, v *fastjson.Value) {
696 cont := Content{}
697 if dat := v.GetStringBytes(); len(dat) > 0 {
698 if err := cont.UnmarshalText(dat); err == nil {
699 _ = n.Append(MakeRef(key), cont)
700 }
701 }
702 })
703 case fastjson.TypeString:
704 if dat := val.GetStringBytes(); len(dat) > 0 {
705 cont := Content{}
706 if err := cont.UnmarshalText(dat); err == nil {
707 _ = n.Append(NilLangRef, cont)
708 }
709 }
710 }
711
712 return nil
713 }
714
715 // UnmarshalText tries to load the NaturalLanguage array from the incoming Text value
716 func (n *NaturalLanguageValues) UnmarshalText(data []byte) error {
717 if len(data) == 0 {
718 return nil
719 }
720 c := Content{}
721 if err := c.UnmarshalText(data); err != nil {
722 return err
723 }
724 return n.Append(NilLangRef, c)
725 }
726
727 func (n NaturalLanguageValues) GobEncode() ([]byte, error) {
728 if len(n) == 0 {
729 return []byte{}, nil
730 }
731 b := new(bytes.Buffer)
732 gg := gob.NewEncoder(b)
733 mm := make([]kv, 0, len(n))
734 for ref, val := range n {
735 mm = append(mm, kv{K: []byte(ref.String()), V: val})
736 }
737 if err := gg.Encode(mm); err != nil {
738 return nil, err
739 }
740 return b.Bytes(), nil
741 }
742
743 func (n *NaturalLanguageValues) GobDecode(data []byte) error {
744 if len(data) == 0 {
745 // NOTE(marius): this behaviour diverges from vanilla gob package
746 return nil
747 }
748 mm := make([]kv, 0)
749 if err := gob.NewDecoder(bytes.NewReader(data)).Decode(&mm); err != nil {
750 return err
751 }
752 for _, m := range mm {
753 _ = n.Append(MakeRef(m.K), m.V)
754 }
755 return nil
756 }
757
758 // Equal
759 func (n NaturalLanguageValues) Equal(with NaturalLanguageValues) bool {
760 if n.Count() != with.Count() {
761 return false
762 }
763
764 for l, wv := range with {
765 nv, ok := n[l]
766 if !ok {
767 return false
768 }
769 if nv.Equal(wv) {
770 continue
771 }
772 return false
773 }
774 return true
775 }