1
0
mirror of https://gitlab.os-k.eu/os-k-team/kvisc.git synced 2023-08-25 14:05:46 +02:00
kvisc/ka/crt/fmt/strtol.k
julianb0 c216d0fbbb
vm
2019-07-05 14:06:14 +02:00

157 lines
2.4 KiB
Plaintext

; The OS/K Team licenses this file to you under the MIT license.
; See the LICENSE file in the project root for more information.
;
; int strtol(const char *str, int base)
;
; rax = integer extracted from str
; rdx = pointer to first invalid byte
;
strtol:
mov ax2, 1
jmp strtoq
;
; int strtoul(const char *str, int base)
;
; rax = integer extracted from str
; rdx = pointer to first invalid byte
;
strtoul:
xor ax2, ax2
jmp strtoq
;
; int strtoq(const char *str, int base, bool signed)
;
; guesses base when 'base'=0
;
strtoq:
xor rax, rax
mov rdx, ax0
; make sure base is in [2, 32]
b.z ax1, 1, .bad
b.a ax1, 36, .bad
; empty string?
b.z b[rdx], 0, .done
.skip_spc:
cmp b[rdx], ' '
inc.z rdx
jmp.z .skip_spc
; skip +
cmp b[rdx], '+'
inc.z rdx
; signed?
test ax2, ax2
xor.z r10, r10
jmp.z .unsigned
; parse '-'
cmp b[rdx], '-'
inc.z rdx
mov.z r10, 1
sub.nz r10, r10
.unsigned:
; base 0
b.z ax1, 0, .base_0
; base prefix?
b.nz b[rdx], '0', .main_loop
inc rdx
movzx rcx, b[rdx]
; "0x"/"0b" prefix
b.z rcx, 0, .done ; "0"
b.z rcx, 'x', .parsed_0x
b.z rcx, 'b', .parsed_0b
; may be octal, but we don't care
; we accept "0110101010" (despite base=2) for instance
jmp .main_loop
.parsed_0x:
; are we in base 16?
; if not, leave rax = 0 and *rdx = 'x'
b.nz ax1, 16, .done
; else
inc rdx
jmp .main_loop
.parsed_0b:
; are we in base 2?
; if not, leave rax = 0 and *rdx = 'b'
b.nz ax1, 2, .done
; else
inc rdx
jmp .main_loop
.base_0:
; guess base
cmp b[rdx], '0'
mov.nz ax1, 10
jmp.nz .main_loop
inc rdx
cmp b[rdx], 'x'
inc.z rdx
mov.z ax1, 16
jmp.z .main_loop
cmp b[rdx], 'b'
inc.z rdx
mov.z ax1, 2
jmp.z .main_loop
mov ax1, 8
.main_loop:
movzx rx8, b[rdx]
inc rdx
cmp rx8, '0'
jmp.b .done
cmp.ae rx8, '9'
sub.be rx8, '0'
jmp.be .next
cmp rx8, 'A'
cmp.ae rx8, 'Z'
sub.be rx8, 55 ; 'A' - 10
jmp.be .next
cmp rx8, 'a'
jmp.b .next
cmp.ae rx8, 'z'
sub.be rx8, 87 ; 'a' - 10
jmp.be .next
.next:
; too large for base?
b.ae rx8, ax1, .done
mul rax, ax1
add rax, rx8
jmp .main_loop
.done:
; negative?
test r10, r10
ret.z
; yes
neg rax, rax
ret
.bad:
mov q[errno], EINVAL
ret