File: SDLRWwrapper.cpp

package info (click to toggle)
vcmi 1.6.5%2Bdfsg-2
  • links: PTS, VCS
  • area: contrib
  • in suites: forky, sid, trixie
  • size: 32,060 kB
  • sloc: cpp: 238,971; python: 265; sh: 224; xml: 157; ansic: 78; objc: 61; makefile: 49
file content (97 lines) | stat: -rw-r--r-- 2,054 bytes parent folder | download
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
/*
 * SDLRWwrapper.cpp, part of VCMI engine
 *
 * Authors: listed in file AUTHORS in main folder
 *
 * License: GNU General Public License v2.0 or later
 * Full text of license available in license.txt file, in main folder
 *
 */

#include "StdInc.h"
#include "SDLRWwrapper.h"

#include "../../lib/filesystem/CInputStream.h"

#include <SDL_rwops.h>

static inline CInputStream* get_stream(SDL_RWops* context)
{
	return static_cast<CInputStream*>(context->hidden.unknown.data1);
}

static Sint64 impl_size(SDL_RWops* context)
{
    return get_stream(context)->getSize();
}

static Sint64 impl_seek(SDL_RWops* context, Sint64 offset, int whence)
{
	auto stream = get_stream(context);
	switch (whence)
	{
	case RW_SEEK_SET:
		return stream->seek(offset);
		break;
	case RW_SEEK_CUR:
		return stream->seek(stream->tell() + offset);
		break;
	case RW_SEEK_END:
		return stream->seek(stream->getSize() + offset);
		break;
	default:
		return -1;
	}

}

static std::size_t impl_read(SDL_RWops* context, void *ptr, size_t size, size_t maxnum)
{
    auto stream = get_stream(context);
    auto oldpos = stream->tell();

    auto count = stream->read(static_cast<ui8*>(ptr), size*maxnum);

	if (count != 0 && count != size*maxnum)
	{
		// if not a whole amount of objects of size has been read, we need to seek
		stream->seek(oldpos + size * (count / size));
	}

    return count / size;
}

static std::size_t impl_write(SDL_RWops* context, const void *ptr, size_t size, size_t num)
{
	// writing is not supported
    return 0;
}

static int impl_close(SDL_RWops* context)
{
	if (context == nullptr)
		return 0;

    delete get_stream(context);
    SDL_FreeRW(context);
    return 0;
}


SDL_RWops* MakeSDLRWops(std::unique_ptr<CInputStream> in)
{
	SDL_RWops* result = SDL_AllocRW();
	if (!result)
		return nullptr;

	result->size  = &impl_size;
	result->seek  = &impl_seek;
	result->read  = &impl_read;
	result->write = &impl_write;
	result->close = &impl_close;

	result->type = SDL_RWOPS_UNKNOWN;
	result->hidden.unknown.data1 = in.release();

	return result;
}