kodept_core/
code_source.rs1use std::fs::File;
2use std::io::{Cursor, Read, Seek, SeekFrom};
3use std::path::PathBuf;
4
5#[derive(Debug)]
6pub enum CodeSource {
7 Memory {
8 name: String,
9 contents: Cursor<String>,
10 },
11 File {
12 name: PathBuf,
13 file: File,
14 },
15}
16
17impl CodeSource {
18 pub fn memory<S: Into<String>>(name: S, contents: String) -> Self {
19 Self::Memory {
20 name: name.into(),
21 contents: Cursor::new(contents),
22 }
23 }
24
25 pub fn file<S: Into<PathBuf>>(name: S, contents: File) -> Self {
26 Self::File {
27 name: name.into(),
28 file: contents,
29 }
30 }
31
32 #[must_use]
33 pub fn name(&self) -> &str {
34 match self {
35 CodeSource::Memory { name, .. } => name,
36 CodeSource::File { name, .. } => name.to_str().unwrap_or("<unknown location>"),
37 }
38 }
39}
40
41impl Read for CodeSource {
42 fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
43 match self {
44 CodeSource::Memory { contents, .. } => contents.read(buf),
45 CodeSource::File { file, .. } => file.read(buf),
46 }
47 }
48}
49
50impl Seek for CodeSource {
51 fn seek(&mut self, pos: SeekFrom) -> std::io::Result<u64> {
52 match self {
53 CodeSource::Memory { contents, .. } => contents.seek(pos),
54 CodeSource::File { file, .. } => file.seek(pos),
55 }
56 }
57}