Skip to main content

Node

Struct Node 

Source
pub struct Node {
    pub kind: Kind,
    pub name: String,
    pub value: String,
    pub attrs: Vec<(String, String)>,
    pub children: Vec<Node>,
}
Expand description

One node of a description tree.

Fields§

§kind: Kind

What this node holds.

§name: String

The tag name. A text node has no name.

§value: String

The text. An element has no text of its own.

§attrs: Vec<(String, String)>

The attributes of an element, in the order they were written.

No call of the C ABI creates one (include/lsl/xml.h). An attribute reaches the tree only through a document that an inlet reads, and the oracle keeps it, so this keeps it too.

§children: Vec<Node>

The nodes below this one.

Implementations§

Source§

impl Node

Source

pub fn element(name: &str) -> Node

A tag with no content.

Source

pub fn text(value: &str) -> Node

A run of text.

Source

pub fn cdata(value: &str) -> Node

A section of character data.

Source

pub fn append_child(&mut self, name: &str) -> &mut Node

Add a tag below this node and return it.

Examples found in repository?
examples/publish.rs (line 132)
106fn main() {
107    let a = parse();
108    let stream_name = tagged(&a.name, &a.tag);
109    let marker_name = tagged(&format!("{}-Markers", a.name), &a.tag);
110    let suffix = if a.tag.is_empty() {
111        String::new()
112    } else {
113        format!("_{}", a.tag)
114    };
115
116    let mut info = StreamInfo::new(
117        &stream_name,
118        &a.stream_type,
119        a.channels as u32,
120        Format::Float32,
121        a.rate,
122    );
123    // A source identifier lets a consumer find the stream again after a
124    // restart. Without one, no recovery is possible. SPEC.md 10.1.
125    //
126    // The identifier and the tree below match `oracle/publish.c` exactly, so
127    // the three publishers of `oracle/labrecorder.sh` describe one stream and
128    // a plot of one can be compared with a plot of another.
129    info.source_id = format!("{}_publish{suffix}", a.name);
130
131    {
132        let chns = info.desc.append_child("channels");
133        for k in 0..a.channels {
134            let c = chns.append_child("channel");
135            c.append_child_value("label", &label(k));
136            c.append_child_value("unit", "microvolts");
137            c.append_child_value("type", &a.stream_type);
138        }
139    }
140    info.desc
141        .append_child_value("manufacturer", "conformance publisher");
142    let acq = info.desc.append_child("acquisition");
143    acq.append_child_value("model", "publish example");
144
145    let outlet = match Outlet::new(info) {
146        Ok(o) => o,
147        Err(e) => {
148            eprintln!("cannot publish: {e}");
149            std::process::exit(1);
150        }
151    };
152
153    // A marker stream is a second stream: one channel of text, and no rate.
154    // A recorder treats it as events rather than as a signal.
155    let markers = if a.markers {
156        let mut m = StreamInfo::new(&marker_name, "Markers", 1, Format::String, 0.0);
157        m.source_id = format!("{}_markers{suffix}", a.name);
158        match Outlet::new(m) {
159            Ok(o) => Some(o),
160            Err(e) => {
161                eprintln!("cannot publish the markers: {e}");
162                None
163            }
164        }
165    } else {
166        None
167    };
168
169    let published = outlet.info();
170    println!("=== the stream is published");
171    println!("  name          {}", published.name);
172    println!("  type          {}", published.stream_type);
173    println!("  channels      {} float32", published.channel_count);
174    println!("  rate          {} Hz", published.nominal_srate);
175    println!("  source id     {}", published.source_id);
176    println!("  session       {}", published.session_id);
177    println!("  host          {}", published.hostname);
178    println!("  uid           {}", published.uid);
179    let cfg = labstream_net::config::get();
180    let port = |n: u16| {
181        if n == 0 {
182            "none".to_string()
183        } else {
184            n.to_string()
185        }
186    };
187    println!(
188        "  IPv4          data {}  service {}",
189        port(published.v4data_port),
190        port(published.v4service_port)
191    );
192    println!(
193        "  IPv6          data {}  service {}",
194        port(published.v6data_port),
195        port(published.v6service_port)
196    );
197    let which = match (cfg.allow_ipv4, cfg.allow_ipv6) {
198        (true, true) => "IPv4 and IPv6",
199        (true, false) => "IPv4 only",
200        (false, true) => "IPv6 only. A consumer has no other way to reach this stream.",
201        (false, false) => "none. Nothing can reach this stream.",
202    };
203    println!("  protocols     {which}");
204    match &markers {
205        Some(m) => {
206            println!(
207                "  marker stream {}  ({})",
208                m.info().name,
209                m.info().source_id
210            );
211            println!("                one every second, on a zero crossing of channel one");
212            if !m.holds_multicast_port() {
213                println!("  WARNING: the marker stream does not hold the multicast port.");
214            }
215        }
216        None => println!("  marker stream none"),
217    }
218
219    // A query from another machine arrives by multicast or by broadcast. The
220    // outlet joins each group on each local address, so this list is the one
221    // that decides whether another machine can find the stream at all.
222    let addresses = labstream_net::local_ipv4_addresses();
223    println!("\n=== the addresses that carry a query");
224    if addresses.is_empty() {
225        println!("  none found. Another machine will not see this stream.");
226    }
227    for addr in &addresses {
228        println!("  {addr}");
229    }
230    println!("  multicast port {}", cfg.multicast_port);
231    println!("  groups         {}", cfg.multicast_addresses.join(", "));
232    println!("  configuration  {}", cfg.source);
233    if outlet.holds_multicast_port() {
234        println!("  multicast port held by this outlet");
235    } else {
236        println!(
237            "  WARNING: port {} is held by another process on this machine.",
238            cfg.multicast_port
239        );
240        println!("  A multicast query will not reach this outlet. Stop the other");
241        println!("  program, or expect the other machine to find nothing.");
242    }
243
244    println!("\n=== open LabRecorder on the other machine and press Update");
245    println!("  The count below rises when a recorder links the stream.\n");
246
247    let period = if a.rate > 0.0 { 1.0 / a.rate } else { 0.01 };
248    let start = Instant::now();
249    let mut n: u64 = 0;
250    let mut consumers = 0;
251    let mut reported = Instant::now() - Duration::from_secs(10);
252    let mut block: Vec<Sample> = Vec::new();
253
254    loop {
255        if a.seconds > 0.0 && start.elapsed().as_secs_f64() >= a.seconds {
256            println!("\n{n} samples sent. Stopping.");
257            return;
258        }
259
260        let now = outlet.consumer_count();
261        if now != consumers {
262            println!(
263                "  consumers {consumers} -> {now}   after {:.1} s, {n} samples",
264                start.elapsed().as_secs_f64()
265            );
266            consumers = now;
267        }
268        if reported.elapsed() >= Duration::from_secs(5) {
269            println!(
270                "  {:.0} s, {n} samples, {consumers} consumer(s)",
271                start.elapsed().as_secs_f64()
272            );
273            reported = Instant::now();
274        }
275
276        // The value of a channel comes from the sample number, so a recording
277        // can be tested later. The last channel holds the number itself.
278        let t = n as f64 / a.rate.max(1.0);
279        let values: Vec<Value> = (0..a.channels)
280            .map(|k| {
281                if k + 1 == a.channels {
282                    Value::F32(n as f32)
283                } else {
284                    let hz = (k + 1) as f64;
285                    Value::F32((100.0 * (2.0 * std::f64::consts::PI * hz * t).sin()) as f32)
286                }
287            })
288            .collect();
289        let sample = Sample {
290            // A timestamp of zero means the current clock. SPEC.md 8.3.
291            timestamp: 0.0,
292            values,
293        };
294
295        if a.chunk > 1 {
296            block.push(sample);
297            if block.len() == a.chunk {
298                // The timestamp names the last sample of the chunk. SPEC.md 9.2.
299                outlet.push_chunk(&block, 0.0);
300                block.clear();
301            }
302        } else {
303            outlet.push(&sample);
304        }
305
306        // The marker carries the same rule for its timestamp as the sample: a
307        // value of zero means the current clock. The two therefore sit within
308        // a fraction of one period of each other. SPEC.md 8.3.
309        if let (Some(m), Some(text)) = (&markers, marker_for(n, a.rate)) {
310            m.push(&Sample {
311                timestamp: 0.0,
312                values: vec![Value::Str(text.into_bytes())],
313            });
314        }
315        n += 1;
316
317        std::thread::sleep(Duration::from_secs_f64(period));
318    }
319}
Source

