Initial implementation (#4)
This commit is contained in:
parent
a78b14ae33
commit
ec2651207c
6 changed files with 281 additions and 25 deletions
14
src/lib.rs
14
src/lib.rs
|
@ -2,14 +2,16 @@ mod utils;
|
|||
|
||||
use wasm_bindgen::prelude::*;
|
||||
|
||||
#[wasm_bindgen]
|
||||
extern "C" {
|
||||
fn alert(s: &str);
|
||||
}
|
||||
#[cfg(feature = "wee_alloc")]
|
||||
#[global_allocator]
|
||||
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;
|
||||
|
||||
#[wasm_bindgen]
|
||||
pub fn greet() {
|
||||
pub fn merge(files: js_sys::Array) -> wasm_bindgen::JsValue {
|
||||
utils::set_panic_hook();
|
||||
let files: Vec<String> = utils::translate_js_to_rust(files);
|
||||
let merged: gpx::Gpx = utils::join_gpx_files(files);
|
||||
let out_vec: Vec<u8> = utils::write_gpx_to_buffer(merged);
|
||||
|
||||
alert("Hello, gpx-web-utils!");
|
||||
JsValue::from_str(&String::from_utf8(out_vec).unwrap())
|
||||
}
|
||||
|
|
48
src/utils.rs
48
src/utils.rs
|
@ -1,10 +1,46 @@
|
|||
pub fn set_panic_hook() {
|
||||
// When the `console_error_panic_hook` feature is enabled, we can call the
|
||||
// `set_panic_hook` function at least once during initialization, and then
|
||||
// we will get better error messages if our code ever panics.
|
||||
//
|
||||
// For more details see
|
||||
// https://github.com/rustwasm/console_error_panic_hook#readme
|
||||
#[cfg(feature = "console_error_panic_hook")]
|
||||
console_error_panic_hook::set_once();
|
||||
}
|
||||
|
||||
pub fn translate_js_to_rust(files: js_sys::Array) -> Vec<String> {
|
||||
// https://github.com/rustwasm/wasm-bindgen/issues/111
|
||||
files.iter().map(|f| f.as_string().unwrap()).collect()
|
||||
}
|
||||
|
||||
pub fn join_gpx_files(files: Vec<String>) -> gpx::Gpx {
|
||||
let mut merged: gpx::Gpx = Default::default();
|
||||
|
||||
for file in files.iter() {
|
||||
let buffer = std::io::BufReader::new(file.as_bytes());
|
||||
let mut parsed_gpx: gpx::Gpx = gpx::read(buffer).expect("invalid gpx");
|
||||
|
||||
merged.tracks.append(&mut parsed_gpx.tracks);
|
||||
merged.waypoints.append(&mut parsed_gpx.waypoints);
|
||||
}
|
||||
|
||||
let link = gpx::Link {
|
||||
href: String::from("https://gpx.thermokar.st"),
|
||||
..Default::default()
|
||||
};
|
||||
let author = gpx::Person {
|
||||
link: Some(link),
|
||||
..Default::default()
|
||||
};
|
||||
let metadata = gpx::Metadata {
|
||||
name: Some(String::from("merged")),
|
||||
author: Some(author),
|
||||
..Default::default()
|
||||
};
|
||||
merged.metadata = Some(metadata);
|
||||
merged.version = gpx::GpxVersion::Gpx11;
|
||||
|
||||
merged
|
||||
}
|
||||
|
||||
pub fn write_gpx_to_buffer(gpx: gpx::Gpx) -> Vec<u8> {
|
||||
let mut buffer = Vec::new();
|
||||
gpx::write(&gpx, &mut buffer).unwrap();
|
||||
|
||||
buffer
|
||||
}
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue