on master help sign in
Implement putWord16be
76c9a4aLennart Kolmodin
BitsPut.hs+16−1
@@ -1,6 +1,7 @@
1module BitsPut
1module BitsPut
2 ( putBool
2 ( putBool
3 , putWord8
3 , putWord8
4+ , putWord16be
4 , runBitPut
5 , runBitPut
5 )
6 )
6 where
7 where
@@ -43,7 +44,21 @@ putWord16be n w
43 | otherwise =
44 | otherwise =
44 BitPut $ \s -> PairS () $
45 BitPut $ \s -> PairS () $
45 case s of
46 case s of
47+ -- as n>=9, it's too big to fit into one single byte
48+ -- it'll either use 2 or 3 bytes
49+ -- it'll fit in 2 bytes
50+ (S b t o) | o + n <= 16 -> flush $
51+ let o' = o + n - 8
52+ w' = t .|. fromIntegral (w `shiftR` o')
53+ t' = fromIntegral (w `shiftL` (8-o'))
54+ in (S (b `mappend` B.singleton w') t' o')
55+ -- 3 bytes required
46− (S b t o) | otherwise -> undefined
56+ | otherwise -> flush $
57+ let o' = o + n - 16
58+ w' = t .|. fromIntegral (w `shiftR` (o' + 8))
59+ w'' = fromIntegral ((w `shiftR` o') .&. 0xff)
60+ t' = fromIntegral (w `shiftL` (8-o'))
61+ in (S (b `mappend` B.singleton w' `mappend` B.singleton w'') t' o')
47
62
48flush :: S -> S
63flush :: S -> S
49flush s@(S b w o)
64flush s@(S b w o)