Page MenuHomePhabricator

Add `msortv()`, a stable, well-behaved sort method
ClosedPublic

Authored by epriestley on Mar 6 2016, 3:57 PM.
Tags
None
Referenced Files
Unknown Object (File)
Mon, Dec 23, 1:25 AM
Unknown Object (File)
Thu, Dec 5, 1:18 AM
Unknown Object (File)
Nov 20 2024, 6:28 PM
Unknown Object (File)
Nov 15 2024, 8:08 PM
Unknown Object (File)
Nov 12 2024, 12:16 PM
Unknown Object (File)
Nov 9 2024, 2:20 PM
Unknown Object (File)
Nov 8 2024, 11:53 AM
Unknown Object (File)
Nov 1 2024, 5:14 AM
Subscribers
None

Details

Summary

Ref T6861. We currently have three minor issues with sorting:

  • If types get mixed, PHP goes crazy. This is discussed in T6861.
  • The sort isn't guaranteed to be stable (identical input items are not reordered), but we'd probably always prefer a stable sort to a slightly more efficient one.
  • Interacting with sort keys is a mess of sprintf('~%020.020f', ...) nonsense.

Introduce msortv() and PhutilSortVector to solve these. The new msortv() is:

  • well-behaved (no craziness on mixed types); and
  • stable (input items with the same sort key are never reordered).

PhutilSortVector is a helper so you don't have to do the sprintf(...) garbage. Instead, classes will do this:

- return sprintf(
-   '~%020d%s',
-   $this->getOrder(),
-   $this->getName());

+ return id(new PhutilSortVector())
+   ->addInt($this->getOrder())
+   ->addString($this->getName());

This should be easier to read and much easier to get right, particularly for odd inputs at the edge of the range (like the most-negative integer).

Test Plan

Added and executed unit tests.

Diff Detail

Repository
rPHU libphutil
Lint
Lint Not Applicable
Unit
Tests Not Applicable

Event Timeline

epriestley retitled this revision from to Add `msortv()`, a stable, well-behaved sort method.
epriestley updated this object.
epriestley edited the test plan for this revision. (Show Details)
epriestley added a reviewer: chad.

Particular motivation here is that I'm going to be sorting actions and panels, and those sorts need to be stable and I don't particularly want to write yet another sprintf('~%...') method.

chad edited edge metadata.
This revision is now accepted and ready to land.Mar 6 2016, 4:08 PM
This revision was automatically updated to reflect the committed changes.