Skip to content

Commit

Permalink
start on support for assoc sorts
Browse files Browse the repository at this point in the history
  • Loading branch information
Absolucy committed Nov 30, 2024
1 parent 5a5c182 commit 27cc052
Showing 1 changed file with 29 additions and 2 deletions.
31 changes: 29 additions & 2 deletions crates/sort/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,44 @@ extern crate meowtonin;
use meowtonin::{ByondResult, ByondValue};
use std::cmp::Ordering;

fn reassemble_list(list: Vec<[ByondValue; 2]>) -> ByondResult<ByondValue> {
let mut sorted_list = ByondValue::new_list()?;
for [key, value] in list {
sorted_list.write_list_index(key, value)?;
}
Ok(sorted_list)
}

fn assoc_a_b<'a, 'b>(
[a_key, a_val]: &'a [ByondValue; 2],
[b_key, b_val]: &'b [ByondValue; 2],
associative: bool,
) -> (&'a ByondValue, &'b ByondValue) {
if associative {
(a_val, b_val)
} else {
(a_key, b_key)
}
}

#[byond_fn]
pub fn sort_with_proc(mut list: Vec<ByondValue>, proc_name: String) -> Vec<ByondValue> {
pub fn sort_with_proc(
list: ByondValue,
proc_name: String,
associative: Option<bool>,
) -> ByondResult<ByondValue> {
let associative = associative.unwrap_or(false);
let mut list = list.read_assoc_list()?;
list.sort_by(|a, b| {
let (a, b) = assoc_a_b(a, b, associative);
match meowtonin::call_global::<_, _, _, Option<isize>>(&proc_name, [a, b])
.expect("sort proc failed")
{
Some(ret) => ret.cmp(&0),
None => Ordering::Equal,
}
});
list
reassemble_list(list)
}

#[byond_fn]
Expand Down

0 comments on commit 27cc052

Please sign in to comment.