Move internal/cgen up a couple of directories

This commit is contained in:
Nigel Tao committed 2019-03-09 13:28:59 +11:00
1 parent 9980a6fef4
commit 6826f2f748
23 files changed
+3 -1

No files matched your search

-112
View File
@@ -1,112 +0,0 @@
// After editing this file, run "go generate" in the parent directory.
// Copyright 2017 The Wuffs Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef WUFFS_INCLUDE_GUARD__BASE
#define WUFFS_INCLUDE_GUARD__BASE
#if defined(WUFFS_IMPLEMENTATION) && !defined(WUFFS_CONFIG__MODULES)
#define WUFFS_CONFIG__MODULES
#define WUFFS_CONFIG__MODULE__BASE
#endif
// !! WUFFS MONOLITHIC RELEASE DISCARDS EVERYTHING ABOVE.
// !! INSERT base/copyright
#include <stdbool.h>
#include <stdint.h>
#include <string.h>
#ifdef __cplusplus
extern "C" {
#endif
// !! INSERT base/all-public.h.
#ifdef __cplusplus
} // extern "C"
#endif
// WUFFS C HEADER ENDS HERE.
#ifdef WUFFS_IMPLEMENTATION
#ifdef __cplusplus
extern "C" {
#endif
// !! INSERT base/all-private.h.
#if !defined(WUFFS_CONFIG__MODULES) || defined(WUFFS_CONFIG__MODULE__BASE)
const uint8_t wuffs_base__low_bits_mask__u8[9] = {
0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF,
};
const uint16_t wuffs_base__low_bits_mask__u16[17] = {
0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF,
0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF,
};
const uint32_t wuffs_base__low_bits_mask__u32[33] = {
0x00000000, 0x00000001, 0x00000003, 0x00000007, 0x0000000F, 0x0000001F,
0x0000003F, 0x0000007F, 0x000000FF, 0x000001FF, 0x000003FF, 0x000007FF,
0x00000FFF, 0x00001FFF, 0x00003FFF, 0x00007FFF, 0x0000FFFF, 0x0001FFFF,
0x0003FFFF, 0x0007FFFF, 0x000FFFFF, 0x001FFFFF, 0x003FFFFF, 0x007FFFFF,
0x00FFFFFF, 0x01FFFFFF, 0x03FFFFFF, 0x07FFFFFF, 0x0FFFFFFF, 0x1FFFFFFF,
0x3FFFFFFF, 0x7FFFFFFF, 0xFFFFFFFF,
};
const uint64_t wuffs_base__low_bits_mask__u64[65] = {
0x0000000000000000, 0x0000000000000001, 0x0000000000000003,
0x0000000000000007, 0x000000000000000F, 0x000000000000001F,
0x000000000000003F, 0x000000000000007F, 0x00000000000000FF,
0x00000000000001FF, 0x00000000000003FF, 0x00000000000007FF,
0x0000000000000FFF, 0x0000000000001FFF, 0x0000000000003FFF,
0x0000000000007FFF, 0x000000000000FFFF, 0x000000000001FFFF,
0x000000000003FFFF, 0x000000000007FFFF, 0x00000000000FFFFF,
0x00000000001FFFFF, 0x00000000003FFFFF, 0x00000000007FFFFF,
0x0000000000FFFFFF, 0x0000000001FFFFFF, 0x0000000003FFFFFF,
0x0000000007FFFFFF, 0x000000000FFFFFFF, 0x000000001FFFFFFF,
0x000000003FFFFFFF, 0x000000007FFFFFFF, 0x00000000FFFFFFFF,
0x00000001FFFFFFFF, 0x00000003FFFFFFFF, 0x00000007FFFFFFFF,
0x0000000FFFFFFFFF, 0x0000001FFFFFFFFF, 0x0000003FFFFFFFFF,
0x0000007FFFFFFFFF, 0x000000FFFFFFFFFF, 0x000001FFFFFFFFFF,
0x000003FFFFFFFFFF, 0x000007FFFFFFFFFF, 0x00000FFFFFFFFFFF,
0x00001FFFFFFFFFFF, 0x00003FFFFFFFFFFF, 0x00007FFFFFFFFFFF,
0x0000FFFFFFFFFFFF, 0x0001FFFFFFFFFFFF, 0x0003FFFFFFFFFFFF,
0x0007FFFFFFFFFFFF, 0x000FFFFFFFFFFFFF, 0x001FFFFFFFFFFFFF,
0x003FFFFFFFFFFFFF, 0x007FFFFFFFFFFFFF, 0x00FFFFFFFFFFFFFF,
0x01FFFFFFFFFFFFFF, 0x03FFFFFFFFFFFFFF, 0x07FFFFFFFFFFFFFF,
0x0FFFFFFFFFFFFFFF, 0x1FFFFFFFFFFFFFFF, 0x3FFFFFFFFFFFFFFF,
0x7FFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF,
};
// !! INSERT wuffs_base__status strings.
// !! INSERT base/image-impl.c.
#endif // !defined(WUFFS_CONFIG__MODULES) ||
// defined(WUFFS_CONFIG__MODULE__BASE)
#ifdef __cplusplus
} // extern "C"
#endif
#endif // WUFFS_IMPLEMENTATION
// !! WUFFS MONOLITHIC RELEASE DISCARDS EVERYTHING BELOW.
#endif // WUFFS_INCLUDE_GUARD__BASE
@@ -1,479 +0,0 @@
// After editing this file, run "go generate" in the parent directory.
// Copyright 2017 The Wuffs Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
static inline wuffs_base__empty_struct //
wuffs_base__ignore_status(wuffs_base__status z) {
return wuffs_base__make_empty_struct();
}
// WUFFS_BASE__MAGIC is a magic number to check that initializers are called.
// It's not foolproof, given C doesn't automatically zero memory before use,
// but it should catch 99.99% of cases.
//
// Its (non-zero) value is arbitrary, based on md5sum("wuffs").
#define WUFFS_BASE__MAGIC ((uint32_t)0x3CCB6C71)
// WUFFS_BASE__DISABLED is a magic number to indicate that a non-recoverable
// error was previously encountered.
//
// Its (non-zero) value is arbitrary, based on md5sum("disabled").
#define WUFFS_BASE__DISABLED ((uint32_t)0x075AE3D2)
// Denote intentional fallthroughs for -Wimplicit-fallthrough.
//
// The order matters here. Clang also defines "__GNUC__".
#if defined(__clang__) && __cplusplus >= 201103L
#define WUFFS_BASE__FALLTHROUGH [[clang::fallthrough]]
#elif !defined(__clang__) && defined(__GNUC__) && (__GNUC__ >= 7)
#define WUFFS_BASE__FALLTHROUGH __attribute__((fallthrough))
#else
#define WUFFS_BASE__FALLTHROUGH
#endif
// Use switch cases for coroutine suspension points, similar to the technique
// in https://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
//
// We use trivial macros instead of an explicit assignment and case statement
// so that clang-format doesn't get confused by the unusual "case"s.
#define WUFFS_BASE__COROUTINE_SUSPENSION_POINT_0 case 0:;
#define WUFFS_BASE__COROUTINE_SUSPENSION_POINT(n) \
coro_susp_point = n; \
WUFFS_BASE__FALLTHROUGH; \
case n:;
#define WUFFS_BASE__COROUTINE_SUSPENSION_POINT_MAYBE_SUSPEND(n) \
if (!status) { \
goto ok; \
} else if (*status != '$') { \
goto exit; \
} \
coro_susp_point = n; \
goto suspend; \
case n:;
// Clang also defines "__GNUC__".
#if defined(__GNUC__)
#define WUFFS_BASE__LIKELY(expr) (__builtin_expect(!!(expr), 1))
#define WUFFS_BASE__UNLIKELY(expr) (__builtin_expect(!!(expr), 0))
#else
#define WUFFS_BASE__LIKELY(expr) (expr)
#define WUFFS_BASE__UNLIKELY(expr) (expr)
#endif
// The helpers below are functions, instead of macros, because their arguments
// can be an expression that we shouldn't evaluate more than once.
//
// They are static, so that linking multiple wuffs .o files won't complain about
// duplicate function definitions.
//
// They are explicitly marked inline, even if modern compilers don't use the
// inline attribute to guide optimizations such as inlining, to avoid the
// -Wunused-function warning, and we like to compile with -Wall -Werror.
// ---------------- Numeric Types
static inline uint8_t //
wuffs_base__load_u8be(uint8_t* p) {
return p[0];
}
static inline uint16_t //
wuffs_base__load_u16be(uint8_t* p) {
return ((uint16_t)(p[0]) << 8) | ((uint16_t)(p[1]) << 0);
}
static inline uint16_t //
wuffs_base__load_u16le(uint8_t* p) {
return ((uint16_t)(p[0]) << 0) | ((uint16_t)(p[1]) << 8);
}
static inline uint32_t //
wuffs_base__load_u24be(uint8_t* p) {
return ((uint32_t)(p[0]) << 16) | ((uint32_t)(p[1]) << 8) |
((uint32_t)(p[2]) << 0);
}
static inline uint32_t //
wuffs_base__load_u24le(uint8_t* p) {
return ((uint32_t)(p[0]) << 0) | ((uint32_t)(p[1]) << 8) |
((uint32_t)(p[2]) << 16);
}
static inline uint32_t //
wuffs_base__load_u32be(uint8_t* p) {
return ((uint32_t)(p[0]) << 24) | ((uint32_t)(p[1]) << 16) |
((uint32_t)(p[2]) << 8) | ((uint32_t)(p[3]) << 0);
}
static inline uint32_t //
wuffs_base__load_u32le(uint8_t* p) {
return ((uint32_t)(p[0]) << 0) | ((uint32_t)(p[1]) << 8) |
((uint32_t)(p[2]) << 16) | ((uint32_t)(p[3]) << 24);
}
static inline uint64_t //
wuffs_base__load_u40be(uint8_t* p) {
return ((uint64_t)(p[0]) << 32) | ((uint64_t)(p[1]) << 24) |
((uint64_t)(p[2]) << 16) | ((uint64_t)(p[3]) << 8) |
((uint64_t)(p[4]) << 0);
}
static inline uint64_t //
wuffs_base__load_u40le(uint8_t* p) {
return ((uint64_t)(p[0]) << 0) | ((uint64_t)(p[1]) << 8) |
((uint64_t)(p[2]) << 16) | ((uint64_t)(p[3]) << 24) |
((uint64_t)(p[4]) << 32);
}
static inline uint64_t //
wuffs_base__load_u48be(uint8_t* p) {
return ((uint64_t)(p[0]) << 40) | ((uint64_t)(p[1]) << 32) |
((uint64_t)(p[2]) << 24) | ((uint64_t)(p[3]) << 16) |
((uint64_t)(p[4]) << 8) | ((uint64_t)(p[5]) << 0);
}
static inline uint64_t //
wuffs_base__load_u48le(uint8_t* p) {
return ((uint64_t)(p[0]) << 0) | ((uint64_t)(p[1]) << 8) |
((uint64_t)(p[2]) << 16) | ((uint64_t)(p[3]) << 24) |
((uint64_t)(p[4]) << 32) | ((uint64_t)(p[5]) << 40);
}
static inline uint64_t //
wuffs_base__load_u56be(uint8_t* p) {
return ((uint64_t)(p[0]) << 48) | ((uint64_t)(p[1]) << 40) |
((uint64_t)(p[2]) << 32) | ((uint64_t)(p[3]) << 24) |
((uint64_t)(p[4]) << 16) | ((uint64_t)(p[5]) << 8) |
((uint64_t)(p[6]) << 0);
}
static inline uint64_t //
wuffs_base__load_u56le(uint8_t* p) {
return ((uint64_t)(p[0]) << 0) | ((uint64_t)(p[1]) << 8) |
((uint64_t)(p[2]) << 16) | ((uint64_t)(p[3]) << 24) |
((uint64_t)(p[4]) << 32) | ((uint64_t)(p[5]) << 40) |
((uint64_t)(p[6]) << 48);
}
static inline uint64_t //
wuffs_base__load_u64be(uint8_t* p) {
return ((uint64_t)(p[0]) << 56) | ((uint64_t)(p[1]) << 48) |
((uint64_t)(p[2]) << 40) | ((uint64_t)(p[3]) << 32) |
((uint64_t)(p[4]) << 24) | ((uint64_t)(p[5]) << 16) |
((uint64_t)(p[6]) << 8) | ((uint64_t)(p[7]) << 0);
}
static inline uint64_t //
wuffs_base__load_u64le(uint8_t* p) {
return ((uint64_t)(p[0]) << 0) | ((uint64_t)(p[1]) << 8) |
((uint64_t)(p[2]) << 16) | ((uint64_t)(p[3]) << 24) |
((uint64_t)(p[4]) << 32) | ((uint64_t)(p[5]) << 40) |
((uint64_t)(p[6]) << 48) | ((uint64_t)(p[7]) << 56);
}
// --------
static inline void //
wuffs_base__store_u8be(uint8_t* p, uint8_t x) {
p[0] = x;
}
static inline void //
wuffs_base__store_u16be(uint8_t* p, uint16_t x) {
p[0] = x >> 8;
p[1] = x >> 0;
}
static inline void //
wuffs_base__store_u16le(uint8_t* p, uint16_t x) {
p[0] = x >> 0;
p[1] = x >> 8;
}
static inline void //
wuffs_base__store_u24be(uint8_t* p, uint32_t x) {
p[0] = x >> 16;
p[1] = x >> 8;
p[2] = x >> 0;
}
static inline void //
wuffs_base__store_u24le(uint8_t* p, uint32_t x) {
p[0] = x >> 0;
p[1] = x >> 8;
p[2] = x >> 16;
}
static inline void //
wuffs_base__store_u32be(uint8_t* p, uint32_t x) {
p[0] = x >> 24;
p[1] = x >> 16;
p[2] = x >> 8;
p[3] = x >> 0;
}
static inline void //
wuffs_base__store_u32le(uint8_t* p, uint32_t x) {
p[0] = x >> 0;
p[1] = x >> 8;
p[2] = x >> 16;
p[3] = x >> 24;
}
static inline void //
wuffs_base__store_u40be(uint8_t* p, uint64_t x) {
p[0] = x >> 32;
p[1] = x >> 24;
p[2] = x >> 16;
p[3] = x >> 8;
p[4] = x >> 0;
}
static inline void //
wuffs_base__store_u40le(uint8_t* p, uint64_t x) {
p[0] = x >> 0;
p[1] = x >> 8;
p[2] = x >> 16;
p[3] = x >> 24;
p[4] = x >> 32;
}
static inline void //
wuffs_base__store_u48be(uint8_t* p, uint64_t x) {
p[0] = x >> 40;
p[1] = x >> 32;
p[2] = x >> 24;
p[3] = x >> 16;
p[4] = x >> 8;
p[5] = x >> 0;
}
static inline void //
wuffs_base__store_u48le(uint8_t* p, uint64_t x) {
p[0] = x >> 0;
p[1] = x >> 8;
p[2] = x >> 16;
p[3] = x >> 24;
p[4] = x >> 32;
p[5] = x >> 40;
}
static inline void //
wuffs_base__store_u56be(uint8_t* p, uint64_t x) {
p[0] = x >> 48;
p[1] = x >> 40;
p[2] = x >> 32;
p[3] = x >> 24;
p[4] = x >> 16;
p[5] = x >> 8;
p[6] = x >> 0;
}
static inline void //
wuffs_base__store_u56le(uint8_t* p, uint64_t x) {
p[0] = x >> 0;
p[1] = x >> 8;
p[2] = x >> 16;
p[3] = x >> 24;
p[4] = x >> 32;
p[5] = x >> 40;
p[6] = x >> 48;
}
static inline void //
wuffs_base__store_u64be(uint8_t* p, uint64_t x) {
p[0] = x >> 56;
p[1] = x >> 48;
p[2] = x >> 40;
p[3] = x >> 32;
p[4] = x >> 24;
p[5] = x >> 16;
p[6] = x >> 8;
p[7] = x >> 0;
}
static inline void //
wuffs_base__store_u64le(uint8_t* p, uint64_t x) {
p[0] = x >> 0;
p[1] = x >> 8;
p[2] = x >> 16;
p[3] = x >> 24;
p[4] = x >> 32;
p[5] = x >> 40;
p[6] = x >> 48;
p[7] = x >> 56;
}
// --------
extern const uint8_t wuffs_base__low_bits_mask__u8[9];
extern const uint16_t wuffs_base__low_bits_mask__u16[17];
extern const uint32_t wuffs_base__low_bits_mask__u32[33];
extern const uint64_t wuffs_base__low_bits_mask__u64[65];
#define WUFFS_BASE__LOW_BITS_MASK__U8(n) (wuffs_base__low_bits_mask__u8[n])
#define WUFFS_BASE__LOW_BITS_MASK__U16(n) (wuffs_base__low_bits_mask__u16[n])
#define WUFFS_BASE__LOW_BITS_MASK__U32(n) (wuffs_base__low_bits_mask__u32[n])
#define WUFFS_BASE__LOW_BITS_MASK__U64(n) (wuffs_base__low_bits_mask__u64[n])
// --------
static inline void //
wuffs_base__u8__sat_add_indirect(uint8_t* x, uint8_t y) {
*x = wuffs_base__u8__sat_add(*x, y);
}
static inline void //
wuffs_base__u8__sat_sub_indirect(uint8_t* x, uint8_t y) {
*x = wuffs_base__u8__sat_sub(*x, y);
}
static inline void //
wuffs_base__u16__sat_add_indirect(uint16_t* x, uint16_t y) {
*x = wuffs_base__u16__sat_add(*x, y);
}
static inline void //
wuffs_base__u16__sat_sub_indirect(uint16_t* x, uint16_t y) {
*x = wuffs_base__u16__sat_sub(*x, y);
}
static inline void //
wuffs_base__u32__sat_add_indirect(uint32_t* x, uint32_t y) {
*x = wuffs_base__u32__sat_add(*x, y);
}
static inline void //
wuffs_base__u32__sat_sub_indirect(uint32_t* x, uint32_t y) {
*x = wuffs_base__u32__sat_sub(*x, y);
}
static inline void //
wuffs_base__u64__sat_add_indirect(uint64_t* x, uint64_t y) {
*x = wuffs_base__u64__sat_add(*x, y);
}
static inline void //
wuffs_base__u64__sat_sub_indirect(uint64_t* x, uint64_t y) {
*x = wuffs_base__u64__sat_sub(*x, y);
}
// ---------------- Slices and Tables
// wuffs_base__slice_u8__prefix returns up to the first up_to bytes of s.
static inline wuffs_base__slice_u8 //
wuffs_base__slice_u8__prefix(wuffs_base__slice_u8 s, uint64_t up_to) {
if ((uint64_t)(s.len) > up_to) {
s.len = up_to;
}
return s;
}
// wuffs_base__slice_u8__suffix returns up to the last up_to bytes of s.
static inline wuffs_base__slice_u8 //
wuffs_base__slice_u8__suffix(wuffs_base__slice_u8 s, uint64_t up_to) {
if ((uint64_t)(s.len) > up_to) {
s.ptr += (uint64_t)(s.len) - up_to;
s.len = up_to;
}
return s;
}
// wuffs_base__slice_u8__copy_from_slice calls memmove(dst.ptr, src.ptr, len)
// where len is the minimum of dst.len and src.len.
//
// Passing a wuffs_base__slice_u8 with all fields NULL or zero (a valid, empty
// slice) is valid and results in a no-op.
static inline uint64_t //
wuffs_base__slice_u8__copy_from_slice(wuffs_base__slice_u8 dst,
wuffs_base__slice_u8 src) {
size_t len = dst.len < src.len ? dst.len : src.len;
if (len > 0) {
memmove(dst.ptr, src.ptr, len);
}
return len;
}
// --------
static inline wuffs_base__slice_u8 //
wuffs_base__table_u8__row(wuffs_base__table_u8 t, uint32_t y) {
if (y < t.height) {
return wuffs_base__make_slice_u8(t.ptr + (t.stride * y), t.width);
}
return wuffs_base__make_slice_u8(NULL, 0);
}
// ---------------- Slices and Tables (Utility)
static inline wuffs_base__slice_u8 //
wuffs_base__utility__null_slice_u8() {
return wuffs_base__make_slice_u8(NULL, 0);
}
// ---------------- Bureaucracy re -Wunused-function
static inline void
wuffs_base__acknowledge_potentially_unused_functions__core_private()
WUFFS_BASE__POTENTIALLY_UNUSED;
static inline void
wuffs_base__acknowledge_potentially_unused_functions__core_private() {
(void)(wuffs_base__ignore_status);
(void)(wuffs_base__load_u16be);
(void)(wuffs_base__load_u16le);
(void)(wuffs_base__load_u24be);
(void)(wuffs_base__load_u24le);
(void)(wuffs_base__load_u32be);
(void)(wuffs_base__load_u32le);
(void)(wuffs_base__load_u40be);
(void)(wuffs_base__load_u40le);
(void)(wuffs_base__load_u48be);
(void)(wuffs_base__load_u48le);
(void)(wuffs_base__load_u56be);
(void)(wuffs_base__load_u56le);
(void)(wuffs_base__load_u64be);
(void)(wuffs_base__load_u64le);
(void)(wuffs_base__load_u8be);
(void)(wuffs_base__slice_u8__copy_from_slice);
(void)(wuffs_base__slice_u8__prefix);
(void)(wuffs_base__slice_u8__suffix);
(void)(wuffs_base__store_u16be);
(void)(wuffs_base__store_u16le);
(void)(wuffs_base__store_u24be);
(void)(wuffs_base__store_u24le);
(void)(wuffs_base__store_u32be);
(void)(wuffs_base__store_u32le);
(void)(wuffs_base__store_u40be);
(void)(wuffs_base__store_u40le);
(void)(wuffs_base__store_u48be);
(void)(wuffs_base__store_u48le);
(void)(wuffs_base__store_u56be);
(void)(wuffs_base__store_u56le);
(void)(wuffs_base__store_u64be);
(void)(wuffs_base__store_u64le);
(void)(wuffs_base__store_u8be);
(void)(wuffs_base__table_u8__row);
(void)(wuffs_base__u16__sat_add_indirect);
(void)(wuffs_base__u16__sat_sub_indirect);
(void)(wuffs_base__u32__sat_add_indirect);
(void)(wuffs_base__u32__sat_sub_indirect);
(void)(wuffs_base__u64__sat_add_indirect);
(void)(wuffs_base__u64__sat_sub_indirect);
(void)(wuffs_base__u8__sat_add_indirect);
(void)(wuffs_base__u8__sat_sub_indirect);
(void)(wuffs_base__utility__null_slice_u8);
}
@@ -1,448 +0,0 @@
// After editing this file, run "go generate" in the parent directory.
// Copyright 2017 The Wuffs Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// Wuffs assumes that:
// - converting a uint32_t to a size_t will never overflow.
// - converting a size_t to a uint64_t will never overflow.
#ifdef __WORDSIZE
#if (__WORDSIZE != 32) && (__WORDSIZE != 64)
#error "Wuffs requires a word size of either 32 or 64 bits"
#endif
#endif
// WUFFS_VERSION is the major.minor.patch version, as per https://semver.org/,
// as a uint64_t. The major number is the high 32 bits. The minor number is the
// middle 16 bits. The patch number is the low 16 bits. The pre-release label
// and build metadata are part of the string representation (such as
// "1.2.3-beta+456.20181231") but not the uint64_t representation.
//
// WUFFS_VERSION_PRE_RELEASE_LABEL (such as "", "beta" or "rc.1") being
// non-empty denotes a developer preview, not a release version, and has no
// backwards or forwards compatibility guarantees.
//
// WUFFS_VERSION_BUILD_METADATA_XXX, if non-zero, are the number of commits and
// the last commit date in the repository used to build this library. Within
// each major.minor branch, the commit count should increase monotonically.
//
// !! Some code generation programs can override WUFFS_VERSION.
#define WUFFS_VERSION ((uint64_t)0)
#define WUFFS_VERSION_MAJOR ((uint64_t)0)
#define WUFFS_VERSION_MINOR ((uint64_t)0)
#define WUFFS_VERSION_PATCH ((uint64_t)0)
#define WUFFS_VERSION_PRE_RELEASE_LABEL "work.in.progress"
#define WUFFS_VERSION_BUILD_METADATA_COMMIT_COUNT 0
#define WUFFS_VERSION_BUILD_METADATA_COMMIT_DATE 0
#define WUFFS_VERSION_STRING "0.0.0+0.00000000"
// Define WUFFS_CONFIG__STATIC_FUNCTIONS to make all of Wuffs' functions have
// static storage. The motivation is discussed in the "ALLOW STATIC
// IMPLEMENTATION" section of
// https://raw.githubusercontent.com/nothings/stb/master/docs/stb_howto.txt
#ifdef WUFFS_CONFIG__STATIC_FUNCTIONS
#define WUFFS_BASE__MAYBE_STATIC static
#else
#define WUFFS_BASE__MAYBE_STATIC
#endif
// Clang also defines "__GNUC__".
#if defined(__GNUC__)
#define WUFFS_BASE__POTENTIALLY_UNUSED __attribute__((unused))
#define WUFFS_BASE__WARN_UNUSED_RESULT __attribute__((warn_unused_result))
#else
#define WUFFS_BASE__POTENTIALLY_UNUSED
#define WUFFS_BASE__WARN_UNUSED_RESULT
#endif
// Flags for wuffs_foo__bar__initialize functions.
#define WUFFS_INITIALIZE__DEFAULT_OPTIONS ((uint32_t)0x00000000)
// WUFFS_INITIALIZE__ALREADY_ZEROED means that the "self" receiver struct value
// has already been set to all zeroes.
#define WUFFS_INITIALIZE__ALREADY_ZEROED ((uint32_t)0x00000001)
// WUFFS_INITIALIZE__LEAVE_INTERNAL_BUFFERS_UNINITIALIZED means that, absent
// WUFFS_INITIALIZE__ALREADY_ZEROED, only some of the "self" receiver struct
// value will be set to all zeroes. Internal buffers, which tend to be a large
// proportion of the struct's size, will be left uninitialized. Internal means
// that the buffer is contained by the receiver struct, as opposed to being
// passed as a separately allocated "work buffer".
//
// With or without this bit set, the Wuffs compiler still enforces that no
// reads or writes will overflow internal buffers' bounds. Even with this bit
// set, the Wuffs standard library also considers reading from an uninitialized
// buffer to be a bug, and strives to never do so, but unlike buffer overflows,
// it is not a bug class that the Wuffs compiler eliminates.
//
// For those paranoid about security, leave this bit unset, so that
// wuffs_foo__bar__initialize will initialize the entire struct value to zeroes
// (unless WUFFS_INITIALIZE__ALREADY_ZEROED is set).
//
// Setting this bit gives a small absolute improvement on micro-benchmarks, but
// this can be a large relative effect, up to 2x faster, when the actual work
// to be done is also small, such as decompressing small input. See git commit
// 438fc105 "Move some struct fields to private_data" for some numbers and a
// discussion, noting that its commit message was written before this
// WUFFS_INITIALIZE__LEAVE_INTERNAL_BUFFERS_UNINITIALIZED option was defined.
#define WUFFS_INITIALIZE__LEAVE_INTERNAL_BUFFERS_UNINITIALIZED \
((uint32_t)0x00000002)
// --------
// wuffs_base__empty_struct is used when a Wuffs function returns an empty
// struct. In C, if a function f returns void, you can't say "x = f()", but in
// Wuffs, if a function g returns empty, you can say "y = g()".
typedef struct {
// private_impl is a placeholder field. It isn't explicitly used, except that
// without it, the sizeof a struct with no fields can differ across C/C++
// compilers, and it is undefined behavior in C99. For example, gcc says that
// the sizeof an empty struct is 0, and g++ says that it is 1. This leads to
// ABI incompatibility if a Wuffs .c file is processed by one compiler and
// its .h file with another compiler.
//
// Instead, we explicitly insert an otherwise unused field, so that the
// sizeof this struct is always 1.
uint8_t private_impl;
} wuffs_base__empty_struct;
static inline wuffs_base__empty_struct //
wuffs_base__make_empty_struct() {
wuffs_base__empty_struct ret;
ret.private_impl = 0;
return ret;
}
// wuffs_base__utility is a placeholder receiver type. It enables what Java
// calls static methods, as opposed to regular methods.
typedef struct {
// private_impl is a placeholder field. It isn't explicitly used, except that
// without it, the sizeof a struct with no fields can differ across C/C++
// compilers, and it is undefined behavior in C99. For example, gcc says that
// the sizeof an empty struct is 0, and g++ says that it is 1. This leads to
// ABI incompatibility if a Wuffs .c file is processed by one compiler and
// its .h file with another compiler.
//
// Instead, we explicitly insert an otherwise unused field, so that the
// sizeof this struct is always 1.
uint8_t private_impl;
} wuffs_base__utility;
// --------
// A status is either NULL (meaning OK) or a string message. That message is
// human-readable, for programmers, but it is not for end users. It is not
// localized, and does not contain additional contextual information such as a
// source filename.
//
// Status strings are statically allocated and should never be free'd. They can
// be compared by the == operator and not just by strcmp.
//
// Statuses come in four categories:
// - OK: the request was completed, successfully.
// - Warnings: the request was completed, unsuccessfully.
// - Suspensions: the request was not completed, but can be re-tried.
// - Errors: the request was not completed, permanently.
//
// When a function returns an incomplete status, a suspension means that that
// function should be called again within a new context, such as after flushing
// or re-filling an I/O buffer. An error means that an irrecoverable failure
// state was reached.
typedef const char* wuffs_base__status;
// !! INSERT wuffs_base__status names.
static inline bool //
wuffs_base__status__is_complete(wuffs_base__status z) {
return (z == NULL) || ((*z != '$') && (*z != '#'));
}
static inline bool //
wuffs_base__status__is_error(wuffs_base__status z) {
return z && (*z == '#');
}
static inline bool //
wuffs_base__status__is_ok(wuffs_base__status z) {
return z == NULL;
}
static inline bool //
wuffs_base__status__is_suspension(wuffs_base__status z) {
return z && (*z == '$');
}
static inline bool //
wuffs_base__status__is_warning(wuffs_base__status z) {
return z && (*z != '$') && (*z != '#');
}
// --------
// Flicks are a unit of time. One flick (frame-tick) is 1 / 705_600_000 of a
// second. See https://github.com/OculusVR/Flicks
typedef int64_t wuffs_base__flicks;
#define WUFFS_BASE__FLICKS_PER_SECOND ((uint64_t)705600000)
#define WUFFS_BASE__FLICKS_PER_MILLISECOND ((uint64_t)705600)
// ---------------- Numeric Types
static inline uint8_t //
wuffs_base__u8__min(uint8_t x, uint8_t y) {
return x < y ? x : y;
}
static inline uint8_t //
wuffs_base__u8__max(uint8_t x, uint8_t y) {
return x > y ? x : y;
}
static inline uint16_t //
wuffs_base__u16__min(uint16_t x, uint16_t y) {
return x < y ? x : y;
}
static inline uint16_t //
wuffs_base__u16__max(uint16_t x, uint16_t y) {
return x > y ? x : y;
}
static inline uint32_t //
wuffs_base__u32__min(uint32_t x, uint32_t y) {
return x < y ? x : y;
}
static inline uint32_t //
wuffs_base__u32__max(uint32_t x, uint32_t y) {
return x > y ? x : y;
}
static inline uint64_t //
wuffs_base__u64__min(uint64_t x, uint64_t y) {
return x < y ? x : y;
}
static inline uint64_t //
wuffs_base__u64__max(uint64_t x, uint64_t y) {
return x > y ? x : y;
}
// --------
// Saturating arithmetic (sat_add, sat_sub) branchless bit-twiddling algorithms
// are per https://locklessinc.com/articles/sat_arithmetic/
//
// It is important that the underlying types are unsigned integers, as signed
// integer arithmetic overflow is undefined behavior in C.
static inline uint8_t //
wuffs_base__u8__sat_add(uint8_t x, uint8_t y) {
uint8_t res = x + y;
res |= -(res < x);
return res;
}
static inline uint8_t //
wuffs_base__u8__sat_sub(uint8_t x, uint8_t y) {
uint8_t res = x - y;
res &= -(res <= x);
return res;
}
static inline uint16_t //
wuffs_base__u16__sat_add(uint16_t x, uint16_t y) {
uint16_t res = x + y;
res |= -(res < x);
return res;
}
static inline uint16_t //
wuffs_base__u16__sat_sub(uint16_t x, uint16_t y) {
uint16_t res = x - y;
res &= -(res <= x);
return res;
}
static inline uint32_t //
wuffs_base__u32__sat_add(uint32_t x, uint32_t y) {
uint32_t res = x + y;
res |= -(res < x);
return res;
}
static inline uint32_t //
wuffs_base__u32__sat_sub(uint32_t x, uint32_t y) {
uint32_t res = x - y;
res &= -(res <= x);
return res;
}
static inline uint64_t //
wuffs_base__u64__sat_add(uint64_t x, uint64_t y) {
uint64_t res = x + y;
res |= -(res < x);
return res;
}
static inline uint64_t //
wuffs_base__u64__sat_sub(uint64_t x, uint64_t y) {
uint64_t res = x - y;
res &= -(res <= x);
return res;
}
// ---------------- Slices and Tables
// WUFFS_BASE__SLICE is a 1-dimensional buffer.
//
// len measures a number of elements, not necessarily a size in bytes.
//
// A value with all fields NULL or zero is a valid, empty slice.
#define WUFFS_BASE__SLICE(T) \
struct { \
T* ptr; \
size_t len; \
}
// WUFFS_BASE__TABLE is a 2-dimensional buffer.
//
// width height, and stride measure a number of elements, not necessarily a
// size in bytes.
//
// A value with all fields NULL or zero is a valid, empty table.
#define WUFFS_BASE__TABLE(T) \
struct { \
T* ptr; \
size_t width; \
size_t height; \
size_t stride; \
}
typedef WUFFS_BASE__SLICE(uint8_t) wuffs_base__slice_u8;
typedef WUFFS_BASE__SLICE(uint16_t) wuffs_base__slice_u16;
typedef WUFFS_BASE__SLICE(uint32_t) wuffs_base__slice_u32;
typedef WUFFS_BASE__SLICE(uint64_t) wuffs_base__slice_u64;
typedef WUFFS_BASE__TABLE(uint8_t) wuffs_base__table_u8;
typedef WUFFS_BASE__TABLE(uint16_t) wuffs_base__table_u16;
typedef WUFFS_BASE__TABLE(uint32_t) wuffs_base__table_u32;
typedef WUFFS_BASE__TABLE(uint64_t) wuffs_base__table_u64;
static inline wuffs_base__slice_u8 //
wuffs_base__make_slice_u8(uint8_t* ptr, size_t len) {
wuffs_base__slice_u8 ret;
ret.ptr = ptr;
ret.len = len;
return ret;
}
static inline wuffs_base__slice_u16 //
wuffs_base__make_slice_u16(uint16_t* ptr, size_t len) {
wuffs_base__slice_u16 ret;
ret.ptr = ptr;
ret.len = len;
return ret;
}
static inline wuffs_base__slice_u32 //
wuffs_base__make_slice_u32(uint32_t* ptr, size_t len) {
wuffs_base__slice_u32 ret;
ret.ptr = ptr;
ret.len = len;
return ret;
}
static inline wuffs_base__slice_u64 //
wuffs_base__make_slice_u64(uint64_t* ptr, size_t len) {
wuffs_base__slice_u64 ret;
ret.ptr = ptr;
ret.len = len;
return ret;
}
// wuffs_base__slice_u8__subslice_i returns s[i:].
//
// It returns an empty slice if i is out of bounds.
static inline wuffs_base__slice_u8 //
wuffs_base__slice_u8__subslice_i(wuffs_base__slice_u8 s, uint64_t i) {
if ((i <= SIZE_MAX) && (i <= s.len)) {
return wuffs_base__make_slice_u8(s.ptr + i, s.len - i);
}
return wuffs_base__make_slice_u8(NULL, 0);
}
// wuffs_base__slice_u8__subslice_j returns s[:j].
//
// It returns an empty slice if j is out of bounds.
static inline wuffs_base__slice_u8 //
wuffs_base__slice_u8__subslice_j(wuffs_base__slice_u8 s, uint64_t j) {
if ((j <= SIZE_MAX) && (j <= s.len)) {
return wuffs_base__make_slice_u8(s.ptr, j);
}
return wuffs_base__make_slice_u8(NULL, 0);
}
// wuffs_base__slice_u8__subslice_ij returns s[i:j].
//
// It returns an empty slice if i or j is out of bounds.
static inline wuffs_base__slice_u8 //
wuffs_base__slice_u8__subslice_ij(wuffs_base__slice_u8 s,
uint64_t i,
uint64_t j) {
if ((i <= j) && (j <= SIZE_MAX) && (j <= s.len)) {
return wuffs_base__make_slice_u8(s.ptr + i, j - i);
}
return wuffs_base__make_slice_u8(NULL, 0);
}
// ---------------- Bureaucracy re -Wunused-function
static inline void
wuffs_base__acknowledge_potentially_unused_functions__core_public()
WUFFS_BASE__POTENTIALLY_UNUSED;
static inline void
wuffs_base__acknowledge_potentially_unused_functions__core_public() {
(void)(wuffs_base__make_empty_struct);
(void)(wuffs_base__make_slice_u16);
(void)(wuffs_base__make_slice_u32);
(void)(wuffs_base__make_slice_u64);
(void)(wuffs_base__make_slice_u8);
(void)(wuffs_base__slice_u8__subslice_i);
(void)(wuffs_base__slice_u8__subslice_ij);
(void)(wuffs_base__slice_u8__subslice_j);
(void)(wuffs_base__status__is_complete);
(void)(wuffs_base__status__is_error);
(void)(wuffs_base__status__is_ok);
(void)(wuffs_base__status__is_suspension);
(void)(wuffs_base__status__is_warning);
(void)(wuffs_base__u16__max);
(void)(wuffs_base__u16__min);
(void)(wuffs_base__u16__sat_add);
(void)(wuffs_base__u16__sat_sub);
(void)(wuffs_base__u32__max);
(void)(wuffs_base__u32__min);
(void)(wuffs_base__u32__sat_add);
(void)(wuffs_base__u32__sat_sub);
(void)(wuffs_base__u64__max);
(void)(wuffs_base__u64__min);
(void)(wuffs_base__u64__sat_add);
(void)(wuffs_base__u64__sat_sub);
(void)(wuffs_base__u8__max);
(void)(wuffs_base__u8__min);
(void)(wuffs_base__u8__sat_add);
(void)(wuffs_base__u8__sat_sub);
}
-167
View File
@@ -1,167 +0,0 @@
// After editing this file, run "go generate" in the parent directory.
// Copyright 2017 The Wuffs Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ---------------- Images
const uint32_t wuffs_base__pixel_format__bits_per_channel[16] = {
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
0x08, 0x0A, 0x0C, 0x10, 0x18, 0x20, 0x30, 0x40,
};
static uint64_t //
wuffs_base__pixel_swizzler__copy_1_1(wuffs_base__slice_u8 dst,
wuffs_base__slice_u8 dst_palette,
wuffs_base__slice_u8 src) {
return wuffs_base__slice_u8__copy_from_slice(dst, src);
}
static uint64_t //
wuffs_base__pixel_swizzler__copy_4_1(wuffs_base__slice_u8 dst,
wuffs_base__slice_u8 dst_palette,
wuffs_base__slice_u8 src) {
if (dst_palette.len != 1024) {
return 0;
}
size_t dst_len4 = dst.len / 4;
size_t len = dst_len4 < src.len ? dst_len4 : src.len;
uint8_t* d = dst.ptr;
uint8_t* s = src.ptr;
size_t n = len;
const int N = 4;
while (n >= N) {
wuffs_base__store_u32le(
d + (0 * 4),
wuffs_base__load_u32le(dst_palette.ptr + ((uint32_t)(s[0]) * 4)));
wuffs_base__store_u32le(
d + (1 * 4),
wuffs_base__load_u32le(dst_palette.ptr + ((uint32_t)(s[1]) * 4)));
wuffs_base__store_u32le(
d + (2 * 4),
wuffs_base__load_u32le(dst_palette.ptr + ((uint32_t)(s[2]) * 4)));
wuffs_base__store_u32le(
d + (3 * 4),
wuffs_base__load_u32le(dst_palette.ptr + ((uint32_t)(s[3]) * 4)));
s += 1 * N;
d += 4 * N;
n -= 1 * N;
}
while (n >= 1) {
wuffs_base__store_u32le(
d + (0 * 4),
wuffs_base__load_u32le(dst_palette.ptr + ((uint32_t)(s[0]) * 4)));
s += 1 * 1;
d += 4 * 1;
n -= 1 * 1;
}
return len;
}
static uint64_t //
wuffs_base__pixel_swizzler__swap_rgbx_bgrx(wuffs_base__slice_u8 dst,
wuffs_base__slice_u8 src) {
size_t len4 = (dst.len < src.len ? dst.len : src.len) / 4;
uint8_t* d = dst.ptr;
uint8_t* s = src.ptr;
size_t n = len4;
while (n--) {
uint8_t b0 = s[0];
uint8_t b1 = s[1];
uint8_t b2 = s[2];
uint8_t b3 = s[3];
d[0] = b2;
d[1] = b1;
d[2] = b0;
d[3] = b3;
s += 4;
d += 4;
}
return len4 * 4;
}
void //
wuffs_base__pixel_swizzler__prepare(wuffs_base__pixel_swizzler* p,
wuffs_base__pixel_format dst_format,
wuffs_base__slice_u8 dst_palette,
wuffs_base__pixel_format src_format,
wuffs_base__slice_u8 src_palette) {
if (!p) {
return;
}
// TODO: support many more formats.
uint64_t (*func)(wuffs_base__slice_u8 dst, wuffs_base__slice_u8 dst_palette,
wuffs_base__slice_u8 src) = NULL;
switch (src_format) {
case WUFFS_BASE__PIXEL_FORMAT__INDEXED__BGRA_BINARY:
switch (dst_format) {
case WUFFS_BASE__PIXEL_FORMAT__INDEXED__BGRA_NONPREMUL:
case WUFFS_BASE__PIXEL_FORMAT__INDEXED__BGRA_PREMUL:
case WUFFS_BASE__PIXEL_FORMAT__INDEXED__BGRA_BINARY:
if (wuffs_base__slice_u8__copy_from_slice(dst_palette, src_palette) !=
1024) {
break;
}
func = wuffs_base__pixel_swizzler__copy_1_1;
break;
case WUFFS_BASE__PIXEL_FORMAT__BGRA_NONPREMUL:
case WUFFS_BASE__PIXEL_FORMAT__BGRA_PREMUL:
case WUFFS_BASE__PIXEL_FORMAT__BGRA_BINARY:
if (wuffs_base__slice_u8__copy_from_slice(dst_palette, src_palette) !=
1024) {
break;
}
func = wuffs_base__pixel_swizzler__copy_4_1;
break;
case WUFFS_BASE__PIXEL_FORMAT__RGBA_NONPREMUL:
case WUFFS_BASE__PIXEL_FORMAT__RGBA_PREMUL:
case WUFFS_BASE__PIXEL_FORMAT__RGBA_BINARY:
if (wuffs_base__pixel_swizzler__swap_rgbx_bgrx(dst_palette,
src_palette) != 1024) {
break;
}
func = wuffs_base__pixel_swizzler__copy_4_1;
break;
default:
break;
}
break;
default:
break;
}
p->private_impl.func = func;
}
uint64_t //
wuffs_base__pixel_swizzler__swizzle_packed(wuffs_base__pixel_swizzler* p,
wuffs_base__slice_u8 dst,
wuffs_base__slice_u8 dst_palette,
wuffs_base__slice_u8 src) {
if (p && p->private_impl.func) {
return (*(p->private_impl.func))(dst, dst_palette, src);
}
return 0;
}
@@ -1,17 +0,0 @@
// After editing this file, run "go generate" in the parent directory.
// Copyright 2017 The Wuffs Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ---------------- Images
@@ -1,1118 +0,0 @@
// After editing this file, run "go generate" in the parent directory.
// Copyright 2017 The Wuffs Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ---------------- Images
// wuffs_base__color_u32_argb_premul is an 8 bit per channel premultiplied
// Alpha, Red, Green, Blue color, as a uint32_t value. It is in word order, not
// byte order: its value is always 0xAARRGGBB, regardless of endianness.
typedef uint32_t wuffs_base__color_u32_argb_premul;
// --------
// wuffs_base__pixel_format encodes the format of the bytes that constitute an
// image frame's pixel data. Its bits:
// - bit 31 is reserved.
// - bits 30 .. 28 encodes color (and channel order, in terms of memory).
// - bit 27 is reserved.
// - bits 26 .. 24 encodes transparency.
// - bits 23 .. 21 are reserved.
// - bit 20 indicates big-endian/MSB-first (as opposed to little/LSB).
// - bit 19 indicates floating point (as opposed to integer).
// - bit 18 indicates palette-indexed. The number-of-planes (the next
// field) will be zero, as the format is considered packed,
// but the 8-bit N-BGRA color data is stored in plane 3.
// - bits 17 .. 16 are the number of planes, minus 1. Zero means packed.
// - bits 15 .. 12 encodes the number of bits (depth) in the 3rd channel.
// - bits 11 .. 8 encodes the number of bits (depth) in the 2nd channel.
// - bits 7 .. 4 encodes the number of bits (depth) in the 1st channel.
// - bits 3 .. 0 encodes the number of bits (depth) in the 0th channel.
//
// The bit fields of a wuffs_base__pixel_format are not independent. For
// example, the number of planes should not be greater than the number of
// channels. Similarly, bits 15..4 are unused (and should be zero) if bits
// 31..24 (color and transparency) together imply only 1 channel (gray, no
// alpha) and floating point samples should mean a bit depth of 16, 32 or 64.
//
// Formats hold between 1 and 4 channels. For example: Y (1 channel: gray), YA
// (2 channels: gray and alpha), BGR (3 channels: blue, green, red) or CMYK (4
// channels: cyan, magenta, yellow, black).
//
// For direct formats with N > 1 channels, those channels can be laid out in
// either 1 (packed) or N (planar) planes. For example, RGBA data is usually
// packed, but YCbCr data is usually planar, due to chroma subsampling (for
// details, see the wuffs_base__pixel_subsampling type).
//
// For indexed formats, the palette (always 256 × 4 bytes) holds 8 bits per
// channel non-alpha-premultiplied BGRA color data. There is only 1 plane (for
// the index), as the format is considered packed. Plane 0 holds the per-pixel
// indices. Plane 3 is re-purposed to hold the per-index colors.
//
// The color field is encoded in 3 bits:
// - 0 means A (Alpha).
// - 1 means Y or YA (Gray, Alpha).
// - 2 means YCbCr or YCbCrA (Luma, Chroma-blue, Chroma-red, Alpha).
// - 3 means YCoCg or YCoCgA (Luma, Chroma-orange, Chroma-green, Alpha).
// - 4 means BGR, BGRX or BGRA (Blue, Green, Red, X-padding or Alpha).
// - 5 means RGB, RGBX or RGBA (Red, Green, Blue, X-padding or Alpha).
// - 6 means CMY or CMYK (Cyan, Magenta, Yellow, Black).
// - all other values are reserved.
//
// In Wuffs, channels are given in memory order (also known as byte order),
// regardless of endianness, since the C type for the pixel data is an array of
// bytes, not an array of uint32_t. For example, packed BGRA with 8 bits per
// channel means that the bytes in memory are always Blue, Green, Red then
// Alpha. On big-endian systems, that is the uint32_t 0xBBGGRRAA. On
// little-endian, 0xAARRGGBB.
//
// When the color field (3 bits) encodes multiple options, the transparency
// field (3 bits) distinguishes them:
// - 0 means fully opaque, no extra channels
// - 1 means fully opaque, one extra channel (X or K, padding or black).
// - 5 means one extra alpha channel, other channels are non-premultiplied.
// - 6 means one extra alpha channel, other channels are premultiplied.
// - 7 means one extra alpha channel, binary alpha.
// - all other values are reserved.
//
// Binary alpha means that if a color is not completely opaque, it is
// completely transparent black. As a source pixel format, it can therefore be
// treated as either non-premultiplied or premultiplied.
//
// The zero wuffs_base__pixel_format value is an invalid pixel format, as it is
// invalid to combine the zero color (alpha only) with the zero transparency.
//
// Bit depth is encoded in 4 bits:
// - 0 means the channel or index is unused.
// - x means a bit depth of x, for x in the range 1..8.
// - 9 means a bit depth of 10.
// - 10 means a bit depth of 12.
// - 11 means a bit depth of 16.
// - 12 means a bit depth of 24.
// - 13 means a bit depth of 32.
// - 14 means a bit depth of 48.
// - 15 means a bit depth of 64.
//
// For example, wuffs_base__pixel_format 0x5510BBBB is a natural format for
// decoding a PNG image - network byte order (also known as big-endian),
// packed, non-premultiplied alpha - that happens to be 16-bit-depth truecolor
// with alpha (RGBA). In memory order:
//
// ptr+0 ptr+1 ptr+2 ptr+3 ptr+4 ptr+5 ptr+6 ptr+7
// Rhi Rlo Ghi Glo Bhi Blo Ahi Alo
//
// For example, the value wuffs_base__pixel_format 0x40000565 means BGR with no
// alpha or padding, 5/6/5 bits for blue/green/red, packed 2 bytes per pixel,
// laid out LSB-first in memory order:
//
// ptr+0........... ptr+1...........
// MSB LSB MSB LSB
// G₂G₁G₀B₄B₃B₂B₁B₀ R₄R₃R₂R₁R₀G₅G₄G₃
//
// On little-endian systems (but not big-endian), this Wuffs pixel format value
// (0x40000565) corresponds to the Cairo library's CAIRO_FORMAT_RGB16_565, the
// SDL2 (Simple DirectMedia Layer 2) library's SDL_PIXELFORMAT_RGB565 and the
// Skia library's kRGB_565_SkColorType. Note BGR in Wuffs versus RGB in the
// other libraries.
//
// Regardless of endianness, this Wuffs pixel format value (0x40000565)
// corresponds to the V4L2 (Video For Linux 2) library's V4L2_PIX_FMT_RGB565
// and the Wayland-DRM library's WL_DRM_FORMAT_RGB565.
//
// Different software libraries name their pixel formats (and especially their
// channel order) either according to memory layout or as bits of a native
// integer type like uint32_t. The two conventions differ because of a system's
// endianness. As mentioned earlier, Wuffs pixel formats are always in memory
// order. More detail of other software libraries' naming conventions is in the
// Pixel Format Guide at https://afrantzis.github.io/pixel-format-guide/
//
// Do not manipulate these bits directly; they are private implementation
// details. Use methods such as wuffs_base__pixel_format__num_planes instead.
typedef uint32_t wuffs_base__pixel_format;
// Common 8-bit-depth pixel formats. This list is not exhaustive; not all valid
// wuffs_base__pixel_format values are present.
#define WUFFS_BASE__PIXEL_FORMAT__INVALID ((wuffs_base__pixel_format)0x00000000)
#define WUFFS_BASE__PIXEL_FORMAT__A ((wuffs_base__pixel_format)0x02000008)
#define WUFFS_BASE__PIXEL_FORMAT__Y ((wuffs_base__pixel_format)0x10000008)
#define WUFFS_BASE__PIXEL_FORMAT__YA_NONPREMUL \
((wuffs_base__pixel_format)0x15000008)
#define WUFFS_BASE__PIXEL_FORMAT__YA_PREMUL \
((wuffs_base__pixel_format)0x16000008)
#define WUFFS_BASE__PIXEL_FORMAT__YCBCR ((wuffs_base__pixel_format)0x20020888)
#define WUFFS_BASE__PIXEL_FORMAT__YCBCRK ((wuffs_base__pixel_format)0x21038888)
#define WUFFS_BASE__PIXEL_FORMAT__YCBCRA_NONPREMUL \
((wuffs_base__pixel_format)0x25038888)
#define WUFFS_BASE__PIXEL_FORMAT__YCOCG ((wuffs_base__pixel_format)0x30020888)
#define WUFFS_BASE__PIXEL_FORMAT__YCOCGK ((wuffs_base__pixel_format)0x31038888)
#define WUFFS_BASE__PIXEL_FORMAT__YCOCGA_NONPREMUL \
((wuffs_base__pixel_format)0x35038888)
#define WUFFS_BASE__PIXEL_FORMAT__INDEXED__BGRA_NONPREMUL \
((wuffs_base__pixel_format)0x45040008)
#define WUFFS_BASE__PIXEL_FORMAT__INDEXED__BGRA_PREMUL \
((wuffs_base__pixel_format)0x46040008)
#define WUFFS_BASE__PIXEL_FORMAT__INDEXED__BGRA_BINARY \
((wuffs_base__pixel_format)0x47040008)
#define WUFFS_BASE__PIXEL_FORMAT__BGR ((wuffs_base__pixel_format)0x40000888)
#define WUFFS_BASE__PIXEL_FORMAT__BGRX ((wuffs_base__pixel_format)0x41008888)
#define WUFFS_BASE__PIXEL_FORMAT__BGRA_NONPREMUL \
((wuffs_base__pixel_format)0x45008888)
#define WUFFS_BASE__PIXEL_FORMAT__BGRA_PREMUL \
((wuffs_base__pixel_format)0x46008888)
#define WUFFS_BASE__PIXEL_FORMAT__BGRA_BINARY \
((wuffs_base__pixel_format)0x47008888)
#define WUFFS_BASE__PIXEL_FORMAT__RGB ((wuffs_base__pixel_format)0x50000888)
#define WUFFS_BASE__PIXEL_FORMAT__RGBX ((wuffs_base__pixel_format)0x51008888)
#define WUFFS_BASE__PIXEL_FORMAT__RGBA_NONPREMUL \
((wuffs_base__pixel_format)0x55008888)
#define WUFFS_BASE__PIXEL_FORMAT__RGBA_PREMUL \
((wuffs_base__pixel_format)0x56008888)
#define WUFFS_BASE__PIXEL_FORMAT__RGBA_BINARY \
((wuffs_base__pixel_format)0x57008888)
#define WUFFS_BASE__PIXEL_FORMAT__CMY ((wuffs_base__pixel_format)0x60020888)
#define WUFFS_BASE__PIXEL_FORMAT__CMYK ((wuffs_base__pixel_format)0x61038888)
extern const uint32_t wuffs_base__pixel_format__bits_per_channel[16];
static inline bool //
wuffs_base__pixel_format__is_valid(wuffs_base__pixel_format f) {
return f != 0;
}
// wuffs_base__pixel_format__bits_per_pixel returns, for packed pixel formats,
// the number of bits per pixel. It returns 0 for planar pixel formats.
static inline uint32_t //
wuffs_base__pixel_format__bits_per_pixel(wuffs_base__pixel_format f) {
if (((f >> 16) & 0x03) != 0) {
return 0;
}
return wuffs_base__pixel_format__bits_per_channel[0x0F & (f >> 0)] +
wuffs_base__pixel_format__bits_per_channel[0x0F & (f >> 4)] +
wuffs_base__pixel_format__bits_per_channel[0x0F & (f >> 8)] +
wuffs_base__pixel_format__bits_per_channel[0x0F & (f >> 12)];
}
static inline bool //
wuffs_base__pixel_format__is_indexed(wuffs_base__pixel_format f) {
return (f >> 18) & 0x01;
}
static inline bool //
wuffs_base__pixel_format__is_packed(wuffs_base__pixel_format f) {
return ((f >> 16) & 0x03) == 0;
}
static inline bool //
wuffs_base__pixel_format__is_planar(wuffs_base__pixel_format f) {
return ((f >> 16) & 0x03) != 0;
}
static inline uint32_t //
wuffs_base__pixel_format__num_planes(wuffs_base__pixel_format f) {
return ((f >> 16) & 0x03) + 1;
}
#define WUFFS_BASE__PIXEL_FORMAT__NUM_PLANES_MAX 4
#define WUFFS_BASE__PIXEL_FORMAT__INDEXED__INDEX_PLANE 0
#define WUFFS_BASE__PIXEL_FORMAT__INDEXED__COLOR_PLANE 3
// --------
// wuffs_base__pixel_subsampling encodes the mapping of pixel space coordinates
// (x, y) to pixel buffer indices (i, j). That mapping can differ for each
// plane p. For a depth of 8 bits (1 byte), the p'th plane's sample starts at
// (planes[p].ptr + (j * planes[p].stride) + i).
//
// For packed pixel formats, the mapping is trivial: i = x and j = y. For
// planar pixel formats, the mapping can differ due to chroma subsampling. For
// example, consider a three plane YCbCr pixel format with 4:2:2 subsampling.
// For the luma (Y) channel, there is one sample for every pixel, but for the
// chroma (Cb, Cr) channels, there is one sample for every two pixels: pairs of
// horizontally adjacent pixels form one macropixel, i = x / 2 and j == y. In
// general, for a given p:
// - i = (x + bias_x) >> shift_x.
// - j = (y + bias_y) >> shift_y.
// where biases and shifts are in the range 0..3 and 0..2 respectively.
//
// In general, the biases will be zero after decoding an image. However, making
// a sub-image may change the bias, since the (x, y) coordinates are relative
// to the sub-image's top-left origin, but the backing pixel buffers were
// created relative to the original image's origin.
//
// For each plane p, each of those four numbers (biases and shifts) are encoded
// in two bits, which combine to form an 8 bit unsigned integer:
//
// e_p = (bias_x << 6) | (shift_x << 4) | (bias_y << 2) | (shift_y << 0)
//
// Those e_p values (e_0 for the first plane, e_1 for the second plane, etc)
// combine to form a wuffs_base__pixel_subsampling value:
//
// pixsub = (e_3 << 24) | (e_2 << 16) | (e_1 << 8) | (e_0 << 0)
//
// Do not manipulate these bits directly; they are private implementation
// details. Use methods such as wuffs_base__pixel_subsampling__bias_x instead.
typedef uint32_t wuffs_base__pixel_subsampling;
#define WUFFS_BASE__PIXEL_SUBSAMPLING__NONE ((wuffs_base__pixel_subsampling)0)
#define WUFFS_BASE__PIXEL_SUBSAMPLING__444 \
((wuffs_base__pixel_subsampling)0x000000)
#define WUFFS_BASE__PIXEL_SUBSAMPLING__440 \
((wuffs_base__pixel_subsampling)0x010100)
#define WUFFS_BASE__PIXEL_SUBSAMPLING__422 \
((wuffs_base__pixel_subsampling)0x101000)
#define WUFFS_BASE__PIXEL_SUBSAMPLING__420 \
((wuffs_base__pixel_subsampling)0x111100)
#define WUFFS_BASE__PIXEL_SUBSAMPLING__411 \
((wuffs_base__pixel_subsampling)0x202000)
#define WUFFS_BASE__PIXEL_SUBSAMPLING__410 \
((wuffs_base__pixel_subsampling)0x212100)
static inline uint32_t //
wuffs_base__pixel_subsampling__bias_x(wuffs_base__pixel_subsampling s,
uint32_t plane) {
uint32_t shift = ((plane & 0x03) * 8) + 6;
return (s >> shift) & 0x03;
}
static inline uint32_t //
wuffs_base__pixel_subsampling__shift_x(wuffs_base__pixel_subsampling s,
uint32_t plane) {
uint32_t shift = ((plane & 0x03) * 8) + 4;
return (s >> shift) & 0x03;
}
static inline uint32_t //
wuffs_base__pixel_subsampling__bias_y(wuffs_base__pixel_subsampling s,
uint32_t plane) {
uint32_t shift = ((plane & 0x03) * 8) + 2;
return (s >> shift) & 0x03;
}
static inline uint32_t //
wuffs_base__pixel_subsampling__shift_y(wuffs_base__pixel_subsampling s,
uint32_t plane) {
uint32_t shift = ((plane & 0x03) * 8) + 0;
return (s >> shift) & 0x03;
}
// --------
typedef struct {
// Do not access the private_impl's fields directly. There is no API/ABI
// compatibility or safety guarantee if you do so.
struct {
wuffs_base__pixel_format pixfmt;
wuffs_base__pixel_subsampling pixsub;
uint32_t width;
uint32_t height;
} private_impl;
#ifdef __cplusplus
inline void set(wuffs_base__pixel_format pixfmt,
wuffs_base__pixel_subsampling pixsub,
uint32_t width,
uint32_t height);
inline void invalidate();
inline bool is_valid();
inline wuffs_base__pixel_format pixel_format();
inline wuffs_base__pixel_subsampling pixel_subsampling();
inline wuffs_base__rect_ie_u32 bounds();
inline uint32_t width();
inline uint32_t height();
inline uint64_t pixbuf_len();
#endif // __cplusplus
} wuffs_base__pixel_config;
// TODO: Should this function return bool? An error type?
static inline void //
wuffs_base__pixel_config__set(wuffs_base__pixel_config* c,
wuffs_base__pixel_format pixfmt,
wuffs_base__pixel_subsampling pixsub,
uint32_t width,
uint32_t height) {
if (!c) {
return;
}
if (pixfmt) {
uint64_t wh = ((uint64_t)width) * ((uint64_t)height);
// TODO: handle things other than 1 byte per pixel.
if (wh <= ((uint64_t)SIZE_MAX)) {
c->private_impl.pixfmt = pixfmt;
c->private_impl.pixsub = pixsub;
c->private_impl.width = width;
c->private_impl.height = height;
return;
}
}
c->private_impl.pixfmt = 0;
c->private_impl.pixsub = 0;
c->private_impl.width = 0;
c->private_impl.height = 0;
}
static inline void //
wuffs_base__pixel_config__invalidate(wuffs_base__pixel_config* c) {
if (c) {
c->private_impl.pixfmt = 0;
c->private_impl.pixsub = 0;
c->private_impl.width = 0;
c->private_impl.height = 0;
}
}
static inline bool //
wuffs_base__pixel_config__is_valid(wuffs_base__pixel_config* c) {
return c && c->private_impl.pixfmt;
}
static inline wuffs_base__pixel_format //
wuffs_base__pixel_config__pixel_format(wuffs_base__pixel_config* c) {
return c ? c->private_impl.pixfmt : 0;
}
static inline wuffs_base__pixel_subsampling //
wuffs_base__pixel_config__pixel_subsampling(wuffs_base__pixel_config* c) {
return c ? c->private_impl.pixsub : 0;
}
static inline wuffs_base__rect_ie_u32 //
wuffs_base__pixel_config__bounds(wuffs_base__pixel_config* c) {
if (c) {
wuffs_base__rect_ie_u32 ret;
ret.min_incl_x = 0;
ret.min_incl_y = 0;
ret.max_excl_x = c->private_impl.width;
ret.max_excl_y = c->private_impl.height;
return ret;
}
wuffs_base__rect_ie_u32 ret;
ret.min_incl_x = 0;
ret.min_incl_y = 0;
ret.max_excl_x = 0;
ret.max_excl_y = 0;
return ret;
}
static inline uint32_t //
wuffs_base__pixel_config__width(wuffs_base__pixel_config* c) {
return c ? c->private_impl.width : 0;
}
static inline uint32_t //
wuffs_base__pixel_config__height(wuffs_base__pixel_config* c) {
return c ? c->private_impl.height : 0;
}
// TODO: this is the right API for planar (not packed) pixbufs? Should it allow
// decoding into a color model different from the format's intrinsic one? For
// example, decoding a JPEG image straight to RGBA instead of to YCbCr?
static inline uint64_t //
wuffs_base__pixel_config__pixbuf_len(wuffs_base__pixel_config* c) {
if (!c) {
return 0;
}
if (wuffs_base__pixel_format__is_planar(c->private_impl.pixfmt)) {
// TODO: support planar pixel formats, concious of pixel subsampling.
return 0;
}
uint32_t bits_per_pixel =
wuffs_base__pixel_format__bits_per_pixel(c->private_impl.pixfmt);
if ((bits_per_pixel == 0) || ((bits_per_pixel % 8) != 0)) {
// TODO: support fraction-of-byte pixels, e.g. 1 bit per pixel?
return 0;
}
uint64_t bytes_per_pixel = bits_per_pixel / 8;
uint64_t n =
((uint64_t)c->private_impl.width) * ((uint64_t)c->private_impl.height);
if (n > (UINT64_MAX / bytes_per_pixel)) {
return 0;
}
n *= bytes_per_pixel;
if (wuffs_base__pixel_format__is_indexed(c->private_impl.pixfmt)) {
if (n > (UINT64_MAX - 1024)) {
return 0;
}
n += 1024;
}
return n;
}
#ifdef __cplusplus
inline void //
wuffs_base__pixel_config::set(wuffs_base__pixel_format pixfmt,
wuffs_base__pixel_subsampling pixsub,
uint32_t width,
uint32_t height) {
wuffs_base__pixel_config__set(this, pixfmt, pixsub, width, height);
}
inline void //
wuffs_base__pixel_config::invalidate() {
wuffs_base__pixel_config__invalidate(this);
}
inline bool //
wuffs_base__pixel_config::is_valid() {
return wuffs_base__pixel_config__is_valid(this);
}
inline wuffs_base__pixel_format //
wuffs_base__pixel_config::pixel_format() {
return wuffs_base__pixel_config__pixel_format(this);
}
inline wuffs_base__pixel_subsampling //
wuffs_base__pixel_config::pixel_subsampling() {
return wuffs_base__pixel_config__pixel_subsampling(this);
}
inline wuffs_base__rect_ie_u32 //
wuffs_base__pixel_config::bounds() {
return wuffs_base__pixel_config__bounds(this);
}
inline uint32_t //
wuffs_base__pixel_config::width() {
return wuffs_base__pixel_config__width(this);
}
inline uint32_t //
wuffs_base__pixel_config::height() {
return wuffs_base__pixel_config__height(this);
}
inline uint64_t //
wuffs_base__pixel_config::pixbuf_len() {
return wuffs_base__pixel_config__pixbuf_len(this);
}
#endif // __cplusplus
// --------
typedef struct {
wuffs_base__pixel_config pixcfg;
// Do not access the private_impl's fields directly. There is no API/ABI
// compatibility or safety guarantee if you do so.
struct {
uint64_t first_frame_io_position;
bool first_frame_is_opaque;
} private_impl;
#ifdef __cplusplus
inline void set(wuffs_base__pixel_format pixfmt,
wuffs_base__pixel_subsampling pixsub,
uint32_t width,
uint32_t height,
uint64_t first_frame_io_position,
bool first_frame_is_opaque);
inline void invalidate();
inline bool is_valid();
inline uint64_t first_frame_io_position();
inline bool first_frame_is_opaque();
#endif // __cplusplus
} wuffs_base__image_config;
// TODO: Should this function return bool? An error type?
static inline void //
wuffs_base__image_config__set(wuffs_base__image_config* c,
wuffs_base__pixel_format pixfmt,
wuffs_base__pixel_subsampling pixsub,
uint32_t width,
uint32_t height,
uint64_t first_frame_io_position,
bool first_frame_is_opaque) {
if (!c) {
return;
}
if (wuffs_base__pixel_format__is_valid(pixfmt)) {
c->pixcfg.private_impl.pixfmt = pixfmt;
c->pixcfg.private_impl.pixsub = pixsub;
c->pixcfg.private_impl.width = width;
c->pixcfg.private_impl.height = height;
c->private_impl.first_frame_io_position = first_frame_io_position;
c->private_impl.first_frame_is_opaque = first_frame_is_opaque;
return;
}
c->pixcfg.private_impl.pixfmt = 0;
c->pixcfg.private_impl.pixsub = 0;
c->pixcfg.private_impl.width = 0;
c->pixcfg.private_impl.height = 0;
c->private_impl.first_frame_io_position = 0;
c->private_impl.first_frame_is_opaque = 0;
}
static inline void //
wuffs_base__image_config__invalidate(wuffs_base__image_config* c) {
if (c) {
c->pixcfg.private_impl.pixfmt = 0;
c->pixcfg.private_impl.pixsub = 0;
c->pixcfg.private_impl.width = 0;
c->pixcfg.private_impl.height = 0;
c->private_impl.first_frame_io_position = 0;
c->private_impl.first_frame_is_opaque = 0;
}
}
static inline bool //
wuffs_base__image_config__is_valid(wuffs_base__image_config* c) {
return c && wuffs_base__pixel_config__is_valid(&(c->pixcfg));
}
static inline uint64_t //
wuffs_base__image_config__first_frame_io_position(wuffs_base__image_config* c) {
return c ? c->private_impl.first_frame_io_position : 0;
}
static inline bool //
wuffs_base__image_config__first_frame_is_opaque(wuffs_base__image_config* c) {
return c ? c->private_impl.first_frame_is_opaque : false;
}
#ifdef __cplusplus
inline void //
wuffs_base__image_config::set(wuffs_base__pixel_format pixfmt,
wuffs_base__pixel_subsampling pixsub,
uint32_t width,
uint32_t height,
uint64_t first_frame_io_position,
bool first_frame_is_opaque) {
wuffs_base__image_config__set(this, pixfmt, pixsub, width, height,
first_frame_io_position, first_frame_is_opaque);
}
inline void //
wuffs_base__image_config::invalidate() {
wuffs_base__image_config__invalidate(this);
}
inline bool //
wuffs_base__image_config::is_valid() {
return wuffs_base__image_config__is_valid(this);
}
inline uint64_t //
wuffs_base__image_config::first_frame_io_position() {
return wuffs_base__image_config__first_frame_io_position(this);
}
inline bool //
wuffs_base__image_config::first_frame_is_opaque() {
return wuffs_base__image_config__first_frame_is_opaque(this);
}
#endif // __cplusplus
// --------
// wuffs_base__animation_blend encodes, for an animated image, how to blend the
// transparent pixels of this frame with the existing canvas. In Porter-Duff
// compositing operator terminology:
// - 0 means the frame may be transparent, and should be blended "src over
// dst", also known as just "over".
// - 1 means the frame may be transparent, and should be blended "src".
// - 2 means the frame is completely opaque, so that "src over dst" and "src"
// are equivalent.
//
// These semantics are conservative. It is valid for a completely opaque frame
// to have a blend value other than 2.
typedef uint8_t wuffs_base__animation_blend;
#define WUFFS_BASE__ANIMATION_BLEND__SRC_OVER_DST \
((wuffs_base__animation_blend)0)
#define WUFFS_BASE__ANIMATION_BLEND__SRC ((wuffs_base__animation_blend)1)
#define WUFFS_BASE__ANIMATION_BLEND__OPAQUE ((wuffs_base__animation_blend)2)
// --------
// wuffs_base__animation_disposal encodes, for an animated image, how to
// dispose of a frame after displaying it:
// - None means to draw the next frame on top of this one.
// - Restore Background means to clear the frame's dirty rectangle to "the
// background color" (in practice, this means transparent black) before
// drawing the next frame.
// - Restore Previous means to undo the current frame, so that the next frame
// is drawn on top of the previous one.
typedef uint8_t wuffs_base__animation_disposal;
#define WUFFS_BASE__ANIMATION_DISPOSAL__NONE ((wuffs_base__animation_disposal)0)
#define WUFFS_BASE__ANIMATION_DISPOSAL__RESTORE_BACKGROUND \
((wuffs_base__animation_disposal)1)
#define WUFFS_BASE__ANIMATION_DISPOSAL__RESTORE_PREVIOUS \
((wuffs_base__animation_disposal)2)
// --------
typedef struct {
// Do not access the private_impl's fields directly. There is no API/ABI
// compatibility or safety guarantee if you do so.
struct {
wuffs_base__rect_ie_u32 bounds;
wuffs_base__flicks duration;
uint64_t index;
uint64_t io_position;
wuffs_base__animation_blend blend;
wuffs_base__animation_disposal disposal;
} private_impl;
#ifdef __cplusplus
inline void update(wuffs_base__rect_ie_u32 bounds,
wuffs_base__flicks duration,
uint64_t index,
uint64_t io_position,
wuffs_base__animation_blend blend,
wuffs_base__animation_disposal disposal);
inline wuffs_base__rect_ie_u32 bounds();
inline uint32_t width();
inline uint32_t height();
inline wuffs_base__flicks duration();
inline uint64_t index();
inline uint64_t io_position();
inline wuffs_base__animation_blend blend();
inline wuffs_base__animation_disposal disposal();
#endif // __cplusplus
} wuffs_base__frame_config;
static inline void //
wuffs_base__frame_config__update(wuffs_base__frame_config* c,
wuffs_base__rect_ie_u32 bounds,
wuffs_base__flicks duration,
uint64_t index,
uint64_t io_position,
wuffs_base__animation_blend blend,
wuffs_base__animation_disposal disposal) {
if (!c) {
return;
}
c->private_impl.bounds = bounds;
c->private_impl.duration = duration;
c->private_impl.index = index;
c->private_impl.io_position = io_position;
c->private_impl.blend = blend;
c->private_impl.disposal = disposal;
}
static inline wuffs_base__rect_ie_u32 //
wuffs_base__frame_config__bounds(wuffs_base__frame_config* c) {
if (c) {
return c->private_impl.bounds;
}
wuffs_base__rect_ie_u32 ret;
ret.min_incl_x = 0;
ret.min_incl_y = 0;
ret.max_excl_x = 0;
ret.max_excl_y = 0;
return ret;
}
static inline uint32_t //
wuffs_base__frame_config__width(wuffs_base__frame_config* c) {
return c ? wuffs_base__rect_ie_u32__width(&c->private_impl.bounds) : 0;
}
static inline uint32_t //
wuffs_base__frame_config__height(wuffs_base__frame_config* c) {
return c ? wuffs_base__rect_ie_u32__height(&c->private_impl.bounds) : 0;
}
// wuffs_base__frame_config__duration returns the amount of time to display
// this frame. Zero means to display forever - a still (non-animated) image.
static inline wuffs_base__flicks //
wuffs_base__frame_config__duration(wuffs_base__frame_config* c) {
return c ? c->private_impl.duration : 0;
}
// wuffs_base__frame_config__index returns the index of this frame. The first
// frame in an image has index 0, the second frame has index 1, and so on.
static inline uint64_t //
wuffs_base__frame_config__index(wuffs_base__frame_config* c) {
return c ? c->private_impl.index : 0;
}
// wuffs_base__frame_config__io_position returns the I/O stream position before
// the frame config.
static inline uint64_t //
wuffs_base__frame_config__io_position(wuffs_base__frame_config* c) {
return c ? c->private_impl.io_position : 0;
}
// wuffs_base__frame_config__blend returns, for an animated image, how to blend
// the transparent pixels of this frame with the existing canvas.
static inline wuffs_base__animation_blend //
wuffs_base__frame_config__blend(wuffs_base__frame_config* c) {
return c ? c->private_impl.blend : 0;
}
// wuffs_base__frame_config__disposal returns, for an animated image, how to
// dispose of this frame after displaying it.
static inline wuffs_base__animation_disposal //
wuffs_base__frame_config__disposal(wuffs_base__frame_config* c) {
return c ? c->private_impl.disposal : 0;
}
#ifdef __cplusplus
inline void //
wuffs_base__frame_config::update(wuffs_base__rect_ie_u32 bounds,
wuffs_base__flicks duration,
uint64_t index,
uint64_t io_position,
wuffs_base__animation_blend blend,
wuffs_base__animation_disposal disposal) {
wuffs_base__frame_config__update(this, bounds, duration, index, io_position,
blend, disposal);
}
inline wuffs_base__rect_ie_u32 //
wuffs_base__frame_config::bounds() {
return wuffs_base__frame_config__bounds(this);
}
inline uint32_t //
wuffs_base__frame_config::width() {
return wuffs_base__frame_config__width(this);
}
inline uint32_t //
wuffs_base__frame_config::height() {
return wuffs_base__frame_config__height(this);
}
inline wuffs_base__flicks //
wuffs_base__frame_config::duration() {
return wuffs_base__frame_config__duration(this);
}
inline uint64_t //
wuffs_base__frame_config::index() {
return wuffs_base__frame_config__index(this);
}
inline uint64_t //
wuffs_base__frame_config::io_position() {
return wuffs_base__frame_config__io_position(this);
}
inline wuffs_base__animation_blend //
wuffs_base__frame_config::blend() {
return wuffs_base__frame_config__blend(this);
}
inline wuffs_base__animation_disposal //
wuffs_base__frame_config::disposal() {
return wuffs_base__frame_config__disposal(this);
}
#endif // __cplusplus
// --------
typedef struct {
wuffs_base__pixel_config pixcfg;
// Do not access the private_impl's fields directly. There is no API/ABI
// compatibility or safety guarantee if you do so.
struct {
wuffs_base__table_u8 planes[WUFFS_BASE__PIXEL_FORMAT__NUM_PLANES_MAX];
// TODO: color spaces.
} private_impl;
#ifdef __cplusplus
inline wuffs_base__status set_from_slice(wuffs_base__pixel_config* pixcfg,
wuffs_base__slice_u8 pixbuf_memory);
inline wuffs_base__slice_u8 palette();
inline wuffs_base__pixel_format pixel_format();
inline wuffs_base__table_u8 plane(uint32_t p);
#endif // __cplusplus
} wuffs_base__pixel_buffer;
static inline wuffs_base__status //
wuffs_base__pixel_buffer__set_from_slice(wuffs_base__pixel_buffer* b,
wuffs_base__pixel_config* pixcfg,
wuffs_base__slice_u8 pixbuf_memory) {
if (!b) {
return wuffs_base__error__bad_receiver;
}
memset(b, 0, sizeof(*b));
if (!pixcfg) {
return wuffs_base__error__bad_argument;
}
if (wuffs_base__pixel_format__is_planar(pixcfg->private_impl.pixfmt)) {
// TODO: support planar pixel formats, concious of pixel subsampling.
return wuffs_base__error__bad_argument;
}
uint32_t bits_per_pixel =
wuffs_base__pixel_format__bits_per_pixel(pixcfg->private_impl.pixfmt);
if ((bits_per_pixel == 0) || ((bits_per_pixel % 8) != 0)) {
return wuffs_base__error__bad_argument;
}
uint64_t bytes_per_pixel = bits_per_pixel / 8;
uint8_t* ptr = pixbuf_memory.ptr;
uint64_t len = pixbuf_memory.len;
if (wuffs_base__pixel_format__is_indexed(pixcfg->private_impl.pixfmt)) {
// Split a 1024 byte chunk (256 palette entries × 4 bytes per entry) from
// the start of pixbuf_memory. We split from the start, not the end, so
// that the both chunks' pointers have the same alignment as the original
// pointer, up to an alignment of 1024.
if (len < 1024) {
return wuffs_base__error__bad_argument_length_too_short;
}
wuffs_base__table_u8* tab =
&b->private_impl.planes[WUFFS_BASE__PIXEL_FORMAT__INDEXED__COLOR_PLANE];
tab->ptr = ptr;
tab->width = 1024;
tab->height = 1;
tab->stride = 1024;
ptr += 1024;
len -= 1024;
}
uint64_t wh = ((uint64_t)pixcfg->private_impl.width) *
((uint64_t)pixcfg->private_impl.height);
size_t width = (size_t)(pixcfg->private_impl.width);
if ((wh > (UINT64_MAX / bytes_per_pixel)) ||
(width > (SIZE_MAX / bytes_per_pixel))) {
return wuffs_base__error__bad_argument;
}
wh *= bytes_per_pixel;
width *= bytes_per_pixel;
if (wh > len) {
return wuffs_base__error__bad_argument_length_too_short;
}
b->pixcfg = *pixcfg;
wuffs_base__table_u8* tab = &b->private_impl.planes[0];
tab->ptr = ptr;
tab->width = width;
tab->height = pixcfg->private_impl.height;
tab->stride = width;
return NULL;
}
// wuffs_base__pixel_buffer__palette returns the palette color data. If
// non-empty, it will have length 1024.
static inline wuffs_base__slice_u8 //
wuffs_base__pixel_buffer__palette(wuffs_base__pixel_buffer* b) {
if (b &&
wuffs_base__pixel_format__is_indexed(b->pixcfg.private_impl.pixfmt)) {
wuffs_base__table_u8* tab =
&b->private_impl.planes[WUFFS_BASE__PIXEL_FORMAT__INDEXED__COLOR_PLANE];
if ((tab->width == 1024) && (tab->height == 1)) {
return wuffs_base__make_slice_u8(tab->ptr, 1024);
}
}
return wuffs_base__make_slice_u8(NULL, 0);
}
static inline wuffs_base__pixel_format //
wuffs_base__pixel_buffer__pixel_format(wuffs_base__pixel_buffer* b) {
if (b) {
return b->pixcfg.private_impl.pixfmt;
}
return WUFFS_BASE__PIXEL_FORMAT__INVALID;
}
static inline wuffs_base__table_u8 //
wuffs_base__pixel_buffer__plane(wuffs_base__pixel_buffer* b, uint32_t p) {
if (b && (p < WUFFS_BASE__PIXEL_FORMAT__NUM_PLANES_MAX)) {
return b->private_impl.planes[p];
}
wuffs_base__table_u8 ret;
ret.ptr = NULL;
ret.width = 0;
ret.height = 0;
ret.stride = 0;
return ret;
}
#ifdef __cplusplus
inline wuffs_base__status //
wuffs_base__pixel_buffer::set_from_slice(wuffs_base__pixel_config* pixcfg,
wuffs_base__slice_u8 pixbuf_memory) {
return wuffs_base__pixel_buffer__set_from_slice(this, pixcfg, pixbuf_memory);
}
inline wuffs_base__slice_u8 //
wuffs_base__pixel_buffer::palette() {
return wuffs_base__pixel_buffer__palette(this);
}
inline wuffs_base__pixel_format //
wuffs_base__pixel_buffer::pixel_format() {
return wuffs_base__pixel_buffer__pixel_format(this);
}
inline wuffs_base__table_u8 //
wuffs_base__pixel_buffer::plane(uint32_t p) {
return wuffs_base__pixel_buffer__plane(this, p);
}
#endif // __cplusplus
// --------
typedef struct {
// Do not access the private_impl's fields directly. There is no API/ABI
// compatibility or safety guarantee if you do so.
struct {
uint8_t TODO;
} private_impl;
#ifdef __cplusplus
#endif // __cplusplus
} wuffs_base__decode_frame_options;
#ifdef __cplusplus
#endif // __cplusplus
// --------
typedef struct {
// Do not access the private_impl's fields directly. There is no API/ABI
// compatibility or safety guarantee if you do so.
struct {
// TODO: should the func type take restrict pointers?
uint64_t (*func)(wuffs_base__slice_u8 dst,
wuffs_base__slice_u8 dst_palette,
wuffs_base__slice_u8 src);
} private_impl;
#ifdef __cplusplus
inline void prepare(wuffs_base__pixel_format dst_format,
wuffs_base__slice_u8 dst_palette,
wuffs_base__pixel_format src_format,
wuffs_base__slice_u8 src_palette);
inline uint64_t swizzle_packed(wuffs_base__slice_u8 dst,
wuffs_base__slice_u8 dst_palette,
wuffs_base__slice_u8 src);
#endif // __cplusplus
} wuffs_base__pixel_swizzler;
// TODO: should prepare (both the C and C++ methods) return a status?
void //
wuffs_base__pixel_swizzler__prepare(wuffs_base__pixel_swizzler* p,
wuffs_base__pixel_format dst_format,
wuffs_base__slice_u8 dst_palette,
wuffs_base__pixel_format src_format,
wuffs_base__slice_u8 src_palette);
uint64_t //
wuffs_base__pixel_swizzler__swizzle_packed(wuffs_base__pixel_swizzler* p,
wuffs_base__slice_u8 dst,
wuffs_base__slice_u8 dst_palette,
wuffs_base__slice_u8 src);
#ifdef __cplusplus
inline void //
wuffs_base__pixel_swizzler::prepare(wuffs_base__pixel_format dst_format,
wuffs_base__slice_u8 dst_palette,
wuffs_base__pixel_format src_format,
wuffs_base__slice_u8 src_palette) {
wuffs_base__pixel_swizzler__prepare(this, dst_format, dst_palette, src_format,
src_palette);
}
uint64_t //
wuffs_base__pixel_swizzler::swizzle_packed(wuffs_base__slice_u8 dst,
wuffs_base__slice_u8 dst_palette,
wuffs_base__slice_u8 src) {
return wuffs_base__pixel_swizzler__swizzle_packed(this, dst, dst_palette,
src);
}
#endif // __cplusplus
// ---------------- Bureaucracy re -Wunused-function
static inline void
wuffs_base__acknowledge_potentially_unused_functions__image_public()
WUFFS_BASE__POTENTIALLY_UNUSED;
static inline void
wuffs_base__acknowledge_potentially_unused_functions__image_public() {
(void)(wuffs_base__frame_config__blend);
(void)(wuffs_base__frame_config__bounds);
(void)(wuffs_base__frame_config__disposal);
(void)(wuffs_base__frame_config__duration);
(void)(wuffs_base__frame_config__height);
(void)(wuffs_base__frame_config__index);
(void)(wuffs_base__frame_config__io_position);
(void)(wuffs_base__frame_config__update);
(void)(wuffs_base__frame_config__width);
(void)(wuffs_base__image_config__first_frame_io_position);
(void)(wuffs_base__image_config__first_frame_is_opaque);
(void)(wuffs_base__image_config__invalidate);
(void)(wuffs_base__image_config__is_valid);
(void)(wuffs_base__image_config__set);
(void)(wuffs_base__pixel_buffer__palette);
(void)(wuffs_base__pixel_buffer__pixel_format);
(void)(wuffs_base__pixel_buffer__plane);
(void)(wuffs_base__pixel_buffer__set_from_slice);
(void)(wuffs_base__pixel_config__bounds);
(void)(wuffs_base__pixel_config__height);
(void)(wuffs_base__pixel_config__invalidate);
(void)(wuffs_base__pixel_config__is_valid);
(void)(wuffs_base__pixel_config__pixbuf_len);
(void)(wuffs_base__pixel_config__pixel_format);
(void)(wuffs_base__pixel_config__pixel_subsampling);
(void)(wuffs_base__pixel_config__set);
(void)(wuffs_base__pixel_config__width);
(void)(wuffs_base__pixel_format__bits_per_pixel);
(void)(wuffs_base__pixel_format__is_indexed);
(void)(wuffs_base__pixel_format__is_packed);
(void)(wuffs_base__pixel_format__is_planar);
(void)(wuffs_base__pixel_format__is_valid);
(void)(wuffs_base__pixel_format__num_planes);
(void)(wuffs_base__pixel_subsampling__bias_x);
(void)(wuffs_base__pixel_subsampling__bias_y);
(void)(wuffs_base__pixel_subsampling__shift_x);
(void)(wuffs_base__pixel_subsampling__shift_y);
(void)(wuffs_base__pixel_swizzler__prepare);
(void)(wuffs_base__pixel_swizzler__swizzle_packed);
}
-336
View File
@@ -1,336 +0,0 @@
// After editing this file, run "go generate" in the parent directory.
// Copyright 2017 The Wuffs Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ---------------- I/O
static inline bool //
wuffs_base__io_buffer__is_valid(wuffs_base__io_buffer buf) {
return (buf.data.ptr || (buf.data.len == 0)) &&
(buf.data.len >= buf.meta.wi) && (buf.meta.wi >= buf.meta.ri);
}
// TODO: wuffs_base__io_reader__is_eof is no longer used by Wuffs per se, but
// it might be handy to programs that use Wuffs. Either delete it, or promote
// it to the public API.
//
// If making this function public (i.e. moving it to base-header.h), it also
// needs to allow NULL (i.e. implicit, callee-calculated) mark/limit.
static inline bool //
wuffs_base__io_reader__is_eof(wuffs_base__io_reader o) {
wuffs_base__io_buffer* buf = o.private_impl.buf;
return buf && buf->meta.closed &&
(buf->data.ptr + buf->meta.wi == o.private_impl.limit);
}
static inline bool //
wuffs_base__io_reader__is_valid(wuffs_base__io_reader o) {
wuffs_base__io_buffer* buf = o.private_impl.buf;
// Note: if making this function public (i.e. moving it to base-header.h), it
// also needs to allow NULL (i.e. implicit, callee-calculated) mark/limit.
return buf ? ((buf->data.ptr <= o.private_impl.mark) &&
(o.private_impl.mark <= o.private_impl.limit) &&
(o.private_impl.limit <= buf->data.ptr + buf->data.len))
: ((o.private_impl.mark == NULL) &&
(o.private_impl.limit == NULL));
}
static inline bool //
wuffs_base__io_writer__is_valid(wuffs_base__io_writer o) {
wuffs_base__io_buffer* buf = o.private_impl.buf;
// Note: if making this function public (i.e. moving it to base-header.h), it
// also needs to allow NULL (i.e. implicit, callee-calculated) mark/limit.
return buf ? ((buf->data.ptr <= o.private_impl.mark) &&
(o.private_impl.mark <= o.private_impl.limit) &&
(o.private_impl.limit <= buf->data.ptr + buf->data.len))
: ((o.private_impl.mark == NULL) &&
(o.private_impl.limit == NULL));
}
static inline uint32_t //
wuffs_base__io_writer__copy_n_from_history(uint8_t** ptr_iop_w,
uint8_t* io0_w,
uint8_t* io1_w,
uint32_t length,
uint32_t distance) {
if (!distance) {
return 0;
}
uint8_t* p = *ptr_iop_w;
if ((size_t)(p - io0_w) < (size_t)(distance)) {
return 0;
}
uint8_t* q = p - distance;
size_t n = io1_w - p;
if ((size_t)(length) > n) {
length = n;
} else {
n = length;
}
// TODO: unrolling by 3 seems best for the std/deflate benchmarks, but that
// is mostly because 3 is the minimum length for the deflate format. This
// function implementation shouldn't overfit to that one format. Perhaps the
// copy_n_from_history Wuffs method should also take an unroll hint argument,
// and the cgen can look if that argument is the constant expression '3'.
//
// See also wuffs_base__io_writer__copy_n_from_history_fast below.
//
// Alternatively, or additionally, have a sloppy_copy_n_from_history method
// that copies 8 bytes at a time, possibly writing more than length bytes?
for (; n >= 3; n -= 3) {
*p++ = *q++;
*p++ = *q++;
*p++ = *q++;
}
for (; n; n--) {
*p++ = *q++;
}
*ptr_iop_w = p;
return length;
}
// wuffs_base__io_writer__copy_n_from_history_fast is like the
// wuffs_base__io_writer__copy_n_from_history function above, but has stronger
// pre-conditions. The caller needs to prove that:
// - distance > 0
// - distance <= (*ptr_iop_w - io0_w)
// - length <= (io1_w - *ptr_iop_w)
static inline uint32_t //
wuffs_base__io_writer__copy_n_from_history_fast(uint8_t** ptr_iop_w,
uint8_t* io0_w,
uint8_t* io1_w,
uint32_t length,
uint32_t distance) {
uint8_t* p = *ptr_iop_w;
uint8_t* q = p - distance;
uint32_t n = length;
for (; n >= 3; n -= 3) {
*p++ = *q++;
*p++ = *q++;
*p++ = *q++;
}
for (; n; n--) {
*p++ = *q++;
}
*ptr_iop_w = p;
return length;
}
static inline uint32_t //
wuffs_base__io_writer__copy_n_from_reader(uint8_t** ptr_iop_w,
uint8_t* io1_w,
uint32_t length,
uint8_t** ptr_iop_r,
uint8_t* io1_r) {
uint8_t* iop_w = *ptr_iop_w;
size_t n = length;
if (n > ((size_t)(io1_w - iop_w))) {
n = io1_w - iop_w;
}
uint8_t* iop_r = *ptr_iop_r;
if (n > ((size_t)(io1_r - iop_r))) {
n = io1_r - iop_r;
}
if (n > 0) {
memmove(iop_w, iop_r, n);
*ptr_iop_w += n;
*ptr_iop_r += n;
}
return n;
}
static inline uint64_t //
wuffs_base__io_writer__copy_from_slice(uint8_t** ptr_iop_w,
uint8_t* io1_w,
wuffs_base__slice_u8 src) {
uint8_t* iop_w = *ptr_iop_w;
size_t n = src.len;
if (n > ((size_t)(io1_w - iop_w))) {
n = io1_w - iop_w;
}
if (n > 0) {
memmove(iop_w, src.ptr, n);
*ptr_iop_w += n;
}
return n;
}
static inline uint32_t //
wuffs_base__io_writer__copy_n_from_slice(uint8_t** ptr_iop_w,
uint8_t* io1_w,
uint32_t length,
wuffs_base__slice_u8 src) {
uint8_t* iop_w = *ptr_iop_w;
size_t n = src.len;
if (n > length) {
n = length;
}
if (n > ((size_t)(io1_w - iop_w))) {
n = io1_w - iop_w;
}
if (n > 0) {
memmove(iop_w, src.ptr, n);
*ptr_iop_w += n;
}
return n;
}
static inline wuffs_base__empty_struct //
wuffs_base__io_reader__set(wuffs_base__io_reader* o,
wuffs_base__io_buffer* b,
uint8_t** ptr_iop_r,
uint8_t** ptr_io1_r,
wuffs_base__slice_u8 data) {
b->data = data;
b->meta.wi = data.len;
b->meta.ri = 0;
b->meta.pos = 0;
b->meta.closed = false;
o->private_impl.buf = b;
o->private_impl.mark = data.ptr;
o->private_impl.limit = data.ptr + data.len;
*ptr_iop_r = data.ptr;
*ptr_io1_r = data.ptr + data.len;
wuffs_base__empty_struct ret;
ret.private_impl = 0;
return ret;
}
static inline wuffs_base__empty_struct //
wuffs_base__io_reader__set_limit(wuffs_base__io_reader* o,
uint8_t* iop_r,
uint64_t limit) {
if (o && (((size_t)(o->private_impl.limit - iop_r)) > limit)) {
o->private_impl.limit = iop_r + limit;
}
wuffs_base__empty_struct ret;
ret.private_impl = 0;
return ret;
}
static inline wuffs_base__empty_struct //
wuffs_base__io_reader__set_mark(wuffs_base__io_reader* o, uint8_t* mark) {
o->private_impl.mark = mark;
wuffs_base__empty_struct ret;
ret.private_impl = 0;
return ret;
}
static inline wuffs_base__slice_u8 //
wuffs_base__io_reader__take(uint8_t** ptr_iop_r, uint8_t* io1_r, uint64_t n) {
if (n <= ((size_t)(io1_r - *ptr_iop_r))) {
uint8_t* p = *ptr_iop_r;
*ptr_iop_r += n;
return wuffs_base__make_slice_u8(p, n);
}
return wuffs_base__make_slice_u8(NULL, 0);
}
static inline wuffs_base__empty_struct //
wuffs_base__io_writer__set(wuffs_base__io_writer* o,
wuffs_base__io_buffer* b,
uint8_t** ptr_iop_w,
uint8_t** ptr_io1_w,
wuffs_base__slice_u8 data) {
b->data = data;
b->meta.wi = 0;
b->meta.ri = 0;
b->meta.pos = 0;
b->meta.closed = false;
o->private_impl.buf = b;
o->private_impl.mark = data.ptr;
o->private_impl.limit = data.ptr + data.len;
*ptr_iop_w = data.ptr;
*ptr_io1_w = data.ptr + data.len;
wuffs_base__empty_struct ret;
ret.private_impl = 0;
return ret;
}
static inline wuffs_base__empty_struct //
wuffs_base__io_writer__set_mark(wuffs_base__io_writer* o, uint8_t* mark) {
o->private_impl.mark = mark;
wuffs_base__empty_struct ret;
ret.private_impl = 0;
return ret;
}
// ---------------- I/O (Utility)
static inline wuffs_base__io_buffer //
wuffs_base__utility__null_io_buffer() {
wuffs_base__io_buffer ret;
ret.data.ptr = NULL;
ret.data.len = 0;
ret.meta.wi = 0;
ret.meta.ri = 0;
ret.meta.pos = 0;
ret.meta.closed = false;
return ret;
}
static inline wuffs_base__io_reader //
wuffs_base__utility__null_io_reader() {
wuffs_base__io_reader ret;
ret.private_impl.buf = NULL;
ret.private_impl.mark = NULL;
ret.private_impl.limit = NULL;
return ret;
}
static inline wuffs_base__io_writer //
wuffs_base__utility__null_io_writer() {
wuffs_base__io_writer ret;
ret.private_impl.buf = NULL;
ret.private_impl.mark = NULL;
ret.private_impl.limit = NULL;
return ret;
}
// ---------------- Bureaucracy re -Wunused-function
static inline void
wuffs_base__acknowledge_potentially_unused_functions__io_private()
WUFFS_BASE__POTENTIALLY_UNUSED;
static inline void
wuffs_base__acknowledge_potentially_unused_functions__io_private() {
(void)(wuffs_base__io_buffer__is_valid);
(void)(wuffs_base__io_reader__is_eof);
(void)(wuffs_base__io_reader__is_valid);
(void)(wuffs_base__io_reader__set);
(void)(wuffs_base__io_reader__set_limit);
(void)(wuffs_base__io_reader__set_mark);
(void)(wuffs_base__io_reader__take);
(void)(wuffs_base__io_writer__copy_from_slice);
(void)(wuffs_base__io_writer__copy_n_from_history);
(void)(wuffs_base__io_writer__copy_n_from_history_fast);
(void)(wuffs_base__io_writer__copy_n_from_reader);
(void)(wuffs_base__io_writer__copy_n_from_slice);
(void)(wuffs_base__io_writer__is_valid);
(void)(wuffs_base__io_writer__set);
(void)(wuffs_base__io_writer__set_mark);
(void)(wuffs_base__utility__null_io_buffer);
(void)(wuffs_base__utility__null_io_reader);
(void)(wuffs_base__utility__null_io_writer);
}
-160
View File
@@ -1,160 +0,0 @@
// After editing this file, run "go generate" in the parent directory.
// Copyright 2017 The Wuffs Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ---------------- I/O
struct wuffs_base__io_buffer__struct;
typedef struct {
// Do not access the private_impl's fields directly. There is no API/ABI
// compatibility or safety guarantee if you do so.
struct {
struct wuffs_base__io_buffer__struct* buf;
// The bounds values are typically NULL, when created by the Wuffs public
// API. NULL means that the callee substitutes the implicit bounds derived
// from buf.
uint8_t* mark;
uint8_t* limit;
} private_impl;
} wuffs_base__io_reader;
typedef struct {
// Do not access the private_impl's fields directly. There is no API/ABI
// compatibility or safety guarantee if you do so.
struct {
struct wuffs_base__io_buffer__struct* buf;
// The bounds values are typically NULL, when created by the Wuffs public
// API. NULL means that the callee substitutes the implicit bounds derived
// from buf.
uint8_t* mark;
uint8_t* limit;
} private_impl;
} wuffs_base__io_writer;
// wuffs_base__io_buffer_meta is the metadata for a wuffs_base__io_buffer's
// data.
typedef struct {
size_t wi; // Write index. Invariant: wi <= len.
size_t ri; // Read index. Invariant: ri <= wi.
uint64_t pos; // Position of the buffer start relative to the stream start.
bool closed; // No further writes are expected.
} wuffs_base__io_buffer_meta;
// wuffs_base__io_buffer is a 1-dimensional buffer (a pointer and length) plus
// additional metadata.
//
// A value with all fields zero is a valid, empty buffer.
typedef struct wuffs_base__io_buffer__struct {
wuffs_base__slice_u8 data;
wuffs_base__io_buffer_meta meta;
#ifdef __cplusplus
inline void compact();
inline wuffs_base__io_reader reader();
inline wuffs_base__io_writer writer();
inline uint64_t reader_io_position();
inline uint64_t writer_io_position();
#endif // __cplusplus
} wuffs_base__io_buffer;
// wuffs_base__io_buffer__compact moves any written but unread bytes to the
// start of the buffer.
static inline void //
wuffs_base__io_buffer__compact(wuffs_base__io_buffer* buf) {
if (!buf || (buf->meta.ri == 0)) {
return;
}
buf->meta.pos = wuffs_base__u64__sat_add(buf->meta.pos, buf->meta.ri);
size_t n = buf->meta.wi - buf->meta.ri;
if (n != 0) {
memmove(buf->data.ptr, buf->data.ptr + buf->meta.ri, n);
}
buf->meta.wi = n;
buf->meta.ri = 0;
}
static inline wuffs_base__io_reader //
wuffs_base__io_buffer__reader(wuffs_base__io_buffer* buf) {
wuffs_base__io_reader ret;
ret.private_impl.buf = buf;
ret.private_impl.mark = NULL;
ret.private_impl.limit = NULL;
return ret;
}
static inline wuffs_base__io_writer //
wuffs_base__io_buffer__writer(wuffs_base__io_buffer* buf) {
wuffs_base__io_writer ret;
ret.private_impl.buf = buf;
ret.private_impl.mark = NULL;
ret.private_impl.limit = NULL;
return ret;
}
static inline uint64_t //
wuffs_base__io_buffer__reader_io_position(wuffs_base__io_buffer* buf) {
return buf ? wuffs_base__u64__sat_add(buf->meta.pos, buf->meta.ri) : 0;
}
static inline uint64_t //
wuffs_base__io_buffer__writer_io_position(wuffs_base__io_buffer* buf) {
return buf ? wuffs_base__u64__sat_add(buf->meta.pos, buf->meta.wi) : 0;
}
#ifdef __cplusplus
inline void //
wuffs_base__io_buffer__struct::compact() {
wuffs_base__io_buffer__compact(this);
}
inline wuffs_base__io_reader //
wuffs_base__io_buffer__struct::reader() {
return wuffs_base__io_buffer__reader(this);
}
inline wuffs_base__io_writer //
wuffs_base__io_buffer__struct::writer() {
return wuffs_base__io_buffer__writer(this);
}
inline uint64_t //
wuffs_base__io_buffer__struct::reader_io_position() {
return wuffs_base__io_buffer__reader_io_position(this);
}
inline uint64_t //
wuffs_base__io_buffer__struct::writer_io_position() {
return wuffs_base__io_buffer__writer_io_position(this);
}
#endif // __cplusplus
// ---------------- Bureaucracy re -Wunused-function
static inline void
wuffs_base__acknowledge_potentially_unused_functions__io_public()
WUFFS_BASE__POTENTIALLY_UNUSED;
static inline void
wuffs_base__acknowledge_potentially_unused_functions__io_public() {
(void)(wuffs_base__io_buffer__compact);
(void)(wuffs_base__io_buffer__reader);
(void)(wuffs_base__io_buffer__reader_io_position);
(void)(wuffs_base__io_buffer__writer);
(void)(wuffs_base__io_buffer__writer_io_position);
}
@@ -1,17 +0,0 @@
// After editing this file, run "go generate" in the parent directory.
// Copyright 2017 The Wuffs Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ---------------- Memory Allocation
@@ -1,88 +0,0 @@
// After editing this file, run "go generate" in the parent directory.
// Copyright 2017 The Wuffs Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ---------------- Memory Allocation
// The memory allocation related functions in this section aren't used by Wuffs
// per se, but they may be helpful to the code that uses Wuffs.
// wuffs_base__malloc_slice_uxx wraps calling a malloc-like function, except
// that it takes a uint64_t number of elements instead of a size_t size in
// bytes, and it returns a slice (a pointer and a length) instead of just a
// pointer.
//
// You can pass the C stdlib's malloc as the malloc_func.
//
// It returns an empty slice (containing a NULL ptr field) if (num_uxx *
// sizeof(uintxx_t)) would overflow SIZE_MAX.
static inline wuffs_base__slice_u8 //
wuffs_base__malloc_slice_u8(void* (*malloc_func)(size_t), uint64_t num_u8) {
if (malloc_func && (num_u8 <= (SIZE_MAX / sizeof(uint8_t)))) {
void* p = (*malloc_func)(num_u8 * sizeof(uint8_t));
if (p) {
return wuffs_base__make_slice_u8((uint8_t*)(p), num_u8);
}
}
return wuffs_base__make_slice_u8(NULL, 0);
}
static inline wuffs_base__slice_u16 //
wuffs_base__malloc_slice_u16(void* (*malloc_func)(size_t), uint64_t num_u16) {
if (malloc_func && (num_u16 <= (SIZE_MAX / sizeof(uint16_t)))) {
void* p = (*malloc_func)(num_u16 * sizeof(uint16_t));
if (p) {
return wuffs_base__make_slice_u16((uint16_t*)(p), num_u16);
}
}
return wuffs_base__make_slice_u16(NULL, 0);
}
static inline wuffs_base__slice_u32 //
wuffs_base__malloc_slice_u32(void* (*malloc_func)(size_t), uint64_t num_u32) {
if (malloc_func && (num_u32 <= (SIZE_MAX / sizeof(uint32_t)))) {
void* p = (*malloc_func)(num_u32 * sizeof(uint32_t));
if (p) {
return wuffs_base__make_slice_u32((uint32_t*)(p), num_u32);
}
}
return wuffs_base__make_slice_u32(NULL, 0);
}
static inline wuffs_base__slice_u64 //
wuffs_base__malloc_slice_u64(void* (*malloc_func)(size_t), uint64_t num_u64) {
if (malloc_func && (num_u64 <= (SIZE_MAX / sizeof(uint64_t)))) {
void* p = (*malloc_func)(num_u64 * sizeof(uint64_t));
if (p) {
return wuffs_base__make_slice_u64((uint64_t*)(p), num_u64);
}
}
return wuffs_base__make_slice_u64(NULL, 0);
}
// ---------------- Bureaucracy re -Wunused-function
static inline void
wuffs_base__acknowledge_potentially_unused_functions__memory_public()
WUFFS_BASE__POTENTIALLY_UNUSED;
static inline void
wuffs_base__acknowledge_potentially_unused_functions__memory_public() {
(void)(wuffs_base__malloc_slice_u16);
(void)(wuffs_base__malloc_slice_u32);
(void)(wuffs_base__malloc_slice_u64);
(void)(wuffs_base__malloc_slice_u8);
}
@@ -1,141 +0,0 @@
// After editing this file, run "go generate" in the parent directory.
// Copyright 2017 The Wuffs Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ---------------- Ranges and Rects
static inline uint32_t //
wuffs_base__range_ii_u32__get_min_incl(const wuffs_base__range_ii_u32* r) {
return r->min_incl;
}
static inline uint32_t //
wuffs_base__range_ii_u32__get_max_incl(const wuffs_base__range_ii_u32* r) {
return r->max_incl;
}
static inline uint32_t //
wuffs_base__range_ie_u32__get_min_incl(const wuffs_base__range_ie_u32* r) {
return r->min_incl;
}
static inline uint32_t //
wuffs_base__range_ie_u32__get_max_excl(const wuffs_base__range_ie_u32* r) {
return r->max_excl;
}
static inline uint64_t //
wuffs_base__range_ii_u64__get_min_incl(const wuffs_base__range_ii_u64* r) {
return r->min_incl;
}
static inline uint64_t //
wuffs_base__range_ii_u64__get_max_incl(const wuffs_base__range_ii_u64* r) {
return r->max_incl;
}
static inline uint64_t //
wuffs_base__range_ie_u64__get_min_incl(const wuffs_base__range_ie_u64* r) {
return r->min_incl;
}
static inline uint64_t //
wuffs_base__range_ie_u64__get_max_excl(const wuffs_base__range_ie_u64* r) {
return r->max_excl;
}
// ---------------- Ranges and Rects (Utility)
static inline wuffs_base__range_ii_u32 //
wuffs_base__utility__make_range_ii_u32(uint32_t min_incl, uint32_t max_incl) {
wuffs_base__range_ii_u32 ret;
ret.min_incl = min_incl;
ret.max_incl = max_incl;
return ret;
}
static inline wuffs_base__range_ie_u32 //
wuffs_base__utility__make_range_ie_u32(uint32_t min_incl, uint32_t max_excl) {
wuffs_base__range_ie_u32 ret;
ret.min_incl = min_incl;
ret.max_excl = max_excl;
return ret;
}
static inline wuffs_base__range_ii_u64 //
wuffs_base__utility__make_range_ii_u64(uint64_t min_incl, uint64_t max_incl) {
wuffs_base__range_ii_u64 ret;
ret.min_incl = min_incl;
ret.max_incl = max_incl;
return ret;
}
static inline wuffs_base__range_ie_u64 //
wuffs_base__utility__make_range_ie_u64(uint64_t min_incl, uint64_t max_excl) {
wuffs_base__range_ie_u64 ret;
ret.min_incl = min_incl;
ret.max_excl = max_excl;
return ret;
}
static inline wuffs_base__rect_ii_u32 //
wuffs_base__utility__make_rect_ii_u32(uint32_t min_incl_x,
uint32_t min_incl_y,
uint32_t max_incl_x,
uint32_t max_incl_y) {
wuffs_base__rect_ii_u32 ret;
ret.min_incl_x = min_incl_x;
ret.min_incl_y = min_incl_y;
ret.max_incl_x = max_incl_x;
ret.max_incl_y = max_incl_y;
return ret;
}
static inline wuffs_base__rect_ie_u32 //
wuffs_base__utility__make_rect_ie_u32(uint32_t min_incl_x,
uint32_t min_incl_y,
uint32_t max_excl_x,
uint32_t max_excl_y) {
wuffs_base__rect_ie_u32 ret;
ret.min_incl_x = min_incl_x;
ret.min_incl_y = min_incl_y;
ret.max_excl_x = max_excl_x;
ret.max_excl_y = max_excl_y;
return ret;
}
// ---------------- Bureaucracy re -Wunused-function
static inline void
wuffs_base__acknowledge_potentially_unused_functions__range_private()
WUFFS_BASE__POTENTIALLY_UNUSED;
static inline void
wuffs_base__acknowledge_potentially_unused_functions__range_private() {
(void)(wuffs_base__range_ie_u32__get_max_excl);
(void)(wuffs_base__range_ie_u32__get_min_incl);
(void)(wuffs_base__range_ie_u64__get_max_excl);
(void)(wuffs_base__range_ie_u64__get_min_incl);
(void)(wuffs_base__range_ii_u32__get_max_incl);
(void)(wuffs_base__range_ii_u32__get_min_incl);
(void)(wuffs_base__range_ii_u64__get_max_incl);
(void)(wuffs_base__range_ii_u64__get_min_incl);
(void)(wuffs_base__utility__make_range_ie_u32);
(void)(wuffs_base__utility__make_range_ie_u64);
(void)(wuffs_base__utility__make_range_ii_u32);
(void)(wuffs_base__utility__make_range_ii_u64);
(void)(wuffs_base__utility__make_rect_ie_u32);
(void)(wuffs_base__utility__make_rect_ii_u32);
}
@@ -1,791 +0,0 @@
// After editing this file, run "go generate" in the parent directory.
// Copyright 2017 The Wuffs Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ---------------- Ranges and Rects
// Ranges are either inclusive ("range_ii") or exclusive ("range_ie") on the
// high end. Both the "ii" and "ie" flavors are useful in practice.
//
// The "ei" and "ee" flavors also exist in theory, but aren't widely used. In
// Wuffs, the low end is always inclusive.
//
// The "ii" (closed interval) flavor is useful when refining e.g. "the set of
// all uint32_t values" to a contiguous subset: "uint32_t values in the closed
// interval [M, N]", for uint32_t values M and N. An unrefined type (in other
// words, the set of all uint32_t values) is not representable in the "ie"
// flavor because if N equals ((1<<32) - 1) then (N + 1) will overflow.
//
// On the other hand, the "ie" (half-open interval) flavor is recommended by
// Dijkstra's "Why numbering should start at zero" at
// http://www.cs.utexas.edu/users/EWD/ewd08xx/EWD831.PDF and a further
// discussion of motivating rationale is at
// https://www.quora.com/Why-are-Python-ranges-half-open-exclusive-instead-of-closed-inclusive
//
// For example, with "ie", the number of elements in "uint32_t values in the
// half-open interval [M, N)" is equal to max(0, N-M). Furthermore, that number
// of elements (in one dimension, a length, in two dimensions, a width or
// height) is itself representable as a uint32_t without overflow, again for
// uint32_t values M and N. In the contrasting "ii" flavor, the length of the
// closed interval [0, (1<<32) - 1] is 1<<32, which cannot be represented as a
// uint32_t. In Wuffs, because of this potential overflow, the "ie" flavor has
// length / width / height methods, but the "ii" flavor does not.
//
// It is valid for min > max (for range_ii) or for min >= max (for range_ie),
// in which case the range is empty. There are multiple representations of an
// empty range.
typedef struct wuffs_base__range_ii_u32__struct {
uint32_t min_incl;
uint32_t max_incl;
#ifdef __cplusplus
inline bool is_empty();
inline bool equals(wuffs_base__range_ii_u32__struct s);
inline wuffs_base__range_ii_u32__struct intersect(
wuffs_base__range_ii_u32__struct s);
inline wuffs_base__range_ii_u32__struct unite(
wuffs_base__range_ii_u32__struct s);
inline bool contains(uint32_t x);
inline bool contains_range(wuffs_base__range_ii_u32__struct s);
#endif // __cplusplus
} wuffs_base__range_ii_u32;
static inline bool //
wuffs_base__range_ii_u32__is_empty(wuffs_base__range_ii_u32* r) {
return r->min_incl > r->max_incl;
}
static inline bool //
wuffs_base__range_ii_u32__equals(wuffs_base__range_ii_u32* r,
wuffs_base__range_ii_u32 s) {
return (r->min_incl == s.min_incl && r->max_incl == s.max_incl) ||
(wuffs_base__range_ii_u32__is_empty(r) &&
wuffs_base__range_ii_u32__is_empty(&s));
}
static inline wuffs_base__range_ii_u32 //
wuffs_base__range_ii_u32__intersect(wuffs_base__range_ii_u32* r,
wuffs_base__range_ii_u32 s) {
wuffs_base__range_ii_u32 t;
t.min_incl = wuffs_base__u32__max(r->min_incl, s.min_incl);
t.max_incl = wuffs_base__u32__min(r->max_incl, s.max_incl);
return t;
}
static inline wuffs_base__range_ii_u32 //
wuffs_base__range_ii_u32__unite(wuffs_base__range_ii_u32* r,
wuffs_base__range_ii_u32 s) {
if (wuffs_base__range_ii_u32__is_empty(r)) {
return s;
}
if (wuffs_base__range_ii_u32__is_empty(&s)) {
return *r;
}
wuffs_base__range_ii_u32 t;
t.min_incl = wuffs_base__u32__min(r->min_incl, s.min_incl);
t.max_incl = wuffs_base__u32__max(r->max_incl, s.max_incl);
return t;
}
static inline bool //
wuffs_base__range_ii_u32__contains(wuffs_base__range_ii_u32* r, uint32_t x) {
return (r->min_incl <= x) && (x <= r->max_incl);
}
static inline bool //
wuffs_base__range_ii_u32__contains_range(wuffs_base__range_ii_u32* r,
wuffs_base__range_ii_u32 s) {
return wuffs_base__range_ii_u32__equals(
&s, wuffs_base__range_ii_u32__intersect(r, s));
}
#ifdef __cplusplus
inline bool //
wuffs_base__range_ii_u32::is_empty() {
return wuffs_base__range_ii_u32__is_empty(this);
}
inline bool //
wuffs_base__range_ii_u32::equals(wuffs_base__range_ii_u32 s) {
return wuffs_base__range_ii_u32__equals(this, s);
}
inline wuffs_base__range_ii_u32 //
wuffs_base__range_ii_u32::intersect(wuffs_base__range_ii_u32 s) {
return wuffs_base__range_ii_u32__intersect(this, s);
}
inline wuffs_base__range_ii_u32 //
wuffs_base__range_ii_u32::unite(wuffs_base__range_ii_u32 s) {
return wuffs_base__range_ii_u32__unite(this, s);
}
inline bool //
wuffs_base__range_ii_u32::contains(uint32_t x) {
return wuffs_base__range_ii_u32__contains(this, x);
}
inline bool //
wuffs_base__range_ii_u32::contains_range(wuffs_base__range_ii_u32 s) {
return wuffs_base__range_ii_u32__contains_range(this, s);
}
#endif // __cplusplus
// --------
typedef struct wuffs_base__range_ie_u32__struct {
uint32_t min_incl;
uint32_t max_excl;
#ifdef __cplusplus
inline bool is_empty();
inline bool equals(wuffs_base__range_ie_u32__struct s);
inline wuffs_base__range_ie_u32__struct intersect(
wuffs_base__range_ie_u32__struct s);
inline wuffs_base__range_ie_u32__struct unite(
wuffs_base__range_ie_u32__struct s);
inline bool contains(uint32_t x);
inline bool contains_range(wuffs_base__range_ie_u32__struct s);
inline uint32_t length();
#endif // __cplusplus
} wuffs_base__range_ie_u32;
static inline bool //
wuffs_base__range_ie_u32__is_empty(wuffs_base__range_ie_u32* r) {
return r->min_incl >= r->max_excl;
}
static inline bool //
wuffs_base__range_ie_u32__equals(wuffs_base__range_ie_u32* r,
wuffs_base__range_ie_u32 s) {
return (r->min_incl == s.min_incl && r->max_excl == s.max_excl) ||
(wuffs_base__range_ie_u32__is_empty(r) &&
wuffs_base__range_ie_u32__is_empty(&s));
}
static inline wuffs_base__range_ie_u32 //
wuffs_base__range_ie_u32__intersect(wuffs_base__range_ie_u32* r,
wuffs_base__range_ie_u32 s) {
wuffs_base__range_ie_u32 t;
t.min_incl = wuffs_base__u32__max(r->min_incl, s.min_incl);
t.max_excl = wuffs_base__u32__min(r->max_excl, s.max_excl);
return t;
}
static inline wuffs_base__range_ie_u32 //
wuffs_base__range_ie_u32__unite(wuffs_base__range_ie_u32* r,
wuffs_base__range_ie_u32 s) {
if (wuffs_base__range_ie_u32__is_empty(r)) {
return s;
}
if (wuffs_base__range_ie_u32__is_empty(&s)) {
return *r;
}
wuffs_base__range_ie_u32 t;
t.min_incl = wuffs_base__u32__min(r->min_incl, s.min_incl);
t.max_excl = wuffs_base__u32__max(r->max_excl, s.max_excl);
return t;
}
static inline bool //
wuffs_base__range_ie_u32__contains(wuffs_base__range_ie_u32* r, uint32_t x) {
return (r->min_incl <= x) && (x < r->max_excl);
}
static inline bool //
wuffs_base__range_ie_u32__contains_range(wuffs_base__range_ie_u32* r,
wuffs_base__range_ie_u32 s) {
return wuffs_base__range_ie_u32__equals(
&s, wuffs_base__range_ie_u32__intersect(r, s));
}
static inline uint32_t //
wuffs_base__range_ie_u32__length(wuffs_base__range_ie_u32* r) {
return wuffs_base__u32__sat_sub(r->max_excl, r->min_incl);
}
#ifdef __cplusplus
inline bool //
wuffs_base__range_ie_u32::is_empty() {
return wuffs_base__range_ie_u32__is_empty(this);
}
inline bool //
wuffs_base__range_ie_u32::equals(wuffs_base__range_ie_u32 s) {
return wuffs_base__range_ie_u32__equals(this, s);
}
inline wuffs_base__range_ie_u32 //
wuffs_base__range_ie_u32::intersect(wuffs_base__range_ie_u32 s) {
return wuffs_base__range_ie_u32__intersect(this, s);
}
inline wuffs_base__range_ie_u32 //
wuffs_base__range_ie_u32::unite(wuffs_base__range_ie_u32 s) {
return wuffs_base__range_ie_u32__unite(this, s);
}
inline bool //
wuffs_base__range_ie_u32::contains(uint32_t x) {
return wuffs_base__range_ie_u32__contains(this, x);
}
inline bool //
wuffs_base__range_ie_u32::contains_range(wuffs_base__range_ie_u32 s) {
return wuffs_base__range_ie_u32__contains_range(this, s);
}
inline uint32_t //
wuffs_base__range_ie_u32::length() {
return wuffs_base__range_ie_u32__length(this);
}
#endif // __cplusplus
// --------
typedef struct wuffs_base__range_ii_u64__struct {
uint64_t min_incl;
uint64_t max_incl;
#ifdef __cplusplus
inline bool is_empty();
inline bool equals(wuffs_base__range_ii_u64__struct s);
inline wuffs_base__range_ii_u64__struct intersect(
wuffs_base__range_ii_u64__struct s);
inline wuffs_base__range_ii_u64__struct unite(
wuffs_base__range_ii_u64__struct s);
inline bool contains(uint64_t x);
inline bool contains_range(wuffs_base__range_ii_u64__struct s);
#endif // __cplusplus
} wuffs_base__range_ii_u64;
static inline bool //
wuffs_base__range_ii_u64__is_empty(wuffs_base__range_ii_u64* r) {
return r->min_incl > r->max_incl;
}
static inline bool //
wuffs_base__range_ii_u64__equals(wuffs_base__range_ii_u64* r,
wuffs_base__range_ii_u64 s) {
return (r->min_incl == s.min_incl && r->max_incl == s.max_incl) ||
(wuffs_base__range_ii_u64__is_empty(r) &&
wuffs_base__range_ii_u64__is_empty(&s));
}
static inline wuffs_base__range_ii_u64 //
wuffs_base__range_ii_u64__intersect(wuffs_base__range_ii_u64* r,
wuffs_base__range_ii_u64 s) {
wuffs_base__range_ii_u64 t;
t.min_incl = wuffs_base__u64__max(r->min_incl, s.min_incl);
t.max_incl = wuffs_base__u64__min(r->max_incl, s.max_incl);
return t;
}
static inline wuffs_base__range_ii_u64 //
wuffs_base__range_ii_u64__unite(wuffs_base__range_ii_u64* r,
wuffs_base__range_ii_u64 s) {
if (wuffs_base__range_ii_u64__is_empty(r)) {
return s;
}
if (wuffs_base__range_ii_u64__is_empty(&s)) {
return *r;
}
wuffs_base__range_ii_u64 t;
t.min_incl = wuffs_base__u64__min(r->min_incl, s.min_incl);
t.max_incl = wuffs_base__u64__max(r->max_incl, s.max_incl);
return t;
}
static inline bool //
wuffs_base__range_ii_u64__contains(wuffs_base__range_ii_u64* r, uint64_t x) {
return (r->min_incl <= x) && (x <= r->max_incl);
}
static inline bool //
wuffs_base__range_ii_u64__contains_range(wuffs_base__range_ii_u64* r,
wuffs_base__range_ii_u64 s) {
return wuffs_base__range_ii_u64__equals(
&s, wuffs_base__range_ii_u64__intersect(r, s));
}
#ifdef __cplusplus
inline bool //
wuffs_base__range_ii_u64::is_empty() {
return wuffs_base__range_ii_u64__is_empty(this);
}
inline bool //
wuffs_base__range_ii_u64::equals(wuffs_base__range_ii_u64 s) {
return wuffs_base__range_ii_u64__equals(this, s);
}
inline wuffs_base__range_ii_u64 //
wuffs_base__range_ii_u64::intersect(wuffs_base__range_ii_u64 s) {
return wuffs_base__range_ii_u64__intersect(this, s);
}
inline wuffs_base__range_ii_u64 //
wuffs_base__range_ii_u64::unite(wuffs_base__range_ii_u64 s) {
return wuffs_base__range_ii_u64__unite(this, s);
}
inline bool //
wuffs_base__range_ii_u64::contains(uint64_t x) {
return wuffs_base__range_ii_u64__contains(this, x);
}
inline bool //
wuffs_base__range_ii_u64::contains_range(wuffs_base__range_ii_u64 s) {
return wuffs_base__range_ii_u64__contains_range(this, s);
}
#endif // __cplusplus
// --------
typedef struct wuffs_base__range_ie_u64__struct {
uint64_t min_incl;
uint64_t max_excl;
#ifdef __cplusplus
inline bool is_empty();
inline bool equals(wuffs_base__range_ie_u64__struct s);
inline wuffs_base__range_ie_u64__struct intersect(
wuffs_base__range_ie_u64__struct s);
inline wuffs_base__range_ie_u64__struct unite(
wuffs_base__range_ie_u64__struct s);
inline bool contains(uint64_t x);
inline bool contains_range(wuffs_base__range_ie_u64__struct s);
inline uint64_t length();
#endif // __cplusplus
} wuffs_base__range_ie_u64;
static inline bool //
wuffs_base__range_ie_u64__is_empty(wuffs_base__range_ie_u64* r) {
return r->min_incl >= r->max_excl;
}
static inline bool //
wuffs_base__range_ie_u64__equals(wuffs_base__range_ie_u64* r,
wuffs_base__range_ie_u64 s) {
return (r->min_incl == s.min_incl && r->max_excl == s.max_excl) ||
(wuffs_base__range_ie_u64__is_empty(r) &&
wuffs_base__range_ie_u64__is_empty(&s));
}
static inline wuffs_base__range_ie_u64 //
wuffs_base__range_ie_u64__intersect(wuffs_base__range_ie_u64* r,
wuffs_base__range_ie_u64 s) {
wuffs_base__range_ie_u64 t;
t.min_incl = wuffs_base__u64__max(r->min_incl, s.min_incl);
t.max_excl = wuffs_base__u64__min(r->max_excl, s.max_excl);
return t;
}
static inline wuffs_base__range_ie_u64 //
wuffs_base__range_ie_u64__unite(wuffs_base__range_ie_u64* r,
wuffs_base__range_ie_u64 s) {
if (wuffs_base__range_ie_u64__is_empty(r)) {
return s;
}
if (wuffs_base__range_ie_u64__is_empty(&s)) {
return *r;
}
wuffs_base__range_ie_u64 t;
t.min_incl = wuffs_base__u64__min(r->min_incl, s.min_incl);
t.max_excl = wuffs_base__u64__max(r->max_excl, s.max_excl);
return t;
}
static inline bool //
wuffs_base__range_ie_u64__contains(wuffs_base__range_ie_u64* r, uint64_t x) {
return (r->min_incl <= x) && (x < r->max_excl);
}
static inline bool //
wuffs_base__range_ie_u64__contains_range(wuffs_base__range_ie_u64* r,
wuffs_base__range_ie_u64 s) {
return wuffs_base__range_ie_u64__equals(
&s, wuffs_base__range_ie_u64__intersect(r, s));
}
static inline uint64_t //
wuffs_base__range_ie_u64__length(wuffs_base__range_ie_u64* r) {
return wuffs_base__u64__sat_sub(r->max_excl, r->min_incl);
}
#ifdef __cplusplus
inline bool //
wuffs_base__range_ie_u64::is_empty() {
return wuffs_base__range_ie_u64__is_empty(this);
}
inline bool //
wuffs_base__range_ie_u64::equals(wuffs_base__range_ie_u64 s) {
return wuffs_base__range_ie_u64__equals(this, s);
}
inline wuffs_base__range_ie_u64 //
wuffs_base__range_ie_u64::intersect(wuffs_base__range_ie_u64 s) {
return wuffs_base__range_ie_u64__intersect(this, s);
}
inline wuffs_base__range_ie_u64 //
wuffs_base__range_ie_u64::unite(wuffs_base__range_ie_u64 s) {
return wuffs_base__range_ie_u64__unite(this, s);
}
inline bool //
wuffs_base__range_ie_u64::contains(uint64_t x) {
return wuffs_base__range_ie_u64__contains(this, x);
}
inline bool //
wuffs_base__range_ie_u64::contains_range(wuffs_base__range_ie_u64 s) {
return wuffs_base__range_ie_u64__contains_range(this, s);
}
inline uint64_t //
wuffs_base__range_ie_u64::length() {
return wuffs_base__range_ie_u64__length(this);
}
#endif // __cplusplus
// --------
// wuffs_base__rect_ii_u32 is a rectangle (a 2-dimensional range) on the
// integer grid. The "ii" means that the bounds are inclusive on the low end
// and inclusive on the high end. It contains all points (x, y) such that
// ((min_incl_x <= x) && (x <= max_incl_x)) and likewise for y.
//
// It is valid for min > max, in which case the rectangle is empty. There are
// multiple representations of an empty rectangle.
//
// The X and Y axes increase right and down.
typedef struct wuffs_base__rect_ii_u32__struct {
uint32_t min_incl_x;
uint32_t min_incl_y;
uint32_t max_incl_x;
uint32_t max_incl_y;
#ifdef __cplusplus
inline bool is_empty();
inline bool equals(wuffs_base__rect_ii_u32__struct s);
inline wuffs_base__rect_ii_u32__struct intersect(
wuffs_base__rect_ii_u32__struct s);
inline wuffs_base__rect_ii_u32__struct unite(
wuffs_base__rect_ii_u32__struct s);
inline bool contains(uint32_t x, uint32_t y);
inline bool contains_rect(wuffs_base__rect_ii_u32__struct s);
#endif // __cplusplus
} wuffs_base__rect_ii_u32;
static inline bool //
wuffs_base__rect_ii_u32__is_empty(wuffs_base__rect_ii_u32* r) {
return (r->min_incl_x > r->max_incl_x) || (r->min_incl_y > r->max_incl_y);
}
static inline bool //
wuffs_base__rect_ii_u32__equals(wuffs_base__rect_ii_u32* r,
wuffs_base__rect_ii_u32 s) {
return (r->min_incl_x == s.min_incl_x && r->min_incl_y == s.min_incl_y &&
r->max_incl_x == s.max_incl_x && r->max_incl_y == s.max_incl_y) ||
(wuffs_base__rect_ii_u32__is_empty(r) &&
wuffs_base__rect_ii_u32__is_empty(&s));
}
static inline wuffs_base__rect_ii_u32 //
wuffs_base__rect_ii_u32__intersect(wuffs_base__rect_ii_u32* r,
wuffs_base__rect_ii_u32 s) {
wuffs_base__rect_ii_u32 t;
t.min_incl_x = wuffs_base__u32__max(r->min_incl_x, s.min_incl_x);
t.min_incl_y = wuffs_base__u32__max(r->min_incl_y, s.min_incl_y);
t.max_incl_x = wuffs_base__u32__min(r->max_incl_x, s.max_incl_x);
t.max_incl_y = wuffs_base__u32__min(r->max_incl_y, s.max_incl_y);
return t;
}
static inline wuffs_base__rect_ii_u32 //
wuffs_base__rect_ii_u32__unite(wuffs_base__rect_ii_u32* r,
wuffs_base__rect_ii_u32 s) {
if (wuffs_base__rect_ii_u32__is_empty(r)) {
return s;
}
if (wuffs_base__rect_ii_u32__is_empty(&s)) {
return *r;
}
wuffs_base__rect_ii_u32 t;
t.min_incl_x = wuffs_base__u32__min(r->min_incl_x, s.min_incl_x);
t.min_incl_y = wuffs_base__u32__min(r->min_incl_y, s.min_incl_y);
t.max_incl_x = wuffs_base__u32__max(r->max_incl_x, s.max_incl_x);
t.max_incl_y = wuffs_base__u32__max(r->max_incl_y, s.max_incl_y);
return t;
}
static inline bool //
wuffs_base__rect_ii_u32__contains(wuffs_base__rect_ii_u32* r,
uint32_t x,
uint32_t y) {
return (r->min_incl_x <= x) && (x <= r->max_incl_x) && (r->min_incl_y <= y) &&
(y <= r->max_incl_y);
}
static inline bool //
wuffs_base__rect_ii_u32__contains_rect(wuffs_base__rect_ii_u32* r,
wuffs_base__rect_ii_u32 s) {
return wuffs_base__rect_ii_u32__equals(
&s, wuffs_base__rect_ii_u32__intersect(r, s));
}
#ifdef __cplusplus
inline bool //
wuffs_base__rect_ii_u32::is_empty() {
return wuffs_base__rect_ii_u32__is_empty(this);
}
inline bool //
wuffs_base__rect_ii_u32::equals(wuffs_base__rect_ii_u32 s) {
return wuffs_base__rect_ii_u32__equals(this, s);
}
inline wuffs_base__rect_ii_u32 //
wuffs_base__rect_ii_u32::intersect(wuffs_base__rect_ii_u32 s) {
return wuffs_base__rect_ii_u32__intersect(this, s);
}
inline wuffs_base__rect_ii_u32 //
wuffs_base__rect_ii_u32::unite(wuffs_base__rect_ii_u32 s) {
return wuffs_base__rect_ii_u32__unite(this, s);
}
inline bool //
wuffs_base__rect_ii_u32::contains(uint32_t x, uint32_t y) {
return wuffs_base__rect_ii_u32__contains(this, x, y);
}
inline bool //
wuffs_base__rect_ii_u32::contains_rect(wuffs_base__rect_ii_u32 s) {
return wuffs_base__rect_ii_u32__contains_rect(this, s);
}
#endif // __cplusplus
// --------
// wuffs_base__rect_ie_u32 is a rectangle (a 2-dimensional range) on the
// integer grid. The "ie" means that the bounds are inclusive on the low end
// and exclusive on the high end. It contains all points (x, y) such that
// ((min_incl_x <= x) && (x < max_excl_x)) and likewise for y.
//
// It is valid for min >= max, in which case the rectangle is empty. There are
// multiple representations of an empty rectangle, including a value with all
// fields zero.
//
// The X and Y axes increase right and down.
typedef struct wuffs_base__rect_ie_u32__struct {
uint32_t min_incl_x;
uint32_t min_incl_y;
uint32_t max_excl_x;
uint32_t max_excl_y;
#ifdef __cplusplus
inline bool is_empty();
inline bool equals(wuffs_base__rect_ie_u32__struct s);
inline wuffs_base__rect_ie_u32__struct intersect(
wuffs_base__rect_ie_u32__struct s);
inline wuffs_base__rect_ie_u32__struct unite(
wuffs_base__rect_ie_u32__struct s);
inline bool contains(uint32_t x, uint32_t y);
inline bool contains_rect(wuffs_base__rect_ie_u32__struct s);
inline uint32_t width();
inline uint32_t height();
#endif // __cplusplus
} wuffs_base__rect_ie_u32;
static inline bool //
wuffs_base__rect_ie_u32__is_empty(wuffs_base__rect_ie_u32* r) {
return (r->min_incl_x >= r->max_excl_x) || (r->min_incl_y >= r->max_excl_y);
}
static inline bool //
wuffs_base__rect_ie_u32__equals(wuffs_base__rect_ie_u32* r,
wuffs_base__rect_ie_u32 s) {
return (r->min_incl_x == s.min_incl_x && r->min_incl_y == s.min_incl_y &&
r->max_excl_x == s.max_excl_x && r->max_excl_y == s.max_excl_y) ||
(wuffs_base__rect_ie_u32__is_empty(r) &&
wuffs_base__rect_ie_u32__is_empty(&s));
}
static inline wuffs_base__rect_ie_u32 //
wuffs_base__rect_ie_u32__intersect(wuffs_base__rect_ie_u32* r,
wuffs_base__rect_ie_u32 s) {
wuffs_base__rect_ie_u32 t;
t.min_incl_x = wuffs_base__u32__max(r->min_incl_x, s.min_incl_x);
t.min_incl_y = wuffs_base__u32__max(r->min_incl_y, s.min_incl_y);
t.max_excl_x = wuffs_base__u32__min(r->max_excl_x, s.max_excl_x);
t.max_excl_y = wuffs_base__u32__min(r->max_excl_y, s.max_excl_y);
return t;
}
static inline wuffs_base__rect_ie_u32 //
wuffs_base__rect_ie_u32__unite(wuffs_base__rect_ie_u32* r,
wuffs_base__rect_ie_u32 s) {
if (wuffs_base__rect_ie_u32__is_empty(r)) {
return s;
}
if (wuffs_base__rect_ie_u32__is_empty(&s)) {
return *r;
}
wuffs_base__rect_ie_u32 t;
t.min_incl_x = wuffs_base__u32__min(r->min_incl_x, s.min_incl_x);
t.min_incl_y = wuffs_base__u32__min(r->min_incl_y, s.min_incl_y);
t.max_excl_x = wuffs_base__u32__max(r->max_excl_x, s.max_excl_x);
t.max_excl_y = wuffs_base__u32__max(r->max_excl_y, s.max_excl_y);
return t;
}
static inline bool //
wuffs_base__rect_ie_u32__contains(wuffs_base__rect_ie_u32* r,
uint32_t x,
uint32_t y) {
return (r->min_incl_x <= x) && (x < r->max_excl_x) && (r->min_incl_y <= y) &&
(y < r->max_excl_y);
}
static inline bool //
wuffs_base__rect_ie_u32__contains_rect(wuffs_base__rect_ie_u32* r,
wuffs_base__rect_ie_u32 s) {
return wuffs_base__rect_ie_u32__equals(
&s, wuffs_base__rect_ie_u32__intersect(r, s));
}
static inline uint32_t //
wuffs_base__rect_ie_u32__width(wuffs_base__rect_ie_u32* r) {
return wuffs_base__u32__sat_sub(r->max_excl_x, r->min_incl_x);
}
static inline uint32_t //
wuffs_base__rect_ie_u32__height(wuffs_base__rect_ie_u32* r) {
return wuffs_base__u32__sat_sub(r->max_excl_y, r->min_incl_y);
}
#ifdef __cplusplus
inline bool //
wuffs_base__rect_ie_u32::is_empty() {
return wuffs_base__rect_ie_u32__is_empty(this);
}
inline bool //
wuffs_base__rect_ie_u32::equals(wuffs_base__rect_ie_u32 s) {
return wuffs_base__rect_ie_u32__equals(this, s);
}
inline wuffs_base__rect_ie_u32 //
wuffs_base__rect_ie_u32::intersect(wuffs_base__rect_ie_u32 s) {
return wuffs_base__rect_ie_u32__intersect(this, s);
}
inline wuffs_base__rect_ie_u32 //
wuffs_base__rect_ie_u32::unite(wuffs_base__rect_ie_u32 s) {
return wuffs_base__rect_ie_u32__unite(this, s);
}
inline bool //
wuffs_base__rect_ie_u32::contains(uint32_t x, uint32_t y) {
return wuffs_base__rect_ie_u32__contains(this, x, y);
}
inline bool //
wuffs_base__rect_ie_u32::contains_rect(wuffs_base__rect_ie_u32 s) {
return wuffs_base__rect_ie_u32__contains_rect(this, s);
}
inline uint32_t //
wuffs_base__rect_ie_u32::width() {
return wuffs_base__rect_ie_u32__width(this);
}
inline uint32_t //
wuffs_base__rect_ie_u32::height() {
return wuffs_base__rect_ie_u32__height(this);
}
#endif // __cplusplus
// ---------------- Bureaucracy re -Wunused-function
static inline void
wuffs_base__acknowledge_potentially_unused_functions__range_public()
WUFFS_BASE__POTENTIALLY_UNUSED;
static inline void
wuffs_base__acknowledge_potentially_unused_functions__range_public() {
(void)(wuffs_base__range_ie_u32__contains);
(void)(wuffs_base__range_ie_u32__contains_range);
(void)(wuffs_base__range_ie_u32__equals);
(void)(wuffs_base__range_ie_u32__intersect);
(void)(wuffs_base__range_ie_u32__is_empty);
(void)(wuffs_base__range_ie_u32__length);
(void)(wuffs_base__range_ie_u32__unite);
(void)(wuffs_base__range_ie_u64__contains);
(void)(wuffs_base__range_ie_u64__contains_range);
(void)(wuffs_base__range_ie_u64__equals);
(void)(wuffs_base__range_ie_u64__intersect);
(void)(wuffs_base__range_ie_u64__is_empty);
(void)(wuffs_base__range_ie_u64__length);
(void)(wuffs_base__range_ie_u64__unite);
(void)(wuffs_base__range_ii_u32__contains);
(void)(wuffs_base__range_ii_u32__contains_range);
(void)(wuffs_base__range_ii_u32__equals);
(void)(wuffs_base__range_ii_u32__intersect);
(void)(wuffs_base__range_ii_u32__is_empty);
(void)(wuffs_base__range_ii_u32__unite);
(void)(wuffs_base__range_ii_u64__contains);
(void)(wuffs_base__range_ii_u64__contains_range);
(void)(wuffs_base__range_ii_u64__equals);
(void)(wuffs_base__range_ii_u64__intersect);
(void)(wuffs_base__range_ii_u64__is_empty);
(void)(wuffs_base__range_ii_u64__unite);
(void)(wuffs_base__rect_ie_u32__contains);
(void)(wuffs_base__rect_ie_u32__contains_rect);
(void)(wuffs_base__rect_ie_u32__equals);
(void)(wuffs_base__rect_ie_u32__height);
(void)(wuffs_base__rect_ie_u32__intersect);
(void)(wuffs_base__rect_ie_u32__is_empty);
(void)(wuffs_base__rect_ie_u32__unite);
(void)(wuffs_base__rect_ie_u32__width);
(void)(wuffs_base__rect_ii_u32__contains);
(void)(wuffs_base__rect_ie_u32__contains_rect);
(void)(wuffs_base__rect_ii_u32__equals);
(void)(wuffs_base__rect_ii_u32__intersect);
(void)(wuffs_base__rect_ii_u32__is_empty);
(void)(wuffs_base__rect_ii_u32__unite);
}
-824
View File
@@ -1,824 +0,0 @@
// Copyright 2017 The Wuffs Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cgen
import (
"errors"
"fmt"
"math/big"
"strings"
a "github.com/google/wuffs/lang/ast"
t "github.com/google/wuffs/lang/token"
)
var (
errNoSuchBuiltin = errors.New("cgen: internal error: no such built-in")
errOptimizationNotApplicable = errors.New("cgen: internal error: optimization not applicable")
)
func (g *gen) writeBuiltinCall(b *buffer, n *a.Expr, depth uint32) error {
if n.Operator() != t.IDOpenParen {
return errNoSuchBuiltin
}
method := n.LHS().AsExpr()
recv := method.LHS().AsExpr()
recvTyp := recv.MType()
switch recvTyp.Decorator() {
case 0:
// No-op.
case t.IDNptr, t.IDPtr:
// TODO: don't hard-code set.
if method.Ident() != t.IDSet {
return errNoSuchBuiltin
}
// TODO: don't hard-code a_dst.
b.printf("wuffs_base__image_config__set(a_dst")
for _, o := range n.Args() {
b.writeb(',')
if err := g.writeExpr(b, o.AsArg().Value(), depth); err != nil {
return err
}
}
b.printf(")")
return nil
case t.IDSlice:
return g.writeBuiltinSlice(b, recv, method.Ident(), n.Args(), depth)
case t.IDTable:
return g.writeBuiltinTable(b, recv, method.Ident(), n.Args(), depth)
default:
return errNoSuchBuiltin
}
qid := recvTyp.QID()
if qid[0] != t.IDBase {
return errNoSuchBuiltin
}
if qid[1].IsNumType() {
return g.writeBuiltinNumType(b, recv, method.Ident(), n.Args(), depth)
} else {
switch qid[1] {
case t.IDIOReader:
return g.writeBuiltinIOReader(b, recv, method.Ident(), n.Args(), depth)
case t.IDIOWriter:
return g.writeBuiltinIOWriter(b, recv, method.Ident(), n.Args(), depth)
}
}
return errNoSuchBuiltin
}
func (g *gen) writeBuiltinIO(b *buffer, recv *a.Expr, method t.ID, args []*a.Node, depth uint32) error {
switch method {
case t.IDAvailable:
p0, p1 := "", ""
// TODO: don't hard-code these.
switch recv.Str(g.tm) {
case "args.dst":
p0 = "io1_a_dst"
p1 = "iop_a_dst"
case "args.src":
p0 = "io1_a_src"
p1 = "iop_a_src"
case "w":
p0 = "io1_v_w"
p1 = "iop_v_w"
}
if p0 == "" {
return fmt.Errorf(`TODO: cgen a "foo.available" expression`)
}
b.printf("((uint64_t)(%s - %s))", p0, p1)
return nil
case t.IDSet:
typ, v := "reader", "r"
if len(args) == 1 {
typ, v = "writer", "w"
}
b.printf("wuffs_base__io_%s__set(&v_%s, &u_%s, &iop_v_%s, &io1_v_%s,", typ, v, v, v, v)
return g.writeArgs(b, args, depth)
}
return errNoSuchBuiltin
}
func (g *gen) writeBuiltinIOReader(b *buffer, recv *a.Expr, method t.ID, args []*a.Node, depth uint32) error {
// TODO: don't hard-code the recv being a_src.
switch method {
case t.IDUndoByte:
b.writes("(iop_a_src--, wuffs_base__make_empty_struct())")
return nil
case t.IDCanUndoByte:
b.writes("(iop_a_src > io0_a_src)")
return nil
case t.IDPosition:
b.printf("(a_src.private_impl.buf ? wuffs_base__u64__sat_add(" +
"a_src.private_impl.buf->meta.pos, iop_a_src - a_src.private_impl.buf->data.ptr) : 0)")
return nil
case t.IDSetLimit:
b.printf("wuffs_base__io_reader__set_limit(&%ssrc, iop_a_src,", aPrefix)
// TODO: update the iop variables?
return g.writeArgs(b, args, depth)
case t.IDSetMark:
b.printf("wuffs_base__io_reader__set_mark(&%ssrc, iop_a_src)", aPrefix)
return nil
case t.IDSinceMark, t.IDSinceMarkLength:
prefix, name := aPrefix, "src"
if recv.Operator() == 0 {
prefix, name = vPrefix, recv.Ident().Str(g.tm)
}
if method == t.IDSinceMark {
b.printf("wuffs_base__make_slice_u8(%s%s.private_impl.mark, (size_t)(", prefix, name)
}
b.printf("iop_%s%s - %s%s.private_impl.mark", prefix, name, prefix, name)
if method == t.IDSinceMark {
b.writes("))")
}
return nil
case t.IDSkipFast:
// Generate a two part expression using the comma operator: "(pointer
// increment, return_empty_struct call)". The final part is a function
// call (to a static inline function) instead of a struct literal, to
// avoid a "expression result unused" compiler error.
b.writes("(iop_a_src += ")
if err := g.writeExpr(b, args[0].AsArg().Value(), depth); err != nil {
return err
}
b.writes(", wuffs_base__make_empty_struct())")
return nil
case t.IDTake:
b.printf("wuffs_base__io_reader__take(&iop_a_src, io1_a_src,")
return g.writeArgs(b, args, depth)
}
if method >= peekMethodsBase {
if m := method - peekMethodsBase; m < t.ID(len(peekMethods)) {
if p := peekMethods[m]; p.n != 0 {
if p.size != p.n {
b.printf("((uint%d_t)(", p.size)
}
b.printf("wuffs_base__load_u%d%ce(iop_a_src)", p.n, p.endianness)
if p.size != p.n {
b.writes("))")
}
return nil
}
}
}
return g.writeBuiltinIO(b, recv, method, args, depth)
}
func (g *gen) writeBuiltinIOWriter(b *buffer, recv *a.Expr, method t.ID, args []*a.Node, depth uint32) error {
// TODO: don't hard-code the recv being a_dst or w.
switch method {
case t.IDCopyNFromHistory, t.IDCopyNFromHistoryFast:
suffix := ""
if method == t.IDCopyNFromHistoryFast {
suffix = "_fast"
}
b.printf("wuffs_base__io_writer__copy_n_from_history%s("+
"&iop_a_dst, %sdst.private_impl.mark, io1_a_dst",
suffix, aPrefix)
for _, o := range args {
b.writeb(',')
if err := g.writeExpr(b, o.AsArg().Value(), depth); err != nil {
return err
}
}
b.writeb(')')
return nil
case t.IDCopyNFromReader:
b.printf("wuffs_base__io_writer__copy_n_from_reader(&iop_a_dst, io1_a_dst,")
if err := g.writeExpr(b, args[0].AsArg().Value(), depth); err != nil {
return err
}
// TODO: don't assume that the last argument is "args.src".
b.printf(", &iop_a_src, io1_a_src)")
return nil
case t.IDCopyFromSlice:
b.printf("wuffs_base__io_writer__copy_from_slice(&iop_a_dst, io1_a_dst,")
return g.writeArgs(b, args, depth)
case t.IDCopyNFromSlice:
b.printf("wuffs_base__io_writer__copy_n_from_slice(&iop_a_dst, io1_a_dst,")
return g.writeArgs(b, args, depth)
case t.IDPosition:
b.printf("(a_dst.private_impl.buf ? wuffs_base__u64__sat_add(" +
"a_dst.private_impl.buf->meta.pos, iop_a_dst - a_dst.private_impl.buf->data.ptr) : 0)")
return nil
case t.IDSetMark:
// TODO: is a private_impl.mark the right representation? What
// if the function is passed a (ptr io_writer) instead of a
// (io_writer)? Do we still want to have that mark live outside of
// the function scope?
b.printf("wuffs_base__io_writer__set_mark(&%sdst, iop_a_dst)", aPrefix)
return nil
case t.IDSinceMark, t.IDSinceMarkLength:
prefix, name := aPrefix, "dst"
if recv.Operator() == 0 {
prefix, name = vPrefix, recv.Ident().Str(g.tm)
}
if method == t.IDSinceMark {
b.printf("wuffs_base__make_slice_u8(%s%s.private_impl.mark, (size_t)(", prefix, name)
}
b.printf("iop_%s%s - %s%s.private_impl.mark", prefix, name, prefix, name)
if method == t.IDSinceMark {
b.writes("))")
}
return nil
}
if method >= writeFastMethodsBase {
if m := method - writeFastMethodsBase; m < t.ID(len(writeFastMethods)) {
if p := writeFastMethods[m]; p.n != 0 {
// Generate a three part expression using the comma operator:
// "(store, pointer increment, return_empty_struct call)". The
// final part is a function call (to a static inline function)
// instead of a struct literal, to avoid a "expression result
// unused" compiler error.
b.printf("(wuffs_base__store_u%d%ce(iop_a_dst,", p.n, p.endianness)
if err := g.writeExpr(b, args[0].AsArg().Value(), depth); err != nil {
return err
}
b.printf("), iop_a_dst += %d, wuffs_base__make_empty_struct())", p.n/8)
return nil
}
}
}
return g.writeBuiltinIO(b, recv, method, args, depth)
}
func (g *gen) writeBuiltinNumType(b *buffer, recv *a.Expr, method t.ID, args []*a.Node, depth uint32) error {
switch method {
case t.IDLowBits:
// "recv.low_bits(n:etc)" in C is one of:
// - "((recv) & constant)"
// - "((recv) & WUFFS_BASE__LOW_BITS_MASK__UXX(n))"
b.writes("((")
if err := g.writeExpr(b, recv, depth); err != nil {
return err
}
b.writes(") & ")
if cv := args[0].AsArg().Value().ConstValue(); cv != nil && cv.Sign() >= 0 && cv.Cmp(sixtyFour) <= 0 {
mask := big.NewInt(0)
mask.Lsh(one, uint(cv.Uint64()))
mask.Sub(mask, one)
b.printf("0x%s", strings.ToUpper(mask.Text(16)))
} else {
if sz, err := g.sizeof(recv.MType()); err != nil {
return err
} else {
b.printf("WUFFS_BASE__LOW_BITS_MASK__U%d(", 8*sz)
}
if err := g.writeExpr(b, args[0].AsArg().Value(), depth); err != nil {
return err
}
b.writes(")")
}
b.writes(")")
return nil
case t.IDHighBits:
// "recv.high_bits(n:etc)" in C is "((recv) >> (8*sizeof(recv) - (n)))".
b.writes("((")
if err := g.writeExpr(b, recv, depth); err != nil {
return err
}
b.writes(") >> (")
if sz, err := g.sizeof(recv.MType()); err != nil {
return err
} else {
b.printf("%d", 8*sz)
}
b.writes(" - (")
if err := g.writeExpr(b, args[0].AsArg().Value(), depth); err != nil {
return err
}
b.writes(")))")
return nil
case t.IDMax:
b.writes("wuffs_base__u")
if sz, err := g.sizeof(recv.MType()); err != nil {
return err
} else {
b.printf("%d", 8*sz)
}
b.writes("__max(")
if err := g.writeExpr(b, recv, depth); err != nil {
return err
}
b.writes(",")
if err := g.writeExpr(b, args[0].AsArg().Value(), depth); err != nil {
return err
}
b.writes(")")
return nil
case t.IDMin:
b.writes("wuffs_base__u")
if sz, err := g.sizeof(recv.MType()); err != nil {
return err
} else {
b.printf("%d", 8*sz)
}
b.writes("__min(")
if err := g.writeExpr(b, recv, depth); err != nil {
return err
}
b.writes(",")
if err := g.writeExpr(b, args[0].AsArg().Value(), depth); err != nil {
return err
}
b.writes(")")
return nil
}
return errNoSuchBuiltin
}
func (g *gen) writeBuiltinSlice(b *buffer, recv *a.Expr, method t.ID, args []*a.Node, depth uint32) error {
switch method {
case t.IDCopyFromSlice:
if err := g.writeBuiltinSliceCopyFromSlice8(b, recv, method, args, depth); err != errOptimizationNotApplicable {
return err
}
// TODO: don't assume that the slice is a slice of base.u8.
b.writes("wuffs_base__slice_u8__copy_from_slice(")
if err := g.writeExpr(b, recv, depth); err != nil {
return err
}
b.writeb(',')
return g.writeArgs(b, args, depth)
case t.IDLength:
if recv.Operator() == t.IDOpenParen {
if method := recv.LHS().AsExpr(); method.Operator() == t.IDDot && method.Ident() == t.IDSinceMark {
if lhs := method.LHS().AsExpr(); lhs.MType().IsIOType() {
b.writes("((uint64_t)(")
if lhs.MType().QID()[1] == t.IDIOReader {
if err := g.writeBuiltinIOReader(b, lhs, t.IDSinceMarkLength, nil, depth); err != nil {
return err
}
} else {
if err := g.writeBuiltinIOWriter(b, lhs, t.IDSinceMarkLength, nil, depth); err != nil {
return err
}
}
b.writes("))")
return nil
}
}
}
b.writes("((uint64_t)(")
if err := g.writeExpr(b, recv, depth); err != nil {
return err
}
b.writes(".len))")
return nil
case t.IDSuffix:
// TODO: don't assume that the slice is a slice of base.u8.
b.writes("wuffs_base__slice_u8__suffix(")
if err := g.writeExpr(b, recv, depth); err != nil {
return err
}
b.writeb(',')
return g.writeArgs(b, args, depth)
}
return errNoSuchBuiltin
}
// writeBuiltinSliceCopyFromSlice8 writes an optimized version of:
//
// foo[fIndex:fIndex + 8].copy_from_slice!(s:bar[bIndex:bIndex + 8])
func (g *gen) writeBuiltinSliceCopyFromSlice8(b *buffer, recv *a.Expr, method t.ID, args []*a.Node, depth uint32) error {
if method != t.IDCopyFromSlice || len(args) != 1 {
return errOptimizationNotApplicable
}
foo, fIndex := matchFooIndexIndexPlus8(recv)
bar, bIndex := matchFooIndexIndexPlus8(args[0].AsArg().Value())
if foo == nil || bar == nil {
return errOptimizationNotApplicable
}
b.writes("memcpy((")
if err := g.writeExpr(b, foo, depth); err != nil {
return err
}
if foo.MType().IsSliceType() {
b.writes(".ptr")
}
if fIndex != nil {
b.writes(")+(")
if err := g.writeExpr(b, fIndex, depth); err != nil {
return err
}
}
b.writes("),(")
if err := g.writeExpr(b, bar, depth); err != nil {
return err
}
if bar.MType().IsSliceType() {
b.writes(".ptr")
}
if bIndex != nil {
b.writes(")+(")
if err := g.writeExpr(b, bIndex, depth); err != nil {
return err
}
}
// TODO: don't assume that the slice is a slice of base.u8.
b.writes("), 8)")
return nil
}
// matchFooIndexIndexPlus8 matches n with "foo[index:index + 8]" or "foo[:8]".
// It returns a nil foo if there isn't a match.
func matchFooIndexIndexPlus8(n *a.Expr) (foo *a.Expr, index *a.Expr) {
if n.Operator() != t.IDColon {
return nil, nil
}
foo = n.LHS().AsExpr()
index = n.MHS().AsExpr()
rhs := n.RHS().AsExpr()
if rhs == nil {
return nil, nil
}
if index == nil {
// No-op.
} else if rhs.Operator() != t.IDXBinaryPlus || !rhs.LHS().AsExpr().Eq(index) {
return nil, nil
} else {
rhs = rhs.RHS().AsExpr()
}
if cv := rhs.ConstValue(); cv == nil || cv.Cmp(eight) != 0 {
return nil, nil
}
return foo, index
}
func (g *gen) writeBuiltinTable(b *buffer, recv *a.Expr, method t.ID, args []*a.Node, depth uint32) error {
field := ""
switch method {
case t.IDHeight:
field = "height"
case t.IDStride:
field = "stride"
case t.IDWidth:
field = "width"
case t.IDRow:
// TODO: don't assume that the table is a table of base.u8.
b.writes("wuffs_base__table_u8__row(")
if err := g.writeExpr(b, recv, depth); err != nil {
return err
}
b.writeb(',')
return g.writeArgs(b, args, depth)
}
if field != "" {
b.writes("((uint64_t)(")
if err := g.writeExpr(b, recv, depth); err != nil {
return err
}
b.printf(".%s))", field)
return nil
}
return errNoSuchBuiltin
}
func (g *gen) writeArgs(b *buffer, args []*a.Node, depth uint32) error {
for i, o := range args {
if i > 0 {
b.writeb(',')
}
if err := g.writeExpr(b, o.AsArg().Value(), depth); err != nil {
return err
}
}
b.writes(")")
return nil
}
func (g *gen) writeBuiltinQuestionCall(b *buffer, n *a.Expr, depth uint32) error {
// TODO: also handle (or reject??) being on the RHS of an =? operator.
if (n.Operator() != t.IDOpenParen) || (!n.Effect().Coroutine()) {
return errNoSuchBuiltin
}
method := n.LHS().AsExpr()
recv := method.LHS().AsExpr()
recvTyp := recv.MType()
if !recvTyp.IsIOType() {
return errNoSuchBuiltin
}
if recvTyp.QID()[1] == t.IDIOReader {
switch method.Ident() {
case t.IDReadU8, t.IDReadU8AsU32, t.IDReadU8AsU64:
if err := g.writeCoroSuspPoint(b, false); err != nil {
return err
}
if g.currFunk.tempW > maxTemp {
return fmt.Errorf("too many temporary variables required")
}
temp := g.currFunk.tempW
g.currFunk.tempW++
b.printf("if (WUFFS_BASE__UNLIKELY(iop_a_src == io1_a_src)) {" +
"status = wuffs_base__suspension__short_read; goto suspend; }")
// TODO: watch for passing an array type to writeCTypeName? In C, an
// array type can decay into a pointer.
if err := g.writeCTypeName(b, n.MType(), tPrefix, fmt.Sprint(temp)); err != nil {
return err
}
b.printf(" = *iop_a_src++;\n")
return nil
case t.IDSkip:
x := n.Args()[0].AsArg().Value()
if cv := x.ConstValue(); cv != nil && cv.Cmp(one) == 0 {
if err := g.writeCoroSuspPoint(b, false); err != nil {
return err
}
b.printf("if (WUFFS_BASE__UNLIKELY(iop_a_src == io1_a_src)) {" +
"status = wuffs_base__suspension__short_read; goto suspend; }")
b.printf("iop_a_src++;\n")
return nil
}
g.currFunk.usesScratch = true
// TODO: don't hard-code [0], and allow recursive coroutines.
scratchName := fmt.Sprintf("self->private_data.%s%s[0].scratch",
sPrefix, g.currFunk.astFunc.FuncName().Str(g.tm))
b.printf("%s = ", scratchName)
if err := g.writeExpr(b, x, depth); err != nil {
return err
}
b.writes(";\n")
if err := g.writeCoroSuspPoint(b, false); err != nil {
return err
}
b.printf("if (%s > ((uint64_t)(io1_a_src - iop_a_src))) {\n", scratchName)
b.printf("%s -= io1_a_src - iop_a_src;\n", scratchName)
b.printf("iop_a_src = io1_a_src;\n")
b.writes("status = wuffs_base__suspension__short_read; goto suspend; }\n")
b.printf("iop_a_src += %s;\n", scratchName)
return nil
}
if method.Ident() >= readMethodsBase {
if m := method.Ident() - readMethodsBase; m < t.ID(len(readMethods)) {
if p := readMethods[m]; p.n != 0 {
if err := g.writeCoroSuspPoint(b, false); err != nil {
return err
}
return g.writeReadUxxAsUyy(b, n, "a_src", p.n, p.size, p.endianness)
}
}
}
} else {
switch method.Ident() {
case t.IDWriteU8:
if err := g.writeCoroSuspPoint(b, false); err != nil {
return err
}
b.writes("if (iop_a_dst == io1_a_dst) {\n" +
"status = wuffs_base__suspension__short_write; goto suspend; }\n" +
"*iop_a_dst++ = ")
x := n.Args()[0].AsArg().Value()
if err := g.writeExpr(b, x, depth); err != nil {
return err
}
b.writes(";\n")
return nil
}
}
return errNoSuchBuiltin
}
func (g *gen) writeReadUxxAsUyy(b *buffer, n *a.Expr, preName string, xx uint8, yy uint8, endianness uint8) error {
if (xx&7 != 0) || (xx < 16) || (xx > 64) {
return fmt.Errorf("internal error: bad writeReadUXX size %d", xx)
}
if endianness != 'b' && endianness != 'l' {
return fmt.Errorf("internal error: bad writeReadUXX endianness %q", endianness)
}
if g.currFunk.tempW > maxTemp {
return fmt.Errorf("too many temporary variables required")
}
temp := g.currFunk.tempW
g.currFunk.tempW++
if err := g.writeCTypeName(b, n.MType(), tPrefix, fmt.Sprint(temp)); err != nil {
return err
}
b.writes(";")
g.currFunk.usesScratch = true
// TODO: don't hard-code [0], and allow recursive coroutines.
scratchName := fmt.Sprintf("self->private_data.%s%s[0].scratch",
sPrefix, g.currFunk.astFunc.FuncName().Str(g.tm))
b.printf("if (WUFFS_BASE__LIKELY(io1_a_src - iop_a_src >= %d)) {", xx/8)
b.printf("%s%d =", tPrefix, temp)
if xx != yy {
b.printf("((uint%d_t)(", yy)
}
b.printf("wuffs_base__load_u%d%ce(iop_a_src)", xx, endianness)
if xx != yy {
b.writes("))")
}
b.printf("; iop_a_src += %d;\n", xx/8)
b.printf("} else {")
b.printf("%s = 0;\n", scratchName)
if err := g.writeCoroSuspPoint(b, false); err != nil {
return err
}
b.printf("while (true) {")
b.printf("if (WUFFS_BASE__UNLIKELY(iop_%s == io1_%s)) {"+
"status = wuffs_base__suspension__short_read; goto suspend; }",
preName, preName)
b.printf("uint64_t *scratch = &%s;", scratchName)
b.printf("uint32_t num_bits_%d = *scratch", temp)
switch endianness {
case 'b':
b.writes("& 0xFF; *scratch >>= 8; *scratch <<= 8;")
b.printf("*scratch |= ((uint64_t)(*%s%s++)) << (56 - num_bits_%d);",
iopPrefix, preName, temp)
case 'l':
b.writes(">> 56; *scratch <<= 8; *scratch >>= 8;")
b.printf("*scratch |= ((uint64_t)(*%s%s++)) << num_bits_%d;",
iopPrefix, preName, temp)
}
b.printf("if (num_bits_%d == %d) { %s%d =", temp, xx-8, tPrefix, temp)
if xx != yy {
b.printf("((uint%d_t)(", yy)
}
switch endianness {
case 'b':
b.printf("*scratch >> %d", 64-xx)
case 'l':
b.printf("*scratch")
}
if xx != yy {
b.writes("))")
}
b.printf("; break;")
b.printf("}")
b.printf("num_bits_%d += 8;", temp)
switch endianness {
case 'b':
b.printf("*scratch |= ((uint64_t)(num_bits_%d));", temp)
case 'l':
b.printf("*scratch |= ((uint64_t)(num_bits_%d)) << 56;", temp)
}
b.writes("}}\n")
return nil
}
const readMethodsBase = t.IDReadU8
var readMethods = [...]struct {
size uint8
n uint8
endianness uint8
}{
t.IDReadU8 - readMethodsBase: {8, 8, 'b'},
t.IDReadU16BE - readMethodsBase: {16, 16, 'b'},
t.IDReadU16LE - readMethodsBase: {16, 16, 'l'},
t.IDReadU8AsU32 - readMethodsBase: {32, 8, 'b'},
t.IDReadU16BEAsU32 - readMethodsBase: {32, 16, 'b'},
t.IDReadU16LEAsU32 - readMethodsBase: {32, 16, 'l'},
t.IDReadU24BEAsU32 - readMethodsBase: {32, 24, 'b'},
t.IDReadU24LEAsU32 - readMethodsBase: {32, 24, 'l'},
t.IDReadU32BE - readMethodsBase: {32, 32, 'b'},
t.IDReadU32LE - readMethodsBase: {32, 32, 'l'},
t.IDReadU8AsU64 - readMethodsBase: {64, 8, 'b'},
t.IDReadU16BEAsU64 - readMethodsBase: {64, 16, 'b'},
t.IDReadU16LEAsU64 - readMethodsBase: {64, 16, 'l'},
t.IDReadU24BEAsU64 - readMethodsBase: {64, 24, 'b'},
t.IDReadU24LEAsU64 - readMethodsBase: {64, 24, 'l'},
t.IDReadU32BEAsU64 - readMethodsBase: {64, 32, 'b'},
t.IDReadU32LEAsU64 - readMethodsBase: {64, 32, 'l'},
t.IDReadU40BEAsU64 - readMethodsBase: {64, 40, 'b'},
t.IDReadU40LEAsU64 - readMethodsBase: {64, 40, 'l'},
t.IDReadU48BEAsU64 - readMethodsBase: {64, 48, 'b'},
t.IDReadU48LEAsU64 - readMethodsBase: {64, 48, 'l'},
t.IDReadU56BEAsU64 - readMethodsBase: {64, 56, 'b'},
t.IDReadU56LEAsU64 - readMethodsBase: {64, 56, 'l'},
t.IDReadU64BE - readMethodsBase: {64, 64, 'b'},
t.IDReadU64LE - readMethodsBase: {64, 64, 'l'},
}
const peekMethodsBase = t.IDPeekU8
var peekMethods = [...]struct {
size uint8
n uint8
endianness uint8
}{
t.IDPeekU8 - peekMethodsBase: {8, 8, 'b'},
t.IDPeekU16BE - peekMethodsBase: {16, 16, 'b'},
t.IDPeekU16LE - peekMethodsBase: {16, 16, 'l'},
t.IDPeekU8AsU32 - peekMethodsBase: {32, 8, 'b'},
t.IDPeekU16BEAsU32 - peekMethodsBase: {32, 16, 'b'},
t.IDPeekU16LEAsU32 - peekMethodsBase: {32, 16, 'l'},
t.IDPeekU24BEAsU32 - peekMethodsBase: {32, 24, 'b'},
t.IDPeekU24LEAsU32 - peekMethodsBase: {32, 24, 'l'},
t.IDPeekU32BE - peekMethodsBase: {32, 32, 'b'},
t.IDPeekU32LE - peekMethodsBase: {32, 32, 'l'},
t.IDPeekU8AsU64 - peekMethodsBase: {64, 8, 'b'},
t.IDPeekU16BEAsU64 - peekMethodsBase: {64, 16, 'b'},
t.IDPeekU16LEAsU64 - peekMethodsBase: {64, 16, 'l'},
t.IDPeekU24BEAsU64 - peekMethodsBase: {64, 24, 'b'},
t.IDPeekU24LEAsU64 - peekMethodsBase: {64, 24, 'l'},
t.IDPeekU32BEAsU64 - peekMethodsBase: {64, 32, 'b'},
t.IDPeekU32LEAsU64 - peekMethodsBase: {64, 32, 'l'},
t.IDPeekU40BEAsU64 - peekMethodsBase: {64, 40, 'b'},
t.IDPeekU40LEAsU64 - peekMethodsBase: {64, 40, 'l'},
t.IDPeekU48BEAsU64 - peekMethodsBase: {64, 48, 'b'},
t.IDPeekU48LEAsU64 - peekMethodsBase: {64, 48, 'l'},
t.IDPeekU56BEAsU64 - peekMethodsBase: {64, 56, 'b'},
t.IDPeekU56LEAsU64 - peekMethodsBase: {64, 56, 'l'},
t.IDPeekU64BE - peekMethodsBase: {64, 64, 'b'},
t.IDPeekU64LE - peekMethodsBase: {64, 64, 'l'},
}
const writeFastMethodsBase = t.IDWriteFastU8
var writeFastMethods = [...]struct {
n uint8
endianness uint8
}{
t.IDWriteFastU8 - writeFastMethodsBase: {8, 'b'},
t.IDWriteFastU16BE - writeFastMethodsBase: {16, 'b'},
t.IDWriteFastU16LE - writeFastMethodsBase: {16, 'l'},
t.IDWriteFastU24BE - writeFastMethodsBase: {24, 'b'},
t.IDWriteFastU24LE - writeFastMethodsBase: {24, 'l'},
t.IDWriteFastU32BE - writeFastMethodsBase: {32, 'b'},
t.IDWriteFastU32LE - writeFastMethodsBase: {32, 'l'},
t.IDWriteFastU40BE - writeFastMethodsBase: {40, 'b'},
t.IDWriteFastU40LE - writeFastMethodsBase: {40, 'l'},
t.IDWriteFastU48BE - writeFastMethodsBase: {48, 'b'},
t.IDWriteFastU48LE - writeFastMethodsBase: {48, 'l'},
t.IDWriteFastU56BE - writeFastMethodsBase: {56, 'b'},
t.IDWriteFastU56LE - writeFastMethodsBase: {56, 'l'},
t.IDWriteFastU64BE - writeFastMethodsBase: {64, 'b'},
t.IDWriteFastU64LE - writeFastMethodsBase: {64, 'l'},
}
-1060
View File
@@ -1,1060 +0,0 @@
// Copyright 2017 The Wuffs Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//go:generate go run gen.go
package cgen
import (
"bytes"
"errors"
"flag"
"fmt"
"math/big"
"os"
"os/exec"
"sort"
"strings"
"github.com/google/wuffs/lang/builtin"
"github.com/google/wuffs/lang/check"
"github.com/google/wuffs/lang/generate"
cf "github.com/google/wuffs/cmd/commonflags"
a "github.com/google/wuffs/lang/ast"
t "github.com/google/wuffs/lang/token"
)
var (
zero = big.NewInt(0)
one = big.NewInt(1)
eight = big.NewInt(8)
sixtyFour = big.NewInt(64)
mibi = big.NewInt(1 << 20)
typeExprUtility = a.NewTypeExpr(0, t.IDBase, t.IDUtility, nil, nil, nil)
)
// Prefixes are prepended to names to form a namespace and to avoid e.g.
// "double" being a valid Wuffs variable name but not a valid C one.
const (
aPrefix = "a_" // Function argument.
fPrefix = "f_" // Struct field.
iPrefix = "i_" // Iterate variable.
oPrefix = "o_" // Temporary io_bind variable.
pPrefix = "p_" // Coroutine suspension point (program counter).
sPrefix = "s_" // Coroutine stack (saved local variables).
tPrefix = "t_" // Temporary local variable.
uPrefix = "u_" // Derived from a local variable.
vPrefix = "v_" // Local variable.
)
// I/O (reader/writer) prefixes. In the generated C code, the variables with
// these prefixes all have type uint8_t*. The iop_etc variables are the key
// ones. For an io_reader or io_writer function argument a_src or a_dst,
// reading or writing the next byte (and advancing the stream) is essentially
// "etc = *iop_a_src++" or "*io_a_dst++ = etc".
//
// The other two prefixes, giving names like io0_etc and io1_etc, are
// auxilliary pointers: lower and upper inclusive bounds. As an iop_etc pointer
// advances, it cannot advance past io1_etc. In the rarer case that an iop_etc
// pointer retreats, undoing a read or write, it cannot retreat past io0_etc.
//
// At the start of a function, these pointers are initialized from an
// io_buffer's fields (ptr, ri, wi, len), or possibly a limit field. For an
// io_reader:
// - io0_etc = ptr + ri
// - iop_etc = ptr + ri
// - io1_etc = ptr + wi or limit
// and for an io_writer:
// - io0_etc = ptr + wi
// - iop_etc = ptr + wi
// - io1_etc = ptr + len or limit
//
// TODO: discuss marks and limits, and how (if at all) auxilliary pointers can
// change over a function's lifetime.
const (
io0Prefix = "io0_" // Lower bound.
io1Prefix = "io1_" // Upper bound.
iopPrefix = "iop_" // Pointer.
)
// Do transpiles a Wuffs program to a C program.
//
// The arguments list the source Wuffs files. If no arguments are given, it
// reads from stdin.
//
// The generated program is written to stdout.
func Do(args []string) error {
flags := flag.FlagSet{}
cformatterFlag := flags.String("cformatter", cf.CformatterDefault, cf.CformatterUsage)
genlinenumFlag := flags.Bool("genlinenum", cf.GenlinenumDefault, cf.GenlinenumUsage)
return generate.Do(&flags, args, func(pkgName string, tm *t.Map, c *check.Checker, files []*a.File) ([]byte, error) {
if !cf.IsAlphaNumericIsh(*cformatterFlag) {
return nil, fmt.Errorf("bad -cformatter flag value %q", *cformatterFlag)
}
unformatted := []byte(nil)
if pkgName == "base" {
if len(files) != 0 {
return nil, fmt.Errorf("base package shouldn't have any .wuffs files")
}
buf := make(buffer, 0, 128*1024)
if err := expandBangBangInsert(&buf, baseAllImplC, map[string]func(*buffer) error{
"// !! INSERT base/all-private.h.\n": insertBaseAllPrivateH,
"// !! INSERT base/all-public.h.\n": insertBaseAllPublicH,
"// !! INSERT base/copyright\n": insertBaseCopyright,
"// !! INSERT base/image-impl.c.\n": insertBaseImageImplC,
"// !! INSERT wuffs_base__status strings.\n": func(b *buffer) error {
for _, z := range builtin.Statuses {
msg, _ := t.Unescape(z)
if msg == "" {
continue
}
pre := "warning"
if msg[0] == '$' {
pre = "suspension"
} else if msg[0] == '#' {
pre = "error"
}
b.printf("const char* wuffs_base__%s__%s = \"%sbase: %s\";\n",
pre, cName(msg, ""), msg[:1], msg[1:])
}
return nil
},
}); err != nil {
return nil, err
}
unformatted = []byte(buf)
} else {
g := &gen{
pkgPrefix: "wuffs_" + pkgName + "__",
pkgName: pkgName,
tm: tm,
checker: c,
files: files,
genlinenum: *genlinenumFlag,
}
var err error
unformatted, err = g.generate()
if err != nil {
return nil, err
}
}
stdout := &bytes.Buffer{}
cmd := exec.Command(*cformatterFlag, "-style=Chromium")
cmd.Stdin = bytes.NewReader(unformatted)
cmd.Stdout = stdout
cmd.Stderr = os.Stderr
if err := cmd.Run(); err != nil {
return nil, err
}
return stdout.Bytes(), nil
})
}
type visibility uint32
const (
bothPubPri = visibility(iota)
pubOnly
priOnly
)
const (
maxIOBinds = 100
maxTemp = 10000
)
type status struct {
cName string
msg string
fromThisPkg bool
public bool
}
func statusMsgIsError(msg string) bool {
return (len(msg) != 0) && (msg[0] == '#')
}
func statusMsgIsSuspension(msg string) bool {
return (len(msg) != 0) && (msg[0] == '$')
}
func statusMsgIsWarning(msg string) bool {
return (len(msg) == 0) || (msg[0] != '$' && msg[0] != '#')
}
type buffer []byte
func (b *buffer) Write(p []byte) (int, error) {
*b = append(*b, p...)
return len(p), nil
}
func (b *buffer) printf(format string, args ...interface{}) { fmt.Fprintf(b, format, args...) }
func (b *buffer) writeb(x byte) { *b = append(*b, x) }
func (b *buffer) writes(s string) { *b = append(*b, s...) }
func (b *buffer) writex(s []byte) { *b = append(*b, s...) }
func expandBangBangInsert(b *buffer, s string, m map[string]func(*buffer) error) error {
for {
remaining := ""
if i := strings.IndexByte(s, '\n'); i >= 0 {
s, remaining = s[:i+1], s[i+1:]
}
const prefix = "// !! INSERT "
if !strings.HasPrefix(s, prefix) {
b.writes(s)
} else if f := m[s]; f == nil {
msg := []byte(fmt.Sprintf("unrecognized line %q, want one of:\n", s))
keys := []string(nil)
for k := range m {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
msg = append(msg, '\t')
msg = append(msg, k...)
}
return errors.New(string(msg))
} else if err := f(b); err != nil {
return err
}
if remaining == "" {
break
}
s = remaining
}
return nil
}
func insertBaseAllPrivateH(buf *buffer) error {
buf.writes(baseCorePrivateH)
buf.writeb('\n')
buf.writes(baseRangePrivateH)
buf.writeb('\n')
buf.writes(baseIOPrivateH)
buf.writeb('\n')
buf.writes(baseMemoryPrivateH)
buf.writeb('\n')
buf.writes(baseImagePrivateH)
buf.writeb('\n')
return nil
}
func insertBaseAllPublicH(buf *buffer) error {
if err := expandBangBangInsert(buf, baseCorePublicH, map[string]func(*buffer) error{
"// !! INSERT wuffs_base__status names.\n": func(b *buffer) error {
for _, z := range builtin.Statuses {
msg, _ := t.Unescape(z)
if msg == "" {
return fmt.Errorf("bad built-in status %q", z)
}
pre := "warning"
if statusMsgIsError(msg) {
pre = "error"
} else if statusMsgIsSuspension(msg) {
pre = "suspension"
}
b.printf("extern const char* wuffs_base__%s__%s;\n", pre, cName(msg, ""))
}
return nil
},
}); err != nil {
return err
}
buf.writeb('\n')
buf.writes(baseRangePublicH)
buf.writeb('\n')
buf.writes(baseIOPublicH)
buf.writeb('\n')
buf.writes(baseMemoryPublicH)
buf.writeb('\n')
buf.writes(baseImagePublicH)
buf.writeb('\n')
return nil
}
func insertBaseCopyright(buf *buffer) error {
buf.writes(baseCopyright)
buf.writeb('\n')
return nil
}
func insertBaseImageImplC(buf *buffer) error {
buf.writes(baseImageImplC)
buf.writeb('\n')
return nil
}
type gen struct {
pkgPrefix string // e.g. "wuffs_jpeg__"
pkgName string // e.g. "jpeg"
tm *t.Map
checker *check.Checker
files []*a.File
// genlinenum is whether to print "// foo.wuffs:123" comments in the
// generated C code. This can be useful for debugging, although it is not
// enabled by default as it can lead to many spurious changes in the
// generated C code (due to line numbers changing) when editing Wuffs code.
genlinenum bool
privateDataFields map[t.QQID]struct{}
scalarConstsMap map[t.QID]*a.Const
statusList []status
statusMap map[t.QID]status
structList []*a.Struct
structMap map[t.QID]*a.Struct
currFunk funk
funks map[t.QQID]funk
numPublicCoroutines uint32
}
func (g *gen) generate() ([]byte, error) {
b := new(buffer)
g.statusMap = map[t.QID]status{}
if err := g.forEachStatus(b, bothPubPri, (*gen).gatherStatuses); err != nil {
return nil, err
}
for _, z := range builtin.Statuses {
id, err := g.tm.Insert(z)
if err != nil {
return nil, err
}
msg, _ := t.Unescape(z)
if msg == "" {
return nil, fmt.Errorf("bad built-in status %q", z)
}
if err := g.addStatus(t.QID{t.IDBase, id}, msg, true); err != nil {
return nil, err
}
}
g.scalarConstsMap = map[t.QID]*a.Const{}
if err := g.forEachConst(b, bothPubPri, (*gen).gatherScalarConsts); err != nil {
return nil, err
}
// Make a topologically sorted list of structs.
unsortedStructs := []*a.Struct(nil)
for _, file := range g.files {
for _, tld := range file.TopLevelDecls() {
if tld.Kind() == a.KStruct {
unsortedStructs = append(unsortedStructs, tld.AsStruct())
}
}
}
var ok bool
g.structList, ok = a.TopologicalSortStructs(unsortedStructs)
if !ok {
return nil, fmt.Errorf("cyclical struct definitions")
}
g.structMap = map[t.QID]*a.Struct{}
g.privateDataFields = map[t.QQID]struct{}{}
for _, n := range g.structList {
qid := n.QID()
g.structMap[qid] = n
for _, f := range n.Fields() {
f := f.AsField()
if f.PrivateData() {
g.privateDataFields[t.QQID{qid[0], qid[1], f.Name()}] = struct{}{}
}
}
}
g.funks = map[t.QQID]funk{}
if err := g.forEachFunc(nil, bothPubPri, (*gen).gatherFuncImpl); err != nil {
return nil, err
}
includeGuard := "WUFFS_INCLUDE_GUARD__" + strings.ToUpper(g.pkgName)
b.printf("#ifndef %s\n#define %s\n\n", includeGuard, includeGuard)
if err := g.genIncludes(b); err != nil {
return nil, err
}
b.writes("// !! WUFFS MONOLITHIC RELEASE DISCARDS EVERYTHING ABOVE.\n\n")
if err := g.genHeader(b); err != nil {
return nil, err
}
b.writex(wiStartImpl)
if err := g.genImpl(b); err != nil {
return nil, err
}
b.writex(wiEnd)
b.writes("// !! WUFFS MONOLITHIC RELEASE DISCARDS EVERYTHING BELOW.\n\n")
b.printf("#endif // %s\n\n", includeGuard)
return *b, nil
}
func (g *gen) genIncludes(b *buffer) error {
b.writes("#if defined(WUFFS_IMPLEMENTATION) && !defined(WUFFS_CONFIG__MODULES)\n")
b.writes("#define WUFFS_CONFIG__MODULES\n")
b.printf("#define WUFFS_CONFIG__MODULE__%s\n", strings.ToUpper(g.pkgName))
b.writes("#endif\n\n")
usesList := []string(nil)
usesMap := map[string]struct{}{}
for _, file := range g.files {
for _, tld := range file.TopLevelDecls() {
if tld.Kind() != a.KUse {
continue
}
useDirname := g.tm.ByID(tld.AsUse().Path())
useDirname, _ = t.Unescape(useDirname)
// TODO: sanity check useDirname via commonflags.IsValidUsePath?
if _, ok := usesMap[useDirname]; ok {
continue
}
usesMap[useDirname] = struct{}{}
usesList = append(usesList, useDirname)
}
}
sort.Strings(usesList)
b.writes("#include \"./wuffs-base.c\"\n")
for _, use := range usesList {
b.printf("#include \"./wuffs-%s.c\"\n",
strings.Replace(use, "/", "-", -1))
}
b.writeb('\n')
return nil
}
func (g *gen) genHeader(b *buffer) error {
b.writes("\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n")
b.writes("// ---------------- Status Codes\n\n")
for _, z := range g.statusList {
if !z.fromThisPkg || !z.public {
continue
}
b.printf("extern const char* %s;\n", z.cName)
}
b.writes("\n")
b.writes("// ---------------- Public Consts\n\n")
if err := g.forEachConst(b, pubOnly, (*gen).writeConst); err != nil {
return err
}
b.writes("// ---------------- Struct Declarations\n\n")
for _, n := range g.structList {
structName := n.QID().Str(g.tm)
b.printf("typedef struct %s%s__struct %s%s;\n\n", g.pkgPrefix, structName, g.pkgPrefix, structName)
}
b.writes("// ---------------- Public Initializer Prototypes\n\n")
b.writes("// For any given \"wuffs_foo__bar* self\", \"wuffs_foo__bar__initialize(self,\n")
b.writes("// etc)\" should be called before any other \"wuffs_foo__bar__xxx(self, etc)\".\n")
b.writes("//\n")
b.writes("// Pass sizeof(*self) and WUFFS_VERSION for sizeof_star_self and wuffs_version.\n")
b.writes("// Pass 0 (or some combination of WUFFS_INITIALIZE__XXX) for initialize_flags.\n\n")
for _, n := range g.structList {
if n.Public() {
if err := g.writeInitializerPrototype(b, n); err != nil {
return err
}
}
}
b.writes("// ---------------- Public Function Prototypes\n\n")
if err := g.forEachFunc(b, pubOnly, (*gen).writeFuncPrototype); err != nil {
return err
}
b.writes("// ---------------- Struct Definitions\n\n")
b.writes("// These structs' fields, and the sizeof them, are private implementation\n")
b.writes("// details that aren't guaranteed to be stable across Wuffs versions.\n")
b.writes("//\n")
b.writes("// See https://en.wikipedia.org/wiki/Opaque_pointer#C\n\n")
b.writes("#if defined(__cplusplus) || defined(WUFFS_IMPLEMENTATION)\n\n")
for _, n := range g.structList {
if err := g.writeStruct(b, n); err != nil {
return err
}
}
b.writes("#endif // defined(__cplusplus) || defined(WUFFS_IMPLEMENTATION)\n")
b.writes("\n#ifdef __cplusplus\n} // extern \"C\"\n#endif\n\n")
return nil
}
func (g *gen) genImpl(b *buffer) error {
module := "!defined(WUFFS_CONFIG__MODULES) || defined(WUFFS_CONFIG__MODULE__" +
strings.ToUpper(g.pkgName) + ")"
b.printf("#if %s\n\n", module)
b.writes("// ---------------- Status Codes Implementations\n\n")
for _, z := range g.statusList {
if !z.fromThisPkg || z.msg == "" {
continue
}
b.printf("const char* %s = \"%s%s: %s\";\n", z.cName, z.msg[:1], g.pkgName, z.msg[1:])
}
b.writes("\n")
b.writes("// ---------------- Private Consts\n\n")
if err := g.forEachConst(b, priOnly, (*gen).writeConst); err != nil {
return err
}
b.writes("// ---------------- Private Initializer Prototypes\n\n")
for _, n := range g.structList {
if !n.Public() {
if err := g.writeInitializerPrototype(b, n); err != nil {
return err
}
}
}
b.writes("// ---------------- Private Function Prototypes\n\n")
if err := g.forEachFunc(b, priOnly, (*gen).writeFuncPrototype); err != nil {
return err
}
b.writes("// ---------------- Initializer Implementations\n\n")
for _, n := range g.structList {
if err := g.writeInitializerImpl(b, n); err != nil {
return err
}
}
b.writes("// ---------------- Function Implementations\n\n")
if err := g.forEachFunc(b, bothPubPri, (*gen).writeFuncImpl); err != nil {
return err
}
b.printf("#endif // %s\n\n", module)
return nil
}
func (g *gen) forEachConst(b *buffer, v visibility, f func(*gen, *buffer, *a.Const) error) error {
for _, file := range g.files {
for _, tld := range file.TopLevelDecls() {
if tld.Kind() != a.KConst ||
(v == pubOnly && tld.AsRaw().Flags()&a.FlagsPublic == 0) ||
(v == priOnly && tld.AsRaw().Flags()&a.FlagsPublic != 0) {
continue
}
if err := f(g, b, tld.AsConst()); err != nil {
return err
}
}
}
return nil
}
func (g *gen) forEachFunc(b *buffer, v visibility, f func(*gen, *buffer, *a.Func) error) error {
for _, file := range g.files {
for _, tld := range file.TopLevelDecls() {
if tld.Kind() != a.KFunc ||
(v == pubOnly && tld.AsRaw().Flags()&a.FlagsPublic == 0) ||
(v == priOnly && tld.AsRaw().Flags()&a.FlagsPublic != 0) {
continue
}
if err := f(g, b, tld.AsFunc()); err != nil {
return err
}
}
}
return nil
}
func (g *gen) forEachStatus(b *buffer, v visibility, f func(*gen, *buffer, *a.Status) error) error {
for _, file := range g.files {
for _, tld := range file.TopLevelDecls() {
if tld.Kind() != a.KStatus ||
(v == pubOnly && tld.AsRaw().Flags()&a.FlagsPublic == 0) ||
(v == priOnly && tld.AsRaw().Flags()&a.FlagsPublic != 0) {
continue
}
if err := f(g, b, tld.AsStatus()); err != nil {
return err
}
}
}
return nil
}
func (g *gen) cName(name string) string {
return cName(name, g.pkgPrefix)
}
func cName(name string, pkgPrefix string) string {
s := []byte(pkgPrefix)
underscore := true
for _, r := range name {
if 'A' <= r && r <= 'Z' {
s = append(s, byte(r+'a'-'A'))
underscore = false
} else if ('a' <= r && r <= 'z') || ('0' <= r && r <= '9') {
s = append(s, byte(r))
underscore = false
} else if !underscore {
s = append(s, '_')
underscore = true
}
}
if underscore {
s = s[:len(s)-1]
}
return string(s)
}
func uintBits(qid t.QID) uint32 {
if qid[0] == t.IDBase {
switch qid[1] {
case t.IDU8:
return 8
case t.IDU16:
return 16
case t.IDU32:
return 32
case t.IDU64:
return 64
}
}
return 0
}
func (g *gen) sizeof(typ *a.TypeExpr) (uint32, error) {
if typ.Decorator() == 0 {
if n := uintBits(typ.QID()); n != 0 {
return n / 8, nil
}
}
return 0, fmt.Errorf("unknown sizeof for %q", typ.Str(g.tm))
}
func (g *gen) gatherStatuses(b *buffer, n *a.Status) error {
raw := n.QID()[1].Str(g.tm)
msg, ok := t.Unescape(raw)
if !ok || msg == "" {
return fmt.Errorf("bad status message %q", raw)
}
return g.addStatus(n.QID(), msg, n.Public())
}
func (g *gen) addStatus(qid t.QID, msg string, public bool) error {
category := "warning__"
if msg[0] == '$' {
category = "suspension__"
} else if msg[0] == '#' {
category = "error__"
}
z := status{
cName: g.packagePrefix(qid) + category + cName(msg, ""),
msg: msg,
fromThisPkg: qid[0] == 0,
public: public,
}
g.statusList = append(g.statusList, z)
g.statusMap[qid] = z
return nil
}
func (g *gen) gatherScalarConsts(b *buffer, n *a.Const) error {
if cv := n.Value().ConstValue(); cv != nil {
g.scalarConstsMap[n.QID()] = n
}
return nil
}
func (g *gen) writeConst(b *buffer, n *a.Const) error {
if n.Public() {
if cv := n.Value().ConstValue(); cv != nil {
b.printf("#define %s %v\n\n", strings.ToUpper(g.pkgPrefix+n.QID()[1].Str(g.tm)), cv)
}
}
b.writes("static const ")
if err := g.writeCTypeName(b, n.XType(), "//\n"+g.pkgPrefix, n.QID()[1].Str(g.tm)); err != nil {
return err
}
b.writes("//\n WUFFS_BASE__POTENTIALLY_UNUSED = ")
if err := g.writeConstList(b, n.Value()); err != nil {
return err
}
b.writes(";\n\n")
return nil
}
func (g *gen) writeConstList(b *buffer, n *a.Expr) error {
if n.Operator() == t.IDComma {
b.writeb('{')
for _, o := range n.Args() {
if err := g.writeConstList(b, o.AsExpr()); err != nil {
return err
}
b.writeb(',')
}
b.writeb('}')
} else if cv := n.ConstValue(); cv != nil {
b.writes(cv.String())
} else {
return fmt.Errorf("invalid const value %q", n.Str(g.tm))
}
return nil
}
func (g *gen) writeStructPrivateImpl(b *buffer, n *a.Struct) error {
// TODO: allow max depth > 1 for recursive coroutines.
const maxDepth = 1
b.writes("// Do not access the private_impl's or private_data's fields directly. There\n")
b.writes("// is no API/ABI compatibility or safety guarantee if you do so. Instead, use\n")
b.writes("// the wuffs_foo__bar__baz functions.\n")
b.writes("//\n")
b.writes("// It is a struct, not a struct*, so that the outermost wuffs_foo__bar struct\n")
b.writes("// can be stack allocated when WUFFS_IMPLEMENTATION is defined.\n\n")
b.writes("struct {\n")
if n.Classy() {
b.writes("uint32_t magic;\n")
b.writes("uint32_t active_coroutine;\n")
b.writes("\n")
}
for _, o := range n.Fields() {
o := o.AsField()
if o.PrivateData() || o.XType().Eq(typeExprUtility) {
continue
}
if err := g.writeCTypeName(b, o.XType(), fPrefix, o.Name().Str(g.tm)); err != nil {
return err
}
b.writes(";\n")
}
if n.Classy() {
b.writeb('\n')
for _, file := range g.files {
for _, tld := range file.TopLevelDecls() {
if tld.Kind() != a.KFunc {
continue
}
o := tld.AsFunc()
if o.Receiver() != n.QID() || !o.Effect().Coroutine() {
continue
}
k := g.funks[o.QQID()]
if k.coroSuspPoint == 0 {
continue
}
b.printf("uint32_t %s%s[%d];\n", pPrefix, o.FuncName().Str(g.tm), maxDepth)
}
}
}
b.writes("} private_impl;\n\n")
{
oldOuterLenB0 := len(*b)
b.writes("struct {\n")
oldOuterLenB1 := len(*b)
for _, o := range n.Fields() {
o := o.AsField()
if !o.PrivateData() || o.XType().Eq(typeExprUtility) {
continue
}
if err := g.writeCTypeName(b, o.XType(), fPrefix, o.Name().Str(g.tm)); err != nil {
return err
}
b.writes(";\n")
}
if oldOuterLenB1 != len(*b) {
b.writeb('\n')
}
for _, file := range g.files {
for _, tld := range file.TopLevelDecls() {
if tld.Kind() != a.KFunc {
continue
}
o := tld.AsFunc()
if o.Receiver() != n.QID() || !o.Effect().Coroutine() {
continue
}
k := g.funks[o.QQID()]
if k.coroSuspPoint == 0 && !k.usesScratch {
continue
}
oldInnerLenB0 := len(*b)
b.writes("struct {\n")
oldInnerLenB1 := len(*b)
if k.coroSuspPoint != 0 {
if err := g.writeVars(b, &k, true); err != nil {
return err
}
}
if k.usesScratch {
b.writes("uint64_t scratch;\n")
}
if oldInnerLenB1 != len(*b) {
b.printf("} %s%s[%d];\n", sPrefix, o.FuncName().Str(g.tm), maxDepth)
} else {
*b = (*b)[:oldInnerLenB0]
}
}
}
if oldOuterLenB1 != len(*b) {
b.writes("} private_data;\n\n")
} else {
*b = (*b)[:oldOuterLenB0]
}
}
return nil
}
func (g *gen) writeStruct(b *buffer, n *a.Struct) error {
structName := n.QID().Str(g.tm)
fullStructName := g.pkgPrefix + structName + "__struct"
b.printf("struct %s {\n", fullStructName)
b.writex(wiStart)
if err := g.writeStructPrivateImpl(b, n); err != nil {
return err
}
b.writex(wiElse)
b.writes("// When WUFFS_IMPLEMENTATION is not defined, this placeholder private_impl is\n")
b.writes("// large enough to discourage trying to allocate one on the stack. The sizeof\n")
b.writes("// the real private_impl (and the sizeof the real outermost wuffs_foo__bar\n")
b.writes("// struct) is not part of the public, stable, memory-safe API. Call\n")
b.writes("// wuffs_foo__bar__baz methods (which all take a \"this\"-like pointer as their\n")
b.writes("// first argument) instead of fiddling with bar.private_impl.qux fields.\n")
b.writes("//\n")
b.writes("// Even when WUFFS_IMPLEMENTATION is not defined, the outermost struct still\n")
b.writes("// defines C++ convenience methods. These methods forward on \"this\", so that\n")
b.writes("// you can write \"bar->baz(etc)\" instead of \"wuffs_foo__bar__baz(bar, etc)\".\n")
b.writes("private:\n")
b.writes("union {\n")
b.writes("uint32_t align_as_per_magic_field;\n")
b.writes("uint8_t placeholder[1073741824]; // 1 GiB.\n")
b.writes("} private_impl;\n\n")
b.writes("public:\n")
b.writex(wiEnd)
if n.AsNode().AsRaw().Flags()&a.FlagsPublic != 0 {
if err := g.writeCppMethods(b, n); err != nil {
return err
}
}
b.printf("}; // struct %s\n\n", fullStructName)
return nil
}
func (g *gen) writeCppMethods(b *buffer, n *a.Struct) error {
structName := n.QID().Str(g.tm)
fullStructName := g.pkgPrefix + structName + "__struct"
b.writes("#ifdef __cplusplus\n\n")
// The empty // comment makes clang-format place the function name
// at the start of a line.
b.writes("inline wuffs_base__status WUFFS_BASE__WARN_UNUSED_RESULT //\n" +
"initialize(size_t sizeof_star_self, uint64_t wuffs_version, uint32_t initialize_flags) {\n")
b.printf("return %s%s__initialize(this, sizeof_star_self, wuffs_version, initialize_flags);\n}\n\n",
g.pkgPrefix, structName)
structID := n.QID()[1]
for _, file := range g.files {
for _, tld := range file.TopLevelDecls() {
if (tld.Kind() != a.KFunc) || (tld.AsRaw().Flags()&a.FlagsPublic == 0) {
continue
}
f := tld.AsFunc()
qqid := f.QQID()
if qqid[1] != structID {
continue
}
if err := g.writeFuncSignature(b, f, cppInsideStruct); err != nil {
return err
}
b.writes("{ return ")
b.writes(g.funcCName(f))
b.writes("(this")
for _, o := range f.In().Fields() {
b.writeb(',')
b.writes(aPrefix)
b.writes(o.AsField().Name().Str(g.tm))
}
b.writes(");}\n\n")
}
}
b.writes("#if (__cplusplus >= 201103L) && !defined(WUFFS_IMPLEMENTATION)\n")
b.writes("// Disallow copy and assign.\n")
b.printf("%s(const %s&) = delete;\n", fullStructName, fullStructName)
b.printf("%s& operator=(const %s&) = delete;\n", fullStructName, fullStructName)
b.writes("#endif // (__cplusplus >= 201103L) && !defined(WUFFS_IMPLEMENTATION)\n\n")
b.writes("#endif // __cplusplus\n\n")
return nil
}
var (
wiStartImpl = []byte("\n// WUFFS C HEADER ENDS HERE.\n#ifdef WUFFS_IMPLEMENTATION\n\n")
wiStart = []byte("\n#ifdef WUFFS_IMPLEMENTATION\n\n")
wiElse = []byte("\n#else // WUFFS_IMPLEMENTATION\n\n")
wiEnd = []byte("\n#endif // WUFFS_IMPLEMENTATION\n\n")
)
func (g *gen) writeInitializerSignature(b *buffer, n *a.Struct, public bool) error {
structName := n.QID().Str(g.tm)
b.printf("wuffs_base__status WUFFS_BASE__WARN_UNUSED_RESULT //\n"+
"%s%s__initialize(%s%s *self, size_t sizeof_star_self, uint64_t wuffs_version, uint32_t initialize_flags)",
g.pkgPrefix, structName, g.pkgPrefix, structName)
return nil
}
func (g *gen) writeSizeofSignature(b *buffer, n *a.Struct) error {
b.printf("size_t //\nsizeof__%s%s()", g.pkgPrefix, n.QID().Str(g.tm))
return nil
}
func (g *gen) writeInitializerPrototype(b *buffer, n *a.Struct) error {
if !n.Classy() {
return nil
}
if err := g.writeInitializerSignature(b, n, n.Public()); err != nil {
return err
}
b.writes(";\n\n")
if n.Public() {
if err := g.writeSizeofSignature(b, n); err != nil {
return err
}
b.writes(";\n\n")
}
return nil
}
func (g *gen) writeInitializerImpl(b *buffer, n *a.Struct) error {
if !n.Classy() {
return nil
}
if err := g.writeInitializerSignature(b, n, false); err != nil {
return err
}
b.writes("{\n")
b.writes("if (!self) { return wuffs_base__error__bad_receiver; }\n")
b.writes("if (sizeof(*self) != sizeof_star_self) {\n")
b.writes(" return wuffs_base__error__bad_sizeof_receiver;\n")
b.writes("}\n")
b.writes("if (((wuffs_version >> 32) != WUFFS_VERSION_MAJOR) || " +
"(((wuffs_version >> 16) & 0xFFFF) > WUFFS_VERSION_MINOR)) {\n")
b.writes(" return wuffs_base__error__bad_wuffs_version;\n")
b.writes("}\n\n")
b.writes("if ((initialize_flags & WUFFS_INITIALIZE__ALREADY_ZEROED) != 0) {\n")
b.writes(" // The whole point of this if-check is to detect an uninitialized *self.\n")
b.writes(" // We disable the warning on GCC. Clang-5.0 does not have this warning.\n")
b.writes(" #if !defined(__clang__) && defined(__GNUC__)\n")
b.writes(" #pragma GCC diagnostic push\n")
b.writes(" #pragma GCC diagnostic ignored \"-Wmaybe-uninitialized\"\n")
b.writes(" #endif\n")
b.writes(" if (self->private_impl.magic != 0) {\n")
b.writes(" return wuffs_base__error__initialize_falsely_claimed_already_zeroed;\n")
b.writes(" }\n")
b.writes(" #if !defined(__clang__) && defined(__GNUC__)\n")
b.writes(" #pragma GCC diagnostic pop\n")
b.writes(" #endif\n")
b.writes("} else {\n")
b.writes(" void* p = &(self->private_impl);\n")
b.writes(" size_t n = sizeof(self->private_impl);\n")
b.writes(" if ((initialize_flags & WUFFS_INITIALIZE__LEAVE_INTERNAL_BUFFERS_UNINITIALIZED) == 0) {\n")
b.writes(" p = self;\n")
b.writes(" n = sizeof(*self);\n")
b.writes(" initialize_flags |= WUFFS_INITIALIZE__ALREADY_ZEROED;\n")
b.writes(" }\n")
b.writes(" memset(p, 0, n);\n")
b.writes("}\n\n")
// Call any ctors on sub-structs.
for _, f := range n.Fields() {
f := f.AsField()
x := f.XType()
if x != x.Innermost() {
// TODO: arrays of sub-structs.
continue
}
prefix := g.pkgPrefix
qid := x.QID()
if qid[0] == t.IDBase {
// Base types don't need further initialization.
continue
} else if qid[0] != 0 {
// See gen.packagePrefix for a related TODO with otherPkg.
otherPkg := g.tm.ByID(qid[0])
prefix = "wuffs_" + otherPkg + "__"
} else if g.structMap[qid] == nil {
continue
}
b.printf("{\n")
b.printf("wuffs_base__status z = %s%s__initialize("+
"&self->private_data.%s%s, sizeof(self->private_data.%s%s), WUFFS_VERSION, initialize_flags);\n",
prefix, qid[1].Str(g.tm), fPrefix, f.Name().Str(g.tm), fPrefix, f.Name().Str(g.tm))
b.printf("if (z) { return z; }\n")
b.printf("}\n")
}
b.writes("self->private_impl.magic = WUFFS_BASE__MAGIC;\n")
b.writes("return NULL;\n")
b.writes("}\n\n")
if n.Public() {
if err := g.writeSizeofSignature(b, n); err != nil {
return err
}
b.printf("{ return sizeof (%s%s); }\n\n", g.pkgPrefix, n.QID().Str(g.tm))
}
return nil
}
-243
View File
@@ -1,243 +0,0 @@
// Code generated by running "go generate". DO NOT EDIT.
// Copyright 2017 The Wuffs Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cgen
const baseAllImplC = "" +
"#ifndef WUFFS_INCLUDE_GUARD__BASE\n#define WUFFS_INCLUDE_GUARD__BASE\n\n#if defined(WUFFS_IMPLEMENTATION) && !defined(WUFFS_CONFIG__MODULES)\n#define WUFFS_CONFIG__MODULES\n#define WUFFS_CONFIG__MODULE__BASE\n#endif\n\n// !! WUFFS MONOLITHIC RELEASE DISCARDS EVERYTHING ABOVE.\n\n// !! INSERT base/copyright\n\n#include <stdbool.h>\n#include <stdint.h>\n#include <string.h>\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n// !! INSERT base/all-public.h.\n\n#ifdef __cplusplus\n} // extern \"C\"\n#endif\n\n// WUFFS C HEADER ENDS HERE.\n#ifdef WUFFS_IMPLEMENTATION\n\n#ifdef __cplusplus\nextern \"C\" {\n#endif\n\n// !! INSERT base/all-private.h.\n\n#if !defined(WUFFS_CONFIG__MODULES) || defined(WUFFS_CONFIG__MODULE__BASE)\n\nconst uint8_t wuffs_base__low_bits_mask__u8[9] = {\n 0x00, 0x01, 0x03, 0x07, 0x0F, 0x1F, 0x3F, 0x7F, 0xFF,\n};\n\nconst uint16_t wuffs_base__low_bits_mask__u16[17] = {\n 0x0000, 0x0001, 0x0003, 0x0007, 0x000F, 0x001F, 0x003F, 0x007F, 0x00FF,\n 0x01FF, 0x03FF, 0x07FF, 0x0FFF, 0x1FFF, 0x3FFF, 0x7FFF, 0xFFFF,\n};\n\nconst uint32_t wuffs_ba" +
"se__low_bits_mask__u32[33] = {\n 0x00000000, 0x00000001, 0x00000003, 0x00000007, 0x0000000F, 0x0000001F,\n 0x0000003F, 0x0000007F, 0x000000FF, 0x000001FF, 0x000003FF, 0x000007FF,\n 0x00000FFF, 0x00001FFF, 0x00003FFF, 0x00007FFF, 0x0000FFFF, 0x0001FFFF,\n 0x0003FFFF, 0x0007FFFF, 0x000FFFFF, 0x001FFFFF, 0x003FFFFF, 0x007FFFFF,\n 0x00FFFFFF, 0x01FFFFFF, 0x03FFFFFF, 0x07FFFFFF, 0x0FFFFFFF, 0x1FFFFFFF,\n 0x3FFFFFFF, 0x7FFFFFFF, 0xFFFFFFFF,\n};\n\nconst uint64_t wuffs_base__low_bits_mask__u64[65] = {\n 0x0000000000000000, 0x0000000000000001, 0x0000000000000003,\n 0x0000000000000007, 0x000000000000000F, 0x000000000000001F,\n 0x000000000000003F, 0x000000000000007F, 0x00000000000000FF,\n 0x00000000000001FF, 0x00000000000003FF, 0x00000000000007FF,\n 0x0000000000000FFF, 0x0000000000001FFF, 0x0000000000003FFF,\n 0x0000000000007FFF, 0x000000000000FFFF, 0x000000000001FFFF,\n 0x000000000003FFFF, 0x000000000007FFFF, 0x00000000000FFFFF,\n 0x00000000001FFFFF, 0x00000000003FFFFF, 0x00000000007FFFFF,\n " +
" 0x0000000000FFFFFF, 0x0000000001FFFFFF, 0x0000000003FFFFFF,\n 0x0000000007FFFFFF, 0x000000000FFFFFFF, 0x000000001FFFFFFF,\n 0x000000003FFFFFFF, 0x000000007FFFFFFF, 0x00000000FFFFFFFF,\n 0x00000001FFFFFFFF, 0x00000003FFFFFFFF, 0x00000007FFFFFFFF,\n 0x0000000FFFFFFFFF, 0x0000001FFFFFFFFF, 0x0000003FFFFFFFFF,\n 0x0000007FFFFFFFFF, 0x000000FFFFFFFFFF, 0x000001FFFFFFFFFF,\n 0x000003FFFFFFFFFF, 0x000007FFFFFFFFFF, 0x00000FFFFFFFFFFF,\n 0x00001FFFFFFFFFFF, 0x00003FFFFFFFFFFF, 0x00007FFFFFFFFFFF,\n 0x0000FFFFFFFFFFFF, 0x0001FFFFFFFFFFFF, 0x0003FFFFFFFFFFFF,\n 0x0007FFFFFFFFFFFF, 0x000FFFFFFFFFFFFF, 0x001FFFFFFFFFFFFF,\n 0x003FFFFFFFFFFFFF, 0x007FFFFFFFFFFFFF, 0x00FFFFFFFFFFFFFF,\n 0x01FFFFFFFFFFFFFF, 0x03FFFFFFFFFFFFFF, 0x07FFFFFFFFFFFFFF,\n 0x0FFFFFFFFFFFFFFF, 0x1FFFFFFFFFFFFFFF, 0x3FFFFFFFFFFFFFFF,\n 0x7FFFFFFFFFFFFFFF, 0xFFFFFFFFFFFFFFFF,\n};\n\n// !! INSERT wuffs_base__status strings.\n\n// !! INSERT base/image-impl.c.\n\n#endif // !defined(WUFFS_CONFIG__MODULES) ||\n // defined(WUFFS_C" +
"ONFIG__MODULE__BASE)\n\n#ifdef __cplusplus\n} // extern \"C\"\n#endif\n\n#endif // WUFFS_IMPLEMENTATION\n\n// !! WUFFS MONOLITHIC RELEASE DISCARDS EVERYTHING BELOW.\n\n#endif // WUFFS_INCLUDE_GUARD__BASE\n" +
""
const baseImageImplC = "" +
"// ---------------- Images\n\nconst uint32_t wuffs_base__pixel_format__bits_per_channel[16] = {\n 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,\n 0x08, 0x0A, 0x0C, 0x10, 0x18, 0x20, 0x30, 0x40,\n};\n\nstatic uint64_t //\nwuffs_base__pixel_swizzler__copy_1_1(wuffs_base__slice_u8 dst,\n wuffs_base__slice_u8 dst_palette,\n wuffs_base__slice_u8 src) {\n return wuffs_base__slice_u8__copy_from_slice(dst, src);\n}\n\nstatic uint64_t //\nwuffs_base__pixel_swizzler__copy_4_1(wuffs_base__slice_u8 dst,\n wuffs_base__slice_u8 dst_palette,\n wuffs_base__slice_u8 src) {\n if (dst_palette.len != 1024) {\n return 0;\n }\n size_t dst_len4 = dst.len / 4;\n size_t len = dst_len4 < src.len ? dst_len4 : src.len;\n uint8_t* d = dst.ptr;\n uint8_t* s = src.ptr;\n\n size_t n = len;\n const int N = 4;\n\n while (n >= N) {\n wuffs_base__store_u32le(\n d + (0 * 4),\n wuffs_base__load_u3" +
"2le(dst_palette.ptr + ((uint32_t)(s[0]) * 4)));\n wuffs_base__store_u32le(\n d + (1 * 4),\n wuffs_base__load_u32le(dst_palette.ptr + ((uint32_t)(s[1]) * 4)));\n wuffs_base__store_u32le(\n d + (2 * 4),\n wuffs_base__load_u32le(dst_palette.ptr + ((uint32_t)(s[2]) * 4)));\n wuffs_base__store_u32le(\n d + (3 * 4),\n wuffs_base__load_u32le(dst_palette.ptr + ((uint32_t)(s[3]) * 4)));\n\n s += 1 * N;\n d += 4 * N;\n n -= 1 * N;\n }\n\n while (n >= 1) {\n wuffs_base__store_u32le(\n d + (0 * 4),\n wuffs_base__load_u32le(dst_palette.ptr + ((uint32_t)(s[0]) * 4)));\n\n s += 1 * 1;\n d += 4 * 1;\n n -= 1 * 1;\n }\n\n return len;\n}\n\nstatic uint64_t //\nwuffs_base__pixel_swizzler__swap_rgbx_bgrx(wuffs_base__slice_u8 dst,\n wuffs_base__slice_u8 src) {\n size_t len4 = (dst.len < src.len ? dst.len : src.len) / 4;\n uint8_t* d = dst.ptr;\n uint8_t* s = src.ptr;\n\n size_t n = len4;\n while (n--) {\n uint8_t b0 = s[0];\n " +
"uint8_t b1 = s[1];\n uint8_t b2 = s[2];\n uint8_t b3 = s[3];\n d[0] = b2;\n d[1] = b1;\n d[2] = b0;\n d[3] = b3;\n s += 4;\n d += 4;\n }\n return len4 * 4;\n}\n\nvoid //\nwuffs_base__pixel_swizzler__prepare(wuffs_base__pixel_swizzler* p,\n wuffs_base__pixel_format dst_format,\n wuffs_base__slice_u8 dst_palette,\n wuffs_base__pixel_format src_format,\n wuffs_base__slice_u8 src_palette) {\n if (!p) {\n return;\n }\n\n // TODO: support many more formats.\n\n uint64_t (*func)(wuffs_base__slice_u8 dst, wuffs_base__slice_u8 dst_palette,\n wuffs_base__slice_u8 src) = NULL;\n\n switch (src_format) {\n case WUFFS_BASE__PIXEL_FORMAT__INDEXED__BGRA_BINARY:\n switch (dst_format) {\n case WUFFS_BASE__PIXEL_FORMAT__INDEXED__BGRA_NONPREMUL:\n case WUFFS_BASE__PIXEL_FORMAT__INDEXED__BGRA_PREMUL:\n case WUFFS_BASE__PIXEL_FORMAT__INDEXED__BG" +
"RA_BINARY:\n if (wuffs_base__slice_u8__copy_from_slice(dst_palette, src_palette) !=\n 1024) {\n break;\n }\n func = wuffs_base__pixel_swizzler__copy_1_1;\n break;\n case WUFFS_BASE__PIXEL_FORMAT__BGRA_NONPREMUL:\n case WUFFS_BASE__PIXEL_FORMAT__BGRA_PREMUL:\n case WUFFS_BASE__PIXEL_FORMAT__BGRA_BINARY:\n if (wuffs_base__slice_u8__copy_from_slice(dst_palette, src_palette) !=\n 1024) {\n break;\n }\n func = wuffs_base__pixel_swizzler__copy_4_1;\n break;\n case WUFFS_BASE__PIXEL_FORMAT__RGBA_NONPREMUL:\n case WUFFS_BASE__PIXEL_FORMAT__RGBA_PREMUL:\n case WUFFS_BASE__PIXEL_FORMAT__RGBA_BINARY:\n if (wuffs_base__pixel_swizzler__swap_rgbx_bgrx(dst_palette,\n src_palette) != 1024) {\n break;\n }\n func = wuffs_base__pixel_swizzler__copy_4_1;\n break;\n default:\n br" +
"eak;\n }\n break;\n\n default:\n break;\n }\n\n p->private_impl.func = func;\n}\n\nuint64_t //\nwuffs_base__pixel_swizzler__swizzle_packed(wuffs_base__pixel_swizzler* p,\n wuffs_base__slice_u8 dst,\n wuffs_base__slice_u8 dst_palette,\n wuffs_base__slice_u8 src) {\n if (p && p->private_impl.func) {\n return (*(p->private_impl.func))(dst, dst_palette, src);\n }\n return 0;\n}\n" +
""
const baseCorePrivateH = "" +
"static inline wuffs_base__empty_struct //\nwuffs_base__ignore_status(wuffs_base__status z) {\n return wuffs_base__make_empty_struct();\n}\n\n// WUFFS_BASE__MAGIC is a magic number to check that initializers are called.\n// It's not foolproof, given C doesn't automatically zero memory before use,\n// but it should catch 99.99% of cases.\n//\n// Its (non-zero) value is arbitrary, based on md5sum(\"wuffs\").\n#define WUFFS_BASE__MAGIC ((uint32_t)0x3CCB6C71)\n\n// WUFFS_BASE__DISABLED is a magic number to indicate that a non-recoverable\n// error was previously encountered.\n//\n// Its (non-zero) value is arbitrary, based on md5sum(\"disabled\").\n#define WUFFS_BASE__DISABLED ((uint32_t)0x075AE3D2)\n\n// Denote intentional fallthroughs for -Wimplicit-fallthrough.\n//\n// The order matters here. Clang also defines \"__GNUC__\".\n#if defined(__clang__) && __cplusplus >= 201103L\n#define WUFFS_BASE__FALLTHROUGH [[clang::fallthrough]]\n#elif !defined(__clang__) && defined(__GNUC__) && (__GNUC__ >= 7)\n#define WUFFS_BASE__FALLTHROUGH __attribute" +
"__((fallthrough))\n#else\n#define WUFFS_BASE__FALLTHROUGH\n#endif\n\n// Use switch cases for coroutine suspension points, similar to the technique\n// in https://www.chiark.greenend.org.uk/~sgtatham/coroutines.html\n//\n// We use trivial macros instead of an explicit assignment and case statement\n// so that clang-format doesn't get confused by the unusual \"case\"s.\n#define WUFFS_BASE__COROUTINE_SUSPENSION_POINT_0 case 0:;\n#define WUFFS_BASE__COROUTINE_SUSPENSION_POINT(n) \\\n coro_susp_point = n; \\\n WUFFS_BASE__FALLTHROUGH; \\\n case n:;\n\n#define WUFFS_BASE__COROUTINE_SUSPENSION_POINT_MAYBE_SUSPEND(n) \\\n if (!status) { \\\n goto ok; \\\n } else if (*status != '$') { \\\n goto exit; \\\n } \\\n coro_susp_point = n; " +
" \\\n goto suspend; \\\n case n:;\n\n// Clang also defines \"__GNUC__\".\n#if defined(__GNUC__)\n#define WUFFS_BASE__LIKELY(expr) (__builtin_expect(!!(expr), 1))\n#define WUFFS_BASE__UNLIKELY(expr) (__builtin_expect(!!(expr), 0))\n#else\n#define WUFFS_BASE__LIKELY(expr) (expr)\n#define WUFFS_BASE__UNLIKELY(expr) (expr)\n#endif\n\n// The helpers below are functions, instead of macros, because their arguments\n// can be an expression that we shouldn't evaluate more than once.\n//\n// They are static, so that linking multiple wuffs .o files won't complain about\n// duplicate function definitions.\n//\n// They are explicitly marked inline, even if modern compilers don't use the\n// inline attribute to guide optimizations such as inlining, to avoid the\n// -Wunused-function warning, and we like to compile with -Wall -Werror.\n\n" +
"" +
"// ---------------- Numeric Types\n\nstatic inline uint8_t //\nwuffs_base__load_u8be(uint8_t* p) {\n return p[0];\n}\n\nstatic inline uint16_t //\nwuffs_base__load_u16be(uint8_t* p) {\n return ((uint16_t)(p[0]) << 8) | ((uint16_t)(p[1]) << 0);\n}\n\nstatic inline uint16_t //\nwuffs_base__load_u16le(uint8_t* p) {\n return ((uint16_t)(p[0]) << 0) | ((uint16_t)(p[1]) << 8);\n}\n\nstatic inline uint32_t //\nwuffs_base__load_u24be(uint8_t* p) {\n return ((uint32_t)(p[0]) << 16) | ((uint32_t)(p[1]) << 8) |\n ((uint32_t)(p[2]) << 0);\n}\n\nstatic inline uint32_t //\nwuffs_base__load_u24le(uint8_t* p) {\n return ((uint32_t)(p[0]) << 0) | ((uint32_t)(p[1]) << 8) |\n ((uint32_t)(p[2]) << 16);\n}\n\nstatic inline uint32_t //\nwuffs_base__load_u32be(uint8_t* p) {\n return ((uint32_t)(p[0]) << 24) | ((uint32_t)(p[1]) << 16) |\n ((uint32_t)(p[2]) << 8) | ((uint32_t)(p[3]) << 0);\n}\n\nstatic inline uint32_t //\nwuffs_base__load_u32le(uint8_t* p) {\n return ((uint32_t)(p[0]) << 0) | ((uint32_t)(p[1]) << 8) |\n ((uin" +
"t32_t)(p[2]) << 16) | ((uint32_t)(p[3]) << 24);\n}\n\nstatic inline uint64_t //\nwuffs_base__load_u40be(uint8_t* p) {\n return ((uint64_t)(p[0]) << 32) | ((uint64_t)(p[1]) << 24) |\n ((uint64_t)(p[2]) << 16) | ((uint64_t)(p[3]) << 8) |\n ((uint64_t)(p[4]) << 0);\n}\n\nstatic inline uint64_t //\nwuffs_base__load_u40le(uint8_t* p) {\n return ((uint64_t)(p[0]) << 0) | ((uint64_t)(p[1]) << 8) |\n ((uint64_t)(p[2]) << 16) | ((uint64_t)(p[3]) << 24) |\n ((uint64_t)(p[4]) << 32);\n}\n\nstatic inline uint64_t //\nwuffs_base__load_u48be(uint8_t* p) {\n return ((uint64_t)(p[0]) << 40) | ((uint64_t)(p[1]) << 32) |\n ((uint64_t)(p[2]) << 24) | ((uint64_t)(p[3]) << 16) |\n ((uint64_t)(p[4]) << 8) | ((uint64_t)(p[5]) << 0);\n}\n\nstatic inline uint64_t //\nwuffs_base__load_u48le(uint8_t* p) {\n return ((uint64_t)(p[0]) << 0) | ((uint64_t)(p[1]) << 8) |\n ((uint64_t)(p[2]) << 16) | ((uint64_t)(p[3]) << 24) |\n ((uint64_t)(p[4]) << 32) | ((uint64_t)(p[5]) << 40);\n}\n\nstatic inline u" +
"int64_t //\nwuffs_base__load_u56be(uint8_t* p) {\n return ((uint64_t)(p[0]) << 48) | ((uint64_t)(p[1]) << 40) |\n ((uint64_t)(p[2]) << 32) | ((uint64_t)(p[3]) << 24) |\n ((uint64_t)(p[4]) << 16) | ((uint64_t)(p[5]) << 8) |\n ((uint64_t)(p[6]) << 0);\n}\n\nstatic inline uint64_t //\nwuffs_base__load_u56le(uint8_t* p) {\n return ((uint64_t)(p[0]) << 0) | ((uint64_t)(p[1]) << 8) |\n ((uint64_t)(p[2]) << 16) | ((uint64_t)(p[3]) << 24) |\n ((uint64_t)(p[4]) << 32) | ((uint64_t)(p[5]) << 40) |\n ((uint64_t)(p[6]) << 48);\n}\n\nstatic inline uint64_t //\nwuffs_base__load_u64be(uint8_t* p) {\n return ((uint64_t)(p[0]) << 56) | ((uint64_t)(p[1]) << 48) |\n ((uint64_t)(p[2]) << 40) | ((uint64_t)(p[3]) << 32) |\n ((uint64_t)(p[4]) << 24) | ((uint64_t)(p[5]) << 16) |\n ((uint64_t)(p[6]) << 8) | ((uint64_t)(p[7]) << 0);\n}\n\nstatic inline uint64_t //\nwuffs_base__load_u64le(uint8_t* p) {\n return ((uint64_t)(p[0]) << 0) | ((uint64_t)(p[1]) << 8) |\n ((uint64_t)" +
"(p[2]) << 16) | ((uint64_t)(p[3]) << 24) |\n ((uint64_t)(p[4]) << 32) | ((uint64_t)(p[5]) << 40) |\n ((uint64_t)(p[6]) << 48) | ((uint64_t)(p[7]) << 56);\n}\n\n" +
"" +
"// --------\n\nstatic inline void //\nwuffs_base__store_u8be(uint8_t* p, uint8_t x) {\n p[0] = x;\n}\n\nstatic inline void //\nwuffs_base__store_u16be(uint8_t* p, uint16_t x) {\n p[0] = x >> 8;\n p[1] = x >> 0;\n}\n\nstatic inline void //\nwuffs_base__store_u16le(uint8_t* p, uint16_t x) {\n p[0] = x >> 0;\n p[1] = x >> 8;\n}\n\nstatic inline void //\nwuffs_base__store_u24be(uint8_t* p, uint32_t x) {\n p[0] = x >> 16;\n p[1] = x >> 8;\n p[2] = x >> 0;\n}\n\nstatic inline void //\nwuffs_base__store_u24le(uint8_t* p, uint32_t x) {\n p[0] = x >> 0;\n p[1] = x >> 8;\n p[2] = x >> 16;\n}\n\nstatic inline void //\nwuffs_base__store_u32be(uint8_t* p, uint32_t x) {\n p[0] = x >> 24;\n p[1] = x >> 16;\n p[2] = x >> 8;\n p[3] = x >> 0;\n}\n\nstatic inline void //\nwuffs_base__store_u32le(uint8_t* p, uint32_t x) {\n p[0] = x >> 0;\n p[1] = x >> 8;\n p[2] = x >> 16;\n p[3] = x >> 24;\n}\n\nstatic inline void //\nwuffs_base__store_u40be(uint8_t* p, uint64_t x) {\n p[0] = x >> 32;\n p[1] = x >> 24;\n p[2] = x >> 16;\n p[3] = x >> 8;\n p[4] = x >>" +
" 0;\n}\n\nstatic inline void //\nwuffs_base__store_u40le(uint8_t* p, uint64_t x) {\n p[0] = x >> 0;\n p[1] = x >> 8;\n p[2] = x >> 16;\n p[3] = x >> 24;\n p[4] = x >> 32;\n}\n\nstatic inline void //\nwuffs_base__store_u48be(uint8_t* p, uint64_t x) {\n p[0] = x >> 40;\n p[1] = x >> 32;\n p[2] = x >> 24;\n p[3] = x >> 16;\n p[4] = x >> 8;\n p[5] = x >> 0;\n}\n\nstatic inline void //\nwuffs_base__store_u48le(uint8_t* p, uint64_t x) {\n p[0] = x >> 0;\n p[1] = x >> 8;\n p[2] = x >> 16;\n p[3] = x >> 24;\n p[4] = x >> 32;\n p[5] = x >> 40;\n}\n\nstatic inline void //\nwuffs_base__store_u56be(uint8_t* p, uint64_t x) {\n p[0] = x >> 48;\n p[1] = x >> 40;\n p[2] = x >> 32;\n p[3] = x >> 24;\n p[4] = x >> 16;\n p[5] = x >> 8;\n p[6] = x >> 0;\n}\n\nstatic inline void //\nwuffs_base__store_u56le(uint8_t* p, uint64_t x) {\n p[0] = x >> 0;\n p[1] = x >> 8;\n p[2] = x >> 16;\n p[3] = x >> 24;\n p[4] = x >> 32;\n p[5] = x >> 40;\n p[6] = x >> 48;\n}\n\nstatic inline void //\nwuffs_base__store_u64be(uint8_t* p, uint64_t x) {\n p[0] = x >> 56" +
";\n p[1] = x >> 48;\n p[2] = x >> 40;\n p[3] = x >> 32;\n p[4] = x >> 24;\n p[5] = x >> 16;\n p[6] = x >> 8;\n p[7] = x >> 0;\n}\n\nstatic inline void //\nwuffs_base__store_u64le(uint8_t* p, uint64_t x) {\n p[0] = x >> 0;\n p[1] = x >> 8;\n p[2] = x >> 16;\n p[3] = x >> 24;\n p[4] = x >> 32;\n p[5] = x >> 40;\n p[6] = x >> 48;\n p[7] = x >> 56;\n}\n\n" +
"" +
"// --------\n\nextern const uint8_t wuffs_base__low_bits_mask__u8[9];\nextern const uint16_t wuffs_base__low_bits_mask__u16[17];\nextern const uint32_t wuffs_base__low_bits_mask__u32[33];\nextern const uint64_t wuffs_base__low_bits_mask__u64[65];\n\n#define WUFFS_BASE__LOW_BITS_MASK__U8(n) (wuffs_base__low_bits_mask__u8[n])\n#define WUFFS_BASE__LOW_BITS_MASK__U16(n) (wuffs_base__low_bits_mask__u16[n])\n#define WUFFS_BASE__LOW_BITS_MASK__U32(n) (wuffs_base__low_bits_mask__u32[n])\n#define WUFFS_BASE__LOW_BITS_MASK__U64(n) (wuffs_base__low_bits_mask__u64[n])\n\n" +
"" +
"// --------\n\nstatic inline void //\nwuffs_base__u8__sat_add_indirect(uint8_t* x, uint8_t y) {\n *x = wuffs_base__u8__sat_add(*x, y);\n}\n\nstatic inline void //\nwuffs_base__u8__sat_sub_indirect(uint8_t* x, uint8_t y) {\n *x = wuffs_base__u8__sat_sub(*x, y);\n}\n\nstatic inline void //\nwuffs_base__u16__sat_add_indirect(uint16_t* x, uint16_t y) {\n *x = wuffs_base__u16__sat_add(*x, y);\n}\n\nstatic inline void //\nwuffs_base__u16__sat_sub_indirect(uint16_t* x, uint16_t y) {\n *x = wuffs_base__u16__sat_sub(*x, y);\n}\n\nstatic inline void //\nwuffs_base__u32__sat_add_indirect(uint32_t* x, uint32_t y) {\n *x = wuffs_base__u32__sat_add(*x, y);\n}\n\nstatic inline void //\nwuffs_base__u32__sat_sub_indirect(uint32_t* x, uint32_t y) {\n *x = wuffs_base__u32__sat_sub(*x, y);\n}\n\nstatic inline void //\nwuffs_base__u64__sat_add_indirect(uint64_t* x, uint64_t y) {\n *x = wuffs_base__u64__sat_add(*x, y);\n}\n\nstatic inline void //\nwuffs_base__u64__sat_sub_indirect(uint64_t* x, uint64_t y) {\n *x = wuffs_base__u64__sat_sub(*x, y);\n}\n\n" +
"" +
"// ---------------- Slices and Tables\n\n// wuffs_base__slice_u8__prefix returns up to the first up_to bytes of s.\nstatic inline wuffs_base__slice_u8 //\nwuffs_base__slice_u8__prefix(wuffs_base__slice_u8 s, uint64_t up_to) {\n if ((uint64_t)(s.len) > up_to) {\n s.len = up_to;\n }\n return s;\n}\n\n// wuffs_base__slice_u8__suffix returns up to the last up_to bytes of s.\nstatic inline wuffs_base__slice_u8 //\nwuffs_base__slice_u8__suffix(wuffs_base__slice_u8 s, uint64_t up_to) {\n if ((uint64_t)(s.len) > up_to) {\n s.ptr += (uint64_t)(s.len) - up_to;\n s.len = up_to;\n }\n return s;\n}\n\n// wuffs_base__slice_u8__copy_from_slice calls memmove(dst.ptr, src.ptr, len)\n// where len is the minimum of dst.len and src.len.\n//\n// Passing a wuffs_base__slice_u8 with all fields NULL or zero (a valid, empty\n// slice) is valid and results in a no-op.\nstatic inline uint64_t //\nwuffs_base__slice_u8__copy_from_slice(wuffs_base__slice_u8 dst,\n wuffs_base__slice_u8 src) {\n size_t len = dst.l" +
"en < src.len ? dst.len : src.len;\n if (len > 0) {\n memmove(dst.ptr, src.ptr, len);\n }\n return len;\n}\n\n" +
"" +
"// --------\n\nstatic inline wuffs_base__slice_u8 //\nwuffs_base__table_u8__row(wuffs_base__table_u8 t, uint32_t y) {\n if (y < t.height) {\n return wuffs_base__make_slice_u8(t.ptr + (t.stride * y), t.width);\n }\n return wuffs_base__make_slice_u8(NULL, 0);\n}\n\n" +
"" +
"// ---------------- Slices and Tables (Utility)\n\nstatic inline wuffs_base__slice_u8 //\nwuffs_base__utility__null_slice_u8() {\n return wuffs_base__make_slice_u8(NULL, 0);\n}\n\n" +
"" +
"// ---------------- Bureaucracy re -Wunused-function\n\nstatic inline void\nwuffs_base__acknowledge_potentially_unused_functions__core_private()\n WUFFS_BASE__POTENTIALLY_UNUSED;\n\nstatic inline void\nwuffs_base__acknowledge_potentially_unused_functions__core_private() {\n (void)(wuffs_base__ignore_status);\n (void)(wuffs_base__load_u16be);\n (void)(wuffs_base__load_u16le);\n (void)(wuffs_base__load_u24be);\n (void)(wuffs_base__load_u24le);\n (void)(wuffs_base__load_u32be);\n (void)(wuffs_base__load_u32le);\n (void)(wuffs_base__load_u40be);\n (void)(wuffs_base__load_u40le);\n (void)(wuffs_base__load_u48be);\n (void)(wuffs_base__load_u48le);\n (void)(wuffs_base__load_u56be);\n (void)(wuffs_base__load_u56le);\n (void)(wuffs_base__load_u64be);\n (void)(wuffs_base__load_u64le);\n (void)(wuffs_base__load_u8be);\n (void)(wuffs_base__slice_u8__copy_from_slice);\n (void)(wuffs_base__slice_u8__prefix);\n (void)(wuffs_base__slice_u8__suffix);\n (void)(wuffs_base__store_u16be);\n (void)(wuffs_base__store_u16le);\n (void)(w" +
"uffs_base__store_u24be);\n (void)(wuffs_base__store_u24le);\n (void)(wuffs_base__store_u32be);\n (void)(wuffs_base__store_u32le);\n (void)(wuffs_base__store_u40be);\n (void)(wuffs_base__store_u40le);\n (void)(wuffs_base__store_u48be);\n (void)(wuffs_base__store_u48le);\n (void)(wuffs_base__store_u56be);\n (void)(wuffs_base__store_u56le);\n (void)(wuffs_base__store_u64be);\n (void)(wuffs_base__store_u64le);\n (void)(wuffs_base__store_u8be);\n (void)(wuffs_base__table_u8__row);\n (void)(wuffs_base__u16__sat_add_indirect);\n (void)(wuffs_base__u16__sat_sub_indirect);\n (void)(wuffs_base__u32__sat_add_indirect);\n (void)(wuffs_base__u32__sat_sub_indirect);\n (void)(wuffs_base__u64__sat_add_indirect);\n (void)(wuffs_base__u64__sat_sub_indirect);\n (void)(wuffs_base__u8__sat_add_indirect);\n (void)(wuffs_base__u8__sat_sub_indirect);\n (void)(wuffs_base__utility__null_slice_u8);\n}\n" +
""
const baseCorePublicH = "" +
"// Wuffs assumes that:\n// - converting a uint32_t to a size_t will never overflow.\n// - converting a size_t to a uint64_t will never overflow.\n#ifdef __WORDSIZE\n#if (__WORDSIZE != 32) && (__WORDSIZE != 64)\n#error \"Wuffs requires a word size of either 32 or 64 bits\"\n#endif\n#endif\n\n// WUFFS_VERSION is the major.minor.patch version, as per https://semver.org/,\n// as a uint64_t. The major number is the high 32 bits. The minor number is the\n// middle 16 bits. The patch number is the low 16 bits. The pre-release label\n// and build metadata are part of the string representation (such as\n// \"1.2.3-beta+456.20181231\") but not the uint64_t representation.\n//\n// WUFFS_VERSION_PRE_RELEASE_LABEL (such as \"\", \"beta\" or \"rc.1\") being\n// non-empty denotes a developer preview, not a release version, and has no\n// backwards or forwards compatibility guarantees.\n//\n// WUFFS_VERSION_BUILD_METADATA_XXX, if non-zero, are the number of commits and\n// the last commit date in the repository used to build this library. Within\n// eac" +
"h major.minor branch, the commit count should increase monotonically.\n//\n// !! Some code generation programs can override WUFFS_VERSION.\n#define WUFFS_VERSION ((uint64_t)0)\n#define WUFFS_VERSION_MAJOR ((uint64_t)0)\n#define WUFFS_VERSION_MINOR ((uint64_t)0)\n#define WUFFS_VERSION_PATCH ((uint64_t)0)\n#define WUFFS_VERSION_PRE_RELEASE_LABEL \"work.in.progress\"\n#define WUFFS_VERSION_BUILD_METADATA_COMMIT_COUNT 0\n#define WUFFS_VERSION_BUILD_METADATA_COMMIT_DATE 0\n#define WUFFS_VERSION_STRING \"0.0.0+0.00000000\"\n\n// Define WUFFS_CONFIG__STATIC_FUNCTIONS to make all of Wuffs' functions have\n// static storage. The motivation is discussed in the \"ALLOW STATIC\n// IMPLEMENTATION\" section of\n// https://raw.githubusercontent.com/nothings/stb/master/docs/stb_howto.txt\n#ifdef WUFFS_CONFIG__STATIC_FUNCTIONS\n#define WUFFS_BASE__MAYBE_STATIC static\n#else\n#define WUFFS_BASE__MAYBE_STATIC\n#endif\n\n// Clang also defines \"__GNUC__\".\n#if defined(__GNUC__)\n#define WUFFS_BASE__POTENTIALLY_UNUSED __attribute__((unused))\n#define WUFFS_BASE" +
"__WARN_UNUSED_RESULT __attribute__((warn_unused_result))\n#else\n#define WUFFS_BASE__POTENTIALLY_UNUSED\n#define WUFFS_BASE__WARN_UNUSED_RESULT\n#endif\n\n// Flags for wuffs_foo__bar__initialize functions.\n\n#define WUFFS_INITIALIZE__DEFAULT_OPTIONS ((uint32_t)0x00000000)\n\n// WUFFS_INITIALIZE__ALREADY_ZEROED means that the \"self\" receiver struct value\n// has already been set to all zeroes.\n#define WUFFS_INITIALIZE__ALREADY_ZEROED ((uint32_t)0x00000001)\n\n// WUFFS_INITIALIZE__LEAVE_INTERNAL_BUFFERS_UNINITIALIZED means that, absent\n// WUFFS_INITIALIZE__ALREADY_ZEROED, only some of the \"self\" receiver struct\n// value will be set to all zeroes. Internal buffers, which tend to be a large\n// proportion of the struct's size, will be left uninitialized. Internal means\n// that the buffer is contained by the receiver struct, as opposed to being\n// passed as a separately allocated \"work buffer\".\n//\n// With or without this bit set, the Wuffs compiler still enforces that no\n// reads or writes will overflow internal buffers' bound" +
"s. Even with this bit\n// set, the Wuffs standard library also considers reading from an uninitialized\n// buffer to be a bug, and strives to never do so, but unlike buffer overflows,\n// it is not a bug class that the Wuffs compiler eliminates.\n//\n// For those paranoid about security, leave this bit unset, so that\n// wuffs_foo__bar__initialize will initialize the entire struct value to zeroes\n// (unless WUFFS_INITIALIZE__ALREADY_ZEROED is set).\n//\n// Setting this bit gives a small absolute improvement on micro-benchmarks, but\n// this can be a large relative effect, up to 2x faster, when the actual work\n// to be done is also small, such as decompressing small input. See git commit\n// 438fc105 \"Move some struct fields to private_data\" for some numbers and a\n// discussion, noting that its commit message was written before this\n// WUFFS_INITIALIZE__LEAVE_INTERNAL_BUFFERS_UNINITIALIZED option was defined.\n#define WUFFS_INITIALIZE__LEAVE_INTERNAL_BUFFERS_UNINITIALIZED \\\n ((uint32_t)0x00000002)\n\n" +
"" +
"// --------\n\n// wuffs_base__empty_struct is used when a Wuffs function returns an empty\n// struct. In C, if a function f returns void, you can't say \"x = f()\", but in\n// Wuffs, if a function g returns empty, you can say \"y = g()\".\ntypedef struct {\n // private_impl is a placeholder field. It isn't explicitly used, except that\n // without it, the sizeof a struct with no fields can differ across C/C++\n // compilers, and it is undefined behavior in C99. For example, gcc says that\n // the sizeof an empty struct is 0, and g++ says that it is 1. This leads to\n // ABI incompatibility if a Wuffs .c file is processed by one compiler and\n // its .h file with another compiler.\n //\n // Instead, we explicitly insert an otherwise unused field, so that the\n // sizeof this struct is always 1.\n uint8_t private_impl;\n} wuffs_base__empty_struct;\n\nstatic inline wuffs_base__empty_struct //\nwuffs_base__make_empty_struct() {\n wuffs_base__empty_struct ret;\n ret.private_impl = 0;\n return ret;\n}\n\n// wuffs_base__utility is" +
" a placeholder receiver type. It enables what Java\n// calls static methods, as opposed to regular methods.\ntypedef struct {\n // private_impl is a placeholder field. It isn't explicitly used, except that\n // without it, the sizeof a struct with no fields can differ across C/C++\n // compilers, and it is undefined behavior in C99. For example, gcc says that\n // the sizeof an empty struct is 0, and g++ says that it is 1. This leads to\n // ABI incompatibility if a Wuffs .c file is processed by one compiler and\n // its .h file with another compiler.\n //\n // Instead, we explicitly insert an otherwise unused field, so that the\n // sizeof this struct is always 1.\n uint8_t private_impl;\n} wuffs_base__utility;\n\n" +
"" +
"// --------\n\n// A status is either NULL (meaning OK) or a string message. That message is\n// human-readable, for programmers, but it is not for end users. It is not\n// localized, and does not contain additional contextual information such as a\n// source filename.\n//\n// Status strings are statically allocated and should never be free'd. They can\n// be compared by the == operator and not just by strcmp.\n//\n// Statuses come in four categories:\n// - OK: the request was completed, successfully.\n// - Warnings: the request was completed, unsuccessfully.\n// - Suspensions: the request was not completed, but can be re-tried.\n// - Errors: the request was not completed, permanently.\n//\n// When a function returns an incomplete status, a suspension means that that\n// function should be called again within a new context, such as after flushing\n// or re-filling an I/O buffer. An error means that an irrecoverable failure\n// state was reached.\ntypedef const char* wuffs_base__status;\n\n// !! INSERT wuffs_bas" +
"e__status names.\n\nstatic inline bool //\nwuffs_base__status__is_complete(wuffs_base__status z) {\n return (z == NULL) || ((*z != '$') && (*z != '#'));\n}\n\nstatic inline bool //\nwuffs_base__status__is_error(wuffs_base__status z) {\n return z && (*z == '#');\n}\n\nstatic inline bool //\nwuffs_base__status__is_ok(wuffs_base__status z) {\n return z == NULL;\n}\n\nstatic inline bool //\nwuffs_base__status__is_suspension(wuffs_base__status z) {\n return z && (*z == '$');\n}\n\nstatic inline bool //\nwuffs_base__status__is_warning(wuffs_base__status z) {\n return z && (*z != '$') && (*z != '#');\n}\n\n" +
"" +
"// --------\n\n// Flicks are a unit of time. One flick (frame-tick) is 1 / 705_600_000 of a\n// second. See https://github.com/OculusVR/Flicks\ntypedef int64_t wuffs_base__flicks;\n\n#define WUFFS_BASE__FLICKS_PER_SECOND ((uint64_t)705600000)\n#define WUFFS_BASE__FLICKS_PER_MILLISECOND ((uint64_t)705600)\n\n" +
"" +
"// ---------------- Numeric Types\n\nstatic inline uint8_t //\nwuffs_base__u8__min(uint8_t x, uint8_t y) {\n return x < y ? x : y;\n}\n\nstatic inline uint8_t //\nwuffs_base__u8__max(uint8_t x, uint8_t y) {\n return x > y ? x : y;\n}\n\nstatic inline uint16_t //\nwuffs_base__u16__min(uint16_t x, uint16_t y) {\n return x < y ? x : y;\n}\n\nstatic inline uint16_t //\nwuffs_base__u16__max(uint16_t x, uint16_t y) {\n return x > y ? x : y;\n}\n\nstatic inline uint32_t //\nwuffs_base__u32__min(uint32_t x, uint32_t y) {\n return x < y ? x : y;\n}\n\nstatic inline uint32_t //\nwuffs_base__u32__max(uint32_t x, uint32_t y) {\n return x > y ? x : y;\n}\n\nstatic inline uint64_t //\nwuffs_base__u64__min(uint64_t x, uint64_t y) {\n return x < y ? x : y;\n}\n\nstatic inline uint64_t //\nwuffs_base__u64__max(uint64_t x, uint64_t y) {\n return x > y ? x : y;\n}\n\n" +
"" +
"// --------\n\n// Saturating arithmetic (sat_add, sat_sub) branchless bit-twiddling algorithms\n// are per https://locklessinc.com/articles/sat_arithmetic/\n//\n// It is important that the underlying types are unsigned integers, as signed\n// integer arithmetic overflow is undefined behavior in C.\n\nstatic inline uint8_t //\nwuffs_base__u8__sat_add(uint8_t x, uint8_t y) {\n uint8_t res = x + y;\n res |= -(res < x);\n return res;\n}\n\nstatic inline uint8_t //\nwuffs_base__u8__sat_sub(uint8_t x, uint8_t y) {\n uint8_t res = x - y;\n res &= -(res <= x);\n return res;\n}\n\nstatic inline uint16_t //\nwuffs_base__u16__sat_add(uint16_t x, uint16_t y) {\n uint16_t res = x + y;\n res |= -(res < x);\n return res;\n}\n\nstatic inline uint16_t //\nwuffs_base__u16__sat_sub(uint16_t x, uint16_t y) {\n uint16_t res = x - y;\n res &= -(res <= x);\n return res;\n}\n\nstatic inline uint32_t //\nwuffs_base__u32__sat_add(uint32_t x, uint32_t y) {\n uint32_t res = x + y;\n res |= -(res < x);\n return res;\n}\n\nstatic inline uint32_t //\nwuffs_base_" +
"_u32__sat_sub(uint32_t x, uint32_t y) {\n uint32_t res = x - y;\n res &= -(res <= x);\n return res;\n}\n\nstatic inline uint64_t //\nwuffs_base__u64__sat_add(uint64_t x, uint64_t y) {\n uint64_t res = x + y;\n res |= -(res < x);\n return res;\n}\n\nstatic inline uint64_t //\nwuffs_base__u64__sat_sub(uint64_t x, uint64_t y) {\n uint64_t res = x - y;\n res &= -(res <= x);\n return res;\n}\n\n" +
"" +
"// ---------------- Slices and Tables\n\n// WUFFS_BASE__SLICE is a 1-dimensional buffer.\n//\n// len measures a number of elements, not necessarily a size in bytes.\n//\n// A value with all fields NULL or zero is a valid, empty slice.\n#define WUFFS_BASE__SLICE(T) \\\n struct { \\\n T* ptr; \\\n size_t len; \\\n }\n\n// WUFFS_BASE__TABLE is a 2-dimensional buffer.\n//\n// width height, and stride measure a number of elements, not necessarily a\n// size in bytes.\n//\n// A value with all fields NULL or zero is a valid, empty table.\n#define WUFFS_BASE__TABLE(T) \\\n struct { \\\n T* ptr; \\\n size_t width; \\\n size_t height; \\\n size_t stride; \\\n }\n\ntypedef WUFFS_BASE__SLICE(uint8_t) wuffs_base__slice_u8;\ntypedef WUFFS_BASE__SLICE(uint16_t) wuffs_base__slice_u16;\ntypedef WUFFS_BASE__SLICE(uint32_t) wuffs_base__slice_u32;\ntypedef WUFFS_BASE__SLICE(uint64_t) wuffs_base__slice_u64;\n\ntypedef WUFFS_BASE__TABLE(u" +
"int8_t) wuffs_base__table_u8;\ntypedef WUFFS_BASE__TABLE(uint16_t) wuffs_base__table_u16;\ntypedef WUFFS_BASE__TABLE(uint32_t) wuffs_base__table_u32;\ntypedef WUFFS_BASE__TABLE(uint64_t) wuffs_base__table_u64;\n\nstatic inline wuffs_base__slice_u8 //\nwuffs_base__make_slice_u8(uint8_t* ptr, size_t len) {\n wuffs_base__slice_u8 ret;\n ret.ptr = ptr;\n ret.len = len;\n return ret;\n}\n\nstatic inline wuffs_base__slice_u16 //\nwuffs_base__make_slice_u16(uint16_t* ptr, size_t len) {\n wuffs_base__slice_u16 ret;\n ret.ptr = ptr;\n ret.len = len;\n return ret;\n}\n\nstatic inline wuffs_base__slice_u32 //\nwuffs_base__make_slice_u32(uint32_t* ptr, size_t len) {\n wuffs_base__slice_u32 ret;\n ret.ptr = ptr;\n ret.len = len;\n return ret;\n}\n\nstatic inline wuffs_base__slice_u64 //\nwuffs_base__make_slice_u64(uint64_t* ptr, size_t len) {\n wuffs_base__slice_u64 ret;\n ret.ptr = ptr;\n ret.len = len;\n return ret;\n}\n\n// wuffs_base__slice_u8__subslice_i returns s[i:].\n//\n// It returns an empty slice if i is out of bounds.\nstatic inl" +
"ine wuffs_base__slice_u8 //\nwuffs_base__slice_u8__subslice_i(wuffs_base__slice_u8 s, uint64_t i) {\n if ((i <= SIZE_MAX) && (i <= s.len)) {\n return wuffs_base__make_slice_u8(s.ptr + i, s.len - i);\n }\n return wuffs_base__make_slice_u8(NULL, 0);\n}\n\n// wuffs_base__slice_u8__subslice_j returns s[:j].\n//\n// It returns an empty slice if j is out of bounds.\nstatic inline wuffs_base__slice_u8 //\nwuffs_base__slice_u8__subslice_j(wuffs_base__slice_u8 s, uint64_t j) {\n if ((j <= SIZE_MAX) && (j <= s.len)) {\n return wuffs_base__make_slice_u8(s.ptr, j);\n }\n return wuffs_base__make_slice_u8(NULL, 0);\n}\n\n// wuffs_base__slice_u8__subslice_ij returns s[i:j].\n//\n// It returns an empty slice if i or j is out of bounds.\nstatic inline wuffs_base__slice_u8 //\nwuffs_base__slice_u8__subslice_ij(wuffs_base__slice_u8 s,\n uint64_t i,\n uint64_t j) {\n if ((i <= j) && (j <= SIZE_MAX) && (j <= s.len)) {\n return wuffs_base__make_slice_u8(s.ptr + i, j - i);\n " +
" }\n return wuffs_base__make_slice_u8(NULL, 0);\n}\n\n" +
"" +
"// ---------------- Bureaucracy re -Wunused-function\n\nstatic inline void\nwuffs_base__acknowledge_potentially_unused_functions__core_public()\n WUFFS_BASE__POTENTIALLY_UNUSED;\n\nstatic inline void\nwuffs_base__acknowledge_potentially_unused_functions__core_public() {\n (void)(wuffs_base__make_empty_struct);\n (void)(wuffs_base__make_slice_u16);\n (void)(wuffs_base__make_slice_u32);\n (void)(wuffs_base__make_slice_u64);\n (void)(wuffs_base__make_slice_u8);\n (void)(wuffs_base__slice_u8__subslice_i);\n (void)(wuffs_base__slice_u8__subslice_ij);\n (void)(wuffs_base__slice_u8__subslice_j);\n (void)(wuffs_base__status__is_complete);\n (void)(wuffs_base__status__is_error);\n (void)(wuffs_base__status__is_ok);\n (void)(wuffs_base__status__is_suspension);\n (void)(wuffs_base__status__is_warning);\n (void)(wuffs_base__u16__max);\n (void)(wuffs_base__u16__min);\n (void)(wuffs_base__u16__sat_add);\n (void)(wuffs_base__u16__sat_sub);\n (void)(wuffs_base__u32__max);\n (void)(wuffs_base__u32__min);\n (void)(wuffs_base__u32_" +
"_sat_add);\n (void)(wuffs_base__u32__sat_sub);\n (void)(wuffs_base__u64__max);\n (void)(wuffs_base__u64__min);\n (void)(wuffs_base__u64__sat_add);\n (void)(wuffs_base__u64__sat_sub);\n (void)(wuffs_base__u8__max);\n (void)(wuffs_base__u8__min);\n (void)(wuffs_base__u8__sat_add);\n (void)(wuffs_base__u8__sat_sub);\n}\n" +
""
const baseMemoryPrivateH = "" +
"// ---------------- Memory Allocation\n" +
""
const baseMemoryPublicH = "" +
"// ---------------- Memory Allocation\n\n// The memory allocation related functions in this section aren't used by Wuffs\n// per se, but they may be helpful to the code that uses Wuffs.\n\n// wuffs_base__malloc_slice_uxx wraps calling a malloc-like function, except\n// that it takes a uint64_t number of elements instead of a size_t size in\n// bytes, and it returns a slice (a pointer and a length) instead of just a\n// pointer.\n//\n// You can pass the C stdlib's malloc as the malloc_func.\n//\n// It returns an empty slice (containing a NULL ptr field) if (num_uxx *\n// sizeof(uintxx_t)) would overflow SIZE_MAX.\n\nstatic inline wuffs_base__slice_u8 //\nwuffs_base__malloc_slice_u8(void* (*malloc_func)(size_t), uint64_t num_u8) {\n if (malloc_func && (num_u8 <= (SIZE_MAX / sizeof(uint8_t)))) {\n void* p = (*malloc_func)(num_u8 * sizeof(uint8_t));\n if (p) {\n return wuffs_base__make_slice_u8((uint8_t*)(p), num_u8);\n }\n }\n return wuffs_base__make_slice_u8(NULL, 0);\n}\n\nstatic inline wuffs_base__slice_u16 //\nwuffs" +
"_base__malloc_slice_u16(void* (*malloc_func)(size_t), uint64_t num_u16) {\n if (malloc_func && (num_u16 <= (SIZE_MAX / sizeof(uint16_t)))) {\n void* p = (*malloc_func)(num_u16 * sizeof(uint16_t));\n if (p) {\n return wuffs_base__make_slice_u16((uint16_t*)(p), num_u16);\n }\n }\n return wuffs_base__make_slice_u16(NULL, 0);\n}\n\nstatic inline wuffs_base__slice_u32 //\nwuffs_base__malloc_slice_u32(void* (*malloc_func)(size_t), uint64_t num_u32) {\n if (malloc_func && (num_u32 <= (SIZE_MAX / sizeof(uint32_t)))) {\n void* p = (*malloc_func)(num_u32 * sizeof(uint32_t));\n if (p) {\n return wuffs_base__make_slice_u32((uint32_t*)(p), num_u32);\n }\n }\n return wuffs_base__make_slice_u32(NULL, 0);\n}\n\nstatic inline wuffs_base__slice_u64 //\nwuffs_base__malloc_slice_u64(void* (*malloc_func)(size_t), uint64_t num_u64) {\n if (malloc_func && (num_u64 <= (SIZE_MAX / sizeof(uint64_t)))) {\n void* p = (*malloc_func)(num_u64 * sizeof(uint64_t));\n if (p) {\n return wuffs_base__make_slice_u64((uint64_" +
"t*)(p), num_u64);\n }\n }\n return wuffs_base__make_slice_u64(NULL, 0);\n}\n\n" +
"" +
"// ---------------- Bureaucracy re -Wunused-function\n\nstatic inline void\nwuffs_base__acknowledge_potentially_unused_functions__memory_public()\n WUFFS_BASE__POTENTIALLY_UNUSED;\n\nstatic inline void\nwuffs_base__acknowledge_potentially_unused_functions__memory_public() {\n (void)(wuffs_base__malloc_slice_u16);\n (void)(wuffs_base__malloc_slice_u32);\n (void)(wuffs_base__malloc_slice_u64);\n (void)(wuffs_base__malloc_slice_u8);\n}\n" +
""
const baseImagePrivateH = "" +
"// ---------------- Images\n" +
""
const baseImagePublicH = "" +
"// ---------------- Images\n\n// wuffs_base__color_u32_argb_premul is an 8 bit per channel premultiplied\n// Alpha, Red, Green, Blue color, as a uint32_t value. It is in word order, not\n// byte order: its value is always 0xAARRGGBB, regardless of endianness.\ntypedef uint32_t wuffs_base__color_u32_argb_premul;\n\n" +
"" +
"// --------\n\n// wuffs_base__pixel_format encodes the format of the bytes that constitute an\n// image frame's pixel data. Its bits:\n// - bit 31 is reserved.\n// - bits 30 .. 28 encodes color (and channel order, in terms of memory).\n// - bit 27 is reserved.\n// - bits 26 .. 24 encodes transparency.\n// - bits 23 .. 21 are reserved.\n// - bit 20 indicates big-endian/MSB-first (as opposed to little/LSB).\n// - bit 19 indicates floating point (as opposed to integer).\n// - bit 18 indicates palette-indexed. The number-of-planes (the next\n// field) will be zero, as the format is considered packed,\n// but the 8-bit N-BGRA color data is stored in plane 3.\n// - bits 17 .. 16 are the number of planes, minus 1. Zero means packed.\n// - bits 15 .. 12 encodes the number of bits (depth) in the 3rd channel.\n// - bits 11 .. 8 encodes the number of bits (depth) in the 2nd channel.\n// - bits 7 .. 4 encodes the number of bits (depth) in the 1st channe" +
"l.\n// - bits 3 .. 0 encodes the number of bits (depth) in the 0th channel.\n//\n// The bit fields of a wuffs_base__pixel_format are not independent. For\n// example, the number of planes should not be greater than the number of\n// channels. Similarly, bits 15..4 are unused (and should be zero) if bits\n// 31..24 (color and transparency) together imply only 1 channel (gray, no\n// alpha) and floating point samples should mean a bit depth of 16, 32 or 64.\n//\n// Formats hold between 1 and 4 channels. For example: Y (1 channel: gray), YA\n// (2 channels: gray and alpha), BGR (3 channels: blue, green, red) or CMYK (4\n// channels: cyan, magenta, yellow, black).\n//\n// For direct formats with N > 1 channels, those channels can be laid out in\n// either 1 (packed) or N (planar) planes. For example, RGBA data is usually\n// packed, but YCbCr data is usually planar, due to chroma subsampling (for\n// details, see the wuffs_base__pixel_subsampling type).\n//\n// For indexed formats, the palette (always 256 × 4 bytes) holds 8 bi" +
"ts per\n// channel non-alpha-premultiplied BGRA color data. There is only 1 plane (for\n// the index), as the format is considered packed. Plane 0 holds the per-pixel\n// indices. Plane 3 is re-purposed to hold the per-index colors.\n//\n// The color field is encoded in 3 bits:\n// - 0 means A (Alpha).\n// - 1 means Y or YA (Gray, Alpha).\n// - 2 means YCbCr or YCbCrA (Luma, Chroma-blue, Chroma-red, Alpha).\n// - 3 means YCoCg or YCoCgA (Luma, Chroma-orange, Chroma-green, Alpha).\n// - 4 means BGR, BGRX or BGRA (Blue, Green, Red, X-padding or Alpha).\n// - 5 means RGB, RGBX or RGBA (Red, Green, Blue, X-padding or Alpha).\n// - 6 means CMY or CMYK (Cyan, Magenta, Yellow, Black).\n// - all other values are reserved.\n//\n// In Wuffs, channels are given in memory order (also known as byte order),\n// regardless of endianness, since the C type for the pixel data is an array of\n// bytes, not an array of uint32_t. For example, packed BGRA with 8 bits per\n// channel means th" +
"at the bytes in memory are always Blue, Green, Red then\n// Alpha. On big-endian systems, that is the uint32_t 0xBBGGRRAA. On\n// little-endian, 0xAARRGGBB.\n//\n// When the color field (3 bits) encodes multiple options, the transparency\n// field (3 bits) distinguishes them:\n// - 0 means fully opaque, no extra channels\n// - 1 means fully opaque, one extra channel (X or K, padding or black).\n// - 5 means one extra alpha channel, other channels are non-premultiplied.\n// - 6 means one extra alpha channel, other channels are premultiplied.\n// - 7 means one extra alpha channel, binary alpha.\n// - all other values are reserved.\n//\n// Binary alpha means that if a color is not completely opaque, it is\n// completely transparent black. As a source pixel format, it can therefore be\n// treated as either non-premultiplied or premultiplied.\n//\n// The zero wuffs_base__pixel_format value is an invalid pixel format, as it is\n// invalid to combine the zero color (alpha only) with the zero transparency.\n//\n// Bit depth is" +
" encoded in 4 bits:\n// - 0 means the channel or index is unused.\n// - x means a bit depth of x, for x in the range 1..8.\n// - 9 means a bit depth of 10.\n// - 10 means a bit depth of 12.\n// - 11 means a bit depth of 16.\n// - 12 means a bit depth of 24.\n// - 13 means a bit depth of 32.\n// - 14 means a bit depth of 48.\n// - 15 means a bit depth of 64.\n//\n// For example, wuffs_base__pixel_format 0x5510BBBB is a natural format for\n// decoding a PNG image - network byte order (also known as big-endian),\n// packed, non-premultiplied alpha - that happens to be 16-bit-depth truecolor\n// with alpha (RGBA). In memory order:\n//\n// ptr+0 ptr+1 ptr+2 ptr+3 ptr+4 ptr+5 ptr+6 ptr+7\n// Rhi Rlo Ghi Glo Bhi Blo Ahi Alo\n//\n// For example, the value wuffs_base__pixel_format 0x40000565 means BGR with no\n// alpha or padding, 5/6/5 bits for blue/green/red, packed 2 bytes per pixel,\n// laid out LSB-first in memory order:\n//\n// ptr+0........... ptr+1...........\n// MSB LSB MSB " +
" LSB\n// G₂G₁G₀B₄B₃B₂B₁B₀ R₄R₃R₂R₁R₀G₅G₄G₃\n//\n// On little-endian systems (but not big-endian), this Wuffs pixel format value\n// (0x40000565) corresponds to the Cairo library's CAIRO_FORMAT_RGB16_565, the\n// SDL2 (Simple DirectMedia Layer 2) library's SDL_PIXELFORMAT_RGB565 and the\n// Skia library's kRGB_565_SkColorType. Note BGR in Wuffs versus RGB in the\n// other libraries.\n//\n// Regardless of endianness, this Wuffs pixel format value (0x40000565)\n// corresponds to the V4L2 (Video For Linux 2) library's V4L2_PIX_FMT_RGB565\n// and the Wayland-DRM library's WL_DRM_FORMAT_RGB565.\n//\n// Different software libraries name their pixel formats (and especially their\n// channel order) either according to memory layout or as bits of a native\n// integer type like uint32_t. The two conventions differ because of a system's\n// endianness. As mentioned earlier, Wuffs pixel formats are always in memory\n// order. More detail of other software libraries' naming conventions is in the\n// Pi" +
"xel Format Guide at https://afrantzis.github.io/pixel-format-guide/\n//\n// Do not manipulate these bits directly; they are private implementation\n// details. Use methods such as wuffs_base__pixel_format__num_planes instead.\ntypedef uint32_t wuffs_base__pixel_format;\n\n// Common 8-bit-depth pixel formats. This list is not exhaustive; not all valid\n// wuffs_base__pixel_format values are present.\n\n#define WUFFS_BASE__PIXEL_FORMAT__INVALID ((wuffs_base__pixel_format)0x00000000)\n\n#define WUFFS_BASE__PIXEL_FORMAT__A ((wuffs_base__pixel_format)0x02000008)\n\n#define WUFFS_BASE__PIXEL_FORMAT__Y ((wuffs_base__pixel_format)0x10000008)\n#define WUFFS_BASE__PIXEL_FORMAT__YA_NONPREMUL \\\n ((wuffs_base__pixel_format)0x15000008)\n#define WUFFS_BASE__PIXEL_FORMAT__YA_PREMUL \\\n ((wuffs_base__pixel_format)0x16000008)\n\n#define WUFFS_BASE__PIXEL_FORMAT__YCBCR ((wuffs_base__pixel_format)0x20020888)\n#define WUFFS_BASE__PIXEL_FORMAT__YCBCRK ((wuffs_base__pixel_format)0x21038888)\n#define WUFFS_BASE__PIXEL_FORMAT__YCBCRA_NONPREMUL \\\n ((w" +
"uffs_base__pixel_format)0x25038888)\n\n#define WUFFS_BASE__PIXEL_FORMAT__YCOCG ((wuffs_base__pixel_format)0x30020888)\n#define WUFFS_BASE__PIXEL_FORMAT__YCOCGK ((wuffs_base__pixel_format)0x31038888)\n#define WUFFS_BASE__PIXEL_FORMAT__YCOCGA_NONPREMUL \\\n ((wuffs_base__pixel_format)0x35038888)\n\n#define WUFFS_BASE__PIXEL_FORMAT__INDEXED__BGRA_NONPREMUL \\\n ((wuffs_base__pixel_format)0x45040008)\n#define WUFFS_BASE__PIXEL_FORMAT__INDEXED__BGRA_PREMUL \\\n ((wuffs_base__pixel_format)0x46040008)\n#define WUFFS_BASE__PIXEL_FORMAT__INDEXED__BGRA_BINARY \\\n ((wuffs_base__pixel_format)0x47040008)\n\n#define WUFFS_BASE__PIXEL_FORMAT__BGR ((wuffs_base__pixel_format)0x40000888)\n#define WUFFS_BASE__PIXEL_FORMAT__BGRX ((wuffs_base__pixel_format)0x41008888)\n#define WUFFS_BASE__PIXEL_FORMAT__BGRA_NONPREMUL \\\n ((wuffs_base__pixel_format)0x45008888)\n#define WUFFS_BASE__PIXEL_FORMAT__BGRA_PREMUL \\\n ((wuffs_base__pixel_format)0x46008888)\n#define WUFFS_BASE__PIXEL_FORMAT__BGRA_BINARY \\\n ((wuffs_base__pixel_format)0x47008888)\n\n#define W" +
"UFFS_BASE__PIXEL_FORMAT__RGB ((wuffs_base__pixel_format)0x50000888)\n#define WUFFS_BASE__PIXEL_FORMAT__RGBX ((wuffs_base__pixel_format)0x51008888)\n#define WUFFS_BASE__PIXEL_FORMAT__RGBA_NONPREMUL \\\n ((wuffs_base__pixel_format)0x55008888)\n#define WUFFS_BASE__PIXEL_FORMAT__RGBA_PREMUL \\\n ((wuffs_base__pixel_format)0x56008888)\n#define WUFFS_BASE__PIXEL_FORMAT__RGBA_BINARY \\\n ((wuffs_base__pixel_format)0x57008888)\n\n#define WUFFS_BASE__PIXEL_FORMAT__CMY ((wuffs_base__pixel_format)0x60020888)\n#define WUFFS_BASE__PIXEL_FORMAT__CMYK ((wuffs_base__pixel_format)0x61038888)\n\nextern const uint32_t wuffs_base__pixel_format__bits_per_channel[16];\n\nstatic inline bool //\nwuffs_base__pixel_format__is_valid(wuffs_base__pixel_format f) {\n return f != 0;\n}\n\n// wuffs_base__pixel_format__bits_per_pixel returns, for packed pixel formats,\n// the number of bits per pixel. It returns 0 for planar pixel formats.\nstatic inline uint32_t //\nwuffs_base__pixel_format__bits_per_pixel(wuffs_base__pixel_format f) {\n if (((f >> 16) & 0x03" +
") != 0) {\n return 0;\n }\n return wuffs_base__pixel_format__bits_per_channel[0x0F & (f >> 0)] +\n wuffs_base__pixel_format__bits_per_channel[0x0F & (f >> 4)] +\n wuffs_base__pixel_format__bits_per_channel[0x0F & (f >> 8)] +\n wuffs_base__pixel_format__bits_per_channel[0x0F & (f >> 12)];\n}\n\nstatic inline bool //\nwuffs_base__pixel_format__is_indexed(wuffs_base__pixel_format f) {\n return (f >> 18) & 0x01;\n}\n\nstatic inline bool //\nwuffs_base__pixel_format__is_packed(wuffs_base__pixel_format f) {\n return ((f >> 16) & 0x03) == 0;\n}\n\nstatic inline bool //\nwuffs_base__pixel_format__is_planar(wuffs_base__pixel_format f) {\n return ((f >> 16) & 0x03) != 0;\n}\n\nstatic inline uint32_t //\nwuffs_base__pixel_format__num_planes(wuffs_base__pixel_format f) {\n return ((f >> 16) & 0x03) + 1;\n}\n\n#define WUFFS_BASE__PIXEL_FORMAT__NUM_PLANES_MAX 4\n\n#define WUFFS_BASE__PIXEL_FORMAT__INDEXED__INDEX_PLANE 0\n#define WUFFS_BASE__PIXEL_FORMAT__INDEXED__COLOR_PLANE 3\n\n" +
"" +
"// --------\n\n// wuffs_base__pixel_subsampling encodes the mapping of pixel space coordinates\n// (x, y) to pixel buffer indices (i, j). That mapping can differ for each\n// plane p. For a depth of 8 bits (1 byte), the p'th plane's sample starts at\n// (planes[p].ptr + (j * planes[p].stride) + i).\n//\n// For packed pixel formats, the mapping is trivial: i = x and j = y. For\n// planar pixel formats, the mapping can differ due to chroma subsampling. For\n// example, consider a three plane YCbCr pixel format with 4:2:2 subsampling.\n// For the luma (Y) channel, there is one sample for every pixel, but for the\n// chroma (Cb, Cr) channels, there is one sample for every two pixels: pairs of\n// horizontally adjacent pixels form one macropixel, i = x / 2 and j == y. In\n// general, for a given p:\n// - i = (x + bias_x) >> shift_x.\n// - j = (y + bias_y) >> shift_y.\n// where biases and shifts are in the range 0..3 and 0..2 respectively.\n//\n// In general, the biases will be zero after decoding an image. However, making\n// a su" +
"b-image may change the bias, since the (x, y) coordinates are relative\n// to the sub-image's top-left origin, but the backing pixel buffers were\n// created relative to the original image's origin.\n//\n// For each plane p, each of those four numbers (biases and shifts) are encoded\n// in two bits, which combine to form an 8 bit unsigned integer:\n//\n// e_p = (bias_x << 6) | (shift_x << 4) | (bias_y << 2) | (shift_y << 0)\n//\n// Those e_p values (e_0 for the first plane, e_1 for the second plane, etc)\n// combine to form a wuffs_base__pixel_subsampling value:\n//\n// pixsub = (e_3 << 24) | (e_2 << 16) | (e_1 << 8) | (e_0 << 0)\n//\n// Do not manipulate these bits directly; they are private implementation\n// details. Use methods such as wuffs_base__pixel_subsampling__bias_x instead.\ntypedef uint32_t wuffs_base__pixel_subsampling;\n\n#define WUFFS_BASE__PIXEL_SUBSAMPLING__NONE ((wuffs_base__pixel_subsampling)0)\n\n#define WUFFS_BASE__PIXEL_SUBSAMPLING__444 \\\n ((wuffs_base__pixel_subsampling)0x000000)\n#define WUFFS_BASE__PI" +
"XEL_SUBSAMPLING__440 \\\n ((wuffs_base__pixel_subsampling)0x010100)\n#define WUFFS_BASE__PIXEL_SUBSAMPLING__422 \\\n ((wuffs_base__pixel_subsampling)0x101000)\n#define WUFFS_BASE__PIXEL_SUBSAMPLING__420 \\\n ((wuffs_base__pixel_subsampling)0x111100)\n#define WUFFS_BASE__PIXEL_SUBSAMPLING__411 \\\n ((wuffs_base__pixel_subsampling)0x202000)\n#define WUFFS_BASE__PIXEL_SUBSAMPLING__410 \\\n ((wuffs_base__pixel_subsampling)0x212100)\n\nstatic inline uint32_t //\nwuffs_base__pixel_subsampling__bias_x(wuffs_base__pixel_subsampling s,\n uint32_t plane) {\n uint32_t shift = ((plane & 0x03) * 8) + 6;\n return (s >> shift) & 0x03;\n}\n\nstatic inline uint32_t //\nwuffs_base__pixel_subsampling__shift_x(wuffs_base__pixel_subsampling s,\n uint32_t plane) {\n uint32_t shift = ((plane & 0x03) * 8) + 4;\n return (s >> shift) & 0x03;\n}\n\nstatic inline uint32_t //\nwuffs_base__pixel_subsampling__bias_y(wuffs_base__pixel_subsampling s,\n " +
" uint32_t plane) {\n uint32_t shift = ((plane & 0x03) * 8) + 2;\n return (s >> shift) & 0x03;\n}\n\nstatic inline uint32_t //\nwuffs_base__pixel_subsampling__shift_y(wuffs_base__pixel_subsampling s,\n uint32_t plane) {\n uint32_t shift = ((plane & 0x03) * 8) + 0;\n return (s >> shift) & 0x03;\n}\n\n" +
"" +
"// --------\n\ntypedef struct {\n // Do not access the private_impl's fields directly. There is no API/ABI\n // compatibility or safety guarantee if you do so.\n struct {\n wuffs_base__pixel_format pixfmt;\n wuffs_base__pixel_subsampling pixsub;\n uint32_t width;\n uint32_t height;\n } private_impl;\n\n#ifdef __cplusplus\n inline void set(wuffs_base__pixel_format pixfmt,\n wuffs_base__pixel_subsampling pixsub,\n uint32_t width,\n uint32_t height);\n inline void invalidate();\n inline bool is_valid();\n inline wuffs_base__pixel_format pixel_format();\n inline wuffs_base__pixel_subsampling pixel_subsampling();\n inline wuffs_base__rect_ie_u32 bounds();\n inline uint32_t width();\n inline uint32_t height();\n inline uint64_t pixbuf_len();\n#endif // __cplusplus\n\n} wuffs_base__pixel_config;\n\n// TODO: Should this function return bool? An error type?\nstatic inline void //\nwuffs_base__pixel_config__set(wuffs_base__pixel_config* c,\n wuf" +
"fs_base__pixel_format pixfmt,\n wuffs_base__pixel_subsampling pixsub,\n uint32_t width,\n uint32_t height) {\n if (!c) {\n return;\n }\n if (pixfmt) {\n uint64_t wh = ((uint64_t)width) * ((uint64_t)height);\n // TODO: handle things other than 1 byte per pixel.\n if (wh <= ((uint64_t)SIZE_MAX)) {\n c->private_impl.pixfmt = pixfmt;\n c->private_impl.pixsub = pixsub;\n c->private_impl.width = width;\n c->private_impl.height = height;\n return;\n }\n }\n\n c->private_impl.pixfmt = 0;\n c->private_impl.pixsub = 0;\n c->private_impl.width = 0;\n c->private_impl.height = 0;\n}\n\nstatic inline void //\nwuffs_base__pixel_config__invalidate(wuffs_base__pixel_config* c) {\n if (c) {\n c->private_impl.pixfmt = 0;\n c->private_impl.pixsub = 0;\n c->private_impl.width = 0;\n c->private_impl.height = 0;\n }\n}\n\nstatic inline bool //\nwuffs_base__pixel_config__is_valid(wuffs_base__pixel_config* c) {\n return " +
"c && c->private_impl.pixfmt;\n}\n\nstatic inline wuffs_base__pixel_format //\nwuffs_base__pixel_config__pixel_format(wuffs_base__pixel_config* c) {\n return c ? c->private_impl.pixfmt : 0;\n}\n\nstatic inline wuffs_base__pixel_subsampling //\nwuffs_base__pixel_config__pixel_subsampling(wuffs_base__pixel_config* c) {\n return c ? c->private_impl.pixsub : 0;\n}\n\nstatic inline wuffs_base__rect_ie_u32 //\nwuffs_base__pixel_config__bounds(wuffs_base__pixel_config* c) {\n if (c) {\n wuffs_base__rect_ie_u32 ret;\n ret.min_incl_x = 0;\n ret.min_incl_y = 0;\n ret.max_excl_x = c->private_impl.width;\n ret.max_excl_y = c->private_impl.height;\n return ret;\n }\n\n wuffs_base__rect_ie_u32 ret;\n ret.min_incl_x = 0;\n ret.min_incl_y = 0;\n ret.max_excl_x = 0;\n ret.max_excl_y = 0;\n return ret;\n}\n\nstatic inline uint32_t //\nwuffs_base__pixel_config__width(wuffs_base__pixel_config* c) {\n return c ? c->private_impl.width : 0;\n}\n\nstatic inline uint32_t //\nwuffs_base__pixel_config__height(wuffs_base__pixel_config* c) {\n" +
" return c ? c->private_impl.height : 0;\n}\n\n// TODO: this is the right API for planar (not packed) pixbufs? Should it allow\n// decoding into a color model different from the format's intrinsic one? For\n// example, decoding a JPEG image straight to RGBA instead of to YCbCr?\nstatic inline uint64_t //\nwuffs_base__pixel_config__pixbuf_len(wuffs_base__pixel_config* c) {\n if (!c) {\n return 0;\n }\n if (wuffs_base__pixel_format__is_planar(c->private_impl.pixfmt)) {\n // TODO: support planar pixel formats, concious of pixel subsampling.\n return 0;\n }\n uint32_t bits_per_pixel =\n wuffs_base__pixel_format__bits_per_pixel(c->private_impl.pixfmt);\n if ((bits_per_pixel == 0) || ((bits_per_pixel % 8) != 0)) {\n // TODO: support fraction-of-byte pixels, e.g. 1 bit per pixel?\n return 0;\n }\n uint64_t bytes_per_pixel = bits_per_pixel / 8;\n\n uint64_t n =\n ((uint64_t)c->private_impl.width) * ((uint64_t)c->private_impl.height);\n if (n > (UINT64_MAX / bytes_per_pixel)) {\n return 0;\n }\n n *= byte" +
"s_per_pixel;\n\n if (wuffs_base__pixel_format__is_indexed(c->private_impl.pixfmt)) {\n if (n > (UINT64_MAX - 1024)) {\n return 0;\n }\n n += 1024;\n }\n\n return n;\n}\n\n#ifdef __cplusplus\n\ninline void //\nwuffs_base__pixel_config::set(wuffs_base__pixel_format pixfmt,\n wuffs_base__pixel_subsampling pixsub,\n uint32_t width,\n uint32_t height) {\n wuffs_base__pixel_config__set(this, pixfmt, pixsub, width, height);\n}\n\ninline void //\nwuffs_base__pixel_config::invalidate() {\n wuffs_base__pixel_config__invalidate(this);\n}\n\ninline bool //\nwuffs_base__pixel_config::is_valid() {\n return wuffs_base__pixel_config__is_valid(this);\n}\n\ninline wuffs_base__pixel_format //\nwuffs_base__pixel_config::pixel_format() {\n return wuffs_base__pixel_config__pixel_format(this);\n}\n\ninline wuffs_base__pixel_subsampling //\nwuffs_base__pixel_config::pixel_subsampling() {\n return wuffs_base__pixel_config__pixel_subsampling(this);\n}\n\ninline wu" +
"ffs_base__rect_ie_u32 //\nwuffs_base__pixel_config::bounds() {\n return wuffs_base__pixel_config__bounds(this);\n}\n\ninline uint32_t //\nwuffs_base__pixel_config::width() {\n return wuffs_base__pixel_config__width(this);\n}\n\ninline uint32_t //\nwuffs_base__pixel_config::height() {\n return wuffs_base__pixel_config__height(this);\n}\n\ninline uint64_t //\nwuffs_base__pixel_config::pixbuf_len() {\n return wuffs_base__pixel_config__pixbuf_len(this);\n}\n\n#endif // __cplusplus\n\n" +
"" +
"// --------\n\ntypedef struct {\n wuffs_base__pixel_config pixcfg;\n\n // Do not access the private_impl's fields directly. There is no API/ABI\n // compatibility or safety guarantee if you do so.\n struct {\n uint64_t first_frame_io_position;\n bool first_frame_is_opaque;\n } private_impl;\n\n#ifdef __cplusplus\n inline void set(wuffs_base__pixel_format pixfmt,\n wuffs_base__pixel_subsampling pixsub,\n uint32_t width,\n uint32_t height,\n uint64_t first_frame_io_position,\n bool first_frame_is_opaque);\n inline void invalidate();\n inline bool is_valid();\n inline uint64_t first_frame_io_position();\n inline bool first_frame_is_opaque();\n#endif // __cplusplus\n\n} wuffs_base__image_config;\n\n// TODO: Should this function return bool? An error type?\nstatic inline void //\nwuffs_base__image_config__set(wuffs_base__image_config* c,\n wuffs_base__pixel_format pixfmt,\n wuffs_base__" +
"pixel_subsampling pixsub,\n uint32_t width,\n uint32_t height,\n uint64_t first_frame_io_position,\n bool first_frame_is_opaque) {\n if (!c) {\n return;\n }\n if (wuffs_base__pixel_format__is_valid(pixfmt)) {\n c->pixcfg.private_impl.pixfmt = pixfmt;\n c->pixcfg.private_impl.pixsub = pixsub;\n c->pixcfg.private_impl.width = width;\n c->pixcfg.private_impl.height = height;\n c->private_impl.first_frame_io_position = first_frame_io_position;\n c->private_impl.first_frame_is_opaque = first_frame_is_opaque;\n return;\n }\n\n c->pixcfg.private_impl.pixfmt = 0;\n c->pixcfg.private_impl.pixsub = 0;\n c->pixcfg.private_impl.width = 0;\n c->pixcfg.private_impl.height = 0;\n c->private_impl.first_frame_io_position = 0;\n c->private_impl.first_frame_is_opaque = 0;\n}\n\nstatic inline void //\nwuffs_base__image_config__invalidate(wuffs_base__image_config* c) {\n if (c) {\n c->pixcfg.private_impl.p" +
"ixfmt = 0;\n c->pixcfg.private_impl.pixsub = 0;\n c->pixcfg.private_impl.width = 0;\n c->pixcfg.private_impl.height = 0;\n c->private_impl.first_frame_io_position = 0;\n c->private_impl.first_frame_is_opaque = 0;\n }\n}\n\nstatic inline bool //\nwuffs_base__image_config__is_valid(wuffs_base__image_config* c) {\n return c && wuffs_base__pixel_config__is_valid(&(c->pixcfg));\n}\n\nstatic inline uint64_t //\nwuffs_base__image_config__first_frame_io_position(wuffs_base__image_config* c) {\n return c ? c->private_impl.first_frame_io_position : 0;\n}\n\nstatic inline bool //\nwuffs_base__image_config__first_frame_is_opaque(wuffs_base__image_config* c) {\n return c ? c->private_impl.first_frame_is_opaque : false;\n}\n\n#ifdef __cplusplus\n\ninline void //\nwuffs_base__image_config::set(wuffs_base__pixel_format pixfmt,\n wuffs_base__pixel_subsampling pixsub,\n uint32_t width,\n uint32_t height,\n uint64_t first" +
"_frame_io_position,\n bool first_frame_is_opaque) {\n wuffs_base__image_config__set(this, pixfmt, pixsub, width, height,\n first_frame_io_position, first_frame_is_opaque);\n}\n\ninline void //\nwuffs_base__image_config::invalidate() {\n wuffs_base__image_config__invalidate(this);\n}\n\ninline bool //\nwuffs_base__image_config::is_valid() {\n return wuffs_base__image_config__is_valid(this);\n}\n\ninline uint64_t //\nwuffs_base__image_config::first_frame_io_position() {\n return wuffs_base__image_config__first_frame_io_position(this);\n}\n\ninline bool //\nwuffs_base__image_config::first_frame_is_opaque() {\n return wuffs_base__image_config__first_frame_is_opaque(this);\n}\n\n#endif // __cplusplus\n\n" +
"" +
"// --------\n\n// wuffs_base__animation_blend encodes, for an animated image, how to blend the\n// transparent pixels of this frame with the existing canvas. In Porter-Duff\n// compositing operator terminology:\n// - 0 means the frame may be transparent, and should be blended \"src over\n// dst\", also known as just \"over\".\n// - 1 means the frame may be transparent, and should be blended \"src\".\n// - 2 means the frame is completely opaque, so that \"src over dst\" and \"src\"\n// are equivalent.\n//\n// These semantics are conservative. It is valid for a completely opaque frame\n// to have a blend value other than 2.\ntypedef uint8_t wuffs_base__animation_blend;\n\n#define WUFFS_BASE__ANIMATION_BLEND__SRC_OVER_DST \\\n ((wuffs_base__animation_blend)0)\n#define WUFFS_BASE__ANIMATION_BLEND__SRC ((wuffs_base__animation_blend)1)\n#define WUFFS_BASE__ANIMATION_BLEND__OPAQUE ((wuffs_base__animation_blend)2)\n\n" +
"" +
"// --------\n\n// wuffs_base__animation_disposal encodes, for an animated image, how to\n// dispose of a frame after displaying it:\n// - None means to draw the next frame on top of this one.\n// - Restore Background means to clear the frame's dirty rectangle to \"the\n// background color\" (in practice, this means transparent black) before\n// drawing the next frame.\n// - Restore Previous means to undo the current frame, so that the next frame\n// is drawn on top of the previous one.\ntypedef uint8_t wuffs_base__animation_disposal;\n\n#define WUFFS_BASE__ANIMATION_DISPOSAL__NONE ((wuffs_base__animation_disposal)0)\n#define WUFFS_BASE__ANIMATION_DISPOSAL__RESTORE_BACKGROUND \\\n ((wuffs_base__animation_disposal)1)\n#define WUFFS_BASE__ANIMATION_DISPOSAL__RESTORE_PREVIOUS \\\n ((wuffs_base__animation_disposal)2)\n\n" +
"" +
"// --------\n\ntypedef struct {\n // Do not access the private_impl's fields directly. There is no API/ABI\n // compatibility or safety guarantee if you do so.\n struct {\n wuffs_base__rect_ie_u32 bounds;\n wuffs_base__flicks duration;\n uint64_t index;\n uint64_t io_position;\n wuffs_base__animation_blend blend;\n wuffs_base__animation_disposal disposal;\n } private_impl;\n\n#ifdef __cplusplus\n inline void update(wuffs_base__rect_ie_u32 bounds,\n wuffs_base__flicks duration,\n uint64_t index,\n uint64_t io_position,\n wuffs_base__animation_blend blend,\n wuffs_base__animation_disposal disposal);\n inline wuffs_base__rect_ie_u32 bounds();\n inline uint32_t width();\n inline uint32_t height();\n inline wuffs_base__flicks duration();\n inline uint64_t index();\n inline uint64_t io_position();\n inline wuffs_base__animation_blend blend();\n inline wuffs_base__animation_disposal disposal();\n#endif // __cpluspl" +
"us\n\n} wuffs_base__frame_config;\n\nstatic inline void //\nwuffs_base__frame_config__update(wuffs_base__frame_config* c,\n wuffs_base__rect_ie_u32 bounds,\n wuffs_base__flicks duration,\n uint64_t index,\n uint64_t io_position,\n wuffs_base__animation_blend blend,\n wuffs_base__animation_disposal disposal) {\n if (!c) {\n return;\n }\n\n c->private_impl.bounds = bounds;\n c->private_impl.duration = duration;\n c->private_impl.index = index;\n c->private_impl.io_position = io_position;\n c->private_impl.blend = blend;\n c->private_impl.disposal = disposal;\n}\n\nstatic inline wuffs_base__rect_ie_u32 //\nwuffs_base__frame_config__bounds(wuffs_base__frame_config* c) {\n if (c) {\n return c->private_impl.bounds;\n }\n\n wuffs_base__rect_ie_u32 ret;\n ret.min_incl_x = 0;\n ret.min_incl_y = 0;\n ret.max_excl_x = 0;\n ret.max_excl_y = 0;" +
"\n return ret;\n}\n\nstatic inline uint32_t //\nwuffs_base__frame_config__width(wuffs_base__frame_config* c) {\n return c ? wuffs_base__rect_ie_u32__width(&c->private_impl.bounds) : 0;\n}\n\nstatic inline uint32_t //\nwuffs_base__frame_config__height(wuffs_base__frame_config* c) {\n return c ? wuffs_base__rect_ie_u32__height(&c->private_impl.bounds) : 0;\n}\n\n// wuffs_base__frame_config__duration returns the amount of time to display\n// this frame. Zero means to display forever - a still (non-animated) image.\nstatic inline wuffs_base__flicks //\nwuffs_base__frame_config__duration(wuffs_base__frame_config* c) {\n return c ? c->private_impl.duration : 0;\n}\n\n// wuffs_base__frame_config__index returns the index of this frame. The first\n// frame in an image has index 0, the second frame has index 1, and so on.\nstatic inline uint64_t //\nwuffs_base__frame_config__index(wuffs_base__frame_config* c) {\n return c ? c->private_impl.index : 0;\n}\n\n// wuffs_base__frame_config__io_position returns the I/O stream position before\n//" +
" the frame config.\nstatic inline uint64_t //\nwuffs_base__frame_config__io_position(wuffs_base__frame_config* c) {\n return c ? c->private_impl.io_position : 0;\n}\n\n// wuffs_base__frame_config__blend returns, for an animated image, how to blend\n// the transparent pixels of this frame with the existing canvas.\nstatic inline wuffs_base__animation_blend //\nwuffs_base__frame_config__blend(wuffs_base__frame_config* c) {\n return c ? c->private_impl.blend : 0;\n}\n\n// wuffs_base__frame_config__disposal returns, for an animated image, how to\n// dispose of this frame after displaying it.\nstatic inline wuffs_base__animation_disposal //\nwuffs_base__frame_config__disposal(wuffs_base__frame_config* c) {\n return c ? c->private_impl.disposal : 0;\n}\n\n#ifdef __cplusplus\n\ninline void //\nwuffs_base__frame_config::update(wuffs_base__rect_ie_u32 bounds,\n wuffs_base__flicks duration,\n uint64_t index,\n uint64_t io_position,\n " +
" wuffs_base__animation_blend blend,\n wuffs_base__animation_disposal disposal) {\n wuffs_base__frame_config__update(this, bounds, duration, index, io_position,\n blend, disposal);\n}\n\ninline wuffs_base__rect_ie_u32 //\nwuffs_base__frame_config::bounds() {\n return wuffs_base__frame_config__bounds(this);\n}\n\ninline uint32_t //\nwuffs_base__frame_config::width() {\n return wuffs_base__frame_config__width(this);\n}\n\ninline uint32_t //\nwuffs_base__frame_config::height() {\n return wuffs_base__frame_config__height(this);\n}\n\ninline wuffs_base__flicks //\nwuffs_base__frame_config::duration() {\n return wuffs_base__frame_config__duration(this);\n}\n\ninline uint64_t //\nwuffs_base__frame_config::index() {\n return wuffs_base__frame_config__index(this);\n}\n\ninline uint64_t //\nwuffs_base__frame_config::io_position() {\n return wuffs_base__frame_config__io_position(this);\n}\n\ninline wuffs_base__animation_blend //\nwuffs_base__frame_config::bl" +
"end() {\n return wuffs_base__frame_config__blend(this);\n}\n\ninline wuffs_base__animation_disposal //\nwuffs_base__frame_config::disposal() {\n return wuffs_base__frame_config__disposal(this);\n}\n\n#endif // __cplusplus\n\n" +
"" +
"// --------\n\ntypedef struct {\n wuffs_base__pixel_config pixcfg;\n\n // Do not access the private_impl's fields directly. There is no API/ABI\n // compatibility or safety guarantee if you do so.\n struct {\n wuffs_base__table_u8 planes[WUFFS_BASE__PIXEL_FORMAT__NUM_PLANES_MAX];\n // TODO: color spaces.\n } private_impl;\n\n#ifdef __cplusplus\n inline wuffs_base__status set_from_slice(wuffs_base__pixel_config* pixcfg,\n wuffs_base__slice_u8 pixbuf_memory);\n inline wuffs_base__slice_u8 palette();\n inline wuffs_base__pixel_format pixel_format();\n inline wuffs_base__table_u8 plane(uint32_t p);\n#endif // __cplusplus\n\n} wuffs_base__pixel_buffer;\n\nstatic inline wuffs_base__status //\nwuffs_base__pixel_buffer__set_from_slice(wuffs_base__pixel_buffer* b,\n wuffs_base__pixel_config* pixcfg,\n wuffs_base__slice_u8 pixbuf_memory) {\n if (!b) {\n return wuffs_base__error__bad_receiver;\n }\n memset" +
"(b, 0, sizeof(*b));\n if (!pixcfg) {\n return wuffs_base__error__bad_argument;\n }\n if (wuffs_base__pixel_format__is_planar(pixcfg->private_impl.pixfmt)) {\n // TODO: support planar pixel formats, concious of pixel subsampling.\n return wuffs_base__error__bad_argument;\n }\n uint32_t bits_per_pixel =\n wuffs_base__pixel_format__bits_per_pixel(pixcfg->private_impl.pixfmt);\n if ((bits_per_pixel == 0) || ((bits_per_pixel % 8) != 0)) {\n return wuffs_base__error__bad_argument;\n }\n uint64_t bytes_per_pixel = bits_per_pixel / 8;\n\n uint8_t* ptr = pixbuf_memory.ptr;\n uint64_t len = pixbuf_memory.len;\n if (wuffs_base__pixel_format__is_indexed(pixcfg->private_impl.pixfmt)) {\n // Split a 1024 byte chunk (256 palette entries × 4 bytes per entry) from\n // the start of pixbuf_memory. We split from the start, not the end, so\n // that the both chunks' pointers have the same alignment as the original\n // pointer, up to an alignment of 1024.\n if (len < 1024) {\n return wuffs_base__error__" +
"bad_argument_length_too_short;\n }\n wuffs_base__table_u8* tab =\n &b->private_impl.planes[WUFFS_BASE__PIXEL_FORMAT__INDEXED__COLOR_PLANE];\n tab->ptr = ptr;\n tab->width = 1024;\n tab->height = 1;\n tab->stride = 1024;\n ptr += 1024;\n len -= 1024;\n }\n\n uint64_t wh = ((uint64_t)pixcfg->private_impl.width) *\n ((uint64_t)pixcfg->private_impl.height);\n size_t width = (size_t)(pixcfg->private_impl.width);\n if ((wh > (UINT64_MAX / bytes_per_pixel)) ||\n (width > (SIZE_MAX / bytes_per_pixel))) {\n return wuffs_base__error__bad_argument;\n }\n wh *= bytes_per_pixel;\n width *= bytes_per_pixel;\n if (wh > len) {\n return wuffs_base__error__bad_argument_length_too_short;\n }\n\n b->pixcfg = *pixcfg;\n wuffs_base__table_u8* tab = &b->private_impl.planes[0];\n tab->ptr = ptr;\n tab->width = width;\n tab->height = pixcfg->private_impl.height;\n tab->stride = width;\n return NULL;\n}\n\n// wuffs_base__pixel_buffer__palette returns the palette color data. If\n// non-empty, it wi" +
"ll have length 1024.\nstatic inline wuffs_base__slice_u8 //\nwuffs_base__pixel_buffer__palette(wuffs_base__pixel_buffer* b) {\n if (b &&\n wuffs_base__pixel_format__is_indexed(b->pixcfg.private_impl.pixfmt)) {\n wuffs_base__table_u8* tab =\n &b->private_impl.planes[WUFFS_BASE__PIXEL_FORMAT__INDEXED__COLOR_PLANE];\n if ((tab->width == 1024) && (tab->height == 1)) {\n return wuffs_base__make_slice_u8(tab->ptr, 1024);\n }\n }\n return wuffs_base__make_slice_u8(NULL, 0);\n}\n\nstatic inline wuffs_base__pixel_format //\nwuffs_base__pixel_buffer__pixel_format(wuffs_base__pixel_buffer* b) {\n if (b) {\n return b->pixcfg.private_impl.pixfmt;\n }\n return WUFFS_BASE__PIXEL_FORMAT__INVALID;\n}\n\nstatic inline wuffs_base__table_u8 //\nwuffs_base__pixel_buffer__plane(wuffs_base__pixel_buffer* b, uint32_t p) {\n if (b && (p < WUFFS_BASE__PIXEL_FORMAT__NUM_PLANES_MAX)) {\n return b->private_impl.planes[p];\n }\n\n wuffs_base__table_u8 ret;\n ret.ptr = NULL;\n ret.width = 0;\n ret.height = 0;\n ret.stride =" +
" 0;\n return ret;\n}\n\n#ifdef __cplusplus\n\ninline wuffs_base__status //\nwuffs_base__pixel_buffer::set_from_slice(wuffs_base__pixel_config* pixcfg,\n wuffs_base__slice_u8 pixbuf_memory) {\n return wuffs_base__pixel_buffer__set_from_slice(this, pixcfg, pixbuf_memory);\n}\n\ninline wuffs_base__slice_u8 //\nwuffs_base__pixel_buffer::palette() {\n return wuffs_base__pixel_buffer__palette(this);\n}\n\ninline wuffs_base__pixel_format //\nwuffs_base__pixel_buffer::pixel_format() {\n return wuffs_base__pixel_buffer__pixel_format(this);\n}\n\ninline wuffs_base__table_u8 //\nwuffs_base__pixel_buffer::plane(uint32_t p) {\n return wuffs_base__pixel_buffer__plane(this, p);\n}\n\n#endif // __cplusplus\n\n" +
"" +
"// --------\n\ntypedef struct {\n // Do not access the private_impl's fields directly. There is no API/ABI\n // compatibility or safety guarantee if you do so.\n struct {\n uint8_t TODO;\n } private_impl;\n\n#ifdef __cplusplus\n#endif // __cplusplus\n\n} wuffs_base__decode_frame_options;\n\n#ifdef __cplusplus\n\n#endif // __cplusplus\n\n" +
"" +
"// --------\n\ntypedef struct {\n // Do not access the private_impl's fields directly. There is no API/ABI\n // compatibility or safety guarantee if you do so.\n struct {\n // TODO: should the func type take restrict pointers?\n uint64_t (*func)(wuffs_base__slice_u8 dst,\n wuffs_base__slice_u8 dst_palette,\n wuffs_base__slice_u8 src);\n } private_impl;\n\n#ifdef __cplusplus\n inline void prepare(wuffs_base__pixel_format dst_format,\n wuffs_base__slice_u8 dst_palette,\n wuffs_base__pixel_format src_format,\n wuffs_base__slice_u8 src_palette);\n inline uint64_t swizzle_packed(wuffs_base__slice_u8 dst,\n wuffs_base__slice_u8 dst_palette,\n wuffs_base__slice_u8 src);\n#endif // __cplusplus\n\n} wuffs_base__pixel_swizzler;\n\n// TODO: should prepare (both the C and C++ methods) return a status?\n\nvoid //\nwuffs_base__pixel_swizzler__prepare(wuffs_base__pixel_swi" +
"zzler* p,\n wuffs_base__pixel_format dst_format,\n wuffs_base__slice_u8 dst_palette,\n wuffs_base__pixel_format src_format,\n wuffs_base__slice_u8 src_palette);\n\nuint64_t //\nwuffs_base__pixel_swizzler__swizzle_packed(wuffs_base__pixel_swizzler* p,\n wuffs_base__slice_u8 dst,\n wuffs_base__slice_u8 dst_palette,\n wuffs_base__slice_u8 src);\n\n#ifdef __cplusplus\n\ninline void //\nwuffs_base__pixel_swizzler::prepare(wuffs_base__pixel_format dst_format,\n wuffs_base__slice_u8 dst_palette,\n wuffs_base__pixel_format src_format,\n wuffs_base__slice_u8 src_palette) {\n wuffs_base__pixel_swizzler__prepare(this, dst_format, dst_palette, src_format,\n " +
" src_palette);\n}\n\nuint64_t //\nwuffs_base__pixel_swizzler::swizzle_packed(wuffs_base__slice_u8 dst,\n wuffs_base__slice_u8 dst_palette,\n wuffs_base__slice_u8 src) {\n return wuffs_base__pixel_swizzler__swizzle_packed(this, dst, dst_palette,\n src);\n}\n\n#endif // __cplusplus\n\n" +
"" +
"// ---------------- Bureaucracy re -Wunused-function\n\nstatic inline void\nwuffs_base__acknowledge_potentially_unused_functions__image_public()\n WUFFS_BASE__POTENTIALLY_UNUSED;\n\nstatic inline void\nwuffs_base__acknowledge_potentially_unused_functions__image_public() {\n (void)(wuffs_base__frame_config__blend);\n (void)(wuffs_base__frame_config__bounds);\n (void)(wuffs_base__frame_config__disposal);\n (void)(wuffs_base__frame_config__duration);\n (void)(wuffs_base__frame_config__height);\n (void)(wuffs_base__frame_config__index);\n (void)(wuffs_base__frame_config__io_position);\n (void)(wuffs_base__frame_config__update);\n (void)(wuffs_base__frame_config__width);\n (void)(wuffs_base__image_config__first_frame_io_position);\n (void)(wuffs_base__image_config__first_frame_is_opaque);\n (void)(wuffs_base__image_config__invalidate);\n (void)(wuffs_base__image_config__is_valid);\n (void)(wuffs_base__image_config__set);\n (void)(wuffs_base__pixel_buffer__palette);\n (void)(wuffs_base__pixel_buffer__pixel_format);\n (" +
"void)(wuffs_base__pixel_buffer__plane);\n (void)(wuffs_base__pixel_buffer__set_from_slice);\n (void)(wuffs_base__pixel_config__bounds);\n (void)(wuffs_base__pixel_config__height);\n (void)(wuffs_base__pixel_config__invalidate);\n (void)(wuffs_base__pixel_config__is_valid);\n (void)(wuffs_base__pixel_config__pixbuf_len);\n (void)(wuffs_base__pixel_config__pixel_format);\n (void)(wuffs_base__pixel_config__pixel_subsampling);\n (void)(wuffs_base__pixel_config__set);\n (void)(wuffs_base__pixel_config__width);\n (void)(wuffs_base__pixel_format__bits_per_pixel);\n (void)(wuffs_base__pixel_format__is_indexed);\n (void)(wuffs_base__pixel_format__is_packed);\n (void)(wuffs_base__pixel_format__is_planar);\n (void)(wuffs_base__pixel_format__is_valid);\n (void)(wuffs_base__pixel_format__num_planes);\n (void)(wuffs_base__pixel_subsampling__bias_x);\n (void)(wuffs_base__pixel_subsampling__bias_y);\n (void)(wuffs_base__pixel_subsampling__shift_x);\n (void)(wuffs_base__pixel_subsampling__shift_y);\n (void)(wuffs_base__pixel_" +
"swizzler__prepare);\n (void)(wuffs_base__pixel_swizzler__swizzle_packed);\n}\n" +
""
const baseIOPrivateH = "" +
"// ---------------- I/O\n\nstatic inline bool //\nwuffs_base__io_buffer__is_valid(wuffs_base__io_buffer buf) {\n return (buf.data.ptr || (buf.data.len == 0)) &&\n (buf.data.len >= buf.meta.wi) && (buf.meta.wi >= buf.meta.ri);\n}\n\n// TODO: wuffs_base__io_reader__is_eof is no longer used by Wuffs per se, but\n// it might be handy to programs that use Wuffs. Either delete it, or promote\n// it to the public API.\n//\n// If making this function public (i.e. moving it to base-header.h), it also\n// needs to allow NULL (i.e. implicit, callee-calculated) mark/limit.\n\nstatic inline bool //\nwuffs_base__io_reader__is_eof(wuffs_base__io_reader o) {\n wuffs_base__io_buffer* buf = o.private_impl.buf;\n return buf && buf->meta.closed &&\n (buf->data.ptr + buf->meta.wi == o.private_impl.limit);\n}\n\nstatic inline bool //\nwuffs_base__io_reader__is_valid(wuffs_base__io_reader o) {\n wuffs_base__io_buffer* buf = o.private_impl.buf;\n // Note: if making this function public (i.e. moving it to base-header.h), it\n // also " +
"needs to allow NULL (i.e. implicit, callee-calculated) mark/limit.\n return buf ? ((buf->data.ptr <= o.private_impl.mark) &&\n (o.private_impl.mark <= o.private_impl.limit) &&\n (o.private_impl.limit <= buf->data.ptr + buf->data.len))\n : ((o.private_impl.mark == NULL) &&\n (o.private_impl.limit == NULL));\n}\n\nstatic inline bool //\nwuffs_base__io_writer__is_valid(wuffs_base__io_writer o) {\n wuffs_base__io_buffer* buf = o.private_impl.buf;\n // Note: if making this function public (i.e. moving it to base-header.h), it\n // also needs to allow NULL (i.e. implicit, callee-calculated) mark/limit.\n return buf ? ((buf->data.ptr <= o.private_impl.mark) &&\n (o.private_impl.mark <= o.private_impl.limit) &&\n (o.private_impl.limit <= buf->data.ptr + buf->data.len))\n : ((o.private_impl.mark == NULL) &&\n (o.private_impl.limit == NULL));\n}\n\nstatic inline uint32_t //\nwuffs_base__io_writer__copy_n_from_history(uin" +
"t8_t** ptr_iop_w,\n uint8_t* io0_w,\n uint8_t* io1_w,\n uint32_t length,\n uint32_t distance) {\n if (!distance) {\n return 0;\n }\n uint8_t* p = *ptr_iop_w;\n if ((size_t)(p - io0_w) < (size_t)(distance)) {\n return 0;\n }\n uint8_t* q = p - distance;\n size_t n = io1_w - p;\n if ((size_t)(length) > n) {\n length = n;\n } else {\n n = length;\n }\n // TODO: unrolling by 3 seems best for the std/deflate benchmarks, but that\n // is mostly because 3 is the minimum length for the deflate format. This\n // function implementation shouldn't overfit to that one format. Perhaps the\n // copy_n_from_history Wuffs method should also take an unroll hint argument,\n // and the cgen can look if that argument is the constant expression '3'.\n //\n // See also wuffs_base__io_writer__copy_n_from_history_fast below.\n //\n // Alternatively, or additionall" +
"y, have a sloppy_copy_n_from_history method\n // that copies 8 bytes at a time, possibly writing more than length bytes?\n for (; n >= 3; n -= 3) {\n *p++ = *q++;\n *p++ = *q++;\n *p++ = *q++;\n }\n for (; n; n--) {\n *p++ = *q++;\n }\n *ptr_iop_w = p;\n return length;\n}\n\n// wuffs_base__io_writer__copy_n_from_history_fast is like the\n// wuffs_base__io_writer__copy_n_from_history function above, but has stronger\n// pre-conditions. The caller needs to prove that:\n// - distance > 0\n// - distance <= (*ptr_iop_w - io0_w)\n// - length <= (io1_w - *ptr_iop_w)\nstatic inline uint32_t //\nwuffs_base__io_writer__copy_n_from_history_fast(uint8_t** ptr_iop_w,\n uint8_t* io0_w,\n uint8_t* io1_w,\n uint32_t length,\n uint32_t distance) {\n uint8_t* p = *ptr_iop_w;\n uint8_t* q = p - distance;\n uint32_t n = length;\n for (; n" +
" >= 3; n -= 3) {\n *p++ = *q++;\n *p++ = *q++;\n *p++ = *q++;\n }\n for (; n; n--) {\n *p++ = *q++;\n }\n *ptr_iop_w = p;\n return length;\n}\n\nstatic inline uint32_t //\nwuffs_base__io_writer__copy_n_from_reader(uint8_t** ptr_iop_w,\n uint8_t* io1_w,\n uint32_t length,\n uint8_t** ptr_iop_r,\n uint8_t* io1_r) {\n uint8_t* iop_w = *ptr_iop_w;\n size_t n = length;\n if (n > ((size_t)(io1_w - iop_w))) {\n n = io1_w - iop_w;\n }\n uint8_t* iop_r = *ptr_iop_r;\n if (n > ((size_t)(io1_r - iop_r))) {\n n = io1_r - iop_r;\n }\n if (n > 0) {\n memmove(iop_w, iop_r, n);\n *ptr_iop_w += n;\n *ptr_iop_r += n;\n }\n return n;\n}\n\nstatic inline uint64_t //\nwuffs_base__io_writer__copy_from_slice(uint8_t** ptr_iop_w,\n uint8_t* io1_w,\n wuffs_base__slice_u8 src) {\n uint8_t* iop" +
"_w = *ptr_iop_w;\n size_t n = src.len;\n if (n > ((size_t)(io1_w - iop_w))) {\n n = io1_w - iop_w;\n }\n if (n > 0) {\n memmove(iop_w, src.ptr, n);\n *ptr_iop_w += n;\n }\n return n;\n}\n\nstatic inline uint32_t //\nwuffs_base__io_writer__copy_n_from_slice(uint8_t** ptr_iop_w,\n uint8_t* io1_w,\n uint32_t length,\n wuffs_base__slice_u8 src) {\n uint8_t* iop_w = *ptr_iop_w;\n size_t n = src.len;\n if (n > length) {\n n = length;\n }\n if (n > ((size_t)(io1_w - iop_w))) {\n n = io1_w - iop_w;\n }\n if (n > 0) {\n memmove(iop_w, src.ptr, n);\n *ptr_iop_w += n;\n }\n return n;\n}\n\nstatic inline wuffs_base__empty_struct //\nwuffs_base__io_reader__set(wuffs_base__io_reader* o,\n wuffs_base__io_buffer* b,\n uint8_t** ptr_iop_r,\n uint8_t** ptr_io1_r,\n wuffs_base__slice_u8 data) {\n b->data = " +
"data;\n b->meta.wi = data.len;\n b->meta.ri = 0;\n b->meta.pos = 0;\n b->meta.closed = false;\n\n o->private_impl.buf = b;\n o->private_impl.mark = data.ptr;\n o->private_impl.limit = data.ptr + data.len;\n *ptr_iop_r = data.ptr;\n *ptr_io1_r = data.ptr + data.len;\n\n wuffs_base__empty_struct ret;\n ret.private_impl = 0;\n return ret;\n}\n\nstatic inline wuffs_base__empty_struct //\nwuffs_base__io_reader__set_limit(wuffs_base__io_reader* o,\n uint8_t* iop_r,\n uint64_t limit) {\n if (o && (((size_t)(o->private_impl.limit - iop_r)) > limit)) {\n o->private_impl.limit = iop_r + limit;\n }\n\n wuffs_base__empty_struct ret;\n ret.private_impl = 0;\n return ret;\n}\n\nstatic inline wuffs_base__empty_struct //\nwuffs_base__io_reader__set_mark(wuffs_base__io_reader* o, uint8_t* mark) {\n o->private_impl.mark = mark;\n\n wuffs_base__empty_struct ret;\n ret.private_impl = 0;\n return ret;\n}\n\nstatic inline wuffs_base__slice_u8 //\nwuffs_base__io_reader__take(uint8_" +
"t** ptr_iop_r, uint8_t* io1_r, uint64_t n) {\n if (n <= ((size_t)(io1_r - *ptr_iop_r))) {\n uint8_t* p = *ptr_iop_r;\n *ptr_iop_r += n;\n return wuffs_base__make_slice_u8(p, n);\n }\n return wuffs_base__make_slice_u8(NULL, 0);\n}\n\nstatic inline wuffs_base__empty_struct //\nwuffs_base__io_writer__set(wuffs_base__io_writer* o,\n wuffs_base__io_buffer* b,\n uint8_t** ptr_iop_w,\n uint8_t** ptr_io1_w,\n wuffs_base__slice_u8 data) {\n b->data = data;\n b->meta.wi = 0;\n b->meta.ri = 0;\n b->meta.pos = 0;\n b->meta.closed = false;\n\n o->private_impl.buf = b;\n o->private_impl.mark = data.ptr;\n o->private_impl.limit = data.ptr + data.len;\n *ptr_iop_w = data.ptr;\n *ptr_io1_w = data.ptr + data.len;\n\n wuffs_base__empty_struct ret;\n ret.private_impl = 0;\n return ret;\n}\n\nstatic inline wuffs_base__empty_struct //\nwuffs_base__io_writer__set_mark(wuffs_base__io_writer* o, uint8_t* mark) {\n o->private_impl.mark = " +
"mark;\n\n wuffs_base__empty_struct ret;\n ret.private_impl = 0;\n return ret;\n}\n\n" +
"" +
"// ---------------- I/O (Utility)\n\nstatic inline wuffs_base__io_buffer //\nwuffs_base__utility__null_io_buffer() {\n wuffs_base__io_buffer ret;\n ret.data.ptr = NULL;\n ret.data.len = 0;\n ret.meta.wi = 0;\n ret.meta.ri = 0;\n ret.meta.pos = 0;\n ret.meta.closed = false;\n return ret;\n}\n\nstatic inline wuffs_base__io_reader //\nwuffs_base__utility__null_io_reader() {\n wuffs_base__io_reader ret;\n ret.private_impl.buf = NULL;\n ret.private_impl.mark = NULL;\n ret.private_impl.limit = NULL;\n return ret;\n}\n\nstatic inline wuffs_base__io_writer //\nwuffs_base__utility__null_io_writer() {\n wuffs_base__io_writer ret;\n ret.private_impl.buf = NULL;\n ret.private_impl.mark = NULL;\n ret.private_impl.limit = NULL;\n return ret;\n}\n\n" +
"" +
"// ---------------- Bureaucracy re -Wunused-function\n\nstatic inline void\nwuffs_base__acknowledge_potentially_unused_functions__io_private()\n WUFFS_BASE__POTENTIALLY_UNUSED;\n\nstatic inline void\nwuffs_base__acknowledge_potentially_unused_functions__io_private() {\n (void)(wuffs_base__io_buffer__is_valid);\n (void)(wuffs_base__io_reader__is_eof);\n (void)(wuffs_base__io_reader__is_valid);\n (void)(wuffs_base__io_reader__set);\n (void)(wuffs_base__io_reader__set_limit);\n (void)(wuffs_base__io_reader__set_mark);\n (void)(wuffs_base__io_reader__take);\n (void)(wuffs_base__io_writer__copy_from_slice);\n (void)(wuffs_base__io_writer__copy_n_from_history);\n (void)(wuffs_base__io_writer__copy_n_from_history_fast);\n (void)(wuffs_base__io_writer__copy_n_from_reader);\n (void)(wuffs_base__io_writer__copy_n_from_slice);\n (void)(wuffs_base__io_writer__is_valid);\n (void)(wuffs_base__io_writer__set);\n (void)(wuffs_base__io_writer__set_mark);\n (void)(wuffs_base__utility__null_io_buffer);\n (void)(wuffs_base__utility_" +
"_null_io_reader);\n (void)(wuffs_base__utility__null_io_writer);\n}\n" +
""
const baseIOPublicH = "" +
"// ---------------- I/O\n\nstruct wuffs_base__io_buffer__struct;\n\ntypedef struct {\n // Do not access the private_impl's fields directly. There is no API/ABI\n // compatibility or safety guarantee if you do so.\n struct {\n struct wuffs_base__io_buffer__struct* buf;\n // The bounds values are typically NULL, when created by the Wuffs public\n // API. NULL means that the callee substitutes the implicit bounds derived\n // from buf.\n uint8_t* mark;\n uint8_t* limit;\n } private_impl;\n} wuffs_base__io_reader;\n\ntypedef struct {\n // Do not access the private_impl's fields directly. There is no API/ABI\n // compatibility or safety guarantee if you do so.\n struct {\n struct wuffs_base__io_buffer__struct* buf;\n // The bounds values are typically NULL, when created by the Wuffs public\n // API. NULL means that the callee substitutes the implicit bounds derived\n // from buf.\n uint8_t* mark;\n uint8_t* limit;\n } private_impl;\n} wuffs_base__io_writer;\n\n// wuffs_base__io_buffer_meta is the met" +
"adata for a wuffs_base__io_buffer's\n// data.\ntypedef struct {\n size_t wi; // Write index. Invariant: wi <= len.\n size_t ri; // Read index. Invariant: ri <= wi.\n uint64_t pos; // Position of the buffer start relative to the stream start.\n bool closed; // No further writes are expected.\n} wuffs_base__io_buffer_meta;\n\n// wuffs_base__io_buffer is a 1-dimensional buffer (a pointer and length) plus\n// additional metadata.\n//\n// A value with all fields zero is a valid, empty buffer.\ntypedef struct wuffs_base__io_buffer__struct {\n wuffs_base__slice_u8 data;\n wuffs_base__io_buffer_meta meta;\n\n#ifdef __cplusplus\n inline void compact();\n inline wuffs_base__io_reader reader();\n inline wuffs_base__io_writer writer();\n inline uint64_t reader_io_position();\n inline uint64_t writer_io_position();\n#endif // __cplusplus\n\n} wuffs_base__io_buffer;\n\n// wuffs_base__io_buffer__compact moves any written but unread bytes to the\n// start of the buffer.\nstatic inline void //\nwuffs_base__io_buffer__compact(wuffs" +
"_base__io_buffer* buf) {\n if (!buf || (buf->meta.ri == 0)) {\n return;\n }\n buf->meta.pos = wuffs_base__u64__sat_add(buf->meta.pos, buf->meta.ri);\n size_t n = buf->meta.wi - buf->meta.ri;\n if (n != 0) {\n memmove(buf->data.ptr, buf->data.ptr + buf->meta.ri, n);\n }\n buf->meta.wi = n;\n buf->meta.ri = 0;\n}\n\nstatic inline wuffs_base__io_reader //\nwuffs_base__io_buffer__reader(wuffs_base__io_buffer* buf) {\n wuffs_base__io_reader ret;\n ret.private_impl.buf = buf;\n ret.private_impl.mark = NULL;\n ret.private_impl.limit = NULL;\n return ret;\n}\n\nstatic inline wuffs_base__io_writer //\nwuffs_base__io_buffer__writer(wuffs_base__io_buffer* buf) {\n wuffs_base__io_writer ret;\n ret.private_impl.buf = buf;\n ret.private_impl.mark = NULL;\n ret.private_impl.limit = NULL;\n return ret;\n}\n\nstatic inline uint64_t //\nwuffs_base__io_buffer__reader_io_position(wuffs_base__io_buffer* buf) {\n return buf ? wuffs_base__u64__sat_add(buf->meta.pos, buf->meta.ri) : 0;\n}\n\nstatic inline uint64_t //\nwuffs_base__io_buffer_" +
"_writer_io_position(wuffs_base__io_buffer* buf) {\n return buf ? wuffs_base__u64__sat_add(buf->meta.pos, buf->meta.wi) : 0;\n}\n\n#ifdef __cplusplus\n\ninline void //\nwuffs_base__io_buffer__struct::compact() {\n wuffs_base__io_buffer__compact(this);\n}\n\ninline wuffs_base__io_reader //\nwuffs_base__io_buffer__struct::reader() {\n return wuffs_base__io_buffer__reader(this);\n}\n\ninline wuffs_base__io_writer //\nwuffs_base__io_buffer__struct::writer() {\n return wuffs_base__io_buffer__writer(this);\n}\n\ninline uint64_t //\nwuffs_base__io_buffer__struct::reader_io_position() {\n return wuffs_base__io_buffer__reader_io_position(this);\n}\n\ninline uint64_t //\nwuffs_base__io_buffer__struct::writer_io_position() {\n return wuffs_base__io_buffer__writer_io_position(this);\n}\n\n#endif // __cplusplus\n\n" +
"" +
"// ---------------- Bureaucracy re -Wunused-function\n\nstatic inline void\nwuffs_base__acknowledge_potentially_unused_functions__io_public()\n WUFFS_BASE__POTENTIALLY_UNUSED;\n\nstatic inline void\nwuffs_base__acknowledge_potentially_unused_functions__io_public() {\n (void)(wuffs_base__io_buffer__compact);\n (void)(wuffs_base__io_buffer__reader);\n (void)(wuffs_base__io_buffer__reader_io_position);\n (void)(wuffs_base__io_buffer__writer);\n (void)(wuffs_base__io_buffer__writer_io_position);\n}\n" +
""
const baseRangePrivateH = "" +
"// ---------------- Ranges and Rects\n\nstatic inline uint32_t //\nwuffs_base__range_ii_u32__get_min_incl(const wuffs_base__range_ii_u32* r) {\n return r->min_incl;\n}\n\nstatic inline uint32_t //\nwuffs_base__range_ii_u32__get_max_incl(const wuffs_base__range_ii_u32* r) {\n return r->max_incl;\n}\n\nstatic inline uint32_t //\nwuffs_base__range_ie_u32__get_min_incl(const wuffs_base__range_ie_u32* r) {\n return r->min_incl;\n}\n\nstatic inline uint32_t //\nwuffs_base__range_ie_u32__get_max_excl(const wuffs_base__range_ie_u32* r) {\n return r->max_excl;\n}\n\nstatic inline uint64_t //\nwuffs_base__range_ii_u64__get_min_incl(const wuffs_base__range_ii_u64* r) {\n return r->min_incl;\n}\n\nstatic inline uint64_t //\nwuffs_base__range_ii_u64__get_max_incl(const wuffs_base__range_ii_u64* r) {\n return r->max_incl;\n}\n\nstatic inline uint64_t //\nwuffs_base__range_ie_u64__get_min_incl(const wuffs_base__range_ie_u64* r) {\n return r->min_incl;\n}\n\nstatic inline uint64_t //\nwuffs_base__range_ie_u64__get_max_excl(const wuffs_base__range_" +
"ie_u64* r) {\n return r->max_excl;\n}\n\n" +
"" +
"// ---------------- Ranges and Rects (Utility)\n\nstatic inline wuffs_base__range_ii_u32 //\nwuffs_base__utility__make_range_ii_u32(uint32_t min_incl, uint32_t max_incl) {\n wuffs_base__range_ii_u32 ret;\n ret.min_incl = min_incl;\n ret.max_incl = max_incl;\n return ret;\n}\n\nstatic inline wuffs_base__range_ie_u32 //\nwuffs_base__utility__make_range_ie_u32(uint32_t min_incl, uint32_t max_excl) {\n wuffs_base__range_ie_u32 ret;\n ret.min_incl = min_incl;\n ret.max_excl = max_excl;\n return ret;\n}\n\nstatic inline wuffs_base__range_ii_u64 //\nwuffs_base__utility__make_range_ii_u64(uint64_t min_incl, uint64_t max_incl) {\n wuffs_base__range_ii_u64 ret;\n ret.min_incl = min_incl;\n ret.max_incl = max_incl;\n return ret;\n}\n\nstatic inline wuffs_base__range_ie_u64 //\nwuffs_base__utility__make_range_ie_u64(uint64_t min_incl, uint64_t max_excl) {\n wuffs_base__range_ie_u64 ret;\n ret.min_incl = min_incl;\n ret.max_excl = max_excl;\n return ret;\n}\n\nstatic inline wuffs_base__rect_ii_u32 //\nwuffs_base__utility__make_rect_ii_" +
"u32(uint32_t min_incl_x,\n uint32_t min_incl_y,\n uint32_t max_incl_x,\n uint32_t max_incl_y) {\n wuffs_base__rect_ii_u32 ret;\n ret.min_incl_x = min_incl_x;\n ret.min_incl_y = min_incl_y;\n ret.max_incl_x = max_incl_x;\n ret.max_incl_y = max_incl_y;\n return ret;\n}\n\nstatic inline wuffs_base__rect_ie_u32 //\nwuffs_base__utility__make_rect_ie_u32(uint32_t min_incl_x,\n uint32_t min_incl_y,\n uint32_t max_excl_x,\n uint32_t max_excl_y) {\n wuffs_base__rect_ie_u32 ret;\n ret.min_incl_x = min_incl_x;\n ret.min_incl_y = min_incl_y;\n ret.max_excl_x = max_excl_x;\n ret.max_excl_y = max_excl_y;\n return ret;\n}\n\n" +
"" +
"// ---------------- Bureaucracy re -Wunused-function\n\nstatic inline void\nwuffs_base__acknowledge_potentially_unused_functions__range_private()\n WUFFS_BASE__POTENTIALLY_UNUSED;\n\nstatic inline void\nwuffs_base__acknowledge_potentially_unused_functions__range_private() {\n (void)(wuffs_base__range_ie_u32__get_max_excl);\n (void)(wuffs_base__range_ie_u32__get_min_incl);\n (void)(wuffs_base__range_ie_u64__get_max_excl);\n (void)(wuffs_base__range_ie_u64__get_min_incl);\n (void)(wuffs_base__range_ii_u32__get_max_incl);\n (void)(wuffs_base__range_ii_u32__get_min_incl);\n (void)(wuffs_base__range_ii_u64__get_max_incl);\n (void)(wuffs_base__range_ii_u64__get_min_incl);\n (void)(wuffs_base__utility__make_range_ie_u32);\n (void)(wuffs_base__utility__make_range_ie_u64);\n (void)(wuffs_base__utility__make_range_ii_u32);\n (void)(wuffs_base__utility__make_range_ii_u64);\n (void)(wuffs_base__utility__make_rect_ie_u32);\n (void)(wuffs_base__utility__make_rect_ii_u32);\n}\n" +
""
const baseRangePublicH = "" +
"// ---------------- Ranges and Rects\n\n// Ranges are either inclusive (\"range_ii\") or exclusive (\"range_ie\") on the\n// high end. Both the \"ii\" and \"ie\" flavors are useful in practice.\n//\n// The \"ei\" and \"ee\" flavors also exist in theory, but aren't widely used. In\n// Wuffs, the low end is always inclusive.\n//\n// The \"ii\" (closed interval) flavor is useful when refining e.g. \"the set of\n// all uint32_t values\" to a contiguous subset: \"uint32_t values in the closed\n// interval [M, N]\", for uint32_t values M and N. An unrefined type (in other\n// words, the set of all uint32_t values) is not representable in the \"ie\"\n// flavor because if N equals ((1<<32) - 1) then (N + 1) will overflow.\n//\n// On the other hand, the \"ie\" (half-open interval) flavor is recommended by\n// Dijkstra's \"Why numbering should start at zero\" at\n// http://www.cs.utexas.edu/users/EWD/ewd08xx/EWD831.PDF and a further\n// discussion of motivating rationale is at\n// https://www.quora.com/Why-are-Python-ranges-half-open-exclusive-instead-of-close" +
"d-inclusive\n//\n// For example, with \"ie\", the number of elements in \"uint32_t values in the\n// half-open interval [M, N)\" is equal to max(0, N-M). Furthermore, that number\n// of elements (in one dimension, a length, in two dimensions, a width or\n// height) is itself representable as a uint32_t without overflow, again for\n// uint32_t values M and N. In the contrasting \"ii\" flavor, the length of the\n// closed interval [0, (1<<32) - 1] is 1<<32, which cannot be represented as a\n// uint32_t. In Wuffs, because of this potential overflow, the \"ie\" flavor has\n// length / width / height methods, but the \"ii\" flavor does not.\n//\n// It is valid for min > max (for range_ii) or for min >= max (for range_ie),\n// in which case the range is empty. There are multiple representations of an\n// empty range.\n\ntypedef struct wuffs_base__range_ii_u32__struct {\n uint32_t min_incl;\n uint32_t max_incl;\n\n#ifdef __cplusplus\n inline bool is_empty();\n inline bool equals(wuffs_base__range_ii_u32__struct s);\n inline wuffs_base__range_" +
"ii_u32__struct intersect(\n wuffs_base__range_ii_u32__struct s);\n inline wuffs_base__range_ii_u32__struct unite(\n wuffs_base__range_ii_u32__struct s);\n inline bool contains(uint32_t x);\n inline bool contains_range(wuffs_base__range_ii_u32__struct s);\n#endif // __cplusplus\n\n} wuffs_base__range_ii_u32;\n\nstatic inline bool //\nwuffs_base__range_ii_u32__is_empty(wuffs_base__range_ii_u32* r) {\n return r->min_incl > r->max_incl;\n}\n\nstatic inline bool //\nwuffs_base__range_ii_u32__equals(wuffs_base__range_ii_u32* r,\n wuffs_base__range_ii_u32 s) {\n return (r->min_incl == s.min_incl && r->max_incl == s.max_incl) ||\n (wuffs_base__range_ii_u32__is_empty(r) &&\n wuffs_base__range_ii_u32__is_empty(&s));\n}\n\nstatic inline wuffs_base__range_ii_u32 //\nwuffs_base__range_ii_u32__intersect(wuffs_base__range_ii_u32* r,\n wuffs_base__range_ii_u32 s) {\n wuffs_base__range_ii_u32 t;\n t.min_incl = wuffs_base__u32__max(r->min_incl, s.min" +
"_incl);\n t.max_incl = wuffs_base__u32__min(r->max_incl, s.max_incl);\n return t;\n}\n\nstatic inline wuffs_base__range_ii_u32 //\nwuffs_base__range_ii_u32__unite(wuffs_base__range_ii_u32* r,\n wuffs_base__range_ii_u32 s) {\n if (wuffs_base__range_ii_u32__is_empty(r)) {\n return s;\n }\n if (wuffs_base__range_ii_u32__is_empty(&s)) {\n return *r;\n }\n wuffs_base__range_ii_u32 t;\n t.min_incl = wuffs_base__u32__min(r->min_incl, s.min_incl);\n t.max_incl = wuffs_base__u32__max(r->max_incl, s.max_incl);\n return t;\n}\n\nstatic inline bool //\nwuffs_base__range_ii_u32__contains(wuffs_base__range_ii_u32* r, uint32_t x) {\n return (r->min_incl <= x) && (x <= r->max_incl);\n}\n\nstatic inline bool //\nwuffs_base__range_ii_u32__contains_range(wuffs_base__range_ii_u32* r,\n wuffs_base__range_ii_u32 s) {\n return wuffs_base__range_ii_u32__equals(\n &s, wuffs_base__range_ii_u32__intersect(r, s));\n}\n\n#ifdef __cplusplus\n\ninline bool //\nwuffs_base__range" +
"_ii_u32::is_empty() {\n return wuffs_base__range_ii_u32__is_empty(this);\n}\n\ninline bool //\nwuffs_base__range_ii_u32::equals(wuffs_base__range_ii_u32 s) {\n return wuffs_base__range_ii_u32__equals(this, s);\n}\n\ninline wuffs_base__range_ii_u32 //\nwuffs_base__range_ii_u32::intersect(wuffs_base__range_ii_u32 s) {\n return wuffs_base__range_ii_u32__intersect(this, s);\n}\n\ninline wuffs_base__range_ii_u32 //\nwuffs_base__range_ii_u32::unite(wuffs_base__range_ii_u32 s) {\n return wuffs_base__range_ii_u32__unite(this, s);\n}\n\ninline bool //\nwuffs_base__range_ii_u32::contains(uint32_t x) {\n return wuffs_base__range_ii_u32__contains(this, x);\n}\n\ninline bool //\nwuffs_base__range_ii_u32::contains_range(wuffs_base__range_ii_u32 s) {\n return wuffs_base__range_ii_u32__contains_range(this, s);\n}\n\n#endif // __cplusplus\n\n" +
"" +
"// --------\n\ntypedef struct wuffs_base__range_ie_u32__struct {\n uint32_t min_incl;\n uint32_t max_excl;\n\n#ifdef __cplusplus\n inline bool is_empty();\n inline bool equals(wuffs_base__range_ie_u32__struct s);\n inline wuffs_base__range_ie_u32__struct intersect(\n wuffs_base__range_ie_u32__struct s);\n inline wuffs_base__range_ie_u32__struct unite(\n wuffs_base__range_ie_u32__struct s);\n inline bool contains(uint32_t x);\n inline bool contains_range(wuffs_base__range_ie_u32__struct s);\n inline uint32_t length();\n#endif // __cplusplus\n\n} wuffs_base__range_ie_u32;\n\nstatic inline bool //\nwuffs_base__range_ie_u32__is_empty(wuffs_base__range_ie_u32* r) {\n return r->min_incl >= r->max_excl;\n}\n\nstatic inline bool //\nwuffs_base__range_ie_u32__equals(wuffs_base__range_ie_u32* r,\n wuffs_base__range_ie_u32 s) {\n return (r->min_incl == s.min_incl && r->max_excl == s.max_excl) ||\n (wuffs_base__range_ie_u32__is_empty(r) &&\n wuffs_base__range_ie_u32__is_empty(&s" +
"));\n}\n\nstatic inline wuffs_base__range_ie_u32 //\nwuffs_base__range_ie_u32__intersect(wuffs_base__range_ie_u32* r,\n wuffs_base__range_ie_u32 s) {\n wuffs_base__range_ie_u32 t;\n t.min_incl = wuffs_base__u32__max(r->min_incl, s.min_incl);\n t.max_excl = wuffs_base__u32__min(r->max_excl, s.max_excl);\n return t;\n}\n\nstatic inline wuffs_base__range_ie_u32 //\nwuffs_base__range_ie_u32__unite(wuffs_base__range_ie_u32* r,\n wuffs_base__range_ie_u32 s) {\n if (wuffs_base__range_ie_u32__is_empty(r)) {\n return s;\n }\n if (wuffs_base__range_ie_u32__is_empty(&s)) {\n return *r;\n }\n wuffs_base__range_ie_u32 t;\n t.min_incl = wuffs_base__u32__min(r->min_incl, s.min_incl);\n t.max_excl = wuffs_base__u32__max(r->max_excl, s.max_excl);\n return t;\n}\n\nstatic inline bool //\nwuffs_base__range_ie_u32__contains(wuffs_base__range_ie_u32* r, uint32_t x) {\n return (r->min_incl <= x) && (x < r->max_excl);\n}\n\nstatic inline bool //\nwuffs_base__range_ie_u32__cont" +
"ains_range(wuffs_base__range_ie_u32* r,\n wuffs_base__range_ie_u32 s) {\n return wuffs_base__range_ie_u32__equals(\n &s, wuffs_base__range_ie_u32__intersect(r, s));\n}\n\nstatic inline uint32_t //\nwuffs_base__range_ie_u32__length(wuffs_base__range_ie_u32* r) {\n return wuffs_base__u32__sat_sub(r->max_excl, r->min_incl);\n}\n\n#ifdef __cplusplus\n\ninline bool //\nwuffs_base__range_ie_u32::is_empty() {\n return wuffs_base__range_ie_u32__is_empty(this);\n}\n\ninline bool //\nwuffs_base__range_ie_u32::equals(wuffs_base__range_ie_u32 s) {\n return wuffs_base__range_ie_u32__equals(this, s);\n}\n\ninline wuffs_base__range_ie_u32 //\nwuffs_base__range_ie_u32::intersect(wuffs_base__range_ie_u32 s) {\n return wuffs_base__range_ie_u32__intersect(this, s);\n}\n\ninline wuffs_base__range_ie_u32 //\nwuffs_base__range_ie_u32::unite(wuffs_base__range_ie_u32 s) {\n return wuffs_base__range_ie_u32__unite(this, s);\n}\n\ninline bool //\nwuffs_base__range_ie_u32::contains(uint32_t x) {\n return wuffs_bas" +
"e__range_ie_u32__contains(this, x);\n}\n\ninline bool //\nwuffs_base__range_ie_u32::contains_range(wuffs_base__range_ie_u32 s) {\n return wuffs_base__range_ie_u32__contains_range(this, s);\n}\n\ninline uint32_t //\nwuffs_base__range_ie_u32::length() {\n return wuffs_base__range_ie_u32__length(this);\n}\n\n#endif // __cplusplus\n\n" +
"" +
"// --------\n\ntypedef struct wuffs_base__range_ii_u64__struct {\n uint64_t min_incl;\n uint64_t max_incl;\n\n#ifdef __cplusplus\n inline bool is_empty();\n inline bool equals(wuffs_base__range_ii_u64__struct s);\n inline wuffs_base__range_ii_u64__struct intersect(\n wuffs_base__range_ii_u64__struct s);\n inline wuffs_base__range_ii_u64__struct unite(\n wuffs_base__range_ii_u64__struct s);\n inline bool contains(uint64_t x);\n inline bool contains_range(wuffs_base__range_ii_u64__struct s);\n#endif // __cplusplus\n\n} wuffs_base__range_ii_u64;\n\nstatic inline bool //\nwuffs_base__range_ii_u64__is_empty(wuffs_base__range_ii_u64* r) {\n return r->min_incl > r->max_incl;\n}\n\nstatic inline bool //\nwuffs_base__range_ii_u64__equals(wuffs_base__range_ii_u64* r,\n wuffs_base__range_ii_u64 s) {\n return (r->min_incl == s.min_incl && r->max_incl == s.max_incl) ||\n (wuffs_base__range_ii_u64__is_empty(r) &&\n wuffs_base__range_ii_u64__is_empty(&s));\n}\n\nstatic inline wuffs_ba" +
"se__range_ii_u64 //\nwuffs_base__range_ii_u64__intersect(wuffs_base__range_ii_u64* r,\n wuffs_base__range_ii_u64 s) {\n wuffs_base__range_ii_u64 t;\n t.min_incl = wuffs_base__u64__max(r->min_incl, s.min_incl);\n t.max_incl = wuffs_base__u64__min(r->max_incl, s.max_incl);\n return t;\n}\n\nstatic inline wuffs_base__range_ii_u64 //\nwuffs_base__range_ii_u64__unite(wuffs_base__range_ii_u64* r,\n wuffs_base__range_ii_u64 s) {\n if (wuffs_base__range_ii_u64__is_empty(r)) {\n return s;\n }\n if (wuffs_base__range_ii_u64__is_empty(&s)) {\n return *r;\n }\n wuffs_base__range_ii_u64 t;\n t.min_incl = wuffs_base__u64__min(r->min_incl, s.min_incl);\n t.max_incl = wuffs_base__u64__max(r->max_incl, s.max_incl);\n return t;\n}\n\nstatic inline bool //\nwuffs_base__range_ii_u64__contains(wuffs_base__range_ii_u64* r, uint64_t x) {\n return (r->min_incl <= x) && (x <= r->max_incl);\n}\n\nstatic inline bool //\nwuffs_base__range_ii_u64__contains_range(wuffs_base__range" +
"_ii_u64* r,\n wuffs_base__range_ii_u64 s) {\n return wuffs_base__range_ii_u64__equals(\n &s, wuffs_base__range_ii_u64__intersect(r, s));\n}\n\n#ifdef __cplusplus\n\ninline bool //\nwuffs_base__range_ii_u64::is_empty() {\n return wuffs_base__range_ii_u64__is_empty(this);\n}\n\ninline bool //\nwuffs_base__range_ii_u64::equals(wuffs_base__range_ii_u64 s) {\n return wuffs_base__range_ii_u64__equals(this, s);\n}\n\ninline wuffs_base__range_ii_u64 //\nwuffs_base__range_ii_u64::intersect(wuffs_base__range_ii_u64 s) {\n return wuffs_base__range_ii_u64__intersect(this, s);\n}\n\ninline wuffs_base__range_ii_u64 //\nwuffs_base__range_ii_u64::unite(wuffs_base__range_ii_u64 s) {\n return wuffs_base__range_ii_u64__unite(this, s);\n}\n\ninline bool //\nwuffs_base__range_ii_u64::contains(uint64_t x) {\n return wuffs_base__range_ii_u64__contains(this, x);\n}\n\ninline bool //\nwuffs_base__range_ii_u64::contains_range(wuffs_base__range_ii_u64 s) {\n return wuffs_base__range_ii_u64__contains_range(this, s" +
");\n}\n\n#endif // __cplusplus\n\n" +
"" +
"// --------\n\ntypedef struct wuffs_base__range_ie_u64__struct {\n uint64_t min_incl;\n uint64_t max_excl;\n\n#ifdef __cplusplus\n inline bool is_empty();\n inline bool equals(wuffs_base__range_ie_u64__struct s);\n inline wuffs_base__range_ie_u64__struct intersect(\n wuffs_base__range_ie_u64__struct s);\n inline wuffs_base__range_ie_u64__struct unite(\n wuffs_base__range_ie_u64__struct s);\n inline bool contains(uint64_t x);\n inline bool contains_range(wuffs_base__range_ie_u64__struct s);\n inline uint64_t length();\n#endif // __cplusplus\n\n} wuffs_base__range_ie_u64;\n\nstatic inline bool //\nwuffs_base__range_ie_u64__is_empty(wuffs_base__range_ie_u64* r) {\n return r->min_incl >= r->max_excl;\n}\n\nstatic inline bool //\nwuffs_base__range_ie_u64__equals(wuffs_base__range_ie_u64* r,\n wuffs_base__range_ie_u64 s) {\n return (r->min_incl == s.min_incl && r->max_excl == s.max_excl) ||\n (wuffs_base__range_ie_u64__is_empty(r) &&\n wuffs_base__range_ie_u64__is_empty(&s" +
"));\n}\n\nstatic inline wuffs_base__range_ie_u64 //\nwuffs_base__range_ie_u64__intersect(wuffs_base__range_ie_u64* r,\n wuffs_base__range_ie_u64 s) {\n wuffs_base__range_ie_u64 t;\n t.min_incl = wuffs_base__u64__max(r->min_incl, s.min_incl);\n t.max_excl = wuffs_base__u64__min(r->max_excl, s.max_excl);\n return t;\n}\n\nstatic inline wuffs_base__range_ie_u64 //\nwuffs_base__range_ie_u64__unite(wuffs_base__range_ie_u64* r,\n wuffs_base__range_ie_u64 s) {\n if (wuffs_base__range_ie_u64__is_empty(r)) {\n return s;\n }\n if (wuffs_base__range_ie_u64__is_empty(&s)) {\n return *r;\n }\n wuffs_base__range_ie_u64 t;\n t.min_incl = wuffs_base__u64__min(r->min_incl, s.min_incl);\n t.max_excl = wuffs_base__u64__max(r->max_excl, s.max_excl);\n return t;\n}\n\nstatic inline bool //\nwuffs_base__range_ie_u64__contains(wuffs_base__range_ie_u64* r, uint64_t x) {\n return (r->min_incl <= x) && (x < r->max_excl);\n}\n\nstatic inline bool //\nwuffs_base__range_ie_u64__cont" +
"ains_range(wuffs_base__range_ie_u64* r,\n wuffs_base__range_ie_u64 s) {\n return wuffs_base__range_ie_u64__equals(\n &s, wuffs_base__range_ie_u64__intersect(r, s));\n}\n\nstatic inline uint64_t //\nwuffs_base__range_ie_u64__length(wuffs_base__range_ie_u64* r) {\n return wuffs_base__u64__sat_sub(r->max_excl, r->min_incl);\n}\n\n#ifdef __cplusplus\n\ninline bool //\nwuffs_base__range_ie_u64::is_empty() {\n return wuffs_base__range_ie_u64__is_empty(this);\n}\n\ninline bool //\nwuffs_base__range_ie_u64::equals(wuffs_base__range_ie_u64 s) {\n return wuffs_base__range_ie_u64__equals(this, s);\n}\n\ninline wuffs_base__range_ie_u64 //\nwuffs_base__range_ie_u64::intersect(wuffs_base__range_ie_u64 s) {\n return wuffs_base__range_ie_u64__intersect(this, s);\n}\n\ninline wuffs_base__range_ie_u64 //\nwuffs_base__range_ie_u64::unite(wuffs_base__range_ie_u64 s) {\n return wuffs_base__range_ie_u64__unite(this, s);\n}\n\ninline bool //\nwuffs_base__range_ie_u64::contains(uint64_t x) {\n return wuffs_bas" +
"e__range_ie_u64__contains(this, x);\n}\n\ninline bool //\nwuffs_base__range_ie_u64::contains_range(wuffs_base__range_ie_u64 s) {\n return wuffs_base__range_ie_u64__contains_range(this, s);\n}\n\ninline uint64_t //\nwuffs_base__range_ie_u64::length() {\n return wuffs_base__range_ie_u64__length(this);\n}\n\n#endif // __cplusplus\n\n" +
"" +
"// --------\n\n// wuffs_base__rect_ii_u32 is a rectangle (a 2-dimensional range) on the\n// integer grid. The \"ii\" means that the bounds are inclusive on the low end\n// and inclusive on the high end. It contains all points (x, y) such that\n// ((min_incl_x <= x) && (x <= max_incl_x)) and likewise for y.\n//\n// It is valid for min > max, in which case the rectangle is empty. There are\n// multiple representations of an empty rectangle.\n//\n// The X and Y axes increase right and down.\ntypedef struct wuffs_base__rect_ii_u32__struct {\n uint32_t min_incl_x;\n uint32_t min_incl_y;\n uint32_t max_incl_x;\n uint32_t max_incl_y;\n\n#ifdef __cplusplus\n inline bool is_empty();\n inline bool equals(wuffs_base__rect_ii_u32__struct s);\n inline wuffs_base__rect_ii_u32__struct intersect(\n wuffs_base__rect_ii_u32__struct s);\n inline wuffs_base__rect_ii_u32__struct unite(\n wuffs_base__rect_ii_u32__struct s);\n inline bool contains(uint32_t x, uint32_t y);\n inline bool contains_rect(wuffs_base__rect_ii_u32__struct s);\n#en" +
"dif // __cplusplus\n\n} wuffs_base__rect_ii_u32;\n\nstatic inline bool //\nwuffs_base__rect_ii_u32__is_empty(wuffs_base__rect_ii_u32* r) {\n return (r->min_incl_x > r->max_incl_x) || (r->min_incl_y > r->max_incl_y);\n}\n\nstatic inline bool //\nwuffs_base__rect_ii_u32__equals(wuffs_base__rect_ii_u32* r,\n wuffs_base__rect_ii_u32 s) {\n return (r->min_incl_x == s.min_incl_x && r->min_incl_y == s.min_incl_y &&\n r->max_incl_x == s.max_incl_x && r->max_incl_y == s.max_incl_y) ||\n (wuffs_base__rect_ii_u32__is_empty(r) &&\n wuffs_base__rect_ii_u32__is_empty(&s));\n}\n\nstatic inline wuffs_base__rect_ii_u32 //\nwuffs_base__rect_ii_u32__intersect(wuffs_base__rect_ii_u32* r,\n wuffs_base__rect_ii_u32 s) {\n wuffs_base__rect_ii_u32 t;\n t.min_incl_x = wuffs_base__u32__max(r->min_incl_x, s.min_incl_x);\n t.min_incl_y = wuffs_base__u32__max(r->min_incl_y, s.min_incl_y);\n t.max_incl_x = wuffs_base__u32__min(r->max_incl_x, s.max_incl_x);\n t.ma" +
"x_incl_y = wuffs_base__u32__min(r->max_incl_y, s.max_incl_y);\n return t;\n}\n\nstatic inline wuffs_base__rect_ii_u32 //\nwuffs_base__rect_ii_u32__unite(wuffs_base__rect_ii_u32* r,\n wuffs_base__rect_ii_u32 s) {\n if (wuffs_base__rect_ii_u32__is_empty(r)) {\n return s;\n }\n if (wuffs_base__rect_ii_u32__is_empty(&s)) {\n return *r;\n }\n wuffs_base__rect_ii_u32 t;\n t.min_incl_x = wuffs_base__u32__min(r->min_incl_x, s.min_incl_x);\n t.min_incl_y = wuffs_base__u32__min(r->min_incl_y, s.min_incl_y);\n t.max_incl_x = wuffs_base__u32__max(r->max_incl_x, s.max_incl_x);\n t.max_incl_y = wuffs_base__u32__max(r->max_incl_y, s.max_incl_y);\n return t;\n}\n\nstatic inline bool //\nwuffs_base__rect_ii_u32__contains(wuffs_base__rect_ii_u32* r,\n uint32_t x,\n uint32_t y) {\n return (r->min_incl_x <= x) && (x <= r->max_incl_x) && (r->min_incl_y <= y) &&\n (y <= r->max_incl_y);\n}\n\nstatic inline bool //\nwuffs_base__rect_ii_u32" +
"__contains_rect(wuffs_base__rect_ii_u32* r,\n wuffs_base__rect_ii_u32 s) {\n return wuffs_base__rect_ii_u32__equals(\n &s, wuffs_base__rect_ii_u32__intersect(r, s));\n}\n\n#ifdef __cplusplus\n\ninline bool //\nwuffs_base__rect_ii_u32::is_empty() {\n return wuffs_base__rect_ii_u32__is_empty(this);\n}\n\ninline bool //\nwuffs_base__rect_ii_u32::equals(wuffs_base__rect_ii_u32 s) {\n return wuffs_base__rect_ii_u32__equals(this, s);\n}\n\ninline wuffs_base__rect_ii_u32 //\nwuffs_base__rect_ii_u32::intersect(wuffs_base__rect_ii_u32 s) {\n return wuffs_base__rect_ii_u32__intersect(this, s);\n}\n\ninline wuffs_base__rect_ii_u32 //\nwuffs_base__rect_ii_u32::unite(wuffs_base__rect_ii_u32 s) {\n return wuffs_base__rect_ii_u32__unite(this, s);\n}\n\ninline bool //\nwuffs_base__rect_ii_u32::contains(uint32_t x, uint32_t y) {\n return wuffs_base__rect_ii_u32__contains(this, x, y);\n}\n\ninline bool //\nwuffs_base__rect_ii_u32::contains_rect(wuffs_base__rect_ii_u32 s) {\n return wuffs_base__rect_ii_u32_" +
"_contains_rect(this, s);\n}\n\n#endif // __cplusplus\n\n" +
"" +
"// --------\n\n// wuffs_base__rect_ie_u32 is a rectangle (a 2-dimensional range) on the\n// integer grid. The \"ie\" means that the bounds are inclusive on the low end\n// and exclusive on the high end. It contains all points (x, y) such that\n// ((min_incl_x <= x) && (x < max_excl_x)) and likewise for y.\n//\n// It is valid for min >= max, in which case the rectangle is empty. There are\n// multiple representations of an empty rectangle, including a value with all\n// fields zero.\n//\n// The X and Y axes increase right and down.\ntypedef struct wuffs_base__rect_ie_u32__struct {\n uint32_t min_incl_x;\n uint32_t min_incl_y;\n uint32_t max_excl_x;\n uint32_t max_excl_y;\n\n#ifdef __cplusplus\n inline bool is_empty();\n inline bool equals(wuffs_base__rect_ie_u32__struct s);\n inline wuffs_base__rect_ie_u32__struct intersect(\n wuffs_base__rect_ie_u32__struct s);\n inline wuffs_base__rect_ie_u32__struct unite(\n wuffs_base__rect_ie_u32__struct s);\n inline bool contains(uint32_t x, uint32_t y);\n inline bool contains_r" +
"ect(wuffs_base__rect_ie_u32__struct s);\n inline uint32_t width();\n inline uint32_t height();\n#endif // __cplusplus\n\n} wuffs_base__rect_ie_u32;\n\nstatic inline bool //\nwuffs_base__rect_ie_u32__is_empty(wuffs_base__rect_ie_u32* r) {\n return (r->min_incl_x >= r->max_excl_x) || (r->min_incl_y >= r->max_excl_y);\n}\n\nstatic inline bool //\nwuffs_base__rect_ie_u32__equals(wuffs_base__rect_ie_u32* r,\n wuffs_base__rect_ie_u32 s) {\n return (r->min_incl_x == s.min_incl_x && r->min_incl_y == s.min_incl_y &&\n r->max_excl_x == s.max_excl_x && r->max_excl_y == s.max_excl_y) ||\n (wuffs_base__rect_ie_u32__is_empty(r) &&\n wuffs_base__rect_ie_u32__is_empty(&s));\n}\n\nstatic inline wuffs_base__rect_ie_u32 //\nwuffs_base__rect_ie_u32__intersect(wuffs_base__rect_ie_u32* r,\n wuffs_base__rect_ie_u32 s) {\n wuffs_base__rect_ie_u32 t;\n t.min_incl_x = wuffs_base__u32__max(r->min_incl_x, s.min_incl_x);\n t.min_incl_y = wuffs_base__u32__max(r->m" +
"in_incl_y, s.min_incl_y);\n t.max_excl_x = wuffs_base__u32__min(r->max_excl_x, s.max_excl_x);\n t.max_excl_y = wuffs_base__u32__min(r->max_excl_y, s.max_excl_y);\n return t;\n}\n\nstatic inline wuffs_base__rect_ie_u32 //\nwuffs_base__rect_ie_u32__unite(wuffs_base__rect_ie_u32* r,\n wuffs_base__rect_ie_u32 s) {\n if (wuffs_base__rect_ie_u32__is_empty(r)) {\n return s;\n }\n if (wuffs_base__rect_ie_u32__is_empty(&s)) {\n return *r;\n }\n wuffs_base__rect_ie_u32 t;\n t.min_incl_x = wuffs_base__u32__min(r->min_incl_x, s.min_incl_x);\n t.min_incl_y = wuffs_base__u32__min(r->min_incl_y, s.min_incl_y);\n t.max_excl_x = wuffs_base__u32__max(r->max_excl_x, s.max_excl_x);\n t.max_excl_y = wuffs_base__u32__max(r->max_excl_y, s.max_excl_y);\n return t;\n}\n\nstatic inline bool //\nwuffs_base__rect_ie_u32__contains(wuffs_base__rect_ie_u32* r,\n uint32_t x,\n uint32_t y) {\n return (r->min_incl_x <= x) && (x < r->max_excl_x) && (r->m" +
"in_incl_y <= y) &&\n (y < r->max_excl_y);\n}\n\nstatic inline bool //\nwuffs_base__rect_ie_u32__contains_rect(wuffs_base__rect_ie_u32* r,\n wuffs_base__rect_ie_u32 s) {\n return wuffs_base__rect_ie_u32__equals(\n &s, wuffs_base__rect_ie_u32__intersect(r, s));\n}\n\nstatic inline uint32_t //\nwuffs_base__rect_ie_u32__width(wuffs_base__rect_ie_u32* r) {\n return wuffs_base__u32__sat_sub(r->max_excl_x, r->min_incl_x);\n}\n\nstatic inline uint32_t //\nwuffs_base__rect_ie_u32__height(wuffs_base__rect_ie_u32* r) {\n return wuffs_base__u32__sat_sub(r->max_excl_y, r->min_incl_y);\n}\n\n#ifdef __cplusplus\n\ninline bool //\nwuffs_base__rect_ie_u32::is_empty() {\n return wuffs_base__rect_ie_u32__is_empty(this);\n}\n\ninline bool //\nwuffs_base__rect_ie_u32::equals(wuffs_base__rect_ie_u32 s) {\n return wuffs_base__rect_ie_u32__equals(this, s);\n}\n\ninline wuffs_base__rect_ie_u32 //\nwuffs_base__rect_ie_u32::intersect(wuffs_base__rect_ie_u32 s) {\n return wuffs_base__rect_ie_u32__intersect(th" +
"is, s);\n}\n\ninline wuffs_base__rect_ie_u32 //\nwuffs_base__rect_ie_u32::unite(wuffs_base__rect_ie_u32 s) {\n return wuffs_base__rect_ie_u32__unite(this, s);\n}\n\ninline bool //\nwuffs_base__rect_ie_u32::contains(uint32_t x, uint32_t y) {\n return wuffs_base__rect_ie_u32__contains(this, x, y);\n}\n\ninline bool //\nwuffs_base__rect_ie_u32::contains_rect(wuffs_base__rect_ie_u32 s) {\n return wuffs_base__rect_ie_u32__contains_rect(this, s);\n}\n\ninline uint32_t //\nwuffs_base__rect_ie_u32::width() {\n return wuffs_base__rect_ie_u32__width(this);\n}\n\ninline uint32_t //\nwuffs_base__rect_ie_u32::height() {\n return wuffs_base__rect_ie_u32__height(this);\n}\n\n#endif // __cplusplus\n\n" +
"" +
"// ---------------- Bureaucracy re -Wunused-function\n\nstatic inline void\nwuffs_base__acknowledge_potentially_unused_functions__range_public()\n WUFFS_BASE__POTENTIALLY_UNUSED;\n\nstatic inline void\nwuffs_base__acknowledge_potentially_unused_functions__range_public() {\n (void)(wuffs_base__range_ie_u32__contains);\n (void)(wuffs_base__range_ie_u32__contains_range);\n (void)(wuffs_base__range_ie_u32__equals);\n (void)(wuffs_base__range_ie_u32__intersect);\n (void)(wuffs_base__range_ie_u32__is_empty);\n (void)(wuffs_base__range_ie_u32__length);\n (void)(wuffs_base__range_ie_u32__unite);\n (void)(wuffs_base__range_ie_u64__contains);\n (void)(wuffs_base__range_ie_u64__contains_range);\n (void)(wuffs_base__range_ie_u64__equals);\n (void)(wuffs_base__range_ie_u64__intersect);\n (void)(wuffs_base__range_ie_u64__is_empty);\n (void)(wuffs_base__range_ie_u64__length);\n (void)(wuffs_base__range_ie_u64__unite);\n (void)(wuffs_base__range_ii_u32__contains);\n (void)(wuffs_base__range_ii_u32__contains_range);\n (void)(wuff" +
"s_base__range_ii_u32__equals);\n (void)(wuffs_base__range_ii_u32__intersect);\n (void)(wuffs_base__range_ii_u32__is_empty);\n (void)(wuffs_base__range_ii_u32__unite);\n (void)(wuffs_base__range_ii_u64__contains);\n (void)(wuffs_base__range_ii_u64__contains_range);\n (void)(wuffs_base__range_ii_u64__equals);\n (void)(wuffs_base__range_ii_u64__intersect);\n (void)(wuffs_base__range_ii_u64__is_empty);\n (void)(wuffs_base__range_ii_u64__unite);\n (void)(wuffs_base__rect_ie_u32__contains);\n (void)(wuffs_base__rect_ie_u32__contains_rect);\n (void)(wuffs_base__rect_ie_u32__equals);\n (void)(wuffs_base__rect_ie_u32__height);\n (void)(wuffs_base__rect_ie_u32__intersect);\n (void)(wuffs_base__rect_ie_u32__is_empty);\n (void)(wuffs_base__rect_ie_u32__unite);\n (void)(wuffs_base__rect_ie_u32__width);\n (void)(wuffs_base__rect_ii_u32__contains);\n (void)(wuffs_base__rect_ie_u32__contains_rect);\n (void)(wuffs_base__rect_ii_u32__equals);\n (void)(wuffs_base__rect_ii_u32__intersect);\n (void)(wuffs_base__rect_ii_u32__is_em" +
"pty);\n (void)(wuffs_base__rect_ii_u32__unite);\n}\n" +
""
const baseCopyright = "" +
"// Copyright 2017 The Wuffs Authors.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// https://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n" +
""
-537
View File
@@ -1,537 +0,0 @@
// Copyright 2017 The Wuffs Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cgen
import (
"fmt"
a "github.com/google/wuffs/lang/ast"
t "github.com/google/wuffs/lang/token"
)
func (g *gen) writeExpr(b *buffer, n *a.Expr, depth uint32) error {
if depth > a.MaxExprDepth {
return fmt.Errorf("expression recursion depth too large")
}
depth++
if cv := n.ConstValue(); cv != nil {
if typ := n.MType(); typ.IsNumTypeOrIdeal() {
b.writes(cv.String())
} else if typ.IsNullptr() || typ.IsStatus() {
b.writes("NULL")
} else if cv.Cmp(zero) == 0 {
b.writes("false")
} else if cv.Cmp(one) == 0 {
b.writes("true")
} else {
return fmt.Errorf("%v has type bool but constant value %v is neither 0 or 1", n.Str(g.tm), cv)
}
return nil
}
switch op := n.Operator(); {
case op.IsXUnaryOp():
return g.writeExprUnaryOp(b, n, depth)
case op.IsXBinaryOp():
return g.writeExprBinaryOp(b, n, depth)
case op.IsXAssociativeOp():
return g.writeExprAssociativeOp(b, n, depth)
}
return g.writeExprOther(b, n, depth)
}
func (g *gen) writeExprOther(b *buffer, n *a.Expr, depth uint32) error {
switch n.Operator() {
case 0:
if ident := n.Ident(); ident == t.IDThis {
b.writes("self")
} else if ident == t.IDCoroutineResumed {
if g.currFunk.astFunc.Effect().Coroutine() {
// TODO: don't hard-code [0], and allow recursive coroutines.
b.printf("(self->private_impl.%s%s[0] != 0)",
pPrefix, g.currFunk.astFunc.FuncName().Str(g.tm))
} else {
b.writes("false")
}
} else if ident.IsStrLiteral(g.tm) {
if z := g.statusMap[n.StatusQID()]; z.cName != "" {
b.writes(z.cName)
} else {
return fmt.Errorf("unrecognized status %s", n.StatusQID().Str(g.tm))
}
} else if c, ok := g.scalarConstsMap[t.QID{0, n.Ident()}]; ok {
b.writes(c.Value().ConstValue().String())
} else {
if n.GlobalIdent() {
b.writes(g.pkgPrefix)
} else {
b.writes(vPrefix)
}
b.writes(ident.Str(g.tm))
}
return nil
case t.IDOpenParen:
// n is a function call.
if err := g.writeBuiltinCall(b, n, depth); err != errNoSuchBuiltin {
return err
}
if n.LHS().AsExpr().Ident() == t.IDReset {
method := n.LHS().AsExpr()
recv := method.LHS().AsExpr()
recvTyp, addr := recv.MType(), "&"
if p := recvTyp.Decorator(); p == t.IDNptr || p == t.IDPtr {
recvTyp, addr = recvTyp.Inner(), ""
}
if recvTyp.Decorator() != 0 {
return fmt.Errorf("cannot generate reset method call %q for receiver type %q",
n.Str(g.tm), recv.MType().Str(g.tm))
}
qid := recvTyp.QID()
if isBaseRangeType(qid) {
// Generate a 2 part expression using the comma operator: "(memset
// call, return_empty_struct call)". The final part is a function
// call (to a static inline function) instead of a struct literal,
// to avoid a "expression result unused" compiler error.
b.printf("(memset(%s", addr)
if err := g.writeExpr(b, recv, depth); err != nil {
return err
}
b.printf(", 0, sizeof (%s%s)), wuffs_base__make_empty_struct())",
g.packagePrefix(qid), qid[1].Str(g.tm))
} else {
b.printf("wuffs_base__ignore_status("+
"%s%s__initialize(%s", g.packagePrefix(qid), qid[1].Str(g.tm), addr)
if err := g.writeExpr(b, recv, depth); err != nil {
return err
}
b.printf(", sizeof (%s%s), WUFFS_VERSION, 0))", g.packagePrefix(qid), qid[1].Str(g.tm))
}
return nil
}
return g.writeExprUserDefinedCall(b, n, depth)
case t.IDOpenBracket:
// n is an index.
if err := g.writeExpr(b, n.LHS().AsExpr(), depth); err != nil {
return err
}
if lTyp := n.LHS().AsExpr().MType(); lTyp.IsSliceType() {
// TODO: don't assume that the slice is a slice of base.u8.
b.writes(".ptr")
}
b.writeb('[')
if err := g.writeExpr(b, n.RHS().AsExpr(), depth); err != nil {
return err
}
b.writeb(']')
return nil
case t.IDColon:
// n is a slice.
lhs := n.LHS().AsExpr()
mhs := n.MHS().AsExpr()
rhs := n.RHS().AsExpr()
switch {
case mhs != nil && rhs == nil:
b.writes("wuffs_base__slice_u8__subslice_i(")
case mhs == nil && rhs != nil:
b.writes("wuffs_base__slice_u8__subslice_j(")
case mhs != nil && rhs != nil:
b.writes("wuffs_base__slice_u8__subslice_ij(")
}
lhsIsArray := lhs.MType().IsArrayType()
if lhsIsArray {
// TODO: don't assume that the slice is a slice of base.u8.
b.writes("wuffs_base__make_slice_u8(")
}
if err := g.writeExpr(b, lhs, depth); err != nil {
return err
}
if lhsIsArray {
b.printf(", %v)", lhs.MType().ArrayLength().ConstValue())
}
if mhs != nil {
b.writeb(',')
if err := g.writeExpr(b, mhs, depth); err != nil {
return err
}
}
if rhs != nil {
b.writeb(',')
if err := g.writeExpr(b, rhs, depth); err != nil {
return err
}
}
if mhs != nil || rhs != nil {
b.writeb(')')
}
return nil
case t.IDDot:
lhs := n.LHS().AsExpr()
if lhs.Ident() == t.IDArgs {
b.writes(aPrefix)
b.writes(n.Ident().Str(g.tm))
return nil
}
if err := g.writeExpr(b, lhs, depth); err != nil {
return err
}
if p := lhs.MType().Decorator(); p == t.IDNptr || p == t.IDPtr {
b.writes("->")
} else {
b.writes(".")
}
b.writes(g.privateImplData(lhs.MType(), n.Ident()))
b.writeb('.')
b.writes(fPrefix)
b.writes(n.Ident().Str(g.tm))
return nil
}
return fmt.Errorf("unrecognized token (0x%X) for writeExprOther", n.Operator())
}
func (g *gen) privateImplData(typ *a.TypeExpr, fieldName t.ID) string {
if p := typ.Decorator(); p == t.IDNptr || p == t.IDPtr {
typ = typ.Inner()
}
if s := g.structMap[typ.QID()]; s != nil {
qid := s.QID()
if _, ok := g.privateDataFields[t.QQID{qid[0], qid[1], fieldName}]; ok {
return "private_data"
}
}
return "private_impl"
}
func (g *gen) writeExprUnaryOp(b *buffer, n *a.Expr, depth uint32) error {
op := n.Operator()
opName := cOpName(op)
if opName == "" {
return fmt.Errorf("unrecognized operator %q", op.AmbiguousForm().Str(g.tm))
}
b.writes(opName)
return g.writeExpr(b, n.RHS().AsExpr(), depth)
}
func (g *gen) writeExprBinaryOp(b *buffer, n *a.Expr, depth uint32) error {
opName := ""
op := n.Operator()
switch op {
case t.IDXBinaryTildeSatPlus, t.IDXBinaryTildeSatMinus:
uBits := uintBits(n.MType().QID())
if uBits == 0 {
return fmt.Errorf("unsupported tilde-operator type %q", n.MType().Str(g.tm))
}
uOp := "add"
if op != t.IDXBinaryTildeSatPlus {
uOp = "sub"
}
b.printf("wuffs_base__u%d__sat_%s", uBits, uOp)
opName = ","
case t.IDXBinaryAs:
return g.writeExprAs(b, n.LHS().AsExpr(), n.RHS().AsTypeExpr(), depth)
default:
opName = cOpName(op)
if opName == "" {
return fmt.Errorf("unrecognized operator %q", op.AmbiguousForm().Str(g.tm))
}
}
b.writeb('(')
if err := g.writeExpr(b, n.LHS().AsExpr(), depth); err != nil {
return err
}
b.writes(opName)
if err := g.writeExpr(b, n.RHS().AsExpr(), depth); err != nil {
return err
}
b.writeb(')')
return nil
}
func (g *gen) writeExprAs(b *buffer, lhs *a.Expr, rhs *a.TypeExpr, depth uint32) error {
b.writes("((")
// TODO: watch for passing an array type to writeCTypeName? In C, an array
// type can decay into a pointer.
if err := g.writeCTypeName(b, rhs, "", ""); err != nil {
return err
}
b.writes(")(")
if err := g.writeExpr(b, lhs, depth); err != nil {
return err
}
b.writes("))")
return nil
}
func (g *gen) writeExprAssociativeOp(b *buffer, n *a.Expr, depth uint32) error {
op := n.Operator()
opName := cOpName(op)
if opName == "" {
return fmt.Errorf("unrecognized operator %q", op.AmbiguousForm().Str(g.tm))
}
b.writeb('(')
for i, o := range n.Args() {
if i != 0 {
b.writes(opName)
}
if err := g.writeExpr(b, o.AsExpr(), depth); err != nil {
return err
}
}
b.writeb(')')
return nil
}
func (g *gen) writeExprUserDefinedCall(b *buffer, n *a.Expr, depth uint32) error {
method := n.LHS().AsExpr()
recv := method.LHS().AsExpr()
recvTyp, addr := recv.MType(), "&"
if p := recvTyp.Decorator(); p == t.IDNptr || p == t.IDPtr {
recvTyp, addr = recvTyp.Inner(), ""
} else if recvTyp.IsStatus() {
addr = ""
}
if recvTyp.Decorator() != 0 {
return fmt.Errorf("cannot generate user-defined method call %q for receiver type %q",
n.Str(g.tm), recv.MType().Str(g.tm))
}
qid := recvTyp.QID()
b.printf("%s%s__%s(", g.packagePrefix(qid), qid[1].Str(g.tm), method.Ident().Str(g.tm))
if !recvTyp.Eq(typeExprUtility) {
b.writes(addr)
if err := g.writeExpr(b, recv, depth); err != nil {
return err
}
if len(n.Args()) > 0 {
b.writeb(',')
}
}
return g.writeArgs(b, n.Args(), depth)
}
func (g *gen) writeCTypeName(b *buffer, n *a.TypeExpr, varNamePrefix string, varName string) error {
// It may help to refer to http://unixwiz.net/techtips/reading-cdecl.html
// TODO: fix this, allow slices of all types, not just of base.u8's. Also
// allow arrays of slices, slices of pointers, etc.
if n.IsSliceType() {
o := n.Inner()
if o.Decorator() == 0 && o.QID() == (t.QID{t.IDBase, t.IDU8}) && !o.IsRefined() {
b.writes("wuffs_base__slice_u8")
b.writeb(' ')
b.writes(varNamePrefix)
b.writes(varName)
return nil
}
return fmt.Errorf("cannot convert Wuffs type %q to C", n.Str(g.tm))
}
if n.IsTableType() {
o := n.Inner()
if o.Decorator() == 0 && o.QID() == (t.QID{t.IDBase, t.IDU8}) && !o.IsRefined() {
b.writes("wuffs_base__table_u8")
b.writeb(' ')
b.writes(varNamePrefix)
b.writes(varName)
return nil
}
return fmt.Errorf("cannot convert Wuffs type %q to C", n.Str(g.tm))
}
// maxNumPointers is an arbitrary implementation restriction.
const maxNumPointers = 16
x := n
for ; x != nil && x.IsArrayType(); x = x.Inner() {
}
numPointers, innermost := 0, x
for ; innermost != nil && innermost.Inner() != nil; innermost = innermost.Inner() {
if p := innermost.Decorator(); p == t.IDNptr || p == t.IDPtr {
if numPointers == maxNumPointers {
return fmt.Errorf("cannot convert Wuffs type %q to C: too many ptr's", n.Str(g.tm))
}
numPointers++
continue
}
// TODO: fix this.
return fmt.Errorf("cannot convert Wuffs type %q to C", n.Str(g.tm))
}
fallback := true
if qid := innermost.QID(); qid[0] == t.IDBase {
if key := qid[1]; key < t.ID(len(cTypeNames)) {
if s := cTypeNames[key]; s != "" {
b.writes(s)
fallback = false
}
}
}
if fallback {
qid := innermost.QID()
b.printf("%s%s", g.packagePrefix(qid), qid[1].Str(g.tm))
}
for i := 0; i < numPointers; i++ {
b.writeb('*')
}
b.writeb(' ')
b.writes(varNamePrefix)
b.writes(varName)
x = n
for ; x != nil && x.IsArrayType(); x = x.Inner() {
b.writeb('[')
b.writes(x.ArrayLength().ConstValue().String())
b.writeb(']')
}
return nil
}
func (g *gen) packagePrefix(qid t.QID) string {
if qid[0] != 0 {
otherPkg := g.tm.ByID(qid[0])
// TODO: map the "deflate" in "deflate.decoder" to the "deflate" in
// `use "std/deflate"`, and use the latter "deflate".
//
// This is pretty academic at the moment, since they're the same
// "deflate", but in the future, we might be able to rename used
// packages, e.g. `use "foo/bar" as "baz"`, so "baz.qux" would map
// to generating "wuffs_bar__qux".
//
// TODO: sanitize or validate otherPkg, e.g. that it's ASCII only?
//
// See gen.writeInitializerImpl for a similar use of otherPkg.
return "wuffs_" + otherPkg + "__"
}
return g.pkgPrefix
}
func isBaseRangeType(qid t.QID) bool {
if qid[0] == t.IDBase {
switch qid[1] {
case t.IDRangeIEU32, t.IDRangeIIU32, t.IDRangeIEU64, t.IDRangeIIU64:
return true
}
}
return false
}
var cTypeNames = [...]string{
t.IDI8: "int8_t",
t.IDI16: "int16_t",
t.IDI32: "int32_t",
t.IDI64: "int64_t",
t.IDU8: "uint8_t",
t.IDU16: "uint16_t",
t.IDU32: "uint32_t",
t.IDU64: "uint64_t",
t.IDBool: "bool",
t.IDIOReader: "wuffs_base__io_reader",
t.IDIOWriter: "wuffs_base__io_writer",
}
const noSuchCOperator = " no_such_C_operator "
func cOpName(x t.ID) string {
if x < t.ID(len(cOpNames)) {
if s := cOpNames[x]; s != "" {
return s
}
}
return noSuchCOperator
}
var cOpNames = [...]string{
t.IDPlusEq: " += ",
t.IDMinusEq: " -= ",
t.IDStarEq: " *= ",
t.IDSlashEq: " /= ",
t.IDShiftLEq: " <<= ",
t.IDShiftREq: " >>= ",
t.IDAmpEq: " &= ",
t.IDPipeEq: " |= ",
t.IDHatEq: " ^= ",
t.IDPercentEq: " %= ",
t.IDTildeModShiftLEq: " <<= ",
t.IDTildeModPlusEq: " += ",
t.IDTildeModMinusEq: " -= ",
t.IDTildeSatPlusEq: noSuchCOperator,
t.IDTildeSatMinusEq: noSuchCOperator,
t.IDEq: " = ",
t.IDEqQuestion: " = ",
t.IDXUnaryPlus: " + ",
t.IDXUnaryMinus: " - ",
t.IDXUnaryNot: " ! ",
t.IDXUnaryRef: " & ",
t.IDXUnaryDeref: " * ",
t.IDXBinaryPlus: " + ",
t.IDXBinaryMinus: " - ",
t.IDXBinaryStar: " * ",
t.IDXBinarySlash: " / ",
t.IDXBinaryShiftL: " << ",
t.IDXBinaryShiftR: " >> ",
t.IDXBinaryAmp: " & ",
t.IDXBinaryPipe: " | ",
t.IDXBinaryHat: " ^ ",
t.IDXBinaryPercent: " % ",
t.IDXBinaryTildeModShiftL: " << ",
t.IDXBinaryTildeModPlus: " + ",
t.IDXBinaryTildeModMinus: " - ",
t.IDXBinaryTildeSatPlus: noSuchCOperator,
t.IDXBinaryTildeSatMinus: noSuchCOperator,
t.IDXBinaryNotEq: " != ",
t.IDXBinaryLessThan: " < ",
t.IDXBinaryLessEq: " <= ",
t.IDXBinaryEqEq: " == ",
t.IDXBinaryGreaterEq: " >= ",
t.IDXBinaryGreaterThan: " > ",
t.IDXBinaryAnd: " && ",
t.IDXBinaryOr: " || ",
t.IDXBinaryAs: noSuchCOperator,
t.IDXAssociativePlus: " + ",
t.IDXAssociativeStar: " * ",
t.IDXAssociativeAmp: " & ",
t.IDXAssociativePipe: " | ",
t.IDXAssociativeHat: " ^ ",
t.IDXAssociativeAnd: " && ",
t.IDXAssociativeOr: " || ",
}
-495
View File
@@ -1,495 +0,0 @@
// Copyright 2017 The Wuffs Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cgen
import (
"fmt"
"math/big"
a "github.com/google/wuffs/lang/ast"
t "github.com/google/wuffs/lang/token"
)
type funk struct {
bPrologue buffer
bBodyResume buffer
bBody buffer
bBodySuspend buffer
bEpilogue buffer
astFunc *a.Func
cName string
coroID uint32
returnsStatus bool
varList []*a.Var
varResumables map[t.ID]bool
derivedVars map[t.ID]struct{}
jumpTargets map[a.Loop]uint32
coroSuspPoint uint32
ioBinds uint32
tempW uint32
tempR uint32
usesScratch bool
hasGotoOK bool
}
func (k *funk) jumpTarget(n a.Loop) (uint32, error) {
if k.jumpTargets == nil {
k.jumpTargets = map[a.Loop]uint32{}
}
if jt, ok := k.jumpTargets[n]; ok {
return jt, nil
}
jt := uint32(len(k.jumpTargets))
if jt == 1000000 {
return 0, fmt.Errorf("too many jump targets")
}
k.jumpTargets[n] = jt
return jt, nil
}
func (g *gen) funcCName(n *a.Func) string {
if r := n.Receiver(); !r.IsZero() {
// TODO: this isn't right if r[0] != 0, i.e. the receiver is from a
// used package. There might be similar cases elsewhere in this
// package.
return g.pkgPrefix + r.Str(g.tm) + "__" + n.FuncName().Str(g.tm)
}
return g.pkgPrefix + n.FuncName().Str(g.tm)
}
// C++ related function signature constants.
const (
cppNone = 0 // Not C++, just plain C.
cppInsideStruct = 1
cppOutsideStruct = 2
)
func (g *gen) writeFuncSignature(b *buffer, n *a.Func, cpp uint32) error {
if cpp != cppNone {
b.writes("inline ")
} else if n.Public() {
b.writes("WUFFS_BASE__MAYBE_STATIC ")
} else {
b.writes("static ")
}
// TODO: write n's return values.
if n.Effect().Coroutine() {
b.writes("wuffs_base__status ")
} else if out := n.Out(); out == nil {
b.writes("wuffs_base__empty_struct ")
// TODO: does writeCTypeName generate the right C if out is an array?
} else if err := g.writeCTypeName(b, out, "", ""); err != nil {
return err
}
// The empty // comment makes clang-format place the function name at the
// start of a line.
b.writes("//\n")
switch cpp {
case cppNone:
b.writes(g.funcCName(n))
case cppInsideStruct:
b.writes(n.FuncName().Str(g.tm))
case cppOutsideStruct:
b.writes(g.pkgPrefix)
b.writes(n.Receiver().Str(g.tm))
b.writes("::")
b.writes(n.FuncName().Str(g.tm))
}
b.writeb('(')
comma := false
if cpp == cppNone {
if r := n.Receiver(); !r.IsZero() {
if n.Effect().Pure() {
b.writes("const ")
}
b.printf("%s%s *self", g.pkgPrefix, r.Str(g.tm))
comma = true
}
}
for _, o := range n.In().Fields() {
if comma {
b.writeb(',')
}
comma = true
o := o.AsField()
if err := g.writeCTypeName(b, o.XType(), aPrefix, o.Name().Str(g.tm)); err != nil {
return err
}
}
b.printf(")")
if cpp != cppNone && !n.Receiver().IsZero() && n.Effect().Pure() {
b.writes(" const ")
}
return nil
}
func (g *gen) writeFuncPrototype(b *buffer, n *a.Func) error {
if err := g.writeFuncSignature(b, n, cppNone); err != nil {
return err
}
b.writes(";\n\n")
return nil
}
func (g *gen) writeFuncImpl(b *buffer, n *a.Func) error {
k := g.funks[n.QQID()]
b.printf("// -------- func %s.%s\n\n", g.pkgName, n.QQID().Str(g.tm))
if err := g.writeFuncSignature(b, n, cppNone); err != nil {
return err
}
b.writes("{\n")
b.writex(k.bPrologue)
if k.astFunc.Effect().Coroutine() {
b.writex(k.bBodyResume)
}
b.writex(k.bBody)
if k.astFunc.Effect().Coroutine() {
b.writex(k.bBodySuspend)
} else if k.hasGotoOK {
b.writes("\ngoto ok;ok:\n") // The goto avoids the "unused label" warning.
}
b.writex(k.bEpilogue)
b.writes("}\n\n")
return nil
}
func (g *gen) gatherFuncImpl(_ *buffer, n *a.Func) error {
if n.Public() && n.Effect().Coroutine() {
g.numPublicCoroutines++
}
g.currFunk = funk{
astFunc: n,
cName: g.funcCName(n),
coroID: g.numPublicCoroutines,
returnsStatus: n.Effect().Coroutine() ||
((n.Out() != nil) && n.Out().IsStatus()),
}
if err := g.findVars(); err != nil {
return err
}
g.findDerivedVars()
if err := g.writeFuncImplPrologue(&g.currFunk.bPrologue); err != nil {
return err
}
if err := g.writeFuncImplBodyResume(&g.currFunk.bBodyResume); err != nil {
return err
}
if err := g.writeFuncImplBody(&g.currFunk.bBody); err != nil {
return err
}
if err := g.writeFuncImplBodySuspend(&g.currFunk.bBodySuspend); err != nil {
return err
}
if err := g.writeFuncImplEpilogue(&g.currFunk.bEpilogue); err != nil {
return err
}
if g.currFunk.tempW != g.currFunk.tempR {
return fmt.Errorf("internal error: temporary variable count out of sync")
}
g.funks[n.QQID()] = g.currFunk
return nil
}
func (g *gen) writeOutParamZeroValue(b *buffer, typ *a.TypeExpr) error {
if typ == nil {
b.writes("wuffs_base__make_empty_struct()")
return nil
} else if typ.IsNumType() {
b.writes("0")
return nil
} else if typ.IsSliceType() {
if inner := typ.Inner(); (inner.Decorator() == 0) && (inner.QID() == t.QID{t.IDBase, t.IDU8}) {
b.writes("wuffs_base__make_slice_u8(NULL, 0)")
return nil
}
} else if (typ.Decorator() == 0) && (typ.QID()[0] == t.IDBase) {
switch typ.QID()[1] {
case t.IDRangeIEU32:
b.writes("wuffs_base__utility__make_range_ie_u32(0, 0)")
return nil
case t.IDRangeIIU32:
b.writes("wuffs_base__utility__make_range_ii_u32(0, 0)")
return nil
case t.IDRangeIEU64:
b.writes("wuffs_base__utility__make_range_ie_u64(0, 0)")
return nil
case t.IDRangeIIU64:
b.writes("wuffs_base__utility__make_range_ii_u64(0, 0)")
return nil
case t.IDRectIEU32:
b.writes("wuffs_base__utility__make_rect_ie_u32(0, 0, 0, 0)")
return nil
case t.IDRectIIU32:
b.writes("wuffs_base__utility__make_rect_ii_u32(0, 0, 0, 0)")
return nil
}
}
return fmt.Errorf("internal error: cannot write the zero value of type %q", typ.Str(g.tm))
}
func (g *gen) writeFuncImplPrologue(b *buffer) error {
// Check the initialized/disabled state and the "self" arg.
if g.currFunk.astFunc.Public() && !g.currFunk.astFunc.Receiver().IsZero() {
out := g.currFunk.astFunc.Out()
b.writes("if (!self) { return ")
if g.currFunk.returnsStatus {
b.writes("wuffs_base__error__bad_receiver")
} else if err := g.writeOutParamZeroValue(b, out); err != nil {
return err
}
b.writes(";}")
if g.currFunk.astFunc.Effect().Pure() {
b.writes("if ((self->private_impl.magic != WUFFS_BASE__MAGIC) &&")
b.writes(" (self->private_impl.magic != WUFFS_BASE__DISABLED)) {")
} else {
b.writes("if (self->private_impl.magic != WUFFS_BASE__MAGIC) {")
}
b.writes("return ")
if g.currFunk.returnsStatus {
b.writes("(self->private_impl.magic == WUFFS_BASE__DISABLED) " +
"? wuffs_base__error__disabled_by_previous_error " +
": wuffs_base__error__initialize_not_called")
} else if err := g.writeOutParamZeroValue(b, out); err != nil {
return err
}
b.writes(";}\n")
}
// For public functions, check (at runtime) the other args for bounds and
// null-ness. For private functions, those checks are done at compile time.
if g.currFunk.astFunc.Public() {
if err := g.writeFuncImplArgChecks(b, g.currFunk.astFunc); err != nil {
return err
}
// For public coroutines, check that we are not suspended in an active
// coroutine.
if g.currFunk.astFunc.Effect().Coroutine() {
b.printf("if ((self->private_impl.active_coroutine != 0) && "+
"(self->private_impl.active_coroutine != %d)) {\n", g.currFunk.coroID)
b.writes("self->private_impl.magic = WUFFS_BASE__DISABLED;\n")
b.writes("return wuffs_base__error__interleaved_coroutine_calls;\n")
b.writes("}\n")
b.writes("self->private_impl.active_coroutine = 0;\n")
}
}
if g.currFunk.astFunc.Effect().Coroutine() ||
(g.currFunk.returnsStatus && (len(g.currFunk.derivedVars) > 0)) {
// TODO: rename the "status" variable to "ret"?
b.printf("wuffs_base__status status = NULL;\n")
}
b.writes("\n")
// Generate the local variables.
if err := g.writeVars(b, &g.currFunk, false); err != nil {
return err
}
b.writes("\n")
if g.currFunk.derivedVars != nil {
for _, o := range g.currFunk.astFunc.In().Fields() {
o := o.AsField()
if err := g.writeLoadDerivedVar(b, "", aPrefix, o.Name(), o.XType(), true); err != nil {
return err
}
}
b.writes("\n")
}
return nil
}
func (g *gen) writeFuncImplBodyResume(b *buffer) error {
if g.currFunk.astFunc.Effect().Coroutine() {
// TODO: don't hard-code [0], and allow recursive coroutines.
b.printf("uint32_t coro_susp_point = self->private_impl.%s%s[0];\n",
pPrefix, g.currFunk.astFunc.FuncName().Str(g.tm))
b.printf("if (coro_susp_point) {\n")
if err := g.writeResumeSuspend(b, &g.currFunk, false); err != nil {
return err
}
b.writes("}\n")
// Generate a coroutine switch similiar to the technique in
// https://www.chiark.greenend.org.uk/~sgtatham/coroutines.html
//
// The matching } is written below. See "Close the coroutine switch".
b.writes("switch (coro_susp_point) {\nWUFFS_BASE__COROUTINE_SUSPENSION_POINT_0;\n\n")
}
return nil
}
func (g *gen) writeFuncImplBody(b *buffer) error {
for _, o := range g.currFunk.astFunc.Body() {
if err := g.writeStatement(b, o, 0); err != nil {
return err
}
}
return nil
}
func (g *gen) writeFuncImplBodySuspend(b *buffer) error {
if g.currFunk.astFunc.Effect().Coroutine() {
// We've reached the end of the function body. Reset the coroutine
// suspension point so that the next call to this function starts at
// the top.
b.writes("\ngoto ok;ok:") // The goto avoids the "unused label" warning.
b.printf("self->private_impl.%s%s[0] = 0;\n",
pPrefix, g.currFunk.astFunc.FuncName().Str(g.tm))
b.writes("goto exit; }\n\n") // Close the coroutine switch.
b.writes("goto suspend;suspend:") // The goto avoids the "unused label" warning.
b.printf("self->private_impl.%s%s[0] = coro_susp_point;\n",
pPrefix, g.currFunk.astFunc.FuncName().Str(g.tm))
if g.currFunk.astFunc.Public() {
b.printf("self->private_impl.active_coroutine = %d;\n", g.currFunk.coroID)
}
if err := g.writeResumeSuspend(b, &g.currFunk, true); err != nil {
return err
}
b.writes("\n")
}
return nil
}
func (g *gen) writeFuncImplEpilogue(b *buffer) error {
if g.currFunk.astFunc.Effect().Coroutine() ||
(g.currFunk.returnsStatus && (len(g.currFunk.derivedVars) > 0)) {
b.writes("goto exit;exit:") // The goto avoids the "unused label" warning.
}
if g.currFunk.derivedVars != nil {
for _, o := range g.currFunk.astFunc.In().Fields() {
o := o.AsField()
if err := g.writeSaveDerivedVar(b, "", aPrefix, o.Name(), o.XType()); err != nil {
return err
}
}
b.writes("\n")
}
if g.currFunk.astFunc.Effect().Coroutine() ||
(g.currFunk.returnsStatus && (len(g.currFunk.derivedVars) > 0)) {
if g.currFunk.astFunc.Public() {
b.writes("if (wuffs_base__status__is_error(status)) { " +
"self->private_impl.magic = WUFFS_BASE__DISABLED; }\n")
}
b.writes("return status;\n")
} else if g.currFunk.astFunc.Out() == nil {
b.writes("return wuffs_base__make_empty_struct();\n")
}
return nil
}
func (g *gen) writeFuncImplArgChecks(b *buffer, n *a.Func) error {
checks := []string(nil)
for _, o := range n.In().Fields() {
o := o.AsField()
oTyp := o.XType()
if oTyp.Decorator() != t.IDPtr && !oTyp.IsRefined() {
// TODO: Also check elements, for array-typed arguments.
continue
}
switch {
case oTyp.Decorator() == t.IDPtr:
checks = append(checks, fmt.Sprintf("!%s%s", aPrefix, o.Name().Str(g.tm)))
case oTyp.IsRefined():
bounds := [2]*big.Int{}
for i, bound := range oTyp.Bounds() {
if bound != nil {
if cv := bound.ConstValue(); cv != nil {
bounds[i] = cv
}
}
}
if qid := oTyp.QID(); qid[0] == t.IDBase {
if key := qid[1]; key < t.ID(len(numTypeBounds)) {
ntb := numTypeBounds[key]
for i := 0; i < 2; i++ {
if bounds[i] != nil && ntb[i] != nil && bounds[i].Cmp(ntb[i]) == 0 {
bounds[i] = nil
continue
}
}
}
}
for i, bound := range bounds {
if bound != nil {
op := '<'
if i != 0 {
op = '>'
}
checks = append(checks, fmt.Sprintf("%s%s %c %s", aPrefix, o.Name().Str(g.tm), op, bound))
}
}
}
}
if len(checks) == 0 {
return nil
}
b.writes("if (")
for i, c := range checks {
if i != 0 {
b.writes(" || ")
}
b.writes(c)
}
b.writes(") {")
b.writes("self->private_impl.magic = WUFFS_BASE__DISABLED;\n")
if g.currFunk.astFunc.Effect().Coroutine() {
b.writes("return wuffs_base__error__bad_argument;\n\n")
} else {
// TODO: don't assume that the return type is empty.
b.printf("return wuffs_base__make_empty_struct();\n")
}
b.writes("}\n")
return nil
}
var numTypeBounds = [...][2]*big.Int{
t.IDI8: {big.NewInt(-1 << 7), big.NewInt(1<<7 - 1)},
t.IDI16: {big.NewInt(-1 << 15), big.NewInt(1<<15 - 1)},
t.IDI32: {big.NewInt(-1 << 31), big.NewInt(1<<31 - 1)},
t.IDI64: {big.NewInt(-1 << 63), big.NewInt(1<<63 - 1)},
t.IDU8: {zero, big.NewInt(0).SetUint64(1<<8 - 1)},
t.IDU16: {zero, big.NewInt(0).SetUint64(1<<16 - 1)},
t.IDU32: {zero, big.NewInt(0).SetUint64(1<<32 - 1)},
t.IDU64: {zero, big.NewInt(0).SetUint64(1<<64 - 1)},
t.IDBool: {zero, one},
}
-152
View File
@@ -1,152 +0,0 @@
// Copyright 2017 The Wuffs Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// +build ignore
package main
// gen.go converts base.* to data.go.
//
// Invoke it via "go generate".
import (
"bytes"
"fmt"
"go/format"
"io/ioutil"
"os"
)
const columns = 1024
func main() {
if err := main1(); err != nil {
os.Stderr.WriteString(err.Error() + "\n")
os.Exit(1)
}
}
func main1() error {
out := &bytes.Buffer{}
out.WriteString("// Code generated by running \"go generate\". DO NOT EDIT.\n")
out.WriteString("\n")
out.WriteString("// Copyright 2017 The Wuffs Authors.\n")
out.WriteString("//\n")
out.WriteString("// Licensed under the Apache License, Version 2.0 (the \"License\");\n")
out.WriteString("// you may not use this file except in compliance with the License.\n")
out.WriteString("// You may obtain a copy of the License at\n")
out.WriteString("//\n")
out.WriteString("// https://www.apache.org/licenses/LICENSE-2.0\n")
out.WriteString("//\n")
out.WriteString("// Unless required by applicable law or agreed to in writing, software\n")
out.WriteString("// distributed under the License is distributed on an \"AS IS\" BASIS,\n")
out.WriteString("// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n")
out.WriteString("// See the License for the specific language governing permissions and\n")
out.WriteString("// limitations under the License.\n")
out.WriteString("\n")
out.WriteString("package cgen\n")
out.WriteString("\n")
if err := genBase(out); err != nil {
return err
}
formatted, err := format.Source(out.Bytes())
if err != nil {
return err
}
return ioutil.WriteFile("data.go", formatted, 0644)
}
func genBase(out *bytes.Buffer) error {
files := []struct {
filename, varname string
}{
{"base/all-impl.c", "baseAllImplC"},
{"base/image-impl.c", "baseImageImplC"},
{"base/core-private.h", "baseCorePrivateH"},
{"base/core-public.h", "baseCorePublicH"},
{"base/memory-private.h", "baseMemoryPrivateH"},
{"base/memory-public.h", "baseMemoryPublicH"},
{"base/image-private.h", "baseImagePrivateH"},
{"base/image-public.h", "baseImagePublicH"},
{"base/io-private.h", "baseIOPrivateH"},
{"base/io-public.h", "baseIOPublicH"},
{"base/range-private.h", "baseRangePrivateH"},
{"base/range-public.h", "baseRangePublicH"},
}
prefixAfterEditing := []byte("// After editing this file,")
prefixCopyright := []byte("// Copyright ")
copyright := []byte(nil)
for _, f := range files {
in, err := ioutil.ReadFile(f.filename)
if err != nil {
return err
}
if !bytes.HasPrefix(in, prefixAfterEditing) {
return fmt.Errorf("%s's contents do not start with %q", f.filename, prefixAfterEditing)
}
if i := bytes.Index(in, []byte("\n\n")); i >= 0 {
in = in[i+2:]
}
if !bytes.HasPrefix(in, prefixCopyright) {
return fmt.Errorf("%s's contents do not start with %q", f.filename, prefixCopyright)
}
if i := bytes.Index(in, []byte("\n\n")); i >= 0 {
if len(copyright) == 0 {
copyright = in[:i+2]
}
in = in[i+2:]
}
fmt.Fprintf(out, "const %s = \"\" +\n", f.varname)
writeStringConst(out, in)
out.WriteString("\"\"\n\n")
}
fmt.Fprintf(out, "const baseCopyright = \"\" +\n")
writeStringConst(out, copyright)
out.WriteString("\"\"\n\n")
return nil
}
var dashDashDashDash = []byte("// ----")
func writeStringConst(out *bytes.Buffer, s []byte) {
for len(s) > 0 {
remaining := []byte(nil)
if i := bytes.Index(s[1:], dashDashDashDash); i >= 0 {
s, remaining = s[:i+1], s[i+1:]
}
for len(s) > 0 {
t := s
if len(t) > columns {
t = t[:columns]
}
s = s[len(t):]
fmt.Fprintf(out, "%q +\n", t)
}
s = remaining
if len(s) > 0 {
out.WriteString("\"\" +\n")
}
}
}
-471
View File
@@ -1,471 +0,0 @@
// Copyright 2018 The Wuffs Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cgen
// This file deals with determining whether local variables need to be kept:
// saved / loaded when suspending / resuming a coroutine. For simplicity, this
// is a boolean property of each local variable. The analysis does not
// determine that a local variable needs saving at some CSPs (coroutine
// suspension points) but not others.
//
// Fexample, in this code:
//
// i = etc
// yield foo // The first CSP.
// j = 0
// while j < i {
// a[j] = 42
// j += 1
// }
// c = 100 + args.src.read_u8!??() // The second CSP.
// k = a[c]
//
// There are two CSPs. The i local variable will need to be kept, as it is
// written to before the first CSP and read from after the first CSP.
// Similarly, the a local variable (an array) will need to be kept, as its use
// crosses the second CSP. The j local variable need not be kept, as all of its
// uses happens between two consecutive CSPs. To be precise, for every possible
// code path (including if branches and while loops), each read from j is
// preceded by a write to j without an intervening CSP. The c and k local
// variables also need not be kept, as their uses are all after the last CSP.
//
// Algorithmically, we walk through a function's statements in two passes. The
// first pass finds all of the local variables, and assigns an integer index to
// each one. The second tracks (in a slice indexed by that integer index) each
// local variable's resumability, one of three possible states: none, weak and
// strong. Strong means that the local variable definitely needs to be kept.
// Weak means that we have (in the worst case, for branches' and loops'
// multiple paths) seen a CSP without a write afterwards, so that seeing a read
// would change the resumability to strong. None means that we have not seen a
// CSP since the last write.
//
// Essentially, the state transitions are: strong is sticky, weak to strong
// happens on a read, weak to none happens on a write, and none to weak happens
// on a CSP. When reconciling multiple code paths, the strongest wins, where
// strong > weak and weak > none. Loops are repeated until the reconciliations
// between the N'th and N+1'th iteration are all no-ops. There can be multiple
// reconciliations per iteration, due to break and continue statements.
//
// Care is taken with a coroutine call in a statement or expression. Arguments
// to the coroutine are 'inside' and are before the CSP. The rest of the
// expression is 'outside' and are after the CSP.
import (
"fmt"
a "github.com/google/wuffs/lang/ast"
t "github.com/google/wuffs/lang/token"
)
// subExprFilter is used, when analyzing an expression containing a coroutine
// call, for multiple analysis passes: before, during and after that call.
type subExprFilter uint32
const (
subExprFilterNone = subExprFilter(0)
subExprFilterBeforeCoroutine = subExprFilter(1)
subExprFilterDuringCoroutine = subExprFilter(2)
subExprFilterAfterCoroutine = subExprFilter(3)
)
// resumability tracks whether a local variable's value will need to be kept
// across CSPs (coroutine suspension points).
type resumability uint32
const (
resumabilityNone = resumability(0)
resumabilityWeak = resumability(1)
resumabilityStrong = resumability(2)
)
// resumabilities is a slice of resumability values, one per local variable.
type resumabilities []resumability
func (r resumabilities) clone() resumabilities {
return append(resumabilities(nil), r...)
}
func (r resumabilities) reconcile(s resumabilities) (changed bool) {
if len(r) != len(s) {
panic("resumabilities have different length")
}
for i := range r {
if r[i] < s[i] {
r[i] = s[i]
changed = true
}
}
return changed
}
func (r resumabilities) lowerWeakToNone(i int) {
if r[i] == resumabilityWeak {
r[i] = resumabilityNone
}
}
func (r resumabilities) raiseWeakToStrong(i int) {
if r[i] == resumabilityWeak {
r[i] = resumabilityStrong
}
}
func (r resumabilities) raiseNoneToWeak() {
for i, x := range r {
if x == resumabilityNone {
r[i] = resumabilityWeak
}
}
}
type loopResumable struct {
before resumabilities
after resumabilities
changed bool
}
type resumabilityHelper struct {
tm *t.Map
vars map[t.ID]int // Maps from local variable name to resumabilities index.
loops map[a.Loop]*loopResumable
}
func (g *gen) findVars() error {
h := resumabilityHelper{
tm: g.tm,
vars: map[t.ID]int{},
loops: map[a.Loop]*loopResumable{},
}
f := g.currFunk.astFunc
for _, n := range f.Body() {
if n.Kind() != a.KVar {
break
}
g.currFunk.varList = append(g.currFunk.varList, n.AsVar())
h.vars[n.AsVar().Name()] = len(h.vars)
}
if f.Effect().Coroutine() {
r := make(resumabilities, len(h.vars))
if err := h.doBlock(r, f.Body(), 0); err != nil {
return err
}
g.currFunk.varResumables = map[t.ID]bool{}
for i, v := range g.currFunk.varList {
g.currFunk.varResumables[v.Name()] = r[i] == resumabilityStrong
}
}
return nil
}
func (h *resumabilityHelper) doBlock(r resumabilities, block []*a.Node, depth uint32) error {
if depth > a.MaxBodyDepth {
return fmt.Errorf("body recursion depth too large")
}
depth++
loop:
for _, o := range block {
switch o.Kind() {
case a.KAssign:
if err := h.doAssign(r, o.AsAssign(), depth); err != nil {
return err
}
case a.KExpr:
if err := h.doExpr(r, o.AsExpr()); err != nil {
return err
}
case a.KIOBind:
if err := h.doIOBind(r, o.AsIOBind(), depth); err != nil {
return err
}
case a.KIf:
if err := h.doIf(r, o.AsIf(), depth); err != nil {
return err
}
case a.KIterate:
if err := h.doIterate(r, o.AsIterate(), depth); err != nil {
return err
}
case a.KJump:
if err := h.doJump(r, o.AsJump(), depth); err != nil {
return err
}
break loop
case a.KRet:
if err := h.doRet(r, o.AsRet(), depth); err != nil {
return err
}
if o.AsRet().Keyword() == t.IDReturn {
break loop
}
case a.KVar:
if err := h.doVar(r, o.AsVar(), depth); err != nil {
return err
}
case a.KWhile:
if err := h.doWhile(r, o.AsWhile(), depth); err != nil {
return err
}
}
}
return nil
}
func (h *resumabilityHelper) doAssign(r resumabilities, n *a.Assign, depth uint32) error {
if err := h.doExpr(r, n.RHS()); err != nil {
return err
}
if n.LHS() == nil {
return nil
}
// If the LHS is not a local variable (e.g. "this.foo[bar] = etc", or if
// the LHS is implicitly also on the RHS (e.g. for a += or *= operator),
// walk the LHS Expr.
if n.LHS().Operator() != 0 || (n.Operator() != t.IDEq && n.Operator() != t.IDEqQuestion) {
if err := h.doExpr(r, n.LHS()); err != nil {
return err
}
}
// If the LHS is just a local variable, then call lowerWeakToNone.
if lhs := n.LHS(); lhs.Operator() == 0 {
if i, ok := h.vars[lhs.Ident()]; !ok {
return fmt.Errorf("unrecognized variable %q", lhs.Ident().Str(h.tm))
} else {
r.lowerWeakToNone(i)
}
}
return nil
}
func (h *resumabilityHelper) doExpr(r resumabilities, n *a.Expr) error {
if !n.Effect().Coroutine() {
return h.doExpr1(r, n, subExprFilterNone, 0)
}
for sef := subExprFilterBeforeCoroutine; sef <= subExprFilterAfterCoroutine; sef++ {
if err := h.doExpr1(r, n, sef, 0); err != nil {
return err
}
}
return nil
}
func (h *resumabilityHelper) doExpr1(r resumabilities, n *a.Expr, sef subExprFilter, depth uint32) error {
if depth > a.MaxBodyDepth {
return fmt.Errorf("body recursion depth too large")
}
depth++
processOnlySubExprs := false
if sef != subExprFilterNone {
switch sef {
case subExprFilterBeforeCoroutine:
if !n.Effect().Coroutine() {
return nil
}
sef = subExprFilterNone
processOnlySubExprs = true
case subExprFilterDuringCoroutine:
if n.Effect().Coroutine() {
switch n.Operator() {
case t.IDOpenParen:
r.raiseNoneToWeak()
default:
return fmt.Errorf("unrecognized ast.Expr coroutine operator")
}
return nil
}
processOnlySubExprs = true
case subExprFilterAfterCoroutine:
if n.Effect().Coroutine() {
return nil
}
}
}
for _, o := range n.AsNode().AsRaw().SubNodes() {
if o != nil && o.Kind() == a.KExpr {
if err := h.doExpr1(r, o.AsExpr(), sef, depth); err != nil {
return err
}
}
}
for _, o := range n.Args() {
e := (*a.Expr)(nil)
switch o.Kind() {
case a.KArg:
e = o.AsArg().Value()
case a.KExpr:
e = o.AsExpr()
default:
return fmt.Errorf("unrecognized arg kind")
}
if err := h.doExpr1(r, e, sef, depth); err != nil {
return err
}
}
if !processOnlySubExprs && n.Operator() == 0 {
if i, ok := h.vars[n.Ident()]; ok {
r.raiseWeakToStrong(i)
}
}
return nil
}
func (h *resumabilityHelper) doIOBind(r resumabilities, n *a.IOBind, depth uint32) error {
if err := h.doExpr(r, n.IO()); err != nil {
return err
}
if err := h.doExpr(r, n.Arg1()); err != nil {
return err
}
return h.doBlock(r, n.Body(), depth)
}
func (h *resumabilityHelper) doIf(r resumabilities, n *a.If, depth uint32) error {
scratch := make(resumabilities, len(r))
result := make(resumabilities, len(r))
for ; n != nil; n = n.ElseIf() {
if err := h.doExpr(r, n.Condition()); err != nil {
return err
}
copy(scratch, r)
if err := h.doBlock(scratch, n.BodyIfTrue(), depth); err != nil {
return err
}
result.reconcile(scratch)
copy(scratch, r)
if err := h.doBlock(scratch, n.BodyIfFalse(), depth); err != nil {
return err
}
result.reconcile(scratch)
}
copy(r, result)
return nil
}
func (h *resumabilityHelper) doIterate(r resumabilities, n *a.Iterate, depth uint32) error {
// TODO: ban jumps, rets and coroutine calls inside an iterate. Also ensure
// that the iterate variable values are all pure expressions.
for _, o := range n.Assigns() {
o := o.AsAssign()
if err := h.doExpr(r, o.RHS()); err != nil {
return err
}
name := o.LHS().Ident()
if i, ok := h.vars[name]; !ok {
return fmt.Errorf("unrecognized variable %q", name.Str(h.tm))
} else {
r.lowerWeakToNone(i)
}
}
return h.doBlock(r, n.Body(), depth)
}
func (h *resumabilityHelper) doJump(r resumabilities, n *a.Jump, depth uint32) error {
l := h.loops[n.JumpTarget()]
switch n.Keyword() {
case t.IDBreak:
l.changed = l.before.reconcile(r) || l.changed
case t.IDContinue:
l.changed = l.after.reconcile(r) || l.changed
default:
return fmt.Errorf("unrecognized ast.Jump keyword")
}
return nil
}
func (h *resumabilityHelper) doRet(r resumabilities, n *a.Ret, depth uint32) error {
if err := h.doExpr(r, n.Value()); err != nil {
return err
}
switch n.Keyword() {
case t.IDReturn:
// No-op.
case t.IDYield:
r.raiseNoneToWeak()
default:
return fmt.Errorf("unrecognized ast.Ret keyword")
}
return nil
}
func (h *resumabilityHelper) doVar(r resumabilities, n *a.Var, depth uint32) error {
name := n.Name()
if i, ok := h.vars[name]; !ok {
return fmt.Errorf("unrecognized variable %q", name.Str(h.tm))
} else {
r.lowerWeakToNone(i)
}
return nil
}
func (h *resumabilityHelper) doWhile(r resumabilities, n *a.While, depth uint32) error {
l := &loopResumable{
before: make(resumabilities, len(r)),
after: make(resumabilities, len(r)),
changed: false,
}
h.loops[n] = l
copy(l.before, r)
if err := h.doExpr(r, n.Condition()); err != nil {
return err
}
copy(l.after, r)
for {
copy(r, l.after)
if err := h.doBlock(r, n.Body(), depth); err != nil {
return err
}
l.changed = l.before.reconcile(r) || l.changed
copy(r, l.before)
if err := h.doExpr(r, n.Condition()); err != nil {
return err
}
l.changed = l.after.reconcile(r) || l.changed
if !l.changed {
break
}
l.changed = false
}
copy(r, l.after)
return nil
}
-524
View File
@@ -1,524 +0,0 @@
// Copyright 2017 The Wuffs Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cgen
import (
"fmt"
"strings"
a "github.com/google/wuffs/lang/ast"
t "github.com/google/wuffs/lang/token"
)
func (g *gen) writeStatement(b *buffer, n *a.Node, depth uint32) error {
if depth > a.MaxBodyDepth {
return fmt.Errorf("body recursion depth too large")
}
depth++
if n.Kind() == a.KAssert {
// Assertions only apply at compile-time.
return nil
}
if (n.Kind() == a.KAssign) && (n.AsAssign().LHS() != nil) && n.AsAssign().RHS().Effect().Coroutine() {
// Put n's code into its own block, to restrict the scope of the
// tPrefix temporary variables. This helps avoid "jump bypasses
// variable initialization" compiler warnings with the coroutine
// suspension points.
b.writes("{\n")
defer b.writes("}\n")
}
if g.genlinenum {
filename, line := n.AsRaw().FilenameLine()
if i := strings.LastIndexByte(filename, '/'); i >= 0 {
filename = filename[i+1:]
}
if i := strings.LastIndexByte(filename, '\\'); i >= 0 {
filename = filename[i+1:]
}
b.printf("// %s:%d\n", filename, line)
}
switch n.Kind() {
case a.KAssign:
n := n.AsAssign()
return g.writeStatementAssign(b, n.Operator(), n.LHS(), n.RHS(), depth)
case a.KIOBind:
return g.writeStatementIOBind(b, n.AsIOBind(), depth)
case a.KIf:
return g.writeStatementIf(b, n.AsIf(), depth)
case a.KIterate:
return g.writeStatementIterate(b, n.AsIterate(), depth)
case a.KJump:
return g.writeStatementJump(b, n.AsJump(), depth)
case a.KRet:
return g.writeStatementRet(b, n.AsRet(), depth)
case a.KVar:
return nil
case a.KWhile:
return g.writeStatementWhile(b, n.AsWhile(), depth)
}
return fmt.Errorf("unrecognized ast.Kind (%s) for writeStatement", n.Kind())
}
func (g *gen) writeStatementAssign(b *buffer, op t.ID, lhs *a.Expr, rhs *a.Expr, depth uint32) error {
if depth > a.MaxExprDepth {
return fmt.Errorf("expression recursion depth too large")
}
depth++
hack, err := g.writeStatementAssign0(b, op, lhs, rhs)
if err != nil {
return err
}
if lhs != nil {
if err := g.writeStatementAssign1(b, op, lhs, rhs); err != nil {
return err
}
}
if hack {
if err := g.writeLoadExprDerivedVars(b, rhs); err != nil {
return err
}
}
return nil
}
func (g *gen) writeStatementAssign0(b *buffer, op t.ID, lhs *a.Expr, rhs *a.Expr) (bool, error) {
if err := g.writeBuiltinQuestionCall(b, rhs, 0); err != errNoSuchBuiltin {
return false, err
}
doWork, hack := (lhs == nil) || rhs.Effect().Coroutine(), false
if !doWork && (rhs.Operator() == t.IDOpenParen) && (len(g.currFunk.derivedVars) > 0) {
// TODO: tighten this heuristic for filtering out all but user-defined
// method receivers.
method := rhs.LHS().AsExpr()
if (method == nil) || !method.LHS().MType().IsPointerType() {
return false, nil
}
for _, arg := range rhs.Args() {
v := arg.AsArg().Value()
// TODO: walk v, not just check it for an exact match for
// "args.foo", for some foo in derivedVars?
if v.Operator() != t.IDDot {
continue
}
if vLHS := v.LHS().AsExpr(); vLHS.Operator() != 0 || vLHS.Ident() != t.IDArgs {
continue
}
if _, ok := g.currFunk.derivedVars[v.Ident()]; ok {
doWork, hack = true, true
break
}
}
}
if doWork {
if err := g.writeSaveExprDerivedVars(b, rhs); err != nil {
return false, err
}
if op == t.IDEqQuestion {
if g.currFunk.tempW > maxTemp {
return false, fmt.Errorf("too many temporary variables required")
}
temp := g.currFunk.tempW
g.currFunk.tempW++
b.printf("wuffs_base__status %s%d = ", tPrefix, temp)
} else if rhs.Effect().Coroutine() {
if err := g.writeCoroSuspPoint(b, false); err != nil {
return false, err
}
b.writes("status = ")
} else if rhs.Effect().Coroutine() {
b.writes("status = ")
}
if !hack {
if err := g.writeExpr(b, rhs, 0); err != nil {
return false, err
}
b.writes(";\n")
if err := g.writeLoadExprDerivedVars(b, rhs); err != nil {
return false, err
}
}
if op != t.IDEqQuestion && rhs.Effect().Coroutine() {
b.writes("if (status) { goto suspend; }\n")
}
}
return hack, nil
}
func (g *gen) writeStatementAssign1(b *buffer, op t.ID, lhs *a.Expr, rhs *a.Expr) error {
lhsBuf := buffer(nil)
if err := g.writeExpr(&lhsBuf, lhs, 0); err != nil {
return err
}
opName, closer := "", ""
if lTyp := lhs.MType(); lTyp.IsArrayType() {
b.writes("memcpy(")
opName, closer = ",", fmt.Sprintf(", sizeof(%s))", lhsBuf)
} else {
switch op {
case t.IDTildeSatPlusEq, t.IDTildeSatMinusEq:
uBits := uintBits(lTyp.QID())
if uBits == 0 {
return fmt.Errorf("unsupported tilde-operator type %q", lTyp.Str(g.tm))
}
uOp := "add"
if op != t.IDTildeSatPlusEq {
uOp = "sub"
}
b.printf("wuffs_base__u%d__sat_%s_indirect(&", uBits, uOp)
opName, closer = ",", ")"
default:
opName = cOpName(op)
if opName == "" {
return fmt.Errorf("unrecognized operator %q", op.AmbiguousForm().Str(g.tm))
}
}
}
b.writex(lhsBuf)
b.writes(opName)
if rhs.Effect().Coroutine() {
if g.currFunk.tempR != (g.currFunk.tempW - 1) {
return fmt.Errorf("internal error: temporary variable count out of sync")
}
b.printf("%s%d", tPrefix, g.currFunk.tempR)
g.currFunk.tempR++
} else if err := g.writeExpr(b, rhs, 0); err != nil {
return err
}
b.writes(closer)
b.writes(";\n")
return nil
}
func (g *gen) writeStatementIOBind(b *buffer, n *a.IOBind, depth uint32) error {
if g.currFunk.ioBinds > maxIOBinds {
return fmt.Errorf("too many temporary variables required")
}
ioBindNum := g.currFunk.ioBinds
g.currFunk.ioBinds++
// TODO: do these variables need to be func-scoped (bigger scope)
// instead of block-scoped (smaller scope) if the coro_susp_point
// switch can jump past this initialization??
b.writes("{\n")
{
e := n.IO()
// TODO: restrict (in the type checker or parser) that e is either a
// local variable or args.foo?
prefix := vPrefix
if e.Operator() != 0 {
prefix = aPrefix
}
cTyp := "reader"
if e.MType().QID()[1] == t.IDIOWriter {
cTyp = "writer"
}
name := e.Ident().Str(g.tm)
b.printf("wuffs_base__io_%s %s%d_%s%s = %s%s;\n",
cTyp, oPrefix, ioBindNum, prefix, name, prefix, name)
// TODO: save / restore all iop vars, not just for local IO vars? How
// does this work if the io_bind body advances these pointers, either
// directly or by calling other funcs?
if e.Operator() == 0 {
b.printf("uint8_t *%s%d_%s%s%s = %s%s%s;\n",
oPrefix, ioBindNum, iopPrefix, prefix, name, iopPrefix, prefix, name)
b.printf("uint8_t *%s%d_%s%s%s = %s%s%s;\n",
oPrefix, ioBindNum, io1Prefix, prefix, name, io1Prefix, prefix, name)
}
if n.Keyword() == t.IDIOBind {
b.printf("wuffs_base__io_%s__set(&%s%s, &u_%s, &iop_%s%s, &io1_%s%s,",
cTyp, prefix, name, name, prefix, name, prefix, name)
if err := g.writeExpr(b, n.Arg1(), 0); err != nil {
return err
}
b.writes(");\n")
} else {
// TODO: restrict (in the type checker or parser) that e is
// args.foo?
b.printf("wuffs_base__io_%s__set_limit(&%s%s, iop_%s%s,\n", cTyp, prefix, name, prefix, name)
if err := g.writeExpr(b, n.Arg1(), 0); err != nil {
return err
}
b.writes(");\n")
}
}
for _, o := range n.Body() {
if err := g.writeStatement(b, o, depth); err != nil {
return err
}
}
{
e := n.IO()
prefix := vPrefix
if e.Operator() != 0 {
prefix = aPrefix
}
name := e.Ident().Str(g.tm)
b.printf("%s%s = %s%d_%s%s;\n",
prefix, name, oPrefix, ioBindNum, prefix, name)
if e.Operator() == 0 {
b.printf("%s%s%s = %s%d_%s%s%s;\n",
iopPrefix, prefix, name, oPrefix, ioBindNum, iopPrefix, prefix, name)
b.printf("%s%s%s = %s%d_%s%s%s;\n",
io1Prefix, prefix, name, oPrefix, ioBindNum, io1Prefix, prefix, name)
}
}
b.writes("}\n")
return nil
}
func (g *gen) writeStatementIf(b *buffer, n *a.If, depth uint32) error {
// For an "if true { etc }", just write the "etc".
if cv := n.Condition().ConstValue(); (cv != nil) && (cv.Cmp(one) == 0) &&
(n.ElseIf() == nil) && (len(n.BodyIfFalse()) == 0) {
for _, o := range n.BodyIfTrue() {
if err := g.writeStatement(b, o, depth); err != nil {
return err
}
}
return nil
}
for {
condition := buffer(nil)
if err := g.writeExpr(&condition, n.Condition(), 0); err != nil {
return err
}
// Calling trimParens avoids clang's -Wparentheses-equality warning.
b.printf("if (%s) {\n", trimParens(condition))
for _, o := range n.BodyIfTrue() {
if err := g.writeStatement(b, o, depth); err != nil {
return err
}
}
if bif := n.BodyIfFalse(); len(bif) > 0 {
b.writes("} else {\n")
for _, o := range bif {
if err := g.writeStatement(b, o, depth); err != nil {
return err
}
}
break
}
n = n.ElseIf()
if n == nil {
break
}
b.writes("} else ")
}
b.writes("}\n")
return nil
}
func (g *gen) writeStatementIterate(b *buffer, n *a.Iterate, depth uint32) error {
assigns := n.Assigns()
if len(assigns) == 0 {
return nil
}
if len(assigns) != 1 {
return fmt.Errorf("TODO: iterate over more than one assign")
}
o := assigns[0].AsAssign()
name := o.LHS().Ident().Str(g.tm)
b.writes("{\n")
// TODO: don't assume that the slice is a slice of base.u8. In
// particular, the code gen can be subtle if the slice element type has
// zero size, such as the empty struct.
b.printf("wuffs_base__slice_u8 %sslice_%s =", iPrefix, name)
if err := g.writeExpr(b, o.RHS(), 0); err != nil {
return err
}
b.writes(";\n")
b.printf("%s%s = %sslice_%s;\n", vPrefix, name, iPrefix, name)
// TODO: look at n.HasContinue() and n.HasBreak().
round := uint32(0)
for ; n != nil; n = n.ElseIterate() {
length := n.Length().SmallPowerOf2Value()
unroll := n.Unroll().SmallPowerOf2Value()
for {
if err := g.writeIterateRound(b, name, n.Body(), round, depth, length, unroll); err != nil {
return err
}
round++
if unroll == 1 {
break
}
unroll = 1
}
}
b.writes("}\n")
return nil
}
func (g *gen) writeStatementJump(b *buffer, n *a.Jump, depth uint32) error {
jt, err := g.currFunk.jumpTarget(n.JumpTarget())
if err != nil {
return err
}
keyword := "continue"
if n.Keyword() == t.IDBreak {
keyword = "break"
}
b.printf("goto label_%d_%s;\n", jt, keyword)
return nil
}
func (g *gen) writeStatementRet(b *buffer, n *a.Ret, depth uint32) error {
retExpr := n.Value()
if g.currFunk.astFunc.Effect().Coroutine() ||
(g.currFunk.returnsStatus && (len(g.currFunk.derivedVars) > 0)) {
isOK := false
b.writes("status = ")
if retExpr.Operator() == 0 && retExpr.Ident() == t.IDOk {
b.writes("NULL")
isOK = true
} else {
if retExpr.Ident().IsStrLiteral(g.tm) {
msg, _ := t.Unescape(retExpr.Ident().Str(g.tm))
isOK = statusMsgIsWarning(msg)
}
if err := g.writeExpr(
b, retExpr, depth); err != nil {
return err
}
}
b.writes(";")
if n.Keyword() == t.IDYield {
return g.writeCoroSuspPoint(b, true)
}
if n.RetsError() {
b.writes("goto exit;")
} else if isOK {
g.currFunk.hasGotoOK = true
b.writes("goto ok;")
} else {
g.currFunk.hasGotoOK = true
// TODO: the "goto exit"s can be "goto ok".
b.writes("if (wuffs_base__status__is_error(status)) { goto exit; }" +
"else if (wuffs_base__status__is_suspension(status)) { " +
"status = wuffs_base__error__cannot_return_a_suspension; goto exit; } goto ok;")
}
return nil
}
b.writes("return ")
if g.currFunk.astFunc.Out() == nil {
b.writes("wuffs_base__make_empty_struct()")
} else if err := g.writeExpr(b, retExpr, depth); err != nil {
return err
}
b.writeb(';')
return nil
}
func (g *gen) writeStatementWhile(b *buffer, n *a.While, depth uint32) error {
if n.HasContinue() {
jt, err := g.currFunk.jumpTarget(n)
if err != nil {
return err
}
b.printf("label_%d_continue:;\n", jt)
}
condition := buffer(nil)
if err := g.writeExpr(&condition, n.Condition(), 0); err != nil {
return err
}
// Calling trimParens avoids clang's -Wparentheses-equality warning.
b.printf("while (%s) {\n", trimParens(condition))
for _, o := range n.Body() {
if err := g.writeStatement(b, o, depth); err != nil {
return err
}
}
b.writes("}\n")
if n.HasBreak() {
jt, err := g.currFunk.jumpTarget(n)
if err != nil {
return err
}
b.printf("label_%d_break:;\n", jt)
}
return nil
}
func (g *gen) writeIterateRound(b *buffer, name string, body []*a.Node, round uint32, depth uint32, length int, unroll int) error {
b.printf("%s%s.len = %d;\n", vPrefix, name, length)
b.printf("uint8_t* %send%d_%s = %sslice_%s.ptr + (%sslice_%s.len / %d) * %d;\n",
iPrefix, round, name, iPrefix, name, iPrefix, name, length*unroll, length*unroll)
b.printf("while (%s%s.ptr < %send%d_%s) {\n", vPrefix, name, iPrefix, round, name)
for i := 0; i < unroll; i++ {
for _, o := range body {
if err := g.writeStatement(b, o, depth); err != nil {
return err
}
}
b.printf("%s%s.ptr += %d;\n", vPrefix, name, length)
}
b.writes("}\n")
return nil
}
func (g *gen) writeCoroSuspPoint(b *buffer, maybeSuspend bool) error {
const maxCoroSuspPoint = 0xFFFFFFFF
g.currFunk.coroSuspPoint++
if g.currFunk.coroSuspPoint == maxCoroSuspPoint {
return fmt.Errorf("too many coroutine suspension points required")
}
macro := ""
if maybeSuspend {
macro = "_MAYBE_SUSPEND"
}
b.printf("WUFFS_BASE__COROUTINE_SUSPENSION_POINT%s(%d);\n", macro, g.currFunk.coroSuspPoint)
return nil
}
func trimParens(b []byte) []byte {
if len(b) > 1 && b[0] == '(' && b[len(b)-1] == ')' {
return b[1 : len(b)-1]
}
return b
}
-312
View File
@@ -1,312 +0,0 @@
// Copyright 2017 The Wuffs Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package cgen
import (
"errors"
"fmt"
a "github.com/google/wuffs/lang/ast"
t "github.com/google/wuffs/lang/token"
)
var errNeedDerivedVar = errors.New("cgen: internal error: need derived var")
func (g *gen) needDerivedVar(name t.ID) bool {
for _, o := range g.currFunk.astFunc.Body() {
err := o.Walk(func(p *a.Node) error {
// Look for p matching "args.name.etc(etc)".
if p.Kind() != a.KExpr {
return nil
}
q := p.AsExpr()
if q.Operator() != t.IDOpenParen {
return nil
}
q = q.LHS().AsExpr()
if q.Operator() != t.IDDot {
return nil
}
q = q.LHS().AsExpr()
if q.Operator() != t.IDDot || q.Ident() != name {
return nil
}
q = q.LHS().AsExpr()
if q.Operator() != 0 || q.Ident() != t.IDArgs {
return nil
}
return errNeedDerivedVar
})
if err == errNeedDerivedVar {
return true
}
}
return false
}
func (g *gen) findDerivedVars() {
for _, o := range g.currFunk.astFunc.In().Fields() {
o := o.AsField()
if !o.XType().IsIOType() || !g.needDerivedVar(o.Name()) {
continue
}
if g.currFunk.derivedVars == nil {
g.currFunk.derivedVars = map[t.ID]struct{}{}
}
g.currFunk.derivedVars[o.Name()] = struct{}{}
}
}
func (g *gen) writeLoadDerivedVar(b *buffer, hack string, prefix string, name t.ID, typ *a.TypeExpr, header bool) error {
// TODO: remove this hack. We're picking up the wrong name for "src:r,
// dummy:args.src".
if name.Str(g.tm) == "dummy" {
name = g.tm.ByName("src")
}
// TODO: also remove this hack.
if hack == "w" {
b.printf("%s%sw = %sw.data.ptr + %sw.meta.wi;\n", iopPrefix, vPrefix, uPrefix, uPrefix)
return nil
} else if hack == "r" {
b.printf("%s%sr = %sr.data.ptr + %sr.meta.ri;\n", iopPrefix, vPrefix, uPrefix, uPrefix)
return nil
}
if !typ.IsIOType() {
return nil
}
if g.currFunk.derivedVars == nil {
return nil
}
if _, ok := g.currFunk.derivedVars[name]; !ok {
return nil
}
preName := prefix + name.Str(g.tm)
i0, i1 := "meta.ri", "meta.wi"
if typ.QID()[1] == t.IDIOWriter {
i0, i1 = "meta.wi", "data.len"
}
if header {
b.printf("uint8_t* %s%s = NULL;", iopPrefix, preName)
b.printf("uint8_t* %s%s WUFFS_BASE__POTENTIALLY_UNUSED = NULL;", io0Prefix, preName)
b.printf("uint8_t* %s%s WUFFS_BASE__POTENTIALLY_UNUSED = NULL;", io1Prefix, preName)
}
b.printf("if (%s.private_impl.buf) {", preName)
b.printf("%s%s = %s.private_impl.buf->data.ptr + %s.private_impl.buf->%s;",
iopPrefix, preName, preName, preName, i0)
if header {
b.printf("if (!%s.private_impl.mark) {", preName)
b.printf("%s.private_impl.mark = %s%s;", preName, iopPrefix, preName)
b.printf("%s.private_impl.limit = %s.private_impl.buf->data.ptr + %s.private_impl.buf->%s;",
preName, preName, preName, i1)
b.printf("}\n")
if typ.QID()[1] == t.IDIOWriter {
b.printf("if (%s.private_impl.buf->meta.closed) {", preName)
b.printf("%s.private_impl.limit = %s%s;", preName, iopPrefix, preName)
b.printf("}\n")
}
b.printf("%s%s = %s.private_impl.mark;", io0Prefix, preName, preName)
b.printf("%s%s = %s.private_impl.limit;", io1Prefix, preName, preName)
}
b.printf("}\n")
return nil
}
func (g *gen) writeSaveDerivedVar(b *buffer, hack string, prefix string, name t.ID, typ *a.TypeExpr) error {
// TODO: remove this hack. We're picking up the wrong name for "src:r,
// dummy:args.src".
if name.Str(g.tm) == "dummy" {
name = g.tm.ByName("src")
}
// TODO: also remove this hack.
if hack == "w" {
b.printf("%sw.meta.wi = %s%sw - %sw.data.ptr;\n", uPrefix, iopPrefix, vPrefix, uPrefix)
return nil
} else if hack == "r" {
b.printf("%sr.meta.ri = %s%sr - %sr.data.ptr;\n", uPrefix, iopPrefix, vPrefix, uPrefix)
return nil
}
if !typ.IsIOType() {
return nil
}
if g.currFunk.derivedVars == nil {
return nil
}
if _, ok := g.currFunk.derivedVars[name]; !ok {
return nil
}
preName := prefix + name.Str(g.tm)
i0 := "ri"
if typ.QID()[1] == t.IDIOWriter {
i0 = "wi"
}
b.printf("if (%s.private_impl.buf) {", preName)
b.printf("%s.private_impl.buf->meta.%s = %s%s - %s.private_impl.buf->data.ptr;",
preName, i0, iopPrefix, preName, preName)
b.printf("}\n")
return nil
}
func (g *gen) writeLoadExprDerivedVars(b *buffer, n *a.Expr) error {
if g.currFunk.derivedVars == nil {
return nil
}
if n.Operator() != t.IDOpenParen {
return nil
}
for _, o := range n.Args() {
o := o.AsArg()
prefix := aPrefix
// TODO: don't hard-code these.
hack := ""
if s := o.Value().Str(g.tm); s != "args.dst" && s != "args.src" && s != "w" && s != "r" {
continue
} else if s == "w" || s == "r" {
prefix = vPrefix
hack = s
}
if err := g.writeLoadDerivedVar(b, hack, prefix, o.Name(), o.Value().MType(), false); err != nil {
return err
}
}
return nil
}
func (g *gen) writeSaveExprDerivedVars(b *buffer, n *a.Expr) error {
if g.currFunk.derivedVars == nil {
return nil
}
if n.Operator() != t.IDOpenParen {
return nil
}
for _, o := range n.Args() {
o := o.AsArg()
prefix := aPrefix
// TODO: don't hard-code these.
hack := ""
if s := o.Value().Str(g.tm); s != "args.dst" && s != "args.src" && s != "w" && s != "r" {
continue
} else if s == "w" || s == "r" {
prefix = vPrefix
hack = s
}
if err := g.writeSaveDerivedVar(b, hack, prefix, o.Name(), o.Value().MType()); err != nil {
return err
}
}
return nil
}
func (g *gen) writeResumeSuspend1(b *buffer, f *funk, n *a.Var, suspend bool) error {
if typ := n.XType(); typ.HasPointers() {
return nil
} else if f.varResumables == nil || !f.varResumables[n.Name()] {
return nil
} else {
local := fmt.Sprintf("%s%s", vPrefix, n.Name().Str(g.tm))
lhs := local
// TODO: don't hard-code [0], and allow recursive coroutines.
rhs := fmt.Sprintf("self->private_data.%s%s[0].%s", sPrefix, g.currFunk.astFunc.FuncName().Str(g.tm), lhs)
if suspend {
lhs, rhs = rhs, lhs
}
switch typ.Decorator() {
case 0:
b.printf("%s = %s;\n", lhs, rhs)
return nil
case t.IDArray:
inner := typ.Inner()
if inner.Decorator() != 0 {
break
}
qid := inner.QID()
if qid[0] != t.IDBase {
break
}
switch qid[1] {
case t.IDU8, t.IDU16, t.IDU32, t.IDU64:
b.printf("memcpy(%s, %s, sizeof(%s));\n", lhs, rhs, local)
return nil
}
}
}
return fmt.Errorf("cannot resume or suspend a local variable %q of type %q",
n.Name().Str(g.tm), n.XType().Str(g.tm))
}
func (g *gen) writeResumeSuspend(b *buffer, f *funk, suspend bool) error {
for _, n := range f.varList {
if err := g.writeResumeSuspend1(b, f, n, suspend); err != nil {
return err
}
}
return nil
}
func (g *gen) writeVars(b *buffer, f *funk, inStructDecl bool) error {
for _, n := range f.varList {
typ := n.XType()
if inStructDecl {
if typ.HasPointers() || f.varResumables == nil || !f.varResumables[n.Name()] {
continue
}
}
name := n.Name().Str(g.tm)
if err := g.writeCTypeName(b, typ, vPrefix, name); err != nil {
return err
}
if inStructDecl {
b.writes(";\n")
} else if typ.IsNumType() {
b.writes(" = 0;\n")
} else if typ.IsBool() {
b.writes(" = false;\n")
} else if typ.IsStatus() {
b.writes(" = NULL;\n")
} else if typ.IsIOType() {
typName := "reader"
if typ.QID()[1] == t.IDIOWriter {
typName = "writer"
}
b.printf(" = wuffs_base__utility__null_io_%s();\n", typName)
} else {
b.writes(" = {0};\n")
}
if typ.IsIOType() {
b.printf("wuffs_base__io_buffer %s%s WUFFS_BASE__POTENTIALLY_UNUSED = "+
"wuffs_base__utility__null_io_buffer();\n", uPrefix, name)
preName := vPrefix + name
// TODO: io0_etc variables?
b.printf("uint8_t* %s%s WUFFS_BASE__POTENTIALLY_UNUSED = NULL;\n", iopPrefix, preName)
b.printf("uint8_t* %s%s WUFFS_BASE__POTENTIALLY_UNUSED = NULL;\n", io1Prefix, preName)
}
}
return nil
}
+1 -1
View File
@@ -19,7 +19,7 @@ import (
"fmt"
"os"
"github.com/google/wuffs/cmd/wuffs-c/internal/cgen"
"github.com/google/wuffs/internal/cgen"
)
func main() {