|
| 1 | +// |
| 2 | +// Graph.mm |
| 3 | +// OpenGraph_SPI |
| 4 | + |
| 5 | +#include "Graph.hpp" |
| 6 | +#include "OGGraphDescription.h" |
| 7 | + |
| 8 | +#if OG_OBJC_FOUNDATION |
| 9 | +#include <Foundation/Foundation.h> |
| 10 | +#include <zlib.h> |
| 11 | + |
| 12 | +void OG::Graph::write_to_file(const Graph * _Nullable graph, const char * _Nullable name, uint8_t options) OG_NOEXCEPT { |
| 13 | + @autoreleasepool { |
| 14 | + NSDictionary <NSString *, id> *options_dict = @{ |
| 15 | + (__bridge NSString *)OGDescriptionFormat: (__bridge NSString *)OGDescriptionFormatDictionary, |
| 16 | + (__bridge NSString *)OGDescriptionIncludeValues: @((options & 1) == 0), |
| 17 | + (__bridge NSString *)OGDescriptionAllGraphs: @(graph == nil) |
| 18 | + }; |
| 19 | + NSString *description = (__bridge NSString *)Graph::description(graph, options_dict); |
| 20 | + if (description == nil) { |
| 21 | + return; |
| 22 | + } |
| 23 | + const char *cstring_name = name ?: "graph.ag-gzon"; |
| 24 | + |
| 25 | + NSData *data = [NSJSONSerialization dataWithJSONObject:description options:0 error:nil]; |
| 26 | + NSString *file_path = [NSString stringWithUTF8String:cstring_name]; |
| 27 | + if (cstring_name[0] != '/') { |
| 28 | + file_path = [NSTemporaryDirectory() stringByAppendingPathComponent:file_path]; |
| 29 | + } |
| 30 | + NSError *error = nil; |
| 31 | + BOOL success = YES; |
| 32 | + if ([file_path.pathExtension isEqualToString:@"ag-gzon"]) { |
| 33 | + gzFile file = gzopen(file_path.fileSystemRepresentation, "wb"); |
| 34 | + if (file != NULL) { |
| 35 | + const char *bytes = (const char *)[data bytes]; |
| 36 | + NSUInteger remaining = [data length]; |
| 37 | + while (remaining != 0) { |
| 38 | + int bytes_written = gzwrite(file, bytes, (unsigned int)remaining); |
| 39 | + if (bytes_written <= 0) { |
| 40 | + success = NO; |
| 41 | + break; |
| 42 | + } |
| 43 | + bytes += bytes_written; |
| 44 | + remaining -= bytes_written; |
| 45 | + } |
| 46 | + gzclose(file); |
| 47 | + } |
| 48 | + } else { |
| 49 | + success = [data writeToFile:file_path options:0 error:&error]; |
| 50 | + } |
| 51 | + if (success) { |
| 52 | + fprintf(stderr, "Wrote graph data to \"%s\".\n", file_path.UTF8String); |
| 53 | + } else { |
| 54 | + fprintf(stderr, "Unable to write to \"%s\": %s\n", file_path.UTF8String, error.description.UTF8String); |
| 55 | + } |
| 56 | + } |
| 57 | +} |
| 58 | + |
| 59 | +#endif /* OG_OBJC_FOUNDATION */ |
0 commit comments