ziglang/zig
262
6.0k
Fork
You've already forked zig
782

There are too many integer parsing implementations in the standard library #30881

Open
opened 2026年01月18日 12:34:32 +01:00 by rpkak · 6 comments
Contributor
Copy link

#12446
#24687

In addition to std.fmt.parse* functions there are in no particular order:

One problem with such code duplication is that more code means more bugs. While writing this, I found #30880.

Some of the implementations above (like std.math.big.int.Mutable.setString) are likely too specific to benefit from a common implementation, but many of these use cases could use a common implementation.

Some properties that, in my opinion, should be configurable in a common implementation (feel free to argue against these or in favour of other properties):

  • Should symbols like _ be allowed between digits? Which symbols (', _)?
  • Are + and - allowed?
  • What base is the number? Should prefixes like 0x, 0o and 0b change the base to 16, 8 and 2.
  • Is a leading 0 allowed? Should it change the base to 8?
  • Is the complete input string a number or only the beginning of the input string?

Like the author of #24687, I'm not sure what the ideal API would look like. #12446 proposed a config struct.

There are both use cases, for the base to be comptime known and for the base to be known only at runtime (and for the base to be specified by a prefix).

For some use cases the exact length of the input string is comptime known, for other use cases it is not.

For some use cases like std.process.posixGetUserInfoPasswdStream, it might make sense to use a std.Io.Reader instead of a string as the input, but in other use cases, parsing from a fixed reader would probably generate worse machine code than parsing from a string. Also, since string representations of integers are not very long in most use cases, it might make sense in general to first create a []const u8 of the input.

[#12446](https://github.com/ziglang/zig/issues/12446) [#24687](https://github.com/ziglang/zig/issues/24687) In addition to `std.fmt.parse*` functions there are in no particular order: - [`std.crypto.Certificate.parseTimeDigits`](https://codeberg.org/ziglang/zig/src/commit/e5dc5a6eb5608c100e78d6116942a4cd17f56d00/lib/std/crypto/Certificate.zig#L653-L667) - [`std.crypto.Certificate.parseYear4`](https://codeberg.org/ziglang/zig/src/commit/e5dc5a6eb5608c100e78d6116942a4cd17f56d00/lib/std/crypto/Certificate.zig#L682-L694) - [`std.http.Client.Response.Head.parseInt3`](https://codeberg.org/ziglang/zig/src/commit/e5dc5a6eb5608c100e78d6116942a4cd17f56d00/lib/std/http/Client.zig#L694-L699) - [`std.Io.net.Ip4Address.parse`](https://codeberg.org/ziglang/zig/src/commit/e5dc5a6eb5608c100e78d6116942a4cd17f56d00/lib/std/Io/net.zig#L354-L384) - [`std.Io.net.Ip6Address.parse`](https://codeberg.org/ziglang/zig/src/commit/e5dc5a6eb5608c100e78d6116942a4cd17f56d00/lib/std/Io/net.zig#L465-L572) - [`std.fmt.Parser.number`](https://codeberg.org/ziglang/zig/src/commit/e5dc5a6eb5608c100e78d6116942a4cd17f56d00/lib/std/fmt.zig#L167-L181) - [here](https://codeberg.org/ziglang/zig/src/commit/e5dc5a6eb5608c100e78d6116942a4cd17f56d00/lib/std/fmt/parse_float/parse.zig#L43-L46), [here](https://codeberg.org/ziglang/zig/src/commit/e5dc5a6eb5608c100e78d6116942a4cd17f56d00/lib/std/fmt/parse_float/parse.zig#L58-L65), [here](https://codeberg.org/ziglang/zig/src/commit/e5dc5a6eb5608c100e78d6116942a4cd17f56d00/lib/std/fmt/parse_float/parse.zig#L80-L85), [here](https://codeberg.org/ziglang/zig/src/commit/e5dc5a6eb5608c100e78d6116942a4cd17f56d00/lib/std/fmt/parse_float/decimal.zig#L245-L247), [here](https://codeberg.org/ziglang/zig/src/commit/e5dc5a6eb5608c100e78d6116942a4cd17f56d00/lib/std/fmt/parse_float/decimal.zig#L268-L270), and [here](https://codeberg.org/ziglang/zig/src/commit/e5dc5a6eb5608c100e78d6116942a4cd17f56d00/lib/std/fmt/parse_float/decimal.zig#L305-L309) in `std.fmt.parse_float` - [`std.http.ChunkParser.feed`](https://codeberg.org/ziglang/zig/src/commit/e5dc5a6eb5608c100e78d6116942a4cd17f56d00/lib/std/http/ChunkParser.zig#L52-L78) - [`std.zig.number_literal.parseNumberLiteral`](https://codeberg.org/ziglang/zig/src/commit/e5dc5a6eb5608c100e78d6116942a4cd17f56d00/lib/std/zig/number_literal.zig#L65-L179) - Parsing of escape sequences in strings in [zig](https://codeberg.org/ziglang/zig/src/commit/e5dc5a6eb5608c100e78d6116942a4cd17f56d00/lib/std/zig/string_literal.zig#L151-L234) and [json](https://codeberg.org/ziglang/zig/src/commit/e5dc5a6eb5608c100e78d6116942a4cd17f56d00/lib/std/json/Scanner.zig#L722-L904) - [`std.zig.AstGen.parseBitCount`](https://codeberg.org/ziglang/zig/src/commit/e5dc5a6eb5608c100e78d6116942a4cd17f56d00/lib/std/zig/AstGen.zig#L8210-L8229) - `std.process`: parsing [uid](https://codeberg.org/ziglang/zig/src/commit/e5dc5a6eb5608c100e78d6116942a4cd17f56d00/lib/std/process.zig#L199-L221) and [gid](https://codeberg.org/ziglang/zig/src/commit/e5dc5a6eb5608c100e78d6116942a4cd17f56d00/lib/std/process.zig#L222-L244) from `/etc/passwd` - [one implementation](https://codeberg.org/ziglang/zig/src/commit/e5dc5a6eb5608c100e78d6116942a4cd17f56d00/lib/c/stdlib.zig#L200-L233) used by libzigc for `ato*` and `strto*` functions (#30792). - [`std.math.big.int.Mutable.setString`](https://codeberg.org/ziglang/zig/src/commit/e5dc5a6eb5608c100e78d6116942a4cd17f56d00/lib/std/math/big/int.zig#L347-L410) - #30791 - more in aro, translate-c and resinator - maybe more that I haven't found One problem with such code duplication is that more code means more bugs. While writing this, I found #30880. Some of the implementations above (like [`std.math.big.int.Mutable.setString`](https://codeberg.org/ziglang/zig/src/commit/e5dc5a6eb5608c100e78d6116942a4cd17f56d00/lib/std/math/big/int.zig#L347-L410)) are likely too specific to benefit from a common implementation, but many of these use cases could use a common implementation. Some properties that, in my opinion, should be configurable in a common implementation (feel free to argue against these or in favour of other properties): - Should symbols like `_` be allowed between digits? Which symbols (`'`, `_`)? - Are `+` and `-` allowed? - What base is the number? Should prefixes like `0x`, `0o` and `0b` change the base to `16`, `8` and `2`. - Is a leading `0` allowed? Should it change the base to `8`? - Is the complete input string a number or only the beginning of the input string? Like the author of [#24687](https://github.com/ziglang/zig/issues/24687), I'm not sure what the ideal API would look like. [#12446](https://github.com/ziglang/zig/issues/12446) proposed a config struct. There are both use cases, for the base to be comptime known and for the base to be known only at runtime (and for the base to be specified by a prefix). For some use cases the exact length of the input string is comptime known, for other use cases it is not. For some use cases like [`std.process.posixGetUserInfoPasswdStream`](https://codeberg.org/ziglang/zig/src/commit/e5dc5a6eb5608c100e78d6116942a4cd17f56d00/lib/std/process.zig#L154-L247), it might make sense to use a `std.Io.Reader` instead of a string as the input, but in other use cases, parsing from a fixed reader would probably generate worse machine code than parsing from a string. Also, since string representations of integers are not very long in most use cases, it might make sense in general to first create a `[]const u8` of the input.
andrewrk added this to the Urgent milestone 2026年01月18日 22:30:07 +01:00
Shoutouts to https://github.com/ziglang/zig/issues/19231
Contributor
Copy link

One problem with such code duplication is that more code means more bugs.

There's also flip side --- inappropriate code re-use could lead to accepting incorrect strings, like how we accept 6_6_6 ContentLength in HTTP: #30190.

I also stepped into this in TigerBeetle: when implementing our CLI parser, I used fmt.parseInt for numeric arguments, and I hadn't realized that it allows _ until, months later, I went to explicitly add support for _. That was a happy accident in my case, but it could have easily become permanent technical debt.

Actually, right now I realized that my CLI parser allows --cluster=-0, and that is definitely a bug: https://github.com/tigerbeetle/tigerbeetle/pull/3468

I guess my wish here is that, if we have parseInt(s) or parseIntOptions(s, .{}), I would like for those "default" forms to only parse \d+, maybe even forbidding leading zeros, and have embellishments to be explicitly opt-in.

>One problem with such code duplication is that more code means more bugs. There's also flip side --- inappropriate code re-use could lead to accepting incorrect strings, like how we accept 6_6_6 ContentLength in HTTP: https://codeberg.org/ziglang/zig/issues/30190. I also stepped into this in TigerBeetle: when implementing our CLI parser, I used `fmt.parseInt` for numeric arguments, and I hadn't realized that it allows `_` until, months later, I went to explicitly add support for `_`. That was a happy accident in my case, but it could have easily become permanent technical debt. Actually, _right now_ I realized that my CLI parser allows `--cluster=-0`, and _that_ is definitely a bug: https://github.com/tigerbeetle/tigerbeetle/pull/3468 I guess my wish here is that, if we have `parseInt(s)` or `parseIntOptions(s, .{})`, I would like for those "default" forms to only parse `\d+`, maybe even forbidding leading zeros, and have embellishments to be explicitly opt-in.
Member
Copy link

There's also flip side --- inappropriate code re-use could lead to accepting incorrect strings

I ran into this in Kiesel too, most recently in kiesel-js/kiesel@448374d53d.

I guess my wish here is that, if we have parseInt(s) or parseIntOptions(s, .{}), I would like for those "default" forms to only parse \d+, maybe even forbidding leading zeros, and have embellishments to be explicitly opt-in.

I would argue there is no obvious "good" default in this case and options should always be provided, unless the function name is sufficiently clear (e.g. parseDecimalDigits). If that's considered too verbose I agree that \d+ should be the default and everything else opt in.


Right now this issue is focusing on integer parsing but the same applies to std.fmt.parseFloat() - it accepts an arbitrary floating point string format that may or may not be what the application expects. IMO support for things like exponential notation should be configurable.

> There's also flip side --- inappropriate code re-use could lead to accepting incorrect strings I ran into this in Kiesel too, most recently in https://codeberg.org/kiesel-js/kiesel/commit/448374d53d4ba25c7d3db0c78b1d1c76815f92be. > I guess my wish here is that, if we have `parseInt(s)` or `parseIntOptions(s, .{})`, I would like for those "default" forms to only parse `\d+`, maybe even forbidding leading zeros, and have embellishments to be explicitly opt-in. I would argue there is no obvious "good" default in this case and options should always be provided, unless the function name is sufficiently clear (e.g. `parseDecimalDigits`). If that's considered too verbose I agree that `\d+` should be the default and everything else opt in. --- Right now this issue is focusing on integer parsing but the same applies to `std.fmt.parseFloat()` - it accepts an arbitrary floating point string format that may or may not be what the application expects. IMO support for things like exponential notation should be configurable.

I want to point out that it's clear that the intent for some of these was to optimize the implementation for a specific use case. A clear example of this is the first three functions. While I feel that specialized implementations could be reasonable in such cases, I would also argue that there are better ways to implement them, which undermines their reason to exist as "specialized for performance."

If someone with decision-making power can weigh whether to keep them or reuse some general (configurable) function, I would like to take a shot at improving things here.

I want to point out that it's clear that the intent for some of these was to optimize the implementation for a specific use case. A clear example of this is the first three functions. While I feel that specialized implementations could be reasonable in such cases, I would also argue that there are better ways to implement them, which undermines their reason to exist as "specialized for performance." If someone with decision-making power can weigh whether to keep them or reuse some general (configurable) function, I would like to take a shot at improving things here.
Contributor
Copy link
I ended up landing on https://github.com/nektro/zig-extras/blob/master/src/parseDigits.zig

The thing is, if the buffer length is equal to or less than the machine's @sizeOf(usize) and if no special formatting is required, SWAR techniques are usually better.

An example which reimplements the first function:

inlinefnparseTimeDigitsSWARLE(text:*const[2]u8,min:u8,max:u8)!u8{std.debug.assert(min<100);std.debug.assert(min<=max);constd:u16=@bitCast(text.*);constsub=d-%0x3030;constr:u8=@truncate((sub*%0x0A01)>>8);returnif((r-%min)<=(max-min)and(sub+|0x0606)&0xF0F0==0)relseerror.CertificateTimeInvalid;}

On my machine this is around 2.6 times faster than the one in the std.

The thing is, if the buffer length is equal to or less than the machine's `@sizeOf(usize)` and if no special formatting is required, SWAR techniques are usually better. An example which reimplements the first function: ```zig inline fn parseTimeDigitsSWARLE(text: *const [2]u8, min: u8, max: u8) !u8 { std.debug.assert(min < 100); std.debug.assert(min <= max); const d: u16 = @bitCast(text.*); const sub = d -% 0x3030; const r: u8 = @truncate((sub *% 0x0A01) >> 8); return if ((r -% min) <= (max - min) and (sub +| 0x0606) & 0xF0F0 == 0) r else error.CertificateTimeInvalid; } ``` On my machine this is around 2.6 times faster than the one in the std.
Sign in to join this conversation.
No Branch/Tag specified
master
elfv2
spork8
restricted
0.16.x
panic-rewrite
parking-futex-lockfree
windows-Io-cleanup
Io-watch
ParseCommandLineOptions
windows-async-files
poll-ring
debug-file-leaks-differently
debug-file-leaks
ProcessPrng
elfv2-dyn
jobserver
threadtheft
io-threaded-no-queue
0.15.x
Io.net
comptime-allocator
restricted-function-pointers
cli
wasm-linker-writer
wrangle-writer-buffering
sha1-stream
async-await-demo
fixes
0.14.x
ast-node-methods
macos-debug-info
make-vs-configure
fuzz-macos
sans-aro
ArrayList-reserve
incr-bug
llvm-ir-nosanitize-metadata
ci-tarballs
ci-scripts
threadpool
0.12.x
new-pkg-hash
json-diagnostics
more-doctests
rework-comptime-mutation
0.11.x
ci-perf-comment
stage2-async
0.10.x
autofix
0.9.x
aro
hcs
0.8.x
0.7.x
0.16.0
0.15.2
0.15.1
0.15.0
0.14.1
0.14.0
0.12.1
0.13.0
0.12.0
0.11.0
0.10.1
0.10.0
0.9.1
0.9.0
0.8.1
0.8.0
0.7.1
0.7.0
0.6.0
0.5.0
0.4.0
0.3.0
0.2.0
0.1.1
0.1.0
Labels
Clear labels
abi/f32
abi/ilp32
abi/sf
accepted
This proposal is planned.
arch/21k
arch/6502
arch/aarch64
arch/alpha
arch/amdgcn
arch/arc
arch/arc32
arch/arc64
arch/arm
arch/avr
arch/bfin
arch/bpf
arch/colossus
arch/cris
arch/csky
arch/dlx
arch/epiphany
arch/fr30
arch/frv
arch/hexagon
arch/hppa
arch/hppa64
arch/ia64
arch/kalimba
arch/kvx
arch/lanai
arch/lm32
arch/loongarch32
arch/loongarch64
arch/m32r
arch/m68k
arch/m88k
arch/mcore
arch/microblaze
arch/mips
arch/mips64
arch/mmix
arch/moxie
arch/mrisc32
arch/msp430
arch/nds32
arch/ns32k
arch/nvptx
arch/or1k
arch/powerpc
arch/powerpc64
arch/propeller
arch/riscv32
arch/riscv64
arch/rl78
arch/rx
arch/s390x
arch/sh
arch/sparc
arch/sparc64
arch/spirv
arch/spu
arch/tricore
arch/v850
arch/vax
arch/vc4
arch/ve
arch/wasm
arch/x86
arch/x86_64
arch/xcore
arch/xtensa
autodoc
The web application for interactive documentation and generation of its assets.
backend/c
The C backend outputs C source code.
backend/llvm
The LLVM backend outputs an LLVM bitcode module.
backend/self-hosted
The self-hosted backends produce machine code directly.
binutils
Zig's included binary utilities: zig ar, zig dlltool, zig lib, zig ranlib, zig objcopy, and zig rc.
breaking
Implementing this issue could cause existing code to no longer compile or have different behavior.
build system
The Zig build system - zig build, std.Build, the build runner, and package management.
debug info
An issue related to debug information (e.g. DWARF) produced by the Zig compiler.
docs
An issue with documentation, e.g. the language reference or standard library doc comments.
error message
This issue points out an error message that is unhelpful and should be improved.
frontend
Tokenization, parsing, AstGen, ZonGen, Sema, Legalize, and Liveness.
fuzzing
An issue related to Zig's integrated fuzz testing.
incremental
Reuse of internal compiler state for faster compilation.
lib/c
This issue relates to Zig's libc implementation and/or vendored libcs.
lib/compiler-rt
This issue relates to Zig's compiler-rt library.
lib/cxx
This issue relates to Zig's vendored libc++ and/or libc++abi.
lib/std
This issue relates to Zig's standard library.
lib/tsan
This issue relates to Zig's vendored libtsan.
lib/ubsan-rt
This issue relates to Zig's ubsan-rt library.
lib/unwind
This issue relates to Zig's vendored libunwind.
linking
Zig's integrated object file and incremental linker.
miscompilation
The compiler reports success but produces semantically incorrect code.
os/android
os/contiki
os/dragonfly
os/driverkit
os/emscripten
os/freebsd
os/fuchsia
os/haiku
os/hermit
os/hurd
os/illumos
os/ios
os/linux
os/maccatalyst
os/macos
os/managarm
os/netbsd
os/ohos
os/openbsd
os/plan9
os/redox
os/rtems
os/serenity
os/tvos
os/uefi
os/visionos
os/wasi
os/watchos
os/windows
proposal
This issue suggests language modifications. If it also has the "accepted" label then it is planned.
release notes
This issue or pull request should be mentioned in the release notes.
testing
This issue is related to testing the compiler, standard library, or other parts of Zig.
zig cc
Zig as a drop-in C-family compiler.
zig fmt
The Zig source code formatter.
zig reduce
The Zig source code reduction tool.
bounty
https://ziglang.org/news/announcing-donor-bounties
bug
Observed behavior contradicts documented or intended behavior.
contributor-friendly
This issue is limited in scope and/or knowledge of project internals.
downstream
An issue with a third-party project that uses this project.
enhancement
Solving this issue will likely involve adding new logic or components to the codebase.
infra
An issue related to project infrastructure, e.g. continuous integration.
optimization
A task to improve performance and/or resource usage.
question
No questions on the issue tracker; use a community space instead.
regression
Something that used to work in a previous version stopped working
upstream
An issue with a third-party project that this project uses.
use case
Describes a real use case that is difficult or impossible, but does not propose a solution.
No labels
abi/f32
abi/ilp32
abi/sf
accepted
arch/21k
arch/6502
arch/aarch64
arch/alpha
arch/amdgcn
arch/arc
arch/arc32
arch/arc64
arch/arm
arch/avr
arch/bfin
arch/bpf
arch/colossus
arch/cris
arch/csky
arch/dlx
arch/epiphany
arch/fr30
arch/frv
arch/hexagon
arch/hppa
arch/hppa64
arch/ia64
arch/kalimba
arch/kvx
arch/lanai
arch/lm32
arch/loongarch32
arch/loongarch64
arch/m32r
arch/m68k
arch/m88k
arch/mcore
arch/microblaze
arch/mips
arch/mips64
arch/mmix
arch/moxie
arch/mrisc32
arch/msp430
arch/nds32
arch/ns32k
arch/nvptx
arch/or1k
arch/powerpc
arch/powerpc64
arch/propeller
arch/riscv32
arch/riscv64
arch/rl78
arch/rx
arch/s390x
arch/sh
arch/sparc
arch/sparc64
arch/spirv
arch/spu
arch/tricore
arch/v850
arch/vax
arch/vc4
arch/ve
arch/wasm
arch/x86
arch/x86_64
arch/xcore
arch/xtensa
autodoc
backend/c
backend/llvm
backend/self-hosted
binutils
breaking
build system
debug info
docs
error message
frontend
fuzzing
incremental
lib/c
lib/compiler-rt
lib/cxx
lib/std
lib/tsan
lib/ubsan-rt
lib/unwind
linking
miscompilation
os/android
os/contiki
os/dragonfly
os/driverkit
os/emscripten
os/freebsd
os/fuchsia
os/haiku
os/hermit
os/hurd
os/illumos
os/ios
os/linux
os/maccatalyst
os/macos
os/managarm
os/netbsd
os/ohos
os/openbsd
os/plan9
os/redox
os/rtems
os/serenity
os/tvos
os/uefi
os/visionos
os/wasi
os/watchos
os/windows
proposal
release notes
testing
zig cc
zig fmt
zig reduce
bounty
bug
contributor-friendly
downstream
enhancement
infra
optimization
question
regression
upstream
use case
Milestone
Clear milestone
No items
No milestone
Projects
Clear projects
No items
No project
Assignees
Clear assignees
No assignees
6 participants
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
ziglang/zig#30881
Reference in a new issue
ziglang/zig
No description provided.
Delete branch "%!s()"

Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?