summaryrefslogtreecommitdiff
path: root/src/include
diff options
context:
space:
mode:
Diffstat (limited to 'src/include')
-rw-r--r--src/include/memory_chunk.h34
-rw-r--r--src/include/unaligned_memory.h43
2 files changed, 77 insertions, 0 deletions
diff --git a/src/include/memory_chunk.h b/src/include/memory_chunk.h
index c106dba..baa5679 100644
--- a/src/include/memory_chunk.h
+++ b/src/include/memory_chunk.h
@@ -290,6 +290,25 @@ public:
}
/**
+ * MemoryChunk::set_content:
+ * @offset: the offset in this MemoryChunk.
+ * @data: the data to be copied.
+ * @returns: whether the data is copied successfully.
+ *
+ * Data are written directly to the memory area in this MemoryChunk.
+ *
+ */
+ template <typename T>
+ bool set_content(size_t offset, T data){
+ const size_t len = sizeof(data);
+ size_t cursize = std_lite::max(size(), offset + len);
+ ensure_has_space(offset + len);
+ memmove(m_data_begin + offset, &data, len);
+ m_data_end = m_data_begin + cursize;
+ return true;
+ }
+
+ /**
* MemoryChunk::append_content:
* @data: the begin of the data to be copied.
* @len: the length of the data to be copied.
@@ -357,6 +376,21 @@ public:
}
/**
+ * MemoryChunk::get_content:
+ * @offset: the offset in this MemoryChunk.
+ * @returns: the content
+ *
+ * Get the content in this MemoryChunk.
+ *
+ */
+ template <typename T>
+ T get_content(size_t offset) const {
+ T value;
+ memcpy(&value, m_data_begin + offset, sizeof(value));
+ return value;
+ }
+
+ /**
* MemoryChunk::compact_memory:
*
* Compact memory, reduce the size.
diff --git a/src/include/unaligned_memory.h b/src/include/unaligned_memory.h
new file mode 100644
index 0000000..27b2f19
--- /dev/null
+++ b/src/include/unaligned_memory.h
@@ -0,0 +1,43 @@
+#ifndef UNALIGNED_MEMORY_H
+#define UNALIGNED_MEMORY_H
+
+#include <cstring>
+
+/**
+ * UnalignedMemory: Safe unaligned memory access.
+ *
+ * Some instruction sets, or some instructions in some instruction sets
+ * require that memory access is aligned to a specific boundary. These
+ * instructions may trap on unaligned access.
+ *
+ * This class provides methods to load and store values at unaligned
+ * addresses. It ensures that the compiler doesn't generate instructions
+ * that could trap on the unaligned memory access.
+ */
+
+namespace pinyin{
+ template <typename T>
+ class UnalignedMemory{
+ public:
+ /**
+ * Read a value from a possibly unaligned memory address.
+ *
+ */
+ static T load(const void * src) {
+ T value;
+ memcpy(&value, src, sizeof(T));
+ return value;
+ }
+
+ /**
+ * Store a value into a possibly unaligned memory address.
+ *
+ */
+ static void store(T value, void * dest) {
+ memcpy(dest, &value, sizeof(T));
+ }
+ };
+};
+
+
+#endif