rust_tdlib/
tdjson.rs

1//! Interface for methods defined in [td/td_json_client.h](https://github.com/tdlib/td/blob/master/td/telegram/td_json_client.h).
2use std::ffi::CStr;
3use std::ffi::CString;
4use std::os::raw::{c_char, c_double, c_int, c_long};
5use std::ptr;
6
7pub type ClientId = i32;
8
9#[link(name = "tdjson")]
10extern "C" {
11    fn td_create_client_id() -> c_int;
12    fn td_send(client_id: c_int, request: *const c_char);
13    fn td_receive(timeout: c_double) -> *const c_char;
14    fn td_execute(request: *const c_char) -> *const c_char;
15
16    // Deprecated. Use setLogVerbosityLevel request instead.
17    fn td_set_log_verbosity_level(level: c_int);
18    // Deprecated. Use setLogStream request instead.
19    fn td_set_log_file_path(path: *const c_char) -> c_int;
20    // Deprecated. Use setLogStream request instead.
21    fn td_set_log_max_file_size(size: c_long);
22}
23
24pub fn new_client() -> ClientId {
25    unsafe { td_create_client_id() }
26}
27
28pub fn send(client_id: ClientId, request: &str) {
29    let cstring = CString::new(request).unwrap();
30    unsafe { td_send(client_id, cstring.as_ptr()) }
31}
32
33pub fn execute(request: &str) -> Option<String> {
34    let cstring = CString::new(request).unwrap();
35    let result = unsafe {
36        td_execute(cstring.as_ptr())
37            .as_ref()
38            .map(|response| CStr::from_ptr(response).to_string_lossy().into_owned())
39    };
40    result
41}
42
43pub fn receive(timeout: f64) -> Option<String> {
44    unsafe {
45        td_receive(timeout)
46            .as_ref()
47            .map(|response| CStr::from_ptr(response).to_string_lossy().into_owned())
48    }
49}
50
51// Deprecated. Use setLogVerbosityLevel request instead.
52pub fn set_log_verbosity_level(level: i32) {
53    unsafe { td_set_log_verbosity_level(level) };
54}
55
56// Deprecated. Use setLogStream request instead.
57pub fn set_log_file_path(path: Option<&str>) -> bool {
58    let result = match path {
59        None => unsafe { td_set_log_file_path(ptr::null()) },
60        Some(path_) => {
61            let cpath = CString::new(path_).unwrap();
62            unsafe { td_set_log_file_path(cpath.as_ptr()) }
63        }
64    };
65    match result {
66        1 => true,
67        0 => false,
68        _ => panic!("unexpected response from libtdjson: {:?}", result),
69    }
70}
71
72// Deprecated. Use setLogStream request instead.
73pub fn set_log_max_file_size(size: i64) {
74    unsafe { td_set_log_max_file_size(size as c_long) };
75}