Update Iot.js
[platform/upstream/iotjs.git] / src / iotjs_util.c
1 /* Copyright 2015-present Samsung Electronics Co., Ltd. and other contributors
2  *
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15
16
17 #include "iotjs_def.h"
18 #include "iotjs_util.h"
19
20 #include <stdio.h>
21 #include <stdlib.h>
22 #include <string.h>
23
24
25 iotjs_string_t iotjs_file_read(const char* path) {
26   FILE* file = fopen(path, "rb");
27   IOTJS_ASSERT(file != NULL);
28
29   fseek(file, 0, SEEK_END);
30   long len = ftell(file);
31   IOTJS_ASSERT(len >= 0);
32   fseek(file, 0, SEEK_SET);
33
34   char* buffer = iotjs_buffer_allocate(len + 1);
35
36 #if defined(__NUTTX__) || defined(__TIZENRT__)
37   char* ptr = buffer;
38   unsigned nread = 0;
39   unsigned read = 0;
40
41   while ((nread = fread(ptr, 1, IOTJS_MAX_READ_BUFFER_SIZE, file)) > 0) {
42     read += nread;
43     ptr = buffer + read;
44   }
45 #else
46   size_t read = fread(buffer, 1, len, file);
47 #endif
48   IOTJS_ASSERT(read == (size_t)len);
49
50   *(buffer + len) = 0;
51
52   fclose(file);
53
54   iotjs_string_t contents = iotjs_string_create_with_buffer(buffer, len);
55
56   return contents;
57 }
58
59
60 char* iotjs_buffer_allocate(unsigned size) {
61   char* buffer = (char*)(calloc(size, sizeof(char)));
62   IOTJS_ASSERT(buffer != NULL);
63   return buffer;
64 }
65
66
67 char* iotjs_buffer_reallocate(char* buffer, unsigned size) {
68   IOTJS_ASSERT(buffer != NULL);
69   return (char*)(realloc(buffer, size));
70 }
71
72
73 void iotjs_buffer_release(char* buffer) {
74   IOTJS_ASSERT(buffer != NULL);
75   free(buffer);
76 }