Skip to content

Instantly share code, notes, and snippets.

@gabrielnic
Last active June 6, 2022 16:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gabrielnic/fa5dfd8af9928636dae2737a8de014db to your computer and use it in GitHub Desktop.
Save gabrielnic/fa5dfd8af9928636dae2737a8de014db to your computer and use it in GitHub Desktop.
// Blob <-> Text funcs
// textFromBlob
public func textFromBlob(blob : Blob) : Text {
Text.join(",", Iter.map<Nat8, Text>(blob.vals(), Nat8.toText));
};
// blobFromText
public func blobFromText(t : Text) : Blob {
// textToNat8
// turns "123" into 123
func textToNat8(txt : Text) : Nat8 {
var num : Nat32 = 0;
for (v in txt.chars()) {
num := num * 10 + (Char.toNat32(v) - 48); // 0 in ASCII is 48
};
Nat8.fromNat(Nat32.toNat(num));
};
let ts = Text.split(t, #char(','));
let bytes = Array.map<Text, Nat8>(Iter.toArray(ts), textToNat8);
Blob.fromArray(bytes);
};
public func testing() : async () {
let u : Types.Test = {
text = "test";
num = 1;
};
// [Nat8] to text
var txt: Text = textFromBlob(to_candid(u));
// text to blob
let v : ?Types.Test = from_candid(blobFromText(txt));
Debug.print(debug_show(v));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment