0b5f0b441b6ab96462d38bb224d25b93717d6e05
[ghc-base.git] / Data / Array / Diff.hs
1 -----------------------------------------------------------------------------
2 -- |
3 -- Module      :  Data.Array.Diff
4 -- Copyright   :  (c) The University of Glasgow 2001
5 -- License     :  BSD-style (see the file libraries/base/LICENSE)
6 -- 
7 -- Maintainer  :  libraries@haskell.org
8 -- Stability   :  experimental
9 -- Portability :  non-portable
10 --
11 -- Functional arrays with constant-time update.
12 --
13 -----------------------------------------------------------------------------
14
15 module Data.Array.Diff (
16
17     -- * Diff array types
18
19     -- | Diff arrays have an immutable interface, but rely on internal
20     -- updates in place to provide fast functional update operator
21     -- '//'.
22     --
23     -- When the '//' operator is applied to a diff array, its contents
24     -- are physically updated in place. The old array silently changes
25     -- its representation without changing the visible behavior:
26     -- it stores a link to the new current array along with the
27     -- difference to be applied to get the old contents.
28     --
29     -- So if a diff array is used in a single-threaded style,
30     -- i.e. after '//' application the old version is no longer used,
31     -- @a'!'i@ takes O(1) time and @a '//' d@ takes O(@length d@).
32     -- Accessing elements of older versions gradually becomes slower.
33     --
34     -- Updating an array which is not current makes a physical copy.
35     -- The resulting array is unlinked from the old family. So you
36     -- can obtain a version which is guaranteed to be current and
37     -- thus have fast element access by @a '//' []@.
38
39     -- Possible improvement for the future (not implemented now):
40     -- make it possible to say "I will make an update now, but when
41     -- I later return to the old version, I want it to mutate back
42     -- instead of being copied".
43
44     IOToDiffArray, -- data IOToDiffArray
45                    --     (a :: * -> * -> *) -- internal mutable array
46                    --     (i :: *)           -- indices
47                    --     (e :: *)           -- elements
48
49     -- | Type synonyms for the two most important IO array types.
50
51     -- Two most important diff array types are fully polymorphic
52     -- lazy boxed DiffArray:
53     DiffArray,     -- = IOToDiffArray IOArray
54     -- ...and strict unboxed DiffUArray, working only for elements
55     -- of primitive types but more compact and usually faster:
56     DiffUArray,    -- = IOToDiffArray IOUArray
57
58     -- * Overloaded immutable array interface
59     
60     -- | Module "Data.Array.IArray" provides the interface of diff arrays.
61     -- They are instances of class 'IArray'.
62     module Data.Array.IArray,
63
64     -- * Low-level interface
65
66     -- | These are really internal functions, but you will need them
67     -- to make further 'IArray' instances of various diff array types
68     -- (for either more 'MArray' types or more unboxed element types).
69     newDiffArray, readDiffArray, replaceDiffArray
70     )
71     where
72
73 ------------------------------------------------------------------------
74 -- Imports.
75
76 import Prelude
77
78 import Data.Ix
79 import Data.Array.Base
80 import Data.Array.IArray
81 import Data.Array.IO
82
83 import Foreign.Ptr        ( Ptr, FunPtr )
84 import Foreign.StablePtr  ( StablePtr )
85 import Data.Int           ( Int8,  Int16,  Int32,  Int64 )
86 #ifdef __GLASGOW_HASKELL__
87 import Data.Word          ( Word )
88 #endif
89 import Data.Word          ( Word8, Word16, Word32, Word64 )
90
91 import System.IO.Unsafe   ( unsafePerformIO )
92 import Control.Exception  ( evaluate )
93 import Control.Concurrent.MVar ( MVar, newMVar, takeMVar, putMVar, readMVar )
94
95 ------------------------------------------------------------------------
96 -- Diff array types.
97
98 -- | An arbitrary 'MArray' type living in the 'IO' monad can be converted
99 -- to a diff array.
100
101 newtype IOToDiffArray a i e =
102     DiffArray {varDiffArray :: MVar (DiffArrayData a i e)}
103
104 -- Internal representation: either a mutable array, or a link to
105 -- another diff array patched with a list of index+element pairs.
106 data DiffArrayData a i e = Current (a i e)
107                          | Diff (IOToDiffArray a i e) [(Int, e)]
108
109 -- | Fully polymorphic lazy boxed diff array.
110 type DiffArray  = IOToDiffArray IOArray
111
112 -- | Strict unboxed diff array, working only for elements
113 -- of primitive types but more compact and usually faster than 'DiffArray'.
114 type DiffUArray = IOToDiffArray IOUArray
115
116 -- Having 'MArray a e IO' in instance context would require
117 -- -fallow-undecidable-instances, so each instance is separate here.
118
119 ------------------------------------------------------------------------
120 -- Showing DiffArrays
121
122 instance (Ix ix, Show ix, Show e) => Show (DiffArray ix e) where
123   showsPrec = showsIArray
124
125 instance (Ix ix, Show ix) => Show (DiffUArray ix Char) where
126   showsPrec = showsIArray
127
128 instance (Ix ix, Show ix) => Show (DiffUArray ix Int) where
129   showsPrec = showsIArray
130
131 instance (Ix ix, Show ix) => Show (DiffUArray ix Word) where
132   showsPrec = showsIArray
133
134 instance (Ix ix, Show ix) => Show (DiffUArray ix Float) where
135   showsPrec = showsIArray
136
137 instance (Ix ix, Show ix) => Show (DiffUArray ix Double) where
138   showsPrec = showsIArray
139
140 instance (Ix ix, Show ix) => Show (DiffUArray ix Int8) where
141   showsPrec = showsIArray
142
143 instance (Ix ix, Show ix) => Show (DiffUArray ix Int16) where
144   showsPrec = showsIArray
145
146 instance (Ix ix, Show ix) => Show (DiffUArray ix Int32) where
147   showsPrec = showsIArray
148
149 instance (Ix ix, Show ix) => Show (DiffUArray ix Int64) where
150   showsPrec = showsIArray
151
152 instance (Ix ix, Show ix) => Show (DiffUArray ix Word8) where
153   showsPrec = showsIArray
154
155 instance (Ix ix, Show ix) => Show (DiffUArray ix Word16) where
156   showsPrec = showsIArray
157
158 instance (Ix ix, Show ix) => Show (DiffUArray ix Word32) where
159   showsPrec = showsIArray
160
161 instance (Ix ix, Show ix) => Show (DiffUArray ix Word64) where
162   showsPrec = showsIArray
163
164 ------------------------------------------------------------------------
165 -- Boring instances.
166
167 instance HasBounds a => HasBounds (IOToDiffArray a) where
168     bounds a = unsafePerformIO $ boundsDiffArray a
169
170 instance IArray (IOToDiffArray IOArray) e where
171     unsafeArray   lu ies = unsafePerformIO $ newDiffArray lu ies
172     unsafeAt      a i    = unsafePerformIO $ a `readDiffArray` i
173     unsafeReplace a ies  = unsafePerformIO $ a `replaceDiffArray1` ies
174
175 instance IArray (IOToDiffArray IOUArray) Char where
176     unsafeArray   lu ies = unsafePerformIO $ newDiffArray lu ies
177     unsafeAt      a i    = unsafePerformIO $ a `readDiffArray` i
178     unsafeReplace a ies  = unsafePerformIO $ a `replaceDiffArray2` ies
179
180 instance IArray (IOToDiffArray IOUArray) Int where
181     unsafeArray   lu ies = unsafePerformIO $ newDiffArray lu ies
182     unsafeAt      a i    = unsafePerformIO $ a `readDiffArray` i
183     unsafeReplace a ies  = unsafePerformIO $ a `replaceDiffArray2` ies
184
185 instance IArray (IOToDiffArray IOUArray) Word where
186     unsafeArray   lu ies = unsafePerformIO $ newDiffArray lu ies
187     unsafeAt      a i    = unsafePerformIO $ a `readDiffArray` i
188     unsafeReplace a ies  = unsafePerformIO $ a `replaceDiffArray2` ies
189
190 instance IArray (IOToDiffArray IOUArray) (Ptr a) where
191     unsafeArray   lu ies = unsafePerformIO $ newDiffArray lu ies
192     unsafeAt      a i    = unsafePerformIO $ a `readDiffArray` i
193     unsafeReplace a ies  = unsafePerformIO $ a `replaceDiffArray2` ies
194
195 instance IArray (IOToDiffArray IOUArray) (FunPtr a) where
196     unsafeArray   lu ies = unsafePerformIO $ newDiffArray lu ies
197     unsafeAt      a i    = unsafePerformIO $ a `readDiffArray` i
198     unsafeReplace a ies  = unsafePerformIO $ a `replaceDiffArray2` ies
199
200 instance IArray (IOToDiffArray IOUArray) Float where
201     unsafeArray   lu ies = unsafePerformIO $ newDiffArray lu ies
202     unsafeAt      a i    = unsafePerformIO $ a `readDiffArray` i
203     unsafeReplace a ies  = unsafePerformIO $ a `replaceDiffArray2` ies
204
205 instance IArray (IOToDiffArray IOUArray) Double where
206     unsafeArray   lu ies = unsafePerformIO $ newDiffArray lu ies
207     unsafeAt      a i    = unsafePerformIO $ a `readDiffArray` i
208     unsafeReplace a ies  = unsafePerformIO $ a `replaceDiffArray2` ies
209
210 instance IArray (IOToDiffArray IOUArray) (StablePtr a) where
211     unsafeArray   lu ies = unsafePerformIO $ newDiffArray lu ies
212     unsafeAt      a i    = unsafePerformIO $ a `readDiffArray` i
213     unsafeReplace a ies  = unsafePerformIO $ a `replaceDiffArray2` ies
214
215 instance IArray (IOToDiffArray IOUArray) Int8 where
216     unsafeArray   lu ies = unsafePerformIO $ newDiffArray lu ies
217     unsafeAt      a i    = unsafePerformIO $ a `readDiffArray` i
218     unsafeReplace a ies  = unsafePerformIO $ a `replaceDiffArray2` ies
219
220 instance IArray (IOToDiffArray IOUArray) Int16 where
221     unsafeArray   lu ies = unsafePerformIO $ newDiffArray lu ies
222     unsafeAt      a i    = unsafePerformIO $ a `readDiffArray` i
223     unsafeReplace a ies  = unsafePerformIO $ a `replaceDiffArray2` ies
224
225 instance IArray (IOToDiffArray IOUArray) Int32 where
226     unsafeArray   lu ies = unsafePerformIO $ newDiffArray lu ies
227     unsafeAt      a i    = unsafePerformIO $ a `readDiffArray` i
228     unsafeReplace a ies  = unsafePerformIO $ a `replaceDiffArray2` ies
229
230 instance IArray (IOToDiffArray IOUArray) Int64 where
231     unsafeArray   lu ies = unsafePerformIO $ newDiffArray lu ies
232     unsafeAt      a i    = unsafePerformIO $ a `readDiffArray` i
233     unsafeReplace a ies  = unsafePerformIO $ a `replaceDiffArray2` ies
234
235 instance IArray (IOToDiffArray IOUArray) Word8 where
236     unsafeArray   lu ies = unsafePerformIO $ newDiffArray lu ies
237     unsafeAt      a i    = unsafePerformIO $ a `readDiffArray` i
238     unsafeReplace a ies  = unsafePerformIO $ a `replaceDiffArray2` ies
239
240 instance IArray (IOToDiffArray IOUArray) Word16 where
241     unsafeArray   lu ies = unsafePerformIO $ newDiffArray lu ies
242     unsafeAt      a i    = unsafePerformIO $ a `readDiffArray` i
243     unsafeReplace a ies  = unsafePerformIO $ a `replaceDiffArray2` ies
244
245 instance IArray (IOToDiffArray IOUArray) Word32 where
246     unsafeArray   lu ies = unsafePerformIO $ newDiffArray lu ies
247     unsafeAt      a i    = unsafePerformIO $ a `readDiffArray` i
248     unsafeReplace a ies  = unsafePerformIO $ a `replaceDiffArray2` ies
249
250 instance IArray (IOToDiffArray IOUArray) Word64 where
251     unsafeArray   lu ies = unsafePerformIO $ newDiffArray lu ies
252     unsafeAt      a i    = unsafePerformIO $ a `readDiffArray` i
253     unsafeReplace a ies  = unsafePerformIO $ a `replaceDiffArray2` ies
254
255
256
257 ------------------------------------------------------------------------
258 -- The important stuff.
259
260 newDiffArray :: (MArray a e IO, Ix i)
261              => (i,i)
262              -> [(Int, e)]
263              -> IO (IOToDiffArray a i e)
264 newDiffArray (l,u) ies = do
265     a <- newArray_ (l,u)
266     sequence_ [unsafeWrite a i e | (i, e) <- ies]
267     var <- newMVar (Current a)
268     return (DiffArray var)
269
270 readDiffArray :: (MArray a e IO, Ix i)
271               => IOToDiffArray a i e
272               -> Int
273               -> IO e
274 a `readDiffArray` i = do
275     d <- readMVar (varDiffArray a)
276     case d of
277         Current a'  -> unsafeRead a' i
278         Diff a' ies -> maybe (readDiffArray a' i) return (lookup i ies)
279
280 replaceDiffArray :: (MArray a e IO, Ix i)
281                 => IOToDiffArray a i e
282                 -> [(Int, e)]
283                 -> IO (IOToDiffArray a i e)
284 a `replaceDiffArray` ies = do
285     d <- takeMVar (varDiffArray a)
286     case d of
287         Current a' -> case ies of
288             [] -> do
289                 -- We don't do the copy when there is nothing to change
290                 -- and this is the current version. But see below.
291                 putMVar (varDiffArray a) d
292                 return a
293             _:_ -> do
294                 diff <- sequence [do e <- unsafeRead a' i; return (i, e)
295                                   | (i, _) <- ies]
296                 sequence_ [unsafeWrite a' i e | (i, e) <- ies]
297                 var' <- newMVar (Current a')
298                 putMVar (varDiffArray a) (Diff (DiffArray var') diff)
299                 return (DiffArray var')
300         Diff _ _ -> do
301             -- We still do the copy when there is nothing to change
302             -- but this is not the current version. So you can use
303             -- 'a // []' to make sure that the resulting array has
304             -- fast element access.
305             putMVar (varDiffArray a) d
306             a' <- thawDiffArray a
307                 -- thawDiffArray gives a fresh array which we can
308                 -- safely mutate.
309             sequence_ [unsafeWrite a' i e | (i, e) <- ies]
310             var' <- newMVar (Current a')
311             return (DiffArray var')
312
313 -- The elements of the diff list might recursively reference the
314 -- array, so we must seq them before taking the MVar to avoid
315 -- deadlock.
316 replaceDiffArray1 :: (MArray a e IO, Ix i)
317                 => IOToDiffArray a i e
318                 -> [(Int, e)]
319                 -> IO (IOToDiffArray a i e)
320 a `replaceDiffArray1` ies = do
321     mapM_ (evaluate . fst) ies
322     a `replaceDiffArray` ies
323
324 -- If the array contains unboxed elements, then the elements of the
325 -- diff list may also recursively reference the array from inside
326 -- replaceDiffArray, so we must seq them too.
327 replaceDiffArray2 :: (MArray a e IO, Ix i)
328                 => IOToDiffArray a i e
329                 -> [(Int, e)]
330                 -> IO (IOToDiffArray a i e)
331 a `replaceDiffArray2` ies = do
332     mapM_ (\(a,b) -> do evaluate a; evaluate b) ies
333     a `replaceDiffArray` ies
334
335
336 boundsDiffArray :: (HasBounds a, Ix ix)
337                 => IOToDiffArray a ix e
338                 -> IO (ix,ix)
339 boundsDiffArray a = do
340     d <- readMVar (varDiffArray a)
341     case d of
342         Current a' -> return (bounds a')
343         Diff a' _  -> boundsDiffArray a'
344
345 freezeDiffArray :: (MArray a e IO, Ix ix)
346                 => a ix e
347                 -> IO (IOToDiffArray a ix e)
348 freezeDiffArray a = case bounds a of
349   (l,u) -> do
350     a' <- newArray_ (l,u)
351     sequence_ [unsafeRead a i >>= unsafeWrite a' i | i <- [0 .. rangeSize (l,u) - 1]]
352     var <- newMVar (Current a')
353     return (DiffArray var)
354
355 {-# RULES
356 "freeze/DiffArray" freeze = freezeDiffArray
357     #-}
358
359 -- unsafeFreezeDiffArray is really unsafe. Better don't use the old
360 -- array at all after freezing. The contents of the source array will
361 -- be changed when '//' is applied to the resulting array.
362
363 unsafeFreezeDiffArray :: (MArray a e IO, Ix ix)
364                       => a ix e
365                       -> IO (IOToDiffArray a ix e)
366 unsafeFreezeDiffArray a = do
367     var <- newMVar (Current a)
368     return (DiffArray var)
369
370 {-# RULES
371 "unsafeFreeze/DiffArray" unsafeFreeze = unsafeFreezeDiffArray
372     #-}
373
374 thawDiffArray :: (MArray a e IO, Ix ix)
375               => IOToDiffArray a ix e
376               -> IO (a ix e)
377 thawDiffArray a = do
378     d <- readMVar (varDiffArray a)
379     case d of
380         Current a' -> case bounds a' of
381           (l,u) -> do
382             a'' <- newArray_ (l,u)
383             sequence_ [unsafeRead a' i >>= unsafeWrite a'' i | i <- [0 .. rangeSize (l,u) - 1]]
384             return a''
385         Diff a' ies -> do
386             a'' <- thawDiffArray a'
387             sequence_ [unsafeWrite a'' i e | (i, e) <- ies]
388             return a''
389
390 {-# RULES
391 "thaw/DiffArray" thaw = thawDiffArray
392     #-}
393
394 -- unsafeThawDiffArray is really unsafe. Better don't use the old
395 -- array at all after thawing. The contents of the resulting array
396 -- will be changed when '//' is applied to the source array.
397
398 unsafeThawDiffArray :: (MArray a e IO, Ix ix)
399                     => IOToDiffArray a ix e
400                     -> IO (a ix e)
401 unsafeThawDiffArray a = do
402     d <- readMVar (varDiffArray a)
403     case d of
404         Current a'  -> return a'
405         Diff a' ies -> do
406             a'' <- unsafeThawDiffArray a'
407             sequence_ [unsafeWrite a'' i e | (i, e) <- ies]
408             return a''
409
410 {-# RULES
411 "unsafeThaw/DiffArray" unsafeThaw = unsafeThawDiffArray
412     #-}