hysteria2 0.1.2

A feature-rich, asynchronous Rust client library for the Hysteria 2 proxy protocol. / 功能丰富、异步的 Hysteria 2 代理协议 Rust 客户端库。
Documentation
use bytes::{BufMut, Bytes, BytesMut};
use rand::RngCore;

use super::put_varint::put_varint;

/// Hysteria 2 TCP 请求消息
pub struct TCPRequest {
  pub address: String,
  pub padding_len: usize,
}

impl TCPRequest {
  /// Encode the request into a buffer.
  /// 将请求编码到缓冲区中。
  pub fn encode(self) -> Bytes {
    // Pre-calculate buffer size to avoid reallocation.
    // 预计算缓冲区大小以避免重新分配。
    let estimated_size = 8 + self.address.len() + self.padding_len + 16; // Leave extra space for varints. / 为varints留出额外空间。
    let mut buf = BytesMut::with_capacity(estimated_size);

    // TCPRequest ID.
    // TCPRequest ID。
    put_varint(0x401, &mut buf);
    // Address.
    // 地址。
    put_varint(self.address.len() as u64, &mut buf);
    buf.put(self.address.as_bytes());
    // Padding.
    // 填充。
    put_varint(self.padding_len as u64, &mut buf);
    if self.padding_len > 0 {
      // Generate random padding.
      // 生成随机填充。
      let mut padding = vec![0u8; self.padding_len];
      let mut rng = rand::rng();
      rng.fill_bytes(&mut padding);
      buf.put(padding.as_slice());
    }
    buf.freeze()
  }
}