1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
|
extern crate serde;
extern crate serde_json;
extern crate libc;
use libc::{c_char, size_t};
use serde::{Serialize, Deserialize};
use std::{collections::HashMap, ffi::CString, ptr, slice};
//==============================================================================
// Twitter Benchmark Structures
// These match the C++ TwitterData structures exactly
//==============================================================================
#[derive(Serialize, Deserialize)]
pub struct User {
id: u64,
name: String,
screen_name: String,
location: String,
description: String,
verified: bool,
followers_count: u64,
friends_count: u64,
statuses_count: u64,
}
#[derive(Serialize, Deserialize)]
pub struct Status {
created_at: String,
id: u64,
text: String,
user: User,
retweet_count: u64,
favorite_count: u64,
}
#[derive(Serialize, Deserialize)]
pub struct TwitterData {
statuses: Vec<Status>,
}
static mut TWITTER_DATA: *mut TwitterData = std::ptr::null_mut();
#[no_mangle]
pub unsafe extern "C" fn twitter_from_str(raw_input: *const c_char, raw_input_length: size_t) -> *mut TwitterData {
let input = std::str::from_utf8_unchecked(slice::from_raw_parts(raw_input as *const u8, raw_input_length));
match serde_json::from_str(&input) {
Ok(result) => Box::into_raw(Box::new(result)),
Err(_) => std::ptr::null_mut(),
}
}
#[no_mangle]
pub unsafe extern "C" fn set_twitter_data(raw: *mut TwitterData) {
TWITTER_DATA = raw;
}
#[no_mangle]
pub unsafe extern "C" fn serialize_twitter_to_string() -> usize {
if TWITTER_DATA.is_null() {
return 0;
}
let data = &*TWITTER_DATA;
serde_json::to_string(data).unwrap().len()
}
#[no_mangle]
pub unsafe extern "C" fn free_twitter(raw: *mut TwitterData) {
if raw.is_null() {
return;
}
drop(Box::from_raw(raw))
}
#[no_mangle]
pub unsafe extern fn free_string(ptr: *const c_char) {
let _ = std::ffi::CString::from_raw(ptr as *mut _);
}
//==============================================================================
// CITM Catalog Benchmark Structures
// These match the C++ CitmCatalog structures EXACTLY for fair comparison
//==============================================================================
/// Matches C++ CITMPrice struct exactly
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CITMPrice {
pub amount: u64,
#[serde(rename = "audienceSubCategoryId")]
pub audience_sub_category_id: u64,
#[serde(rename = "seatCategoryId")]
pub seat_category_id: u64,
}
/// Matches C++ CITMArea struct exactly
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CITMArea {
#[serde(rename = "areaId")]
pub area_id: u64,
#[serde(rename = "blockIds")]
pub block_ids: Vec<u64>,
}
/// Matches C++ CITMSeatCategory struct exactly
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CITMSeatCategory {
pub areas: Vec<CITMArea>,
#[serde(rename = "seatCategoryId")]
pub seat_category_id: u64,
}
/// Matches C++ CITMPerformance struct exactly
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CITMPerformance {
pub id: u64,
#[serde(rename = "eventId")]
pub event_id: u64,
#[serde(default)]
pub logo: Option<String>,
#[serde(default)]
pub name: Option<String>,
pub prices: Vec<CITMPrice>,
#[serde(rename = "seatCategories")]
pub seat_categories: Vec<CITMSeatCategory>,
#[serde(default)]
#[serde(rename = "seatMapImage")]
pub seat_map_image: Option<String>,
pub start: u64,
#[serde(rename = "venueCode")]
pub venue_code: String,
}
/// Matches C++ CITMEvent struct exactly
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CITMEvent {
pub id: u64,
#[serde(default)]
pub name: Option<String>,
#[serde(default)]
pub description: Option<String>,
#[serde(default)]
pub logo: Option<String>,
#[serde(default)]
#[serde(rename = "subTopicIds")]
pub sub_topic_ids: Vec<u64>,
#[serde(default)]
#[serde(rename = "subjectCode")]
pub subject_code: Option<String>,
#[serde(default)]
pub subtitle: Option<String>,
#[serde(default)]
#[serde(rename = "topicIds")]
pub topic_ids: Vec<u64>,
}
/// Matches C++ CitmCatalog struct exactly - ONLY events and performances
/// This is the key fix: we serialize only what C++ serializes
#[derive(Serialize, Deserialize, Debug)]
pub struct CitmCatalog {
pub events: HashMap<String, CITMEvent>,
pub performances: Vec<CITMPerformance>,
}
static mut CITM_DATA: *mut CitmCatalog = std::ptr::null_mut();
/// Creates a CitmCatalog from a JSON string (UTF-8 encoded).
/// Only extracts events and performances to match C++ behavior.
#[no_mangle]
pub unsafe extern "C" fn citm_from_str(
raw_input: *const c_char,
raw_input_length: usize
) -> *mut CitmCatalog {
if raw_input.is_null() {
eprintln!("Error: Input pointer is null");
return ptr::null_mut();
}
let bytes = slice::from_raw_parts(raw_input as *const u8, raw_input_length);
let input_str = match std::str::from_utf8(bytes) {
Ok(s) => s,
Err(e) => {
eprintln!("Error: Invalid UTF-8 string: {}", e);
return ptr::null_mut();
}
};
// Parse the full JSON to extract only events and performances
match serde_json::from_str::<serde_json::Value>(input_str) {
Ok(full_json) => {
// Extract only the fields we need (matching C++ behavior)
let events: HashMap<String, CITMEvent> = full_json.get("events")
.and_then(|v| serde_json::from_value(v.clone()).ok())
.unwrap_or_default();
let performances: Vec<CITMPerformance> = full_json.get("performances")
.and_then(|v| serde_json::from_value(v.clone()).ok())
.unwrap_or_default();
let catalog = CitmCatalog { events, performances };
Box::into_raw(Box::new(catalog))
},
Err(e) => {
eprintln!("Error deserializing JSON: {}", e);
ptr::null_mut()
}
}
}
/// Serializes a CitmCatalog into a JSON string (UTF-8).
#[no_mangle]
pub unsafe extern "C" fn set_citm_data(raw: *mut CitmCatalog) {
CITM_DATA = raw;
}
#[no_mangle]
pub unsafe extern "C" fn serialize_citm_to_string() -> usize {
if CITM_DATA.is_null() {
return 0;
}
let data = &*CITM_DATA;
return serde_json::to_string(data).unwrap().len();
}
/// Frees the CitmCatalog pointer.
#[no_mangle]
pub unsafe extern "C" fn free_citm(raw_catalog: *mut CitmCatalog) {
if !raw_catalog.is_null() {
drop(Box::from_raw(raw_catalog));
}
}
#[no_mangle]
pub extern "C" fn free_str(ptr: *mut c_char) {
if !ptr.is_null() {
unsafe {
let _ = CString::from_raw(ptr);
}
}
}
//==============================================================================
// FFI Overhead Measurement Functions
// These allow measuring the actual FFI overhead vs pure Rust serialization
//==============================================================================
/// Result structure for FFI overhead measurement
#[repr(C)]
pub struct FfiOverheadResult {
/// Time in nanoseconds for pure serde_json::to_string() (no FFI overhead)
pub pure_serde_ns: u64,
/// Time in nanoseconds for serde + CString conversion
pub serde_plus_cstring_ns: u64,
/// Number of iterations performed
pub iterations: u64,
/// Output size in bytes (for verification)
pub output_size: u64,
}
/// Prevents compiler from optimizing away the value
/// Works on stable Rust (unlike std::hint::black_box which is unstable)
#[inline(never)]
fn black_box<T>(dummy: T) -> T {
unsafe {
let ret = std::ptr::read_volatile(&dummy);
std::mem::forget(dummy);
ret
}
}
/// Measures FFI overhead for Twitter serialization.
/// Performs `iterations` serializations entirely in Rust and returns timing data.
/// This allows comparing against per-call FFI overhead.
#[no_mangle]
pub unsafe extern "C" fn measure_twitter_ffi_overhead(
raw: *mut TwitterData,
iterations: u64
) -> FfiOverheadResult {
use std::time::Instant;
let twitter_data = &*raw;
let output_size: u64;
// Warm-up run
let warmup = serde_json::to_string(&twitter_data).unwrap();
output_size = warmup.len() as u64;
// Measure pure serde_json::to_string() - no CString conversion
let start_pure = Instant::now();
for _ in 0..iterations {
let serialized = serde_json::to_string(&twitter_data).unwrap();
// Prevent optimization from eliminating the work
black_box(&serialized);
}
let pure_serde_ns = start_pure.elapsed().as_nanos() as u64;
// Measure serde + CString conversion (but not FFI return)
let start_cstring = Instant::now();
for _ in 0..iterations {
let serialized = serde_json::to_string(&twitter_data).unwrap();
let cstring = CString::new(serialized).unwrap();
// Prevent optimization from eliminating the work
black_box(&cstring);
}
let serde_plus_cstring_ns = start_cstring.elapsed().as_nanos() as u64;
FfiOverheadResult {
pure_serde_ns,
serde_plus_cstring_ns,
iterations,
output_size,
}
}
/// Measures FFI overhead for CITM serialization.
#[no_mangle]
pub unsafe extern "C" fn measure_citm_ffi_overhead(
raw: *mut CitmCatalog,
iterations: u64
) -> FfiOverheadResult {
use std::time::Instant;
let catalog = &*raw;
let output_size: u64;
// Warm-up run
let warmup = serde_json::to_string(&catalog).unwrap();
output_size = warmup.len() as u64;
// Measure pure serde_json::to_string() - no CString conversion
let start_pure = Instant::now();
for _ in 0..iterations {
let serialized = serde_json::to_string(&catalog).unwrap();
black_box(&serialized);
}
let pure_serde_ns = start_pure.elapsed().as_nanos() as u64;
// Measure serde + CString conversion
let start_cstring = Instant::now();
for _ in 0..iterations {
let serialized = serde_json::to_string(&catalog).unwrap();
let cstring = CString::new(serialized).unwrap();
black_box(&cstring);
}
let serde_plus_cstring_ns = start_cstring.elapsed().as_nanos() as u64;
FfiOverheadResult {
pure_serde_ns,
serde_plus_cstring_ns,
iterations,
output_size,
}
}
|