Implement "TypeLevelReasoning" proposal at wiki:TypeLevelReasoning
[packages/base.git] / Data / Word.hs
1 {-# LANGUAGE Safe #-}
2 {-# LANGUAGE CPP, NoImplicitPrelude #-}
3
4 -----------------------------------------------------------------------------
5 -- |
6 -- Module : Data.Word
7 -- Copyright : (c) The University of Glasgow 2001
8 -- License : BSD-style (see the file libraries/base/LICENSE)
9 --
10 -- Maintainer : libraries@haskell.org
11 -- Stability : experimental
12 -- Portability : portable
13 --
14 -- Unsigned integer types.
15 --
16 -----------------------------------------------------------------------------
17
18 module Data.Word
19 (
20 -- * Unsigned integral types
21
22 Word,
23 Word8, Word16, Word32, Word64,
24
25 -- * byte swapping
26 byteSwap16, byteSwap32, byteSwap64,
27
28 -- * Notes
29
30 -- $notes
31 ) where
32
33 #ifdef __GLASGOW_HASKELL__
34 import GHC.Word
35 #endif
36
37 #ifdef __HUGS__
38 import Hugs.Word
39
40 byteSwap16 :: Word16 -> Word16
41 byteSwap16 w = (w `shift` -8) .|. (w `shift` 8)
42
43 byteSwap32 :: Word32 -> Word32
44 byteSwap32 w =
45 (w `shift` -24) .|. (w `shift` 24)
46 .|. ((w `shift` -8) .&. 0xff00) .|. ((w .&. 0xff00) `shift` 8)
47
48 byteSwap64 :: Word64 -> Word64
49 byteSwap64 w =
50 (w `shift` -56) .|. (w `shift` 56)
51 .|. ((w `shift` -40) .&. 0xff00) .|. ((w .&. 0xff00) `shift` 40)
52 .|. ((w `shift` -24) .&. 0xff0000) .|. ((w .&. 0xff0000) `shift` 24)
53 .|. ((w `shift` -8) .&. 0xff000000) .|. ((w .&. 0xff000000) `shift` 8)
54 #endif
55
56 {- $notes
57
58 * All arithmetic is performed modulo 2^n, where n is the number of
59 bits in the type. One non-obvious consequence of this is that 'Prelude.negate'
60 should /not/ raise an error on negative arguments.
61
62 * For coercing between any two integer types, use
63 'Prelude.fromIntegral', which is specialized for all the
64 common cases so should be fast enough. Coercing word types to and
65 from integer types preserves representation, not sign.
66
67 * It would be very natural to add a type @Natural@ providing an unbounded
68 size unsigned integer, just as 'Prelude.Integer' provides unbounded
69 size signed integers. We do not do that yet since there is no demand
70 for it.
71
72 * The rules that hold for 'Prelude.Enum' instances over a bounded type
73 such as 'Prelude.Int' (see the section of the Haskell report dealing
74 with arithmetic sequences) also hold for the 'Prelude.Enum' instances
75 over the various 'Word' types defined here.
76
77 * Right and left shifts by amounts greater than or equal to the width
78 of the type result in a zero result. This is contrary to the
79 behaviour in C, which is undefined; a common interpretation is to
80 truncate the shift count to the width of the type, for example @1 \<\<
81 32 == 1@ in some C implementations.
82 -}
83