db.rs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. use alloc::string::String;
  2. use alloc::vec::Vec;
  3. use c_str::CStr;
  4. use fs::File;
  5. use header::fcntl;
  6. use io::{self, BufRead, BufReader};
  7. pub enum Separator {
  8. Character(char),
  9. Whitespace,
  10. }
  11. pub struct Db<R: BufRead> {
  12. reader: R,
  13. separator: Separator,
  14. }
  15. impl<R: BufRead> Db<R> {
  16. pub fn new(reader: R, separator: Separator) -> Self {
  17. Db { reader, separator }
  18. }
  19. pub fn read(&mut self) -> io::Result<Option<Vec<String>>> {
  20. let mut line = String::new();
  21. if self.reader.read_line(&mut line)? == 0 {
  22. return Ok(None);
  23. }
  24. let vec = if let Some(not_comment) = line.trim().split('#').next() {
  25. match self.separator {
  26. Separator::Character(c) => not_comment.split(c).map(String::from).collect(),
  27. Separator::Whitespace => not_comment.split_whitespace().map(String::from).collect(),
  28. }
  29. } else {
  30. Vec::new()
  31. };
  32. Ok(Some(vec))
  33. }
  34. }
  35. pub type FileDb = Db<BufReader<File>>;
  36. impl FileDb {
  37. pub fn open(path: &CStr, separator: Separator) -> io::Result<Self> {
  38. let file = File::open(path, fcntl::O_RDONLY | fcntl::O_CLOEXEC)?;
  39. Ok(Db::new(BufReader::new(file), separator))
  40. }
  41. }