summaryrefslogtreecommitdiffstats
path: root/aconf/model/set.lua
blob: dd28a2e02abb0746017d300a17bd12ee3033d91d (plain)
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
73
74
75
76
77
78
--[[
Copyright (c) 2012-2015 Kaarle Ritvanen
See LICENSE file for license details
--]]

--- @module aconf.model
local M = {}

local TreeNode = require('aconf.model.field').TreeNode
local node = require('aconf.model.node')
local object = require('aconf.object')
local pth = require('aconf.path')
local util = require('aconf.util')


--- set object, inherits @{node.List}. An instance of this class represents
-- a set object in the data model, in the context of a specific
-- transaction. A set is an unordered collection of primitive
-- values. Members can be inserted to the set using
-- @{node.insert}. Members can be removed by assigning the nil value
-- to the key to be removed.
-- @klass node.Set
M.Set = object.class(require('aconf.model.node').List)

function M.Set:init(context, params)
   assert(not object.isinstance(params.field, TreeNode))
   params.field.dereference = false

   params.dtype = 'set'

   object.super(self, M.Set):init(context, params)

   local function find(value)
      value = node.BoundMember(
	 self, pth.wildcard, params.field
      ):normalize(value)

      for i, member in pairs(self) do
	 if member == value then return i, value end
      end
   end

   local mt = getmetatable(self)

   function mt.get(k, options)
      options = util.setdefaults(options, {dereference=true})
      local i, v = find(k)
      if i then return mt.load(i, options) end
      if options.create then return v end
   end

   function mt.__newindex(t, k, v)
      assert(v == nil)
      local i = find(k)
      if not i then return end
      mt.save(i, nil)
   end

   --- determines if the given set contains the given value.
   -- @function node.contains
   -- @tparam node.Set set set
   -- @tparam primitive v value
   -- @treturn boolean true if the set contains the value
   function mt.contains(v) return find(v) and true or false end

   local insert = mt.insert
   function mt.insert(v) if not mt.contains(v) then insert(v) end end

   local meta = mt.meta
   function mt.meta()
      local res = meta()
      res.removable = util.map(mt.load, res.removable)
      return res
   end
end


return M