Files
ArduinoJson/src/Arduino/Print.cpp

61 lines
1.6 KiB
C++
Raw Normal View History

// Copyright Benoit Blanchon 2014-2016
2014-10-23 23:39:22 +02:00
// MIT License
//
// Arduino JSON library
// https://github.com/bblanchon/ArduinoJson
// If you like this project, please add a star!
2014-10-16 16:25:42 +02:00
#ifndef ARDUINO
2014-11-03 18:35:22 +01:00
#include "../../include/ArduinoJson/Arduino/Print.hpp"
2014-11-04 10:01:21 +01:00
#include <stdio.h>
#include <math.h> // for isnan() and isinf()
2014-10-16 16:25:42 +02:00
// only for GCC 4.9+
#if defined(__GNUC__) && \
(__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ >= 9))
#pragma GCC diagnostic ignored "-Wfloat-conversion"
#endif
// Visual Studo 2012 didn't have isnan, nor isinf
#if defined(_MSC_VER) && _MSC_VER <= 1700
#include <float.h>
#define isnan(x) _isnan(x)
#define isinf(x) (!_finite(x))
#endif
2014-10-23 19:54:00 +02:00
size_t Print::print(const char s[]) {
size_t n = 0;
while (*s) {
n += write(*s++);
}
return n;
2014-10-16 16:25:42 +02:00
}
2014-10-23 19:54:00 +02:00
size_t Print::print(double value, int digits) {
2015-04-23 21:27:58 +02:00
// https://github.com/arduino/Arduino/blob/db8cbf24c99dc930b9ccff1a43d018c81f178535/hardware/arduino/sam/cores/arduino/Print.cpp#L218
if (isnan(value)) return print("nan");
if (isinf(value)) return print("inf");
2014-10-23 19:54:00 +02:00
char tmp[32];
2015-04-23 21:27:58 +02:00
// https://github.com/arduino/Arduino/blob/db8cbf24c99dc930b9ccff1a43d018c81f178535/hardware/arduino/sam/cores/arduino/Print.cpp#L220
bool isBigDouble = value > 4294967040.0 || value < -4294967040.0;
if (isBigDouble) {
// Arduino's implementation prints "ovf"
// We prefer trying to use scientific notation, since we have sprintf
sprintf(tmp, "%g", value);
} else {
// Here we have the exact same output as Arduino's implementation
sprintf(tmp, "%.*f", digits, value);
}
2014-10-23 19:54:00 +02:00
return print(tmp);
2014-10-16 16:25:42 +02:00
}
2014-10-23 19:54:00 +02:00
size_t Print::println() { return write('\r') + write('\n'); }
2014-10-16 16:25:42 +02:00
2014-10-23 23:45:36 +02:00
#endif