1 {-# OPTIONS_GHC -XNoImplicitPrelude #-}
2 -----------------------------------------------------------------------------
4 -- Module : Foreign.C.String
5 -- Copyright : (c) The FFI task force 2001
6 -- License : BSD-style (see the file libraries/base/LICENSE)
8 -- Maintainer : ffi@haskell.org
9 -- Stability : provisional
10 -- Portability : portable
12 -- Utilities for primitive marshalling of C strings.
14 -- The marshalling converts each Haskell character, representing a Unicode
15 -- code point, to one or more bytes in a manner that, by default, is
16 -- determined by the current locale. As a consequence, no guarantees
17 -- can be made about the relative length of a Haskell string and its
18 -- corresponding C string, and therefore all the marshalling routines
19 -- include memory allocation. The translation between Unicode and the
20 -- encoding of the current locale may be lossy.
22 -----------------------------------------------------------------------------
24 module Foreign.C.String ( -- representation of strings in C
28 CString, -- = Ptr CChar
29 CStringLen, -- = (Ptr CChar, Int)
31 -- ** Using a locale-dependent encoding
33 -- | Currently these functions are identical to their @CAString@ counterparts;
34 -- eventually they will use an encoding determined by the current locale.
36 -- conversion of C strings into Haskell strings
38 peekCString, -- :: CString -> IO String
39 peekCStringLen, -- :: CStringLen -> IO String
41 -- conversion of Haskell strings into C strings
43 newCString, -- :: String -> IO CString
44 newCStringLen, -- :: String -> IO CStringLen
46 -- conversion of Haskell strings into C strings using temporary storage
48 withCString, -- :: String -> (CString -> IO a) -> IO a
49 withCStringLen, -- :: String -> (CStringLen -> IO a) -> IO a
51 charIsRepresentable, -- :: Char -> IO Bool
53 -- ** Using 8-bit characters
55 -- | These variants of the above functions are for use with C libraries
56 -- that are ignorant of Unicode. These functions should be used with
57 -- care, as a loss of information can occur.
59 castCharToCChar, -- :: Char -> CChar
60 castCCharToChar, -- :: CChar -> Char
62 peekCAString, -- :: CString -> IO String
63 peekCAStringLen, -- :: CStringLen -> IO String
64 newCAString, -- :: String -> IO CString
65 newCAStringLen, -- :: String -> IO CStringLen
66 withCAString, -- :: String -> (CString -> IO a) -> IO a
67 withCAStringLen, -- :: String -> (CStringLen -> IO a) -> IO a
71 -- | These variants of the above functions are for use with C libraries
72 -- that encode Unicode using the C @wchar_t@ type in a system-dependent
73 -- way. The only encodings supported are
75 -- * UTF-32 (the C compiler defines @__STDC_ISO_10646__@), or
77 -- * UTF-16 (as used on Windows systems).
79 CWString, -- = Ptr CWchar
80 CWStringLen, -- = (Ptr CWchar, Int)
82 peekCWString, -- :: CWString -> IO String
83 peekCWStringLen, -- :: CWStringLen -> IO String
84 newCWString, -- :: String -> IO CWString
85 newCWStringLen, -- :: String -> IO CWStringLen
86 withCWString, -- :: String -> (CWString -> IO a) -> IO a
87 withCWStringLen, -- :: String -> (CWStringLen -> IO a) -> IO a
91 import Foreign.Marshal.Array
92 import Foreign.C.Types
94 import Foreign.Storable
98 #ifdef __GLASGOW_HASKELL__
104 import Data.Char ( chr, ord )
105 #define unsafeChr chr
108 -----------------------------------------------------------------------------
111 -- representation of strings in C
112 -- ------------------------------
114 -- | A C string is a reference to an array of C characters terminated by NUL.
115 type CString = Ptr CChar
117 -- | A string with explicit length information in bytes instead of a
118 -- terminating NUL (allowing NUL characters in the middle of the string).
119 type CStringLen = (Ptr CChar, Int)
121 -- exported functions
122 -- ------------------
124 -- * the following routines apply the default conversion when converting the
125 -- C-land character encoding into the Haskell-land character encoding
127 -- | Marshal a NUL terminated C string into a Haskell string.
129 peekCString :: CString -> IO String
130 peekCString = peekCAString
132 -- | Marshal a C string with explicit length into a Haskell string.
134 peekCStringLen :: CStringLen -> IO String
135 peekCStringLen = peekCAStringLen
137 -- | Marshal a Haskell string into a NUL terminated C string.
139 -- * the Haskell string may /not/ contain any NUL characters
141 -- * new storage is allocated for the C string and must be
142 -- explicitly freed using 'Foreign.Marshal.Alloc.free' or
143 -- 'Foreign.Marshal.Alloc.finalizerFree'.
145 newCString :: String -> IO CString
146 newCString = newCAString
148 -- | Marshal a Haskell string into a C string (ie, character array) with
149 -- explicit length information.
151 -- * new storage is allocated for the C string and must be
152 -- explicitly freed using 'Foreign.Marshal.Alloc.free' or
153 -- 'Foreign.Marshal.Alloc.finalizerFree'.
155 newCStringLen :: String -> IO CStringLen
156 newCStringLen = newCAStringLen
158 -- | Marshal a Haskell string into a NUL terminated C string using temporary
161 -- * the Haskell string may /not/ contain any NUL characters
163 -- * the memory is freed when the subcomputation terminates (either
164 -- normally or via an exception), so the pointer to the temporary
165 -- storage must /not/ be used after this.
167 withCString :: String -> (CString -> IO a) -> IO a
168 withCString = withCAString
170 -- | Marshal a Haskell string into a C string (ie, character array)
171 -- in temporary storage, with explicit length information.
173 -- * the memory is freed when the subcomputation terminates (either
174 -- normally or via an exception), so the pointer to the temporary
175 -- storage must /not/ be used after this.
177 withCStringLen :: String -> (CStringLen -> IO a) -> IO a
178 withCStringLen = withCAStringLen
180 -- | Determines whether a character can be accurately encoded in a 'CString'.
181 -- Unrepresentable characters are converted to @\'?\'@.
183 -- Currently only Latin-1 characters are representable.
184 charIsRepresentable :: Char -> IO Bool
185 charIsRepresentable c = return (ord c < 256)
187 -- single byte characters
188 -- ----------------------
190 -- ** NOTE: These routines don't handle conversions! **
192 -- | Convert a C byte, representing a Latin-1 character, to the corresponding
193 -- Haskell character.
194 castCCharToChar :: CChar -> Char
195 castCCharToChar ch = unsafeChr (fromIntegral (fromIntegral ch :: Word8))
197 -- | Convert a Haskell character to a C character.
198 -- This function is only safe on the first 256 characters.
199 castCharToCChar :: Char -> CChar
200 castCharToCChar ch = fromIntegral (ord ch)
202 -- | Marshal a NUL terminated C string into a Haskell string.
204 peekCAString :: CString -> IO String
205 #ifndef __GLASGOW_HASKELL__
207 cs <- peekArray0 nUL cp
208 return (cCharsToChars cs)
211 l <- lengthArray0 nUL cp
212 if l <= 0 then return "" else loop "" (l-1)
215 xval <- peekElemOff cp i
216 let val = castCCharToChar xval
217 val `seq` if i <= 0 then return (val:s) else loop (val:s) (i-1)
220 -- | Marshal a C string with explicit length into a Haskell string.
222 peekCAStringLen :: CStringLen -> IO String
223 #ifndef __GLASGOW_HASKELL__
224 peekCAStringLen (cp, len) = do
225 cs <- peekArray len cp
226 return (cCharsToChars cs)
228 peekCAStringLen (cp, len)
229 | len <= 0 = return "" -- being (too?) nice.
230 | otherwise = loop [] (len-1)
233 xval <- peekElemOff cp i
234 let val = castCCharToChar xval
235 -- blow away the coercion ASAP.
236 if (val `seq` (i == 0))
237 then return (val:acc)
238 else loop (val:acc) (i-1)
241 -- | Marshal a Haskell string into a NUL terminated C string.
243 -- * the Haskell string may /not/ contain any NUL characters
245 -- * new storage is allocated for the C string and must be
246 -- explicitly freed using 'Foreign.Marshal.Alloc.free' or
247 -- 'Foreign.Marshal.Alloc.finalizerFree'.
249 newCAString :: String -> IO CString
250 #ifndef __GLASGOW_HASKELL__
251 newCAString = newArray0 nUL . charsToCChars
254 ptr <- mallocArray0 (length str)
256 go [] n = pokeElemOff ptr n nUL
257 go (c:cs) n = do pokeElemOff ptr n (castCharToCChar c); go cs (n+1)
262 -- | Marshal a Haskell string into a C string (ie, character array) with
263 -- explicit length information.
265 -- * new storage is allocated for the C string and must be
266 -- explicitly freed using 'Foreign.Marshal.Alloc.free' or
267 -- 'Foreign.Marshal.Alloc.finalizerFree'.
269 newCAStringLen :: String -> IO CStringLen
270 #ifndef __GLASGOW_HASKELL__
271 newCAStringLen str = newArrayLen (charsToCChars str)
273 newCAStringLen str = do
274 ptr <- mallocArray0 len
276 go [] n = n `seq` return () -- make it strict in n
277 go (c:cs) n = do pokeElemOff ptr n (castCharToCChar c); go cs (n+1)
284 -- | Marshal a Haskell string into a NUL terminated C string using temporary
287 -- * the Haskell string may /not/ contain any NUL characters
289 -- * the memory is freed when the subcomputation terminates (either
290 -- normally or via an exception), so the pointer to the temporary
291 -- storage must /not/ be used after this.
293 withCAString :: String -> (CString -> IO a) -> IO a
294 #ifndef __GLASGOW_HASKELL__
295 withCAString = withArray0 nUL . charsToCChars
298 allocaArray0 (length str) $ \ptr ->
300 go [] n = pokeElemOff ptr n nUL
301 go (c:cs) n = do pokeElemOff ptr n (castCharToCChar c); go cs (n+1)
307 -- | Marshal a Haskell string into a C string (ie, character array)
308 -- in temporary storage, with explicit length information.
310 -- * the memory is freed when the subcomputation terminates (either
311 -- normally or via an exception), so the pointer to the temporary
312 -- storage must /not/ be used after this.
314 withCAStringLen :: String -> (CStringLen -> IO a) -> IO a
315 withCAStringLen str f =
316 #ifndef __GLASGOW_HASKELL__
317 withArrayLen (charsToCChars str) $ \ len ptr -> f (ptr, len)
319 allocaArray len $ \ptr ->
321 go [] n = n `seq` return () -- make it strict in n
322 go (c:cs) n = do pokeElemOff ptr n (castCharToCChar c); go cs (n+1)
330 -- auxiliary definitions
331 -- ----------------------
333 -- C's end of string character
338 -- allocate an array to hold the list and pair it with the number of elements
339 newArrayLen :: Storable a => [a] -> IO (Ptr a, Int)
342 return (a, length xs)
344 #ifndef __GLASGOW_HASKELL__
345 -- cast [CChar] to [Char]
347 cCharsToChars :: [CChar] -> [Char]
348 cCharsToChars xs = map castCCharToChar xs
350 -- cast [Char] to [CChar]
352 charsToCChars :: [Char] -> [CChar]
353 charsToCChars xs = map castCharToCChar xs
356 -----------------------------------------------------------------------------
359 -- representation of wide strings in C
360 -- -----------------------------------
362 -- | A C wide string is a reference to an array of C wide characters
363 -- terminated by NUL.
364 type CWString = Ptr CWchar
366 -- | A wide character string with explicit length information in 'CWchar's
367 -- instead of a terminating NUL (allowing NUL characters in the middle
369 type CWStringLen = (Ptr CWchar, Int)
371 -- | Marshal a NUL terminated C wide string into a Haskell string.
373 peekCWString :: CWString -> IO String
375 cs <- peekArray0 wNUL cp
376 return (cWcharsToChars cs)
378 -- | Marshal a C wide string with explicit length into a Haskell string.
380 peekCWStringLen :: CWStringLen -> IO String
381 peekCWStringLen (cp, len) = do
382 cs <- peekArray len cp
383 return (cWcharsToChars cs)
385 -- | Marshal a Haskell string into a NUL terminated C wide string.
387 -- * the Haskell string may /not/ contain any NUL characters
389 -- * new storage is allocated for the C wide string and must
390 -- be explicitly freed using 'Foreign.Marshal.Alloc.free' or
391 -- 'Foreign.Marshal.Alloc.finalizerFree'.
393 newCWString :: String -> IO CWString
394 newCWString = newArray0 wNUL . charsToCWchars
396 -- | Marshal a Haskell string into a C wide string (ie, wide character array)
397 -- with explicit length information.
399 -- * new storage is allocated for the C wide string and must
400 -- be explicitly freed using 'Foreign.Marshal.Alloc.free' or
401 -- 'Foreign.Marshal.Alloc.finalizerFree'.
403 newCWStringLen :: String -> IO CWStringLen
404 newCWStringLen str = newArrayLen (charsToCWchars str)
406 -- | Marshal a Haskell string into a NUL terminated C wide string using
407 -- temporary storage.
409 -- * the Haskell string may /not/ contain any NUL characters
411 -- * the memory is freed when the subcomputation terminates (either
412 -- normally or via an exception), so the pointer to the temporary
413 -- storage must /not/ be used after this.
415 withCWString :: String -> (CWString -> IO a) -> IO a
416 withCWString = withArray0 wNUL . charsToCWchars
418 -- | Marshal a Haskell string into a NUL terminated C wide string using
419 -- temporary storage.
421 -- * the Haskell string may /not/ contain any NUL characters
423 -- * the memory is freed when the subcomputation terminates (either
424 -- normally or via an exception), so the pointer to the temporary
425 -- storage must /not/ be used after this.
427 withCWStringLen :: String -> (CWStringLen -> IO a) -> IO a
428 withCWStringLen str f =
429 withArrayLen (charsToCWchars str) $ \ len ptr -> f (ptr, len)
431 -- auxiliary definitions
432 -- ----------------------
437 cWcharsToChars :: [CWchar] -> [Char]
438 charsToCWchars :: [Char] -> [CWchar]
440 #ifdef mingw32_HOST_OS
442 -- On Windows, wchar_t is 16 bits wide and CWString uses the UTF-16 encoding.
444 -- coding errors generate Chars in the surrogate range
445 cWcharsToChars = map chr . fromUTF16 . map fromIntegral
447 fromUTF16 (c1:c2:wcs)
448 | 0xd800 <= c1 && c1 <= 0xdbff && 0xdc00 <= c2 && c2 <= 0xdfff =
449 ((c1 - 0xd800)*0x400 + (c2 - 0xdc00) + 0x10000) : fromUTF16 wcs
450 fromUTF16 (c:wcs) = c : fromUTF16 wcs
453 charsToCWchars = foldr utf16Char [] . map ord
456 | c < 0x10000 = fromIntegral c : wcs
457 | otherwise = let c' = c - 0x10000 in
458 fromIntegral (c' `div` 0x400 + 0xd800) :
459 fromIntegral (c' `mod` 0x400 + 0xdc00) : wcs
461 #else /* !mingw32_HOST_OS */
463 cWcharsToChars xs = map castCWcharToChar xs
464 charsToCWchars xs = map castCharToCWchar xs
466 -- These conversions only make sense if __STDC_ISO_10646__ is defined
467 -- (meaning that wchar_t is ISO 10646, aka Unicode)
469 castCWcharToChar :: CWchar -> Char
470 castCWcharToChar ch = chr (fromIntegral ch )
472 castCharToCWchar :: Char -> CWchar
473 castCharToCWchar ch = fromIntegral (ord ch)
475 #endif /* !mingw32_HOST_OS */