Skip to content

Instantly share code, notes, and snippets.

@davidfowl
Last active July 13, 2023 19:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidfowl/f177a76e4de68a5fff3539a22f727e69 to your computer and use it in GitHub Desktop.
Save davidfowl/f177a76e4de68a5fff3539a22f727e69 to your computer and use it in GitHub Desktop.
Base64 optimization question on Twitter (https://twitter.com/davidfowl/status/1679223885256957952?s=20)
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