Skip to content

Commit

Permalink
Implement String <-> Span<char> conversions (#1090)
Browse files Browse the repository at this point in the history
* Add Span.ToString()

(cherry picked from commit 8861109)

* Implement string <-> Span<char> conversions

(cherry picked from commit a54affc)
  • Loading branch information
jvyden committed Jul 27, 2023
1 parent fe2c3fc commit e49409c
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 0 deletions.
10 changes: 10 additions & 0 deletions Source/Mosa.Korlib/System/Span.cs
Original file line number Diff line number Diff line change
Expand Up @@ -137,4 +137,14 @@ public Span<T> Slice(int start, int length)

return new Span<T>(ref Unsafe.Add(ref _pointer.Value, (nint)(uint)start), length);
}

public override string ToString()
{
if (typeof(T) == typeof(char))
{
return new string(new ReadOnlySpan<char>(ref Unsafe.As<T, char>(ref this._pointer.Value), this._length));
}

return $"{nameof(System)}.{nameof(Span<T>)}";
}
}
12 changes: 12 additions & 0 deletions Source/Mosa.Korlib/System/String.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using Stack = System.Collections.Stack;

namespace System;

Expand Down Expand Up @@ -340,6 +341,17 @@ public override bool Equals(object obj)
return !Equals(a, b);
}

public static unsafe implicit operator ReadOnlySpan<char>(string s)
{
if (s == null) return ReadOnlySpan<char>.Empty;
return new ReadOnlySpan<char>(s.first_char, s.length);
}

public static implicit operator string(Span<char> span)
{
return span.ToString();
}

public static unsafe bool Equals(string a, string b)
{
if (a == null || b == null) { return false; }
Expand Down

0 comments on commit e49409c

Please sign in to comment.