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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
//! Prolog streams.
//!
//! This exists mostly to support blob description writers. In the
//! future this will include more proper stream support.
use std::io::{self, Read, Write};
use std::marker::PhantomData;

use either::Either;
use num_enum::FromPrimitive;

use crate::engine::*;
use crate::term::*;
use crate::{fli, term_getable};

/// A stream from prolog, used in blob writers.
pub struct PrologStream {
    stream: *mut fli::IOSTREAM,
}

impl PrologStream {
    /// Wrap the underlying fli object.
    ///
    /// # Safety
    /// This is only safe to do with actual IOSTREAMs coming out of
    /// SWI-Prolog.
    pub unsafe fn wrap(stream: *mut fli::IOSTREAM) -> Self {
        Self { stream }
    }
}

/// A stream from prolog that can be directly written to.
///
/// This stream will be in a claimed state, meaning, any attempted
/// handling of this stream from another (prolog) thread will fail. On
/// drop, this claim will be released. It is therefore important to
/// drop this stream as soon as possible.
pub struct WritablePrologStream<'a> {
    stream: *mut fli::IOSTREAM,
    _x: PhantomData<&'a ()>,
}

impl<'a> WritablePrologStream<'a> {
    /// Wrap a writable prolog stream.
    ///
    /// # Safety
    /// This is only safe to do with actual IOSTREAMs coming out of
    /// SWI-Prolog, which are writable.
    pub unsafe fn new(stream: *mut fli::IOSTREAM) -> WritablePrologStream<'a> {
        WritablePrologStream {
            stream,
            _x: PhantomData,
        }
    }

    pub fn encoding(&self) -> StreamEncoding {
        StreamEncoding::from(unsafe { (*self.stream).encoding })
    }
}

impl<'a> Drop for WritablePrologStream<'a> {
    fn drop(&mut self) {
        unsafe {
            fli::PL_release_stream(self.stream);
        }
    }
}

term_getable! {
    // note that 'a is a known lifetime in this context, set up by the
    // macro, and it refers to the lifetime of the term's origin. This
    // means that the stream retrieved here cannot outlive that
    // origin.
    (WritablePrologStream<'a>, term) => {
        let mut stream: *mut fli::IOSTREAM = std::ptr::null_mut();
        if unsafe { fli::PL_get_stream(term.term_ptr(), &mut stream, fli::SH_OUTPUT|fli::SH_UNLOCKED|fli::SH_NOPAIR) } != 0 {
            Some(unsafe {WritablePrologStream::new(stream) })
        }
        else {
            None
        }
    }
}

unsafe fn ensure_writable_prolog_stream(stream: *mut fli::IOSTREAM) -> io::Result<()> {
    if (*stream).flags & fli::SIO_OUTPUT == 0 {
        Err(io::Error::new(
            io::ErrorKind::BrokenPipe,
            "prolog stream is not writable",
        ))
    } else {
        Ok(())
    }
}

unsafe fn write_to_prolog_stream(stream: *mut fli::IOSTREAM, buf: &[u8]) -> io::Result<usize> {
    ensure_writable_prolog_stream(stream)?;

    let enc = (*stream).encoding;
    let count;
    if enc == fli::IOENC_ENC_OCTET || enc == fli::IOENC_ENC_ANSI || enc == fli::IOENC_ENC_UTF8 {
        // in this case we can just write our buf directly.
        //eprintln!("direct write! ({:?})", buf);
        count = fli::Sfwrite(
            buf.as_ptr() as *const std::ffi::c_void,
            1,
            buf.len(),
            stream,
        );

        let error = fli::Sferror(stream);
        if error == -1 {
            fli::Sclearerr(stream);
            return Err(io::Error::new(
                io::ErrorKind::UnexpectedEof,
                "unexpected eof",
            ));
        }
    } else {
        //eprintln!("indirect write! ({:?}", buf);
        let mut write_buf = Vec::with_capacity(buf.len() + 1);
        write_buf.extend_from_slice(buf);
        write_buf.push(0);
        let result = fli::Sfputs(write_buf.as_ptr() as *const std::os::raw::c_char, stream);
        let error = fli::Sferror(stream);
        if error != 0 {
            fli::Sclearerr(stream);
            return Err(io::Error::new(
                io::ErrorKind::InvalidData,
                "Tried to write data that is out of range for the encoding of this stream",
            ));
        }
        if result == fli::EOF {
            return Err(io::Error::new(
                io::ErrorKind::UnexpectedEof,
                "unexpected eof",
            ));
        }

        count = buf.len();
    }

    Ok(count)
}

