robot_description_builder/
to_rdf.rs

1//! The infrastructure to describe a `Robot` in a robot description format.
2//!
3//! TODO: EXPAND
4// DOCS TODO:
5//  - Module
6//  - to_urdf
7//  - to_sdf
8
9#[cfg(feature = "xml")]
10use quick_xml::Writer;
11#[cfg(feature = "xml")]
12use std::io::{Cursor, Read, Seek};
13
14#[cfg(feature = "urdf")]
15pub mod to_urdf;
16
17#[cfg(feature = "sdf")]
18pub mod to_sdf;
19
20/// A setting for configuring the style of the generated XML representation.
21#[derive(Debug, PartialEq, Eq, Clone, Copy, Default)]
22pub enum XMLMode {
23	/// No indentation in the output XML.
24	#[default]
25	NoIndent,
26	/// Indentation as specified in the output XML.
27	///
28	/// The indentation level will increase with every opening XML element and decreases when a XML element is closed.
29	/// - `char` is the character will be used to indent the elements.
30	/// - `usize` is the amount of character which will be used per indent level.
31	Indent(char, usize),
32}
33
34/// Create a XML-writer with the specified [`XMLMode`].
35#[cfg(feature = "xml")]
36fn make_xml_writer(xml_mode: XMLMode) -> Writer<Cursor<Vec<u8>>> {
37	match xml_mode {
38		XMLMode::NoIndent => Writer::new(Cursor::new(Vec::new())),
39		XMLMode::Indent(c, depth) => {
40			Writer::new_with_indent(Cursor::new(Vec::new()), c as u8, depth)
41		}
42	}
43}
44
45#[cfg(feature = "xml")]
46/// Convert a [`quick_xml::Writer`] to a [`String`].
47///
48/// # Example
49/// ```rust
50/// # use robot_description_builder::{Link, link_data::{Visual, geometry::SphereGeometry}, to_rdf::{xml_writer_to_string, to_urdf::{to_urdf, URDFConfig}}};
51/// let robot = Link::builder("my-link")
52///     .add_visual(
53///         Visual::builder(SphereGeometry::new(4.0))
54///     )
55///     .build_tree()
56///     .to_robot("my-robot");
57///
58/// let writer = to_urdf(&robot, URDFConfig::default()).unwrap();
59/// let urdf_description: String = xml_writer_to_string(writer);
60///
61/// assert_eq!(
62///     urdf_description,
63///     String::from(
64///         "\u{feff}<?xml version=\"1.0\"?><robot name=\"my-robot\"><link name=\"my-link\"><visual><geometry><sphere radius=\"4\"/></geometry></visual></link></robot>"
65///     )
66/// );
67/// ```
68pub fn xml_writer_to_string(writer: Writer<Cursor<Vec<u8>>>) -> String {
69	let mut buffer = writer.into_inner();
70
71	let mut out = String::new();
72	buffer.rewind().unwrap();
73	buffer.read_to_string(&mut out).unwrap();
74
75	out
76}