module Data.BTree.Impure.NonEmpty (
NonEmptyTree(..)
, Node(..)
, fromTree
, toTree
, nonEmptyToList
, fromNonEmptyList
, insertNonEmptyTree
, insertNonEmptyTreeMany
) where
import Control.Applicative ((<$>), (<*>))
import Data.Binary
import Data.List.NonEmpty (NonEmpty((:|)))
import Data.Map (Map)
import Data.Maybe (fromJust)
import Data.Typeable (Typeable)
import qualified Data.List.NonEmpty as NE
import qualified Data.Map as M
import Data.BTree.Alloc.Class
import Data.BTree.Impure (Tree(..), Node(..), insertTree, insertTreeMany, empty, toList)
import Data.BTree.Primitives
data NonEmptyTree key val where
NonEmptyTree :: {
treeHeight :: Height height
,
treeRootId :: NodeId height key val
} -> NonEmptyTree key val
deriving (Typeable)
deriving instance (Show key, Show val) => Show (NonEmptyTree key val)
instance (Value k, Value v) => Value (NonEmptyTree k v) where
instance Binary (NonEmptyTree key val) where
put (NonEmptyTree h root) = put h >> put root
get = NonEmptyTree <$> get <*> get
fromTree :: Tree key val -> Maybe (NonEmptyTree key val)
fromTree (Tree h n) = case n of
Nothing -> Nothing
Just root -> Just $ NonEmptyTree h root
toTree :: NonEmptyTree key val -> Tree key val
toTree (NonEmptyTree h n) = Tree h (Just n)
fromNonEmptyList :: (AllocM m, Key k, Value v)
=> NonEmpty (k, v)
-> m (NonEmptyTree k v)
fromNonEmptyList (x :| xs) = fromJust . fromTree <$> insertTreeMany (M.fromList (x:xs)) empty
insertNonEmptyTree :: (AllocM m, Key k, Value v)
=> k
-> v
-> NonEmptyTree k v
-> m (NonEmptyTree k v)
insertNonEmptyTree k v tree = fromJust . fromTree <$> insertTree k v (toTree tree)
insertNonEmptyTreeMany :: (AllocM m, Key k, Value v)
=> Map k v
-> NonEmptyTree k v
-> m (NonEmptyTree k v)
insertNonEmptyTreeMany kvs tree = fromJust . fromTree <$> insertTreeMany kvs (toTree tree)
nonEmptyToList :: (AllocReaderM m, Key k, Value v)
=> NonEmptyTree k v
-> m (NonEmpty (k, v))
nonEmptyToList tree = NE.fromList <$> toList (toTree tree)