Remove old shuffle header

This commit is contained in:
Justine Tunney 2024-12-30 03:03:32 -08:00
parent c7e3d9f7ff
commit a51ccc8fb1
No known key found for this signature in database
GPG key ID: BE714B4575D6E328
5 changed files with 64 additions and 32 deletions

View file

@ -1,21 +0,0 @@
#ifndef COSMOPOLITAN_LIBC_RAND_SHUFFLE_H_
#define COSMOPOLITAN_LIBC_RAND_SHUFFLE_H_
#include "libc/intrin/xchg.h"
/**
* Fisher-Yates shuffle.
*
* @param R is a function like rand() 0
* @param A is a typed array
* @param n is the number of items in A
* @see ARRAYLEN()
*/
#define shuffle(R, A, n) \
do { \
autotype(A) Array = (A); \
for (size_t i = (n) - 1; i >= 1; --i) { \
xchg(&Array[i], &Array[R() % (i + 1)]); \
} \
} while (0)
#endif /* COSMOPOLITAN_LIBC_RAND_SHUFFLE_H_ */

View file

@ -44,9 +44,8 @@ ssize_t getdelim_unlocked(char **s, size_t *n, int delim, FILE *f) {
*n = 0;
for (i = 0;; i += m) {
m = f->end - f->beg;
if ((p = memchr(f->buf + f->beg, delim, m))) {
if ((p = memchr(f->buf + f->beg, delim, m)))
m = p + 1 - (f->buf + f->beg);
}
if (i + m + 1 > *n) {
n2 = i + m + 1;
s2 = realloc(*s, n2);
@ -59,10 +58,9 @@ ssize_t getdelim_unlocked(char **s, size_t *n, int delim, FILE *f) {
}
}
memcpy(*s + i, f->buf + f->beg, m);
(*s)[i + m] = '\0';
if ((f->beg += m) == f->end) {
(*s)[i + m] = 0;
if ((f->beg += m) == f->end)
f->beg = f->end = 0;
}
if (p) {
return i + m;
} else if (f->fd == -1) {
@ -71,7 +69,7 @@ ssize_t getdelim_unlocked(char **s, size_t *n, int delim, FILE *f) {
if (!rc)
break;
f->end = rc;
} else if (errno != EINTR) {
} else {
f->state = errno;
return -1;
}

View file

@ -16,14 +16,23 @@
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
#include "libc/mem/shuffle.internal.h"
#include "libc/stdio/rand.h"
#include "libc/str/str.h"
/**
* Jumbles up string.
* Performs Fisher-Yates shuffle on string in-place to create anagram.
*
* This implementation uses rand() so `srand(time(0))` may be desired.
*/
char *strfry(char *s) {
shuffle(rand, s, strlen(s));
size_t i = strlen(s);
while (i > 1) {
size_t x = rand();
size_t y = rand();
size_t j = ((x << 31) ^ y) % i--;
char t = s[j];
s[j] = s[i];
s[i] = t;
}
return s;
}