I have a structure that contains a TcpStream for communication and a BytesMut for receiving data. When I need to use it to receive data, I intend to do the following.
#[tokio::test]
async fn test_refmut1() {
struct Ctx {
tcps: TcpStream,
data: BytesMut,
}
async fn recv(ctx: Arc<Mutex<Ctx>>) {
let mut ctx = ctx.lock().await;
ctx.tcps.read_buf(&mut ctx.data).await.unwrap();
}
}
Obviously, this can not compile, because tcps is borrowed once, and BytesMut, which is the read_buf() parameter, is borrrowed again.
As usual, I wrapped the other part using RefCell to get internal mutability.
#[tokio::test]
async fn test_refmut2() {
struct Ctx {
tcps: TcpStream,
data: RefCell<BytesMut>,
}
async fn recv(ctx: Arc<Mutex<Ctx>>) {
let mut ctx = ctx.lock().await;
let tcps = &ctx.tcps;
let mut data = ctx.data.borrow_mut();
ctx.tcps.read_buf(&data).await.unwrap();
}
}
However, this still doesn't compile because read_buf() requires an argument of type &mut BytesMut, which I now borrowed via RefCell as an argument of type RefMut<BytesMut>.
But I know that the two are not directly convertible, what should I do?