4 ms·
Caution with these functions: in most cases you need to check not only the error code, but also the `ptr` in the result. Otherwise you end up with `to_int("0x12
by dgrunwald 2y ago
Caution with these functions: in most cases you need to check not only the error code, but also the `ptr` in the result.
Otherwise you end up with `to_int("0x1234") == 0` instead of the expected `std::nullopt`, because these functions return success if they matched a number at the beginning of the string.
- pilif 2y agohow can this be the ~5th iteration of a very wide-spread use-case and still contain a footgun? The API looks like it's following best-practice, with a specific result type that also contains specific error information and yet, that's not enough and you still end up with edge-cases where things look like they're fine when they aren't.
- amelius 2y agoI suppose the reason is that sometimes you want to parse more than just the number. For example, numbers separated by commas. In that case you will have to call the function repeatedly from your own parsing routine and advance the pointer.
- gpderetta 2y agoYes, if you are parsing in-place numbers in an existing string you do not necessarily know a-priori where the number end. You could have extra logic to look ahead to the end of the number before passing it from_chars, but a) it would require an additional pass and b) you could end up replicating part of the implementation of from chars. from_chars is supposed to be a low lever routine, it must be possible to use it correctly, but it is not necessarily the most ergonomic.
- khwrht 2y agoThat is a good question. The C++ stdlib has some truly bizarre APIs. I wonder if they should freeze std and work on std2.
- otabdeveloper4 2y agofrom_chars is the correct API here. When you're parsing decimal numbers you want to do it with streaming semantics.
- jdbdndj 2y agoI don't see a foot gun, you just need to check if you have consumed the whole input. Which is the norm in nearly any streaming api
- mort96 2y agoIn what way is it streaming? It takes at least the entire numeric string as a string in memory, you can't stream in more data as needed
- randomNumber7 2y agoI didn't see a foot gun either, but somehow my foot went missing.
- deleted 2y ago[deleted]
- pilif 2y agoI get that this is a super low level API, but yet, my expectation about an API that parses a buffer with length to a number and which has a specific enum for error cases as its return type would be that when asked to parse "9not a number" that I would get an error response and not a "the number you asked me to parse is 9 and everything went well" as the result. The whole reason for returning a result enum would be so I don't forget to also check somewhere else whether something could possibly have gone wrong. Especially when there is a specific result type.