impl<'a> Write for WritablePrologStream<'a> {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        assert_some_engine_is_active();

        unsafe { write_to_prolog_stream(self.stream, buf) }
    }

    fn flush(&mut self) -> io::Result<()> {
        assert_some_engine_is_active();
        let result = unsafe { fli::Sflush(self.stream) };
        let error = unsafe { fli::Sferror(self.stream) };
        if error != 0 {
            unsafe { fli::Sclearerr(self.stream) };
        }

        match (result, error) {
            (0, 0) => Ok(()),
            _ => Err(io::Error::new(io::ErrorKind::Other, "prolog flush failed")),
        }
    }
}

impl Write for PrologStream {
    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
        assert_some_engine_is_active();
        unsafe { write_to_prolog_stream(self.stream, buf) }
    }

    fn flush(&mut self) -> io::Result<()> {
        assert_some_engine_is_active();
        let result = unsafe { fli::Sflush(self.stream) };
        let error = unsafe { fli::Sferror(self.stream) };
        if error != 0 {
            unsafe { fli::Sclearerr(self.stream) };
        }
        match (result, error) {
            (0, 0) => Ok(()),
            _ => Err(io::Error::new(io::ErrorKind::Other, "prolog flush failed")),
        }
    }
}

/// A stream from prolog that can be read from.
///
/// This stream will be in a claimed state, meaning, any attempted
/// handling of this stream from another (prolog) thread will fail. On
/// drop, this claim will be released. It is therefore important to
/// drop this stream as soon as possible.
pub struct ReadablePrologStream<'a> {
    stream: *mut fli::IOSTREAM,
    _x: PhantomData<&'a ()>,
}

#[cfg(not(windows))]
#[derive(FromPrimitive)]
#[repr(u32)]
pub enum StreamEncoding {
    #[default]
    Unknown = 0,
    Octet,
    Ascii,
    Latin1,
    Ansi,
    Utf8,
    Utf16Be,
    Utf16Le,
    Wchar,
}

#[cfg(windows)]
#[derive(FromPrimitive)]
#[repr(i32)]
pub enum StreamEncoding {
    #[default]
    Unknown = 0,
    Octet,
    Ascii,
    Latin1,
    Ansi,
    Utf8,
    Utf16Be,
    Utf16Le,
    Wchar,
}

impl<'a> ReadablePrologStream<'a> {
    /// Wrap a readable prolog stream.
    ///
    /// # Safety
    /// This is only safe to do with actual IOSTREAMs coming out of
    /// SWI-Prolog, which are readable.
    pub unsafe fn new(stream: *mut fli::IOSTREAM) -> ReadablePrologStream<'a> {
        ReadablePrologStream {
            stream,
            _x: PhantomData,
        }
    }

    pub fn encoding(&self) -> StreamEncoding {
        StreamEncoding::from(unsafe { (*self.stream).encoding })
    }

    /// Returns an implementation of Read which will automatically
    /// decode the underlying prolog stream, ensuring that it looks
    /// like proper utf-8.
    ///
    /// This is especially useful for cases where we like to pass a
    /// reader to a decoder like serde.
    pub fn decoding_reader(self) -> Either<Self, Latin1Reader<Self>> {
        match self.encoding() {
            StreamEncoding::Latin1 => Either::Right(Latin1Reader::new(self)),
            _ => Either::Left(self),
        }
    }
}

impl<'a> Drop for ReadablePrologStream<'a> {
    fn drop(&mut self) {
        unsafe {
            fli::PL_release_stream(self.stream);
        }
    }
}