pub fn append_child_value(&mut self, name: &str, value: &str) -> &mut Node

Add a tag that holds text.

This matches lsl_append_child_value, which appends the tag and then appends one text node below it (src/lsl_xml_element_c.cpp:74).

Examples found in repository?
examples/publish.rs (line 135)
106fn main() {
107    let a = parse();
108    let stream_name = tagged(&a.name, &a.tag);
109    let marker_name = tagged(&format!("{}-Markers", a.name), &a.tag);
110    let suffix = if a.tag.is_empty() {
111        String::new()
112    } else {
113        format!("_{}", a.tag)
114    };
115
116    let mut info = StreamInfo::new(
117        &stream_name,
118        &a.stream_type,
119        a.channels as u32,
120        Format::Float32,
121        a.rate,
122    );
123    // A source identifier lets a consumer find the stream again after a
124    // restart. Without one, no recovery is possible. SPEC.md 10.1.
125    //
126    // The identifier and the tree below match `oracle/publish.c` exactly, so
127    // the three publishers of `oracle/labrecorder.sh` describe one stream and
128    // a plot of one can be compared with a plot of another.
129    info.source_id = format!("{}_publish{suffix}", a.name);
130
131    {
132        let chns = info.desc.append_child("channels");
133        for k in 0..a.channels {
134            let c = chns.append_child("channel");
135            c.append_child_value("label", &label(k));
136            c.append_child_value("unit", "microvolts");
137            c.append_child_value("type", &a.stream_type);
138        }
139    }
140    info.desc
141        .append_child_value("manufacturer", "conformance publisher");
142    let acq = info.desc.append_child("acquisition");
143    acq.append_child_value("model", "publish example");
144
145    let outlet = match Outlet::new(info) {
146        Ok(o) => o,
147        Err(e) => {
148            eprintln!("cannot publish: {e}");
149            std::process::exit(1);
150        }
151    };
152
153    // A marker stream is a second stream: one channel of text, and no rate.
154    // A recorder treats it as events rather than as a signal.
155    let markers = if a.markers {
156        let mut m = StreamInfo::new(&marker_name, "Markers", 1, Format::String, 0.0);
157        m.source_id = format!("{}_markers{suffix}", a.name);
158        match Outlet::new(m) {
159            Ok(o) => Some(o),
160            Err(e) => {
161                eprintln!("cannot publish the markers: {e}");
162                None
163            }
164        }
165    } else {
166        None
167    };
168
169    let published = outlet.info();
170    println!("=== the stream is published");
171    println!("  name          {}", published.name);
172    println!("  type          {}", published.stream_type);
173    println!("  channels      {} float32", published.channel_count);
174    println!("  rate          {} Hz", published.nominal_srate);
175    println!("  source id     {}", published.source_id);
176    println!("  session       {}", published.session_id);
177    println!("  host          {}", published.hostname);
178    println!("  uid           {}", published.uid);
179    let cfg = labstream_net::config::get();
180    let port = |n: u16| {
181        if n == 0 {
182            "none".to_string()
183        } else {
184            n.to_string()
185        }
186    };
187    println!(
188        "  IPv4          data {}  service {}",
189        port(published.v4data_port),
190        port(published.v4service_port)
191    );
192    println!(
193        "  IPv6          data {}  service {}",
194        port(published.v6data_port),
195        port(published.v6service_port)
196    );
197    let which = match (cfg.allow_ipv4, cfg.allow_ipv6) {
198        (true, true) => "IPv4 and IPv6",
199        (true, false) => "IPv4 only",
200        (false, true) => "IPv6 only. A consumer has no other way to reach this stream.",
201        (false, false) => "none. Nothing can reach this stream.",
202    };
203    println!("  protocols     {which}");
204    match &markers {
205        Some(m) => {
206            println!(
207                "  marker stream {}  ({})",
208                m.info().name,
209                m.info().source_id
210            );
211            println!("                one every second, on a zero crossing of channel one");
212            if !m.holds_multicast_port() {
213                println!("  WARNING: the marker stream does not hold the multicast port.");
214            }
215        }
216        None => println!("  marker stream none"),
217    }
218
219    // A query from another machine arrives by multicast or by broadcast. The
220    // outlet joins each group on each local address, so this list is the one
221    // that decides whether another machine can find the stream at all.
222    let addresses = labstream_net::local_ipv4_addresses();
223    println!("\n=== the addresses that carry a query");
224    if addresses.is_empty() {
225        println!("  none found. Another machine will not see this stream.");
226    }
227    for addr in &addresses {
228        println!("  {addr}");
229    }
230    println!("  multicast port {}", cfg.multicast_port);
231    println!("  groups         {}", cfg.multicast_addresses.join(", "));
232    println!("  configuration  {}", cfg.source);
233    if outlet.holds_multicast_port() {
234        println!("  multicast port held by this outlet");
235    } else {
236        println!(
237            "  WARNING: port {} is held by another process on this machine.",
238            cfg.multicast_port
239        );
240        println!("  A multicast query will not reach this outlet. Stop the other");
241        println!("  program, or expect the other machine to find nothing.");
242    }
243
244    println!("\n=== open LabRecorder on the other machine and press Update");
245    println!("  The count below rises when a recorder links the stream.\n");
246
247    let period = if a.rate > 0.0 { 1.0 / a.rate } else { 0.01 };
248    let start = Instant::now();
249    let mut n: u64 = 0;
250    let mut consumers = 0;
251    let mut reported = Instant::now() - Duration::from_secs(10);
252    let mut block: Vec<Sample> = Vec::new();
253
254    loop {
255        if a.seconds > 0.0 && start.elapsed().as_secs_f64() >= a.seconds {
256            println!("\n{n} samples sent. Stopping.");
257            return;
258        }
259
260        let now = outlet.consumer_count();
261        if now != consumers {
262            println!(
263                "  consumers {consumers} -> {now}   after {:.1} s, {n} samples",
264                start.elapsed().as_secs_f64()
265            );
266            consumers = now;
267        }
268        if reported.elapsed() >= Duration::from_secs(5) {
269            println!(
270                "  {:.0} s, {n} samples, {consumers} consumer(s)",
271                start.elapsed().as_secs_f64()
272            );
273            reported = Instant::now();
274        }
275
276        // The value of a channel comes from the sample number, so a recording
277        // can be tested later. The last channel holds the number itself.
278        let t = n as f64 / a.rate.max(1.0);
279        let values: Vec<Value> = (0..a.channels)
280            .map(|k| {
281                if k + 1 == a.channels {
282                    Value::F32(n as f32)
283                } else {
284                    let hz = (k + 1) as f64;
285                    Value::F32((100.0 * (2.0 * std::f64::consts::PI * hz * t).sin()) as f32)
286                }
287            })
288            .collect();
289        let sample = Sample {
290            // A timestamp of zero means the current clock. SPEC.md 8.3.
291            timestamp: 0.0,
292            values,
293        };
294
295        if a.chunk > 1 {
296            block.push(sample);
297            if block.len() == a.chunk {
298                // The timestamp names the last sample of the chunk. SPEC.md 9.2.
299                outlet.push_chunk(&block, 0.0);
300                block.clear();
301            }
302        } else {
303            outlet.push(&sample);
304        }
305
306        // The marker carries the same rule for its timestamp as the sample: a
307        // value of zero means the current clock. The two therefore sit within
308        // a fraction of one period of each other. SPEC.md 8.3.
309        if let (Some(m), Some(text)) = (&markers, marker_for(n, a.rate)) {
310            m.push(&Sample {
311                timestamp: 0.0,
312                values: vec![Value::Str(text.into_bytes())],
313            });
314        }
315        n += 1;
316
317        std::thread::sleep(Duration::from_secs_f64(period));
318    }
319}
Source

pub fn child(&self, name: &str) -> Option<&Node>

The first child with this name.

Source

pub fn child_mut(&mut self, name: &str) -> Option<&mut Node>

The first child with this name, for a change.

Source

pub fn child_value(&self) -> &str

The text of the first child that holds text.

Source

pub fn child_value_of(&self, name: &str) -> &str

The text of the first child with this name.

Source

pub fn is_empty(&self) -> bool

True when this node holds nothing at all.

Source

pub fn write(&self, out: &mut String, depth: usize)

Write this node and everything below it, and end with a newline.

depth counts the tabs before the opening tag.

Trait Implementations§

Source§

impl Clone for Node

Source§

fn clone(&self) -> Node

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Node

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Default for Node

Source§

fn default() -> Node

Returns the “default value” for a type. Read more
Source§

impl Eq for Node

Source§

impl PartialEq for Node

Source§

fn eq(&self, other: &Node) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for Node

Auto Trait Implementations§

§

impl Freeze for Node

§

impl RefUnwindSafe for Node

§

impl Send for Node

§

impl Sync for Node

§

impl Unpin for Node

§

impl UnsafeUnpin for Node

§

impl UnwindSafe for Node

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.