From 8015fbfc160be0dcfd98e8662d510099d57b434d Mon Sep 17 00:00:00 2001 From: Mark McCaskey Date: Fri, 5 Apr 2019 13:59:33 -0700 Subject: [PATCH 1/2] implement strftime --- lib/emscripten/src/time.rs | 57 ++++++++++++++++++++++++++++++++++---- 1 file changed, 51 insertions(+), 6 deletions(-) diff --git a/lib/emscripten/src/time.rs b/lib/emscripten/src/time.rs index 1f93f3894ae..1cfa984563c 100644 --- a/lib/emscripten/src/time.rs +++ b/lib/emscripten/src/time.rs @@ -298,17 +298,62 @@ pub fn _time(ctx: &mut Ctx, time_p: u32) -> i32 { /// emscripten: _strftime pub fn _strftime( - _ctx: &mut Ctx, - _s_ptr: c_int, - _maxsize: u32, - _format_ptr: c_int, - _tm_ptr: c_int, + ctx: &mut Ctx, + s_ptr: c_int, + maxsize: u32, + format_ptr: c_int, + tm_ptr: c_int, ) -> i32 { debug!( "emscripten::_strftime {} {} {} {}", _s_ptr, _maxsize, _format_ptr, _tm_ptr ); - 0 + + #[allow(clippy::cast_ptr_alignment)] + let s = emscripten_memory_pointer!(ctx.memory(0), s_ptr) as *mut c_char; + #[allow(clippy::cast_ptr_alignment)] + let format = emscripten_memory_pointer!(ctx.memory(0), format_ptr) as *const c_char; + #[allow(clippy::cast_ptr_alignment)] + let tm = emscripten_memory_pointer!(ctx.memory(0), tm_ptr) as *const guest_tm; + + let format_string = unsafe { std::ffi::CStr::from_ptr(format).to_str().unwrap() }; + + debug!("=> format_string: {:?}", format_string); + + let tm = unsafe { &*tm }; + + let rust_tm = ::time::Tm { + tm_sec: tm.tm_sec, + tm_min: tm.tm_min, + tm_hour: tm.tm_hour, + tm_mday: tm.tm_mday, + tm_mon: tm.tm_mon, + tm_year: tm.tm_year, + tm_wday: tm.tm_wday, + tm_yday: tm.tm_yday, + tm_isdst: tm.tm_isdst, + tm_utcoff: tm.tm_gmtoff, + tm_nsec: 0, + }; + + let result_str = match ::time::strftime(format_string, &rust_tm) { + Ok(res_string) => res_string, + // TODO: maybe match on e in Err(e) and return different values if required + _ => return 0, + }; + + // pad for null? + let bytes = result_str.chars().count(); + if bytes as u32 > maxsize { + return 0; + } else { + // write output string + for (i, c) in result_str.chars().enumerate() { + unsafe { *s.add(i) = c as c_char }; + } + // null terminate? + bytes as i32 + } } /// emscripten: _strftime_l From b0a83408ec3f666fde78bb524ad204c69b586d77 Mon Sep 17 00:00:00 2001 From: Mark McCaskey Date: Fri, 5 Apr 2019 14:33:49 -0700 Subject: [PATCH 2/2] fix debug statement --- lib/emscripten/src/time.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/emscripten/src/time.rs b/lib/emscripten/src/time.rs index 1cfa984563c..312808a82da 100644 --- a/lib/emscripten/src/time.rs +++ b/lib/emscripten/src/time.rs @@ -306,7 +306,7 @@ pub fn _strftime( ) -> i32 { debug!( "emscripten::_strftime {} {} {} {}", - _s_ptr, _maxsize, _format_ptr, _tm_ptr + s_ptr, maxsize, format_ptr, tm_ptr ); #[allow(clippy::cast_ptr_alignment)]