mirror of
https://github.com/permissionlesstech/bitchat.git
synced 2026-08-29 07:27:16 +00:00
Fix content length estimation in PrivateMessagePacket encoding and add unit tests for encoding/decoding
This commit is contained in:
parent
a83f0fa735
commit
cbdc880d07
@ -119,7 +119,7 @@ struct PrivateMessagePacket {
|
||||
|
||||
var data = Data()
|
||||
let estimatedMessageLength = 1 + 1 + messageIDData.count
|
||||
let estimatedContentLength = contentData.count > 255 ? 1 + 3 + contentData.count : 1 + 2 + contentData.count
|
||||
let estimatedContentLength = contentData.count >= 255 ? 1 + 3 + contentData.count : 1 + 2 + contentData.count
|
||||
data.reserveCapacity(estimatedMessageLength + estimatedContentLength)
|
||||
|
||||
data.append(TLVType.messageID.rawValue)
|
||||
@ -164,7 +164,7 @@ struct PrivateMessagePacket {
|
||||
|
||||
private func appendContentTLV(value: Data, into buffer: inout Data) {
|
||||
buffer.append(TLVType.content.rawValue)
|
||||
if value.count <= 255 {
|
||||
if value.count < 255 {
|
||||
buffer.append(UInt8(value.count))
|
||||
} else {
|
||||
buffer.append(0xFF)
|
||||
|
||||
40
bitchatTests/Protocol/PrivateMessagePacketTests.swift
Normal file
40
bitchatTests/Protocol/PrivateMessagePacketTests.swift
Normal file
@ -0,0 +1,40 @@
|
||||
import XCTest
|
||||
@testable import bitchat
|
||||
|
||||
final class PrivateMessagePacketTests: XCTestCase {
|
||||
func testEncodeDecodeSupportsLargeContent() throws {
|
||||
let longContent = String(repeating: "A", count: 1024)
|
||||
let packet = PrivateMessagePacket(messageID: "msg-123", content: longContent)
|
||||
|
||||
let encoded = try XCTUnwrap(packet.encode())
|
||||
let decoded = try XCTUnwrap(PrivateMessagePacket.decode(from: encoded))
|
||||
|
||||
XCTAssertEqual(decoded.messageID, "msg-123")
|
||||
XCTAssertEqual(decoded.content, longContent)
|
||||
}
|
||||
|
||||
func testEncodeDecodeContentExactly255Bytes() throws {
|
||||
let content = String(repeating: "B", count: 255)
|
||||
let packet = PrivateMessagePacket(messageID: "msg-255", content: content)
|
||||
|
||||
let encoded = try XCTUnwrap(packet.encode())
|
||||
let decoded = try XCTUnwrap(PrivateMessagePacket.decode(from: encoded))
|
||||
|
||||
XCTAssertEqual(decoded.content.count, 255)
|
||||
XCTAssertEqual(decoded.content, content)
|
||||
}
|
||||
|
||||
func testEncodeRejectsOversizedContent() {
|
||||
let oversizedContent = String(repeating: "C", count: 70_000)
|
||||
let packet = PrivateMessagePacket(messageID: "msg-oversize", content: oversizedContent)
|
||||
|
||||
XCTAssertNil(packet.encode())
|
||||
}
|
||||
|
||||
func testEncodeRejectsOversizedMessageID() {
|
||||
let longID = String(repeating: "x", count: 256)
|
||||
let packet = PrivateMessagePacket(messageID: longID, content: "ok")
|
||||
|
||||
XCTAssertNil(packet.encode())
|
||||
}
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user