graphql_toolkit_writer/fmt/
compact.rs

1use std::io;
2
3use super::formatter::Formatter;
4use crate::ser::{Serialize, Serializer};
5
6/// A compact document formatter that writes GraphQL documents with no extra whitespace.
7///
8/// This is the default formatter used by this crate.
9#[derive(Clone, Debug)]
10pub struct CompactFormatter;
11
12impl Formatter for CompactFormatter {}
13
14impl<W> Serializer<W, CompactFormatter>
15where
16    W: io::Write,
17{
18    /// Create a new serializer that writes to the given I/O stream using the compact formatter.
19    pub fn new(writer: W) -> Self {
20        Serializer::with_formatter(writer, CompactFormatter)
21    }
22}
23
24/// Serialize the given GraphQL AST as a compact GraphQL document into the I/O stream.
25#[inline]
26pub fn to_writer<W, T>(writer: W, value: &T) -> anyhow::Result<()>
27where
28    W: io::Write,
29    T: ?Sized + Serialize,
30{
31    let mut ser = Serializer::new(writer);
32    value.serialize(&mut ser)
33}
34/// Serialize the given GraphQL AST as a compact GraphQL document byte vector.
35#[inline]
36pub fn to_vec<T>(value: &T) -> anyhow::Result<Vec<u8>>
37where
38    T: ?Sized + Serialize,
39{
40    let mut writer = Vec::with_capacity(128);
41    to_writer(&mut writer, value)?;
42    Ok(writer)
43}
44
45/// Serialize the given GraphQL AST as a compact GraphQL document string.
46#[inline]
47pub fn to_string<T>(value: &T) -> anyhow::Result<String>
48where
49    T: ?Sized + Serialize,
50{
51    let vec = to_vec(value)?;
52    let string = unsafe {
53        // We do not emit invalid UTF-8.
54        String::from_utf8_unchecked(vec)
55    };
56    Ok(string)
57}