Base64 optimization question on Twitter (https://twitter.com/davidfowl/status/1679223885256957952?s=20)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.Text.Json; | |
using System.Text.Json.Serialization; | |
var data = new[] | |
{ | |
"Hello"u8.ToArray(), | |
"Twitter"u8.ToArray(), | |
"Optimize"u8.ToArray() | |
} | |
.Select(m => new Message(m)).ToArray(); | |
var response = new Response(MessageBytesToString(data)); | |
Console.WriteLine(JsonSerializer.Serialize(response)); | |
// Turn a list of messages into a single comma separated base64 encoded string | |
string MessageBytesToString(Message[] messages) | |
{ | |
return string.Join(",", messages.Select(m => Convert.ToBase64String(m.Payload))); | |
} | |
class Message(byte[] bytes) | |
{ | |
public byte[] Payload => bytes; | |
} | |
class Response(string messages) | |
{ | |
[JsonPropertyName("messages")] | |
public string Messages => messages; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment