]> git.proxmox.com Git - cargo.git/blob - vendor/serde_derive_internals-0.16.0/src/ctxt.rs
New upstream version 0.23.0
[cargo.git] / vendor / serde_derive_internals-0.16.0 / src / ctxt.rs
1 // Copyright 2017 Serde Developers
2 //
3 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
4 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
5 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
6 // option. This file may not be copied, modified, or distributed
7 // except according to those terms.
8
9 use std::fmt::Display;
10 use std::cell::RefCell;
11
12 #[derive(Default)]
13 pub struct Ctxt {
14 errors: RefCell<Option<Vec<String>>>,
15 }
16
17 impl Ctxt {
18 pub fn new() -> Self {
19 Ctxt { errors: RefCell::new(Some(Vec::new())) }
20 }
21
22 pub fn error<T: Display>(&self, msg: T) {
23 self.errors
24 .borrow_mut()
25 .as_mut()
26 .unwrap()
27 .push(msg.to_string());
28 }
29
30 pub fn check(self) -> Result<(), String> {
31 let mut errors = self.errors.borrow_mut().take().unwrap();
32 match errors.len() {
33 0 => Ok(()),
34 1 => Err(errors.pop().unwrap()),
35 n => {
36 let mut msg = format!("{} errors:", n);
37 for err in errors {
38 msg.push_str("\n\t# ");
39 msg.push_str(&err);
40 }
41 Err(msg)
42 }
43 }
44 }
45 }
46
47 impl Drop for Ctxt {
48 fn drop(&mut self) {
49 if self.errors.borrow().is_some() {
50 panic!("forgot to check for errors");
51 }
52 }
53 }