1use serde::{Deserialize, Serialize};
2use std::{
3 convert::Infallible,
4 fmt,
5 path::{Path, PathBuf},
6 str::FromStr,
7};
8
9#[derive(Clone, PartialOrd, Ord, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
10pub struct SourceId(Vec<String>);
11
12impl fmt::Display for SourceId {
13 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
14 if self.0.is_empty() {
15 write!(f, "?")
16 } else {
17 write!(f, "{}", self.0.clone().join("/"))
18 }
19 }
20}
21
22impl fmt::Debug for SourceId {
23 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
24 write!(f, "{}", self)
25 }
26}
27
28impl SourceId {
29 pub fn empty() -> Self {
30 SourceId(Vec::new())
31 }
32
33 pub fn repl() -> Self {
34 SourceId(vec!["repl".to_string()])
35 }
36
37 pub fn from_path<P: AsRef<Path>>(path: P) -> Self {
38 SourceId(
39 path.as_ref()
40 .iter()
41 .map(|c| c.to_string_lossy().into_owned())
42 .collect(),
43 )
44 }
45
46 pub fn to_path(&self) -> PathBuf {
47 self.0.iter().map(|e| e.to_string()).collect()
48 }
49}
50
51impl FromStr for SourceId {
52 type Err = Infallible;
53
54 fn from_str(s: &str) -> Result<Self, Self::Err> {
55 Ok(SourceId(vec![s.to_string()]))
56 }
57}