@@ -30,6 +30,7 @@ module System.OsString.MODULE_NAME
30
30
31
31
-- * String construction
32
32
, encodeUtf
33
+ , unsafeEncodeUtf
33
34
, encodeWith
34
35
, encodeFS
35
36
, fromBytes
@@ -177,7 +178,7 @@ import GHC.IO.Encoding.UTF8 ( mkUTF8 )
177
178
import qualified System.OsString.Data.ByteString.Short as BSP
178
179
#endif
179
180
import GHC.Stack (HasCallStack )
180
- import Prelude (Bool (.. ), Int , Maybe (.. ), IO , String , Either (.. ), fmap , ($) , (.) , mconcat , fromEnum , fromInteger , mempty , fromIntegral , fail , (<$>) , show , either , pure , const , flip )
181
+ import Prelude (Bool (.. ), Int , Maybe (.. ), IO , String , Either (.. ), fmap , ($) , (.) , mconcat , fromEnum , fromInteger , mempty , fromIntegral , fail , (<$>) , show , either , pure , const , flip , error , id )
181
182
import Data.Bifunctor ( bimap )
182
183
import qualified System.OsString.Data.ByteString.Short.Word16 as BS16
183
184
import qualified System.OsString.Data.ByteString.Short as BS8
@@ -189,13 +190,15 @@ import qualified System.OsString.Data.ByteString.Short as BS8
189
190
--
190
191
-- This encodes as UTF16-LE (strictly), which is a pretty good guess.
191
192
--
192
- -- Throws an 'EncodingException' if encoding fails.
193
+ -- Throws an 'EncodingException' if encoding fails. If the input does not
194
+ -- contain surrogate chars, you can use @unsafeEncodeUtf@.
193
195
#else
194
196
-- | Partial unicode friendly encoding.
195
197
--
196
198
-- This encodes as UTF8 (strictly), which is a good guess.
197
199
--
198
- -- Throws an 'EncodingException' if encoding fails.
200
+ -- Throws an 'EncodingException' if encoding fails. If the input does not
201
+ -- contain surrogate chars, you can use 'unsafeEncodeUtf'.
199
202
#endif
200
203
encodeUtf :: MonadThrow m => String -> m PLATFORM_STRING
201
204
#ifdef WINDOWS
@@ -204,6 +207,17 @@ encodeUtf = either throwM pure . encodeWith utf16le
204
207
encodeUtf = either throwM pure . encodeWith utf8
205
208
#endif
206
209
210
+ -- | Unsafe unicode friendly encoding.
211
+ --
212
+ -- Like 'encodeUtf', except it crashes when the input contains
213
+ -- surrogate chars. For sanitized input, this can be useful.
214
+ unsafeEncodeUtf :: HasCallStack => String -> PLATFORM_STRING
215
+ #ifdef WINDOWS
216
+ unsafeEncodeUtf = either (error . displayException) id . encodeWith utf16le
217
+ #else
218
+ unsafeEncodeUtf = either (error . displayException) id . encodeWith utf8
219
+ #endif
220
+
207
221
-- | Encode a 'String' with the specified encoding.
208
222
encodeWith :: TextEncoding
209
223
-> String
0 commit comments