{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE UndecidableInstances #-}
{-# LANGUAGE ViewPatterns #-}

module Data.RandomAccessList.SkewBinary
  ( RAList (Cons, Nil)
  , contIndexZero
  , contIndexOne
  , safeIndexZero
  , unsafeIndexZero
  , safeIndexOne
  , unsafeIndexOne
  , Data.RandomAccessList.SkewBinary.null
  , uncons
  ) where

import Data.Bits (setBit, unsafeShiftL, unsafeShiftR)
import Data.Word
import GHC.Exts

import Data.RandomAccessList.Class qualified as RAL

-- 'Node' appears first to make it more likely for GHC to reorder pattern matches to make the 'Node'
-- one appear first (which makes it more efficient).
{-| A complete binary tree.
Note: the size of the tree is not stored/cached,
unless it appears as a root tree in 'RAList', which the size is stored inside the Cons. -}
data Tree a
  = Node a !(Tree a) !(Tree a)
  | Leaf a
  deriving stock (Tree a -> Tree a -> Bool
(Tree a -> Tree a -> Bool)
-> (Tree a -> Tree a -> Bool) -> Eq (Tree a)
forall a. Eq a => Tree a -> Tree a -> Bool
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: forall a. Eq a => Tree a -> Tree a -> Bool
== :: Tree a -> Tree a -> Bool
$c/= :: forall a. Eq a => Tree a -> Tree a -> Bool
/= :: Tree a -> Tree a -> Bool
Eq, Int -> Tree a -> ShowS
[Tree a] -> ShowS
Tree a -> String
(Int -> Tree a -> ShowS)
-> (Tree a -> String) -> ([Tree a] -> ShowS) -> Show (Tree a)
forall a. Show a => Int -> Tree a -> ShowS
forall a. Show a => [Tree a] -> ShowS
forall a. Show a => Tree a -> String
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: forall a. Show a => Int -> Tree a -> ShowS
showsPrec :: Int -> Tree a -> ShowS
$cshow :: forall a. Show a => Tree a -> String
show :: Tree a -> String
$cshowList :: forall a. Show a => [Tree a] -> ShowS
showList :: [Tree a] -> ShowS
Show)

{-| A strict list of complete binary trees accompanied by their size.
The trees appear in >=-size order.
Note: this list is strict in its spine, unlike the Prelude list -}
data RAList a
  = BHead
      {-# UNPACK #-} !Word64
      -- ^ the size of the head tree
      !(Tree a)
      -- ^ the head tree
      !(RAList a)
      -- ^ the tail trees
  | Nil
  -- the derived Eq instance is correct,
  -- because binary skew numbers have unique representation
  -- and hence all trees of the same size will have the same structure
  deriving stock (RAList a -> RAList a -> Bool
(RAList a -> RAList a -> Bool)
-> (RAList a -> RAList a -> Bool) -> Eq (RAList a)
forall a. Eq a => RAList a -> RAList a -> Bool
forall a. (a -> a -> Bool) -> (a -> a -> Bool) -> Eq a
$c== :: forall a. Eq a => RAList a -> RAList a -> Bool
== :: RAList a -> RAList a -> Bool
$c/= :: forall a. Eq a => RAList a -> RAList a -> Bool
/= :: RAList a -> RAList a -> Bool
Eq, Int -> RAList a -> ShowS
[RAList a] -> ShowS
RAList a -> String
(Int -> RAList a -> ShowS)
-> (RAList a -> String) -> ([RAList a] -> ShowS) -> Show (RAList a)
forall a. Show a => Int -> RAList a -> ShowS
forall a. Show a => [RAList a] -> ShowS
forall a. Show a => RAList a -> String
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: forall a. Show a => Int -> RAList a -> ShowS
showsPrec :: Int -> RAList a -> ShowS
$cshow :: forall a. Show a => RAList a -> String
show :: RAList a -> String
$cshowList :: forall a. Show a => [RAList a] -> ShowS
showList :: [RAList a] -> ShowS
Show)
  deriving (Int -> [Item (RAList a)] -> RAList a
[Item (RAList a)] -> RAList a
RAList a -> [Item (RAList a)]
([Item (RAList a)] -> RAList a)
-> (Int -> [Item (RAList a)] -> RAList a)
-> (RAList a -> [Item (RAList a)])
-> IsList (RAList a)
forall a. Int -> [Item (RAList a)] -> RAList a
forall a. [Item (RAList a)] -> RAList a
forall a. RAList a -> [Item (RAList a)]
forall l.
([Item l] -> l)
-> (Int -> [Item l] -> l) -> (l -> [Item l]) -> IsList l
$cfromList :: forall a. [Item (RAList a)] -> RAList a
fromList :: [Item (RAList a)] -> RAList a
$cfromListN :: forall a. Int -> [Item (RAList a)] -> RAList a
fromListN :: Int -> [Item (RAList a)] -> RAList a
$ctoList :: forall a. RAList a -> [Item (RAList a)]
toList :: RAList a -> [Item (RAList a)]
IsList) via RAL.AsRAL (RAList a)

null :: RAList a -> Bool
null :: forall a. RAList a -> Bool
null RAList a
Nil = Bool
True
null RAList a
_ = Bool
False
{-# INLINE null #-}

{-# COMPLETE Cons, Nil #-}
{-# COMPLETE BHead, Nil #-}

-- /O(1)/
pattern Cons :: a -> RAList a -> RAList a
pattern $mCons :: forall {r} {a}.
RAList a -> (a -> RAList a -> r) -> ((# #) -> r) -> r
$bCons :: forall a. a -> RAList a -> RAList a
Cons x xs <- (uncons -> Just (x, xs))
  where
    Cons a
x RAList a
xs = a -> RAList a -> RAList a
forall a. a -> RAList a -> RAList a
cons a
x RAList a
xs

-- O(1) worst-case
cons :: a -> RAList a -> RAList a
cons :: forall a. a -> RAList a -> RAList a
cons a
x = \case
  (BHead Word64
w1 Tree a
t1 (BHead Word64
w2 Tree a
t2 RAList a
ts'))
    | Word64
w1 Word64 -> Word64 -> Bool
forall a. Eq a => a -> a -> Bool
== Word64
w2 ->
        -- 'unsafeShiftL w1 1 `setBit`0' is supposed to be a faster version of '(2*w1)+1'
        Word64 -> Tree a -> RAList a -> RAList a
forall a. Word64 -> Tree a -> RAList a -> RAList a
BHead (Word64 -> Int -> Word64
forall a. Bits a => a -> Int -> a
unsafeShiftL Word64
w1 Int
1 Word64 -> Int -> Word64
forall a. Bits a => a -> Int -> a
`setBit` Int
0) (a -> Tree a -> Tree a -> Tree a
forall a. a -> Tree a -> Tree a -> Tree a
Node a
x Tree a
t1 Tree a
t2) RAList a
ts'
  RAList a
ts -> Word64 -> Tree a -> RAList a -> RAList a
forall a. Word64 -> Tree a -> RAList a -> RAList a
BHead Word64
1 (a -> Tree a
forall a. a -> Tree a
Leaf a
x) RAList a
ts
{-# INLINE cons #-}

-- /O(1)/
uncons :: RAList a -> Maybe (a, RAList a)
uncons :: forall a. RAList a -> Maybe (a, RAList a)
uncons = \case
  BHead Word64
_ (Leaf a
x) RAList a
ts -> (a, RAList a) -> Maybe (a, RAList a)
forall a. a -> Maybe a
Just (a
x, RAList a
ts)
  BHead Word64
treeSize (Node a
x Tree a
t1 Tree a
t2) RAList a
ts ->
    -- probably faster than `div w 2`
    let halfSize :: Word64
halfSize = Word64 -> Int -> Word64
forall a. Bits a => a -> Int -> a
unsafeShiftR Word64
treeSize Int
1
     in -- split the node in two)
        (a, RAList a) -> Maybe (a, RAList a)
forall a. a -> Maybe a
Just (a
x, Word64 -> Tree a -> RAList a -> RAList a
forall a. Word64 -> Tree a -> RAList a -> RAList a
BHead Word64
halfSize Tree a
t1 (RAList a -> RAList a) -> RAList a -> RAList a
forall a b. (a -> b) -> a -> b
$ Word64 -> Tree a -> RAList a -> RAList a
forall a. Word64 -> Tree a -> RAList a -> RAList a
BHead Word64
halfSize Tree a
t2 RAList a
ts)
  RAList a
Nil -> Maybe (a, RAList a)
forall a. Maybe a
Nothing
{-# INLINE uncons #-}

{- Note [Optimizations of contIndexZero]
The lookup passes its result to a continuation: 'Nothing' when the index is out of bounds,
or 'Just' the element when it is found. Callers construct their failure result in the
'Nothing' branch. Passing a failure result as a separate argument previously made GHC
allocate the CEK error and its cause before the lookup, wasting those allocations on every
successful lookup.

The local search functions use the continuation, which keeps them inside 'contIndexZero'
until it is inlined at the call site. GHC can then inline the continuation into the search
and turn the recursive calls into local jumps (join points). When the continuation matches
on the 'Maybe', the 'Just' and 'Nothing' constructors are eliminated along with that match;
the intermediate 'Maybe' does not need to be allocated.

In the CEK machine, 'lookupVarName' and the continuation's 'pure' also inline away:
a successful lookup jumps straight to 'returnCek' with the value and the current state token.

The bangs on the index and tree size tell GHC that the search is strict in these arguments.
This lets it use unboxed 'Word64' values throughout the traversal.
-}

{-| Look up a zero-based index and pass the result to the continuation.
An out-of-bounds index gives 'Nothing'. -}
contIndexZero :: forall a b. (Maybe a -> b) -> RAList a -> Word64 -> b
contIndexZero :: forall a b. (Maybe a -> b) -> RAList a -> Word64 -> b
contIndexZero Maybe a -> b
k = RAList a -> Word64 -> b
findTree
  where
    findTree :: RAList a -> Word64 -> b
    -- See Note [Optimizations of contIndexZero].
    findTree :: RAList a -> Word64 -> b
findTree RAList a
Nil !Word64
_ = Maybe a -> b
k Maybe a
forall a. Maybe a
Nothing
    findTree (BHead Word64
w Tree a
t RAList a
ts) Word64
i =
      if Word64
i Word64 -> Word64 -> Bool
forall a. Ord a => a -> a -> Bool
< Word64
w
        then Word64 -> Word64 -> Tree a -> b
indexTree Word64
w Word64
i Tree a
t
        else RAList a -> Word64 -> b
findTree RAList a
ts (Word64
i Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
- Word64
w)

    indexTree :: Word64 -> Word64 -> Tree a -> b
    -- See Note [Optimizations of contIndexZero].
    indexTree :: Word64 -> Word64 -> Tree a -> b
indexTree !Word64
w Word64
0 Tree a
t = case Tree a
t of
      Node a
x Tree a
_ Tree a
_ -> Maybe a -> b
k (a -> Maybe a
forall a. a -> Maybe a
Just a
x)
      Leaf a
x -> if Word64
w Word64 -> Word64 -> Bool
forall a. Eq a => a -> a -> Bool
== Word64
1 then Maybe a -> b
k (a -> Maybe a
forall a. a -> Maybe a
Just a
x) else Maybe a -> b
k Maybe a
forall a. Maybe a
Nothing
    indexTree Word64
_ Word64
_ (Leaf a
_) = Maybe a -> b
k Maybe a
forall a. Maybe a
Nothing
    indexTree Word64
treeSize Word64
offset (Node a
_ Tree a
t1 Tree a
t2) =
      let halfSize :: Word64
halfSize = Word64 -> Int -> Word64
forall a. Bits a => a -> Int -> a
unsafeShiftR Word64
treeSize Int
1 -- probably faster than `div w 2`
       in if Word64
offset Word64 -> Word64 -> Bool
forall a. Ord a => a -> a -> Bool
<= Word64
halfSize
            then Word64 -> Word64 -> Tree a -> b
indexTree Word64
halfSize (Word64
offset Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
- Word64
1) Tree a
t1
            else Word64 -> Word64 -> Tree a -> b
indexTree Word64
halfSize (Word64
offset Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
- Word64
1 Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
- Word64
halfSize) Tree a
t2
{-# INLINE contIndexZero #-}

{-| Look up a one-based index and pass the result to the continuation.
Zero and indices beyond the end give 'Nothing'. -}
contIndexOne :: forall a b. (Maybe a -> b) -> RAList a -> Word64 -> b
contIndexOne :: forall a b. (Maybe a -> b) -> RAList a -> Word64 -> b
contIndexOne Maybe a -> b
k RAList a
_ Word64
0 = Maybe a -> b
k Maybe a
forall a. Maybe a
Nothing
contIndexOne Maybe a -> b
k RAList a
t Word64
n = (Maybe a -> b) -> RAList a -> Word64 -> b
forall a b. (Maybe a -> b) -> RAList a -> Word64 -> b
contIndexZero Maybe a -> b
k RAList a
t (Word64
n Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
- Word64
1)
{-# INLINE contIndexOne #-}

-- 0-based
unsafeIndexZero :: RAList a -> Word64 -> a
unsafeIndexZero :: forall a. RAList a -> Word64 -> a
unsafeIndexZero = (Maybe a -> a) -> RAList a -> Word64 -> a
forall a b. (Maybe a -> b) -> RAList a -> Word64 -> b
contIndexZero ((Maybe a -> a) -> RAList a -> Word64 -> a)
-> (Maybe a -> a) -> RAList a -> Word64 -> a
forall a b. (a -> b) -> a -> b
$ \case
  Maybe a
Nothing -> String -> a
forall a. HasCallStack => String -> a
error String
"out of bounds"
  Just a
x -> a
x
{-# INLINE unsafeIndexZero #-}

-- 0-based
safeIndexZero :: RAList a -> Word64 -> Maybe a
safeIndexZero :: forall a. RAList a -> Word64 -> Maybe a
safeIndexZero = (Maybe a -> Maybe a) -> RAList a -> Word64 -> Maybe a
forall a b. (Maybe a -> b) -> RAList a -> Word64 -> b
contIndexZero Maybe a -> Maybe a
forall a. a -> a
id
{-# INLINE safeIndexZero #-}

-- 1-based
unsafeIndexOne :: RAList a -> Word64 -> a
unsafeIndexOne :: forall a. RAList a -> Word64 -> a
unsafeIndexOne = (Maybe a -> a) -> RAList a -> Word64 -> a
forall a b. (Maybe a -> b) -> RAList a -> Word64 -> b
contIndexOne ((Maybe a -> a) -> RAList a -> Word64 -> a)
-> (Maybe a -> a) -> RAList a -> Word64 -> a
forall a b. (a -> b) -> a -> b
$ \case
  Maybe a
Nothing -> String -> a
forall a. HasCallStack => String -> a
error String
"out of bounds"
  Just a
x -> a
x
{-# INLINE unsafeIndexOne #-}

-- 1-based
safeIndexOne :: RAList a -> Word64 -> Maybe a
safeIndexOne :: forall a. RAList a -> Word64 -> Maybe a
safeIndexOne = (Maybe a -> Maybe a) -> RAList a -> Word64 -> Maybe a
forall a b. (Maybe a -> b) -> RAList a -> Word64 -> b
contIndexOne Maybe a -> Maybe a
forall a. a -> a
id
{-# INLINE safeIndexOne #-}

instance RAL.RandomAccessList (RAList a) where
  type Element (RAList a) = a

  empty :: RAList a
empty = RAList a
forall a. RAList a
Nil
  {-# INLINE empty #-}

  cons :: Element (RAList a) -> RAList a -> RAList a
cons = a -> RAList a -> RAList a
Element (RAList a) -> RAList a -> RAList a
forall a. a -> RAList a -> RAList a
Cons
  {-# INLINE cons #-}

  uncons :: RAList a -> Maybe (Element (RAList a), RAList a)
uncons = RAList a -> Maybe (a, RAList a)
RAList a -> Maybe (Element (RAList a), RAList a)
forall a. RAList a -> Maybe (a, RAList a)
uncons
  {-# INLINE uncons #-}

  length :: RAList a -> Word64
length = Word64 -> RAList a -> Word64
forall {a}. Word64 -> RAList a -> Word64
go Word64
0
    where
      go :: Word64 -> RAList a -> Word64
go !Word64
acc RAList a
Nil = Word64
acc
      go !Word64
acc (BHead Word64
sz Tree a
_ RAList a
tl) = Word64 -> RAList a -> Word64
go (Word64
acc Word64 -> Word64 -> Word64
forall a. Num a => a -> a -> a
+ Word64
sz) RAList a
tl
  {-# INLINE length #-}

  indexZero :: RAList a -> Word64 -> Maybe (Element (RAList a))
indexZero = RAList a -> Word64 -> Maybe a
RAList a -> Word64 -> Maybe (Element (RAList a))
forall a. RAList a -> Word64 -> Maybe a
safeIndexZero
  {-# INLINE indexZero #-}

  indexOne :: RAList a -> Word64 -> Maybe (Element (RAList a))
indexOne = RAList a -> Word64 -> Maybe a
RAList a -> Word64 -> Maybe (Element (RAList a))
forall a. RAList a -> Word64 -> Maybe a
safeIndexOne
  {-# INLINE indexOne #-}

  unsafeIndexZero :: RAList a -> Word64 -> Element (RAList a)
unsafeIndexZero = RAList a -> Word64 -> a
RAList a -> Word64 -> Element (RAList a)
forall a. RAList a -> Word64 -> a
unsafeIndexZero
  {-# INLINE unsafeIndexZero #-}

  unsafeIndexOne :: RAList a -> Word64 -> Element (RAList a)
unsafeIndexOne = RAList a -> Word64 -> a
RAList a -> Word64 -> Element (RAList a)
forall a. RAList a -> Word64 -> a
unsafeIndexOne
  {-# INLINE unsafeIndexOne #-}