Skip to main content

luaur_bytecode_cli/functions/
serialize_summaries.rs

1use alloc::string::String;
2use alloc::vec::Vec;
3use core::ffi::{c_char, c_void};
4use std::ptr;
5
6use luaur_code_gen::records::function_bytecode_summary::FunctionBytecodeSummary;
7
8use crate::functions::serialize_script_summary::serialize_script_summary;
9
10pub fn serialize_summaries(
11    files: &Vec<String>,
12    script_summaries: &Vec<Vec<FunctionBytecodeSummary>>,
13    summary_file: &String,
14) -> bool {
15    let fp = unsafe {
16        fopen(
17            summary_file.as_ptr() as *const c_char,
18            b"w\0".as_ptr() as *const c_char,
19        )
20    };
21    let file_count = files.len();
22
23    if fp.is_null() {
24        // fprintf(stderr, "Unable to open '%s'.\n", summaryFile.c_str());
25        eprintln!("Unable to open '{}'.", summary_file.trim_end_matches('\0'));
26        return false;
27    }
28
29    unsafe {
30        fprintf(fp, b"{\n\0".as_ptr() as *const c_char);
31    }
32
33    for i in 0..file_count {
34        serialize_script_summary(&files[i], &script_summaries[i], fp);
35        unsafe {
36            if i < file_count - 1 {
37                fprintf(fp, b",\n\0".as_ptr() as *const c_char);
38            } else {
39                fprintf(fp, b"\n\0".as_ptr() as *const c_char);
40            }
41        }
42    }
43
44    unsafe {
45        fprintf(fp, b"}\0".as_ptr() as *const c_char);
46        fclose(fp);
47    }
48
49    true
50}
51
52extern "C" {
53    fn fopen(filename: *const c_char, mode: *const c_char) -> *mut c_void;
54    fn fclose(stream: *mut c_void) -> i32;
55    fn fprintf(stream: *mut c_void, format: *const c_char, ...) -> i32;
56}