summaryrefslogtreecommitdiff
path: root/source/core/slang-io.cpp
blob: 6d2320cd074705370d7ba06b1addf45c70958596 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
#include "slang-io.h"
#include "exception.h"

#ifndef __STDC__
#   define __STDC__ 1
#endif

#include <sys/stat.h>

#ifdef _WIN32
#   include <direct.h>

#   define WIN32_LEAN_AND_MEAN
#   define VC_EXTRALEAN
#   include <Windows.h>
#endif

#if defined(__linux__) || defined(__CYGWIN__)
#   include <unistd.h>
#endif

#if SLANG_APPLE_FAMILY
#   include <mach-o/dyld.h>
#endif

#include <limits.h> /* PATH_MAX */
#include <stdio.h>
#include <stdlib.h>

namespace Slang
{
	bool File::Exists(const String & fileName)
	{
#ifdef _WIN32
		struct _stat32 statVar;
		return ::_wstat32(((String)fileName).ToWString(), &statVar) != -1;
#else
		struct stat statVar;
		return ::stat(fileName.Buffer(), &statVar) == 0;
#endif
	}

	String Path::TruncateExt(const String & path)
	{
		UInt dotPos = path.LastIndexOf('.');
		if (dotPos != -1)
			return path.SubString(0, dotPos);
		else
			return path;
	}
	String Path::ReplaceExt(const String & path, const char * newExt)
	{
		StringBuilder sb(path.Length()+10);
		UInt dotPos = path.LastIndexOf('.');
		if (dotPos == -1)
			dotPos = path.Length();
		sb.Append(path.Buffer(), dotPos);
		sb.Append('.');
		sb.Append(newExt);
		return sb.ProduceString();
	}

    static UInt findLastSeparator(String const& path)
    {
		UInt slashPos = path.LastIndexOf('/');
        UInt backslashPos = path.LastIndexOf('\\');

        if (slashPos == -1) return backslashPos;
        if (backslashPos == -1) return slashPos;

        UInt pos = slashPos;
        if (backslashPos > slashPos)
            pos = backslashPos;

        return pos;
    }

	String Path::GetFileName(const String & path)
	{
        UInt pos = findLastSeparator(path);
        if (pos != -1)
        {
            pos = pos + 1;
            return path.SubString(pos, path.Length() - pos);
        }
        else
        {
            return path;
        }
	}
	String Path::GetFileNameWithoutEXT(const String & path)
	{
        String fileName = GetFileName(path);
		UInt dotPos = fileName.LastIndexOf('.');
		if (dotPos == -1)
            return fileName;
		return fileName.SubString(0, dotPos);
	}
	String Path::GetFileExt(const String & path)
	{
		UInt dotPos = path.LastIndexOf('.');
		if (dotPos != -1)
			return path.SubString(dotPos+1, path.Length()-dotPos-1);
		else
			return "";
	}
	String Path::GetDirectoryName(const String & path)
	{
        UInt pos = findLastSeparator(path);
		if (pos != -1)
			return path.SubString(0, pos);
		else
			return "";
	}
	String Path::Combine(const String & path1, const String & path2)
	{
		if (path1.Length() == 0) return path2;
		StringBuilder sb(path1.Length()+path2.Length()+2);
		sb.Append(path1);
		if (!path1.EndsWith('\\') && !path1.EndsWith('/'))
			sb.Append(PathDelimiter);
		sb.Append(path2);
		return sb.ProduceString();
	}
	String Path::Combine(const String & path1, const String & path2, const String & path3)
	{
		StringBuilder sb(path1.Length()+path2.Length()+path3.Length()+3);
		sb.Append(path1);
		if (!path1.EndsWith('\\') && !path1.EndsWith('/'))
			sb.Append(PathDelimiter);
		sb.Append(path2);
		if (!path2.EndsWith('\\') && !path2.EndsWith('/'))
			sb.Append(PathDelimiter);
		sb.Append(path3);
		return sb.ProduceString();
	}

    /* static */ bool Path::IsDriveSpecification(const UnownedStringSlice& element)
    {
        switch (element.size())
        {
            case 0:     
            {
                // We'll just assume it is
                return true;
            }
            case 2:
            {
                // Look for a windows like drive spec
                const char firstChar = element[0]; 
                return element[1] == ':' && ((firstChar >= 'a' && firstChar <= 'z') || (firstChar >= 'A' && firstChar <= 'Z'));
            }
            default:    return false;
        }
        
    }

