{-
--------------------------------------------------------------------------------
--
-- Copyright (C) 2008 Martin Sulzmann, Edmund Lam. All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.

    * Redistributions in binary form must reproduce the above
      copyright notice, this list of conditions and the following
      disclaimer in the documentation and/or other materials provided
      with the distribution.

    * Neither the name of Isaac Jones nor the names of other
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

-}


module Actor.SList where

import IO
import Monad
import Data.IORef

---------------------------------------
-- API for a singly-linked list
-- We use this structure for representing the internal mailbox


data Item a = Node { val :: a
                   , deleted :: Bool
                   , next :: IORef (Item a) }
            | Null
            | Head { next :: IORef (Item a) }

data SList a = SList { headList :: IORef (IORef (Item a)), 
                       tailList :: IORef (IORef (Item a)) }

-- we assume a static head pointer, pointing to the first node which must be Head
-- tail points to the last node which must be Null

type Iterator a = IORef (IORef (Item a))


-- basic api

-- we create a new list
newSList :: IO (SList a)
newSList = 
   do null <- newIORef Null
      hd <- newIORef (Head null)
      hdPtr <- newIORef hd
      tailPtr <- newIORef null
      return (SList {headList = hdPtr, tailList = tailPtr})


-- we add a new node, by overwriting the null tail node
-- we only need to adjust tailList but not headList because
-- of the static Head
-- we return the location of the newly added node
addToTail :: SList a -> a -> IO (IORef (Item a))
addToTail (SList {tailList = tailPtrPtr}) x =
   do null <- newIORef Null
      tailPtr <- readIORef tailPtrPtr
      writeIORef tailPtr (Node {val = x, deleted = False, next = null})
      writeIORef tailPtrPtr null
      return tailPtr


-- the iterator always points to the PREVIOUS node,
-- recall that there's a static dummy new Head
newIterator :: SList a -> IO (Iterator a)
newIterator (SList {headList = hd}) =
  do hdPtr <- readIORef hd
     it <- newIORef hdPtr
     return it


-- test if iterators point to same location
testEqIterator :: Iterator a -> Iterator a -> IO Bool
testEqIterator it1 it2 =
  do it1Ptr <- readIORef it1
     it2Ptr <- readIORef it2
     return (it1Ptr == it2Ptr)

-- assign the rhs iterator's current pointer to the lhs iterator
assignIterator :: Iterator a -> Iterator a -> IO ()
assignIterator lhs rhs =
  do rhsVal <- readIORef rhs
     writeIORef lhs rhsVal
     

-- we iterate through the list and return the first "not deleted" node
-- we delink deleted nodes
-- there's no need to adjust headList, tailList
-- cause headList has a static Head and
-- tailList points to Null
iterateSList :: Iterator a -> IO (Maybe (IORef (Item a)))
iterateSList itPtrPtr = 
  let go prevPtr =
        do prevNode <- readIORef prevPtr
           let curPtr = next prevNode -- the prev node has always a next field
                                      -- recall the static dummy head node
           curNode <- readIORef curPtr
           case curNode of
             Null -> return Nothing -- reached end of the list
             Node { deleted = del, next = nextNode } ->
                if not del
                then -- node available
                     do writeIORef itPtrPtr curPtr  -- adjust iterator
                        return (Just curPtr) 
                else -- delete curNode by setting the next of prevNode to next of curNode
                     do case prevNode of
                          Head {} -> writeIORef prevPtr (Head {next = nextNode})
                          Node {} -> writeIORef prevPtr 
                                       (Node {val = val prevNode, 
                                              deleted = deleted prevNode, 
                                              next = nextNode})
                        go prevPtr 
  in do startPtr <- readIORef itPtrPtr
        go startPtr