Skip to content

Commit 90df366

Browse files
committed
Implemented Show for Attribute
Fixed #2. Also added more convenience methods.
1 parent 7c96cb3 commit 90df366

File tree

1 file changed

+46
-0
lines changed

1 file changed

+46
-0
lines changed

src/common.rs

Lines changed: 46 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -107,6 +107,17 @@ impl Name {
107107
}
108108
}
109109

110+
/// Returns a `Name` instance representing qualified name with the
111+
/// given prefix and namespace URI.
112+
#[inline]
113+
pub fn new(name: &str, prefix: &str, namespace: &str) -> Name {
114+
Name {
115+
local_name: name.to_string(),
116+
prefix: Some(prefix.to_string()),
117+
namespace: Some(namespace.to_string())
118+
}
119+
}
120+
110121
/// Returns a slice with namespace prefix of this name, if it is present.
111122
pub fn prefix_ref<'a>(&'a self) -> Option<&'a str> {
112123
match self.prefix {
@@ -123,6 +134,10 @@ impl Name {
123134
}
124135
}
125136

137+
/// Returns correct XML representation of this local name and prefix.
138+
///
139+
/// This method is different from autoderived `to_string()` because it does not
140+
/// include namespace URI in the result.
126141
pub fn to_str_proper(&self) -> String {
127142
match self.prefix {
128143
Some(ref prefix) => format!("{}:{}", prefix, self.local_name),
@@ -143,7 +158,21 @@ pub struct Attribute {
143158
pub value: String
144159
}
145160

161+
impl fmt::Show for Attribute {
162+
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
163+
write!(f, "{}=\"{}\"", self.name, escape_str(self.value.as_slice()))
164+
}
165+
}
166+
146167
impl Attribute {
168+
/// Returns an `Attribute` instance with the given qualified name and value.
169+
#[inline]
170+
pub fn new(name: Name, value: &str) -> Attribute {
171+
Attribute { name: name, value: value.to_string() }
172+
}
173+
174+
/// Returns an `Attribute` instance with plain local name and the given value.
175+
#[inline]
147176
pub fn new_local(name: &str, value: &str) -> Attribute {
148177
Attribute {
149178
name: Name::new_local(name),
@@ -275,3 +304,20 @@ impl<T> OptionOps<T> for Option<T> {
275304
}
276305
}
277306
}
307+
308+
#[cfg(test)]
309+
mod tests {
310+
use super::{Name, Attribute};
311+
312+
#[test]
313+
fn attribute_show() {
314+
let attr = Attribute::new(
315+
Name::new("attribute", "n", "urn:namespace"),
316+
"its value with > & \" ' < weird symbols"
317+
);
318+
assert_eq!(
319+
attr.to_string().as_slice(),
320+
"{urn:namespace}n:attribute=\"its value with &gt; &amp; &quot; &apos; &lt; weird symbols\""
321+
)
322+
}
323+
}

0 commit comments

Comments
 (0)