module Radix.Word8.Debug
  ( S (..)

  , validPrefix
  , validKey
  ) where

import           Radix.Word8.Foundation

import           Data.Bits



-- | Branch side.
data S = L -- ^ Left. Masked bit of the prefix above this node must be @0@.
       | R -- ^ Right. Masked bit of the prefix above this node must be @1@.
         deriving Int -> S -> ShowS
[S] -> ShowS
S -> String
(Int -> S -> ShowS) -> (S -> String) -> ([S] -> ShowS) -> Show S
forall a.
(Int -> a -> ShowS) -> (a -> String) -> ([a] -> ShowS) -> Show a
$cshowsPrec :: Int -> S -> ShowS
showsPrec :: Int -> S -> ShowS
$cshow :: S -> String
show :: S -> String
$cshowList :: [S] -> ShowS
showList :: [S] -> ShowS
Show



-- | Check whether the prefix below aligns with the side the branch is on.
validPrefix :: Prefix -> S -> Prefix -> Bool
validPrefix :: Key -> S -> Key -> Bool
validPrefix Key
p S
s Key
o =
  let low :: Key
low = Key
p Key -> Key -> Key
forall a. Bits a => a -> a -> a
.&. Key -> Key
forall a. Num a => a -> a
negate Key
p
  in case S
s of
       S
L -> Key
o Key -> Key -> Bool
forall a. Ord a => a -> a -> Bool
< Key
p Bool -> Bool -> Bool
&& Key
p Key -> Key -> Key
forall a. Num a => a -> a -> a
- Key
o Key -> Key -> Bool
forall a. Ord a => a -> a -> Bool
< Key
low
       S
R -> Key
p Key -> Key -> Bool
forall a. Ord a => a -> a -> Bool
< Key
o Bool -> Bool -> Bool
&& Key
o Key -> Key -> Key
forall a. Num a => a -> a -> a
- Key
p Key -> Key -> Bool
forall a. Ord a => a -> a -> Bool
< Key
low



-- | Check whether the key below aligns with the side the branch is on.
validKey :: Prefix -> S -> Key -> Bool
validKey :: Key -> S -> Key -> Bool
validKey Key
p S
s Key
k =
  let low :: Key
low = Key
p Key -> Key -> Key
forall a. Bits a => a -> a -> a
.&. Key -> Key
forall a. Num a => a -> a
negate Key
p
  in case S
s of
       S
L -> Key
k Key -> Key -> Bool
forall a. Ord a => a -> a -> Bool
<  Key
p Bool -> Bool -> Bool
&& Key
p Key -> Key -> Key
forall a. Num a => a -> a -> a
- Key
k Key -> Key -> Bool
forall a. Ord a => a -> a -> Bool
<= Key
low
       S
R -> Key
p Key -> Key -> Bool
forall a. Ord a => a -> a -> Bool
<= Key
k Bool -> Bool -> Bool
&& Key
k Key -> Key -> Key
forall a. Num a => a -> a -> a
- Key
p Key -> Key -> Bool
forall a. Ord a => a -> a -> Bool
<  Key
low