Skip to content

Instantly share code, notes, and snippets.

@GrabYourPitchforks
Last active December 10, 2022 15:14
Show Gist options
  • Save GrabYourPitchforks/86f9e598d6d1f6cd331fc2c7ce02c41d to your computer and use it in GitHub Desktop.
Save GrabYourPitchforks/86f9e598d6d1f6cd331fc2c7ce02c41d to your computer and use it in GitHub Desktop.
MemoryMarshal.Cast challenge
using System;
using System.Runtime.InteropServices;
using System.Text;
class Program
{
static void Main(string[] args)
{
{
// the text below is meaningless
const string text = "abcdefg=䈀㰀笀稀瀀㸀㨀㴀椀栀最㬀昀㼀攀搀挀愀䀀䄀䈀㰀笀稀瀀㸀㨀㴀椀栀最㬀昀㼀攀搀挀愀䀀䄀䈀㰀";
Console.WriteLine(text.ToString());
Console.WriteLine($"UTF-16 length: {text.Length} chars"); // 50 chars
Console.WriteLine($"UTF-8 length: {Encoding.UTF8.GetByteCount(text)} bytes"); // 134 bytes
Console.WriteLine();
Span<char> textAsSpan = text.ToCharArray();
Console.WriteLine(textAsSpan.ToString());
Console.WriteLine($"UTF-16 length: {textAsSpan.Length} chars");
Console.WriteLine($"UTF-8 length: {Encoding.UTF8.GetByteCount(textAsSpan)} bytes");
Console.WriteLine();
textAsSpan = MemoryMarshal.Cast<byte, char>(new byte[4096].AsSpan(1));
text.AsSpan().CopyTo(textAsSpan);
textAsSpan = textAsSpan[0..text.Length];
Console.WriteLine(textAsSpan.ToString());
Console.WriteLine($"UTF-16 length: {textAsSpan.Length} chars");
Console.WriteLine($"UTF-8 length: {Encoding.UTF8.GetByteCount(textAsSpan)} bytes");
Console.WriteLine();
}
Console.WriteLine();
{
const string text = "The quick brown fox jumps over the lazy dog.";
byte[] textAsUtf8 = Encoding.UTF8.GetBytes(text);
Span<char> destination = new char[2048];
int charsWritten = Encoding.UTF8.GetChars(textAsUtf8, destination);
destination = destination[0..charsWritten];
Console.WriteLine(destination.ToString());
Console.WriteLine();
destination = MemoryMarshal.Cast<byte, char>(new byte[4096].AsSpan(1));
charsWritten = Encoding.UTF8.GetChars(textAsUtf8, destination);
destination = destination[0..charsWritten];
Console.WriteLine(destination.ToString());
Console.WriteLine();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment