Skip to content

Commit 495291b

Browse files
committed
Reorder elements without requiring Clone
1 parent 6a30625 commit 495291b

2 files changed

Lines changed: 25 additions & 2 deletions

File tree

‎libcc2rs/src/rc.rs‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1328,12 +1328,14 @@ fn root_address(root: &SliceRoot) -> *const () {
13281328
// Moves the element at(order[i]) to at(i), for every i, as std::sort does
13291329
// once it knows the order. The elements are swapped, which moves them instead
13301330
// of copying them.
1331-
pub fn reorder<T: Clone + ByteRepr>(mut order: Vec<isize>, at: impl Fn(isize) -> Ptr<T>) {
1331+
pub fn reorder<T: ByteRepr>(mut order: Vec<isize>, at: impl Fn(isize) -> Ptr<T>) {
13321332
for i in 0..order.len() {
13331333
let mut cur = i;
13341334
while order[cur] as usize != i {
13351335
let next = order[cur] as usize;
1336-
at(cur as isize).swap_with(&at(next as isize), Ptr::read);
1336+
at(cur as isize).swap_with(&at(next as isize), |_| {
1337+
unreachable!("the elements of a range are in the same array")
1338+
});
13371339
order[cur] = cur as isize;
13381340
cur = next;
13391341
}

‎tests/unit/sort_no_copy.cpp‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,16 @@ bool operator<(const Tracked &a, const Tracked &b) { return a.v < b.v; }
2626

2727
bool greater(const Tracked &a, const Tracked &b) { return a.v > b.v; }
2828

29+
struct MoveOnly {
30+
int v;
31+
MoveOnly(int v) : v(v) {}
32+
MoveOnly(MoveOnly &&) = default;
33+
MoveOnly &operator=(MoveOnly &&) = default;
34+
MoveOnly(const MoveOnly &) = delete;
35+
};
36+
37+
bool operator<(const MoveOnly &a, const MoveOnly &b) { return a.v < b.v; }
38+
2939
struct Bag {
3040
std::vector<Tracked> items;
3141
};
@@ -101,5 +111,16 @@ int main() {
101111
assert(bag_map.find(bags[2])->second == 2);
102112
assert(bag_map.find(bags[1]) == bag_map.end());
103113
assert(copies == 0);
114+
115+
std::vector<MoveOnly> moves;
116+
moves.emplace_back(3);
117+
moves.emplace_back(1);
118+
moves.emplace_back(2);
119+
std::sort(moves.begin(), moves.end());
120+
assert(moves[0].v == 1 && moves[1].v == 2 && moves[2].v == 3);
121+
std::stable_sort(
122+
moves.begin(), moves.end(),
123+
[](const MoveOnly &a, const MoveOnly &b) { return a.v > b.v; });
124+
assert(moves[0].v == 3 && moves[1].v == 2 && moves[2].v == 1);
104125
return copies;
105126
}

0 commit comments

Comments
 (0)