1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
{-
This file is part of shark-disassembler.
Copyright (C) 2014 Ricardo Wurmus
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
-}
module SHARC.Word48 where
import Text.Printf (printf)
import Data.Word (Word8, Word64)
import Data.Bits ((.&.), (.|.), shiftL, shiftR, testBit)
import Data.Binary.Get
import Control.Monad (replicateM)
data Word48 = Word48 (Word8, Word8, Word8, Word8, Word8, Word8)
instance Show Word48 where
show (Word48 (a,b,c,d,e,f)) =
unwords $ map (printf "0x%02X") [a,b,c,d,e,f]
unpackWord8Word48 :: [Word8] -> Word48
unpackWord8Word48 [a,b,c,d,e,f] = Word48 (f,e,d,c,b,a)
getWord48 :: ([Word8] -> Word48) -> Get Word48
getWord48 p = fmap p $ replicateM 6 getWord8
getPackedWord48 :: Get Word48
getPackedWord48 = getWord48 unpackWord8Word48
word48ToWord64 :: Word48 -> Word64
word48ToWord64 (Word48 (a,b,c,d,e,f)) = fromIntegral a `shiftL` 40 .|.
fromIntegral b `shiftL` 32 .|.
fromIntegral c `shiftL` 24 .|.
fromIntegral d `shiftL` 16 .|.
fromIntegral e `shiftL` 8 .|.
fromIntegral f
-- apply mask and shift result to the very right
-- TODO: find a laxer type signature
cutMask :: Integral n => Word64 -> Word64 -> n
cutMask w mask = fromIntegral . fst $ until p shifter (w .&. mask, mask)
where
-- shift word by as much as we need to shift the mask to the very right
p (x, mask') = mask' `testBit` 0
shifter (x, m) = (x `shiftR` 1, m `shiftR` 1)
|