term_getable! {
    // note that 'a is a known lifetime in this context, set up by the
    // macro, and it refers to the lifetime of the term's origin. This
    // means that the stream retrieved here cannot outlive that
    // origin.
    (ReadablePrologStream<'a>, term) => {
        let mut stream: *mut fli::IOSTREAM = std::ptr::null_mut();
        if unsafe { fli::PL_get_stream(term.term_ptr(), &mut stream, fli::SH_INPUT|fli::SH_UNLOCKED|fli::SH_NOPAIR) } != 0 {
            Some(unsafe {ReadablePrologStream::new(stream) })
        }
        else {
            None
        }
    }
}

unsafe fn ensure_readable_prolog_stream(stream: *mut fli::IOSTREAM) -> io::Result<()> {
    if (*stream).flags & fli::SIO_INPUT == 0 {
        Err(io::Error::new(
            io::ErrorKind::BrokenPipe,
            "prolog stream is not readable",
        ))
    } else {
        Ok(())
    }
}

unsafe fn read_from_prolog_stream(stream: *mut fli::IOSTREAM, buf: &mut [u8]) -> io::Result<usize> {
    ensure_readable_prolog_stream(stream)?;

    let count = fli::Sfread(
        buf.as_mut_ptr() as *mut std::ffi::c_void,
        1,
        buf.len(),
        stream,
    );

    let error = fli::Sferror(stream);
    if error == -1 {
        fli::Sclearerr(stream);
        Err(io::Error::new(
            io::ErrorKind::UnexpectedEof,
            "unexpected eof",
        ))
    } else {
        Ok(count)
    }
}

impl<'a> Read for ReadablePrologStream<'a> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        assert_some_engine_is_active();

        unsafe { read_from_prolog_stream(self.stream, buf) }
    }
}

pub struct Latin1Reader<R> {
    inner: R,
    remainder: u8,
}

impl<R> Latin1Reader<R> {
    pub fn new(reader: R) -> Self {
        Self {
            inner: reader,
            remainder: 0,
        }
    }

    pub fn into_inner(self) -> R {
        self.inner
    }
}

impl<R: Read> Read for Latin1Reader<R> {
    fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
        if buf.is_empty() {
            return Ok(0);
        }
        let mut partial_buf = buf;
        let mut count = 0;
        if self.remainder != 0 {
            partial_buf[0] = self.remainder;
            partial_buf = &mut partial_buf[1..];
            count += 1;
            self.remainder = 0;
        }

        if partial_buf.is_empty() {
            return Ok(count);
        } else if partial_buf.len() == 1 {
            // only one character remains. we might be lucky and
            // be able to fit one more character, or we might hit
            // a boundary.
            let mut x = [0_u8; 1];
            let final_count = self.inner.read(&mut x)?;
            if final_count == 0 {
                return Ok(count);
            } else if x[0] & 0x80 != 0 {
                // boundary!
                let c = x[0] as char;
                let mut x2 = [0_u8; 2];
                c.encode_utf8(&mut x2);
                partial_buf[0] = x2[0];
                self.remainder = x2[1];
            } else {
                partial_buf[0] = x[0];
            }
            count += 1;
            return Ok(count);
        }
        // at least 2 bytes remain in buf. this means we can
        // always read at least one latin1 character.

        // for the most part we want to be optimistic and assume
        // that this latin-1 stream is actually just going to be
        // an ascii stream and no special encoding is necessary.
        // So we read directly into the destination buf and only
        // do something special if it turns out this assumption
        // doesn't hold.

        let expected_len = partial_buf.len() / 2;
        let mut len = self.inner.read(&mut partial_buf[..expected_len])?;
        if len == 0 {
            // nothing was read. we should be done.
            return Ok(count);
        }
        // scan for forbidden values
        let found_forbidden = partial_buf[..len].iter().position(|i| i & 0x80 != 0);
        if let Some(mut index) = found_forbidden {
            // copy remainder to a vec so we can start processing
            let copy = partial_buf[index..len].to_vec();
            for c in copy {
                (c as char).encode_utf8(&mut partial_buf[index..index + 2]);
                index += if c & 0x80 == 0 { 1 } else { 2 };
            }
            // finally, since length will have changed through this operation, ensure len is correct.
            len = index;
        }
        count += len;

        Ok(count)
    }
}