Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get current platform end of line character sequence in Rust?

I'm looking for a way to get the platform end of line character sequence (CRLF for Windows, LF for Linux/macOS) at runtime.

like image 234
Geob-o-matic Avatar asked Nov 28 '17 21:11

Geob-o-matic


1 Answers

I don't believe there is any feature that does this specifically. Even the line-aware features of the standard library don't: BufRead::read_line is documented to only recognize \n, and BufRead::lines (source), which strips end-of-line characters, only does so for \n and \r\n, indiscriminate of what platform it's invoked on.

"Platform line ending" is really a category error, though. Files are sent across networks and copied from one computer to another. If your program writes files that need to be opened on Windows in Notepad, it doesn't matter whether the program that generates them is running on Windows or Linux; it needs to emit \r\n. Similarly if the program is writing a specific file format or implementing some network protocol; the format or protocol should tell you what line separator to use. If the format allows either and there is no convention, pick the one you prefer; just use it consistently.

If you're reading line endings, you should probably tolerate either one, like BufRead::lines does.

However, should you really need to, like if your output will be read by a poorly written program that expects different line endings on different platforms, you can use conditional compilation attributes to achieve this effect:

#[cfg(windows)]
const LINE_ENDING: &'static str = "\r\n";
#[cfg(not(windows))]
const LINE_ENDING: &'static str = "\n";
like image 81
trent Avatar answered Sep 19 '22 21:09

trent