DaveGamble / cJSON

Ultralightweight JSON parser in ANSI C
MIT License
10.88k stars 3.22k forks source link

Why isn't cJSON_CreateInteger a thing? #361

Open tonyp7 opened 5 years ago

tonyp7 commented 5 years ago

In case you want to deal with integer numbers, cJSON_CreateNumber seems to be wasteful.

There's an int to double cast that just shouldn't be there; not to mention potential problems with floating point numbers.

More specifically to my case, I'm running the lib on a 32 bits micro-controller with no 64 bit FPU; and that seems to be even more wasteful.

Is there any reason there is no way to natively set an integer directly? Would a PR to add it be accepted?

tonyp7 commented 5 years ago

Seems like you went for the strict Javascript "Number is a 64 bit floating point" design. ... In the end, fair enough I guess!

Alanscut commented 5 years ago

Seems like you went for the strict Javascript "Number is a 64 bit floating point" design. ... In the end, fair enough I guess!

hi, tony. In fact, the JSON(JavaScript Object Notatio) Number type is the Number type in JavaScript. I suppose this kind of design is to follow the JSON specification. Although the scene you mentioned is really a waste of memory.

mrfearless commented 5 years ago

Would be useful to support integers, a cJSON_CreateInteger would be handy, and have it accept a parameter as a dword size in x86 and qword size in x64 - size_t I believe in C code. Additionally a function to set the integer value for that object would be nice as well.

I currently do most of my coding in assembler and link to a statically compiled cjson library using stdcall for the functions. Having only the cJSON_SetNumberHelper that requires a double (qword size in x86 assembler) is awkward to manage.

Currently I have a function to set an integer, and use the fpu to convert it to a float/double so that the cJSON_Number object is correct when printing out (via cJSON_Print functions):

cJSON_SetIntegerValue PROC USES EBX hJSON:DWORD, dwIntegerValue:DWORD
    LOCAL qwNumberValue:QWORD

    mov ebx, hJSON
    .IF [ebx].cJSON.itemtype != cJSON_Number
        mov eax, NULL
        ret
    .ENDIF
    mov eax, dwIntegerValue
    mov [ebx].cJSON.valueint, eax    

    finit
    fild dwIntegerValue
    fstp qword ptr [qwNumberValue]

    mov eax, dword ptr [qwNumberValue]
    mov dword ptr [ebx].cJSON.valuedouble, eax
    mov eax, dword ptr [qwNumberValue+4]
    mov dword ptr [ebx+4].cJSON.valuedouble, eax

    mov eax, hJSON
    ret
cJSON_SetIntegerValue ENDP

So any support for integer creating/setting for x86 and x64 would be useful.