1 // Copyright 2019 TiKV Project Authors. Licensed under Apache-2.0.
2 
3 use crate::grpc_sys::{self, grpc_resource_quota};
4 use std::ffi::CString;
5 use std::ptr;
6 
7 /// ResourceQuota represents a bound on memory and thread usage by the gRPC.
8 /// NOTE: The management of threads created in grpc-core don't use ResourceQuota.
9 /// TODO: Manage the poller threads created in grpc-rs with this ResourceQuota later.
10 pub struct ResourceQuota {
11     raw: *mut grpc_resource_quota,
12 }
13 
14 impl ResourceQuota {
15     /// Create a control block for resource quota. If a name is
16     /// not declared for this control block, a name is automatically
17     /// generated in grpc core.
new(name: Option<&str>) -> ResourceQuota18     pub fn new(name: Option<&str>) -> ResourceQuota {
19         match name {
20             Some(name_str) => {
21                 let name_cstr = CString::new(name_str).unwrap();
22                 ResourceQuota {
23                     raw: unsafe { grpc_sys::grpc_resource_quota_create(name_cstr.as_ptr() as _) },
24                 }
25             }
26             None => ResourceQuota {
27                 raw: unsafe { grpc_sys::grpc_resource_quota_create(ptr::null()) },
28             },
29         }
30     }
31 
32     /// Resize this ResourceQuota to a new memory size.
resize_memory(self, new_size: usize) -> ResourceQuota33     pub fn resize_memory(self, new_size: usize) -> ResourceQuota {
34         unsafe { grpc_sys::grpc_resource_quota_resize(self.raw, new_size) };
35         self
36     }
37 
get_ptr(&self) -> *mut grpc_resource_quota38     pub(crate) fn get_ptr(&self) -> *mut grpc_resource_quota {
39         self.raw
40     }
41 }
42 
43 impl Clone for ResourceQuota {
clone(&self) -> Self44     fn clone(&self) -> Self {
45         unsafe {
46             grpc_sys::grpc_resource_quota_ref(self.raw);
47         }
48         Self { raw: self.raw }
49     }
50 }
51 
52 impl Drop for ResourceQuota {
drop(&mut self)53     fn drop(&mut self) {
54         unsafe {
55             grpc_sys::grpc_resource_quota_unref(self.raw);
56         }
57     }
58 }
59