aboutsummaryrefslogtreecommitdiff
path: root/src/crc.rs
diff options
context:
space:
mode:
authorRobin Krahl <robin.krahl@ireas.org>2019-02-20 23:13:38 +0000
committerRobin Krahl <robin.krahl@ireas.org>2019-02-21 00:16:00 +0100
commit853e613769087a4bf67023e42f7fc4f3b92339fb (patch)
treeacfa941c5be18587d0299710b3e77e42666d3212 /src/crc.rs
parent3e31f2f9f6d7d087b136299468a4a2babdf6ccfb (diff)
downloadntw-853e613769087a4bf67023e42f7fc4f3b92339fb.tar.gz
ntw-853e613769087a4bf67023e42f7fc4f3b92339fb.tar.bz2
Split struct Crc into trait Crc and struct Stm32Crc
There are different ways to implement the CRC check: For testing, we might want to calulate the CRC in the software. On STM32 MCUs, we want to use the CRC peripheral. This patch splits the struct Crc into the Crc trait and the Stm32Crc struct implementing Crc using the CRC peripheral. The Nitrokey struct can now accept any Crc implementation.
Diffstat (limited to 'src/crc.rs')
-rw-r--r--src/crc.rs32
1 files changed, 21 insertions, 11 deletions
diff --git a/src/crc.rs b/src/crc.rs
index cfcf982..6219e8c 100644
--- a/src/crc.rs
+++ b/src/crc.rs
@@ -1,23 +1,25 @@
// Copyright 2019 Robin Krahl <robin.krahl@ireas.org>
// SPDX-License-Identifier: GPL-3.0-or-later
+use core::iter::Iterator;
+
use hal::stm32::CRC;
-pub struct Crc {
+pub trait Crc {
+ fn get(&self, data: &[u8]) -> u32 {
+ self.get_u32(data.chunks(4).map(slice_to_u32))
+ }
+
+ fn get_u32<I: Iterator<Item = u32>>(&self, iter: I) -> u32;
+}
+
+pub struct Stm32Crc {
crc: CRC,
}
-impl Crc {
+impl Stm32Crc {
pub fn new(crc: CRC) -> Self {
- Crc { crc }
- }
-
- pub fn get(&self, data: &[u8]) -> u32 {
- self.reset();
- data.chunks(4)
- .map(slice_to_u32)
- .for_each(|val| self.write(val));
- self.read()
+ Self { crc }
}
fn write(&self, val: u32) {
@@ -33,6 +35,14 @@ impl Crc {
}
}
+impl Crc for Stm32Crc {
+ fn get_u32<I: Iterator<Item = u32>>(&self, iter: I) -> u32 {
+ self.reset();
+ iter.for_each(|val| self.write(val));
+ self.read()
+ }
+}
+
fn slice_to_u32(data: &[u8]) -> u32 {
data.iter()
.enumerate()