Skip to content

Commit

Permalink
First commit
Browse files Browse the repository at this point in the history
  • Loading branch information
Ian Coleman committed Mar 1, 2017
0 parents commit c257e8e
Show file tree
Hide file tree
Showing 4 changed files with 448 additions and 0 deletions.
21 changes: 21 additions & 0 deletions LICENSE
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2017 Ian Coleman

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, Subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or Substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
146 changes: 146 additions & 0 deletions orderedmap.go
@@ -0,0 +1,146 @@
package orderedmap

import (
"encoding/json"
"errors"
"sort"
"strings"
)

var NoValueError = errors.New("No value for this key")

type KeyIndex struct {
Key string
Index int
}
type ByIndex []KeyIndex
func (a ByIndex) Len() int { return len(a) }
func (a ByIndex) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByIndex) Less(i, j int) bool { return a[i].Index < a[j].Index }

type OrderedMap struct {
keys []string
values map[string]interface{}
}

func New() *OrderedMap {
o := OrderedMap{}
o.keys = []string{}
o.values = map[string]interface{}{}
return &o
}

func (o *OrderedMap) Get(key string) (interface{}, bool) {
val, exists := o.values[key]
return val, exists
}

func (o *OrderedMap) Set(key string, value interface{}) {
_, exists := o.values[key]
if !exists {
o.keys = append(o.keys, key)
}
o.values[key] = value
}

func (o *OrderedMap) Delete(key string) {
// check key is in use
_, ok := o.values[key]
if !ok {
return
}
// remove from keys
for i, k := range o.keys {
if k == key {
o.keys = append(o.keys[:i], o.keys[i+1:]...)
break
}
}
// remove from values
delete(o.values, key)
}

func (o *OrderedMap) Keys() []string {
return o.keys
}

func (o *OrderedMap) UnmarshalJSON(b []byte) error {
m := map[string]interface{}{}
if err := json.Unmarshal(b, &m); err != nil {
return err
}
s := string(b)
mapToOrderedMap(o, s, m)
return nil
}

func mapToOrderedMap(o *OrderedMap, s string, m map[string]interface{}) {
// Get the order of the keys
orderedKeys := []KeyIndex{}
for k, _ := range m {
escapedK := strings.Replace(k, `"`, `\"`, -1)
keyStr := `"` + escapedK + `":`
// Find the least-nested instance of keyStr
sections := strings.Split(s, keyStr)
depth := 0
openBraces := 0
closeBraces := 0
i := 0
for j, section := range sections {
i = i + len(section)
openBraces = openBraces + strings.Count(section, "{")
closeBraces = closeBraces + strings.Count(section, "}")
depth = depth + openBraces - closeBraces
if depth <= 1 {
ki := KeyIndex {
Key: k,
Index: i,
}
orderedKeys = append(orderedKeys, ki)
// check if value is nested map
if j < len(sections) - 1 {
nextSectionUnclean := sections[j+1]
nextSection := strings.TrimSpace(nextSectionUnclean)
if string(nextSection[0]) == "{" {
// convert to orderedmap
mkTyped := m[k].(map[string]interface{})
oo := OrderedMap{}
mapToOrderedMap(&oo, nextSection, mkTyped)
m[k] = oo
}
}
break
}
i = i + len(k)
}
}
// Sort the keys
sort.Sort(ByIndex(orderedKeys))
// Convert sorted keys to string slice
k := []string{}
for _, ki := range orderedKeys {
k = append(k, ki.Key)
}
// Set the OrderedMap values
o.values = m
o.keys = k
}

func (o OrderedMap) MarshalJSON() ([]byte, error) {
s := "{"
for _, k := range o.keys {
// add key
kEscaped := strings.Replace(k, `"`, `\"`, -1)
s = s + `"` + kEscaped + `":`
// add value
v := o.values[k]
vBytes, err := json.Marshal(v)
if err != nil {
return []byte{}, err
}
s = s + string(vBytes) + ","
}
s = s[0:len(s)-1]
s = s + "}"
return []byte(s), nil
}
223 changes: 223 additions & 0 deletions orderedmap_test.go
@@ -0,0 +1,223 @@
package orderedmap

import (
"encoding/json"
"fmt"
"testing"
)

