1 /*
2  * Copyright 2020 Lag Free Games, LLC
3  * All Rights Reserved.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the
7  * "Software"), to deal in the Software without restriction, including
8  * without limitation the rights to use, copy, modify, merge, publish,
9  * distribute, sub license, and/or sell copies of the Software, and to
10  * permit persons to whom the Software is furnished to do so, subject to
11  * the following conditions:
12  *
13  * The above copyright notice and this permission notice (including the
14  * next paragraph) shall be included in all copies or substantial portions
15  * of the Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
18  * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
19  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.
20  * IN NO EVENT SHALL VMWARE AND/OR ITS SUPPLIERS BE LIABLE FOR
21  * ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
22  * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
23  * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
24  */
25 
26 #include "memstream.h"
27 
28 #include <stdlib.h>
29 
30 #ifdef _WIN32
31 #include <windows.h>
32 #endif
33 
34 bool
u_memstream_open(struct u_memstream * mem,char ** bufp,size_t * sizep)35 u_memstream_open(struct u_memstream *mem, char **bufp, size_t *sizep)
36 {
37 #ifdef _GAMING_XBOX
38    int err = tmpfile_s(&mem->f);
39    mem->bufp = bufp;
40    mem->sizep = sizep;
41 
42    return err == 0;
43 #elif defined(_WIN32)
44    bool success = false;
45 
46    char path[MAX_PATH];
47    DWORD dwResult = GetTempPath(MAX_PATH, path);
48    if ((dwResult > 0) && (dwResult < MAX_PATH)) {
49       char *temp = mem->temp;
50       UINT uResult = GetTempFileName(path, "MEMSTREAM", 0, temp);
51       if (uResult != 0) {
52          FILE *f = fopen(temp, "w+b");
53          success = f != NULL;
54          if (success)
55          {
56             mem->f = f;
57             mem->bufp = bufp;
58             mem->sizep = sizep;
59          }
60       }
61    }
62 
63    return success;
64 #else
65    FILE *const f = open_memstream(bufp, sizep);
66    mem->f = f;
67    return f != NULL;
68 #endif
69 }
70 
71 void
u_memstream_close(struct u_memstream * mem)72 u_memstream_close(struct u_memstream *mem)
73 {
74    FILE *const f = mem->f;
75 
76 #ifdef _WIN32
77    long size = ftell(f);
78    if (size > 0) {
79       /* reserve space for the null terminator */
80       char *buf = malloc(size + 1);
81       fseek(f, 0, SEEK_SET);
82       fread(buf, 1, size, f);
83       /* insert null terminator */
84       buf[size] = '\0';
85 
86       *mem->bufp = buf;
87       *mem->sizep = size;
88    }
89 
90    remove(mem->temp);
91 #endif
92 
93    fclose(f);
94 }
95