1 // Copyright 2014 The Android Open Source Project 2 // 3 // This software is licensed under the terms of the GNU General Public 4 // License version 2, as published by the Free Software Foundation, and 5 // may be copied, distributed, and modified under those terms. 6 // 7 // This program is distributed in the hope that it will be useful, 8 // but WITHOUT ANY WARRANTY; without even the implied warranty of 9 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 10 // GNU General Public License for more details. 11 12 #ifndef ANDROID_UTILS_FILE_UTILS_H 13 #define ANDROID_UTILS_FILE_UTILS_H 14 15 #include "android/utils/compiler.h" 16 17 #include <stdbool.h> 18 #include <stddef.h> 19 #include <stdint.h> 20 21 ANDROID_BEGIN_HEADER 22 23 // A simple structure used to own a buffer of heap-allocated memory that 24 // typically comes from a file. 25 // |data| is the address of the corresponding data in memory. 26 // |size| is the size of the data in bytes. 27 // |flags| is used internally, do not use it. 28 // Note that |data| will always be NULL if |size| is 0. 29 typedef struct { 30 uint8_t* data; 31 size_t size; 32 // private 33 size_t flags; 34 } FileData; 35 36 // Initializer value for a FileData instance. 37 // Its important that this is all zeroes. 38 #define FILE_DATA_INIT { NULL, 0, 0 } 39 40 // Return true iff a |fileData| is empty. 41 static inline bool fileData_isEmpty(const FileData* fileData) { 42 return fileData->size == 0; 43 } 44 45 // Returns true iff |fileData| is valid. Used for unit-testing. 46 bool fileData_isValid(const FileData* fileData); 47 48 // Initialize a FileData value to the empty value. 49 void fileData_initEmpty(FileData* fileData); 50 51 // Initialize a FileData value by reading the content of a given file 52 // at |filePath|. On success, return 0 and initializes |fileData| properly. 53 // On failure, return -errno code, and set |fileData| to FILE_DATA_INIT. 54 int fileData_initFromFile(FileData* fileData, const char* filePath); 55 56 // Initialize a FileData by copying a memory buffer. 57 // |fileData| is the address of the FileData value to initialize. 58 // |buffer| is the address of the input buffer that will be copied 59 // into the FileData. 60 // |bufferLen| is the buffer length in bytes. 61 // Return 0 on success, -errno code on failure. 62 int fileData_initFromMemory(FileData* fileData, 63 const void* buffer, 64 size_t bufferLen); 65 66 // Copy a FileData value into another one. This copies the contents in 67 // the heap. On success return 0, on failure -errno code. 68 int fileData_initFrom(FileData* fileData, const FileData* other); 69 70 // Swap two FileData values. 71 void fileData_swap(FileData* fileData, FileData* other); 72 73 // Finalize a FileData value. This releases the corresponding memory. 74 void fileData_done(FileData* fileData); 75 76 ANDROID_END_HEADER 77 78 #endif // ANDROID_UTILS_FILE_UTILS_H 79