Merge pull request #47 from kaspar030/make_ntohxp_alignment_safe

implement alignment-safe ntoh16p() && ntoh32p()
diff --git a/CMakeLists.txt b/CMakeLists.txt
index 195c780..e076dc8 100644
--- a/CMakeLists.txt
+++ b/CMakeLists.txt
@@ -24,6 +24,7 @@
 option ( coveralls_send "Send data to coveralls site" OFF )
 option ( build_docs "Create docs using Doxygen" ${DOXYGEN_FOUND} )
 option ( no_floats "Build without floating point support" OFF )
+option ( align_reads    "Use memcpy in ntoh*p()" OFF )
 
 set ( dist_dir    ${CMAKE_BINARY_DIR}/dist )
 set ( prefix      ${CMAKE_INSTALL_PREFIX} )
diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt
index ceb0608..babe95c 100644
--- a/src/CMakeLists.txt
+++ b/src/CMakeLists.txt
@@ -10,6 +10,9 @@
       cn-get.c
 )
 
+if (align_reads)
+  add_definitions(-DCBOR_ALIGN_READS)
+endif()
 if (use_context)
   add_definitions(-DUSE_CBOR_CONTEXT)
 endif()
diff --git a/src/cn-cbor.c b/src/cn-cbor.c
index a7677ae..9093537 100644
--- a/src/cn-cbor.c
+++ b/src/cn-cbor.c
@@ -49,10 +49,25 @@
 }
 #endif /* CBOR_NO_FLOAT */
 
-/* Fix these if you can't do non-aligned reads */
 #define ntoh8p(p) (*(unsigned char*)(p))
+
+#ifndef CBOR_ALIGN_READS
 #define ntoh16p(p) (ntohs(*(unsigned short*)(p)))
 #define ntoh32p(p) (ntohl(*(unsigned long*)(p)))
+#else
+static uint16_t ntoh16p(unsigned char *p) {
+    uint16_t tmp;
+    memcpy(&tmp, p, sizeof(tmp));
+    return ntohs(tmp);
+}
+
+static uint32_t ntoh32p(unsigned char *p) {
+    uint32_t tmp;
+    memcpy(&tmp, p, sizeof(tmp));
+    return ntohl(tmp);
+}
+#endif /* CBOR_ALIGN_READS */
+
 static uint64_t ntoh64p(unsigned char *p) {
   uint64_t ret = ntoh32p(p);
   ret <<= 32;