#include "cpu_work.hpp"

#if defined(__x86_64__) || defined(__amd64__)
// x86-64 file-scoped assembly implementation
#ifdef __APPLE__
asm(".text\n"
    ".globl _spend_cpu_cycles\n"
    "_spend_cpu_cycles:\n"
    "    test %edi, %edi\n" // Test if iterations <= 0
    "    jle .L_end\n"      // Jump to end if <= 0
    ".L_loop:\n"            // Loop start
    "    dec %edi\n"        // Decrement iterations
    "    jnz .L_loop\n"     // Jump back if not zero
    ".L_end:\n"             // End
    "    ret\n"             // Return
);
#else
asm(".text\n"
    ".globl spend_cpu_cycles\n"
    ".type spend_cpu_cycles, @function\n"
    "spend_cpu_cycles:\n"
    "    test %edi, %edi\n" // Test if iterations <= 0
    "    jle .L_end\n"      // Jump to end if <= 0
    ".L_loop:\n"            // Loop start
    "    dec %edi\n"        // Decrement iterations
    "    jnz .L_loop\n"     // Jump back if not zero
    ".L_end:\n"             // End
    "    ret\n"             // Return
    ".size spend_cpu_cycles, .-spend_cpu_cycles\n");
#endif

#elif defined(__aarch64__)
// ARM64 file-scoped assembly implementation
#ifdef __APPLE__
asm(".text\n"
    ".globl _spend_cpu_cycles\n"
    "_spend_cpu_cycles:\n"
    "    cmp w0, wzr\n"     // Compare iterations with zero
    "    b.le .L_end\n"     // Branch to end if <= 0
    ".L_loop:\n"            // Loop start
    "    subs w0, w0, #1\n" // Decrement iterations and set flags
    "    b.ne .L_loop\n"    // Branch back if not zero
    ".L_end:\n"             // End
    "    ret\n"             // Return
);
#else
asm(".text\n"
    ".globl spend_cpu_cycles\n"
    ".type spend_cpu_cycles, %function\n"
    "spend_cpu_cycles:\n"
    "    cmp w0, wzr\n"     // Compare iterations with zero
    "    b.le .L_end\n"     // Branch to end if <= 0
    ".L_loop:\n"            // Loop start
    "    subs w0, w0, #1\n" // Decrement iterations and set flags
    "    b.ne .L_loop\n"    // Branch back if not zero
    ".L_end:\n"             // End
    "    ret\n"             // Return
    ".size spend_cpu_cycles, spend_cpu_cycles\n");
#endif

#endif
