aboutsummaryrefslogtreecommitdiffhomepage
path: root/crates/shirabe-php-shim/src/stream.rs
blob: 44ba0a40aeb3695feb207f5c34e1d30d6f2d6a1e (plain)
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
use crate::{PhpMixed, PhpResource, StreamBacking};
use indexmap::IndexMap;

pub const STREAM_NOTIFY_FAILURE: i64 = 9;
pub const STREAM_NOTIFY_FILE_SIZE_IS: i64 = 5;
pub const STREAM_NOTIFY_PROGRESS: i64 = 7;

/// PHP `stream_get_contents()`: read the remaining bytes from the stream's current position.
/// TODO(phase-e): byte-string semantics — should return Vec<u8>; from_utf8_lossy can corrupt
/// binary reads.
pub fn stream_get_contents(stream: &PhpResource) -> Option<String> {
    stream_read_remaining(stream, None)
}

pub fn stream_resolve_include_path(filename: &str) -> Option<String> {
    let _ = filename;
    todo!()
}

/// PHP `stream_get_contents()` with an explicit max length.
pub fn stream_get_contents_with_max(
    stream: &PhpResource,
    max_length: Option<i64>,
) -> Option<String> {
    stream_read_remaining(stream, max_length)
}

// Reads from the stream's current position: all remaining bytes, or up to `max_length` when given
// (a negative max means "until end").
fn stream_read_remaining(stream: &PhpResource, max_length: Option<i64>) -> Option<String> {
    use std::io::Read;
    match stream {
        PhpResource::Stdin => {
            let mut buf = Vec::new();
            match max_length {
                Some(l) if l >= 0 => {
                    let mut limited = std::io::stdin().take(l as u64);
                    limited.read_to_end(&mut buf).ok()?;
                }
                _ => {
                    std::io::stdin().read_to_end(&mut buf).ok()?;
                }
            }
            Some(String::from_utf8_lossy(&buf).into_owned())
        }
        PhpResource::Stdout | PhpResource::Stderr => None,
        PhpResource::Stream(state) => {
            let mut state = state.borrow_mut();
            if state.closed || !state.readable {
                return None;
            }
            let mut buf = Vec::new();
            let res = match max_length {
                Some(l) if l >= 0 => state.backing.as_rws().take(l as u64).read_to_end(&mut buf),
                _ => state.backing.as_rws().read_to_end(&mut buf),
            };
            res.ok()?;
            Some(String::from_utf8_lossy(&buf).into_owned())
        }
    }
}

pub fn stream_context_create(
    _options: &IndexMap<String, PhpMixed>,
    _params: Option<&IndexMap<String, PhpMixed>>,
) -> PhpMixed {
    todo!()
}

pub fn stream_isatty(stream: PhpResource) -> bool {
    stream_isatty_resource(&stream)
}

pub fn stream_get_wrappers() -> Vec<String> {
    todo!()
}

/// PHP `stream_copy_to_stream()`: copy the remaining bytes of `source` into `dest`, returning the
/// number of bytes copied (or `None` for `false`-on-failure).
pub fn stream_copy_to_stream(source: &PhpResource, dest: &PhpResource) -> Option<i64> {
    use std::io::{Read, Write};
    let mut buf = Vec::new();
    match source {
        PhpResource::Stdin => {
            std::io::stdin().read_to_end(&mut buf).ok()?;
        }
        PhpResource::Stdout | PhpResource::Stderr => return None,
        PhpResource::Stream(state) => {
            let mut state = state.borrow_mut();
            if state.closed || !state.readable {
                return None;
            }
            state.backing.as_rws().read_to_end(&mut buf).ok()?;
        }
    }
    match dest {
        PhpResource::Stdin => None,
        PhpResource::Stdout => std::io::stdout()
            .write_all(&buf)
            .ok()
            .map(|_| buf.len() as i64),
        PhpResource::Stderr => std::io::stderr()
            .write_all(&buf)
            .ok()
            .map(|_| buf.len() as i64),
        PhpResource::Stream(state) => {
            let mut state = state.borrow_mut();
            if state.closed || !state.writable {
                return None;
            }
            state.backing.as_rws().write_all(&buf).ok()?;
            Some(buf.len() as i64)
        }
    }
}

pub fn stream_isatty_resource(resource: &PhpResource) -> bool {
    use std::io::IsTerminal;
    match resource {
        PhpResource::Stdin => std::io::stdin().is_terminal(),
        PhpResource::Stdout => std::io::stdout().is_terminal(),
        PhpResource::Stderr => std::io::stderr().is_terminal(),
        PhpResource::Stream(_) => false,
    }
}

pub fn stream_get_meta_data(_resource: &PhpResource) -> IndexMap<String, PhpMixed> {
    todo!()
}

pub fn stream_set_blocking(_resource: &PhpResource, _enable: bool) -> bool {
    todo!()
}

pub fn stream_select(
    _read: &mut Vec<PhpResource>,
    _write: &mut Vec<PhpResource>,
    _except: &mut Vec<PhpResource>,
    _seconds: i64,
    _microseconds: Option<i64>,
) -> i64 {
    todo!()
}

/// PHP `stream_get_contents($stream, $maxlength, $offset)`. A non-negative `offset` seeks there
/// first; `max_length < 0` reads until end.
pub fn stream_get_contents3(stream: &PhpResource, max_length: i64, offset: i64) -> Option<String> {
    if offset >= 0 {
        crate::fs::fseek(stream, offset, crate::fs::SEEK_SET);
    }
    let max = if max_length < 0 {
        None
    } else {
        Some(max_length)
    };
    stream_read_remaining(stream, max)
}

pub fn is_resource_value(_resource: &PhpResource) -> bool {
    true
}

pub fn get_resource_type(_resource: &PhpResource) -> String {
    "stream".to_string()
}

/// Convenience wrapper over `fopen` for callers that open never-failing `php://` stdio streams and
/// want an infallible `PhpResource`. Panics on failure, matching the previous behavior.
pub fn php_fopen_resource(path: &str, mode: &str) -> PhpResource {
    crate::fs::fopen(path, mode)
        .unwrap_or_else(|e| panic!("php_fopen_resource failed to open {path:?}: {e}"))
}

pub fn php_stdout_resource() -> PhpResource {
    PhpResource::Stdout
}

pub fn php_stderr_resource() -> PhpResource {
    PhpResource::Stderr
}

pub fn stdin() -> PhpResource {
    PhpResource::Stdin
}