1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

use std::{
    ffi::{c_char, c_double, CString},
    fmt::Display,
    io::{Read, Write},
};

use crate::strings::double_to_string;

#[cfg(windows)]
pub const LINE_ENDING: &[u8] = b"\r\n";
#[cfg(not(windows))]
pub const LINE_ENDING: &[u8] = b"\n";

/// Holds output messages from calls to the QIR
/// output recording functions and message calls.
pub struct OutputRecorder {
    buffer: Vec<u8>,
    use_std_out: bool,
}

impl Write for OutputRecorder {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        if self.use_std_out {
            std::io::stdout().write(buf)
        } else {
            self.buffer.write(buf)
        }
    }

    fn flush(&mut self) -> std::io::Result<()> {
        if self.use_std_out {
            std::io::stdout().flush()
        } else {
            self.buffer.flush()
        }
    }
}

impl Read for OutputRecorder {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        self.buffer.as_slice().read(buf)
    }
}

struct DefaultReaderWriter(Vec<u8>);
impl Write for DefaultReaderWriter {
    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
        self.0.write(buf)
    }
    fn flush(&mut self) -> std::io::Result<()> {
        self.0.flush()
    }
}

impl Read for DefaultReaderWriter {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        self.0.as_slice().read(buf)
    }
}

impl Default for OutputRecorder {
    fn default() -> Self {
        OutputRecorder {
            buffer: Vec::new(),
            use_std_out: true,
        }
    }
}

impl OutputRecorder {
    /// Sets whether the output should be written to stdout
    /// or stored in the buffer.
    pub fn use_std_out(&mut self, use_std_out: bool) {
        self.use_std_out = use_std_out;
    }

    /// Writes the newline char(s) to the output.
    pub fn write_newline(&mut self) {
        self.write_all(LINE_ENDING).expect("Failed to write output");
    }

    /// Drains the buffer and returns the contents.
    pub fn drain(&mut self) -> std::vec::Drain<u8> {
        self.buffer.drain(..)
    }
}

thread_local! {
    pub static OUTPUT: std::cell::RefCell<Box<OutputRecorder>> = std::cell::RefCell::new(Box::default());
}

/// Records a string to the output.
/// # Errors
/// Returns an error if the write fails.
pub fn record_output_str(val: &str) -> std::io::Result<()> {
    OUTPUT.with(|output| {
        let mut output = output.borrow_mut();
        output
            .write_all(val.as_bytes())
            .expect("Failed to write output");
        output.write_newline();
    });
    Ok(())
}

/// Records a value to the output.
/// # Errors
/// Returns an error if the write fails.
pub unsafe fn record_output(ty: &str, val: &dyn Display, tag: *mut c_char) -> std::io::Result<()> {
    OUTPUT.with(|output| {
        let mut output = output.borrow_mut();
        output
            .write_fmt(format_args!("OUTPUT\t{ty}\t{val}"))
            .expect("Failed to write output");
        if !tag.is_null() {
            output.write_all(b"\t").expect("Failed to write output");
            output
                .write_all(CString::from_raw(tag).as_bytes())
                .expect("Failed to write output");
        }
        output.write_newline();
    });
    Ok(())
}

/// Inserts a marker in the generated output that indicates the
/// start of an array and how many array elements it has. The second
/// parameter defines a string label for the array. Depending on
/// the output schema, the label is included in the output or omitted.
#[no_mangle]
pub unsafe extern "C" fn __quantum__rt__array_record_output(val: i64, tag: *mut c_char) {
    record_output("ARRAY", &val, tag).expect("Failed to write array output");
}

/// Inserts a marker in the generated output that indicates the
/// start of a tuple and how many tuple elements it has. The second
/// parameter defines a string label for the tuple. Depending on
/// the output schema, the label is included in the output or omitted.
#[no_mangle]
pub unsafe extern "C" fn __quantum__rt__tuple_record_output(val: i64, tag: *mut c_char) {
    record_output("TUPLE", &val, tag).expect("Failed to write tuple output");
}

#[no_mangle]
pub unsafe extern "C" fn __quantum__rt__int_record_output(val: i64, tag: *mut c_char) {
    record_output("INT", &val, tag).expect("Failed to write int output");
}

#[no_mangle]
pub unsafe extern "C" fn __quantum__rt__double_record_output(val: c_double, tag: *mut c_char) {
    record_output("DOUBLE", &double_to_string(val), tag).expect("Failed to write double output");
}

#[no_mangle]
pub unsafe extern "C" fn __quantum__rt__bool_record_output(val: bool, tag: *mut c_char) {
    record_output("BOOL", &val, tag).expect("Failed to write bool output");
}

