summaryrefslogtreecommitdiff
path: root/src/adb_comp.c
blob: 3baaac307b4ef8c0da41aeec46acd5dad1acb354 (plain) (blame)
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
/* adb_comp.c - Alpine Package Keeper (APK)
 *
 * Copyright (C) 2021 Timo Teräs <timo.teras@iki.fi>
 * All rights reserved.
 *
 * SPDX-License-Identifier: GPL-2.0-only
 */

#include "apk_defines.h"
#include "adb.h"

struct apk_istream *adb_decompress(struct apk_istream *is, adb_comp_t *compression)
{
	adb_comp_t c = -1;

	if (IS_ERR(is)) return is;

	uint8_t *buf = apk_istream_peek(is, 4);
	if (IS_ERR(buf)) return ERR_PTR(apk_istream_close_error(is, PTR_ERR(buf)));
	if (memcmp(buf, "ADB", 3) != 0) return ERR_PTR(apk_istream_close_error(is, -APKE_ADB_HEADER));
	switch (buf[3]) {
	case '.':
		c = ADB_COMP_NONE;
		break;
	case 'd':
		c = ADB_COMP_DEFLATE;
		apk_istream_get(is, 4);
		is = apk_istream_deflate(is);
		break;
	}
	if (c == -1) return ERR_PTR(apk_istream_close_error(is, -APKE_ADB_COMPRESSION));
	if (compression) *compression = c;
	return is;
}

struct apk_ostream *adb_compress(struct apk_ostream *os, adb_comp_t compression)
{
	if (IS_ERR(os)) return os;
	switch (compression) {
	case ADB_COMP_NONE:
		return os;
	case ADB_COMP_DEFLATE:
		if (apk_ostream_write(os, "ADBd", 4) < 0) goto err;
		return apk_ostream_deflate(os);
	}
err:
	apk_ostream_cancel(os, -APKE_ADB_COMPRESSION);
	return ERR_PTR(apk_ostream_close(os));
}