-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathHashtableMerger.cs
More file actions
72 lines (64 loc) · 2.84 KB
/
HashtableMerger.cs
File metadata and controls
72 lines (64 loc) · 2.84 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Copyright (C) SomaSim LLC.
// Open source software. Please see LICENSE file for details.
using System;
using System.Collections;
namespace SomaSim.SION
{
/// <summary>
/// Helper class to merge two JSON structures.
///
/// When merging a parent with a child, it will produce a new structure such that:
/// - Each key/value pair from the parent is copied into result
/// - Then each key/value pair from the child is copied into result, and in case of a conflict:
/// - If child's value is string or primitive (bool, double, etc), overrides parent's value
/// - If child's value is a Hashtable or ArrayList, but parent wasn't, overrides
/// - If both values are ArrayList, either overrides or appends parent's value, depending on settings
/// - If both values are hashtables, recursively merge them
/// </summary>
public class HashtableMerger
{
public static bool ThrowExceptionOnBadData = false;
public static object Merge (object parent, object child, bool arrayappend = false) {
if (IsScalar(child)) {
return child;
} else if (child is ArrayList) {
if (!arrayappend || !(parent is ArrayList)) {
return child;
} else {
ArrayList parray = parent as ArrayList;
ArrayList carray = child as ArrayList;
ArrayList result = new ArrayList(parray.Count + carray.Count);
result.AddRange(parray);
result.AddRange(carray);
return result;
}
} else if (child is Hashtable) {
if (!(parent is Hashtable)) {
return child;
} else {
Hashtable chash = child as Hashtable;
Hashtable phash = parent as Hashtable;
Hashtable result = new Hashtable();
foreach (DictionaryEntry entry in phash) {
result[entry.Key] = phash[entry.Key];
}
foreach (DictionaryEntry entry in chash) {
if (result.ContainsKey(entry.Key)) {
result[entry.Key] = Merge(phash[entry.Key], chash[entry.Key], arrayappend);
} else {
result[entry.Key] = chash[entry.Key];
}
}
return result;
}
} else if (ThrowExceptionOnBadData) {
throw new Exception("Unknown value type for value: " + child);
} else {
return null; // not valid, boo
}
}
private static bool IsScalar (object value) {
return value.GetType().IsPrimitive || value is string;
}
}
}