extern "C" {
    fn __k3_ipfs_upload(buf_ptr: u32, res_ptr: u32);
    fn __k3_ipfs_read(cid_ptr: u32) -> u32;
}

pub fn upload(mut contents: Vec<u8>) -> String {
    let mut buf = contents.len().to_le_bytes().to_vec();
    buf.append(&mut contents);
    let res = vec![0u8; 46];
    unsafe {
        __k3_ipfs_upload(buf.as_ptr() as u32, res.as_ptr() as u32);
    }
    String::from_utf8(res).unwrap()
}

pub fn read(cid: &str) -> Vec<u8> {
    unsafe {
        let res_ptr = __k3_ipfs_read(cid.as_ptr() as u32) as *mut u8;
        let len = u32::from_le_bytes(std::slice::from_raw_parts(res_ptr, 4).try_into().unwrap());
        let mut res = vec![0u8; len as usize];
        res.copy_from_slice(std::slice::from_raw_parts(res_ptr.add(4), len as usize));
        res
    }
}
