]> git.scottworley.com Git - voter/commitdiff
Don't ignore errors while reading vote tally
authorScott Worley <scottworley@scottworley.com>
Sun, 7 Apr 2024 12:29:43 +0000 (05:29 -0700)
committerScott Worley <scottworley@scottworley.com>
Sun, 7 Apr 2024 13:13:09 +0000 (06:13 -0700)
src/main.rs

index fcb16c7e6805138c8899d706d3097878b05bba59..865fcb864ec5bf6497a6ac96c42d9174030345d5 100644 (file)
@@ -53,28 +53,32 @@ fn get_voter(request: &cgi::Request) -> Result<&[u8], cgi::Response> {
 
 fn tally_votes(dir: &Path) -> std::io::Result<HashMap<String, HashSet<String>>> {
     let mut tally: HashMap<String, HashSet<String>> = HashMap::new();
-    if let Ok(vfile) = std::fs::File::open(dir.to_owned().join("votes")) {
-        for liner in std::io::BufReader::new(vfile).lines() {
-            let line = liner?;
-            if let Some((voter, datum)) = line.split_once(' ') {
-                if voter.len() == COOKIE_LENGTH {
-                    if let Some((vote, candidate)) = datum.split_once(' ') {
-                        if vote == "0" {
-                            if let Some(entry) = tally.get_mut(candidate) {
-                                entry.remove(voter);
+    match std::fs::File::open(dir.to_owned().join("votes")) {
+        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(tally),
+        Err(e) => Err(e),
+        Ok(vfile) => {
+            for liner in std::io::BufReader::new(vfile).lines() {
+                let line = liner?;
+                if let Some((voter, datum)) = line.split_once(' ') {
+                    if voter.len() == COOKIE_LENGTH {
+                        if let Some((vote, candidate)) = datum.split_once(' ') {
+                            if vote == "0" {
+                                if let Some(entry) = tally.get_mut(candidate) {
+                                    entry.remove(voter);
+                                }
+                            } else if vote == "1" {
+                                tally
+                                    .entry(candidate.to_owned())
+                                    .or_default()
+                                    .insert(voter.to_owned());
                             }
-                        } else if vote == "1" {
-                            tally
-                                .entry(candidate.to_owned())
-                                .or_default()
-                                .insert(voter.to_owned());
                         }
                     }
                 }
             }
+            Ok(tally)
         }
     }
-    Ok(tally)
 }
 
 fn valid_id_char(c: u8) -> bool {