Function libconfig::reader::from_stream [] [src]

pub fn from_stream<T: Read>(stream: &mut T) -> Result<Config, ConfigError>

Reads a configuration from a generic stream. Errors can be caused by:

  • An I/O error on stream, in which case no parsing was done
  • A syntax error

If a syntax error is reported, it means that the stream successfully delivered every piece of data, since parsing doesn't start until the whole input is read to memory.

Examples

For educational / demonstration purposes, we can wrap a string inside a Cursor to simulate a stream of data:

use std::io::Cursor;
use config::reader::from_stream;

let sample_conf = "windows=NO;\nlinux = YES;\n";
let mut cursor = Cursor::new(sample_conf.as_bytes());
let parsed = from_stream(&mut cursor);
assert!(parsed.is_ok());

In this example, we do the same, but with a broken conf:

use std::io::Cursor;
use config::reader::from_stream;
use config::error::ConfigErrorKind;

let sample_conf = "windows=\n";
let mut cursor = Cursor::new(sample_conf.as_bytes());
let parsed = from_stream(&mut cursor);
assert!(parsed.is_err());
assert_eq!(parsed.unwrap_err().kind, ConfigErrorKind::ParseError);

The other situation where an error is returned is when the underlying stream yields an I/O error. We can simulate this behavior by implementing a reader that always returns an error:

use std::io::{Read, Cursor};
use std::io::Error as IoError;
use std::io::Result as IoResult;
use std::io::ErrorKind;

use config::reader::from_stream;
use config::error::ConfigErrorKind;

struct BadCursor;

impl Read for BadCursor {
    fn read(&mut self, buf: &mut [u8]) -> IoResult<usize> {
        Err(IoError::new(ErrorKind::Other, "An I/O error has occurred."))
    }
}

let parsed = from_stream(&mut BadCursor);
assert!(parsed.is_err());
assert_eq!(parsed.unwrap_err().kind, ConfigErrorKind::IoError);