Skip to content

Instantly share code, notes, and snippets.

@ffflorian
Last active September 1, 2017 11:55
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 ffflorian/89e959d059c8675861c87e08ed2511f9 to your computer and use it in GitHub Desktop.
Save ffflorian/89e959d059c8675861c87e08ed2511f9 to your computer and use it in GitHub Desktop.
CBOR Text Coding Example
'use strict';
const CBOR = require('wire-webapp-cbor');
const text_encode = plaintext => {
const encoder = new CBOR.Encoder();
encoder.text(plaintext);
return new Uint8Array(encoder.buffer);
};
const text_decode = encoded => {
const decoder = new CBOR.Decoder(encoded.buffer);
const decoded_text = decoder.text();
return decoded_text;
};
console.log('text_encode', text_encode('Hello')); // [101, 72, 101, 108, 108, 111
console.log('text_decode', text_decode(new Uint8Array([101, 72, 101, 108, 108, 111]))); // Hello
extern crate cbor;
use std::io::Cursor;
use cbor::{Config, Decoder, Encoder};
fn main() {
println!("text_encode: {:?}", text_encode("Hello")); // [101, 72, 101, 108, 108, 111
println!("text_decode: {}", text_decode(&[101, 72, 101, 108, 108, 111])); // Hello
}
fn text_encode(plaintext: &str) -> Vec<u8> {
let mut encoder = Encoder::new(Cursor::new(Vec::new()));
let _ = encoder.text(&plaintext);
encoder.into_writer().into_inner()
}
fn text_decode(encoded: &[u8]) -> String {
let mut decoder = Decoder::new(Config::default(), Cursor::new(encoded));
let decoded_text = decoder.text();
decoded_text.unwrap()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment