| 158 | |
| 159 | |
| 160 | /* Rotates the bytes of [p, p + left + right) so the `right` bytes that start |
| 161 | * at p + left come first. The smaller side goes through a stack buffer (or a |
| 162 | * heap one) and the larger is moved with one memmove; without memory it falls |
| 163 | * back to in-place block swaps (Gries-Mills), O(n) either way. */ |
| 164 | static void alg_rotate_bytes(char *p, size_t left, size_t right) { |
| 165 | if (left == 0 || right == 0) { |
| 166 | return; |
| 167 | } |
| 168 | unsigned char stackbuf[2048]; |
| 169 | size_t small = left < right ? left : right; |
| 170 | unsigned char *tmp = (small <= sizeof stackbuf) ? stackbuf : (unsigned char *)malloc(small); |
| 171 | if (tmp) { |
| 172 | if (left <= right) { |
| 173 | memcpy(tmp, p, left); |
| 174 | memmove(p, p + left, right); |
| 175 | memcpy(p + right, tmp, left); |
| 176 | } |
| 177 | else { |
| 178 | memcpy(tmp, p + left, right); |
| 179 | memmove(p + right, p, left); |
| 180 | memcpy(p, tmp, right); |
| 181 | } |
| 182 | if (tmp != stackbuf) { |
| 183 | free(tmp); |
| 184 | } |
| 185 | return; |
| 186 | } |
| 187 | while (left != 0 && right != 0) { |
| 188 | if (left <= right) { /* A B1 B2 -> B1 A B2 (B1 is final) */ |
| 189 | alg_swap_bytes(p, p + left, left); |
| 190 | p += left; |
| 191 | right -= left; |
| 192 | } |