common: Implement Logger::remove_recording().
[gps-watch.git] / src / common / logger.rs
index 8a1c05cd75f89b676635b7a37c991cde1c84688b..9b498ce64a5cec5e7f76be504fab5395a80ac41c 100644 (file)
@@ -38,6 +38,7 @@ const NUM_SECTORS: usize = MEMORY_SIZE / SECTOR_SIZE;
 #[derive(Clone, Copy, PartialEq, Debug)]
 pub enum Error {
     NoSuchRecording,
+    StorageError,
 }
 
 enum SectorFlag {
@@ -666,4 +667,40 @@ impl<'a> Logger<'a> {
             Err(Error::NoSuchRecording)
         }
     }
+
+    ///
+    /// Remove recording @p recording_id.
+    pub fn remove_recording(&mut self, recording_id: u16) -> Result<(), Error> {
+        if let Some(found_index) = (0..NUM_SECTORS).find(|&index| {
+            let sector_header = &self.sector_header[index as usize];
+
+            sector_header.recording_id == recording_id &&
+            sector_header.starts_recording()
+        }) {
+            let mut next_sector = found_index as usize;
+
+            for _ in 0..NUM_SECTORS {
+                let address = next_sector * SECTOR_SIZE;
+
+                if let Err(_) = self.storage.erase(address) {
+                    return Err(Error::StorageError);
+                }
+
+                // Mark this sector as eligible for the next recording
+                // and ensure it won't be picked up by list_recordings().
+                self.read_sector_header(next_sector);
+
+                next_sector += 1;
+                next_sector &= NUM_SECTORS - 1;
+
+                if !self.sector_header[next_sector].belongs_to(recording_id) {
+                    break;
+                }
+            }
+
+            Ok(())
+        } else {
+            Err(Error::NoSuchRecording)
+        }
+    }
 }