#[no_mangle]
pub unsafe extern "C" fn __quantum__rt__message_record_output(str: *const CString) {
    record_output_str(&format!(
        "INFO\t{}",
        (*str)
            .to_str()
            .expect("Unable to convert input string")
            .escape_default()
    ))
    .expect("Failed to write message output");
}

pub mod legacy {
    use std::{ffi::c_double, ptr::null_mut};

    use crate::strings::double_to_string;

    use super::record_output_str;

    #[allow(non_snake_case)]
    pub extern "C" fn __quantum__rt__array_start_record_output() {
        record_output_str("RESULT\tARRAY_START").expect("Failed to write array start output");
    }

    #[allow(non_snake_case)]
    pub extern "C" fn __quantum__rt__array_end_record_output() {
        record_output_str("RESULT\tARRAY_END").expect("Failed to write array end output");
    }

    #[allow(non_snake_case)]
    pub extern "C" fn __quantum__rt__tuple_start_record_output() {
        record_output_str("RESULT\tTUPLE_START").expect("Failed to write tuple start output");
    }

    #[allow(non_snake_case)]
    pub extern "C" fn __quantum__rt__tuple_end_record_output() {
        record_output_str("RESULT\tTUPLE_END").expect("Failed to write tuple end output");
    }

    #[allow(non_snake_case)]
    pub extern "C" fn __quantum__rt__int_record_output(val: i64) {
        record_output_str(&format!("RESULT\t{val}")).expect("Failed to write int output");
    }

    #[allow(non_snake_case)]
    pub extern "C" fn __quantum__rt__double_record_output(val: c_double) {
        record_output_str(&format!("RESULT\t{}", double_to_string(val)))
            .expect("Failed to write double output");
    }

    #[allow(non_snake_case)]
    pub extern "C" fn __quantum__rt__bool_record_output(val: bool) {
        record_output_str(&format!("RESULT\t{val}")).expect("Failed to write bool output");
    }

    #[allow(non_snake_case)]
    pub unsafe extern "C" fn __quantum__rt__array_record_output(val: i64) {
        super::__quantum__rt__array_record_output(val, null_mut());
    }

    #[allow(non_snake_case)]
    pub unsafe extern "C" fn __quantum__rt__tuple_record_output(val: i64) {
        super::__quantum__rt__tuple_record_output(val, null_mut());
    }
}

#[cfg(test)]
mod tests {
    use std::ptr::null_mut;

    use super::*;

    #[test]
    fn test_output_int_untagged() {
        let val: i64 = 42;
        assert_untagged_output_match("INT", &val, "OUTPUT\tINT\t42");
    }
    #[test]
    fn test_output_double_untagged() {
        let val: f64 = 42.4533;
        let double_str = double_to_string(val);
        assert_untagged_output_match("DOUBLE", &double_str, "OUTPUT\tDOUBLE\t42.4533");
    }
    #[test]
    fn test_output_double_whole_untagged() {
        let val: c_double = 42.000_000_000_000_001;
        let double_str = double_to_string(val);
        assert_untagged_output_match("DOUBLE", &double_str, "OUTPUT\tDOUBLE\t42.0");
    }
    #[test]
    fn test_output_bool_true_untagged() {
        let val: bool = true;
        assert_untagged_output_match("BOOL", &val, "OUTPUT\tBOOL\ttrue");
    }
    #[test]
    fn test_output_bool_false_untagged() {
        let val: bool = false;
        assert_untagged_output_match("BOOL", &val, "OUTPUT\tBOOL\tfalse");
    }
    #[test]
    fn test_output_tuple_untagged() {
        let val: i64 = 42;
        assert_untagged_output_match("TUPLE", &val, "OUTPUT\tTUPLE\t42");
    }
    #[test]
    fn test_output_array_untagged() {
        let val: i64 = 42;
        assert_untagged_output_match("ARRAY", &val, "OUTPUT\tARRAY\t42");
    }
    fn assert_untagged_output_match(ty: &str, val: &dyn Display, expected_str: &str) {
        OUTPUT.with(|output| output.borrow_mut().use_std_out(false));
        unsafe {
            record_output(ty, &val, null_mut()).expect("Failed to write output");
        }

        let actual = OUTPUT.with(|output| {
            let mut output = output.borrow_mut();
            let output = output.drain();
            get_byte_vec_as_string(output.as_slice())
        });

        OUTPUT.with(|output| output.borrow_mut().use_std_out(true));
        let expected = get_string_with_line_ending(expected_str);
        assert_eq!(actual, expected);
    }
    fn get_string_with_line_ending(value: &str) -> String {
        let ending = get_byte_vec_as_string(LINE_ENDING);
        value.to_owned() + ending.as_str()
    }
    fn get_byte_vec_as_string(out: &[u8]) -> String {
        let val = std::str::from_utf8(out).unwrap();
        val.to_string()
    }
}