in reply to [OT] Swapping buffers in place.
(updated include a line inside the while loop to increment iter_count - rather a stupid thing to forget.)void swapBufferChunks( U8 *buf, U32 start1, U32 start2, U32 bufsize ) +{ register U64 *p1 = (U64*)&buf[ start1 ]; register U64 *p2 = (U64*)&buf[ start2 ]; register U64 temp; shift_size = p2 - p1; end_buf = p1 + bufsize; # assuming bufsize is byte count item_count = bufsize / 8; # assuming elements are 8-bytes each iter_count = 0; bgn_ofs = p1; temp = *p1; while ( iter_count < item_count ) { if ( p2 = bgn_ofs ) { *p1 = temp; iter_count++; last if ( iter_count == item_count ); # break out of while + loop as soon as this is true p1++; p2++; bgn_ofs = p1; temp = *p1; } *p1 = *p2; iter_count++; p1 = p2; p2 += shift_size; p2 -= bufsize if ( p2 >= end_buf ); } }
(Updating again to mention that my snippet is bound to have a problem when it hits the last iteration; I haven't tried to fix that in the snippet (left as an exercise for the reader) -- hint: must increment iter_count every time a value is assigned to *p1, and must exit the while loop as soon as iter_count reaches the value of item_count.
(final update: last line used to say ... if ( p2 > end_buf ) which was bound to be wrong. Hell, while I'm at. might as well fix the last-iteration problem too. Still, this sort of thing needs really careful testing, which I haven't done.)
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: [OT] Swapping buffers in place.
by BrowserUk (Patriarch) on Mar 01, 2015 at 10:41 UTC |