Skip to content

Commit b597143

Browse files
committed
avoid unnecessary data copying
1 parent 9654151 commit b597143

File tree

1 file changed

+14
-5
lines changed

1 file changed

+14
-5
lines changed

cereal/messaging/messaging.h

+14-5
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
#pragma once
22

3+
#include <algorithm>
34
#include <cstddef>
45
#include <map>
56
#include <string>
@@ -96,17 +97,25 @@ class PubMaster {
9697
class AlignedBuffer {
9798
public:
9899
kj::ArrayPtr<const capnp::word> align(const char *data, const size_t size) {
99-
words_size = size / sizeof(capnp::word) + 1;
100-
if (aligned_buf.size() < words_size) {
101-
aligned_buf = kj::heapArray<capnp::word>(words_size < 512 ? 512 : words_size);
100+
size_t word_count = (size + sizeof(capnp::word) - 1) / sizeof(capnp::word);
101+
102+
// Check if data is already aligned
103+
if (reinterpret_cast<uintptr_t>(data) % alignof(capnp::word) == 0) {
104+
return kj::ArrayPtr<const capnp::word>((const capnp::word *)data, word_count);
105+
}
106+
107+
// Data is not aligned, perform alignment
108+
if (aligned_buf.size() < word_count) {
109+
aligned_buf = kj::heapArray<capnp::word>(std::max(word_count, size_t(512)));
102110
}
103111
memcpy(aligned_buf.begin(), data, size);
104-
return aligned_buf.slice(0, words_size);
112+
return aligned_buf.slice(0, word_count);
105113
}
114+
106115
inline kj::ArrayPtr<const capnp::word> align(Message *m) {
107116
return align(m->getData(), m->getSize());
108117
}
118+
109119
private:
110120
kj::Array<capnp::word> aligned_buf;
111-
size_t words_size;
112121
};

0 commit comments

Comments
 (0)