083aa4760cb5d831f148f41be689242b8cde0793
[ghc-base.git] / Data / PackedString.hs
1 -----------------------------------------------------------------------------
2 -- |
3 -- Module      :  Data.PackedString
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 :  portable
10 --
11 -- An efficient implementation of strings.
12 --
13 -----------------------------------------------------------------------------
14
15 -- Original GHC implementation by Bryan O\'Sullivan, 
16 -- rewritten to use UArray by Simon Marlow.
17
18 module Data.PackedString (
19         -- * The @PackedString@ type
20         PackedString,      -- abstract, instances: Eq, Ord, Show, Typeable
21
22          -- * Converting to and from @PackedString@s
23         packString,  -- :: String -> PackedString
24         unpackPS,    -- :: PackedString -> String
25
26 #ifndef __NHC__
27         -- * I\/O with @PackedString@s  
28         hPutPS,      -- :: Handle -> PackedString -> IO ()
29         hGetPS,      -- :: Handle -> Int -> IO PackedString
30 #endif
31
32         -- * List-like manipulation functions
33         nilPS,       -- :: PackedString
34         consPS,      -- :: Char -> PackedString -> PackedString
35         headPS,      -- :: PackedString -> Char
36         tailPS,      -- :: PackedString -> PackedString
37         nullPS,      -- :: PackedString -> Bool
38         appendPS,    -- :: PackedString -> PackedString -> PackedString
39         lengthPS,    -- :: PackedString -> Int
40         indexPS,     -- :: PackedString -> Int -> Char
41         mapPS,       -- :: (Char -> Char) -> PackedString -> PackedString
42         filterPS,    -- :: (Char -> Bool) -> PackedString -> PackedString
43         reversePS,   -- :: PackedString -> PackedString
44         concatPS,    -- :: [PackedString] -> PackedString
45         elemPS,      -- :: Char -> PackedString -> Bool
46         substrPS,    -- :: PackedString -> Int -> Int -> PackedString
47         takePS,      -- :: Int -> PackedString -> PackedString
48         dropPS,      -- :: Int -> PackedString -> PackedString
49         splitAtPS,   -- :: Int -> PackedString -> (PackedString, PackedString)
50
51         foldlPS,     -- :: (a -> Char -> a) -> a -> PackedString -> a
52         foldrPS,     -- :: (Char -> a -> a) -> a -> PackedString -> a
53         takeWhilePS, -- :: (Char -> Bool) -> PackedString -> PackedString
54         dropWhilePS, -- :: (Char -> Bool) -> PackedString -> PackedString
55         spanPS,      -- :: (Char -> Bool) -> PackedString -> (PackedString, PackedString)
56         breakPS,     -- :: (Char -> Bool) -> PackedString -> (PackedString, PackedString)
57         linesPS,     -- :: PackedString -> [PackedString]
58         unlinesPS,   -- :: [PackedString] -> PackedString
59         wordsPS,     -- :: PackedString -> [PackedString]
60         unwordsPS,   -- :: [PackedString] -> PackedString
61         splitPS,     -- :: Char -> PackedString -> [PackedString]
62         splitWithPS, -- :: (Char -> Bool) -> PackedString -> [PackedString]
63
64         joinPS,      -- :: PackedString -> [PackedString] -> PackedString
65
66     ) where
67
68 import Prelude
69
70 #ifndef __NHC__
71
72 import Data.Array.Unboxed
73 import Data.Array.IO
74 import Data.Dynamic
75 import Data.Char
76
77 import System.IO
78
79 -- -----------------------------------------------------------------------------
80 -- PackedString type declaration
81
82 -- | A space-efficient representation of a 'String', which supports various
83 -- efficient operations.  A 'PackedString' contains full Unicode 'Char's.
84 newtype PackedString = PS (UArray Int Char)
85
86 instance Eq PackedString where
87    (PS x) == (PS y)  =  x == y
88
89 instance Ord PackedString where
90     compare (PS x) (PS y) = compare x y
91
92 --instance Read PackedString: ToDo
93
94 instance Show PackedString where
95     showsPrec p ps r = showsPrec p (unpackPS ps) r
96
97 #include "Typeable.h"
98 INSTANCE_TYPEABLE0(PackedString,packedStringTc,"PackedString")
99
100 -- -----------------------------------------------------------------------------
101 -- Constructor functions
102
103 -- | The 'nilPS' value is the empty string.
104 nilPS :: PackedString
105 nilPS = PS (array (0,-1) [])
106
107 -- | The 'consPS' function prepends the given character to the
108 -- given string.
109 consPS :: Char -> PackedString -> PackedString
110 consPS c cs = packString (c : (unpackPS cs)) -- ToDo:better
111
112 -- | Convert a 'String' into a 'PackedString'
113 packString :: String -> PackedString
114 packString str = packNChars (length str) str
115
116 -- | The 'packNChars' function creates a 'PackedString' out of the
117 -- first @len@ elements of the given 'String'.
118 packNChars :: Int -> [Char] -> PackedString
119 packNChars len str = PS (array (0,len-1) (zip [0..] str))
120
121 -- -----------------------------------------------------------------------------
122 -- Destructor functions (taking PackedStrings apart)
123
124 -- | Convert a 'PackedString' into a 'String'
125 unpackPS :: PackedString -> String
126 unpackPS (PS ps) = elems ps
127
128 -- -----------------------------------------------------------------------------
129 -- List-mimicking functions for PackedStrings
130
131 -- | The 'lengthPS' function returns the length of the input list.  Analogous to 'length'.
132 lengthPS :: PackedString -> Int
133 lengthPS (PS ps) = rangeSize (bounds ps)
134
135 -- | The 'indexPS' function returns the character in the string at the given position.
136 indexPS :: PackedString -> Int -> Char
137 indexPS (PS ps) i = ps ! i
138
139 -- | The 'headPS' function returns the first element of a 'PackedString' or throws an
140 -- error if the string is empty.
141 headPS :: PackedString -> Char
142 headPS ps
143   | nullPS ps = error "Data.PackedString.headPS: head []"
144   | otherwise  = indexPS ps 0
145
146 -- | The 'tailPS' function returns the tail of a 'PackedString' or throws an error
147 -- if the string is empty.
148 tailPS :: PackedString -> PackedString
149 tailPS ps
150   | len <= 0 = error "Data.PackedString.tailPS: tail []"
151   | len == 1 = nilPS
152   | otherwise  = substrPS ps 1 (len - 1)
153   where
154     len = lengthPS ps
155
156 -- | The 'nullPS' function returns True iff the argument is null.
157 nullPS :: PackedString -> Bool
158 nullPS (PS ps) = rangeSize (bounds ps) == 0
159
160 -- | The 'appendPS' function appends the second string onto the first.
161 appendPS :: PackedString -> PackedString -> PackedString
162 appendPS xs ys
163   | nullPS xs = ys
164   | nullPS ys = xs
165   | otherwise  = concatPS [xs,ys]
166
167 -- | The 'mapPS' function applies a function to each character in the string.
168 mapPS :: (Char -> Char) -> PackedString -> PackedString
169 mapPS f (PS ps) = PS (amap f ps)
170
171 -- | The 'filterPS' function filters out the appropriate substring.
172 filterPS :: (Char -> Bool) -> PackedString -> PackedString {-or String?-}
173 filterPS pred ps = packString (filter pred (unpackPS ps))
174
175 -- | The 'foldlPS' function behaves like 'foldl' on 'PackedString's.
176 foldlPS :: (a -> Char -> a) -> a -> PackedString -> a
177 foldlPS f b ps = foldl f b (unpackPS ps)
178
179 -- | The 'foldrPS' function behaves like 'foldr' on 'PackedString's.
180 foldrPS :: (Char -> a -> a) -> a -> PackedString -> a
181 foldrPS f v ps = foldr f v (unpackPS ps)
182
183 -- | The 'takePS' function takes the first @n@ characters of a 'PackedString'.
184 takePS :: Int -> PackedString -> PackedString
185 takePS n ps = substrPS ps 0 (n-1)
186
187 -- | The 'dropPS' function drops the first @n@ characters of a 'PackedString'.
188 dropPS  :: Int -> PackedString -> PackedString
189 dropPS n ps = substrPS ps n (lengthPS ps - 1)
190
191 -- | The 'splitWithPS' function splits a 'PackedString' at a given index.
192 splitAtPS :: Int -> PackedString -> (PackedString, PackedString)
193 splitAtPS  n ps  = (takePS n ps, dropPS n ps)
194
195 -- | The 'takeWhilePS' function is analogous to the 'takeWhile' function.
196 takeWhilePS :: (Char -> Bool) -> PackedString -> PackedString
197 takeWhilePS pred ps = packString (takeWhile pred (unpackPS ps))
198
199 -- | The 'dropWhilePS' function is analogous to the 'dropWhile' function.
200 dropWhilePS :: (Char -> Bool) -> PackedString -> PackedString
201 dropWhilePS pred ps = packString (dropWhile pred (unpackPS ps))
202
203 -- | The 'elemPS' function returns True iff the given element is in the string.
204 elemPS :: Char -> PackedString -> Bool
205 elemPS c ps = c `elem` unpackPS ps
206
207 -- | The 'spanPS' function returns a pair containing the result of
208 -- running both 'takeWhilePS' and 'dropWhilePS'.
209 spanPS :: (Char -> Bool) -> PackedString -> (PackedString, PackedString)
210 spanPS  p ps = (takeWhilePS p ps, dropWhilePS p ps)
211
212 -- | The 'breakPS' function breaks a string at the first position which
213 -- satisfies the predicate.
214 breakPS :: (Char -> Bool) -> PackedString -> (PackedString, PackedString)
215 breakPS p ps = spanPS (not . p) ps
216
217 -- | The 'linesPS' function splits the input on line-breaks.
218 linesPS :: PackedString -> [PackedString]
219 linesPS ps = splitPS '\n' ps
220
221 -- | The 'unlinesPS' function concatenates the input list after
222 -- interspersing newlines.
223 unlinesPS :: [PackedString] -> PackedString
224 unlinesPS = joinPS (packString "\n")
225
226 -- | The 'wordsPS' function is analogous to the 'words' function.
227 wordsPS :: PackedString -> [PackedString]
228 wordsPS ps = filter (not.nullPS) (splitWithPS isSpace ps)
229
230 -- | The 'unwordsPS' function is analogous to the 'unwords' function.
231 unwordsPS :: [PackedString] -> PackedString
232 unwordsPS = joinPS (packString " ")
233
234 -- | The 'reversePS' function reverses the string.
235 reversePS :: PackedString -> PackedString
236 reversePS ps = packString (reverse (unpackPS ps))
237
238 -- | The 'concatPS' function concatenates a list of 'PackedString's.
239 concatPS :: [PackedString] -> PackedString
240 concatPS pss = packString (concat (map unpackPS pss))
241
242 ------------------------------------------------------------
243
244 -- | The 'joinPS' function takes a 'PackedString' and a list of 'PackedString's
245 -- and concatenates the list after interspersing the first argument between
246 -- each element of the list.
247 joinPS :: PackedString -> [PackedString] -> PackedString
248 joinPS filler pss = concatPS (splice pss)
249  where
250   splice []  = []
251   splice [x] = [x]
252   splice (x:y:xs) = x:filler:splice (y:xs)
253
254 -- ToDo: the obvious generalisation
255 {-
256   Some properties that hold:
257
258   * splitPS x ls = ls'   
259       where False = any (map (x `elemPS`) ls')
260
261   * joinPS (packString [x]) (splitPS x ls) = ls
262 -}
263
264 -- | The 'splitPS' function splits the input string on each occurance of the given 'Char'.
265 splitPS :: Char -> PackedString -> [PackedString]
266 splitPS c = splitWithPS (== c)
267
268 -- | The 'splitWithPS' function takes a character predicate and splits the input string
269 -- at each character which satisfies the predicate.
270 splitWithPS :: (Char -> Bool) -> PackedString -> [PackedString]
271 splitWithPS pred (PS ps) =
272  splitify 0
273  where
274   len = lengthPS (PS ps)
275   
276   splitify n 
277    | n >= len = []
278    | otherwise =
279       let
280        break_pt = first_pos_that_satisfies pred ps len n
281       in
282       if break_pt == n then -- immediate match, empty substring
283          nilPS
284          : splitify (break_pt + 1)
285       else 
286          substrPS (PS ps) n (break_pt - 1) -- leave out the matching character
287          : splitify (break_pt + 1)
288
289 first_pos_that_satisfies pred ps len n = 
290    case [ m | m <- [n..len-1], pred (ps ! m) ] of
291         []    -> len
292         (m:_) -> m
293
294 -- -----------------------------------------------------------------------------
295 -- Local utility functions
296
297 -- The definition of @_substrPS@ is essentially:
298 -- @take (end - begin + 1) (drop begin str)@.
299
300 -- | The 'substrPS' function takes a 'PackedString' and two indices
301 -- and returns the substring of the input string between (and including)
302 -- these indices.
303 substrPS :: PackedString -> Int -> Int -> PackedString
304 substrPS (PS ps) begin end = packString [ ps ! i | i <- [begin..end] ]
305
306 -- -----------------------------------------------------------------------------
307 -- hPutPS
308
309 -- | Outputs a 'PackedString' to the specified 'Handle'.
310 --
311 -- NOTE: the representation of the 'PackedString' in the file is assumed to
312 -- be in the ISO-8859-1 encoding.  In other words, only the least signficant
313 -- byte is taken from each character in the 'PackedString'.
314 hPutPS :: Handle -> PackedString -> IO ()
315 hPutPS h (PS ps) = do
316   let l = lengthPS (PS ps)
317   arr <- newArray_ (0, l-1)
318   sequence_ [ writeArray arr i (fromIntegral (ord (ps ! i))) | i <- [0..l-1] ]
319   hPutArray h arr l
320
321 -- -----------------------------------------------------------------------------
322 -- hGetPS
323
324 -- | Read a 'PackedString' directly from the specified 'Handle'.
325 -- This is far more efficient than reading the characters into a 'String'
326 -- and then using 'packString'.  
327 --
328 -- NOTE: as with 'hPutPS', the string representation in the file is 
329 -- assumed to be ISO-8859-1.
330 hGetPS :: Handle -> Int -> IO PackedString
331 hGetPS h i = do
332   arr <- newArray_ (0, i-1)
333   l <- hGetArray h arr i
334   chars <- mapM (\i -> readArray arr i >>= return.chr.fromIntegral) [0..l-1]
335   return (packString chars)
336
337 #else   /* __NHC__ */
338
339 --import Prelude hiding (append, break, concat, cons, drop, dropWhile,
340 --                       filter, foldl, foldr, head, length, lines, map,
341 --                       nil, null, reverse, span, splitAt, subst, tail,
342 --                       take, takeWhile, unlines, unwords, words)
343 -- also hiding: Ix(..), Functor(..)
344 import qualified NHC.PackedString
345 import NHC.PackedString (PackedString,packString,unpackPS)
346 import List (intersperse)
347
348
349 nilPS       :: PackedString
350 consPS      :: Char -> PackedString -> PackedString
351 headPS      :: PackedString -> Char
352 tailPS      :: PackedString -> PackedString
353 nullPS      :: PackedString -> Bool
354 appendPS    :: PackedString -> PackedString -> PackedString
355 lengthPS    :: PackedString -> Int
356 indexPS     :: PackedString -> Int -> Char
357 mapPS       :: (Char -> Char) -> PackedString -> PackedString
358 filterPS    :: (Char -> Bool) -> PackedString -> PackedString
359 reversePS   :: PackedString -> PackedString
360 concatPS    :: [PackedString] -> PackedString
361 elemPS      :: Char -> PackedString -> Bool
362 substrPS    :: PackedString -> Int -> Int -> PackedString
363 takePS      :: Int -> PackedString -> PackedString
364 dropPS      :: Int -> PackedString -> PackedString
365 splitAtPS   :: Int -> PackedString -> (PackedString, PackedString)
366
367 foldlPS     :: (a -> Char -> a) -> a -> PackedString -> a
368 foldrPS     :: (Char -> a -> a) -> a -> PackedString -> a
369 takeWhilePS :: (Char -> Bool) -> PackedString -> PackedString
370 dropWhilePS :: (Char -> Bool) -> PackedString -> PackedString
371 spanPS      :: (Char -> Bool) -> PackedString -> (PackedString, PackedString)
372 breakPS     :: (Char -> Bool) -> PackedString -> (PackedString, PackedString)
373 linesPS     :: PackedString -> [PackedString]
374 unlinesPS   :: [PackedString] -> PackedString
375
376 wordsPS     :: PackedString -> [PackedString]
377 unwordsPS   :: [PackedString] -> PackedString
378 splitPS     :: Char -> PackedString -> [PackedString]
379 splitWithPS :: (Char -> Bool) -> PackedString -> [PackedString]
380 joinPS      :: PackedString -> [PackedString] -> PackedString
381
382 nilPS       = NHC.PackedString.nil
383 consPS      = NHC.PackedString.cons
384 headPS      = NHC.PackedString.head
385 tailPS      = NHC.PackedString.tail
386 nullPS      = NHC.PackedString.null
387 appendPS    = NHC.PackedString.append
388 lengthPS    = NHC.PackedString.length
389 indexPS p i = (unpackPS p) !! i
390 mapPS       = NHC.PackedString.map
391 filterPS    = NHC.PackedString.filter
392 reversePS   = NHC.PackedString.reverse
393 concatPS    = NHC.PackedString.concat
394 elemPS c p  = c `elem` unpackPS p
395 substrPS    = NHC.PackedString.substr
396 takePS      = NHC.PackedString.take
397 dropPS      = NHC.PackedString.drop
398 splitAtPS   = NHC.PackedString.splitAt
399
400 foldlPS     = NHC.PackedString.foldl
401 foldrPS     = NHC.PackedString.foldr
402 takeWhilePS = NHC.PackedString.takeWhile
403 dropWhilePS = NHC.PackedString.dropWhile
404 spanPS      = NHC.PackedString.span
405 breakPS     = NHC.PackedString.break
406 linesPS     = NHC.PackedString.lines
407 unlinesPS   = NHC.PackedString.unlines
408
409 wordsPS     = NHC.PackedString.words
410 unwordsPS   = NHC.PackedString.unwords
411 splitPS c   = splitWithPS (==c)
412 splitWithPS p =
413     map packString . split' p [] . unpackPS
414   where
415     split' :: (Char->Bool) -> String -> String -> [String]
416     split' pred []  []     = []
417     split' pred acc []     = [reverse acc]
418     split' pred acc (x:xs) | pred x    = reverse acc: split' pred [] xs
419                            | otherwise = split' pred (x:acc) xs
420
421 joinPS sep  = concatPS . intersperse sep
422
423 #endif