Skip to content

Commit

Permalink
std::conv: minor optimizations
Browse files Browse the repository at this point in the history
  • Loading branch information
mertcandav committed Aug 11, 2024
1 parent 2fe80d5 commit d335edf
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 8 deletions.
4 changes: 2 additions & 2 deletions std/conv/atoi.jule
Original file line number Diff line number Diff line change
Expand Up @@ -143,8 +143,8 @@ fn parseUint(mut &s: str, mut base: int, mut bitSize: int): (u64, ConvError) {
// Is like ParseInt but for unsigned numbers.
//
// A sign prefix is not permitted.
fn ParseUint(mut s: str, mut base: int, mut bit_size: int)!: u64 {
un, err := parseUint(s, base, bit_size)
fn ParseUint(mut s: str, mut base: int, mut bitSize: int)!: u64 {
un, err := parseUint(s, base, bitSize)
if err != ConvError.Ok {
error(err)
}
Expand Down
19 changes: 13 additions & 6 deletions std/conv/itoa.jule
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
// ====================================================

use std::unsafe
use bits for std::math::bits

// enable fast path for small integers
Expand Down Expand Up @@ -84,9 +85,12 @@ fn Itoa(i: int): str {
// Returns the string for an i with 0 <= i < nSmalls.
fn small(i: int): str {
if i < 10 {
ret digits[i:i+1]
ret str(byte('0' + i))
}
ret smallsStr[i*2 : i*2+2]
mut buf := make([]byte, 3) // Digits + NULL termination.
buf[0] = smallsStr[i<<1]
buf[1] = smallsStr[i<<1+1]
ret unsafe::StrFromBytes(buf[:2])
}

fn isPowerOfTwo(x: int): bool {
Expand Down Expand Up @@ -114,7 +118,8 @@ fn fmtBits(mut dst: []byte, mut u: u64, base: int, neg: bool, append_: bool): (d
// convert bits
// We use uint values where we can because those will
// fit into a single register even on a 32bit machine.
if base == 10 {
match {
| base == 10:
// common case: use constants for / because
// the compiler can optimize it into a multiply+shift

Expand Down Expand Up @@ -163,7 +168,7 @@ fn fmtBits(mut dst: []byte, mut u: u64, base: int, neg: bool, append_: bool): (d
i--
a[i] = smallsStr[is]
}
} else if isPowerOfTwo(base) {
| isPowerOfTwo(base):
// Use shifts and masks instead of / and %.
// Base is a power of 2 and 2 <= base <= len(digits) where len(digits) is 36.
// The largest power of 2 below or equal to 36 is 32, which is 1 << 5;
Expand All @@ -182,7 +187,7 @@ fn fmtBits(mut dst: []byte, mut u: u64, base: int, neg: bool, append_: bool): (d
// u < base
i--
a[i] = digits[uint(u)]
} else {
|:
// general case
b := u64(base)
for u >= b {
Expand All @@ -209,6 +214,8 @@ fn fmtBits(mut dst: []byte, mut u: u64, base: int, neg: bool, append_: bool): (d
d = append(dst, a[i:]...)
ret
}
s = str(a[i:])
n := copy(a, a[i:])
a[n] = 0 // NULL termination.
s = unsafe::StrFromBytes(a[:n])
ret
}

0 comments on commit d335edf

Please sign in to comment.