1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
//! Navigate, modify and initialize the [`Schema`]

pub mod safe;
mod self_referential;

pub use {
	safe::{BuildSchemaFromApacheSchemaError, ParseSchemaError},
	self_referential::*,
};

impl std::str::FromStr for Schema {
	type Err = ParseSchemaError;
	fn from_str(s: &str) -> Result<Self, Self::Err> {
		let safe_schema: safe::Schema = s.parse()?;
		Ok(safe_schema.into())
	}
}

impl Schema {
	/// Attempt to convert a [`Schema`](apache_avro::Schema) from the
	/// `apache-avro` crate into a [`Schema`]
	pub fn from_apache_schema(
		apache_schema: &apache_avro::Schema,
	) -> Result<Self, BuildSchemaFromApacheSchemaError> {
		let safe_schema = safe::Schema::from_apache_schema(apache_schema)?;
		Ok(safe_schema.into())
	}
}

/// Component of a [`SchemaNode`]
#[derive(Clone, Debug)]
pub struct Enum {
	pub symbols: Vec<String>,
	pub name: Name,
}

/// Component of a [`SchemaNode`]
#[derive(Clone, Debug)]
pub struct Fixed {
	pub size: usize,
	pub name: Name,
}

/// Component of a [`SchemaNode`]
#[derive(Clone, Debug)]
pub struct Decimal {
	pub precision: usize,
	pub scale: u32,
	pub repr: DecimalRepr,
}
#[derive(Clone, Debug)]
pub enum DecimalRepr {
	Bytes,
	Fixed(Fixed),
}

/// Schema component for named variants of a [`SchemaNode`]
#[derive(Debug, Clone)]
pub struct Name {
	fully_qualified_name: String,
	namespace_delimiter_idx: Option<usize>,
}

impl Name {
	pub fn name(&self) -> &str {
		match self.namespace_delimiter_idx {
			None => &self.fully_qualified_name,
			Some(delimiter_idx) => &self.fully_qualified_name[delimiter_idx + 1..],
		}
	}

	pub fn namespace(&self) -> Option<&str> {
		self.namespace_delimiter_idx
			.map(|idx| &self.fully_qualified_name[..idx])
	}

	pub fn fully_qualified_name(&self) -> &str {
		&self.fully_qualified_name
	}
}