func TestOrderedMap(t *testing.T) {
o := New()
// number
o.Set("number", 3)
v, _ := o.Get("number")
if v.(int) != 3 {
t.Error("Set number")
}
// string
o.Set("string", "x")
v, _ = o.Get("string")
if v.(string) != "x" {
t.Error("Set string")
}
// string slice
o.Set("strings", []string{
"t",
"u",
})
v, _ = o.Get("strings")
if v.([]string)[0] != "t" {
t.Error("Set strings first index")
}
if v.([]string)[1] != "u" {
t.Error("Set strings second index")
}
// mixed slice
o.Set("mixed", []interface{}{
1,
"1",
})
v, _ = o.Get("mixed")
if v.([]interface{})[0].(int) != 1 {
t.Error("Set mixed int")
}
if v.([]interface{})[1].(string) != "1" {
t.Error("Set mixed string")
}
// overriding existing key
o.Set("number", 4)
v, _ = o.Get("number")
if v.(int) != 4 {
t.Error("Override existing key")
}
// Keys method
keys := o.Keys()
expectedKeys := []string{
"number",
"string",
"strings",
"mixed",
}
for i, _ := range keys {
if keys[i] != expectedKeys[i] {
t.Error("Keys method", keys[i], "!=", expectedKeys[i])
}
}
for i, _ := range expectedKeys {
if keys[i] != expectedKeys[i] {
t.Error("Keys method", keys[i], "!=", expectedKeys[i])
}
}
// delete
o.Delete("strings")
o.Delete("not a key being used")
if len(o.Keys()) != 3 {
t.Error("Delete method")
}
_, ok := o.Get("strings")
if ok {
t.Error("Delete did not remove 'strings' key")
}
}

func TestMarshalJSON(t *testing.T) {
o := New()
// number
o.Set("number", 3)
// string
o.Set("string", "x")
// new value keeps key in old position
o.Set("number", 4)
// keys not sorted alphabetically
o.Set("z", 1)
o.Set("a", 2)
o.Set("b", 3)
// slice
o.Set("slice", []interface{}{
"1",
1,
})
// orderedmap
v := New()
v.Set("e", 1)
v.Set("a", 2)
o.Set("orderedmap", v)
// double quote in key
o.Set(`test"ing`, 9)
// convert to json
b, err := json.Marshal(o)
if err != nil {
t.Error("Marshalling json", err)
}
s := string(b)
// check json is correctly ordered
if s != `{"number":4,"string":"x","z":1,"a":2,"b":3,"slice":["1",1],"orderedmap":{"e":1,"a":2},"test\"ing":9}` {
t.Error("JSON Marshal value is incorrect", s)
}
// convert to indented json
bi, err := json.MarshalIndent(o, "", " ")
if err != nil {
t.Error("Marshalling indented json", err)
}
si := string(bi)
ei := `{
"number": 4,
"string": "x",
"z": 1,
"a": 2,
"b": 3,
"slice": [
"1",
1
],
"orderedmap": {
"e": 1,
"a": 2
},
"test\"ing": 9
}`
if si != ei {
fmt.Println(ei)
fmt.Println(si)
t.Error("JSON MarshalIndent value is incorrect", si)
}
}

func TestUnmarshalJSON(t *testing.T) {
s := `{
"number": 4,
"string": "x",
"z": 1,
"a": "b",
"b": 3,
"slice": [
"1",
1
],
"orderedmap": {
"e": 1,
"a": 2,
"after": {
"link": "test"
}
},
"test\"ing": 9,
"after": 1
}`
o := New()
err := json.Unmarshal([]byte(s), &o)
if err != nil {
t.Error("JSON Unmarshal error", err)
}
// Check the root keys
expectedKeys := []string{
"number",
"string",
"z",
"a",
"b",
"slice",
"orderedmap",
"test\"ing",
"after",
}
k := o.Keys()
for i := range k {
if k[i] != expectedKeys[i] {
t.Error("Unmarshal root key order", i, k[i], "!=", expectedKeys[i])
}
}
// Check nested maps are converted to orderedmaps
// nested 1 level deep
expectedKeys = []string{
"e",
"a",
"after",
}
vi, ok := o.Get("orderedmap")
if !ok {
t.Error("Missing key for nested map 1 deep")
}
v := vi.(OrderedMap)
k = v.Keys()
for i := range k {
if k[i] != expectedKeys[i] {
t.Error("Key order for nested map 1 deep ", i, k[i], "!=", expectedKeys[i])
}
}
// nested 2 levels deep
expectedKeys = []string{
"link",
}
vi, ok = v.Get("after")
if !ok {
t.Error("Missing key for nested map 2 deep")
}
v = vi.(OrderedMap)
k = v.Keys()
for i := range k {
if k[i] != expectedKeys[i] {
t.Error("Key order for nested map 2 deep", i, k[i], "!=", expectedKeys[i])
}
}
}

0 comments on commit c257e8e

Please sign in to comment.