MCPcopy Create free account
hub / github.com/KaisenAmin/c_std / algorithm_swap

Function algorithm_swap

algorithm/algorithm.c:1489–1535  ·  view source on GitHub ↗

* @brief Swaps the values of two elements. * * @param a Pointer to the first element. * @param b Pointer to the second element. * @param size Size of each element in bytes. */

Source from the content-addressed store, hash-verified

1487 * @param size Size of each element in bytes.
1488 */
1489void algorithm_swap(void *a, void *b, size_t size) {
1490 ALGORITHM_LOG("[algorithm_swap] Info: Swapping two elements of size %zu.", size);
1491
1492 if (!a || !b || a == b || size == 0) {
1493 return;
1494 }
1495
1496 // Fast path: small elements swap byte-by-byte on the stack
1497 enum { STACK_BUF = 256 };
1498 if (size <= STACK_BUF) {
1499 unsigned char temp[STACK_BUF];
1500 memcpy(temp, a, size);
1501 memcpy(a, b, size);
1502 memcpy(b, temp, size);
1503
1504 ALGORITHM_LOG("[algorithm_swap] Success: Stack swap completed.");
1505 return;
1506 }
1507
1508 // Large elements: try heap, fall back to chunked byte swap on OOM so
1509 void *temp = malloc(size);
1510 if (temp) {
1511 memcpy(temp, a, size);
1512 memcpy(a, b, size);
1513 memcpy(b, temp, size);
1514 free(temp);
1515
1516 ALGORITHM_LOG("[algorithm_swap] Success: Heap swap completed.");
1517 return;
1518 }
1519
1520 // OOM fallback: swap in STACK_BUF-sized chunks (correctness-preserving,
1521 // no allocation, never fails).
1522 ALGORITHM_LOG("[algorithm_swap] Warning: malloc failed; using chunked stack swap.");
1523 unsigned char *pa = (unsigned char*)a;
1524 unsigned char *pb = (unsigned char*)b;
1525 unsigned char chunk[STACK_BUF];
1526 size_t remaining = size;
1527
1528 while (remaining > 0) {
1529 size_t n = remaining > STACK_BUF ? STACK_BUF : remaining;
1530 memcpy(chunk, pa, n);
1531 memcpy(pa, pb, n);
1532 memcpy(pb, chunk, n);
1533 pa += n; pb += n; remaining -= n;
1534 }
1535}
1536
1537
1538/**

Callers 1

algorithm_swap_rangesFunction · 0.85

Calls

no outgoing calls

Tested by

no test coverage detected