Skip to content

Commit

Permalink
Apply rustfmt
Browse files Browse the repository at this point in the history
  • Loading branch information
Emilgardis committed Aug 30, 2018
1 parent 5654cb7 commit 60faa4e
Show file tree
Hide file tree
Showing 28 changed files with 636 additions and 466 deletions.
28 changes: 18 additions & 10 deletions src/elementext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
use xmltree::Element;

use types::{Parse, BoolParse};
use failure::ResultExt;
use types::{BoolParse, Parse};

use error::*;

Expand Down Expand Up @@ -36,7 +36,9 @@ impl ElementExt for Element {
String: PartialEq<K>,
{
if let Some(child) = self.get_child(k) {
Ok(Some(child.get_text().map(|s| s.to_owned())?))
Ok(Some(child
.get_text()
.map(|s| s.to_owned())?))
} else {
Ok(None)
}
Expand All @@ -46,7 +48,9 @@ impl ElementExt for Element {
String: PartialEq<K>,
K: ::std::fmt::Display + Clone,
{
self.get_child_text_opt(k.clone())?.ok_or(SVDErrorKind::MissingTag(self.clone(), format!("{}", k)).into(),)
self.get_child_text_opt(k.clone())?.ok_or(
SVDErrorKind::MissingTag(self.clone(), format!("{}", k)).into(),
)
}

/// Get text contained by an XML Element
Expand All @@ -56,25 +60,29 @@ impl ElementExt for Element {
// FIXME: Doesn't look good because SVDErrorKind doesn't format by itself. We already
// capture the element and this information can be used for getting the name
// This would fix ParseError
None => {
Err(SVDErrorKind::EmptyTag(self.clone(), self.name.clone())
.into())
}
None => Err(SVDErrorKind::EmptyTag(
self.clone(),
self.name.clone(),
).into()),
}
}

/// Get a named child element from an XML Element
fn get_child_elem<'a>(&'a self, n: &str) -> Result<&'a Element, SVDError> {
match self.get_child(n) {
Some(s) => Ok(s),
None => Err(SVDErrorKind::MissingTag(self.clone(), n.to_string()).into()),
None => Err(
SVDErrorKind::MissingTag(self.clone(), n.to_string()).into(),
),
}
}

/// Get a u32 value from a named child element
fn get_child_u32(&self, n: &str) -> Result<u32, SVDError> {
let s = self.get_child_elem(n)?;
u32::parse(&s).context(SVDErrorKind::ParseError(self.clone())).map_err(|e| e.into())
u32::parse(&s)
.context(SVDErrorKind::ParseError(self.clone()))
.map_err(|e| e.into())
}

