1/*
2 * Copyright 2017, Andrew Lindesay <apl@lindesay.co.nz>
3 * Distributed under the terms of the MIT License.
4 */
5
6
7#include "JsonEvent.h"
8
9#include <stdlib.h>
10#include <stdio.h>
11
12#include <String.h>
13
14
15BJsonEvent::BJsonEvent(json_event_type eventType, const char* content)
16	:
17	fEventType(eventType),
18	fContent(content),
19	fOwnedContent(NULL)
20{
21}
22
23
24BJsonEvent::BJsonEvent(const char* content)
25	:
26	fEventType(B_JSON_STRING),
27	fContent(content),
28	fOwnedContent(NULL)
29{
30}
31
32
33BJsonEvent::BJsonEvent(double content) {
34	fEventType = B_JSON_NUMBER;
35	fContent = NULL;
36
37	int actualLength = snprintf(0, 0, "%f", content) + 1;
38	char* buffer = (char*) malloc(sizeof(char) * actualLength);
39
40	if (buffer == NULL) {
41		fprintf(stderr, "memory exhaustion\n");
42			// given the risk, this is the only sensible thing to do here.
43		exit(EXIT_FAILURE);
44	}
45
46	sprintf(buffer, "%f", content);
47	fOwnedContent = buffer;
48}
49
50
51BJsonEvent::BJsonEvent(int64 content) {
52	fEventType = B_JSON_NUMBER;
53	fContent = NULL;
54	fOwnedContent = NULL;
55
56	static const char* zeroValue = "0";
57	static const char* oneValue = "1";
58
59	switch (content) {
60		case 0:
61			fContent = zeroValue;
62			break;
63		case 1:
64			fContent = oneValue;
65			break;
66		default:
67		{
68			int actualLength = snprintf(0, 0, "%" B_PRId64, content) + 1;
69			char* buffer = (char*) malloc(sizeof(char) * actualLength);
70
71			if (buffer == NULL) {
72				fprintf(stderr, "memory exhaustion\n");
73					// given the risk, this is the only sensible thing to do
74					// here.
75				exit(EXIT_FAILURE);
76			}
77
78			sprintf(buffer, "%" B_PRId64, content);
79			fOwnedContent = buffer;
80			break;
81		}
82	}
83}
84
85
86BJsonEvent::BJsonEvent(json_event_type eventType)
87	:
88	fEventType(eventType),
89	fContent(NULL),
90	fOwnedContent(NULL)
91{
92}
93
94
95BJsonEvent::~BJsonEvent()
96{
97	if (NULL != fOwnedContent)
98		free(fOwnedContent);
99}
100
101
102json_event_type
103BJsonEvent::EventType() const
104{
105	return fEventType;
106}
107
108
109const char*
110BJsonEvent::Content() const
111{
112	if (NULL != fOwnedContent)
113		return fOwnedContent;
114	return fContent;
115}
116
117
118double
119BJsonEvent::ContentDouble() const
120{
121	return strtod(Content(), NULL);
122}
123
124
125int64
126BJsonEvent::ContentInteger() const
127{
128	return strtoll(Content(), NULL, 10);
129}
130