Minh Nguyen / ArduinoJson
Embed: (wiki syntax)

« Back to documentation index

Show/hide line numbers pgmspace.hpp Source File

pgmspace.hpp

00001 // ArduinoJson - arduinojson.org
00002 // Copyright Benoit Blanchon 2014-2021
00003 // MIT License
00004 
00005 #pragma once
00006 
00007 #include <ArduinoJson/Configuration.hpp>
00008 #include <ArduinoJson/Namespace.hpp>
00009 #include <ArduinoJson/Polyfills/assert.hpp>
00010 
00011 namespace ARDUINOJSON_NAMESPACE {
00012 // Wraps a const char* so that the our functions are picked only if the
00013 // originals are missing
00014 struct pgm_p {
00015   pgm_p(const char* p) : address(p) {}
00016   const char* address;
00017 };
00018 }  // namespace ARDUINOJSON_NAMESPACE
00019 
00020 #ifndef strlen_P
00021 inline size_t strlen_P(ARDUINOJSON_NAMESPACE::pgm_p s) {
00022   const char* p = s.address;
00023   ARDUINOJSON_ASSERT(p != NULL);
00024   while (pgm_read_byte(p)) p++;
00025   return size_t(p - s.address);
00026 }
00027 #endif
00028 
00029 #ifndef strncmp_P
00030 inline int strncmp_P(const char* a, ARDUINOJSON_NAMESPACE::pgm_p b, size_t n) {
00031   const char* s1 = a;
00032   const char* s2 = b.address;
00033   ARDUINOJSON_ASSERT(s1 != NULL);
00034   ARDUINOJSON_ASSERT(s2 != NULL);
00035   while (n-- > 0) {
00036     char c1 = *s1++;
00037     char c2 = static_cast<char>(pgm_read_byte(s2++));
00038     if (c1 < c2)
00039       return -1;
00040     if (c1 > c2)
00041       return 1;
00042     if (c1 == 0 /* and c2 as well */)
00043       return 0;
00044   }
00045   return 0;
00046 }
00047 #endif
00048 
00049 #ifndef strcmp_P
00050 inline int strcmp_P(const char* a, ARDUINOJSON_NAMESPACE::pgm_p b) {
00051   const char* s1 = a;
00052   const char* s2 = b.address;
00053   ARDUINOJSON_ASSERT(s1 != NULL);
00054   ARDUINOJSON_ASSERT(s2 != NULL);
00055   for (;;) {
00056     char c1 = *s1++;
00057     char c2 = static_cast<char>(pgm_read_byte(s2++));
00058     if (c1 < c2)
00059       return -1;
00060     if (c1 > c2)
00061       return 1;
00062     if (c1 == 0 /* and c2 as well */)
00063       return 0;
00064   }
00065 }
00066 #endif
00067 
00068 #ifndef memcpy_P
00069 inline void* memcpy_P(void* dst, ARDUINOJSON_NAMESPACE::pgm_p src, size_t n) {
00070   uint8_t* d = reinterpret_cast<uint8_t*>(dst);
00071   const char* s = src.address;
00072   ARDUINOJSON_ASSERT(d != NULL);
00073   ARDUINOJSON_ASSERT(s != NULL);
00074   while (n-- > 0) {
00075     *d++ = pgm_read_byte(s++);
00076   }
00077   return dst;
00078 }
00079 #endif