#pragma once
#include "Attachment.h"
#include <wtf/Vector.h>
namespace IPC {
class MessageInfo {
public:
MessageInfo()
{
memset(this, 0, sizeof(*this));
}
MessageInfo(size_t bodySize, size_t initialAttachmentCount)
{
memset(this, 0, sizeof(*this));
m_bodySize = bodySize;
m_attachmentCount = initialAttachmentCount;
}
void setBodyOutOfLine()
{
ASSERT(!isBodyOutOfLine());
m_isBodyOutOfLine = true;
m_attachmentCount++;
}
bool isBodyOutOfLine() const { return m_isBodyOutOfLine; }
size_t bodySize() const { return m_bodySize; }
size_t attachmentCount() const { return m_attachmentCount; }
private:
size_t m_bodySize { 0 };
size_t m_attachmentCount { 0 };
bool m_isBodyOutOfLine { false };
};
class UnixMessage {
WTF_MAKE_FAST_ALLOCATED;
public:
UnixMessage(Encoder& encoder)
: m_attachments(encoder.releaseAttachments())
, m_messageInfo(encoder.bufferSize(), m_attachments.size())
, m_body(encoder.buffer())
{
}
UnixMessage(UnixMessage&& other)
{
m_attachments = WTFMove(other.m_attachments);
m_messageInfo = WTFMove(other.m_messageInfo);
if (other.m_bodyOwned) {
std::swap(m_body, other.m_body);
std::swap(m_bodyOwned, other.m_bodyOwned);
} else if (!m_messageInfo.isBodyOutOfLine()) {
m_body = static_cast<uint8_t*>(fastMalloc(m_messageInfo.bodySize()));
memcpy(m_body, other.m_body, m_messageInfo.bodySize());
m_bodyOwned = true;
other.m_body = nullptr;
other.m_bodyOwned = false;
}
}
~UnixMessage()
{
if (m_bodyOwned)
fastFree(m_body);
}
const Vector<Attachment>& attachments() const { return m_attachments; }
MessageInfo& messageInfo() { return m_messageInfo; }
uint8_t* body() const { return m_body; }
size_t bodySize() const { return m_messageInfo.bodySize(); }
void appendAttachment(Attachment&& attachment)
{
m_attachments.append(WTFMove(attachment));
}
private:
Vector<Attachment> m_attachments;
MessageInfo m_messageInfo;
uint8_t* m_body { nullptr };
bool m_bodyOwned { false };
};
}