htools: fix corner case in prop_Text_Load_Instance
[ganeti-local] / htools / Ganeti / HTools / Container.hs
1 {-| Module abstracting the node and instance container implementation.
2
3 This is currently implemented on top of an 'IntMap', which seems to
4 give the best performance for our workload.
5
6 -}
7
8 {-
9
10 Copyright (C) 2009, 2010 Google Inc.
11
12 This program is free software; you can redistribute it and/or modify
13 it under the terms of the GNU General Public License as published by
14 the Free Software Foundation; either version 2 of the License, or
15 (at your option) any later version.
16
17 This program is distributed in the hope that it will be useful, but
18 WITHOUT ANY WARRANTY; without even the implied warranty of
19 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
20 General Public License for more details.
21
22 You should have received a copy of the GNU General Public License
23 along with this program; if not, write to the Free Software
24 Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
25 02110-1301, USA.
26
27 -}
28
29 module Ganeti.HTools.Container
30     (
31      -- * Types
32      Container
33     , Key
34      -- * Creation
35     , IntMap.empty
36     , IntMap.singleton
37     , IntMap.fromList
38      -- * Query
39     , IntMap.size
40     , IntMap.null
41     , find
42     , IntMap.findMax
43      -- * Update
44     , add
45     , addTwo
46     , IntMap.map
47     , IntMap.mapAccum
48     , IntMap.filter
49     -- * Conversion
50     , IntMap.elems
51     , IntMap.keys
52     -- * Element functions
53     , nameOf
54     , findByName
55     ) where
56
57 import qualified Data.IntMap as IntMap
58
59 import qualified Ganeti.HTools.Types as T
60
61 type Key = IntMap.Key
62 type Container = IntMap.IntMap
63
64 -- | Locate a key in the map (must exist).
65 find :: Key -> Container a -> a
66 find k = (IntMap.! k)
67
68 -- | Add or update one element to the map.
69 add :: Key -> a -> Container a -> Container a
70 add = IntMap.insert
71
72 -- | Add or update two elements of the map.
73 addTwo :: Key -> a -> Key -> a -> Container a -> Container a
74 addTwo k1 v1 k2 v2 = add k1 v1 . add k2 v2
75
76 -- | Compute the name of an element in a container.
77 nameOf :: (T.Element a) => Container a -> Key -> String
78 nameOf c k = T.nameOf $ find k c
79
80 -- | Find an element by name in a Container; this is a very slow function.
81 findByName :: (T.Element a, Monad m) =>
82               Container a -> String -> m a
83 findByName c n =
84     let all_elems = IntMap.elems c
85         result = filter ((n `elem`) . T.allNames) all_elems
86     in case result of
87          [item] -> return item
88          _ -> fail $ "Wrong number of elems found with name " ++ n