    /* static */void Path::Split(const UnownedStringSlice& path, List<UnownedStringSlice>& splitOut)
    {
        splitOut.Clear();

        const char* start = path.begin();
        const char* end = path.end();

        while (start < end)
        {
            const char* cur = start;
            // Find the split
            while (cur < end && !IsDelimiter(*cur)) cur++;

            splitOut.Add(UnownedStringSlice(start, cur));
           
            // Next
            start = cur + 1;
        }

        // Okay if the end is empty. And we aren't with a spec like // or c:/ , then drop the final slash 
        if (splitOut.Count() > 1 && splitOut.Last().size() == 0)
        {
            if (splitOut.Count() == 2 && IsDriveSpecification(splitOut[0]))
            {
                return;
            }
            // Remove the last 
            splitOut.RemoveLast();
        }
    }

    /* static */bool Path::IsRelative(const UnownedStringSlice& path)
    {
        List<UnownedStringSlice> split;
        Split(path, split);

        for (const auto& cur : split)
        {
            if (cur == "." || cur == "..")
            {
                return true;
            }
        }
        return false;
    }

    /* static */String Path::Simplify(const UnownedStringSlice& path)
    {
        List<UnownedStringSlice> split;
        Split(path, split);

        // Strictly speaking we could do something about case on platforms like window, but here we won't worry about that
        for (int i = 0; i < int(split.Count()); i++)
        {
            const UnownedStringSlice& cur = split[i];
            if (cur == "." && split.Count() > 1)
            {
                // Just remove it 
                split.RemoveAt(i);
                i--;
            }
            else if (cur == ".." && i > 0)
            {
                // Can we remove this and the one before ?
                UnownedStringSlice& before = split[i - 1];
                if (before == ".." || (i == 1 && IsDriveSpecification(before)))
                {
                    // Can't do it
                    continue;
                }
                split.RemoveRange(i - 1, 2);
                i -= 2;
            }
        }

        // If its empty it must be .
        if (split.Count() == 0)
        {
            split.Add(UnownedStringSlice::fromLiteral("."));
        }
   
        // Reconstruct the string
        StringBuilder builder;
        for (int i = 0; i < int(split.Count()); i++)
        {
            if (i > 0)
            {
                builder.Append(PathDelimiter);
            }
            builder.Append(split[i]);
        }

        return builder;
    }

	bool Path::CreateDir(const String & path)
	{
#if defined(_WIN32)
		return _wmkdir(path.ToWString()) == 0;
#else 
		return mkdir(path.Buffer(), 0777) == 0;
#endif
	}

    /* static */SlangResult Path::GetPathType(const String & path, SlangPathType* pathTypeOut)
    {
#ifdef _WIN32
        // https://msdn.microsoft.com/en-us/library/14h5k7ff.aspx
        struct _stat32 statVar;
        if (::_wstat32(String(path).ToWString(), &statVar) == 0)
        {
            if (statVar.st_mode & _S_IFDIR)
            {
                *pathTypeOut = SLANG_PATH_TYPE_DIRECTORY;
                return SLANG_OK;
            }
            else if (statVar.st_mode & _S_IFREG)
            {
                *pathTypeOut = SLANG_PATH_TYPE_FILE;
                return SLANG_OK;
            }
            return SLANG_FAIL;
        }

        return SLANG_E_NOT_FOUND;
#else
        struct stat statVar;
        if (::stat(path.Buffer(), &statVar) == 0)
        {
            if (S_ISDIR(statVar.st_mode))
            {
                *pathTypeOut = SLANG_PATH_TYPE_DIRECTORY;
                return SLANG_OK;
            }
            if (S_ISREG(statVar.st_mode))
            {
                *pathTypeOut = SLANG_PATH_TYPE_FILE;
                return SLANG_OK;
            }
            return SLANG_FAIL;
        }

        return SLANG_E_NOT_FOUND;
#endif
    }


    /* static */SlangResult Path::GetCanonical(const String & path, String & canonicalPathOut)
    {
#if defined(_WIN32)
        // https://msdn.microsoft.com/en-us/library/506720ff.aspx
        wchar_t* absPath = ::_wfullpath(nullptr, path.ToWString(), 0);
        if (!absPath)
        {
            return SLANG_FAIL;
        }  

        canonicalPathOut =  String::FromWString(absPath);
        ::free(absPath);
        return SLANG_OK;
#else
        // http://man7.org/linux/man-pages/man3/realpath.3.html
        char* canonicalPath = ::realpath(path.begin(), nullptr);
        if (canonicalPath)
        {
            canonicalPathOut = canonicalPath;
            ::free(canonicalPath);
            return SLANG_OK;
        }
        return SLANG_FAIL;
#endif
    }

