HowardHinnant / date

A date and time library based on the C++11/14/17 <chrono> header
Other
3.15k stars 683 forks source link

Parse date string in std::string_view #413

Open guezt1234 opened 5 years ago

guezt1234 commented 5 years ago

Another library (sajson) gives me many arrays of characters representing dates with the same format. Each array is defined by a pointer and a length. To avoid copying each array to a std::string, I try std::string_view.

#include <chrono>
#include <iostream>
#include <string>

int main() {
    std::string s("2018-12-07 20:00:00");
    // suppose the pointer and size are from another library
    std::string_view s_view(s.data(), s.size());

    // try to parse date
    std::chrono::system_clock::time_point dt;
    std::stringstream ss{"2018-12-07 20:00:00"};
    s_view >> date::parse("%F %T", dt);  // Compilation error.
}

But the s_view >> date::parse("%F %T", dt); line gives compilation error. How to avoid copying the data?

Thanks.

HowardHinnant commented 5 years ago

Currently there is no easy way to use this library to parse from a string_view. That is a feature that I might try to get into a future version.

parse only works from std::basic_istream, and so you would have to create a custom set of types derived from std::stringbuf / std::istream using string_view as the backing store in order to accomplish this. Such an exercise is not easy.

Another possibility would be to use the new std::from_chars function to parse from string_view to int and then construct from ints to year_month_day, hours, minutes and seconds.

Spongman commented 1 year ago

this seems like a really weird decision, IMO. a significant portion of the docs are given over to comparing emitted assembly, and yet: <iostream> ...

HowardHinnant commented 1 year ago

General purpose parsing is hard. My money is on Victor Zverovich to come up with something similar to his fmt library.

In the meantime, special purpose high-performance parsing is not that difficult. What makes it easier is you get to decide how much (more likely how little) error handling you want to pursue.

For example here is custom parsing from a string_view I wrote for Posix::time_zone: https://github.com/HowardHinnant/date/blob/master/include/date/ptz.h#L658-L841 and I got a little carried away with fancy error messages. But it is still very fast. And it is not that much code. It is parsing names, times and dates in the several formats that POSIX supports for time zone names (http://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap08.html#tag_08_03).