Last active
June 6, 2022 16:52
-
-
Save gabrielnic/fa5dfd8af9928636dae2737a8de014db to your computer and use it in GitHub Desktop.
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
// 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