/// Get a bool value from a named child element
Expand All @@ -86,7 +94,7 @@ impl ElementExt for Element {
// Merges the children of two elements, maintaining the name and description of the first
fn merge(&self, r: &Self) -> Self {
let mut n = self.clone();
for c in &r.children {
for c in &r.children {
n.children.push(c.clone());
}
n
Expand Down
22 changes: 16 additions & 6 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,9 @@
//! SVD Errors.
//! This module defines error types and messages for SVD parsing and encoding
use xmltree::{Element, ParseError};
use failure::{Backtrace, Context, Fail};
use std::fmt::{self, Display};

use xmltree::{Element, ParseError};

#[derive(Debug)]
pub struct SVDError {
Expand Down Expand Up @@ -39,11 +38,18 @@ pub enum SVDErrorKind {
UnknownUsageVariant(Element),
#[fail(display = "Expected a <{}>, found ...", _1)]
NotExpectedTag(Element, String),
#[fail(display = "Invalid RegisterCluster (expected register or cluster), found {}", _1)]
#[fail(
display = "Invalid RegisterCluster (expected register or cluster), found {}",
_1
)]
InvalidRegisterCluster(Element, String),
#[fail(display = "Invalid modifiedWriteValues variant, found {}", _1)]
InvalidModifiedWriteValues(Element, String),
#[fail(display = "The content of the element could not be parsed to a boolean value {}: {}", _1, _2)]
#[fail(
display = "The content of the element could not be parsed to a boolean value {}: {}",
_1,
_2
)]
InvalidBooleanValue(Element, String, ::std::str::ParseBoolError),
#[fail(display = "encoding method not implemented for svd object {}", _0)]
EncodeNotImplemented(String),
Expand Down Expand Up @@ -86,7 +92,9 @@ impl SVDError {

impl From<SVDErrorKind> for SVDError {
fn from(kind: SVDErrorKind) -> SVDError {
SVDError { inner: Context::new(kind) }
SVDError {
inner: Context::new(kind),
}
}
}

Expand All @@ -98,6 +106,8 @@ impl From<Context<SVDErrorKind>> for SVDError {

impl From<ParseError> for SVDError {
fn from(e: ParseError) -> SVDError {
SVDError { inner: e.context(SVDErrorKind::FileParseError) }
SVDError {
inner: e.context(SVDErrorKind::FileParseError),
}
}
}
28 changes: 20 additions & 8 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ pub mod svd;
pub use svd::*;
// Error defines SVD error types
pub mod error;
use error::{SVDError};
use error::SVDError;
// Parse defines parsing interfaces
pub mod parse;
use parse::Parse;
Expand Down Expand Up @@ -80,28 +80,41 @@ fn trim_utf8_bom(s: &str) -> &str {

/// Helper to create new base xml elements
#[cfg(feature = "unproven")]
pub (crate) fn new_element(name: &str, text: Option<String>) -> Element {
pub(crate) fn new_element(name: &str, text: Option<String>) -> Element {
Element {
name: String::from(name),
attributes: HashMap::new(),
children: Vec::new(),
text: text,
}
}
}

/// Generic test helper function
/// Takes an array of (item, xml) pairs where the item implements
/// Parse and Encode and tests object encoding and decoding
#[cfg(test)]
#[cfg(feature = "unproven")]
pub fn run_test<T: Parse<Error=SVDError, Object=T> + Encode<Error=SVDError> + ::std::fmt::Debug + PartialEq>(tests: &[(T, &str)]) {
pub fn run_test<
T: Parse<Error = SVDError, Object = T>
+ Encode<Error = SVDError>
+ ::std::fmt::Debug
+ PartialEq,
>(
tests: &[(T, &str)],
) {
for t in tests {
let tree1 = Element::parse(t.1.as_bytes()).unwrap();
let elem = T::parse(&tree1).unwrap();
assert_eq!(elem, t.0, "Error parsing xml` (mismatch between parsed and expected)");
assert_eq!(
elem, t.0,
"Error parsing xml` (mismatch between parsed and expected)"
);
let tree2 = elem.encode().unwrap();
assert_eq!(tree1, tree2, "Error encoding xml (mismatch between encoded and original)");
};
assert_eq!(
tree1, tree2,
"Error encoding xml (mismatch between encoded and original)"
);
}
}

#[cfg(test)]
Expand All @@ -117,4 +130,3 @@ mod tests {
assert_eq!("xyz", trim_utf8_bom("xyz"));
}
}

10 changes: 6 additions & 4 deletions src/parse.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,15 @@ pub trait Parse {
fn parse(&Element) -> Result<Self::Object, Self::Error>;
}


/// Parses an optional child element with the provided name and Parse function
/// Returns an none if the child doesn't exist, Ok(Some(e)) if parsing succeeds,
/// and Err() if parsing fails.
pub fn optional<'a, T>(n: &str, e: &'a Element) -> Result<Option<T::Object>, SVDError>
where T: Parse<Error = SVDError>
pub fn optional<'a, T>(
n: &str,
e: &'a Element,
) -> Result<Option<T::Object>, SVDError>
where
T: Parse<Error = SVDError>,
{
let child = match e.get_child(n) {
Some(c) => c,
Expand All @@ -32,4 +35,3 @@ where T: Parse<Error = SVDError>
Err(e) => Err(e),
}
}

28 changes: 7 additions & 21 deletions src/svd/access.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@

use xmltree::Element;

use elementext::ElementExt;
use types::Parse;
#[cfg(feature = "unproven")]
use encode::Encode;
use error::*;
#[cfg(feature = "unproven")]
use new_element;
use error::*;

use types::Parse;

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Access {
Expand Down Expand Up @@ -63,26 +61,14 @@ mod tests {
#[test]
fn decode_encode() {
let tests = vec![
(
Access::ReadOnly,
"<access>read-only</access>"
),
(
Access::ReadWrite,
"<access>read-write</access>"
),
(Access::ReadOnly, "<access>read-only</access>"),
(Access::ReadWrite, "<access>read-write</access>"),
(
Access::ReadWriteOnce,
"<access>read-writeOnce</access>"
),
(
Access::WriteOnly,
"<access>write-only</access>"
),
(
Access::WriteOnce,
"<access>writeOnce</access>"
"<access>read-writeOnce</access>",
),
(Access::WriteOnly, "<access>write-only</access>"),
(Access::WriteOnce, "<access>writeOnce</access>"),
];

run_test::<Access>(&tests[..]);
Expand Down
26 changes: 11 additions & 15 deletions src/svd/addressblock.rs
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@

#[cfg(feature = "unproven")]
use std::collections::HashMap;

use xmltree::Element;
use elementext::ElementExt;
use xmltree::Element;

use types::Parse;

#[cfg(feature = "unproven")]
use encode::Encode;
use error::SVDError;
#[cfg(feature = "unproven")]
use new_element;
use error::SVDError;

#[derive(Clone, Debug, PartialEq)]
pub struct AddressBlock {
Expand Down Expand Up @@ -57,23 +56,20 @@ mod tests {
use super::*;
use run_test;


#[test]
fn decode_encode() {
let tests = vec![
(
AddressBlock {
offset: 0,
size: 0x00000800,
usage: String::from("registers"),
},
"<addressBlock>
let tests = vec![(
AddressBlock {
offset: 0,
size: 0x00000800,
usage: String::from("registers"),
},
"<addressBlock>
<offset>0</offset>
<size>0x00000800</size>
<usage>registers</usage>
</addressBlock>"
),
];
</addressBlock>",
)];

run_test::<AddressBlock>(&tests[..]);
}
Expand Down
Loading

0 comments on commit 60faa4e

Please sign in to comment.