Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

demonstrate "refactor error away" pattern #32

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
45 changes: 7 additions & 38 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,40 +1,9 @@
//! This crate contains the implementation for `rwc` (rust word count), named
//! after the `wc -w` Unix utility.
//!
//! This is intended as an example of how I approach error handling in Rust
//! applications with a focus of different error handling strategies for
//! application and library code.
//!
//! Code inside this file demonstrates application code, which annotates errors
//! with context using [`anyhow`].
//!
//! [`anyhow`]: ../anyhow/index.html

#[cfg(test)]
#[macro_use]
extern crate assert_matches;

pub mod wordcounter;

use std::env;
use std::fs::File;

use crate::wordcounter::count_words;
use anyhow::Context;

/// The run function is called from `main()` in [`rwc`].
///
/// It annotates errors from fallible functions (like `File::open` and
/// `count_words`) with `.context()` before propagating them upwards, where
/// `main()` will eventually handle reporting of the error.
///
/// [`rwc`]: ../rwc/index.html
pub fn run() -> anyhow::Result<()> {
for filename in env::args().skip(1).collect::<Vec<String>>() {
let mut reader = File::open(&filename).context(format!("unable to open '{}'", filename))?;
let wordcount =
count_words(&mut reader).context(format!("unable to count words in '{}'", filename))?;
println!("{} {}", wordcount, filename);
pub fn count_words(lines: &mut dyn Iterator<Item = String>) -> u32 {
let mut wordcount = 0;
for line in lines {
for _word in line.split_whitespace() {
wordcount += 1;
}
}
Ok(())
wordcount
}
35 changes: 25 additions & 10 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,28 @@
//! This crate provides the `rwc` (rust word count) binary, named after the `wc
//! -w` Unix utility.
//!
//! This is intended as an example of how I approach error handling in Rust
//! applications with a focus of different error handling strategies for
//! application and library code.
#![feature(iter_map_while)]
use std::{
env,
fs::File,
io::{BufRead, BufReader},
};

fn main() {
if let Err(err) = wordcount::run() {
eprintln!("Error: {:?}", err);
std::process::exit(1);
use anyhow::Context;

fn main() -> anyhow::Result<()> {
for filename in env::args().skip(1).collect::<Vec<String>>() {
let file = File::open(&filename).context(format!("unable to open '{}'", filename))?;
let reader = BufReader::new(file);

let mut err = None;
let mut iter = reader
.lines()
.map_while(|line| line.map_err(|e| err = Some(e)).ok());
let wordcount = wordcount::count_words(&mut iter);
if let Some(err) = err {
return Err(
anyhow::Error::new(err).context(format!("unable to count words in '{}'", filename))
);
}
println!("{} {}", wordcount, filename);
}
Ok(())
}
128 changes: 0 additions & 128 deletions src/wordcounter.rs

This file was deleted.