import { ClientMsg } from '../network/pbExport' interface ProtoEncodable { create(data: T): unknown encode(message: unknown): { finish(): Uint8Array } decode(buffer: Uint8Array): T } // 将proto对象序列化成buffer export class PbHelper { static Encode(protoClass: ProtoEncodable, data: T): Uint8Array { const message = protoClass.create(data) return protoClass.encode(message).finish() } static DecodeClient(buffer: Uint8Array): [number, Uint8Array] { const cMsg = ClientMsg.decode(buffer) return [cMsg.msgId, cMsg.data] } static Decode(protoClass: ProtoEncodable, buffer: Uint8Array): T { return protoClass.decode(buffer) } static Uint8ToHex(buffer: Uint8Array): string { return Array.from(buffer) .map((byte) => byte.toString(16).padStart(2, '0')) .join(' ') } } // // 假设有一个生成的 Protobuf 类 // class UserMessage { // static create(data: User) { /*...*/ } // static encode(msg: unknown) { /*...*/ } // } // const data = { name: "Alice" }; // const buffer = PbHelper.encode(UserMessage, data); // 显式传入消息类