From c20eadcfd1137398b2e63a870b412787ef4c27a9 Mon Sep 17 00:00:00 2001
From: Jan Breuer <jan.breuer@jaybee.cz>
Date: 摹曛, 02 6月 2016 04:24:46 +0800
Subject: [PATCH] Fix FALSE and TRUE in examples. Make scpi-def.cpp similar to c version

---
 libscpi/src/units.c |   28 +++++++++++++++++-----------
 1 files changed, 17 insertions(+), 11 deletions(-)

diff --git a/libscpi/src/units.c b/libscpi/src/units.c
index b13b467..9fc2072 100644
--- a/libscpi/src/units.c
+++ b/libscpi/src/units.c
@@ -63,7 +63,7 @@
  * units definition IEEE 488.2-1992 tab 7-1
  */
 const scpi_unit_def_t scpi_units_def[] = {
-#if USE_UNITS_PARICLES
+#if USE_UNITS_PARTICLES
     /* Absorbet dose */
     {/* name */ "GY", /* unit */ SCPI_UNIT_GRAY, /* mult */ 1},
 
@@ -90,7 +90,7 @@
 
     /* Mass */
     {/* name */ "U", /* unit */ SCPI_UNIT_ATOMIC_MASS, /* mult */ 1},
-#endif /* USE_UNITS_PARICLES */
+#endif /* USE_UNITS_PARTICLES */
 
 #if USE_UNITS_ANGLE
     /* Angle */
@@ -469,7 +469,7 @@
  * @param context
  * @param value number value
  * @param str target string
- * @param len max length of string
+ * @param len max length of string including null-character termination
  * @return number of chars written to string
  */
 size_t SCPI_NumberToStr(scpi_t * context, const scpi_choice_def_t * special, scpi_number_t * value, char * str, size_t len) {
@@ -477,28 +477,34 @@
     const char * unit;
     size_t result;
 
-    if (!value || !str) {
+    if (!value || !str || len==0) {
         return 0;
     }
 
     if (value->special) {
         if (SCPI_ChoiceToName(special, value->tag, &type)) {
             strncpy(str, type, len);
-            return min(strlen(type), len);
+            result = SCPIDEFINE_strnlen(str, len - 1);
+            str[result] = '\0';
+            return result;
         } else {
-            str[0] = 0;
+            str[0] = '\0';
             return 0;
         }
     }
 
     result = SCPI_DoubleToStr(value->value, str, len);
 
-    unit = translateUnitInverse(context->units, value->unit);
+    if (result + 1 < len) {
+        unit = translateUnitInverse(context->units, value->unit);
 
-    if (unit) {
-        strncat(str, " ", len);
-        strncat(str, unit, len);
-        result += strlen(unit) + 1;
+        if (unit) {
+            strncat(str, " ", len - result);
+            if (result + 2 < len) {
+                strncat(str, unit, len - result - 1);
+            }
+            result = strlen(str);
+        }
     }
 
     return result;

--
Gitblit v1.9.1