Skip to main content

nsi_intermediate/stream/
mod.rs

1//! `.nsi` stream emission.
2//!
3//! Replays a recorded scene in the ɴsɪ stream format so it can be
4//! compared against what 3Delight writes for the same calls. Nodes are
5//! emitted in creation order, which is why the tables are `IndexMap`s.
6//!
7//! The format below was read off 3Delight 2.9.207's own `apistream`
8//! output rather than inferred, which is how the less obvious details
9//! got settled: `I64` is `int64`, `MatrixF64` is `doublematrix`, and an
10//! array length rides *inside* the type name as `int[2]` rather than in
11//! a field of its own.
12//!
13//! ```text
14//! Create "cam" "perspectivecamera"
15//! SetAttribute "cam"
16//!   "fov" "float" 1 45
17//! SetAttribute "m"
18//!   "P" "point" 2 [ 0 0 0 1 2 3 ]
19//!   "resolution" "int[2]" 1 [ 1280 720 ]
20//! SetAttributeAtTime "xf" 0.5
21//!   "t" "double" 1 1
22//! Connect "xf" "" ".root" "objects"
23//! ```
24//!
25//! # What this is not
26//!
27//! A recorder holds scene *state*, not a call log: `set_attribute` is a
28//! map insert, so the grouping of attributes into calls is discarded.
29//! One ɴsɪ call setting three attributes and three calls setting one
30//! each record identically, and both replay as three statements here.
31//!
32//! So a stream diff against 3Delight compares scene state, not call
33//! history. That is the right invariant for a backend -- the renderer
34//! only ever sees final values -- but it means a comparison fixture has
35//! to be built one attribute per call for the two to align literally.
36
37use crate::{EdgeKind, OwnedArgument, OwnedData, Scene};
38use core::fmt;
39use nsi_ffi_wrap::{Arg, nsi_sys::NSIParamFlags};
40use nsi_trait::{Action, Nsi, Type};
41use parking_lot::Mutex;
42use std::io::{self, Write};
43
44/// One ɴsɪ stream string literal, escaped.
45///
46/// Without this a handle or value containing a quote and a newline
47/// closes its literal and the rest parses as further statements. The
48/// stream is a persisted, cross-language format, so that is a
49/// correctness hole rather than a cosmetic one. 3Delight escapes the
50/// same way.
51fn quoted(value: &[u8]) -> Vec<u8> {
52    let mut out = Vec::with_capacity(value.len() + 2);
53    out.push(b'"');
54    for &byte in value {
55        match byte {
56            b'"' => out.extend_from_slice(b"\\\""),
57            b'\\' => out.extend_from_slice(b"\\\\"),
58            b'\n' => out.extend_from_slice(b"\\n"),
59            b'\t' => out.extend_from_slice(b"\\t"),
60            // Every other control byte is three-digit octal, which is
61            // what 3Delight writes -- a carriage return as `\015`. Left
62            // raw, it would end the statement.
63            control if control < 0x20 => {
64                out.extend_from_slice(format!("\\{control:03o}").as_bytes());
65            }
66            // A byte at or above 0x7f goes out raw, which is what
67            // 3Delight writes: `renderdl -cat` echoes a Latin-1 file
68            // name back unchanged rather than escaping it.
69            _ => out.push(byte),
70        }
71    }
72    out.push(b'"');
73    out
74}
75
76/// [`quoted`] for an identifier, which the scene stores as text.
77///
78/// Escaping only ever substitutes ASCII sequences and copies every other
79/// byte through, so UTF-8 in gives UTF-8 out. The fallback is
80/// unreachable rather than a repair.
81fn quoted_str(value: &str) -> String {
82    // Unreachable, and stated rather than repaired: `quoted` substitutes
83    // only for `"`, `\`, `\n`, `\t` and bytes below `0x20`, all ASCII,
84    // and in valid UTF-8 an ASCII byte is always a whole code point --
85    // lead and continuation bytes are `0x80` and above. So every
86    // multi-byte sequence is copied through contiguously and unchanged.
87    // Falling back to a lossy conversion here would quietly rewrite an
88    // identifier, which is the one thing this crate refuses to do.
89    // SAFETY: `quoted` only ever inserts ASCII escapes and copies
90    // every other byte through unchanged, so a UTF-8 input stays UTF-8.
91    String::from_utf8(quoted(value.as_bytes()))
92        .expect("escaping only ASCII preserves UTF-8")
93}
94
95/// Format an `f64` as 3Delight does: C's `printf("%.17g")`.
96///
97/// Rust's `Display` writes the shortest representation that round-trips;
98/// C's `%g` writes a fixed number of significant digits and switches to
99/// exponent form outside a range. They agree on `0.5` and disagree on
100/// `0.1`, `1.0/3.0`, `1e-7` and `1e20`, so the difference is not
101/// cosmetic and the stream gate only passed because the fixture used
102/// values from the agreeing set.
103fn format_f64(value: f64) -> String {
104    const SIGNIFICANT: i32 = 17;
105
106    if value == 0.0 {
107        if value.is_sign_negative() {
108            "-0".to_string()
109        } else {
110            "0".to_string()
111        }
112    } else if !value.is_finite() {
113        // C prints these lowercase and unsuffixed.
114        if value.is_nan() {
115            "nan".to_string()
116        } else if value.is_sign_negative() {
117            "-inf".to_string()
118        } else {
119            "inf".to_string()
120        }
121    } else {
122        let scientific = format!("{:.*e}", (SIGNIFICANT - 1) as usize, value);
123        // SAFETY: `{:e}` always writes exactly one `e`, and what
124        // follows it is always a decimal integer with an optional sign.
125        let (mantissa, exponent) =
126            scientific.split_once('e').expect("Rust always writes one");
127        let exponent: i32 = exponent.parse().expect("an integer exponent");
128
129        if !(-4..SIGNIFICANT).contains(&exponent) {
130            format!(
131                "{}e{}{:02}",
132                trim_zeros(mantissa),
133                if exponent < 0 { '-' } else { '+' },
134                exponent.abs()
135            )
136        } else {
137            let decimals = (SIGNIFICANT - 1 - exponent) as usize;
138            trim_zeros(&format!("{value:.decimals$}"))
139        }
140    }
141}
142
143/// Format an `f32` as 3Delight does.
144///
145/// A *different* printer from the one for doubles, which was a surprise
146/// worth writing down: a double is `%.17g` (`0.1` becomes
147/// `0.10000000000000001`), while a float is the shortest form that
148/// round-trips, written in whichever of decimal or exponent notation is
149/// shorter -- `1e5`, `1e-7`, but `123456790` and `0.1`. The exponent
150/// carries no `+` and no padding, where the double printer's does.
151///
152/// Rust's `Display` never chooses exponent notation, so `100000.0`
153/// would come out as `100000` where 3Delight writes `1e5`.
154fn format_f32(value: f32) -> String {
155    if value.is_finite() {
156        let decimal = format!("{value}");
157        let exponent = format!("{value:e}");
158        if exponent.len() < decimal.len() {
159            exponent
160        } else {
161            decimal
162        }
163    } else if value.is_nan() {
164        "nan".to_string()
165    } else if value.is_sign_negative() {
166        "-inf".to_string()
167    } else {
168        "inf".to_string()
169    }
170}
171
172/// Drop a decimal fraction's trailing zeros, and the point with them.
173fn trim_zeros(value: &str) -> String {
174    if value.contains('.') {
175        value
176            .trim_end_matches('0')
177            .trim_end_matches('.')
178            .to_string()
179    } else {
180        value.to_string()
181    }
182}
183
184/// How a written ɴsɪ stream is compressed.
185///
186/// A compressed stream decompresses to exactly the plain one, so this
187/// is a property of the file rather than of the format.
188///
189/// **Only gzip is read by 3Delight.** `renderdl` reads a `.nsi.gz`
190/// wherever it reads a `.nsi`; handed a zstd stream it fails with
191/// `Invalid char`, and a context configured with
192/// `streamcompression="zstd"` writes plain text. So
193/// `Compression::Zstd` is for consumers of *this* crate -- archives,
194/// caches, transport -- and a file written with it is not something the
195/// renderer will read back.
196///
197/// Each variant beyond [`Compression::None`] costs a dependency and is
198/// behind the feature of the same name, so a consumer that wants neither
199/// pays for neither.
200#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
201#[non_exhaustive]
202pub enum Compression {
203    /// Write the stream as-is.
204    #[default]
205    None,
206    /// gzip, which 3Delight reads.
207    #[cfg(feature = "gzip")]
208    Gzip,
209    /// Zstandard.
210    ///
211    /// Not readable by 3Delight 2.9.207; see the type documentation.
212    #[cfg(feature = "zstd")]
213    Zstd,
214}
215
216impl Compression {
217    /// The conventional file-name suffix, appended to `.nsi`.
218    ///
219    /// Empty for [`Compression::None`].
220    pub const fn extension(self) -> &'static str {
221        match self {
222            Self::None => "",
223            #[cfg(feature = "gzip")]
224            Self::Gzip => ".gz",
225            #[cfg(feature = "zstd")]
226            Self::Zstd => ".zst",
227        }
228    }
229}
230
231/// Write `scene` as an ɴsɪ stream, compressed.
232///
233/// Takes the writer by value because a compressor owns and must finish
234/// it; a half-written compressed stream is not a truncated file, it is
235/// an unreadable one.
236///
237/// # Errors
238///
239/// Any write failure, and any compressor failure.
240pub fn write_stream_with<W: Write>(
241    scene: &Scene,
242    mut out: W,
243    compression: Compression,
244) -> io::Result<()> {
245    match compression {
246        Compression::None => {
247            write_stream(scene, &mut out)?;
248            out.flush()
249        }
250        #[cfg(feature = "gzip")]
251        Compression::Gzip => {
252            let mut encoder = flate2::write::GzEncoder::new(
253                out,
254                flate2::Compression::default(),
255            );
256            write_stream(scene, &mut encoder)?;
257            encoder.finish()?.flush()
258        }
259        #[cfg(feature = "zstd")]
260        Compression::Zstd => {
261            let mut encoder = zstd::stream::write::Encoder::new(out, 0)?;
262            write_stream(scene, &mut encoder)?;
263            encoder.finish()?.flush()
264        }
265    }
266}
267
268/// Write `scene` as an ɴsɪ stream.
269pub fn write_stream<W: Write>(scene: &Scene, out: &mut W) -> io::Result<()> {
270    // `Evaluate` first. The scene holds state, not a call log, so where
271    // one fell among the statements is not recorded -- but an archive
272    // or procedural usually *defines* nodes that later statements
273    // reference, and ɴsɪ requires the nodes a `Connect` names to exist
274    // already. Emitting them first is therefore the order that can
275    // work; emitting them last cannot, when anything here refers to
276    // what they produce. Dropping them, which this did before, loses
277    // them entirely.
278    for args in scene.evaluations() {
279        write!(out, "Evaluate")?;
280        for arg in args {
281            write_arg(out, arg)?;
282        }
283        writeln!(out)?;
284    }
285
286    for (handle, node) in scene.nodes() {
287        // ɴsɪ's reserved handles "don't need to be created using
288        // NSICreate", and 3Delight writes no `Create` for them.
289        if !crate::is_reserved(handle) {
290            writeln!(
291                out,
292                "Create {} {}",
293                quoted_str(handle),
294                quoted_str(&node.node_type)
295            )?;
296        }
297
298        for arg in node.attribute_table().values() {
299            writeln!(out, "SetAttribute {}", quoted_str(handle))?;
300            write_arg(out, arg)?;
301        }
302
303        // Every call, in the order it arrived. Replaying the
304        // timeline instead hands the reader a different scene than was
305        // recorded -- the renderer applies the last call, so
306        // re-ordering the calls re-orders the answer, and dropping a
307        // call a same-time re-set superseded loses what unset the
308        // attribute. See `Node::samples`.
309        for (_, calls) in node.samples() {
310            for (time, arg) in calls {
311                writeln!(
312                    out,
313                    "SetAttributeAtTime {} {}",
314                    quoted_str(handle),
315                    format_f64(*time)
316                )?;
317                write_arg(out, arg)?;
318            }
319        }
320    }
321
322    for edge in scene.edges() {
323        let (from_port, to_port) = match &edge.kind {
324            EdgeKind::ShaderNetwork { from_port, to_port } => {
325                (from_port.as_str(), to_port.as_str())
326            }
327            other => ("", other.to_attribute()),
328        };
329        writeln!(
330            out,
331            "Connect {} {} {} {}",
332            quoted_str(&edge.from),
333            quoted_str(from_port),
334            quoted_str(&edge.to),
335            quoted_str(to_port)
336        )?;
337        // ɴsɪ emits connection arguments as indented parameter lines
338        // under the `Connect`, exactly as for `SetAttribute`.
339        for arg in &edge.args {
340            write_arg(out, arg)?;
341        }
342    }
343
344    Ok(())
345}
346
347/// Write one attribute line: two-space indent, name, type, count, data.
348fn write_arg<W: Write>(out: &mut W, arg: &OwnedArgument) -> io::Result<()> {
349    // A host pointer has no stream representation. 3Delight omits the
350    // whole parameter line, keeping the statement that carried it, so
351    // writing a header with no value would be malformed where 3Delight
352    // writes nothing at all.
353    if matches!(arg.data, OwnedData::Reference(_)) {
354        return Ok(());
355    }
356
357    write!(
358        out,
359        "  {} {} {} ",
360        quoted_str(&arg.name),
361        quoted_str(&type_name(arg)),
362        element_count(arg)
363    )?;
364
365    // 3Delight leaves exactly one scalar bare and brackets everything
366    // else -- an empty slice included, which it writes as `[ ]`.
367    let scalars = scalar_count(arg);
368    if scalars == 0 {
369        // No values, so no separating space either.
370        return writeln!(out, "[ ]");
371    }
372    if scalars != 1 {
373        write!(out, "[ ")?;
374    }
375
376    match &arg.data {
377        OwnedData::F32(v) => {
378            let formatted: Vec<String> =
379                v.iter().copied().map(format_f32).collect();
380            write!(out, "{}", formatted.join(" "))?;
381        }
382        OwnedData::F64(v) => {
383            let formatted: Vec<String> =
384                v.iter().copied().map(format_f64).collect();
385            write!(out, "{}", formatted.join(" "))?;
386        }
387        OwnedData::I32(v) => write_scalars(out, v)?,
388        OwnedData::I64(v) => write_scalars(out, v)?,
389        OwnedData::String(v) => {
390            for (index, value) in v.iter().enumerate() {
391                if index > 0 {
392                    out.write_all(b" ")?;
393                }
394                out.write_all(&quoted(value))?;
395            }
396        }
397        // Returned above; a `Reference` never reaches here.
398        OwnedData::Reference(_) => {}
399    }
400
401    if scalars != 1 {
402        write!(out, " ]")?;
403    }
404    writeln!(out)
405}
406
407fn write_scalars<W: Write, T: fmt::Display>(
408    out: &mut W,
409    values: &[T],
410) -> io::Result<()> {
411    let joined: Vec<String> = values.iter().map(ToString::to_string).collect();
412    write!(out, "{}", joined.join(" "))
413}
414
415/// Total scalars stored, across every element.
416fn scalar_count(arg: &OwnedArgument) -> usize {
417    match &arg.data {
418        OwnedData::F32(v) => v.len(),
419        OwnedData::F64(v) => v.len(),
420        OwnedData::I32(v) => v.len(),
421        OwnedData::I64(v) => v.len(),
422        OwnedData::String(v) => v.len(),
423        OwnedData::Reference(v) => v.len(),
424    }
425}
426
427/// The stream `count` field: elements, then divided by `array_length`.
428///
429/// A two-point `P` is 2. A `resolution` of two `i32`s with
430/// `array_len(2)` is 1, because the array length is carried by the type
431/// name instead.
432fn element_count(arg: &OwnedArgument) -> usize {
433    let per = components_per_element(arg.type_tag);
434    scalar_count(arg) / per / arg.array_length.max(1)
435}
436
437const fn components_per_element(type_tag: Type) -> usize {
438    match type_tag {
439        Type::Color | Type::Point | Type::Vector | Type::Normal => 3,
440        Type::MatrixF32 | Type::MatrixF64 => 16,
441        _ => 1,
442    }
443}
444
445/// ɴsɪ stream type name, with the array length appended when there is
446/// one -- `int` becomes `int[2]` under `array_len(2)`.
447fn type_name(arg: &OwnedArgument) -> String {
448    let base = base_type_name(arg.type_tag);
449    // ɴsɪ marks an array with `NSIParamIsArray`, not by its length, and
450    // `array_len(1)` is a real one-element array: 3Delight writes
451    // `"al1" "float[1]" 2 [ 1 2 ]`. Keying on `> 1` dropped it.
452    let sized = if arg.flags & NSIParamFlags::IsArray.bits() != 0 {
453        format!("{base}[{}]", arg.array_length)
454    } else {
455        base.to_string()
456    };
457
458    let flags = flag_prefix(arg.flags);
459    if flags.is_empty() {
460        sized
461    } else {
462        format!("{flags} {sized}")
463    }
464}
465
466/// ɴsɪ's argument flags, as the letters 3Delight prefixes to the type.
467///
468/// `per_vertex` is `"v point"`, and flags combine into one run of
469/// letters: `per_vertex` plus `linear_interpolation` is `"vl float"`.
470/// `IsArray` is excluded because the array length is already carried by
471/// the `[n]` suffix.
472fn flag_prefix(flags: i32) -> String {
473    [
474        (NSIParamFlags::PerFace, 'f'),
475        (NSIParamFlags::PerVertex, 'v'),
476        (NSIParamFlags::InterpolateLinear, 'l'),
477    ]
478    .iter()
479    .filter(|(flag, _)| flags & flag.bits() != 0)
480    .map(|(_, letter)| *letter)
481    .collect()
482}
483
484/// Verified against 3Delight 2.9.207 apistream output.
485const fn base_type_name(type_tag: Type) -> &'static str {
486    match type_tag {
487        Type::F32 => "float",
488        Type::F64 => "double",
489        Type::I32 => "int",
490        Type::I64 => "int64",
491        Type::String => "string",
492        Type::Color => "color",
493        Type::Point => "point",
494        Type::Vector => "vector",
495        Type::Normal => "normal",
496        Type::MatrixF32 => "matrix",
497        Type::MatrixF64 => "doublematrix",
498        Type::Reference => "pointer",
499        Type::Invalid => "invalid",
500    }
501}
502
503#[cfg(test)]
504mod tests;
505
506/// An [`Nsi`] sink that writes each call straight to a `.nsi` stream.
507///
508/// This is the writing half of a **filter**: `nsi-parse` reads a stream
509/// into any [`Nsi`] sink, and this writes one back out. A consumer that
510/// puts its own [`Nsi`] implementation between the two sees every call
511/// as it goes past and decides what to forward -- 3Delight's
512/// `nsicallbacks.h` in Rust, with a `Result` where it has a `bool`.
513///
514/// ```
515/// # use nsi_intermediate::StreamWriter;
516/// # use nsi_trait::Nsi;
517/// let writer = StreamWriter::new(Vec::new());
518/// writer.create("cam", "perspectivecamera", None).unwrap();
519/// assert_eq!(
520///     String::from_utf8(writer.into_inner()).unwrap(),
521///     "Create \"cam\" \"perspectivecamera\"\n",
522/// );
523/// ```
524///
525/// # Not [`write_stream`]
526///
527/// [`write_stream`] replays a [`Scene`], which is state: it emits each
528/// attribute once, in node order, whatever calls produced it. This
529/// emits the calls, in the order they arrive, holding nothing -- so a
530/// re-set attribute appears twice, a stream keeps its shape, and the
531/// memory cost is one statement rather than one scene.
532#[derive(Debug)]
533pub struct StreamWriter<W: Write> {
534    out: Mutex<W>,
535}
536
537impl<W: Write> StreamWriter<W> {
538    /// A writer emitting into `out`.
539    pub fn new(out: W) -> Self {
540        Self {
541            out: Mutex::new(out),
542        }
543    }
544
545    /// The `out` this was built with.
546    pub fn into_inner(self) -> W {
547        self.out.into_inner()
548    }
549
550    /// Write one statement, then its parameter lines.
551    fn statement(
552        &self,
553        head: &str,
554        args: &[Arg<'_, '_>],
555        skip: Option<&str>,
556    ) -> io::Result<()> {
557        let mut out = self.out.lock();
558        writeln!(out, "{head}")?;
559        for arg in args {
560            let owned = OwnedArgument::from_param(arg);
561            if skip == Some(owned.name.as_str()) {
562                continue;
563            }
564            write_arg(&mut *out, &owned)?;
565        }
566        Ok(())
567    }
568}
569
570impl<W: Write + Send> Nsi for StreamWriter<W> {
571    /// The `Arg` every sink in this workspace speaks, so a filter can
572    /// forward what it was handed without rebuilding it.
573    type Arg<'call> = Arg<'call, 'static>;
574    type Error = io::Error;
575
576    fn create(
577        &self,
578        handle: &str,
579        node_type: &str,
580        args: Option<&[Self::Arg<'_>]>,
581    ) -> Result<(), Self::Error> {
582        // ɴsɪ's `NSICreate` takes optional parameters and 3Delight
583        // writes them, so a filter that dropped them would lose data
584        // on the way through.
585        self.statement(
586            &format!("Create {} {}", quoted_str(handle), quoted_str(node_type)),
587            args.unwrap_or_default(),
588            None,
589        )
590    }
591
592    fn delete(
593        &self,
594        handle: &str,
595        args: Option<&[Self::Arg<'_>]>,
596    ) -> Result<(), Self::Error> {
597        self.statement(
598            &format!("Delete {}", quoted_str(handle)),
599            args.unwrap_or_default(),
600            None,
601        )
602    }
603
604    fn set_attribute(
605        &self,
606        handle: &str,
607        args: &[Self::Arg<'_>],
608    ) -> Result<(), Self::Error> {
609        self.statement(
610            &format!("SetAttribute {}", quoted_str(handle)),
611            args,
612            None,
613        )
614    }
615
616    fn set_attribute_at_time(
617        &self,
618        handle: &str,
619        time: f64,
620        args: &[Self::Arg<'_>],
621    ) -> Result<(), Self::Error> {
622        self.statement(
623            &format!(
624                "SetAttributeAtTime {} {}",
625                quoted_str(handle),
626                format_f64(time)
627            ),
628            args,
629            None,
630        )
631    }
632
633    fn delete_attribute(
634        &self,
635        handle: &str,
636        name: &str,
637    ) -> Result<(), Self::Error> {
638        self.statement(
639            &format!(
640                "DeleteAttribute {} {}",
641                quoted_str(handle),
642                quoted_str(name)
643            ),
644            &[],
645            None,
646        )
647    }
648
649    fn connect(
650        &self,
651        from: &str,
652        from_attribute: Option<&str>,
653        to: &str,
654        to_attribute: &str,
655        args: Option<&[Self::Arg<'_>]>,
656    ) -> Result<(), Self::Error> {
657        self.statement(
658            &format!(
659                "Connect {} {} {} {}",
660                quoted_str(from),
661                // ɴsɪ writes an unnamed source port as the empty
662                // string, and reads that back as none.
663                quoted_str(from_attribute.unwrap_or_default()),
664                quoted_str(to),
665                quoted_str(to_attribute)
666            ),
667            args.unwrap_or_default(),
668            None,
669        )
670    }
671
672    fn disconnect(
673        &self,
674        from: &str,
675        from_attribute: Option<&str>,
676        to: &str,
677        to_attribute: &str,
678    ) -> Result<(), Self::Error> {
679        self.statement(
680            &format!(
681                "Disconnect {} {} {} {}",
682                quoted_str(from),
683                quoted_str(from_attribute.unwrap_or_default()),
684                quoted_str(to),
685                quoted_str(to_attribute)
686            ),
687            &[],
688            None,
689        )
690    }
691
692    fn evaluate(&self, args: &[Self::Arg<'_>]) -> Result<(), Self::Error> {
693        self.statement("Evaluate", args, None)
694    }
695
696    /// The action is written from the typed [`Action`], and an
697    /// `"action"` parameter that arrived in `args` is dropped.
698    ///
699    /// The stream carries the action as a parameter and the trait as an
700    /// enum. `nsi-parse` strips the parameter and passes the enum, and
701    /// `nsi-ffi-wrap`'s `Context` appends it again on the way out, so
702    /// writing both would put two `"action"`s in one statement -- and
703    /// writing neither leaves a `RenderControl` 3Delight rejects.
704    fn render_control(
705        &self,
706        action: Action,
707        args: Option<&[Self::Arg<'_>]>,
708    ) -> Result<(), Self::Error> {
709        self.statement(
710            "RenderControl",
711            args.unwrap_or_default(),
712            Some("action"),
713        )?;
714        let mut out = self.out.lock();
715        writeln!(
716            out,
717            "  {} {} 1 {}",
718            quoted_str("action"),
719            quoted_str("string"),
720            quoted_str(action.as_str())
721        )
722    }
723}