aboutsummaryrefslogtreecommitdiff
path: root/crates/sloth_vm/src/sloth_std/file.rs
diff options
context:
space:
mode:
authornic-gaffney <gaffney_nic@protonmail.com>2023-04-14 03:20:23 -0500
committernic-gaffney <gaffney_nic@protonmail.com>2023-04-14 03:20:23 -0500
commitf6e14f4b2b15b0ace8ed312252ae107f139bd33d (patch)
tree34d844e1c4f1be2c95ef87e6363a76b3502bb40f /crates/sloth_vm/src/sloth_std/file.rs
parent97b7cd10d2bec408cc237e13c61562c810d8fd29 (diff)
downloadsloth-f6e14f4b2b15b0ace8ed312252ae107f139bd33d.tar.gz
Terminal and file stuff
Diffstat (limited to 'crates/sloth_vm/src/sloth_std/file.rs')
-rw-r--r--crates/sloth_vm/src/sloth_std/file.rs73
1 files changed, 73 insertions, 0 deletions
diff --git a/crates/sloth_vm/src/sloth_std/file.rs b/crates/sloth_vm/src/sloth_std/file.rs
new file mode 100644
index 0000000..b6c8adf
--- /dev/null
+++ b/crates/sloth_vm/src/sloth_std/file.rs
@@ -0,0 +1,73 @@
+use std::fs;
+
+use crate::native::{self, NativeFunction, NativeFunctionResult};
+use crate::value::{Object, ObjectType, Primitive};
+use crate::VM;
+
+fn file_read(vm: &mut VM, args: &[Primitive]) -> NativeFunctionResult {
+ let Some(Primitive::Object(ptr)) = args.get(0).cloned() else {
+ return Err(native::Error::InvalidArgument);
+ };
+
+ let object = vm
+ .objects()
+ .get(ptr as usize)
+ .ok_or(native::Error::InvalidArgument)?;
+
+ let ObjectType::String(str) = &object.typ else {
+ return Err(native::Error::InvalidArgument);
+ };
+
+ let contents = fs::read_to_string(str).expect("IO Error: Failed to read file!");
+
+ let object = Object::new(ObjectType::String(contents));
+ let ptr = vm.objects_mut().allocate(object);
+
+ Ok(Primitive::Object(ptr as u32))
+}
+
+pub const FILE_READ: NativeFunction = NativeFunction {
+ name: "file$read",
+ function: file_read,
+ arity: 1,
+ returns_value: true,
+};
+
+fn file_write(vm: &mut VM, args: &[Primitive]) -> NativeFunctionResult {
+ let Some(Primitive::Object(path_ptr)) = args.get(0).cloned() else {
+ return Err(native::Error::InvalidArgument);
+ };
+
+ let path_object = vm
+ .objects()
+ .get(path_ptr as usize)
+ .ok_or(native::Error::InvalidArgument)?;
+
+ let ObjectType::String(path) = &path_object.typ else {
+ return Err(native::Error::InvalidArgument);
+ };
+
+ let Some(Primitive::Object(content_ptr)) = args.get(1).cloned() else {
+ return Err(native::Error::InvalidArgument);
+ };
+
+ let content_object = vm
+ .objects()
+ .get(content_ptr as usize)
+ .ok_or(native::Error::InvalidArgument)?;
+
+ let ObjectType::String(content) = &content_object.typ else {
+ return Err(native::Error::InvalidArgument);
+ };
+
+ let _ = fs::write(path, content);
+
+ Ok(Primitive::Empty)
+}
+
+pub const FILE_WRITE: NativeFunction = NativeFunction {
+ name: "file$write",
+ function: file_write,
+ arity: 2,
+ returns_value: false,
+};