lldb/
stream.rs

1// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
2// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
3// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
4// option. This file may not be copied, modified, or distributed
5// except according to those terms.
6
7use crate::sys;
8use std::ffi::CStr;
9
10/// A destination for streaming data output. By default, this is
11/// a string stream, but it can be redirected to a file.
12#[derive(Debug)]
13pub struct SBStream {
14    /// The underlying raw `SBStreamRef`.
15    pub raw: sys::SBStreamRef,
16}
17
18impl SBStream {
19    /// Construct a new `SBStream`.
20    pub fn new() -> SBStream {
21        SBStream::wrap(unsafe { sys::CreateSBStream() })
22    }
23
24    /// Construct a new `SBStream`.
25    pub(crate) fn wrap(raw: sys::SBStreamRef) -> SBStream {
26        SBStream { raw }
27    }
28
29    /// Construct a new `Some(SBStream)` or `None`.
30    #[allow(dead_code)]
31    pub(crate) fn maybe_wrap(raw: sys::SBStreamRef) -> Option<SBStream> {
32        if unsafe { sys::SBStreamIsValid(raw) } {
33            Some(SBStream { raw })
34        } else {
35            None
36        }
37    }
38
39    /// Check whether or not this is a valid `SBStream` value.
40    pub fn is_valid(&self) -> bool {
41        unsafe { sys::SBStreamIsValid(self.raw) }
42    }
43
44    /// If the stream is directed to a file, forget about the file and
45    /// if the ownership of the file was transferred to this object,
46    /// close the file. If the stream is backed by a local cache, clear
47    /// this cache.
48    pub fn clear(&self) {
49        unsafe { sys::SBStreamClear(self.raw) }
50    }
51
52    /// If this stream is not redirected to a file, this retrieves the
53    /// locally cached data.
54    pub fn data(&self) -> &str {
55        unsafe {
56            match CStr::from_ptr(sys::SBStreamGetData(self.raw)).to_str() {
57                Ok(s) => s,
58                _ => panic!("Invalid string?"),
59            }
60        }
61    }
62
63    /// If this stream is not redirected to a file, this retrieves the
64    /// length of the locally cached data.
65    pub fn len(&self) -> usize {
66        unsafe { sys::SBStreamGetSize(self.raw) }
67    }
68
69    /// Is this stream empty?
70    pub fn is_empty(&self) -> bool {
71        self.len() == 0
72    }
73}
74
75impl Default for SBStream {
76    fn default() -> SBStream {
77        SBStream::new()
78    }
79}
80
81impl Drop for SBStream {
82    fn drop(&mut self) {
83        unsafe { sys::DisposeSBStream(self.raw) };
84    }
85}
86
87unsafe impl Send for SBStream {}
88unsafe impl Sync for SBStream {}