serde_codegen_internals/
ctxt.rs

1use std::fmt::Display;
2use std::cell::RefCell;
3
4#[derive(Default)]
5pub struct Ctxt {
6    errors: RefCell<Option<Vec<String>>>,
7}
8
9impl Ctxt {
10    pub fn new() -> Self {
11        Ctxt { errors: RefCell::new(Some(Vec::new())) }
12    }
13
14    pub fn error<T: Display>(&self, msg: T) {
15        self.errors.borrow_mut().as_mut().unwrap().push(msg.to_string());
16    }
17
18    pub fn check(self) -> Result<(), String> {
19        let mut errors = self.errors.borrow_mut().take().unwrap();
20        match errors.len() {
21            0 => Ok(()),
22            1 => Err(errors.pop().unwrap()),
23            n => {
24                let mut msg = format!("{} errors:", n);
25                for err in errors {
26                    msg.push_str("\n\t# ");
27                    msg.push_str(&err);
28                }
29                Err(msg)
30            }
31        }
32    }
33}
34
35impl Drop for Ctxt {
36    fn drop(&mut self) {
37        if self.errors.borrow().is_some() {
38            panic!("forgot to check for errors");
39        }
40    }
41}