diff options
author | Luke Shumaker <lukeshu@datawire.io> | 2022-08-14 20:52:33 -0600 |
---|---|---|
committer | Luke Shumaker <lukeshu@datawire.io> | 2022-08-17 00:48:19 -0600 |
commit | 3ae8e37b8ca2b9a7769d659e134ee2711dc94b89 (patch) | |
tree | 35d23ddd779820dea1e239e96d5613c2d874a2b7 /compat/json/borrowed_example_text_marshaling_test.go | |
parent | 6b11bd03dd572a4c1b5bb2a72da5a556c7998c56 (diff) |
Borrow more test files [ci-skip]
Diffstat (limited to 'compat/json/borrowed_example_text_marshaling_test.go')
-rw-r--r-- | compat/json/borrowed_example_text_marshaling_test.go | 67 |
1 files changed, 67 insertions, 0 deletions
diff --git a/compat/json/borrowed_example_text_marshaling_test.go b/compat/json/borrowed_example_text_marshaling_test.go new file mode 100644 index 0000000..04c7813 --- /dev/null +++ b/compat/json/borrowed_example_text_marshaling_test.go @@ -0,0 +1,67 @@ +// Copyright 2018 The Go Authors. All rights reserved. +// Use of this source code is governed by a BSD-style +// license that can be found in the LICENSE file. + +package json_test + +import ( + "encoding/json" + "fmt" + "log" + "strings" +) + +type Size int + +const ( + Unrecognized Size = iota + Small + Large +) + +func (s *Size) UnmarshalText(text []byte) error { + switch strings.ToLower(string(text)) { + default: + *s = Unrecognized + case "small": + *s = Small + case "large": + *s = Large + } + return nil +} + +func (s Size) MarshalText() ([]byte, error) { + var name string + switch s { + default: + name = "unrecognized" + case Small: + name = "small" + case Large: + name = "large" + } + return []byte(name), nil +} + +func Example_textMarshalJSON() { + blob := `["small","regular","large","unrecognized","small","normal","small","large"]` + var inventory []Size + if err := json.Unmarshal([]byte(blob), &inventory); err != nil { + log.Fatal(err) + } + + counts := make(map[Size]int) + for _, size := range inventory { + counts[size] += 1 + } + + fmt.Printf("Inventory Counts:\n* Small: %d\n* Large: %d\n* Unrecognized: %d\n", + counts[Small], counts[Large], counts[Unrecognized]) + + // Output: + // Inventory Counts: + // * Small: 3 + // * Large: 2 + // * Unrecognized: 3 +} |