    /// Gets the path to the executable that was invoked that led to the current threads execution
    /// If run from a shared library/dll will be the path of the executable that loaded said library
    /// @param outPath Pointer to buffer to hold the path.
    /// @param ioPathSize Size of the buffer to hold the path (including zero terminator). 
    /// @return SLANG_OK on success, SLANG_E_BUFFER_TOO_SMALL if buffer is too small. If ioPathSize is changed it will be the required size
    static SlangResult _calcExectuablePath(char* outPath, size_t* ioSize)
    {
        SLANG_ASSERT(ioSize);
        const size_t bufferSize = *ioSize;
        SLANG_ASSERT(bufferSize > 0);

#if SLANG_WINDOWS_FAMILY
        // https://docs.microsoft.com/en-us/windows/desktop/api/libloaderapi/nf-libloaderapi-getmodulefilenamea
        
        DWORD res = ::GetModuleFileNameA(::GetModuleHandle(nullptr), outPath, DWORD(bufferSize));
        // If it fits it's the size not including terminator. So must be less than bufferSize
        if (res < bufferSize)
        {
            return SLANG_OK;
        }
        return SLANG_E_BUFFER_TOO_SMALL;
#elif SLANG_LINUX_FAMILY

#   if defined(__linux__) || defined(__CYGWIN__)
        // https://linux.die.net/man/2/readlink
        // Mark last byte with 0, so can check overrun
        ssize_t resSize = ::readlink("/proc/self/exe", outPath, bufferSize);
        if (resSize < 0)
        {
            return SLANG_FAIL;
        }
        if (resSize >= bufferSize)
        {
            return SLANG_E_BUFFER_TOO_SMALL;
        }
        // Zero terminate
        outPath[resSize - 1] = 0;
        return SLANG_OK;
#   else        
        String text = Slang::File::ReadAllText("/proc/self/maps");
        UInt startIndex = text.IndexOf('/');
        if (startIndex == UInt(-1))
        {
            return SLANG_FAIL;
        }
        UInt endIndex = text.IndexOf("\n", startIndex);
        endIndex = (endIndex == UInt(-1)) ? text.Length() : endIndex;

        auto path = text.SubString(startIndex, endIndex - startIndex);

        if (path.getLength() < bufferSize)
        {
            ::memcpy(outPath, path.begin(), path.getLength());
            outPath[path.getLength()] = 0;
            return SLANG_OK;
        }

        *ioSize = path.getLength() + 1;
        return SLANG_E_BUFFER_TOO_SMALL;
#   endif

#elif SLANG_APPLE_FAMILY
        // https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/dyld.3.html
        uint32_t size = uint32_t(*ioSize);
        switch (_NSGetExecutablePath(outPath, &size))
        {
            case 0:           return SLANG_OK;
            case -1:
            {
                *ioSize = size;
                return SLANG_E_BUFFER_TOO_SMALL;
            }
            default: break;
        }
        return SLANG_FAIL;
#else
        return SLANG_E_NOT_IMPLEMENTED;
#endif
    }

    static String _getExecutablePath()
    {
        List<char> buffer;
        // Guess an initial buffer size
        buffer.SetSize(1024);

        while (true)
        {
            const size_t size = buffer.Count();
            size_t bufferSize = size;
            SlangResult res = _calcExectuablePath(buffer.Buffer(), &bufferSize);

            if (SLANG_SUCCEEDED(res))
            {
                return String(buffer.Buffer());
            }

            if (res != SLANG_E_BUFFER_TOO_SMALL)
            {
                // Couldn't determine the executable string
                return String();
            }

            // If bufferSize changed it should be the exact fit size, else we just make the buffer bigger by a guess (50% bigger)
            bufferSize = (bufferSize > size) ? bufferSize : (bufferSize + bufferSize / 2);
            buffer.SetSize(bufferSize);
        }
    }

    /* static */String Path::GetExecutablePath()
    {
        static String executablePath = _getExecutablePath();
        return executablePath;
    }

	Slang::String File::ReadAllText(const Slang::String & fileName)
	{
		StreamReader reader(new FileStream(fileName, FileMode::Open, FileAccess::Read, FileShare::ReadWrite));
		return reader.ReadToEnd();
	}

	Slang::List<unsigned char> File::ReadAllBytes(const Slang::String & fileName)
	{
		RefPtr<FileStream> fs = new FileStream(fileName, FileMode::Open, FileAccess::Read, FileShare::ReadWrite);
		List<unsigned char> buffer;
		while (!fs->IsEnd())
		{
			unsigned char ch;
			int read = (int)fs->Read(&ch, 1);
			if (read)
				buffer.Add(ch);
			else
				break;
		}
		return _Move(buffer);
	}

	void File::WriteAllText(const Slang::String & fileName, const Slang::String & text)
	{
		StreamWriter writer(new FileStream(fileName, FileMode::Create));
		writer.Write(text);
	}


}