1//////////////////////////////////////////////////////////////////////
  2// LibFile: structs.scad
  3//   This file provides manipulation of "structs".  A "struct" is a data structure that
  4//   associates arbitrary keys with values and allows you to get and set values
  5//   by key.
  6// Includes:
  7//   include <BOSL2/std.scad>
  8//   include <BOSL2/structs.scad>
  9// FileGroup: Data Management
 10// FileSummary: Structure/Dictionary Manipulation
 11//////////////////////////////////////////////////////////////////////
 12
 13
 14// Section: struct operations
 15//
 16// A struct is a data structure that associates arbitrary keys (of any type) with values (of any type).
 17// Structures are implemented as lists of [key, value] pairs.
 18//
 19// An empty list `[]` is an empty structure and can be used wherever a structure input is required.
 20
 21// Function: struct_set()
 22// Synopsis: Sets one or more key-value pairs in a struct.
 23// Topics: Data Structures, Dictionaries
 24// See Also: struct_set(), struct_remove(), struct_val(), struct_keys(), echo_struct(), is_struct()
 25// Usage:
 26//   struct2 = struct_set(struct, key, value, [grow=]);
 27//   struct2 = struct_set(struct, [key1, value1, key2, value2, ...], [grow=]);
 28// Description:
 29//   Sets the key(s) in the structure to the specified value(s), returning a new updated structure.  If a
 30//   key exists its value is changed, otherwise the key is added to the structure.  If `grow=false` then
 31//   it is an error to set a key not already defined in the structure.  If you specify the same key twice
 32//   that is also an error.  Note that key order will change when you change a key's value.
 33// Arguments:
 34//   struct = input structure.
 35//   key = key to set or list of key,value pairs to set
 36//   value = value to set the key to (when giving a single key and value)
 37//   ---
 38//   grow = Set to true to allow structure to grow, or false for new keys to generate an error.  Default: true
 39// Example: Create a struct containing just one key-value pair
 40//   some_struct = struct_set([], "answer", 42);
 41//   // 'some_struct' now contains a single value, 42, under one key, "answer".
 42// Example: Create a struct containing more than one key-value pair. Note that keys and values need not be the same type.
 43//   some_struct = struct_set([], ["answer", 42, 2, "two", "quote", "What a nice day"]);
 44//   // 'some struct' now contains these key-value pairs:
 45//   // answer: 42
 46//   // 2: two
 47//   // quote: What a nice day
 48function struct_set(struct, key, value, grow=true) =
 49  is_def(value) ? struct_set(struct,[key,value],grow=grow)
 50  :
 51  assert(is_list(key) && len(key)%2==0, "[key,value] pair list is not a list or has an odd length")
 52  let(
 53      new_entries = [for(i=[0:1:len(key)/2-1]) [key[2*i], key[2*i+1]]],
 54      newkeys = column(new_entries,0),
 55      indlist = search(newkeys, struct,0,0),
 56      badkeys = grow ? (search([undef],new_entries,1,0)[0] != [] ? [undef] : [])
 57                     : [for(i=idx(indlist)) if (is_undef(newkeys[i]) || len(indlist[i])==0) newkeys[i]],
 58      ind = flatten(indlist),
 59      dupfind = search(newkeys, new_entries,0,0),
 60      dupkeys = [for(i=idx(dupfind)) if (len(dupfind[i])>1) newkeys[i]]
 61  )
 62  assert(badkeys==[], str("Unknown or bad key ",_format_key(badkeys[0])," in struct_set"))
 63  assert(dupkeys==[], str("Duplicate key ",_format_key(dupkeys[0])," for struct"))
 64  concat(list_remove(struct,ind), new_entries);
 65
 66function _format_key(key) = is_string(key) ? str("\"",key,"\""): key;
 67
 68// Function: struct_remove()
 69// Synopsis: Removes one or more keys from a struct.
 70// Topics: Data Structures, Dictionaries
 71// See Also: struct_set(), struct_remove(), struct_val(), struct_keys(), echo_struct(), is_struct()
 72// Usage:
 73//   struct2 = struct_remove(struct, key);
 74// Description:
 75//   Remove key or list of keys from a structure.  If you want to remove a single key which is a list
 76//   you must pass it as a singleton list, or struct_remove will attempt to remove the listed items as keys.
 77//   If you list the same item multiple times for removal it will be removed without error.
 78// Arguments:
 79//   struct = input structure
 80//   key = a single key or list of keys to remove.
 81function struct_remove(struct, key) =
 82   !is_list(key) ? struct_remove(struct, [key]) :
 83    let(ind = search(key, struct))
 84    list_remove(struct, [for(i=ind) if (i!=[]) i]);
 85
 86
 87// Function: struct_val()
 88// Synopsis: Returns the value for an key in a struct.
 89// Topics: Data Structures, Dictionaries
 90// See Also: struct_set(), struct_remove(), struct_val(), struct_keys(), echo_struct(), is_struct()
 91// Usage:
 92//   val = struct_val(struct, key, default);
 93// Description:
 94//   Returns the value for the specified key in the structure, or default value if the key is not present
 95// Arguments:
 96//   struct = input structure
 97//   key = key whose value to return
 98//   default = default value to return if key is not present.  Default: undef
 99function struct_val(struct, key, default=undef) =
100    assert(is_def(key),"key is missing")
101    let(ind = search([key],struct)[0])
102    ind == [] ? default : struct[ind][1];
103
104
105// Function: struct_keys()
106// Synopsis: Returns a list of keys for a struct.
107// Topics: Data Structures, Dictionaries
108// See Also: struct_set(), struct_remove(), struct_val(), struct_keys(), echo_struct(), is_struct()
109// Usage:
110//   keys = struct_keys(struct);
111// Description:
112//   Returns a list of the keys in a structure
113// Arguments:
114//   struct = input structure
115function struct_keys(struct) = column(struct,0);
116
117
118// Function&Module: echo_struct()
119// Synopsis: Echoes the struct to the console in a formatted manner.
120// Topics: Data Structures, Dictionaries
121// See Also: struct_set(), struct_remove(), struct_val(), struct_keys(), echo_struct(), is_struct()
122// Usage:
123//   echo_struct(struct, [name]);
124//   foo = echo_struct(struct, [name]);
125// Description:
126//   Displays a list of structure keys and values, one pair per line, for easier reading.
127// Arguments:
128//   struct = input structure
129//   name = optional structure name to list at the top of the output.  Default: ""
130function echo_struct(struct,name="") =
131    let( keylist = [for(entry=struct) str("  ",entry[0],": ",entry[1],"\n")])
132    echo(str("\nStructure ",name,"\n",str_join(keylist)))
133    undef;
134
135module echo_struct(struct,name="") {
136    no_children($children);
137    dummy = echo_struct(struct,name);
138}
139
140
141// Function: is_struct()
142// Synopsis: Returns true if the value is a struct.
143// Topics: Data Structures, Dictionaries
144// See Also: struct_set(), struct_remove(), struct_val(), struct_keys(), echo_struct(), is_struct()
145// Usage:
146//   bool = is_struct(struct);
147// Description:
148//   Returns true if the input is a list of pairs, false otherwise.
149function is_struct(x) =
150    is_list(x) && [for (xx=x) if(!(is_list(xx) && len(xx)==2)) 1] == [];
151
152
153// vim: expandtab tabstop=4 shiftwidth=4 softtabstop=4 nowrap