Skip to content

[Proposal] string.NormalizeLineEndings #40315

Closed

Description

@Symbai

Edit by @GrabYourPitchforks on Wed 31 Mar: Fuller API proposal at the comment #40315 (comment).


Background and Motivation

This is a very common issue developers run into especially on cross platform. When we handle a string which we don't created ourselves it might have a different line ending as expected. On Windows it can be a \n instead of \r\n and on Linux vice versa. On Linux its a bit easier as the workaround can be a simple string.Replace("\r\n", "\n") while on Windows we have to use Regex (because "\r\n".Replace("\n", "\r\n") obviously does something else than we are looking for) and if we don't want to go down the line by reading char by char ourselves. In order to eliminate the issue on all platforms there should be a single API.

Name and place of the API are free to change.

Proposed API

namespace System
{
    public sealed class String
    {

        //
        // Normalizes all line endings to the line ending on which platforms it runs
        //     
        public string NormalizeLineEndings(this string s) {
		#if !PLATFORM_UNIX 
			//Replace all line endings with \r\n
		#else
			//Replace all line endings with \n
		#endif
		}
	}
}

Usage Examples

public class MyPublicAPI
{
	public string DoStuff(string content)
	{
		foreach(string line in content.NormalizeLineEndings().Split(Environment.NewLine))
		{
		}
	}
}
public class MyPublicAPI
{
	public string ShowMessage(string message)
	{
		Console.WriteLine(message.NormalizeLineEndings())
	}
}

Alternative Designs

None

Risks

None

