1use std::cell::RefCell;
33use std::collections::HashMap;
34use std::io::{self, SeekFrom};
35use std::rc::Rc;
36
37use crate::state_stub::{LuaState, LuaStateStubExt as _};
38use lua_types::{LuaError, LuaFileHandle, LuaType, LuaValue};
39use lua_vm::state::{InputHook, OutputHook};
40
41type LStreamMap = RefCell<HashMap<usize, Rc<RefCell<LStream>>>>;
47
48fn lstream_registry(state: &LuaState) -> Rc<LStreamMap> {
56 let installed = state.global().io_streams.clone();
57 match installed {
58 Some(any) => any
59 .downcast::<LStreamMap>()
60 .expect("GlobalState::io_streams holds the io LStream side table"),
61 None => {
62 let fresh: Rc<LStreamMap> = Rc::new(RefCell::new(HashMap::new()));
63 state.global_mut().io_streams = Some(fresh.clone());
64 fresh
65 }
66 }
67}
68
69fn register_lstream(state: &LuaState, ud_id: usize, lstream: LStream) -> Rc<RefCell<LStream>> {
70 let cell = Rc::new(RefCell::new(lstream));
71 lstream_registry(state)
72 .borrow_mut()
73 .insert(ud_id, cell.clone());
74 cell
75}
76
77fn lookup_lstream(state: &LuaState, ud_id: usize) -> Option<Rc<RefCell<LStream>>> {
78 lstream_registry(state).borrow().get(&ud_id).cloned()
79}
80
81pub const LUA_FILE_HANDLE: &[u8] = b"FILE*";
85
86const IO_INPUT_KEY: &[u8] = b"_IO_input";
88
89const IO_OUTPUT_KEY: &[u8] = b"_IO_output";
91
92const IO_PREFIX_LEN: usize = 4;
94
95const MAX_ARG_LINE: usize = 250;
97
98const L_MAX_LEN_NUM: usize = 200;
100
101const EOF_SENTINEL: i32 = -1;
103
104const LUAL_BUFFER_SIZE: usize = 8192;
106
107pub trait LuaFileOps: LuaFileHandle {
116 fn set_buf_mode(&mut self, mode: BufMode, size: usize) -> io::Result<()>;
118}
119
120#[derive(Debug, Clone, Copy, PartialEq, Eq)]
124pub enum SeekWhence {
125 Set,
126 Cur,
127 End,
128}
129
130#[derive(Debug, Clone, Copy, PartialEq, Eq)]
132pub enum BufMode {
133 No,
134 Full,
135 Line,
136}
137
138pub enum StdFileKind {
140 Stdin,
141 Stdout,
142 Stderr,
143}
144
145pub struct LStream {
153 pub file: Option<Box<dyn LuaFileHandle>>,
157 pub close_fn: Option<fn(&mut LuaState) -> Result<usize, LuaError>>,
159}
160
161impl LStream {
162 pub fn is_closed(&self) -> bool {
164 self.close_fn.is_none()
165 }
166}
167
168struct StdStreamHandle {
174 kind: StdFileKind,
175 input_hook: Option<InputHook>,
176 output_hook: Option<OutputHook>,
177 unread: Option<u8>,
178}
179
180impl LuaFileHandle for StdStreamHandle {
181 fn read_byte(&mut self) -> i32 {
182 if let Some(byte) = self.unread.take() {
183 return byte as i32;
184 }
185 match self.kind {
186 StdFileKind::Stdin => {
187 if let Some(read_fn) = self.input_hook {
188 let mut buf = [0u8; 1];
189 return match read_fn(&mut buf) {
190 Ok(1) => buf[0] as i32,
191 _ => EOF_SENTINEL,
192 };
193 }
194
195 #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
196 {
197 EOF_SENTINEL
198 }
199
200 #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
201 {
202 use std::io::Read;
203 let mut buf = [0u8; 1];
204 match std::io::stdin().read(&mut buf) {
205 Ok(1) => buf[0] as i32,
206 _ => EOF_SENTINEL,
207 }
208 }
209 }
210 _ => EOF_SENTINEL,
211 }
212 }
213 fn unread_byte(&mut self, byte: i32) {
214 if (0..=u8::MAX as i32).contains(&byte) {
215 self.unread = Some(byte as u8);
216 }
217 }
218 fn write_bytes(&mut self, data: &[u8]) -> io::Result<usize> {
219 if let Some(write_fn) = self.output_hook {
220 write_fn(data)?;
221 return Ok(data.len());
222 }
223
224 #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
225 {
226 let _ = data;
227 return Err(io::Error::new(
228 io::ErrorKind::Unsupported,
229 "standard output not available in this host",
230 ));
231 }
232
233 #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
234 {
235 use std::io::Write;
236 match self.kind {
237 StdFileKind::Stderr => {
238 std::io::stderr().write_all(data)?;
239 Ok(data.len())
240 }
241 _ => {
242 std::io::stdout().write_all(data)?;
243 Ok(data.len())
244 }
245 }
246 }
247 }
248 fn flush(&mut self) -> io::Result<()> {
249 if self.output_hook.is_some() {
250 return Ok(());
251 }
252
253 #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
254 {
255 return Err(io::Error::new(
256 io::ErrorKind::Unsupported,
257 "standard output not available in this host",
258 ));
259 }
260
261 #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
262 {
263 use std::io::Write;
264 match self.kind {
265 StdFileKind::Stderr => std::io::stderr().flush(),
266 _ => std::io::stdout().flush(),
267 }
268 }
269 }
270 fn seek(&mut self, _pos: SeekFrom) -> io::Result<u64> {
271 Err(io::Error::new(io::ErrorKind::Unsupported, "stdio seek"))
272 }
273 fn tell(&mut self) -> io::Result<u64> {
274 Err(io::Error::new(io::ErrorKind::Unsupported, "stdio tell"))
275 }
276 fn clear_error(&mut self) {}
277 fn has_error(&self) -> bool {
278 false
279 }
280}
281
282impl LuaFileOps for StdStreamHandle {
283 fn set_buf_mode(&mut self, _mode: BufMode, _size: usize) -> io::Result<()> {
284 Ok(())
285 }
286}
287
288impl StdStreamHandle {
289 fn new(
290 kind: StdFileKind,
291 input_hook: Option<InputHook>,
292 output_hook: Option<OutputHook>,
293 ) -> Self {
294 StdStreamHandle {
295 kind,
296 input_hook,
297 output_hook,
298 unread: None,
299 }
300 }
301}
302
303struct ReadNumState {
305 current: i32,
307 count: usize,
309 buf: [u8; L_MAX_LEN_NUM + 1],
311}
312
313impl ReadNumState {
314 fn new(first_byte: i32) -> Self {
315 ReadNumState {
316 current: first_byte,
317 count: 0,
318 buf: [0u8; L_MAX_LEN_NUM + 1],
319 }
320 }
321
322 fn advance(&mut self, file: &mut dyn LuaFileHandle) -> bool {
325 if self.count >= L_MAX_LEN_NUM {
326 self.buf[0] = 0;
327 return false;
328 }
329 self.buf[self.count] = self.current as u8;
330 self.count += 1;
331 self.current = file.read_byte();
332 true
333 }
334
335 fn try2(&mut self, file: &mut dyn LuaFileHandle, set: [u8; 2]) -> bool {
337 if self.current == set[0] as i32 || self.current == set[1] as i32 {
338 self.advance(file)
339 } else {
340 false
341 }
342 }
343
344 fn read_digits(&mut self, file: &mut dyn LuaFileHandle, hex: bool) -> usize {
346 let mut count = 0usize;
347 loop {
348 let is_digit = if hex {
349 (self.current as u8).is_ascii_hexdigit()
350 } else {
351 (self.current as u8).is_ascii_digit()
352 };
353 if !is_digit || self.current == EOF_SENTINEL {
354 break;
355 }
356 if !self.advance(file) {
357 break;
358 }
359 count += 1;
360 }
361 count
362 }
363
364 fn as_bytes(&self) -> &[u8] {
366 &self.buf[..self.count]
367 }
368}
369
370pub const IO_LIB: &[(&[u8], fn(&mut LuaState) -> Result<usize, LuaError>)] = &[
374 (b"close", io_close),
375 (b"flush", io_flush),
376 (b"input", io_input),
377 (b"lines", io_lines),
378 (b"open", io_open),
379 (b"output", io_output),
380 (b"popen", io_popen),
381 (b"read", io_read),
382 (b"tmpfile", io_tmpfile),
383 (b"type", io_type),
384 (b"write", io_write),
385];
386
387pub const FILE_METHODS: &[(&[u8], fn(&mut LuaState) -> Result<usize, LuaError>)] = &[
389 (b"read", f_read),
390 (b"write", f_write),
391 (b"lines", f_lines),
392 (b"flush", f_flush),
393 (b"seek", f_seek),
394 (b"close", f_close),
395 (b"setvbuf", f_setvbuf),
396];
397
398pub const FILE_METAMETHODS: &[(&[u8], fn(&mut LuaState) -> Result<usize, LuaError>)] = &[
400 (b"__gc", f_gc),
401 (b"__close", f_gc),
402 (b"__tostring", f_tostring),
403];
404
405fn check_mode(mode: &[u8]) -> bool {
411 if mode.is_empty() {
412 return false;
413 }
414 let mut idx = 0usize;
415 if !matches!(mode[idx], b'r' | b'w' | b'a') {
416 return false;
417 }
418 idx += 1;
419 if idx < mode.len() && mode[idx] == b'+' {
420 idx += 1;
421 }
422 mode[idx..].iter().all(|&b| b == b'b')
423}
424
425fn check_mode_popen(mode: &[u8]) -> bool {
427 matches!(mode, b"r" | b"w")
428}
429
430fn posix_strerror(code: i32) -> Option<&'static str> {
450 Some(match code {
451 1 => "Operation not permitted",
452 2 => "No such file or directory",
453 3 => "No such process",
454 4 => "Interrupted system call",
455 5 => "Input/output error",
456 7 => "Argument list too long",
457 8 => "Exec format error",
458 9 => "Bad file descriptor",
459 10 => "No child processes",
460 12 => "Cannot allocate memory",
461 13 => "Permission denied",
462 14 => "Bad address",
463 17 => "File exists",
464 20 => "Not a directory",
465 21 => "Is a directory",
466 22 => "Invalid argument",
467 24 => "Too many open files",
468 27 => "File too large",
469 28 => "No space left on device",
470 29 => "Illegal seek",
471 30 => "Read-only file system",
472 32 => "Broken pipe",
473 _ => return None,
474 })
475}
476
477#[cfg_attr(not(windows), allow(dead_code))]
551fn win32_to_crt_errno(win32_code: u32) -> i32 {
552 match win32_code {
553 1 => 22,
554 2 => 2,
555 3 => 2,
556 4 => 24,
557 5 => 13,
558 6 => 9,
559 7 => 12,
560 8 => 12,
561 9 => 12,
562 10 => 7,
563 11 => 8,
564 12 => 22,
565 13 => 22,
566 15 => 2,
567 16 => 13,
568 17 => 18,
569 18 => 2,
570 32 => 13,
571 33 => 13,
572 53 => 2,
573 65 => 13,
574 67 => 2,
575 80 => 17,
576 82 => 13,
577 83 => 13,
578 87 => 22,
579 89 => 11,
580 108 => 13,
581 109 => 32,
582 112 => 28,
583 114 => 9,
584 128 => 10,
585 129 => 10,
586 130 => 9,
587 131 => 22,
588 132 => 13,
589 133 => 13,
590 134 => 13,
591 135 => 13,
592 136 => 13,
593 137 => 13,
594 138 => 13,
595 139 => 13,
596 140 => 13,
597 141 => 13,
598 145 => 41,
599 158 => 13,
600 161 => 2,
601 164 => 11,
602 167 => 13,
603 183 => 17,
604 206 => 2,
605 215 => 11,
606 1816 => 12,
607 _ => 22,
608 }
609}
610
611#[cfg(windows)]
619fn os_errno_for_lua(raw: i32) -> i32 {
620 win32_to_crt_errno(raw as u32)
621}
622
623#[cfg(not(windows))]
624fn os_errno_for_lua(raw: i32) -> i32 {
625 raw
626}
627
628#[cfg(any(unix, target_arch = "wasm32"))]
635fn target_posix_strerror(code: i32) -> Option<&'static str> {
636 posix_strerror(code)
637}
638
639#[cfg(windows)]
640fn target_posix_strerror(code: i32) -> Option<&'static str> {
641 posix_strerror(win32_to_crt_errno(code as u32))
642}
643
644#[cfg(not(any(unix, target_arch = "wasm32", windows)))]
645fn target_posix_strerror(_code: i32) -> Option<&'static str> {
646 None
647}
648
649fn strerror_text(err: &io::Error) -> String {
660 match err.raw_os_error() {
661 Some(code) => match target_posix_strerror(code) {
662 Some(msg) => msg.to_string(),
663 None => {
664 let full = err.to_string();
665 let suffix = format!(" (os error {code})");
666 full.strip_suffix(&suffix).unwrap_or(&full).to_string()
667 }
668 },
669 None => err.to_string(),
670 }
671}
672
673pub(crate) fn file_result(
698 state: &mut LuaState,
699 success: bool,
700 fname: Option<&[u8]>,
701 os_err: io::Error,
702) -> Result<usize, LuaError> {
703 if success {
704 state.push(LuaValue::Bool(true));
705 return Ok(1);
706 }
707 state.push(LuaValue::Nil);
708 let msg = strerror_text(&os_err);
709 match fname {
710 Some(name) => {
711 let mut s = Vec::with_capacity(name.len() + 2 + msg.len());
712 s.extend_from_slice(name);
713 s.extend_from_slice(b": ");
714 s.extend_from_slice(msg.as_bytes());
715 state.push_string(&s)?;
716 }
717 None => {
718 state.push_string(msg.as_bytes())?;
719 }
720 }
721 match os_err.raw_os_error() {
722 Some(code) => {
723 state.push(LuaValue::Int(os_errno_for_lua(code) as i64));
724 Ok(3)
725 }
726 None => Ok(2),
727 }
728}
729
730fn exec_result(state: &mut LuaState, stat: i32) -> Result<usize, LuaError> {
737 if stat == 0 {
738 state.push(LuaValue::Bool(true));
739 Ok(1)
740 } else {
741 state.push(LuaValue::Bool(false));
742 state.push_string(b"exit")?;
743 state.push(LuaValue::Int(stat as i64));
744 Ok(3)
745 }
746}
747
748fn get_lstream(state: &mut LuaState) -> Result<Rc<RefCell<LStream>>, LuaError> {
755 let ud = state.check_arg_userdata(1, LUA_FILE_HANDLE)?;
756 lookup_lstream(state, ud.identity())
757 .ok_or_else(|| LuaError::runtime(format_args!("invalid file handle")))
758}
759
760fn lstream_from_upvalue(state: &mut LuaState, idx: i32) -> Result<Rc<RefCell<LStream>>, LuaError> {
767 let v = state.value_at(crate::state_stub::upvalue_index(idx));
768 let ud_id = match v {
769 LuaValue::UserData(ud) => ud.identity(),
770 _ => {
771 return Err(LuaError::runtime(format_args!(
772 "invalid file handle in upvalue {}",
773 idx
774 )));
775 }
776 };
777 lookup_lstream(state, ud_id)
778 .ok_or_else(|| LuaError::runtime(format_args!("invalid file handle in upvalue {}", idx)))
779}
780
781fn tofile(state: &mut LuaState) -> Result<Rc<RefCell<LStream>>, LuaError> {
787 let p_rc = get_lstream(state)?;
788 let closed = {
789 let p = p_rc.borrow();
790 debug_assert!(p.is_closed() || p.file.is_some());
791 p.is_closed()
792 };
793 if closed {
794 return Err(lua_vm::debug::c_api_runtime(
795 state,
796 b"attempt to use a closed file".to_vec(),
797 ));
798 }
799 Ok(p_rc)
800}
801
802fn new_pre_file(state: &mut LuaState) -> Result<Rc<RefCell<LStream>>, LuaError> {
809 let ud = state.new_userdata_typed(LUA_FILE_HANDLE, std::mem::size_of::<LStream>(), 0)?;
810 state.set_metatable_by_name(LUA_FILE_HANDLE)?;
811 let cell = register_lstream(
812 state,
813 ud.identity(),
814 LStream {
815 file: None,
816 close_fn: None,
817 },
818 );
819 Ok(cell)
820}
821
822fn new_file(state: &mut LuaState) -> Result<Rc<RefCell<LStream>>, LuaError> {
824 let cell = new_pre_file(state)?;
825 cell.borrow_mut().close_fn = Some(io_fclose);
826 Ok(cell)
827}
828
829fn open_failure_error(state: &mut LuaState, fname: &[u8], detail: &[u8]) -> LuaError {
841 if matches!(state.global().lua_version, lua_types::LuaVersion::V51) {
842 let mut extramsg = Vec::with_capacity(fname.len() + 2 + detail.len());
843 extramsg.extend_from_slice(fname);
844 extramsg.extend_from_slice(b": ");
845 extramsg.extend_from_slice(detail);
846 lua_vm::debug::arg_error_impl(state, 1, &extramsg)
847 } else {
848 let mut msg = Vec::with_capacity(fname.len() + detail.len() + 20);
849 msg.extend_from_slice(b"cannot open file '");
850 msg.extend_from_slice(fname);
851 msg.extend_from_slice(b"' (");
852 msg.extend_from_slice(detail);
853 msg.push(b')');
854 lua_vm::debug::c_api_runtime(state, msg)
855 }
856}
857
858fn opencheck(state: &mut LuaState, fname: &[u8], mode: &[u8]) -> Result<(), LuaError> {
863 let hook = state.global().file_open_hook;
864 let fh = match hook {
865 Some(open_fn) => match open_fn(fname, mode) {
866 Ok(fh) => fh,
867 Err(e) => {
868 let detail = strerror_text(&e);
869 return Err(open_failure_error(state, fname, detail.as_bytes()));
870 }
871 },
872 None => {
873 return Err(open_failure_error(
874 state,
875 fname,
876 b"no filesystem hook registered",
877 ));
878 }
879 };
880 let cell = new_file(state)?;
881 cell.borrow_mut().file = Some(fh);
882 Ok(())
883}
884
885fn io_fclose(state: &mut LuaState) -> Result<usize, LuaError> {
894 let p_rc = get_lstream(state)?;
895 let _closed = p_rc.borrow_mut().file.take();
896 state.push(LuaValue::Bool(true));
897 Ok(1)
898}
899
900fn io_pclose(state: &mut LuaState) -> Result<usize, LuaError> {
905 let p_rc = get_lstream(state)?;
906 let _closed = p_rc.borrow_mut().file.take();
907 exec_result(state, 0)
908}
909
910fn io_noclose(state: &mut LuaState) -> Result<usize, LuaError> {
915 let p_rc = get_lstream(state)?;
916 p_rc.borrow_mut().close_fn = Some(io_noclose);
917 state.push(LuaValue::Bool(false));
918 state.push_string(b"cannot close standard file")?;
919 Ok(2)
920}
921
922fn aux_close(state: &mut LuaState) -> Result<usize, LuaError> {
924 let p_rc = get_lstream(state)?;
925 let cf = p_rc.borrow_mut().close_fn.take().ok_or_else(|| {
926 LuaError::runtime(format_args!("attempt to close an already-closed file"))
927 })?;
928 cf(state)
929}
930
931pub fn io_type(state: &mut LuaState) -> Result<usize, LuaError> {
941 state.check_arg_any(1)?;
942 let maybe_userdata = state.test_arg_userdata(1, LUA_FILE_HANDLE);
943 match maybe_userdata {
944 None => {
945 state.push(LuaValue::Nil);
946 }
947 Some(ud) => {
948 let is_closed = match lookup_lstream(state, ud.identity()) {
949 Some(rc) => rc.borrow().is_closed(),
950 None => true,
951 };
952 if is_closed {
953 state.push_string(b"closed file")?;
954 } else {
955 state.push_string(b"file")?;
956 }
957 }
958 }
959 Ok(1)
960}
961
962fn f_tostring(state: &mut LuaState) -> Result<usize, LuaError> {
971 let p_rc = get_lstream(state)?;
972 let closed = p_rc.borrow().is_closed();
973 if closed {
974 state.push_string(b"file (closed)")?;
975 } else {
976 state.push_string(b"file (0x?)")?;
977 }
978 Ok(1)
979}
980
981fn f_close(state: &mut LuaState) -> Result<usize, LuaError> {
985 let _ = tofile(state)?; aux_close(state)
987}
988
989pub fn io_close(state: &mut LuaState) -> Result<usize, LuaError> {
991 if state.type_at(1) == LuaType::None {
995 state.registry_get(IO_OUTPUT_KEY)?;
996 }
997 f_close(state)
998}
999
1000fn f_gc(state: &mut LuaState) -> Result<usize, LuaError> {
1002 let p_rc = get_lstream(state)?;
1003 let needs_close = {
1004 let p = p_rc.borrow();
1005 !p.is_closed() && p.file.is_some()
1006 };
1007 if needs_close {
1008 let _ = aux_close(state);
1010 }
1011 Ok(0)
1012}
1013
1014pub fn io_open(state: &mut LuaState) -> Result<usize, LuaError> {
1021 let filename: Vec<u8> = state.check_arg_string(1)?;
1022 let mode: Vec<u8> = state.opt_arg_string(2, b"r")?;
1023 if !check_mode(&mode) {
1024 return Err(lua_vm::debug::arg_error_impl(state, 2, b"invalid mode"));
1025 }
1026 let hook = state.global().file_open_hook;
1027 match hook {
1028 Some(open_fn) => match open_fn(&filename, &mode) {
1029 Ok(fh) => {
1030 let cell = new_file(state)?;
1031 cell.borrow_mut().file = Some(fh);
1032 Ok(1)
1033 }
1034 Err(os_err) => file_result(state, false, Some(&filename), os_err),
1035 },
1036 None => {
1037 let os_err =
1038 io::Error::new(io::ErrorKind::Unsupported, "no filesystem hook registered");
1039 file_result(state, false, Some(&filename), os_err)
1040 }
1041 }
1042}
1043
1044pub fn io_popen(state: &mut LuaState) -> Result<usize, LuaError> {
1053 let filename: Vec<u8> = state.check_arg_string(1)?;
1054 let mode: Vec<u8> = state.opt_arg_string(2, b"r")?;
1055 if !check_mode_popen(&mode) {
1056 return Err(lua_vm::debug::arg_error_impl(state, 2, b"invalid mode"));
1057 }
1058 let hook = state.global().popen_hook;
1059 match hook {
1060 Some(spawn_fn) => match spawn_fn(&filename, &mode) {
1061 Ok(fh) => {
1062 let cell = new_pre_file(state)?;
1063 let mut p = cell.borrow_mut();
1064 p.file = Some(fh);
1065 p.close_fn = Some(io_pclose);
1066 drop(p);
1067 Ok(1)
1068 }
1069 Err(e) => {
1070 let os_err = io::Error::new(
1071 io::ErrorKind::Other,
1072 match e.message_bytes() {
1073 Some(b) => String::from_utf8_lossy(b).into_owned(),
1074 None => format!("{:?}", &e),
1075 },
1076 );
1077 file_result(state, false, Some(&filename), os_err)
1078 }
1079 },
1080 None => {
1081 let os_err = io::Error::new(
1082 io::ErrorKind::Unsupported,
1083 "popen not enabled in this build",
1084 );
1085 file_result(state, false, Some(&filename), os_err)
1086 }
1087 }
1088}
1089
1090fn native_temp_name() -> io::Result<Vec<u8>> {
1091 #[cfg(all(target_arch = "wasm32", target_os = "unknown"))]
1092 {
1093 return Err(io::Error::new(
1094 io::ErrorKind::Unsupported,
1095 "temporary files not available in this host",
1096 ));
1097 }
1098
1099 #[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
1100 {
1101 let mut path = std::env::temp_dir().to_string_lossy().as_bytes().to_vec();
1102 if path.last().copied() != Some(b'/') && path.last().copied() != Some(b'\\') {
1103 path.push(b'/');
1104 }
1105 let unique = format!(
1106 "lua_tmpfile_{}_{}",
1107 std::process::id(),
1108 std::time::SystemTime::now()
1109 .duration_since(std::time::UNIX_EPOCH)
1110 .map(|d| d.as_nanos())
1111 .unwrap_or(0)
1112 );
1113 path.extend_from_slice(unique.as_bytes());
1114 Ok(path)
1115 }
1116}
1117
1118pub fn io_tmpfile(state: &mut LuaState) -> Result<usize, LuaError> {
1120 let hook = state.global().file_open_hook;
1121 let Some(open_fn) = hook else {
1122 let os_err = io::Error::new(io::ErrorKind::Unsupported, "no filesystem hook registered");
1123 return file_result(state, false, None, os_err);
1124 };
1125
1126 let temp_name_hook = state.global().temp_name_hook;
1127 let path = match temp_name_hook {
1128 Some(temp_fn) => match temp_fn() {
1129 Ok(path) => path,
1130 Err(e) => {
1131 let msg = match e.message_bytes() {
1132 Some(b) => String::from_utf8_lossy(b).into_owned(),
1133 None => format!("{:?}", &e),
1134 };
1135 return file_result(
1136 state,
1137 false,
1138 None,
1139 io::Error::new(io::ErrorKind::Unsupported, msg),
1140 );
1141 }
1142 },
1143 None => match native_temp_name() {
1144 Ok(path) => path,
1145 Err(e) => return file_result(state, false, None, e),
1146 },
1147 };
1148
1149 match open_fn(&path, b"w+b") {
1150 Ok(fh) => {
1151 let cell = new_file(state)?;
1152 cell.borrow_mut().file = Some(fh);
1153 Ok(1)
1154 }
1155 Err(os_err) => file_result(state, false, None, os_err),
1156 }
1157}
1158
1159fn g_iofile(state: &mut LuaState, key: &[u8], mode: &[u8]) -> Result<usize, LuaError> {
1163 if !matches!(state.type_at(1), LuaType::None | LuaType::Nil) {
1164 if state.type_at(1) == LuaType::String {
1165 let filename = state.check_arg_string(1)?;
1166 opencheck(state, &filename, mode)?;
1167 } else {
1168 let _ = tofile(state)?;
1169 state.push_value_at(1)?;
1170 }
1171 state.registry_set(key)?;
1172 }
1173 state.registry_get(key)?;
1174 Ok(1)
1175}
1176
1177pub fn io_input(state: &mut LuaState) -> Result<usize, LuaError> {
1179 g_iofile(state, IO_INPUT_KEY, b"r")
1180}
1181
1182pub fn io_output(state: &mut LuaState) -> Result<usize, LuaError> {
1184 g_iofile(state, IO_OUTPUT_KEY, b"w")
1185}
1186
1187fn read_number_bytes(file: &mut dyn LuaFileHandle) -> Vec<u8> {
1195 let first = loop {
1196 let b = file.read_byte();
1197 if b == EOF_SENTINEL || !(b as u8).is_ascii_whitespace() {
1198 break b;
1199 }
1200 };
1201
1202 let mut rn = ReadNumState::new(first);
1203
1204 rn.try2(file, [b'-', b'+']);
1205
1206 let mut count: usize = 0;
1207 let hex = if rn.try2(file, [b'0', b'0']) {
1208 if rn.try2(file, [b'x', b'X']) {
1209 true
1210 } else {
1211 count = 1;
1212 false
1213 }
1214 } else {
1215 false
1216 };
1217
1218 count += rn.read_digits(file, hex);
1219
1220 let dec_point = b'.';
1221 if rn.try2(file, [dec_point, b'.']) {
1222 count += rn.read_digits(file, hex);
1223 }
1224
1225 if count > 0 {
1226 let exp_chars = if hex { [b'p', b'P'] } else { [b'e', b'E'] };
1227 if rn.try2(file, exp_chars) {
1228 rn.try2(file, [b'-', b'+']);
1229 rn.read_digits(file, false);
1230 }
1231 }
1232
1233 file.unread_byte(rn.current);
1234 rn.as_bytes().to_vec()
1235}
1236
1237fn test_eof(file: &mut dyn LuaFileHandle) -> bool {
1240 let c = file.read_byte();
1241 if c != EOF_SENTINEL {
1242 file.unread_byte(c);
1243 }
1244 c != EOF_SENTINEL
1245}
1246
1247fn read_line(file: &mut dyn LuaFileHandle, chop: bool) -> (Vec<u8>, bool) {
1255 let mut buf: Vec<u8> = Vec::new();
1256 let mut c: i32;
1257
1258 'outer: loop {
1259 for _ in 0..LUAL_BUFFER_SIZE {
1260 c = file.read_byte();
1261 if c == EOF_SENTINEL || c == b'\n' as i32 {
1262 break 'outer;
1263 }
1264 buf.push(c as u8);
1265 }
1266 }
1267
1268 if !chop && c == b'\n' as i32 {
1269 buf.push(b'\n');
1270 }
1271
1272 let had_content = c == b'\n' as i32 || !buf.is_empty();
1273 (buf, had_content)
1274}
1275
1276fn read_all(file: &mut dyn LuaFileHandle) -> Vec<u8> {
1282 let mut buf: Vec<u8> = Vec::new();
1283 loop {
1284 let mut chunk_read = 0usize;
1285 for _ in 0..LUAL_BUFFER_SIZE {
1286 let b = file.read_byte();
1287 if b == EOF_SENTINEL {
1288 break;
1289 }
1290 buf.push(b as u8);
1291 chunk_read += 1;
1292 }
1293 if chunk_read < LUAL_BUFFER_SIZE {
1294 break;
1295 }
1296 }
1297 buf
1298}
1299
1300fn read_chars(file: &mut dyn LuaFileHandle, n: usize) -> (Vec<u8>, bool) {
1302 let mut buf = Vec::with_capacity(n);
1303 for _ in 0..n {
1304 let b = file.read_byte();
1305 if b == EOF_SENTINEL {
1306 break;
1307 }
1308 buf.push(b as u8);
1309 }
1310 let nr = buf.len();
1311 (buf, nr > 0)
1312}
1313
1314#[derive(Clone, Copy, PartialEq, Eq)]
1317enum ReadFormat {
1318 Number,
1319 Line,
1320 LineWithEol,
1321 All,
1322}
1323
1324fn read_format_requires_star(version: lua_types::LuaVersion) -> bool {
1330 matches!(
1331 version,
1332 lua_types::LuaVersion::V51 | lua_types::LuaVersion::V52
1333 )
1334}
1335
1336fn read_format_has_line_with_eol(version: lua_types::LuaVersion) -> bool {
1341 version != lua_types::LuaVersion::V51
1342}
1343
1344fn resolve_read_format(
1357 version: lua_types::LuaVersion,
1358 fmt: &[u8],
1359) -> Result<ReadFormat, &'static [u8]> {
1360 let option = if read_format_requires_star(version) {
1361 if fmt.first() != Some(&b'*') {
1362 return Err(b"invalid option");
1363 }
1364 fmt.get(1).copied()
1365 } else if fmt.first() == Some(&b'*') {
1366 fmt.get(1).copied()
1367 } else {
1368 fmt.first().copied()
1369 };
1370 match option {
1371 Some(b'n') => Ok(ReadFormat::Number),
1372 Some(b'l') => Ok(ReadFormat::Line),
1373 Some(b'L') if read_format_has_line_with_eol(version) => Ok(ReadFormat::LineWithEol),
1374 Some(b'a') => Ok(ReadFormat::All),
1375 _ => Err(b"invalid format"),
1376 }
1377}
1378
1379fn g_read(
1385 state: &mut LuaState,
1386 p_rc: &Rc<RefCell<LStream>>,
1387 first: i32,
1388) -> Result<usize, LuaError> {
1389 let nargs = (state.top() - first + 1).max(0);
1395 let mut n = first;
1396 let mut success = true;
1397
1398 {
1399 let mut p = p_rc.borrow_mut();
1400 let fh = p.file.as_mut().expect("open stream has no file handle");
1401 fh.clear_error();
1402 }
1403
1404 if nargs == 0 {
1405 let (bytes, had) = {
1406 let mut p = p_rc.borrow_mut();
1407 let fh = p
1408 .file
1409 .as_deref_mut()
1410 .expect("open stream has no file handle");
1411 read_line(fh, true)
1412 };
1413 state.push_string(&bytes)?;
1414 success = had;
1415 n = first + 1;
1416 } else {
1417 state.ensure_stack((nargs as i32) + 20, "too many arguments")?;
1418 let mut remaining = nargs;
1419 while remaining > 0 && success {
1420 if state.type_at(n) == LuaType::Number {
1421 let l = state.check_arg_integer(n)? as usize;
1422 if l == 0 {
1423 let not_eof = {
1424 let mut p = p_rc.borrow_mut();
1425 let fh = p
1426 .file
1427 .as_deref_mut()
1428 .expect("open stream has no file handle");
1429 test_eof(fh)
1430 };
1431 state.push_string(b"")?;
1432 success = not_eof;
1433 } else {
1434 let (bytes, had) = {
1435 let mut p = p_rc.borrow_mut();
1436 let fh = p
1437 .file
1438 .as_deref_mut()
1439 .expect("open stream has no file handle");
1440 read_chars(fh, l)
1441 };
1442 state.push_string(&bytes)?;
1443 success = had;
1444 }
1445 } else {
1446 let s: Vec<u8> = state.check_arg_string(n)?;
1447 let version = state.global().lua_version;
1448 let format = match resolve_read_format(version, &s) {
1449 Ok(format) => format,
1450 Err(extramsg) => {
1451 return Err(lua_vm::debug::arg_error_impl(state, n, extramsg));
1452 }
1453 };
1454 match format {
1455 ReadFormat::Number => {
1456 let bytes = {
1457 let mut p = p_rc.borrow_mut();
1458 let fh = p
1459 .file
1460 .as_deref_mut()
1461 .expect("open stream has no file handle");
1462 read_number_bytes(fh)
1463 };
1464 let pushed = state.string_to_number_push(&bytes)?;
1465 if pushed != 0 {
1466 success = true;
1467 } else {
1468 state.push(LuaValue::Nil);
1469 success = false;
1470 }
1471 }
1472 ReadFormat::Line => {
1473 let (bytes, had) = {
1474 let mut p = p_rc.borrow_mut();
1475 let fh = p
1476 .file
1477 .as_deref_mut()
1478 .expect("open stream has no file handle");
1479 read_line(fh, true)
1480 };
1481 state.push_string(&bytes)?;
1482 success = had;
1483 }
1484 ReadFormat::LineWithEol => {
1485 let (bytes, had) = {
1486 let mut p = p_rc.borrow_mut();
1487 let fh = p
1488 .file
1489 .as_deref_mut()
1490 .expect("open stream has no file handle");
1491 read_line(fh, false)
1492 };
1493 state.push_string(&bytes)?;
1494 success = had;
1495 }
1496 ReadFormat::All => {
1497 let bytes = {
1498 let mut p = p_rc.borrow_mut();
1499 let fh = p
1500 .file
1501 .as_deref_mut()
1502 .expect("open stream has no file handle");
1503 read_all(fh)
1504 };
1505 state.push_string(&bytes)?;
1506 success = true;
1507 }
1508 }
1509 }
1510 n += 1;
1511 remaining -= 1;
1512 }
1513 }
1514
1515 let has_err = {
1516 let p = p_rc.borrow();
1517 match p.file.as_deref() {
1518 Some(fh) => fh.has_error(),
1519 None => false,
1520 }
1521 };
1522 if has_err {
1523 let err = {
1524 let p = p_rc.borrow();
1525 match p.file.as_deref().and_then(|fh| fh.last_error_info()) {
1526 Some((code, _msg)) if code != 0 => io::Error::from_raw_os_error(code),
1527 Some((_code, msg)) => io::Error::new(io::ErrorKind::Other, msg),
1528 None => io::Error::new(io::ErrorKind::Other, "file read error"),
1529 }
1530 };
1531 return file_result(state, false, None, err);
1532 }
1533
1534 if !success {
1535 state.pop_n(1);
1536 state.push(LuaValue::Nil);
1537 }
1538
1539 Ok((n - first) as usize)
1540}
1541
1542fn get_io_file_rc(state: &mut LuaState, key: &[u8]) -> Result<Rc<RefCell<LStream>>, LuaError> {
1547 state.registry_get(key)?;
1548 let ud_id = state
1549 .test_arg_userdata(-1, LUA_FILE_HANDLE)
1550 .map(|ud| ud.identity());
1551 state.pop_n(1);
1552 let label = &key[IO_PREFIX_LEN..];
1553 let id = ud_id.ok_or_else(|| {
1554 LuaError::runtime(format_args!(
1555 "default {} file is invalid",
1556 label.escape_ascii()
1557 ))
1558 })?;
1559 let rc = lookup_lstream(state, id).ok_or_else(|| {
1560 LuaError::runtime(format_args!(
1561 "default {} file is invalid",
1562 label.escape_ascii()
1563 ))
1564 })?;
1565 if rc.borrow().is_closed() {
1566 return Err(LuaError::runtime(format_args!(
1567 "default {} file is closed",
1568 label.escape_ascii()
1569 )));
1570 }
1571 Ok(rc)
1572}
1573
1574pub fn io_read(state: &mut LuaState) -> Result<usize, LuaError> {
1576 let p_rc = get_io_file_rc(state, IO_INPUT_KEY)?;
1577 g_read(state, &p_rc, 1)
1578}
1579
1580pub fn f_read(state: &mut LuaState) -> Result<usize, LuaError> {
1582 let p_rc = tofile(state)?;
1583 g_read(state, &p_rc, 2)
1584}
1585
1586fn num_to_write_bytes(state: &mut LuaState, val: &LuaValue) -> Result<Vec<u8>, LuaError> {
1597 let s = lua_vm::object::num_to_string(state, val)?;
1598 Ok(s.as_bytes().to_vec())
1599}
1600
1601fn collect_write_chunks(state: &mut LuaState, first_arg: i32) -> Result<Vec<Vec<u8>>, LuaError> {
1606 let n = state.top() as i32;
1607 let mut chunks: Vec<Vec<u8>> = Vec::with_capacity((n - first_arg + 1).max(0) as usize);
1608 for i in first_arg..=n {
1609 if state.type_at(i) == LuaType::Number {
1610 let val = state.value_at(i);
1611 chunks.push(num_to_write_bytes(state, &val)?);
1612 } else {
1613 let bytes: Vec<u8> = state.check_arg_string(i)?;
1614 chunks.push(bytes);
1615 }
1616 }
1617 Ok(chunks)
1618}
1619
1620fn g_write(
1646 state: &mut LuaState,
1647 p_rc: &Rc<RefCell<LStream>>,
1648 chunks: &[Vec<u8>],
1649) -> Result<Option<usize>, LuaError> {
1650 let mut total: usize = 0;
1651 let write_err: Option<io::Error> = {
1652 let mut p = p_rc.borrow_mut();
1653 let fh = p.file.as_mut().expect("open stream has no file handle");
1654 let mut err = None;
1655 'chunks: for chunk in chunks {
1656 let mut done: usize = 0;
1657 while done < chunk.len() {
1658 match fh.write_bytes(&chunk[done..]) {
1659 Ok(0) => {
1660 err = Some(io::Error::new(io::ErrorKind::WriteZero, "write error"));
1661 break 'chunks;
1662 }
1663 Ok(n) => {
1664 done += n;
1665 total += n;
1666 }
1667 Err(e) => {
1668 err = Some(e);
1669 break 'chunks;
1670 }
1671 }
1672 }
1673 }
1674 err
1675 };
1676
1677 match write_err {
1678 None => Ok(None),
1679 Some(e) => {
1680 let mut nres = file_result(state, false, None, e)?;
1681 if matches!(state.global().lua_version, lua_types::LuaVersion::V55) {
1682 state.push(LuaValue::Int(total as i64));
1683 nres += 1;
1684 }
1685 Ok(Some(nres))
1686 }
1687 }
1688}
1689
1690pub fn io_write(state: &mut LuaState) -> Result<usize, LuaError> {
1696 let chunks = collect_write_chunks(state, 1)?;
1697 let p_rc = get_io_file_rc(state, IO_OUTPUT_KEY)?;
1698 match g_write(state, &p_rc, &chunks)? {
1699 None => {
1700 state.registry_get(IO_OUTPUT_KEY)?;
1701 Ok(1)
1702 }
1703 Some(nres) => Ok(nres),
1704 }
1705}
1706
1707pub fn f_write(state: &mut LuaState) -> Result<usize, LuaError> {
1709 let p_rc = tofile(state)?;
1710 let chunks = collect_write_chunks(state, 2)?;
1711 match g_write(state, &p_rc, &chunks)? {
1712 None => {
1713 state.push_value_at(1)?;
1714 Ok(1)
1715 }
1716 Some(nres) => Ok(nres),
1717 }
1718}
1719
1720pub fn f_seek(state: &mut LuaState) -> Result<usize, LuaError> {
1724 static MODE_NAMES: &[&[u8]] = &[b"set", b"cur", b"end"];
1725
1726 let p_rc = tofile(state)?;
1727 let op = state.check_arg_option(2, Some(b"cur"), MODE_NAMES)?;
1728 let p3: i64 = state.opt_arg_integer(3, 0)?;
1729
1730 let seek_pos = match op {
1731 0 => SeekFrom::Start(p3 as u64),
1732 1 => SeekFrom::Current(p3),
1733 2 => SeekFrom::End(p3),
1734 _ => unreachable!(),
1735 };
1736
1737 let result = {
1738 let mut p = p_rc.borrow_mut();
1739 let fh = p.file.as_mut().expect("open stream has no file handle");
1740 fh.seek(seek_pos)
1741 };
1742 match result {
1743 Ok(pos) => {
1744 state.push(LuaValue::Int(pos as i64));
1745 Ok(1)
1746 }
1747 Err(e) => file_result(state, false, None, e),
1748 }
1749}
1750
1751pub fn f_setvbuf(state: &mut LuaState) -> Result<usize, LuaError> {
1753 static MODE_NAMES: &[&[u8]] = &[b"no", b"full", b"line"];
1754
1755 let p_rc = tofile(state)?;
1756 let op = state.check_arg_option(2, None, MODE_NAMES)?;
1757 let sz: i64 = state.opt_arg_integer(3, LUAL_BUFFER_SIZE as i64)?;
1758 let mode = match op {
1759 0 => BufMode::No,
1760 1 => BufMode::Full,
1761 2 => BufMode::Line,
1762 _ => unreachable!(),
1763 };
1764 let result = {
1765 let mut p = p_rc.borrow_mut();
1766 let fh = p.file.as_mut().expect("open stream has no file handle");
1767 let mode_index = match mode {
1768 BufMode::No => 0,
1769 BufMode::Full => 1,
1770 BufMode::Line => 2,
1771 };
1772 fh.set_buf_mode(mode_index, sz.max(0) as usize)
1773 };
1774 match result {
1775 Ok(()) => file_result(state, true, None, io::Error::last_os_error()),
1776 Err(e) => file_result(state, false, None, e),
1777 }
1778}
1779
1780pub fn io_flush(state: &mut LuaState) -> Result<usize, LuaError> {
1782 let ud_id: Option<usize> = {
1783 state.registry_get(IO_OUTPUT_KEY)?;
1784 let id = state
1785 .test_arg_userdata(-1, LUA_FILE_HANDLE)
1786 .map(|ud| ud.identity());
1787 state.pop_n(1);
1788 id
1789 };
1790 if let Some(id) = ud_id {
1791 if let Some(rc) = lookup_lstream(state, id) {
1792 let result = {
1793 let mut p = rc.borrow_mut();
1794 if p.is_closed() {
1795 return Err(LuaError::runtime(format_args!(
1796 "default output file is closed"
1797 )));
1798 }
1799 let fh = p
1800 .file
1801 .as_deref_mut()
1802 .expect("open stream has no file handle");
1803 fh.flush()
1804 };
1805 return match result {
1806 Ok(()) => {
1807 state.push(LuaValue::Bool(true));
1808 Ok(1)
1809 }
1810 Err(e) => file_result(state, false, None, e),
1811 };
1812 }
1813 }
1814 state.push(LuaValue::Bool(true));
1816 Ok(1)
1817}
1818
1819pub fn f_flush(state: &mut LuaState) -> Result<usize, LuaError> {
1821 let p_rc = tofile(state)?;
1822 let result = {
1823 let mut p = p_rc.borrow_mut();
1824 let fh = p.file.as_mut().expect("open stream has no file handle");
1825 fh.flush()
1826 };
1827 match result {
1828 Ok(()) => {
1829 state.push(LuaValue::Bool(true));
1830 Ok(1)
1831 }
1832 Err(e) => file_result(state, false, None, e),
1833 }
1834}
1835
1836fn aux_lines(state: &mut LuaState, toclose: bool) -> Result<(), LuaError> {
1846 let n = state.top() - 1;
1849 if n > MAX_ARG_LINE as i32 {
1850 return Err(lua_vm::debug::arg_error_impl(
1851 state,
1852 MAX_ARG_LINE as i32 + 2,
1853 b"too many arguments",
1854 ));
1855 }
1856 state.push_value_at(1)?;
1857 state.push(LuaValue::Int(n as i64));
1858 state.push(LuaValue::Bool(toclose));
1859 state.rotate(2, 3)?;
1860 state.push_c_closure(io_readline, (3 + n) as i32)?;
1861 Ok(())
1862}
1863
1864pub fn f_lines(state: &mut LuaState) -> Result<usize, LuaError> {
1866 let _ = tofile(state)?; aux_lines(state, false)?;
1868 Ok(1)
1869}
1870
1871pub fn io_lines(state: &mut LuaState) -> Result<usize, LuaError> {
1873 if state.type_at(1) == LuaType::None {
1874 state.push(LuaValue::Nil);
1875 }
1876 let toclose = if state.type_at(1) == LuaType::Nil {
1877 state.registry_get(IO_INPUT_KEY)?;
1878 state.replace(1)?;
1879 let _ = tofile(state)?;
1880 false
1881 } else {
1882 let filename = state.check_arg_string(1)?;
1883 opencheck(state, &filename, b"r")?;
1884 state.replace(1)?;
1885 true
1886 };
1887
1888 aux_lines(state, toclose)?;
1889
1890 if toclose && state.global().lua_version.lines_returns_to_be_closed() {
1891 state.push(LuaValue::Nil); state.push(LuaValue::Nil); state.push_value_at(1)?; Ok(4)
1895 } else {
1896 Ok(1)
1897 }
1898}
1899
1900fn io_readline(state: &mut LuaState) -> Result<usize, LuaError> {
1908 let n = match state.value_at(crate::state_stub::upvalue_index(2)) {
1909 LuaValue::Int(i) => i as usize,
1910 _ => 0,
1911 };
1912
1913 let p_rc = lstream_from_upvalue(state, 1)?;
1914
1915 if p_rc.borrow().is_closed() {
1916 return Err(LuaError::runtime(format_args!("file is already closed")));
1917 }
1918
1919 lua_vm::api::set_top(state, 1)?;
1920 state.ensure_stack(n as i32, "too many arguments")?;
1921
1922 for i in 1..=n {
1923 let uv = state.value_at(crate::state_stub::upvalue_index(3 + i as i32));
1924 state.push(uv);
1925 }
1926
1927 let result_n: usize = g_read(state, &p_rc, 2)?;
1928
1929 debug_assert!(result_n > 0, "g_read should return at least one value");
1930
1931 let top = state.top_idx().get() as i32;
1932 let first_result_idx = top - result_n as i32;
1933 let first_truthy = !matches!(
1934 state.stack_at(first_result_idx),
1935 LuaValue::Nil | LuaValue::Bool(false)
1936 );
1937 if first_truthy {
1938 return Ok(result_n);
1939 }
1940
1941 if result_n > 1 {
1942 let err_val = state.stack_at(first_result_idx + 1).clone();
1943 return Err(LuaError::from_value(err_val));
1944 }
1945
1946 let toclose = !matches!(
1947 state.value_at(crate::state_stub::upvalue_index(3)),
1948 LuaValue::Nil | LuaValue::Bool(false)
1949 );
1950 if toclose {
1951 lua_vm::api::set_top(state, 0)?;
1952 state.push_upvalue(1)?;
1953 aux_close(state)?;
1954 }
1955
1956 Ok(0)
1957}
1958
1959fn create_meta(state: &mut LuaState) -> Result<(), LuaError> {
1963 state.new_metatable(LUA_FILE_HANDLE)?;
1964 state.set_funcs(FILE_METAMETHODS, 0)?;
1965 state.new_lib_table(FILE_METHODS)?;
1966 state.set_funcs(FILE_METHODS, 0)?;
1967 state.set_field(-2, b"__index")?;
1968 state.pop_n(1);
1969 Ok(())
1970}
1971
1972fn create_std_file(
1974 state: &mut LuaState,
1975 std_kind: StdFileKind,
1976 registry_key: Option<&[u8]>,
1977 field_name: &[u8],
1978) -> Result<(), LuaError> {
1979 let cell = new_pre_file(state)?;
1980 let output_hook = match std_kind {
1981 StdFileKind::Stdout => state.global().stdout_hook,
1982 StdFileKind::Stderr => state.global().stderr_hook,
1983 StdFileKind::Stdin => None,
1984 };
1985 let input_hook = match std_kind {
1986 StdFileKind::Stdin => state.global().stdin_hook,
1987 StdFileKind::Stdout | StdFileKind::Stderr => None,
1988 };
1989 {
1990 let mut p = cell.borrow_mut();
1991 p.file = Some(Box::new(StdStreamHandle::new(
1992 std_kind,
1993 input_hook,
1994 output_hook,
1995 )));
1996 p.close_fn = Some(io_noclose);
1997 }
1998 if let Some(key) = registry_key {
1999 state.push_value_at(-1)?;
2000 state.registry_set(key)?;
2001 }
2002 state.set_field(-2, field_name)?;
2003 Ok(())
2004}
2005
2006pub fn luaopen_io(state: &mut LuaState) -> Result<usize, LuaError> {
2008 state.new_lib(IO_LIB)?;
2009 create_meta(state)?;
2010 create_std_file(state, StdFileKind::Stdin, Some(IO_INPUT_KEY), b"stdin")?;
2011 create_std_file(state, StdFileKind::Stdout, Some(IO_OUTPUT_KEY), b"stdout")?;
2012 create_std_file(state, StdFileKind::Stderr, None, b"stderr")?;
2013 Ok(1)
2014}
2015
2016#[cfg(test)]
2017mod win32_errno_map_tests {
2018 use super::win32_to_crt_errno;
2019
2020 #[test]
2021 fn file_not_found_yields_enoent() {
2022 assert_eq!(win32_to_crt_errno(2), 2, "ERROR_FILE_NOT_FOUND → ENOENT");
2023 }
2024
2025 #[test]
2026 fn path_not_found_yields_enoent() {
2027 assert_eq!(win32_to_crt_errno(3), 2, "ERROR_PATH_NOT_FOUND → ENOENT");
2028 }
2029
2030 #[test]
2031 fn access_denied_yields_eacces() {
2032 assert_eq!(win32_to_crt_errno(5), 13, "ERROR_ACCESS_DENIED → EACCES");
2033 }
2034
2035 #[test]
2036 fn invalid_handle_yields_ebadf() {
2037 assert_eq!(win32_to_crt_errno(6), 9, "ERROR_INVALID_HANDLE → EBADF");
2038 }
2039
2040 #[test]
2041 fn not_enough_memory_yields_enomem() {
2042 assert_eq!(win32_to_crt_errno(8), 12, "ERROR_NOT_ENOUGH_MEMORY → ENOMEM");
2043 }
2044
2045 #[test]
2046 fn arena_trashed_yields_enomem() {
2047 assert_eq!(win32_to_crt_errno(7), 12, "ERROR_ARENA_TRASHED → ENOMEM");
2048 }
2049
2050 #[test]
2051 fn invalid_block_yields_enomem() {
2052 assert_eq!(win32_to_crt_errno(9), 12, "ERROR_INVALID_BLOCK → ENOMEM");
2053 }
2054
2055 #[test]
2056 fn too_many_open_files_yields_emfile() {
2057 assert_eq!(win32_to_crt_errno(4), 24, "ERROR_TOO_MANY_OPEN_FILES → EMFILE");
2058 }
2059
2060 #[test]
2061 fn bad_environment_yields_e2big() {
2062 assert_eq!(win32_to_crt_errno(10), 7, "ERROR_BAD_ENVIRONMENT → E2BIG");
2063 }
2064
2065 #[test]
2066 fn bad_format_yields_enoexec() {
2067 assert_eq!(win32_to_crt_errno(11), 8, "ERROR_BAD_FORMAT → ENOEXEC");
2068 }
2069
2070 #[test]
2071 fn sharing_violation_yields_eacces() {
2072 assert_eq!(win32_to_crt_errno(32), 13, "ERROR_SHARING_VIOLATION → EACCES");
2073 }
2074
2075 #[test]
2076 fn lock_violation_yields_eacces() {
2077 assert_eq!(win32_to_crt_errno(33), 13, "ERROR_LOCK_VIOLATION → EACCES");
2078 }
2079
2080 #[test]
2081 fn file_exists_yields_eexist() {
2082 assert_eq!(win32_to_crt_errno(80), 17, "ERROR_FILE_EXISTS → EEXIST");
2083 }
2084
2085 #[test]
2086 fn already_exists_yields_eexist() {
2087 assert_eq!(win32_to_crt_errno(183), 17, "ERROR_ALREADY_EXISTS → EEXIST");
2088 }
2089
2090 #[test]
2091 fn broken_pipe_yields_epipe() {
2092 assert_eq!(win32_to_crt_errno(109), 32, "ERROR_BROKEN_PIPE → EPIPE");
2093 }
2094
2095 #[test]
2096 fn disk_full_yields_enospc() {
2097 assert_eq!(win32_to_crt_errno(112), 28, "ERROR_DISK_FULL → ENOSPC");
2098 }
2099
2100 #[test]
2101 fn not_same_device_yields_exdev() {
2102 assert_eq!(win32_to_crt_errno(17), 18, "ERROR_NOT_SAME_DEVICE → EXDEV");
2103 }
2104
2105 #[test]
2106 fn invalid_parameter_yields_einval() {
2107 assert_eq!(win32_to_crt_errno(87), 22, "ERROR_INVALID_PARAMETER → EINVAL");
2108 }
2109
2110 #[test]
2111 fn invalid_function_yields_einval() {
2112 assert_eq!(win32_to_crt_errno(1), 22, "ERROR_INVALID_FUNCTION → EINVAL");
2113 }
2114
2115 #[test]
2116 fn bad_pathname_yields_enoent() {
2117 assert_eq!(win32_to_crt_errno(161), 2, "ERROR_BAD_PATHNAME → ENOENT");
2118 }
2119
2120 #[test]
2121 fn filename_exced_range_yields_enoent() {
2122 assert_eq!(win32_to_crt_errno(206), 2, "ERROR_FILENAME_EXCED_RANGE → ENOENT");
2123 }
2124
2125 #[test]
2126 fn network_access_denied_yields_eacces() {
2127 assert_eq!(win32_to_crt_errno(65), 13, "ERROR_NETWORK_ACCESS_DENIED → EACCES");
2128 }
2129
2130 #[test]
2131 fn drive_locked_yields_eacces() {
2132 assert_eq!(win32_to_crt_errno(108), 13, "ERROR_DRIVE_LOCKED → EACCES");
2133 }
2134
2135 #[test]
2136 fn not_enough_quota_yields_enomem() {
2137 assert_eq!(win32_to_crt_errno(1816), 12, "ERROR_NOT_ENOUGH_QUOTA → ENOMEM");
2138 }
2139
2140 #[test]
2141 fn dir_not_empty_yields_windows_crt_enotempty() {
2142 assert_eq!(
2143 win32_to_crt_errno(145),
2144 41,
2145 "ERROR_DIR_NOT_EMPTY → ENOTEMPTY=41 (Windows CRT)"
2146 );
2147 }
2148
2149 #[test]
2150 fn join_and_subst_family_yields_eacces() {
2151 for code in 133u32..=141 {
2152 assert_eq!(win32_to_crt_errno(code), 13, "join/subst error {code} → EACCES");
2153 }
2154 }
2155
2156 #[test]
2157 fn unmapped_codes_yield_einval() {
2158 for code in [0u32, 14, 19, 20, 21, 22, 23, 100, 999, 65535, u32::MAX] {
2159 assert_eq!(
2160 win32_to_crt_errno(code),
2161 22,
2162 "unmapped Win32 code {code} must yield EINVAL=22 (_dosmaperr default)"
2163 );
2164 }
2165 }
2166
2167 #[test]
2168 fn all_table_codes_map_to_positive_errno() {
2169 let mapped_codes: &[u32] = &[
2170 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 16, 17, 18, 32, 33, 53, 65, 67, 80,
2171 82, 83, 87, 89, 108, 109, 112, 114, 128, 129, 130, 131, 132, 133, 134, 135, 136,
2172 137, 138, 139, 140, 141, 145, 158, 161, 164, 167, 183, 206, 215, 1816,
2173 ];
2174 for &code in mapped_codes {
2175 let errno = win32_to_crt_errno(code);
2176 assert!(
2177 errno > 0,
2178 "Win32 code {code} must map to a positive CRT errno, got {errno}"
2179 );
2180 }
2181 }
2182
2183 #[test]
2184 fn mapped_common_file_errnos_have_posix_strerror_text() {
2185 for win32 in [2u32, 3, 5, 6, 80, 109, 112, 183] {
2186 let errno = win32_to_crt_errno(win32);
2187 assert!(
2188 super::posix_strerror(errno).is_some(),
2189 "Win32 code {win32} maps to errno {errno} which must have strerror text"
2190 );
2191 }
2192 }
2193}