     // Helper function to unpack a little-endian, 32-bit unsigned integer from a data packet.
     private func readUint32(from data: Data, atOffset offset: Int) -> UInt32 {
         assert(offset >= 0 && data.count >= offset + 4)
-        let value: UInt32 = data.withUnsafeBytes { $0[offset / 4] }
+        let value = data.withUnsafeBytes { $0.load(fromByteOffset: offset, as: UInt32.self) }
         return UInt32(littleEndian: value)
+    }
+    
+    // Compute the number of padding bytes for the given message size.
+    private func paddingLength(for messageSize: Int) -> Int {
+        let remainder = messageSize % 4
+        return remainder == 0 ? 0 : 4 - remainder
     }
 }
 

        
        var length = UInt32(data.count + messageHeaderSize).littleEndian
        var type = type.rawValue.littleEndian
        
        var message = Data(bytes: &length, count: 4)
        message.append(Data(bytes: &type, count: 4))
        message.append(data)
        
        if sendBuffer.count > 0 {
            // No more data can be send at this time. Queue the message.

        let length = sendBuffer.count
        assert(length > 0)
        
        let rv = sendBuffer.withUnsafeBytes{ body -> CInt in
            return libsocket.socket_send(socket, body.bindMemory(to: UInt8.self).baseAddress, UInt32(length))
        }
        
        if rv < 0 {
