Marcel van Lohuizen | f4d483e | 2019-05-20 08:03:10 -0400 | [diff] [blame] | 1 | // Copyright 2019 CUE Authors |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | package openapi |
| 16 | |
| 17 | import "encoding/json" |
| 18 | |
| 19 | type orderedMap []kvPair |
| 20 | |
| 21 | type kvPair struct { |
| 22 | key string |
| 23 | value interface{} |
| 24 | } |
| 25 | |
| 26 | func (m *orderedMap) Prepend(key string, value interface{}) { |
| 27 | *m = append([]kvPair{{key, value}}, (*m)...) |
| 28 | } |
| 29 | |
| 30 | func (m *orderedMap) Set(key string, value interface{}) { |
| 31 | for i, v := range *m { |
| 32 | if v.key == key { |
| 33 | (*m)[i].value = value |
| 34 | return |
| 35 | } |
| 36 | } |
| 37 | *m = append(*m, kvPair{key, value}) |
| 38 | } |
| 39 | |
| 40 | func (m *orderedMap) Exists(key string) bool { |
| 41 | for _, v := range *m { |
| 42 | if v.key == key { |
| 43 | return true |
| 44 | } |
| 45 | } |
| 46 | return false |
| 47 | } |
| 48 | |
| 49 | func (m *orderedMap) MarshalJSON() (b []byte, err error) { |
| 50 | b = append(b, '{') |
| 51 | for i, v := range *m { |
| 52 | if i > 0 { |
| 53 | b = append(b, ",\n"...) |
| 54 | } |
| 55 | key, err := json.Marshal(v.key) |
| 56 | if je, ok := err.(*json.MarshalerError); ok { |
| 57 | return nil, je.Err |
| 58 | } |
| 59 | b = append(b, key...) |
| 60 | b = append(b, ": "...) |
| 61 | |
| 62 | value, err := json.Marshal(v.value) |
| 63 | if je, ok := err.(*json.MarshalerError); ok { |
| 64 | // return nil, je.Err |
| 65 | value, _ = json.Marshal(je.Err.Error()) |
| 66 | } |
| 67 | b = append(b, value...) |
| 68 | } |
| 69 | b = append(b, '}') |
| 70 | return b, nil |
| 71 | } |