merge.go 941 字节
Newer Older
H
update  
hongming 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
// Copyright 2017 The OPA Authors.  All rights reserved.
// Use of this source code is governed by an Apache2
// license that can be found in the LICENSE file.

// Package merge contains helpers to merge data structures
// frequently encountered in OPA.
package merge

// InterfaceMaps returns the result of merging a and b. If a and b cannot be
// merged because of conflicting key-value pairs, ok is false.
func InterfaceMaps(a map[string]interface{}, b map[string]interface{}) (c map[string]interface{}, ok bool) {

	c = map[string]interface{}{}
	for k := range a {
		c[k] = a[k]
	}

	for k := range b {

		add := b[k]
		exist, ok := c[k]
		if !ok {
			c[k] = add
			continue
		}

		existObj, existOk := exist.(map[string]interface{})
		addObj, addOk := add.(map[string]interface{})
		if !existOk || !addOk {
			return nil, false
		}

		c[k], ok = InterfaceMaps(existObj, addObj)
		if !ok {
			return nil, false
		}
	}

	return c, true
}