1use core::fmt;
2use internment::Intern;
3
4#[derive(Copy, Clone, PartialEq, Eq, Hash)]
5pub struct SrcId(Intern<Vec<String>>);
6
7impl fmt::Display for SrcId {
8 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
9 if self.0.is_empty() {
10 core::write!(f, "?")
11 } else {
12 core::write!(f, "{}", self.0.clone().join("/"))
13 }
14 }
15}
16
17impl fmt::Debug for SrcId {
18 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
19 core::write!(f, "{}", self)
20 }
21}
22
23impl SrcId {
24 #[cfg(test)]
25 pub fn empty() -> Self {
26 SrcId(Intern::new(Vec::new()))
27 }
28
29 pub fn repl() -> Self {
30 SrcId(Intern::new(vec!["repl".to_string()]))
31 }
32 pub fn test() -> Self {
33 SrcId(Intern::new(vec!["test".to_string()]))
34 }
35
36 #[cfg(feature = "std")]
37 pub fn from_path<P: AsRef<std::path::Path>>(path: P) -> Self {
38 SrcId(Intern::new(
39 path.as_ref()
40 .iter()
41 .map(|c| c.to_string_lossy().into_owned())
42 .collect(),
43 ))
44 }
45
46 #[cfg(feature = "std")]
47 pub fn to_path(&self) -> std::path::PathBuf {
48 self.0.iter().map(|e| e.to_string()).collect()
49 }
50}
51impl Default for SrcId {
52 fn default() -> Self {
53 SrcId(Intern::new(vec!["<unknown>".to_string()]))
54 }
55}
56impl From<&str> for SrcId {
57 fn from(s: &str) -> Self {
58 SrcId(Intern::new(vec![s.to_string()]))
59 }
60}
61impl From<String> for SrcId {
62 fn from(s: String) -> Self {
63 SrcId(Intern::new(vec![s]))
64 }
65}
66
67#[cfg(feature = "std")]
68impl From<std::path::PathBuf> for SrcId {
69 fn from(s: std::path::PathBuf) -> Self {
70 SrcId::from_path(s)
71 }
72}