summaryrefslogtreecommitdiff
path: root/zap/src/fndbyte.c
blob: 3283eecd24c5c7158df3be0493472e23633815a9 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
	Copyright 2022 Gabriel Jensen.
	This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0.
	If a copy of the MPL was not distributed with this file, You can obtain one at https://mozilla.org/MPL/2.0/.
*/

#include <zap/priv.h>

#include <stddef.h>
#include <stdint.h>

#if defined(zap_priv_fastimpl)
__asm__ (
	".globl zap_fndbyte\n"

	"zap_fndbyte:\n"
		/*
			void const * ptr
			size_t  num
			uint_least8_t   byte
		*/
#if defined(sus_arch_amd64)
		/* rax: Address of the current element. */
		"movq %rdi,%rax\n"
		/* rsi: Address of the element after the last element. */
		"addq %rdi,%rsi\n"
		/* rcx: Current element. */
	".loop:\n"
		"cmpq %rax,%rsi\n"
		"je .nfnd\n" /* We have went through the entire array without finding the byte. */
		"movb (%rax),%cl\n"
		"cmpb %cl,%dl\n"
		"je .fnd\n" /* We have found the byte. */
		"incq %rax\n"
		"jmp .loop\n"
	".fnd:\n"
		"subq %rdi,%rax\n"
		"ret\n"
	".nfnd:\n"
		"movq $0xFFFFFFFFFFFFFFFF,%rax\n"
		"ret\n"
#elif defined(sus_arch_ia32)
		/* eax: Address of the current element. */
		"movl 0x4(%esp),%eax\n"
		/* ecx: Address of the element after the last element. */
		"movl 0x8(%esp),%ecx\n"
		"addl %eax,%ecx\n"
		/* edx: Byte value. */
		"movb 0xC(%esp),%dl\n"
		/* ebx: Current element. */
		"pushl %ebx\n"
	".loop:\n"
		"cmpl %eax,%ecx\n"
		"je .nfnd\n" /* We have went through the entire array without finding the byte. */
		"movb (%eax),%bl\n"
		"cmpb %bl,%dl\n"
		"je .fnd\n" /* We have found the byte. */
		"incl %eax\n"
		"jmp .loop\n"
	".fnd:\n"
		"popl %ebx\n"
		"subl 0x4(%esp),%eax\n"
		"ret\n"
	".nfnd:\n"
		"popl %ebx\n"
		"movl $0xFFFFFFFF,%eax\n"
		"ret\n"
#endif
);
#else
size_t zap_fndbyte(void const * const _ptr,size_t const _num,uint_least8_t const _byte) {
	uint_least8_t const *       ptr      = (uint_least8_t const *)_ptr;
	uint_least8_t const * const afterbuf = ptr + _num;
	for (;ptr != afterbuf;++ptr) {sus_unlikely (*ptr == _byte) {return ptr - (uint_least8_t const *)_ptr;}}
	return SIZE_MAX;
}
#endif