Activity

  1. added
    api-suggestion
    on Aug 4, 2020
  2. added
    untriaged
    on Aug 4, 2020
  3. Dotnet-GitSync-Bot commented on Aug 4, 2020

    @Dotnet-GitSync-Bot
    Collaborator

    I couldn't figure out the best area label to add to this issue. If you have write-permissions please help me learn by adding exactly one area label.

  4. GrabYourPitchforks commented on Aug 5, 2020

    @GrabYourPitchforks
    Member

    Seems reasonable. Wonder if we should do this on StringBuilder as well.

    Behavior would be to find isolated \r, isolated \n, and grouped \r\n and replace them all with Environment.NewLine.

  5. Gnbrkm41 commented on Aug 5, 2020

    @Gnbrkm41
    Contributor

    Would it also be a possible scenario for someone to normalise the line ending to something that isn't Environment.NewLine? e.g. mixed \r\n and \n to all \n on Windows, non-Console environments.

  6. GrabYourPitchforks commented on Aug 5, 2020

    @GrabYourPitchforks
    Member

    @Gnbrkm41 You mean something like below?

    public sealed class string
    {
        // if lineEnding == null, use Environment.NewLine; otherwise use provided lineEnding as a replacement
        public static string NormalizeLineEndings(string input, string? lineEnding = null);
    }
  7. Gnbrkm41 commented on Aug 5, 2020

    @Gnbrkm41
    Contributor

    Ooh.... That's.... Interesting. Never thought about allowing something that isn't CR, LF or CRLF. Doesn't sound too bad, but I suppose the folks will figure out during the API reviews.

  8. added this to the Future milestone on Aug 14, 2020
  9. removed
    untriaged
    on Aug 24, 2020
  10. GrabYourPitchforks commented on Mar 31, 2021

    @GrabYourPitchforks
    Member

    Been thinking about this a little bit more. We already have an enumeration API over string instances:

    string s = GetString();
    var reader = new StringReader(s);
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        // consume 'line'
    }

    It might also be useful to have an enumeration API over ROS<char> instances:

    ReadOnlySpan<char> chars = GetSpan();
    foreach (ReadOnlySpan<char> line in chars.EnumerateLines())
    {
        // consume 'line'
    }

    A string.NormalizeLineEndings API could be built atop the span-based API fairly easily. It would also be a fairly straightforward implementation: O(n * l) in the worst case, where n is the length of the input string and l is the length of the newline replacement string.

  11. GrabYourPitchforks commented on Mar 31, 2021

    @GrabYourPitchforks
    Member

    API proposal

    public class String
    {
        public string NormalizeLineEndings(string? lineEnding = null);
    }
    
    public static class MemoryExtensions
    {
        // mimics the existing methods 'EnumerateRunes'
        public System.Text.SpanLineEnumerator EnumerateLines(this ReadOnlySpan<char> span);
        public System.Text.SpanLineEnumerator EnumerateLines(this Span<char> span);
    }
    
    namespace System.Text
    {
        // mimics the existing type 'SpanRuneEnumerator'
        public ref struct SpanLineEnumerator
        {
            public ReadOnlySpan<char> Current;
            public SpanLineEnumerator GetEnumerator();
            public bool MoveNext();
        }
    }

    Behaviors & usage

    NormalizeLineEndings searches for occurrences of Unicode newline characters, replacing such occurrences with the value of the lineEnding parameter. If lineEnding is nullptr, defaults to Environment.NewLine (the newline sequence for the current platform).

    Open question: should we call the replacement string parameter replacement instead of lineEnding? There's no requirement for this parameter to itself represent a valid newline sequence.

    Examples:

    string s = GetString(); // may contain a mix of CR, LF, CRLF, LS, PS, etc.
    
    // Normalize line endings to Environment.Newline (all calls below are identical)
    string normalized = s.NormalizeLineEndings();
    string normalized = s.NormalizeLineEndings(null);
    string normalized = s.NormalizeLineEndings(Environment.NewLine);
    
    // Normalize line endings to <CR><LF>, regardless of the current platform
    string normalized = s.NormalizeLineEndings("\r\n");
    
    // Normalize line endings to <LS>, regardless of the current platform
    string normalized = s.NormalizeLineEndings("\u2028");
    
    // Remove all line endings by normalizing them to [empty]
    string normalized = s.NormalizeLineEndings("");

    During span-based enumeration, the Current property will refer back to a substring within the original provided string. The enumerator does not give newlines at the beginning or the end of the input string any special consideration, which may result in empty spans being seen during enumeration.

    Examples:

    ReadOnlySpan<char> span = "Hello\nworld!\r\n";
    
    foreach (var line in span.EnumerateLines())
    {
        // On the first loop, line := span[0..5] ("Hello")
        // On the second loop, line := span[6..12] ("world!")
        // On the third loop, line := span[14..14] ("")
        // Loop then terminates
    }

    Discussion

    This API is useful for #50044 and other scenarios where text intended for user display may be transmitted across the wire, where the host system must account for any newline differences between itself and the remote system.

    The Unicode Standard, §5.8, Recommendation R4, provides that any Unicode-compliant readline routine should recognize the following newline sequences: <CR>, <LF>, <CR><LF>, <NEL>, <FF>, <LS>, and <PS>. Our enumeration routine spans this entire list, and we will replace all such subsequences with the specified replacement string.

    This proposed API is not intended for advanced text processing scenarios, such as a rich text editor that cares about the difference between line separators and paragraph separators. This API is not intended for protocol parsers which must restrict their operations to a subset of known line break characters. For instance, if a protocol mandates that only <CR>, <LF>, and <CR><LF> may be used for line breaks, a parser which wants to maintain compliance with the protocol specification should not rely on this API. This also means that the behavior of NormalizeLineEndings and EnumerateLines may differ from TextReader.ReadLine, which understands only <CR>, <LF>, and <CR><LF> by default.

  12. added
    api-ready-for-review
    and removed
    api-suggestion
    on Mar 31, 2021
  13. GrabYourPitchforks commented on Mar 31, 2021

    @GrabYourPitchforks
    Member

    I incorporated some feedback from subject matter experts and marked this API ready for review.

  14. bartonjs commented on May 21, 2021

    @bartonjs
    Member

    Video

    • Instead of default parameter, make a parameterless overload and make the parameter non-nullable
    • The word "Normalize" is overloaded in this space, suggest ReplaceLineEndings instead of NormalizeLineEndings
    • Suggest replacementText instead of lineEnding in the ReplaceLineEndings method.
    • If a char overload seems reasonable, go ahead and add it, too.
    namespace System
    {
        partial class String
        {
            public string ReplaceLineEndings() => ReplaceLineEndings(Environment.NewLine);
            public string ReplaceLineEndings(string replacementText);
        }
        partial class MemoryExtensions
        {
            public System.Text.SpanLineEnumerator EnumerateLines(this ReadOnlySpan<char> span);
            public System.Text.SpanLineEnumerator EnumerateLines(this Span<char> span);
        }
    }
    namespace System.Text
    {
        public ref struct SpanLineEnumerator
        {
            public ReadOnlySpan<char> Current;
            public SpanLineEnumerator GetEnumerator();
            public bool MoveNext();
        }
    }
  15. added
    api-approved
    and removed
    api-ready-for-review
    on May 21, 2021
  16. ghost added
    in-pr
    on May 22, 2021
  17. ghost removed
    in-pr
    on Jun 7, 2021
  18. ghost locked as resolved and limited conversation to collaborators on Jul 7, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

api-approvedarea-System.Runtime

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions