assemblyscript icon indicating copy to clipboard operation
assemblyscript copied to clipboard

Can the internal SORT<T>(ptr, len, comparator) function be used to sort memory directly?

Open hudsonansley opened this issue 3 years ago • 3 comments

I am working on an AssemblyScript function that manipulates memory directly (setting --memoryBase and using that area) and I am currently using a TypedArray to set values and then sort, and then I copy that to the linear memory. It occurred to me that if I could store the values directly into the memory and sort it in place, that should save some time, and I saw the SORT function in https://github.com/AssemblyScript/assemblyscript/blob/main/std/assembly/util/sort.ts looks like it would do that for me. Is it possible to use that SORT from an AssemblyScript module function? If so, it would be great to see some example code... Related, an example of how to use memcopy in AssemblyScript would be great too...

hudsonansley avatar Sep 11 '22 21:09 hudsonansley

It should be possible to call SORT yourself, like so:

import { SORT, COMPARATOR } from "util";
SORT<i32>(ptr, len, COMPARATOR<i32>()); // or provide a different T / custom comparator

Whether that's a good idea depends a little on the use case I guess. In some cases, SORT allocates temporary buffers on the heap for example. Also note, since this is internal, that there is no guarantee that the function will not be changed, renamed or removed.

dcodeIO avatar Sep 11 '22 23:09 dcodeIO

@MaxGraey Makes me realize that we should probably mark such helpers as @unsafe.

dcodeIO avatar Sep 11 '22 23:09 dcodeIO

I would prefer to add a non-standard static method "compare" for all builtin types. This has been suggested more than once in JS, but as usual it was dissolved in the noise of opinions: https://es.discourse.group/t/builtin-ord-compare-method-for-primitives/724

In this case users will just use this approach:

[1, 2, 0, -2].sort(i32.compare); // same as [1, 2, 0, -2].sort();
['a', 'c', 'b'].sort(String.compare);  // same as ['a', 'c', 'b'].sort();
obj.sort((a, b) => String.compare(a.foo, b.foo));

MaxGraey avatar Sep 12 '22 12:09 MaxGraey

This issue has been automatically marked as stale because it has not had recent activity. It will be closed in one week if no further activity occurs. Thank you for your contributions!

github-actions[bot] avatar Oct 12 '22 23:10 github-actions[bot]