From 74b26de743aa35b502980db129238559673f4cab Mon Sep 17 00:00:00 2001 From: Jonathan Lamothe Date: Sat, 6 Jul 2024 20:55:31 -0400 Subject: [PATCH] detect (but don't correct two-bit errors in a Word16 --- src/Hamming.hs | 5 +++-- test/Hamming/Word16Spec.hs | 20 ++++++++++++++++++-- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/src/Hamming.hs b/src/Hamming.hs index b92fac3..410d3b2 100644 --- a/src/Hamming.hs +++ b/src/Hamming.hs @@ -64,8 +64,9 @@ instance Hamming Word16 where ] correctErrors c - | isValid c = Just c - | otherwise = let + | isValid c = Just c + | not (oddParity c) = Nothing + | otherwise = let errorFlags = map (oddParity . (c .&.)) [0xaaaa, 0xcccc, 0xf0f0, 0xff00] flipAddr = foldl diff --git a/test/Hamming/Word16Spec.hs b/test/Hamming/Word16Spec.hs index 56e0b18..2e75abb 100644 --- a/test/Hamming/Word16Spec.hs +++ b/test/Hamming/Word16Spec.hs @@ -21,7 +21,7 @@ License along with this program. If not, see module Hamming.Word16Spec (spec) where -import Data.Bits (shiftL, xor) +import Data.Bits (shiftL, xor, (.|.)) import Data.Word (Word16) import Hamming @@ -68,7 +68,7 @@ correctErrorsSpec = describe "correctErrors" $ mapM_ in it ("should be " ++ show expected) $ actual `shouldBe` expected ) $ ("valid", withChkBits, Just withChkBits) : - singleBitErrors + singleBitErrors ++ doubleBitErrors singleBitErrors :: [(String, Word16, Maybe Word16)] singleBitErrors = map @@ -78,6 +78,22 @@ singleBitErrors = map in ("bad bit " ++ show bit, code, Just withChkBits) ) [0..15] +doubleBitErrors :: [(String, Word16, Maybe Word16)] +doubleBitErrors = + [ ( \(bitA, bitB) -> let + mask = (1 `shiftL` bitA) .|. (1 `shiftL` bitB) + code = withChkBits `xor` mask + in + ( "bad bits " ++ show bitA ++ " & " ++ show bitB + , code + , Nothing + ) + ) (a, b) + | a <- [0..14] + , b <- [1..15] + , a < b + ] + noChkBits :: Word16 noChkBits = 0x34c0