import t, c


ATOMIC_RELAXED: t.CDefine = 0
ATOMIC_CONSUME: t.CDefine = 1
ATOMIC_ACQUIRE: t.CDefine = 2
ATOMIC_RELEASE: t.CDefine = 3
ATOMIC_ACQ_REL: t.CDefine = 4
ATOMIC_SEQ_CST: t.CDefine = 5


def __atomic_test_and_set(ptr: t.CUInt64T | t.CPtr, order: t.CInt) -> t.CBool:
    result: t.CUInt8T = 1
    c.Asm(f"""mov al, 1
              xchg byte ptr [{c.AsmInp(ptr, t.ASM_DESCR.REG_ANY)}], al
              mov {c.AsmOut(result, t.ASM_DESCR.OUTPUT_REG)}, al""",
        out = [c.AsmOut(result, t.ASM_DESCR.OUTPUT_REG)],
        inp = [c.AsmInp(ptr, t.ASM_DESCR.REG_ANY)],
        op = [t.ASM_DESCR.CLOBBER_MEMORY, t.ASM_DESCR.CLOBBER_RAX])
    return t.CBool(result)


def __atomic_clear(ptr: t.CUInt64T | t.CPtr, order: t.CInt) -> t.CVoid:
    c.Asm(f"""mov byte ptr [{c.AsmInp(ptr, t.ASM_DESCR.REG_ANY)}], 0""",
        inp = [c.AsmInp(ptr, t.ASM_DESCR.REG_ANY)],
        op = [t.ASM_DESCR.CLOBBER_MEMORY])


def __atomic_thread_fence(order: t.CInt) -> t.CVoid:
    c.Asm("mfence", op=[t.ASM_DESCR.CLOBBER_MEMORY])


def __atomic_signal_fence(order: t.CInt) -> t.CVoid:
    pass


def __atomic_always_lock_free(size: t.CSizeT, ptr: t.CVoid | t.CPtr) -> t.CBool:
    return t.CBool(1)


def __atomic_is_lock_free(size: t.CSizeT, ptr: t.CVoid | t.CPtr) -> t.CBool:
    return t.CBool(1)
