repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
|---|---|---|
Drengr-Engine/Drengr
|
Engine/src/core/graphics/cameras/Camera.h
|
#pragma once
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/rotate_vector.hpp>
#include <glm/gtx/vector_angle.hpp>
#include "../assets/Shader.h"
namespace Drengr {
class Camera
{
public:
// Stores the main vectors of the camera
static glm::vec3 m_position;
static glm::vec3 Orientation;// = glm::vec3(0.0f, 0.0f, -1.0f);
static glm::vec3 Up; //= glm::vec3(0.0f, 1.0f, 0.0f);
// Prevents the camera from jumping around when first clicking left click
//bool firstClick = true;
// Stores the width and height of the window
static int m_width;
static int m_height;
// Adjust the speed of the camera and it's sensitivity when looking around
static float m_speed;
static float m_sensitivity;
static void SetAspectRatio(int _width, int _height);
// Camera constructor to set up initial values
Camera(int m_width, int m_height, glm::vec3 position);
static glm::mat4 m_projection;
// Updates and exports the camera matrix to the Vertex Shader
static void UpdateProjectionMatrix(float FOVdeg, float nearPlane, float farPlane, Shader& shader, const char* uniform);
// Handles camera inputs
static void Inputs(GLFWwindow* window);
};
}
|
Drengr-Engine/Drengr
|
Engine/src/core/windows/ui/UI.h
|
<filename>Engine/src/core/windows/ui/UI.h
#pragma once
#include "../Window.h"
#include "UiWindows.h"
#include <imgui/imgui_internal.h>
#include <core/graphics/assets/Texture.h>
#include <fstream>
#include <vector>
namespace Drengr {
namespace UI {
class UIManager {
public:
UIManager();
virtual ~UIManager();
virtual void Update();
void AddWidgit(UIWindow* widgit);
private:
void SetStyle();
void ShowDock(bool* pOpen);
std::vector<UIWindow*> widgits;
};
class UI : public UIManager
{
public:
UI();
~UI();
virtual void Update() override;
private:
void BackupContext();
};
}
}
|
Drengr-Engine/Drengr
|
Engine/src/core/windows/Window.h
|
#pragma once
#include <debug/Debugger.h>
#include <glad/glad.h>
#include <GLFW/glfw3.h>
namespace Drengr{
class Window
{
public:
Window();
~Window();
static bool Create(const char* windowTitle, int m_width, int m_height, bool maximized = true);
static bool ShouldClose();
static void SwapBuffers();
static void Shutdown();
static GLFWwindow* GetGLFWWindow();
private:
static GLFWwindow* m_window;
};
}
|
Drengr-Engine/Drengr
|
Engine/src/core/windows/ui/EditorWindow.h
|
<filename>Engine/src/core/windows/ui/EditorWindow.h
#pragma once
#include "UiWindow.h"
namespace Drengr {
namespace UI {
class EditorWindow : public UIWindow
{
// Inherited via UIWindow
virtual void Draw() override;
};
}
}
|
Drengr-Engine/Drengr
|
Engine/src/core/graphics/assets/Texture.h
|
#pragma once
#include "Shader.h"
#include "stbi_image/stbi_image.h"
namespace Drengr {
class Texture {
public:
Texture(const char* img_filePath, const char* textureType, unsigned int insertSlot, GLenum format = GL_RGBA, GLenum pixelFormat = GL_UNSIGNED_BYTE);
void AssignTextureUnit(Shader& shader, const char* uniform, unsigned int unit);
const char* GetType();
unsigned int Get();
void Bind();
void Unbind();
void Delete();
private:
const char* m_type;
unsigned int m_ID;
unsigned int m_unit;
};
}
|
Drengr-Engine/Drengr
|
Engine/src/core/graphics/assets/Mesh.h
|
#pragma once
#include "../buffers/VertexArrayObject.h"
#include "../buffers/ElementBuffer.h"
#include "../cameras/Camera.h"
#include "Texture.h"
namespace Drengr {
class Mesh
{
public:
Mesh(std::vector<Vertex>& vertices, std::vector<unsigned int>& indices, std::vector<Texture>& textures);
VertexArrayObject vao;
void Draw(Shader& shader, Camera& camera, glm::mat4 matrix = glm::mat4(1));
void SetTransform(float position_x, float position_y, float position_z);
void SetRotation(float degrees, glm::vec3 axis);
void SetScale(float x, float y, float z);
Mesh& GetMesh() { return *this; }
private:
std::vector<Vertex> vertices;
std::vector<unsigned int> indices;
std::vector<Texture> textures;
glm::vec3 m_translation = { 0,0,0 };
glm::mat4 m_rotation = glm::mat4(1.0f);
glm::vec3 m_scale = { 1,1,1 };
};
}
|
Drengr-Engine/Drengr
|
Engine/src/data structures/Vector.h
|
#pragma once
namespace Drengr {
// basic vector implementation
template<typename T>
class Vector
{
public:
Vector(int capacity = 0) : m_capacity(0), m_size(0), m_data(nullptr), b_ptr(0), f_ptr(0) { if (capacity != 0)Resize(capacity); }
Vector& operator[](int& offset){
return m_data[offset];
}
virtual ~Vector() {
}
void PushBack(T item) {
}
void PopBack() {
}
void Resize(unsigned int size=0) {
if (size == 0) {
if (m_capacity == 0) {
m_capacity = 1;
}
else {
m_capacity *= 1.50f;
}
}
else {
if (size > m_capacity) {
m_capacity = size;
}
}
}
int& Capacity() {
return m_capacity;
}
private:
int m_size;
int m_capacity;
int b_ptr;
int f_ptr;
T* m_data;
};
}
|
Drengr-Engine/Drengr
|
Engine/src/core/graphics/assets/Shader.h
|
<filename>Engine/src/core/graphics/assets/Shader.h
#pragma once
#include <glad/glad.h>
#include <string>
#include <fstream>
#include <sstream>
#include <iostream>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
namespace Drengr {
class Shader
{
public:
Shader(const char* v_path, const char* f_path);
void Activate();
void Delete();
void CompilerErrors(unsigned int shader, const char* type);
void SetUniformMat4(const char* location, glm::mat4 value);
const unsigned int& Get() const { return m_ID; }
private:
std::string ReadFile(const char* file);
unsigned int m_ID;
};
}
|
Drengr-Engine/Drengr
|
Engine/src/core/graphics/buffers/ElementBuffer.h
|
#pragma once
#include <glad/glad.h>
#include <vector>
namespace Drengr {
class ElementBuffer
{
public:
ElementBuffer(std::vector<unsigned int> indices);
void Bind();
void Unbind();
void Delete();
private:
unsigned int m_ID;
};
}
|
Drengr-Engine/Drengr
|
Engine/src/core/windows/ui/UIWindows.h
|
<reponame>Drengr-Engine/Drengr
#pragma once
// -- STOP --
// THIS FILE SHOULD ONLY INCLUDE WINDOWS TO INCLUDE TO THE
// UI MANAGER SO THAT THEY CAN BE SAFELY USED
#include "UiWindow.h"
#include "EditorWindow.h"
#include "InspectorWindow.h"
|
Drengr-Engine/Drengr
|
Engine/src/debug/Debugger.h
|
<gh_stars>0
#pragma once
#include <iostream>
#include <string>
#include <sstream>
namespace Drengr {
enum class LogPriority
{
INFO, // normal logs
WARNING, // compiler warnings to be sent to the developer
CRITICAL, // could be breaking
FATAL // need to be breaking
};
class Debugger
{
public:
static void Log(const std::string& msg, LogPriority priority = LogPriority::INFO);
static std::string fg_color;
static std::string bg_color;
static std::string reset_color;
//= "\033[38;5;15m";
};
}
|
fed-v/HarvardX_CS50x3
|
pset1/mario.c
|
<reponame>fed-v/HarvardX_CS50x3
#include <cs50.h>
#include <stdio.h>
int main(void){
// INIT VARIABLES
int flag = 1;
int height = 0;
printf("Height: ");
height = GetInt();
//GET PYRAMID HEIGHT FROM USER
do{
// CONTROL EXIT CODE OF 0
if(height==0){
return 0;
}
// CONTROL VALUE AND SET FLAG
if(height > 0 && height < 24){
flag = 0;
}else{
printf("Retry: ");
height = GetInt();
}
} while(flag == 1);
int spaces = height-1;
//COLUMNS
for(int i=1; i<=height; i++)
{
//EMPTY SPACES
for(int n=0; n<spaces; n++)
{
printf(" ");
}
//BRICKS
for(int l=0; l<i+1; l++)
{
printf("#");
}
printf("\n");
spaces = spaces-1;
}
}
|
fed-v/HarvardX_CS50x3
|
pset3/pset4/breakout.c
|
<gh_stars>0
//
// breakout.c
//
// Computer Science 50
// Problem Set 4
//
// standard libraries
#define _XOPEN_SOURCE
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
// Stanford Portable Library
#include "gevents.h"
#include "gobjects.h"
#include "gwindow.h"
// height and width of game's window in pixels
#define HEIGHT 600
#define WIDTH 400
// number of rows of bricks
#define ROWS 5
// number of columns of bricks
#define COLS 10
// radius of ball in pixels
#define RADIUS 10
// lives
#define LIVES 3
// prototypes
void initBricks(GWindow window); // DONE!
GOval initBall(GWindow window); // DONE!
GRect initPaddle(GWindow window); // DONE!
GLabel initScoreboard(GWindow window); // DONE!
void updateScoreboard(GWindow window, GLabel label, int points);
GObject detectCollision(GWindow window, GOval ball);
int main(void)
{
// seed pseudorandom number generator
srand48(time(NULL));
// instantiate window
GWindow window = newGWindow(WIDTH, HEIGHT);
// instantiate bricks
initBricks(window);
// instantiate ball, centered in middle of window
GOval ball = initBall(window);
// instantiate paddle, centered at bottom of window
GRect paddle = initPaddle(window);
// instantiate scoreboard, centered in middle of window, just above ball
GLabel label = initScoreboard(window);
// number of bricks initially
int bricks = COLS * ROWS;
// number of lives initially
int lives = LIVES;
// number of points initially
int points = 0;
// SET RANDOM INITIAL SPEED
double xSpeed = 2 + drand48();
double ySpeed = 2 + drand48();
// keep playing until game over
while (lives > 0 && bricks > 0)
{
// TODO
GEvent event = getNextEvent(MOUSE_EVENT);
if(event != NULL)
{
if(getEventType(event)== MOUSE_MOVED)
{
// SAVE X POSITION OF MOUSE DURING EVENT
int x = getX(event);
// MAKE SURE PADDLE DOESN'T GO OFFSCREEN
if(x < getWidth(window)-getWidth(paddle))
{
setLocation(paddle, x, 500);
}
}
}
// BALL MOVEMENT!
move(ball, xSpeed, ySpeed);
if(getX(ball) + getWidth(ball) >= getWidth(window) || getX(ball) <= 0)
{
xSpeed = -xSpeed;
}else if(getY(ball) <= 0)
{
ySpeed = -ySpeed;
}else if(getY(ball) + getHeight(ball) >= getHeight(window))
{
lives --;
setLocation(ball, (getWidth(window)-20)/2, (getHeight(window)-20)/2);
setLocation(paddle, (getWidth(window)-100)/2, 500);
// RESET RANDOM SPEED!
xSpeed = 2 + drand48();
ySpeed = 2 + drand48();
waitForClick();
}
pause(10);
// CHECK TO SEE IF I HIT SOMETHING
GObject objectDetected = detectCollision(window, ball);
if(objectDetected != NULL && strcmp(getType(objectDetected), "GLabel") != 0)
{
if(objectDetected == paddle)
{
ySpeed = -ySpeed;
}else if(strcmp(getType(objectDetected), "GRect") == 0)
{
removeGWindow(window, objectDetected);
ySpeed = -ySpeed;
bricks --;
points = points + 20;
updateScoreboard(window, label, points);
}
}
}
if(bricks == 0 && points == 1000)
{
removeGWindow(window, label);
GLabel highScore = newGLabel("You Won! Final score is: 1000");
setFont(highScore, "DejaVuSansMono-20");
setLocation(highScore, (getWidth(window) - getWidth(highScore)) / 2, (getHeight(window) - getHeight(highScore)) / 2);
setColor(highScore, "GRAY");
add(window, highScore);
}else{
removeGWindow(window, label);
removeGWindow(window, ball);
GLabel highScore = newGLabel("You Lose! C'mon man!");
setFont(highScore, "DejaVuSansMono-20");
setLocation(highScore, (getWidth(window) - getWidth(highScore)) / 2, (getHeight(window) - getHeight(highScore)) / 2);
setColor(highScore, "GRAY");
add(window, highScore);
}
// wait for click before exiting
waitForClick();
// game over
closeGWindow(window);
return 0;
}
/**
* Initializes window with a grid of bricks.
*/
void initBricks(GWindow window)
{
int y = 40;
char* colors[] = {"RED", "ORANGE", "YELLOW", "BLUE", "GREEN"};
for(int i=0; i<5; i++)
{
int x = 6;
for(int j=0; j<10; j++)
{
//CREATE RECTANGLE
GRect brick = newGRect(x, y, 34, 10);
setColor(brick, colors[i]);
setFilled(brick, true);
add(window, brick);
x = x + 39;
}
y = y + 15;
}
}
/**
* Instantiates ball in center of window. Returns ball.
*/
GOval initBall(GWindow window)
{
GOval ball = newGOval((getWidth(window)-20)/2, (getHeight(window)-20)/2, 20, 20);
setColor(ball, "BLACK");
setFilled(ball, true);
add(window, ball);
return ball;
}
/**
* Instantiates paddle in bottom-middle of window.
*/
GRect initPaddle(GWindow window)
{
GRect paddle = newGRect((getWidth(window)-100)/2, 500, 80, 10);
setColor(paddle, "BLACK");
setFilled(paddle, true);
add(window, paddle);
return paddle;
}
/**
* Instantiates, configures, and returns label for scoreboard.
*/
GLabel initScoreboard(GWindow window)
{
GLabel score = newGLabel("SCORE: 0");
setFont(score, "DejaVuSansMono-20");
setLocation(score, (getWidth(window) - getWidth(score)) / 2, (getHeight(window) - getHeight(score)) / 2);
setColor(score, "GRAY");
add(window, score);
return score;
}
/**
* Updates scoreboard's label, keeping it centered in window.
*/
void updateScoreboard(GWindow window, GLabel label, int points)
{
// update label
char s[12];
sprintf(s, "SCORE: %i", points);
setLabel(label, s);
// center label in window
double x = (getWidth(window) - getWidth(label)) / 2;
double y = (getHeight(window) - getHeight(label)) / 2;
setLocation(label, x, y);
}
/**
* Detects whether ball has collided with some object in window
* by checking the four corners of its bounding box (which are
* outside the ball's GOval, and so the ball can't collide with
* itself). Returns object if so, else NULL.
*/
GObject detectCollision(GWindow window, GOval ball)
{
// ball's location
double x = getX(ball);
double y = getY(ball);
// for checking for collisions
GObject object;
// check for collision at ball's top-left corner
object = getGObjectAt(window, x, y);
if (object != NULL)
{
return object;
}
// check for collision at ball's top-right corner
object = getGObjectAt(window, x + 2 * RADIUS, y);
if (object != NULL)
{
return object;
}
// check for collision at ball's bottom-left corner
object = getGObjectAt(window, x, y + 2 * RADIUS);
if (object != NULL)
{
return object;
}
// check for collision at ball's bottom-right corner
object = getGObjectAt(window, x + 2 * RADIUS, y + 2 * RADIUS);
if (object != NULL)
{
return object;
}
// no collision
return NULL;
}
|
fed-v/HarvardX_CS50x3
|
pset2/caesar.c
|
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>
int main(int argc, string argv[]){
//ERROR CONTROL
if(argc != 2 )
{
printf("Please include one and only one positive int\nafter calling ceasar!\n");
return 1;
}
//CONVERT STRING TO INT
int key = atoi(argv[1]);
//CONTROL VALID KEY
if(isdigit(key) || key > 0)
{
}else{
printf("Please provide a positive int\n");
return 1;
}
//GET PHRASE TO CIPHER
string plaintext= GetString();
//ITERATE OVER PLAINTEXT
for(int i = 0, n = strlen(plaintext); i < n; i++)
{
//CHECK IF ITS A LETTER
if(isalpha(plaintext[i]))
{
//CHECK IF IT IS UPPER/LOWER CASE
if(isupper(plaintext[i]))
{
printf("%c", (plaintext[i]-'A'+key)%26+'A');
}else{
printf("%c", (plaintext[i]-'a'+key)%26+'a');
}
}else{
printf("%c", plaintext[i]);
}
}
printf("\n");
}
|
fed-v/HarvardX_CS50x3
|
pset2/vigenere.c
|
<reponame>fed-v/HarvardX_CS50x3
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main(int argc, string argv[]){
//ERROR CONTROL
if(argc != 2 )
{
printf("Please include one and only one string key!\n");
return 1;
}
//GET KEY
string key = argv[1];
//ITERATE OVER PLAINTEXT
for(int i = 0, n = strlen(key); i < n; i++)
{
//CHECK IF ITS A LETTER
if(!isalpha(key[i]))
{
printf("Key must ONLY be alphabetical \n");
return 1;
}
}
//GET PHRASE TO CIPHER
string plaintext= GetString();
int shift = 0;
char letter;
//ITERATE OVER PLAINTEXT
for(int i = 0, n = strlen(plaintext); i < n; i++)
{
//CHECK IF ITS A LETTER
if(isalpha(plaintext[i]))
{
//CHECK IF KEY PHRASE IS UPPER/LOWER CASE TO CONVERT SALT LETTER
if(isupper(key[shift]))
{
letter = (int)(key[shift])-(int)'A';
}else{
letter = (int)(key[shift])-(int)'a';
}
//CHECK IF PLAINTEXT IS UPPER/LOWER CASE TO CONVERT CIPHER LETTER
if(isupper(plaintext[i]))
{
printf("%c", (plaintext[i]-'A'+letter)%26+'A');
}else{
printf("%c", (plaintext[i]-'a'+letter)%26+'a');
}
//CHANGE SHIFT NUMBER ACCORDING TO KEY LENGTH
if(shift<(strlen(key)-1))
{
shift++;
}else{
shift = 0;
}
}else{
printf("%c", plaintext[i]);
}
}
printf("\n");
}
|
fed-v/HarvardX_CS50x3
|
pset1/greedy.c
|
<gh_stars>0
#include <cs50.h>
#include <stdio.h>
#include <math.h>
float change;
int coins=0;
int main(void){
//INITIALIZE FUNCTION & PROMPT CHANGE
void countCoins(int cents);
printf("How much is your change?\n ");
change = GetFloat();
//CONTROL CHANGE IS VALID
do{
if(change<=0)
{
printf("Retry:");
change = GetFloat();
}
}while(change<=0);
// CONVERT CHANGE TO CENTS
change = change * 100;
change = round(change);
change = (int) change;
//HOW MANY QUARTERS
countCoins(25);
//HOW MANY DIMES
countCoins(10);
//HOW MANY NICKELS
countCoins(5);
//HOW MANY PENNIES
countCoins(1);
//PRINT TOTAL COINS
printf("%i\n", coins);
}
void countCoins(int cents)
{
while(change>=cents)
{
change = change-cents;
coins = coins + 1;
}
}
|
fed-v/HarvardX_CS50x3
|
pset2/initials.c
|
#include <cs50.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
int main()
{
//printf("What is you name?");
string name = GetString();
printf("%c", toupper(name[0]));
for(int i=0; i<strlen(name); i++)
{
if(name[i] == ' ')
{
if(name[i+1] != ' ')
{
printf("%c", toupper(name[i+1]));
}
}
}
printf("\n");
return 0;
}
|
Goyaya/GYComponents
|
GYComponents/Foundation/NSTimer+GYKit.h
|
<reponame>Goyaya/GYComponents
//
// NSTimer+GYComponent.h
//
//
// Created by 高洋 on 2018/5/12.
// Copyright © 2018年 gaoyang. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
typedef void(^GYTimerBlock) (void);
/// timer--strong-->middleRole--weak-->target
/// ensure your target be weakreference
@interface NSTimer (GYComponent)
+ (NSTimer *)gy_scheduledTimerWithTimerInterval:(NSTimeInterval)interval
block:(GYTimerBlock)block
repeats:(BOOL)yesOrNo;
+ (NSTimer *)gy_scheduledTimerWithTimerInterval:(NSTimeInterval)interval
block:(GYTimerBlock)block
userInfo:(id _Nullable)userInfo
repeats:(BOOL)yesOrNo;
+ (NSTimer *)gy_timerWithTimeInterval:(NSTimeInterval)interval
block:(GYTimerBlock)block
repeats:(BOOL)yesOrNo;
+ (NSTimer *)gy_timerWithTimeInterval:(NSTimeInterval)interval
block:(GYTimerBlock)block
userInfo:(nullable id)userInfo
repeats:(BOOL)yesOrNo;
@end
NS_ASSUME_NONNULL_END
|
Goyaya/GYComponents
|
Example/Pods/Target Support Files/GYComponents/GYComponents-umbrella.h
|
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#else
#ifndef FOUNDATION_EXPORT
#if defined(__cplusplus)
#define FOUNDATION_EXPORT extern "C"
#else
#define FOUNDATION_EXPORT extern
#endif
#endif
#endif
#import "GYComponentsHeader.h"
#import "GYRunLoopObserver.h"
#import "NSTimer+GYKit.h"
#import "GYAVPlayController.h"
#import "GYCollectionViewDivisionLayout.h"
#import "GYPageViewController.h"
FOUNDATION_EXPORT double GYComponentsVersionNumber;
FOUNDATION_EXPORT const unsigned char GYComponentsVersionString[];
|
Goyaya/GYComponents
|
Example/GYComponents/GYLifeCycleViewController.h
|
<reponame>Goyaya/GYComponents<gh_stars>0
//
// GYLifeCycleViewController.h
// GYComponents_Example
//
// Created by gaoyang on 2019/10/28.
// Copyright © 2019 goyaya. All rights reserved.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface GYLifeCycleViewController : UIViewController
@end
NS_ASSUME_NONNULL_END
|
Goyaya/GYComponents
|
GYComponents/Foundation/GYRunLoopObserver.h
|
//
// GYRunLoopObserver.h
//
//
// Created by 高洋 on 2019/5/31.
// Copyright © 2019 Zhibai. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
@class GYRunLoopObserver;
typedef void(^GYRunLoopObserverCallback)(GYRunLoopObserver *observer, CFRunLoopActivity activity);
@interface GYRunLoopObserver : NSObject
/// mode
@property (nonatomic, readonly, assign) CFRunLoopMode mode;
/// activity
@property (nonatomic, readonly, assign) CFRunLoopActivity activity;
/// repeats
@property (nonatomic, readonly, assign) BOOL repeats;
/// order
@property (nonatomic, readonly, assign) CFIndex order;
/// queue
@property (nonatomic, readonly, strong, nullable) NSOperationQueue *queue;
/// callback
@property (nonatomic, readonly, copy) GYRunLoopObserverCallback callback;
/**
create and return an observer of the runloop which thread the method called.
@param mode the mode of runloop to be observed
@param activity the activity of runloop to be observed
@param repeats once or repeats
@param order the priority of observer
@param queue the queue of callback invoke. nil means callback invoked in the queue it init
@param callback callback
@return observer instance
*/
- (instancetype)initWithMode:(CFRunLoopMode)mode
activity:(CFRunLoopActivity)activity
repeats:(BOOL)repeats
order:(CFIndex)order
queue:(NSOperationQueue * _Nullable)queue
usingBlock:(GYRunLoopObserverCallback)callback NS_DESIGNATED_INITIALIZER;
+ (instancetype)new NS_UNAVAILABLE;
- (instancetype)init NS_UNAVAILABLE;
@end
NS_ASSUME_NONNULL_END
|
Goyaya/GYComponents
|
Example/GYComponents/GYCollectionViewDivisionLayoutViewController.h
|
//
// GYCollectionViewDivisionLayoutViewController.h
// GYComponents_Example
//
// Created by 高洋 on 2019/9/11.
// Copyright © 2019 goyaya. All rights reserved.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface GYCollectionViewDivisionLayoutViewController : UIViewController
@end
NS_ASSUME_NONNULL_END
|
Goyaya/GYComponents
|
GYComponents/UI/GYCollectionViewDivisionLayout.h
|
//
// GYCollectionViewDivisionLayout.h
// iOS Knowledge Architecture
//
// Created by 高洋 on 2019/8/13.
// Copyright © 2019 Gaoyang. All rights reserved.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@class GYCollectionViewDivisionLayout;
@protocol GYCollectionViewDivisionLayoutDataSource <UICollectionViewDataSource>
@optional
/// 每个section的等分行数(水平滚动)或列数(垂直滚动)。默认 2
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfColumnsInSection:(NSInteger)section;
@end
@protocol GYCollectionViewDivisionLayoutDelegate <UICollectionViewDelegate>
@optional
/**
根据给定宽度(垂直滚动)参考值获取高度;或根据给定高度(水平滚动)参考值获取宽度;
未实现时使用`refer`的值
@param collectionView collectionView
@param collectionViewLayout layout
@param refer 参考值
@param indexPath indexPath
@return 高度或宽度
*/
- (CGFloat)collectionView:(UICollectionView *)collectionView
layout:(GYCollectionViewDivisionLayout *)collectionViewLayout
valueReferTo:(CGFloat)refer atIndexPath:(NSIndexPath *)indexPath;
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView
layout:(GYCollectionViewDivisionLayout*)collectionViewLayout
insetForSectionAtIndex:(NSInteger)section;
- (CGSize)collectionView:(UICollectionView *)collectionView
layout:(GYCollectionViewDivisionLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section;
- (CGSize)collectionView:(UICollectionView *)collectionView
layout:(GYCollectionViewDivisionLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section;
/// 和滚动方向垂直cell之间的间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(GYCollectionViewDivisionLayout *)collectionViewLayout fixedLineSpacingForSectionAtIndex:(NSInteger)section;
/// 和滚动方向平行cell之间的间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(GYCollectionViewDivisionLayout *)collectionViewLayout fixedInteritemSpacingForSectionAtIndex:(NSInteger)section;
@end
/**
一个等分宽度或高度的layout,类似瀑布流。
* 支持垂直滚动和水平滚动。
* 支持header和footer视图
* 不继承FlowLayout是因为避免FlowLayout在prepare阶段的不必要计算。
*/
@interface GYCollectionViewDivisionLayout : UICollectionViewLayout
/// 滚动方向。默认 UICollectionViewScrollDirectionVertical
@property (nonatomic, readwrite, assign) UICollectionViewScrollDirection scrollDirection;
/// 统一的headerSize、footerSize。默认都是0
@property (nonatomic, readwrite, assign) CGSize headerReferenceSize;
@property (nonatomic, readwrite, assign) CGSize footerReferenceSize;
/// 统一的sectionInset。默认0
@property (nonatomic, readwrite, assign) UIEdgeInsets sectionInset;
/// 列数或行数。默认2
@property (nonatomic, readwrite, assign) NSInteger columns;
/// 两行之间的固定间距。默认10
@property (nonatomic, readwrite, assign) CGFloat fixedLineSpacing;
/// 两列之间的固定间距。默认10
@property (nonatomic, readwrite, assign) CGFloat fixedInteritemSpacing;
- (instancetype)initWithColumns:(NSInteger)columns
fixedLineSpacing:(CGFloat)fixedLineSpacing
fixedInteritemSpacing:(CGFloat)fixedInteritemSpacing;
@end
NS_ASSUME_NONNULL_END
|
Goyaya/GYComponents
|
Example/GYComponents/GYFeaturesTableViewController.h
|
//
// GYFeaturesTableViewController.h
// GYComponents_Example
//
// Created by 高洋 on 2019/9/10.
// Copyright © 2019 goyaya. All rights reserved.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface GYFeaturesTableViewController : UITableViewController
@end
NS_ASSUME_NONNULL_END
|
Goyaya/GYComponents
|
GYComponents/Dependence/GYComponentsHeader.h
|
<filename>GYComponents/Dependence/GYComponentsHeader.h
//
// GYComponentsHeader.h
// GYComponents
//
// Created by 高洋 on 2019/7/28.
//
#ifndef GYComponentsHeader_h
#define GYComponentsHeader_h
/** frome YYKit!
Add this macro before each category implementation, so we don't have to use
-all_load or -force_load to load object files from static libraries that only
contain categories and no classes.
More info: http://developer.apple.com/library/mac/#qa/qa2006/qa1490.html .
*******************************************************************************
Example:
GYSYNTH_DUMMY_CLASS(NSString_GYAdd)
*/
#ifndef GYSYNTH_DUMMY_CLASS
#define GYSYNTH_DUMMY_CLASS(_name_) \
@interface GYSYNTH_DUMMY_CLASS_ ## _name_ : NSObject @end \
@implementation GYSYNTH_DUMMY_CLASS_ ## _name_ @end
#endif
#endif /* GYComponentsHeader_h */
|
Goyaya/GYComponents
|
Example/GYComponents/GYAppDelegate.h
|
<gh_stars>0
//
// GYAppDelegate.h
// GYComponents
//
// Created by goyaya on 07/28/2019.
// Copyright (c) 2019 goyaya. All rights reserved.
//
@import UIKit;
@interface GYAppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@end
|
Goyaya/GYComponents
|
GYComponents/Media/GYAVPlayController.h
|
<reponame>Goyaya/GYComponents
//
// GYAVPlayController.h
// GYComponents
//
// Created by gaoyang on 2019/10/18.
//
#import <Foundation/Foundation.h>
#import <CoreMedia/CMTime.h>
NS_ASSUME_NONNULL_BEGIN
@class GYAVPlayController, AVPlayerItem, AVAsset;
@protocol GYAVPlayControllerDelegate <NSObject>
@optional
/// before play
- (void)AVPlayController:(GYAVPlayController *)playController willPlayItem:(AVPlayerItem *)item;
/**
ready play
@return YES, player will play the item; NO, adverse;
*/
- (BOOL)AVPlayController:(GYAVPlayController *)playController readyPlayItem:(AVPlayerItem *)item;
/// progress updated
- (void)AVPlayController:(GYAVPlayController *)playController item:(AVPlayerItem *)item progressUpdatedTo:(double)progress inTotal:(double)total;
/// play finished
- (void)AVPlayController:(GYAVPlayController *)playController finishedPlayingItem:(AVPlayerItem *)item;
/// failed
- (void)AVPlayController:(GYAVPlayController *)playController failedPlayingItem:(AVPlayerItem *)item withError:(NSError *)error;
@end
@interface GYAVPlayController : NSObject
/// context
@property (nonatomic, readwrite, strong, nullable) id context;
/// delegate
@property (nonatomic, readwrite, weak) id<GYAVPlayControllerDelegate> delegate;
/// url
@property (nonatomic, readwrite, strong, nullable) NSURL *url;
/// asset
@property (nonatomic, readwrite, strong, nullable) AVAsset *asset;
/// item
@property (nonatomic, readwrite, strong, nullable) AVPlayerItem *item;
/// playing or not
@property (nonatomic, readonly, assign, getter=isPlaying) BOOL playing;
/// progress report interval. default is once per second
@property (nonatomic, readwrite, assign) CMTime progressReportInterval;
/// make the view is ready.
/// when the resource is ready, it play by default.
/// you can override by implement delegate method `-AVPlayConPtroller:readyPlayItem:`
- (void)prepare;
/// you should call `prepare` precede this method
- (void)play;
/// pause, can play later
- (void)pause;
/// pause & release resources
/// if you want play again, do prepare -> play
- (void)stop;
/// moves the playback cursor if conditions fit
- (void)seekToTime:(CMTime)time;
- (void)seekToTime:(CMTime)time complete:(void (^ _Nullable)(BOOL finished))complete;
@end
NS_ASSUME_NONNULL_END
|
Goyaya/GYComponents
|
GYComponents/UI/GYPageViewController.h
|
<reponame>Goyaya/GYComponents<gh_stars>0
//
// GYPageViewController.h
// iOS Knowledge Architecture
//
// Created by 高洋 on 2019/7/29.
// Copyright © 2019 Gaoyang. All rights reserved.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@class GYPageViewController;
/**
scroll direction
*/
typedef NS_ENUM(int, GYPageViewControllerScrollDirection) {
GYPageViewControllerScrollDirectionHorizontal,
GYPageViewControllerScrollDirectionVertical
};
@protocol GYPageViewControllerDataSource <NSObject>
@required;
/// total count
- (NSInteger)numberOfItemsInPageViewController:(GYPageViewController *)pageViewController;
/// which should display first
- (NSInteger)indexOfFirstDisplayInPageViewController:(GYPageViewController *)pageViewController;
/// controller at specify index
- (UIViewController *)pageViewController:(GYPageViewController *)controller controllerAtIndex:(NSInteger)index;
@optional
/// scroll direction. default is `GYPageViewControllerScrollDirectionHorizontal`
- (GYPageViewControllerScrollDirection)scrollDirectionInPageViewController:(GYPageViewController *)pageViewController;
@end
@protocol GYPageViewControllerDelegate <NSObject>
@optional;
/**
切换控制器进度。在`willChangeIndexTo:`方法调用之前,该进度不可信,只是报告进度。
@param controller controller
@param index 目标索引。一定检查索引,避免小于0或大于总数的情况
@param progress 总体进度
*/
- (void)pageViewController:(GYPageViewController *)controller mayChangeIndexTo:(NSInteger)index progress:(float)progress;
/**
即将切换
@param controller controller
@param index 目标索引
*/
- (void)pageViewController:(GYPageViewController *)controller willChangeIndexTo:(NSInteger)index;
/**
切换完成
@param controller controller
@param index 目标索引
*/
- (void)pageViewController:(GYPageViewController *)controller didChangeIndexTo:(NSInteger)index;
@end
@protocol GYPageViewControllerAppearance <NSObject>
@required
- (void)setShowsVerticalScrollIndicator:(BOOL)ifNeeds;
- (void)setShowsHorizontalScrollIndicator:(BOOL)ifNeeds;
- (void)setScrollEnabled:(BOOL)enable;
@end
@interface GYPageViewController : UIViewController
@property (nonatomic, readonly, weak, nullable) id<GYPageViewControllerDataSource> dataSource;
@property (nonatomic, readwrite, weak) id<GYPageViewControllerDelegate> delegate;
/// appearance
@property (nonatomic, readonly, strong) id <GYPageViewControllerAppearance> appearance;
/// controllers
@property (nonatomic, readonly, copy, nullable) NSArray<UIViewController *> *controllers;
/// current display index
@property (nonatomic, readonly, assign) NSInteger index;
/**
create and return instance with metadata
@param controllers sub controllers
@param index which should display first
@return instance
*/
- (instancetype)initWithControllers:(NSArray<UIViewController *> *)controllers index:(NSInteger)index;
/**
create and return instance with dataSource
@param dataSource dataSource
@return instance
*/
- (instancetype)initWithDataSource:(id<GYPageViewControllerDataSource>)dataSource;
/**
specify the display index. not trigger delegate event
@param index index
@param animation animation or not
@param complete complete
*/
- (void)setIndex:(NSInteger)index animation:(BOOL)animation complete:(void (^_Nullable)(void))complete;
@end
NS_ASSUME_NONNULL_END
|
Yu2erer/Memory_Pool
|
YY_Allocator.h
|
//
// Created by Yuerer on 2019/11/7.
//
#ifndef YY_ALLOCATOR_H
#define YY_ALLOCATOR_H
namespace YY {
static const int ALIGN = 8;
static const int MAX_BYTES = 128;
static const int FREE_LIST_NUMS = MAX_BYTES / ALIGN; // 16
class Alloc {
public:
static void *allocate(size_t n) {
obj **my_free_list;
obj *result;
if (n > (size_t)MAX_BYTES) {
return ::operator new(n);
}
my_free_list = free_list + FREE_LIST_INDEX(n);
result = *my_free_list;
if (result == nullptr) {
void *r = refill(ROUND_UP(n));
return r;
}
*my_free_list = result->next;
return result;
}
static void deallocate(void *p, size_t n) {
obj *q = (obj *)p;
obj **my_free_list;
if (n > (size_t)MAX_BYTES) {
return ::operator delete(p);
}
my_free_list = free_list + FREE_LIST_INDEX(n);
q->next = *my_free_list;
*my_free_list = q;
}
private:
// 单向链表
union obj {
union obj *next;
};
private:
// 内存池
static char *start_free;
static char *end_free;
static size_t heap_size;
private:
static obj *free_list[FREE_LIST_NUMS];
static void *refill(size_t n);
static char *chunk_alloc(size_t n, int &blocks);
private:
// 从 1 起步
static size_t FREE_LIST_INDEX(size_t bytes) {
return ((bytes + ALIGN - 1) / (ALIGN - 1));
}
static size_t ROUND_UP(size_t bytes) {
return ((bytes + ALIGN - 1) & ~(ALIGN - 1));
}
};
Alloc::obj *Alloc::free_list[FREE_LIST_NUMS] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
char *Alloc::start_free = nullptr;
char *Alloc::end_free = nullptr;
size_t Alloc::heap_size = 0;
void *Alloc::refill(size_t n) {
int blocks = 20;
char *chunk = chunk_alloc(n, blocks);
obj **my_free_list;
obj *result;
obj *next_obj, *current_obj;
if (blocks == 1) {
return chunk;
}
my_free_list = free_list + FREE_LIST_INDEX(n);
result = (obj*)chunk;
*my_free_list = next_obj = (obj*)(chunk + n);
for (int i = 1; ; ++ i) {
current_obj = next_obj;
next_obj = (obj*)((char*)next_obj + n);
if (blocks - 1 == i) {
current_obj->next = nullptr;
break;
} else {
current_obj->next = next_obj;
}
}
return result;
}
char *Alloc::chunk_alloc(size_t n, int &blocks) {
size_t bytes_left = end_free - start_free;
size_t total_bytes = n * blocks;
char *result;
if (bytes_left >= total_bytes) {
result = start_free;
start_free += total_bytes;
return result;
} else if (bytes_left >= n) {
blocks = bytes_left / n;
total_bytes = n * blocks;
result = start_free;
start_free += total_bytes;
return result;
} else {
size_t bytes_to_get = 2 * total_bytes + ROUND_UP(heap_size >> 4);
if (bytes_left > 0) {
obj **my_free_list = free_list + FREE_LIST_INDEX(bytes_left);
((obj*)start_free)->next = *my_free_list;
*my_free_list = (obj*)start_free;
}
start_free = (char*)malloc(bytes_to_get);
if (start_free == nullptr) {
obj **my_free_list;
obj *p;
for (int i = n + ALIGN; i <= MAX_BYTES; i += ALIGN) {
my_free_list = free_list + FREE_LIST_INDEX(i);
p = *my_free_list;
if (p != nullptr) {
*my_free_list = p->next;
start_free = (char *) p;
end_free = (char *) p + i;
return chunk_alloc(n, blocks);
}
}
end_free = nullptr;
start_free = (char*)::operator new(bytes_to_get);
}
heap_size += bytes_to_get;
end_free = start_free + bytes_to_get;
return chunk_alloc(n, blocks);
}
}
template <typename T>
class Allocator {
public:
typedef T value_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef size_t size_type;
typedef ptrdiff_t difference_type;
static T* allocate(size_t n) {
return (n == 0) ? 0 : (T*)Alloc::allocate(n * sizeof(T));
}
static T* allocate() {
return (T*)Alloc::allocate(sizeof(T));
}
static void deallocate(T *p, size_t n) {
if (n != 0) {
Alloc::deallocate(p, n * sizeof(T));
}
}
static void deallocate(T *p) {
Alloc::deallocate(p, sizeof(T));
}
};
}
#endif //YY_ALLOCATOR_H
|
sabersensen/Aspects
|
Aspects.h
|
<filename>Aspects.h
//
// Aspects.h
// Aspects - A delightful, simple library for aspect oriented programming.
//
// Copyright (c) 2014 <NAME>. Licensed under the MIT license.
// Aspects 主要是给view controller 使用 而不是用于高频率hook 比如每秒1000次
#import <Foundation/Foundation.h>
/**
hook执行时期
- AspectPositionAfter: 原方法执行完之后调用 (default)
- AspectPositionInstead: 替换原方法
- AspectPositionBefore: 原方法执行完之前调用
- AspectOptionAutomaticRemoval: 在hook执行完自动移除
*/
typedef NS_OPTIONS(NSUInteger, AspectOptions) {
AspectPositionAfter = 0,
AspectPositionInstead = 1,
AspectPositionBefore = 2,
AspectOptionAutomaticRemoval = 1 << 3
};
/**
隐式协议:允许我们调用remove去撤销一个hook
*/
@protocol AspectToken <NSObject>
/**
撤销一个aspect
@return 撤销成功返回YES,否则返回NO
*/
- (BOOL)remove;
@end
/**
AspectInfo protocol是我们block语法里面的第一个参数。
*/
@protocol AspectInfo <NSObject>
/**
当前被hooked的实例
@return 实例对象
*/
- (id)instance;
/**
返回被hooked方法的原始的invocation
@return invocation
*/
- (NSInvocation *)originalInvocation;
/**
懒加载
@return 返回所有参数
*/
- (NSArray *)arguments;
@end
/**
Aspects利用的OC的消息转发机制来进行hook。这样会有一些性能开销。不要把Aspects加到经常被使用的方法里面。Aspects是用来设计给view/controller 代码使用的,而不是用来hook每秒调用1000次的方法的。
添加Aspects之后,会返回一个隐式的token,这个token可以用来注销hook方法的。所有的调用都是线程安全的。
*/
@interface NSObject (Aspects)
/**
这些参数都会被填充到匹配的block的签名里
你也可以使用一个空block,或者一个简单的id<AspectInfo>
不支持hook静态static方法的
@param selector 是要给它增加切面的原方法 返回一个遵循<AspectInfo>的id对象,这个对象继承了方法的所有参数,
@param options 是代表这个切片增加在原方法的before / instead / after
@param block 这个block复制了正在被hook的方法的签名signature类型
@param error 错误信息
@return 返回一个可以用来撤销aspect的token
*/
+ (id<AspectToken>)aspect_hookSelector:(SEL)selector
withOptions:(AspectOptions)options
usingBlock:(id)block
error:(NSError **)error;
/**
hook实例方法 为一个具体实例的seletor的执行 之前/或者被替换/之后 添加一个block代码
*/
- (id<AspectToken>)aspect_hookSelector:(SEL)selector
withOptions:(AspectOptions)options
usingBlock:(id)block
error:(NSError **)error;
@end
/**
错误码的类型
- AspectErrorSelectorBlacklisted: 这些选择器如release,retain,autorelease被加入黑名单
- AspectErrorDoesNotRespondToSelector: 选择器未找到
- AspectErrorSelectorDeallocPosition: 当正在执行的hook被释放时,只有原方法执行之前被允许
- AspectErrorSelectorAlreadyHookedInClassHierarchy: 静态hook子类相同的方法是不被允许的
- AspectErrorFailedToAllocateClassPair: runtime创建一个类失败
- AspectErrorMissingBlockSignature: block没有被签名编译不能被唤起
- AspectErrorIncompatibleBlockSignature: 签名block没有匹配到方法或者太大
- AspectErrorRemoveObjectAlreadyDeallocated: 已经准备释放(for removing)
*/
typedef NS_ENUM(NSUInteger, AspectErrorCode) {
AspectErrorSelectorBlacklisted = 1,
AspectErrorDoesNotRespondToSelector = 2,
AspectErrorSelectorDeallocPosition = 3,
AspectErrorSelectorAlreadyHookedInClassHierarchy = 4,
AspectErrorFailedToAllocateClassPair = 5,
AspectErrorMissingBlockSignature = 6,
AspectErrorIncompatibleBlockSignature = 7,
AspectErrorRemoveObjectAlreadyDeallocated = 100
};
/// 声明Apsect的ErrorDomain
extern NSString *const AspectErrorDomain;
|
amrshennawi/fbthrift
|
thrift/lib/cpp2/protocol/BinaryProtocol-inl.h
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#ifndef THRIFT2_PROTOCOL_TBINARYPROTOCOL_TCC_
#define THRIFT2_PROTOCOL_TBINARYPROTOCOL_TCC_ 1
#include <thrift/lib/cpp2/protocol/BinaryProtocol.h>
#include <limits>
#include <string>
namespace apache {
namespace thrift {
uint32_t BinaryProtocolWriter::writeMessageBegin(
folly::StringPiece name, MessageType messageType, int32_t seqid) {
int32_t version = (VERSION_1) | ((int32_t)messageType);
uint32_t wsize = 0;
wsize += writeI32(version);
wsize += writeString(name);
wsize += writeI32(seqid);
return wsize;
}
uint32_t BinaryProtocolWriter::writeMessageEnd() {
return 0;
}
uint32_t BinaryProtocolWriter::writeStructBegin(const char* /*name*/) {
return 0;
}
uint32_t BinaryProtocolWriter::writeStructEnd() {
return 0;
}
uint32_t BinaryProtocolWriter::writeFieldBegin(
const char* /*name*/, TType fieldType, int16_t fieldId) {
uint32_t wsize = 0;
wsize += writeByte((int8_t)fieldType);
wsize += writeI16(fieldId);
return wsize;
}
uint32_t BinaryProtocolWriter::writeFieldEnd() {
return 0;
}
uint32_t BinaryProtocolWriter::writeFieldStop() {
return writeByte((int8_t)TType::T_STOP);
}
uint32_t BinaryProtocolWriter::writeMapBegin(
const TType keyType, TType valType, uint32_t size) {
uint32_t wsize = 0;
wsize += writeByte((int8_t)keyType);
wsize += writeByte((int8_t)valType);
wsize += writeI32((int32_t)size);
return wsize;
}
uint32_t BinaryProtocolWriter::writeMapEnd() {
return 0;
}
uint32_t BinaryProtocolWriter::writeListBegin(TType elemType, uint32_t size) {
uint32_t wsize = 0;
wsize += writeByte((int8_t)elemType);
wsize += writeI32((int32_t)size);
return wsize;
}
uint32_t BinaryProtocolWriter::writeListEnd() {
return 0;
}
uint32_t BinaryProtocolWriter::writeSetBegin(TType elemType, uint32_t size) {
uint32_t wsize = 0;
wsize += writeByte((int8_t)elemType);
wsize += writeI32((int32_t)size);
return wsize;
}
uint32_t BinaryProtocolWriter::writeSetEnd() {
return 0;
}
uint32_t BinaryProtocolWriter::writeBool(bool value) {
out_.write(detail::validate_bool(value));
return sizeof(value);
}
uint32_t BinaryProtocolWriter::writeByte(int8_t byte) {
out_.write(byte);
return sizeof(byte);
}
uint32_t BinaryProtocolWriter::writeI16(int16_t i16) {
out_.writeBE(i16);
return sizeof(i16);
}
uint32_t BinaryProtocolWriter::writeI32(int32_t i32) {
out_.writeBE(i32);
return sizeof(i32);
}
uint32_t BinaryProtocolWriter::writeI64(int64_t i64) {
out_.writeBE(i64);
return sizeof(i64);
}
uint32_t BinaryProtocolWriter::writeDouble(double dub) {
static_assert(sizeof(double) == sizeof(uint64_t), "");
static_assert(std::numeric_limits<double>::is_iec559, "");
uint64_t bits = folly::bit_cast<uint64_t>(dub);
out_.writeBE(bits);
return sizeof(bits);
}
uint32_t BinaryProtocolWriter::writeFloat(float flt) {
static_assert(sizeof(float) == sizeof(uint32_t), "");
static_assert(std::numeric_limits<float>::is_iec559, "");
uint32_t bits = folly::bit_cast<uint32_t>(flt);
out_.writeBE(bits);
return sizeof(bits);
}
uint32_t BinaryProtocolWriter::writeString(folly::StringPiece str) {
return writeBinary(str);
}
uint32_t BinaryProtocolWriter::writeBinary(folly::StringPiece str) {
return writeBinary(folly::ByteRange(str));
}
uint32_t BinaryProtocolWriter::writeBinary(folly::ByteRange v) {
uint32_t size = folly::to_narrow(v.size());
uint32_t result = writeI32((int32_t)size);
out_.push(v.data(), size);
return result + size;
}
uint32_t BinaryProtocolWriter::writeBinary(
const std::unique_ptr<folly::IOBuf>& str) {
if (!str) {
return writeI32(0);
}
return writeBinary(*str);
}
uint32_t BinaryProtocolWriter::writeBinary(const folly::IOBuf& str) {
return writeBinaryImpl<true>(str);
}
uint32_t BinaryProtocolWriter::writeRaw(const folly::IOBuf& str) {
return writeBinaryImpl<false>(str);
}
template <bool kWriteSize>
uint32_t BinaryProtocolWriter::writeBinaryImpl(const folly::IOBuf& str) {
size_t size = str.computeChainDataLength();
// leave room for size
uint32_t limit = std::numeric_limits<uint32_t>::max() - serializedSizeI32();
if (size > limit) {
TProtocolException::throwExceededSizeLimit(size, limit);
}
uint32_t result = kWriteSize ? writeI32((int32_t)size) : 0;
if (sharing_ != SHARE_EXTERNAL_BUFFER && !str.isManaged()) {
auto clone = str.clone();
clone->makeManaged();
out_.insert(std::move(clone));
} else {
out_.insert(str);
}
return result + static_cast<uint32_t>(size);
}
void BinaryProtocolWriter::rewriteDouble(double dub, int64_t offset) {
auto cursor = RWCursor(out_);
cursor.advanceToEnd();
cursor -= offset;
cursor.writeBE(folly::bit_cast<uint64_t>(dub));
}
/**
* Functions that return the serialized size
*/
uint32_t BinaryProtocolWriter::serializedMessageSize(
folly::StringPiece name) const {
// I32{version} + String{name} + I32{seqid}
return 2 * serializedSizeI32() + serializedSizeString(name);
}
uint32_t BinaryProtocolWriter::serializedFieldSize(
const char* /*name*/, TType /*fieldType*/, int16_t /*fieldId*/) const {
// byte + I16
return serializedSizeByte() + serializedSizeI16();
}
uint32_t BinaryProtocolWriter::serializedStructSize(const char* /*name*/
) const {
return 0;
}
uint32_t BinaryProtocolWriter::serializedSizeMapBegin(
TType /*keyType*/, TType /*valType*/, uint32_t /*size*/) const {
return serializedSizeByte() + serializedSizeByte() + serializedSizeI32();
}
uint32_t BinaryProtocolWriter::serializedSizeMapEnd() const {
return 0;
}
uint32_t BinaryProtocolWriter::serializedSizeListBegin(
TType /*elemType*/, uint32_t /*size*/
) const {
return serializedSizeByte() + serializedSizeI32();
}
uint32_t BinaryProtocolWriter::serializedSizeListEnd() const {
return 0;
}
uint32_t BinaryProtocolWriter::serializedSizeSetBegin(
TType /*elemType*/, uint32_t /*size*/) const {
return serializedSizeByte() + serializedSizeI32();
}
uint32_t BinaryProtocolWriter::serializedSizeSetEnd() const {
return 0;
}
uint32_t BinaryProtocolWriter::serializedSizeStop() const {
return 1;
}
uint32_t BinaryProtocolWriter::serializedSizeBool(bool /*val*/) const {
return 1;
}
uint32_t BinaryProtocolWriter::serializedSizeByte(int8_t /*val*/) const {
return 1;
}
uint32_t BinaryProtocolWriter::serializedSizeI16(int16_t /*val*/) const {
return 2;
}
uint32_t BinaryProtocolWriter::serializedSizeI32(int32_t /*val*/) const {
return 4;
}
uint32_t BinaryProtocolWriter::serializedSizeI64(int64_t /*val*/) const {
return 8;
}
uint32_t BinaryProtocolWriter::serializedSizeDouble(double /*val*/) const {
return 8;
}
uint32_t BinaryProtocolWriter::serializedSizeFloat(float /*val*/) const {
return 4;
}
uint32_t BinaryProtocolWriter::serializedSizeString(
folly::StringPiece str) const {
return serializedSizeBinary(str);
}
uint32_t BinaryProtocolWriter::serializedSizeBinary(
folly::StringPiece str) const {
return serializedSizeBinary(folly::ByteRange(str));
}
uint32_t BinaryProtocolWriter::serializedSizeBinary(
folly::ByteRange str) const {
// I32{length of string} + binary{string contents}
return serializedSizeI32() + static_cast<uint32_t>(str.size());
}
uint32_t BinaryProtocolWriter::serializedSizeBinary(
std::unique_ptr<folly::IOBuf> const& v) const {
return v ? serializedSizeBinary(*v) : 0;
}
uint32_t BinaryProtocolWriter::serializedSizeBinary(
folly::IOBuf const& v) const {
size_t size = v.computeChainDataLength();
uint32_t limit = std::numeric_limits<uint32_t>::max() - serializedSizeI32();
if (size > limit) {
TProtocolException::throwExceededSizeLimit(size, limit);
}
return serializedSizeI32() + static_cast<uint32_t>(size);
}
uint32_t BinaryProtocolWriter::serializedSizeZCBinary(
folly::StringPiece str) const {
return serializedSizeZCBinary(folly::ByteRange(str));
}
uint32_t BinaryProtocolWriter::serializedSizeZCBinary(
folly::ByteRange v) const {
return serializedSizeBinary(v);
}
uint32_t BinaryProtocolWriter::serializedSizeZCBinary(
std::unique_ptr<folly::IOBuf> const& v) const {
return v ? serializedSizeZCBinary(*v) : 0;
}
uint32_t BinaryProtocolWriter::serializedSizeZCBinary(
folly::IOBuf const& v) const {
size_t size = v.computeChainDataLength();
return (size > folly::IOBufQueue::kMaxPackCopy)
? serializedSizeI32() // too big to pack: size only
: static_cast<uint32_t>(size) + serializedSizeI32(); // size + packed data
}
/**
* Reading functions
*/
void BinaryProtocolReader::readMessageBegin(
std::string& name, MessageType& messageType, int32_t& seqid) {
int32_t sz;
readI32(sz);
if (sz < 0) {
// Check for correct version number
int32_t version = sz & VERSION_MASK;
if (version != VERSION_1) {
throwBadVersionIdentifier(sz);
}
messageType = (MessageType)(sz & 0x000000ff);
readString(name);
readI32(seqid);
} else {
if (this->strict_read_) {
throwMissingVersionIdentifier(sz);
} else {
// Handle pre-versioned input
int8_t type;
readStringBody(name, sz);
readByte(type);
messageType = (MessageType)type;
readI32(seqid);
}
}
}
void BinaryProtocolReader::readMessageEnd() {}
void BinaryProtocolReader::readStructBegin(std::string& name) {
name = "";
}
void BinaryProtocolReader::readStructEnd() {}
void BinaryProtocolReader::readFieldBegin(
std::string& /*name*/, TType& fieldType, int16_t& fieldId) {
int8_t type;
readByte(type);
fieldType = (TType)type;
if (fieldType == TType::T_STOP) {
fieldId = 0;
return;
}
readI16(fieldId);
}
void BinaryProtocolReader::readFieldEnd() {}
void BinaryProtocolReader::readMapBegin(
TType& keyType, TType& valType, uint32_t& size) {
int8_t k, v;
int32_t sizei;
readByte(k);
keyType = (TType)k;
readByte(v);
valType = (TType)v;
readI32(sizei);
checkContainerSize(sizei);
size = (uint32_t)sizei;
}
void BinaryProtocolReader::readMapEnd() {}
void BinaryProtocolReader::readListBegin(TType& elemType, uint32_t& size) {
int8_t e;
int32_t sizei;
readByte(e);
elemType = (TType)e;
readI32(sizei);
checkContainerSize(sizei);
size = (uint32_t)sizei;
}
void BinaryProtocolReader::readListEnd() {}
void BinaryProtocolReader::readSetBegin(TType& elemType, uint32_t& size) {
int8_t e;
int32_t sizei;
readByte(e);
elemType = (TType)e;
readI32(sizei);
checkContainerSize(sizei);
size = (uint32_t)sizei;
}
void BinaryProtocolReader::readSetEnd() {}
void BinaryProtocolReader::readBool(bool& value) {
auto byte = in_.read<uint8_t>();
if (byte >= 2) {
TProtocolException::throwBoolValueOutOfRange(byte);
}
value = static_cast<bool>(byte);
}
void BinaryProtocolReader::readBool(std::vector<bool>::reference value) {
bool ret = false;
readBool(ret);
value = ret;
}
void BinaryProtocolReader::readByte(int8_t& byte) {
byte = in_.read<int8_t>();
}
void BinaryProtocolReader::readI16(int16_t& i16) {
i16 = in_.readBE<int16_t>();
}
void BinaryProtocolReader::readI32(int32_t& i32) {
i32 = in_.readBE<int32_t>();
}
void BinaryProtocolReader::readI64(int64_t& i64) {
i64 = in_.readBE<int64_t>();
}
void BinaryProtocolReader::readDouble(double& dub) {
static_assert(sizeof(double) == sizeof(uint64_t), "");
static_assert(std::numeric_limits<double>::is_iec559, "");
uint64_t bits = in_.readBE<int64_t>();
dub = folly::bit_cast<double>(bits);
}
void BinaryProtocolReader::readFloat(float& flt) {
static_assert(sizeof(float) == sizeof(uint32_t), "");
static_assert(std::numeric_limits<double>::is_iec559, "");
uint32_t bits = in_.readBE<int32_t>();
flt = folly::bit_cast<float>(bits);
}
void BinaryProtocolReader::checkStringSize(int32_t size) {
// Catch error cases
if (size < 0) {
TProtocolException::throwNegativeSize();
}
if (string_limit_ > 0 && size > string_limit_) {
TProtocolException::throwExceededSizeLimit(size, string_limit_);
}
}
void BinaryProtocolReader::checkContainerSize(int32_t size) {
if (size < 0) {
TProtocolException::throwNegativeSize();
} else if (container_limit_ && size > container_limit_) {
TProtocolException::throwExceededSizeLimit(size, container_limit_);
}
}
template <typename StrType>
void BinaryProtocolReader::readString(StrType& str) {
int32_t size;
readI32(size);
readStringBody(str, size);
}
template <typename StrType>
void BinaryProtocolReader::readBinary(StrType& str) {
readString(str);
}
void BinaryProtocolReader::readBinary(std::unique_ptr<folly::IOBuf>& str) {
if (!str) {
str = std::make_unique<folly::IOBuf>();
}
readBinary(*str);
}
void BinaryProtocolReader::readBinary(folly::IOBuf& str) {
int32_t size;
readI32(size);
checkStringSize(size);
in_.clone(str, size);
if (sharing_ != SHARE_EXTERNAL_BUFFER) {
str.makeManaged();
}
}
template <typename StrType>
void BinaryProtocolReader::readStringBody(StrType& str, int32_t size) {
checkStringSize(size);
// Catch empty string case
if (size == 0) {
str.clear();
return;
}
if (static_cast<int32_t>(in_.length()) < size) {
if (!in_.canAdvance(size)) {
protocol::TProtocolException::throwTruncatedData();
}
str.reserve(size); // only reserve for multi iter case below
}
str.clear();
size_t size_left = size;
while (size_left > 0) {
auto data = in_.peekBytes();
auto data_avail = std::min(data.size(), size_left);
if (data.empty()) {
TProtocolException::throwTruncatedData();
}
str.append((const char*)data.data(), data_avail);
size_left -= data_avail;
in_.skipNoAdvance(data_avail);
}
}
uint32_t BinaryProtocolReader::readFromPositionAndAppend(
Cursor& snapshot, std::unique_ptr<IOBuf>& ser) {
int32_t size =
folly::to_narrow(folly::to_signed(folly::io::Cursor(in_) - snapshot));
if (ser) {
std::unique_ptr<IOBuf> newBuf;
snapshot.clone(newBuf, size);
if (sharing_ != SHARE_EXTERNAL_BUFFER) {
newBuf->makeManaged();
}
// IOBuf are circular, so prependChain called on head is the same as
// appending the whole chain at the tail.
ser->prependChain(std::move(newBuf));
} else {
// cut a chunk of things directly
snapshot.clone(ser, size);
if (sharing_ != SHARE_EXTERNAL_BUFFER) {
ser->makeManaged();
}
}
return (uint32_t)size;
}
bool BinaryProtocolReader::advanceToNextField(
int16_t nextFieldId, TType nextFieldType, StructReadState& state) {
if (nextFieldType == TType::T_STOP) {
if (in_.length() && *in_.data() == TType::T_STOP) {
in_.skipNoAdvance(1);
return true;
}
} else {
if (in_.length() >= 3) {
uint8_t type = *in_.data();
if (nextFieldType == type) {
int16_t fieldId =
folly::Endian::big(folly::loadUnaligned<int16_t>(in_.data() + 1));
in_.skipNoAdvance(3);
if (nextFieldId == fieldId) {
return true;
}
state.fieldType = (TType)type;
state.fieldId = fieldId;
return false;
}
state.fieldType = (TType)type;
if (type != TType::T_STOP) {
state.fieldId =
folly::Endian::big(folly::loadUnaligned<int16_t>(in_.data() + 1));
in_.skipNoAdvance(3);
} else {
in_.skipNoAdvance(1);
}
return false;
}
}
state.readFieldBeginNoInline(this);
return false;
}
void BinaryProtocolReader::readFieldBeginWithState(StructReadState& state) {
int8_t type;
readByte(type);
state.fieldType = (TType)type;
if (state.fieldType == TType::T_STOP) {
return;
}
readI16(state.fieldId);
}
constexpr std::size_t BinaryProtocolReader::fixedSizeInContainer(TType type) {
switch (type) {
case TType::T_BOOL:
case TType::T_BYTE:
return 1;
case TType::T_I16:
return 2;
case TType::T_I32:
case TType::T_FLOAT:
return 4;
case TType::T_I64:
case TType::T_DOUBLE:
return 8;
default:
return 0;
}
}
} // namespace thrift
} // namespace apache
#endif // #ifndef THRIFT2_PROTOCOL_TBINARYPROTOCOL_TCC_
|
amrshennawi/fbthrift
|
thrift/lib/py3/tablebased/Serializer.h
|
<gh_stars>0
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <Python.h>
#include <memory>
#include <folly/io/IOBuf.h>
#include <thrift/lib/cpp2/protocol/BinaryProtocol.h>
#include <thrift/lib/cpp2/protocol/CompactProtocol.h>
#include <thrift/lib/py3/tablebased/PythonTableBased.h>
namespace apache {
namespace thrift {
namespace python {
template <typename Writer>
std::unique_ptr<folly::IOBuf> serialize(
const DynamicStructInfo& dynamicStructInfo, const PyObject* object) {
auto queue = folly::IOBufQueue{folly::IOBufQueue::cacheChainLength()};
Writer writer(SHARE_EXTERNAL_BUFFER);
writer.setOutput(&queue);
detail::write(&writer, dynamicStructInfo.getStructInfo(), object);
return queue.move();
}
template <typename Reader>
size_t deserialize(
const DynamicStructInfo& dynamicStructInfo,
const folly::IOBuf* buf,
PyObject* object) {
Reader reader(SHARE_EXTERNAL_BUFFER);
reader.setInput(buf);
detail::read(&reader, dynamicStructInfo.getStructInfo(), object);
return reader.getCursor().getCurrentPosition();
}
using apache::thrift::protocol::PROTOCOL_TYPES;
std::unique_ptr<folly::IOBuf> serialize(
const DynamicStructInfo& dynamicStructInfo,
const PyObject* object,
PROTOCOL_TYPES protocol) {
switch (protocol) {
case PROTOCOL_TYPES::T_COMPACT_PROTOCOL:
return serialize<CompactProtocolWriter>(dynamicStructInfo, object);
case PROTOCOL_TYPES::T_BINARY_PROTOCOL:
return serialize<BinaryProtocolWriter>(dynamicStructInfo, object);
default:
throw TProtocolException(
TProtocolException::NOT_IMPLEMENTED, "protocol not supported yet");
}
}
size_t deserialize(
const DynamicStructInfo& dynamicStructInfo,
const folly::IOBuf* buf,
PyObject* object,
PROTOCOL_TYPES protocol) {
switch (protocol) {
case PROTOCOL_TYPES::T_COMPACT_PROTOCOL:
return deserialize<CompactProtocolReader>(dynamicStructInfo, buf, object);
case PROTOCOL_TYPES::T_BINARY_PROTOCOL:
return deserialize<BinaryProtocolReader>(dynamicStructInfo, buf, object);
default:
throw TProtocolException(
TProtocolException::NOT_IMPLEMENTED, "protocol not supported yet");
}
}
} // namespace python
} // namespace thrift
} // namespace apache
|
amrshennawi/fbthrift
|
thrift/lib/cpp2/transport/rocket/framing/Parser.h
|
<reponame>amrshennawi/fbthrift
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <chrono>
#include <utility>
#include <folly/ExceptionWrapper.h>
#include <folly/Function.h>
#include <folly/io/IOBuf.h>
#include <folly/io/IOBufQueue.h>
#include <folly/io/async/AsyncTransport.h>
#include <thrift/lib/cpp2/Flags.h>
THRIFT_FLAG_DECLARE_int64(rocket_parser_resize_period_seconds);
THRIFT_FLAG_DECLARE_bool(rocket_parser_dont_hold_buffer_enabled);
THRIFT_FLAG_DECLARE_bool(rocket_parser_hybrid_buffer_enabled);
namespace apache {
namespace thrift {
namespace rocket {
template <class T>
class Parser final : public folly::AsyncTransport::ReadCallback,
public folly::HHWheelTimer::Callback {
public:
explicit Parser(
T& owner,
std::chrono::milliseconds resizeBufferTimeout =
kDefaultBufferResizeInterval)
: newBufferLogicEnabled_(
THRIFT_FLAG(rocket_parser_dont_hold_buffer_enabled)),
hybridBufferLogicEnabled_(
THRIFT_FLAG(rocket_parser_hybrid_buffer_enabled) &&
!newBufferLogicEnabled_),
owner_(owner),
resizeBufferTimeout_(resizeBufferTimeout),
periodicResizeBufferTimeout_(
THRIFT_FLAG(rocket_parser_resize_period_seconds)),
readBuffer_(
folly::IOBuf::CreateOp(),
hybridBufferLogicEnabled_ ? kStaticBufferSize : bufferSize_) {}
~Parser() override {
if (currentFrameLength_) {
owner_.decMemoryUsage(currentFrameLength_);
}
}
// AsyncTransport::ReadCallback implementation
FOLLY_NOINLINE void getReadBuffer(void** bufout, size_t* lenout) override;
FOLLY_NOINLINE void readDataAvailable(size_t nbytes) noexcept override;
FOLLY_NOINLINE void readEOF() noexcept override;
FOLLY_NOINLINE void readErr(
const folly::AsyncSocketException&) noexcept override;
FOLLY_NOINLINE void readBufferAvailable(
std::unique_ptr<folly::IOBuf> /*readBuf*/) noexcept override;
bool isBufferMovable() noexcept override { return true; }
// TODO: This should be removed once the new buffer logic controlled by
// THRIFT_FLAG(rocket_parser_dont_hold_buffer_enabled) is stable.
void timeoutExpired() noexcept override;
// TODO: This should be removed once the new buffer logic controlled by
// THRIFT_FLAG(rocket_parser_dont_hold_buffer_enabled) is stable.
const folly::IOBuf& getReadBuffer() const { return readBuffer_; }
// TODO: This should be removed once the new buffer logic controlled by
// THRIFT_FLAG(rocket_parser_dont_hold_buffer_enabled) is stable.
void setReadBuffer(folly::IOBuf&& buffer) { readBuffer_ = std::move(buffer); }
size_t getReadBufferSize() const { return bufferSize_; }
void setReadBufferSize(size_t size) { bufferSize_ = size; }
// TODO: This should be removed once the new buffer logic controlled by
// THRIFT_FLAG(rocket_parser_dont_hold_buffer_enabled) is stable.
void resizeBuffer();
size_t getReadBufLength() const {
if (newBufferLogicEnabled_) {
return readBufQueue_.chainLength();
} else if (hybridBufferLogicEnabled_) {
return dynamicBuffer_ ? dynamicBuffer_->length() : readBuffer_.length();
}
return readBuffer_.computeChainDataLength();
}
bool getNewBufferLogicEnabled() const { return newBufferLogicEnabled_; }
static constexpr size_t kMinBufferSize{256};
static constexpr size_t kMaxBufferSize{4096};
private:
// "old" logic: maintain read buffer in Parser and resize as necessary, hand
// out frames as IOBufs pointing to the buffer
// TODO: remove once hybrid logic is stable
void getReadBufferOld(void** bufout, size_t* lenout);
void readDataAvailableOld(size_t nbytes);
// "new" logic: allocate space for frames and transfer ownership to
// application immediately
// TODO: remove once hybrid logic is stable
void getReadBufferNew(void** bufout, size_t* lenout);
void readDataAvailableNew(size_t nbytes);
// hybrid logic: maintain small, static read buffer in Parser (like "old"
// logic), allocate space in dynamic buffer and immediately transfer ownership
// if necessary (like "new" logic)
void getReadBufferHybrid(void** bufout, size_t* lenout);
void readDataAvailableHybrid(size_t nbytes);
// Flag that controls if the parser should use the new buffer logic
const bool newBufferLogicEnabled_;
// Flag that controls if the parser should use the hybrid buffer logic
const bool hybridBufferLogicEnabled_;
// TODO: This should be removed once the new buffer logic controlled by
// THRIFT_FLAG(rocket_parser_dont_hold_buffer_enabled) is stable.
static constexpr std::chrono::milliseconds kDefaultBufferResizeInterval{
std::chrono::seconds(3)};
T& owner_;
size_t bufferSize_{kMinBufferSize};
// TODO: readBuffer_, lastResizeTime_, resizeBufferTimeout_ and
// periodicResizeBufferTimeout_ should be removed once the new buffer logic
// controlled by THRIFT_FLAG(rocket_parser_dont_hold_buffer_enabled) is
// stable.
std::chrono::steady_clock::time_point lastResizeTime_{
std::chrono::steady_clock::now()};
const std::chrono::milliseconds resizeBufferTimeout_;
const int64_t periodicResizeBufferTimeout_;
bool aligning_{false};
size_t currentFrameLength_{0};
uint8_t currentFrameType_{0};
// used by readDataAvailable or readBufferAvailable API (only one will be
// invoked for a given AsyncTransport)
folly::IOBufQueue readBufQueue_{folly::IOBufQueue::cacheChainLength()};
folly::IOBuf readBuffer_;
// hybrid logic
static constexpr size_t kStaticBufferSize = 1024;
static constexpr size_t kReallocateThreshold = 64;
std::unique_ptr<folly::IOBuf> dynamicBuffer_{nullptr};
bool reallocateIfShared_{false};
};
} // namespace rocket
} // namespace thrift
} // namespace apache
#include <thrift/lib/cpp2/transport/rocket/framing/Parser-inl.h>
|
amrshennawi/fbthrift
|
thrift/lib/cpp2/transport/rocket/framing/Parser-inl.h
|
<filename>thrift/lib/cpp2/transport/rocket/framing/Parser-inl.h<gh_stars>1-10
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <algorithm>
#include <chrono>
#include <exception>
#include <memory>
#include <utility>
#include <folly/ExceptionString.h>
#include <folly/ExceptionWrapper.h>
#include <folly/io/Cursor.h>
#include <folly/io/IOBuf.h>
#include <folly/io/async/AsyncSocketException.h>
#include <folly/io/async/DelayedDestruction.h>
#include <thrift/lib/cpp/transport/TTransportException.h>
#include <thrift/lib/cpp2/transport/rocket/framing/FrameType.h>
#include <thrift/lib/cpp2/transport/rocket/framing/Frames.h>
#include <thrift/lib/cpp2/transport/rocket/framing/Serializer.h>
#include <thrift/lib/cpp2/transport/rocket/framing/Util.h>
namespace apache {
namespace thrift {
namespace rocket {
template <class T>
void Parser<T>::getReadBufferOld(void** bufout, size_t* lenout) {
DCHECK(!readBuffer_.isChained());
if (LIKELY(!aligning_)) {
if (periodicResizeBufferTimeout_ == 0) {
const auto now = std::chrono::steady_clock::now();
if (now - lastResizeTime_ > resizeBufferTimeout_) {
resizeBuffer();
lastResizeTime_ = now;
}
}
readBuffer_.unshareOne();
if (readBuffer_.length() == 0) {
DCHECK(readBuffer_.capacity() > 0);
// If we read everything, reset pointers to 0 and reuse the buffer
readBuffer_.clear();
} else if (readBuffer_.headroom() > 0) {
// Move partially read data to the beginning
readBuffer_.retreat(readBuffer_.headroom());
}
}
*bufout = readBuffer_.writableTail();
*lenout = readBuffer_.tailroom();
}
template <class T>
void Parser<T>::getReadBufferNew(void** bufout, size_t* lenout) {
const auto ret = readBufQueue_.preallocate(bufferSize_, kMaxBufferSize);
*bufout = ret.first;
*lenout = ret.second;
return;
}
template <class T>
void Parser<T>::getReadBufferHybrid(void** bufout, size_t* lenout) {
// if dynamic buffer is not null, read the remainder of currentFrameLength_
// into it, so it contains exactly one full frame
if (dynamicBuffer_) {
*bufout = dynamicBuffer_->writableTail();
*lenout = currentFrameLength_ - dynamicBuffer_->length();
} else {
if (!readBuffer_.isSharedOne()) {
// without external refs, we can move data (same as clear() if length==0)
readBuffer_.retreat(readBuffer_.headroom());
} else if (reallocateIfShared_) {
auto buf = folly::IOBuf(folly::IOBuf::CreateOp(), kStaticBufferSize);
memcpy(buf.writableData(), readBuffer_.data(), readBuffer_.length());
buf.append(readBuffer_.length());
readBuffer_ = std::move(buf);
}
reallocateIfShared_ = false;
*bufout = readBuffer_.writableTail();
*lenout = readBuffer_.tailroom();
}
}
template <class T>
void Parser<T>::readDataAvailableOld(size_t nbytes) {
readBuffer_.append(nbytes);
while (!readBuffer_.empty()) {
if (readBuffer_.length() < Serializer::kMinimumFrameHeaderLength) {
return;
}
folly::io::Cursor cursor(&readBuffer_);
const size_t totalFrameSize = Serializer::kBytesForFrameOrMetadataLength +
readFrameOrMetadataSize(cursor);
if (!currentFrameLength_) {
if (!owner_.incMemoryUsage(totalFrameSize)) {
return;
}
currentFrameLength_ = totalFrameSize;
}
readStreamId(cursor);
uint8_t frameType;
std::tie(frameType, std::ignore) = readFrameTypeAndFlagsUnsafe(cursor);
if (UNLIKELY(
static_cast<FrameType>(frameType) == FrameType::EXT &&
!aligning_)) {
if (readBuffer_.length() < Serializer::kBytesForFrameOrMetadataLength +
ExtFrame::frameHeaderSize()) {
return;
}
ExtFrameType extType = readExtFrameType(cursor);
if (UNLIKELY(extType == ExtFrameType::ALIGNED_PAGE)) {
if (alignTo4k(
readBuffer_,
Serializer::kBytesForFrameOrMetadataLength +
ExtFrame::frameHeaderSize(),
totalFrameSize)) {
aligning_ = true;
}
}
}
if (readBuffer_.length() < totalFrameSize) {
if (readBuffer_.length() + readBuffer_.tailroom() < totalFrameSize) {
DCHECK(!readBuffer_.isChained());
readBuffer_.unshareOne();
bufferSize_ = std::max<size_t>(bufferSize_, totalFrameSize);
readBuffer_.reserve(
0 /* minHeadroom */,
bufferSize_ - readBuffer_.length() /* minTailroom */);
}
return;
}
// Otherwise, we have a full frame to handle.
const size_t bytesToClone =
totalFrameSize - Serializer::kBytesForFrameOrMetadataLength;
cursor.reset(&readBuffer_);
readFrameOrMetadataSize(cursor);
std::unique_ptr<folly::IOBuf> frame;
cursor.clone(frame, bytesToClone);
owner_.decMemoryUsage(currentFrameLength_);
currentFrameLength_ = 0;
readBuffer_.trimStart(totalFrameSize);
aligning_ = false;
owner_.handleFrame(std::move(frame));
}
if (periodicResizeBufferTimeout_ != 0 && !isScheduled() &&
bufferSize_ > kMaxBufferSize) {
owner_.scheduleTimeout(
this, std::chrono::seconds(periodicResizeBufferTimeout_));
}
}
template <class T>
void Parser<T>::readDataAvailableNew(size_t nbytes) {
readBufQueue_.postallocate(nbytes);
while (!readBufQueue_.empty()) {
if (readBufQueue_.chainLength() < Serializer::kMinimumFrameHeaderLength) {
return;
}
folly::io::Cursor cursor(readBufQueue_.front());
const size_t totalFrameSize = Serializer::kBytesForFrameOrMetadataLength +
readFrameOrMetadataSize(cursor);
if (!currentFrameLength_) {
if (!owner_.incMemoryUsage(totalFrameSize)) {
return;
}
currentFrameLength_ = totalFrameSize;
}
readStreamId(cursor);
uint8_t frameType;
std::tie(frameType, std::ignore) = readFrameTypeAndFlagsUnsafe(cursor);
if (UNLIKELY(
static_cast<FrameType>(frameType) == FrameType::EXT &&
!aligning_)) {
if (readBufQueue_.chainLength() <
Serializer::kBytesForFrameOrMetadataLength +
ExtFrame::frameHeaderSize()) {
return;
}
ExtFrameType extType = readExtFrameType(cursor);
if (UNLIKELY(extType == ExtFrameType::ALIGNED_PAGE)) {
if (alignTo4kBufQueue(
readBufQueue_,
Serializer::kBytesForFrameOrMetadataLength +
ExtFrame::frameHeaderSize(),
totalFrameSize)) {
aligning_ = true;
}
}
}
if (readBufQueue_.chainLength() < currentFrameLength_) {
bufferSize_ = currentFrameLength_ - readBufQueue_.chainLength();
return;
}
// Otherwise, we have a full frame to handle.
readBufQueue_.trimStart(Serializer::kBytesForFrameOrMetadataLength);
auto frame = readBufQueue_.split(
currentFrameLength_ - Serializer::kBytesForFrameOrMetadataLength);
owner_.handleFrame(std::move(frame));
owner_.decMemoryUsage(currentFrameLength_);
currentFrameLength_ = 0;
bufferSize_ = kMinBufferSize;
aligning_ = false;
}
}
template <class T>
void Parser<T>::readDataAvailableHybrid(size_t nbytes) {
if (dynamicBuffer_) {
dynamicBuffer_->append(nbytes);
if (dynamicBuffer_->length() < currentFrameLength_) {
return;
}
DCHECK_EQ(dynamicBuffer_->length(), currentFrameLength_);
owner_.handleFrame(std::move(dynamicBuffer_));
owner_.decMemoryUsage(currentFrameLength_);
currentFrameLength_ = 0;
currentFrameType_ = 0;
return;
}
// set reallocate hint if latest read filled most of the buffer
DCHECK_LE(nbytes, readBuffer_.tailroom());
reallocateIfShared_ = readBuffer_.tailroom() - nbytes < kReallocateThreshold;
readBuffer_.append(nbytes);
while (!readBuffer_.empty()) {
const size_t bufLen = readBuffer_.length();
if (bufLen < Serializer::kMinimumFrameHeaderLength) {
return;
}
folly::io::Cursor cursor(&readBuffer_);
if (!currentFrameLength_) {
auto frameLength = readFrameOrMetadataSize(cursor);
if (!owner_.incMemoryUsage(frameLength)) {
return;
}
currentFrameLength_ = frameLength;
// skip over stream ID
cursor.skipNoAdvance(sizeof(StreamId::underlying_type));
// read frameType and ignore flags
std::tie(currentFrameType_, std::ignore) =
readFrameTypeAndFlagsUnsafe(cursor);
} else {
cursor.skipNoAdvance(Serializer::kMinimumFrameHeaderLength);
}
const size_t totalSize =
currentFrameLength_ + Serializer::kBytesForFrameOrMetadataLength;
// check for alignment frame
if (UNLIKELY(
static_cast<FrameType>(currentFrameType_) == FrameType::EXT &&
!aligning_)) {
if (bufLen < Serializer::kBytesForFrameOrMetadataLength +
ExtFrame::frameHeaderSize()) {
return;
}
ExtFrameType extType = readExtFrameType(cursor);
if (UNLIKELY(extType == ExtFrameType::ALIGNED_PAGE)) {
aligning_ = true;
const size_t bytesToCopy = std::min(
currentFrameLength_,
readBuffer_.length() - Serializer::kBytesForFrameOrMetadataLength);
dynamicBuffer_ = get4kAlignedBuf(
currentFrameLength_, ExtFrame::frameHeaderSize(), bytesToCopy);
if (LIKELY(dynamicBuffer_ != nullptr)) {
aligning_ = false;
readBuffer_.trimStart(Serializer::kBytesForFrameOrMetadataLength);
memcpy(
dynamicBuffer_->writableData(), readBuffer_.data(), bytesToCopy);
readBuffer_.trimStart(bytesToCopy);
// if we had the full frame, send it right away and continue loop
if (bytesToCopy == currentFrameLength_) {
owner_.handleFrame(std::move(dynamicBuffer_));
owner_.decMemoryUsage(currentFrameLength_);
currentFrameLength_ = 0;
currentFrameType_ = 0;
continue;
}
// otherwise, return to read rest of frame into dynamic buffer
return;
}
}
}
// we may have an incomplete frame
if (totalSize > bufLen) {
// switch to dynamic buffer only if there is no way to fit the whole frame
// into the static buffer
if (totalSize - bufLen > readBuffer_.tailroom() &&
LIKELY(totalSize > kStaticBufferSize || readBuffer_.isSharedOne())) {
dynamicBuffer_ = folly::IOBuf::createCombined(currentFrameLength_);
readBuffer_.trimStart(Serializer::kBytesForFrameOrMetadataLength);
memcpy(
dynamicBuffer_->writableData(),
readBuffer_.data(),
readBuffer_.length());
dynamicBuffer_->append(readBuffer_.length());
// "free" the data we just copied in readBuffer_
readBuffer_.prepend(Serializer::kBytesForFrameOrMetadataLength);
readBuffer_.trimEnd(readBuffer_.length());
}
return;
}
// otherwise, we have a full frame
cursor.reset(&readBuffer_);
cursor.skipNoAdvance(Serializer::kBytesForFrameOrMetadataLength);
std::unique_ptr<folly::IOBuf> frame;
cursor.clone(frame, currentFrameLength_);
readBuffer_.trimStart(totalSize);
aligning_ = false;
owner_.handleFrame(std::move(frame));
owner_.decMemoryUsage(currentFrameLength_);
currentFrameLength_ = 0;
currentFrameType_ = 0;
}
}
template <class T>
void Parser<T>::getReadBuffer(void** bufout, size_t* lenout) {
if (newBufferLogicEnabled_) {
getReadBufferNew(bufout, lenout);
} else if (hybridBufferLogicEnabled_) {
getReadBufferHybrid(bufout, lenout);
} else {
getReadBufferOld(bufout, lenout);
}
}
template <class T>
void Parser<T>::readDataAvailable(size_t nbytes) noexcept {
folly::DelayedDestruction::DestructorGuard dg(&this->owner_);
try {
if (newBufferLogicEnabled_) {
readDataAvailableNew(nbytes);
} else if (hybridBufferLogicEnabled_) {
readDataAvailableHybrid(nbytes);
} else {
readDataAvailableOld(nbytes);
}
} catch (...) {
auto exceptionStr =
folly::exceptionStr(std::current_exception()).toStdString();
LOG(ERROR) << "Bad frame received, closing connection: " << exceptionStr;
owner_.close(transport::TTransportException(exceptionStr));
}
}
template <class T>
void Parser<T>::readEOF() noexcept {
folly::DelayedDestruction::DestructorGuard dg(&this->owner_);
owner_.close(transport::TTransportException(
transport::TTransportException::TTransportExceptionType::END_OF_FILE,
"Channel got EOF. Check for server hitting connection limit, "
"server connection idle timeout, and server crashes."));
}
template <class T>
void Parser<T>::readErr(const folly::AsyncSocketException& ex) noexcept {
folly::DelayedDestruction::DestructorGuard dg(&this->owner_);
owner_.close(transport::TTransportException(ex));
}
// TODO: This should be removed once the new buffer logic controlled by
// THRIFT_FLAG(rocket_parser_dont_hold_buffer_enabled) is stable.
template <class T>
void Parser<T>::timeoutExpired() noexcept {
if (LIKELY(!aligning_)) {
resizeBuffer();
}
}
template <class T>
void Parser<T>::readBufferAvailable(
std::unique_ptr<folly::IOBuf> buf) noexcept {
folly::DelayedDestruction::DestructorGuard dg(&this->owner_);
try {
readBufQueue_.append(std::move(buf));
while (!readBufQueue_.empty()) {
if (readBufQueue_.chainLength() <
Serializer::kBytesForFrameOrMetadataLength) {
return;
}
folly::io::Cursor cursor(readBufQueue_.front());
if (!currentFrameLength_) {
currentFrameLength_ = Serializer::kBytesForFrameOrMetadataLength +
readFrameOrMetadataSize(cursor);
if (!owner_.incMemoryUsage(currentFrameLength_)) {
currentFrameLength_ = 0;
return;
}
}
if (readBufQueue_.chainLength() < currentFrameLength_) {
return;
}
readBufQueue_.trimStart(Serializer::kBytesForFrameOrMetadataLength);
auto frame = readBufQueue_.split(
currentFrameLength_ - Serializer::kBytesForFrameOrMetadataLength);
owner_.handleFrame(std::move(frame));
owner_.decMemoryUsage(currentFrameLength_);
currentFrameLength_ = 0;
}
} catch (...) {
auto exceptionStr =
folly::exceptionStr(std::current_exception()).toStdString();
LOG(ERROR) << "Bad frame received, closing connection: " << exceptionStr;
owner_.close(transport::TTransportException(exceptionStr));
}
}
// TODO: This should be removed once the new buffer logic controlled by
// THRIFT_FLAG(rocket_parser_dont_hold_buffer_enabled) is stable.
template <class T>
void Parser<T>::resizeBuffer() {
if (bufferSize_ <= kMaxBufferSize || readBuffer_.length() >= kMaxBufferSize) {
return;
}
// resize readBuffer_ to kMaxBufferSize
readBuffer_ = folly::IOBuf(
folly::IOBuf::CopyBufferOp(),
readBuffer_.data(),
readBuffer_.length(),
/* headroom */ 0,
/* tailroom */ kMaxBufferSize - readBuffer_.length());
bufferSize_ = kMaxBufferSize;
}
template <class T>
constexpr size_t Parser<T>::kMinBufferSize;
template <class T>
constexpr size_t Parser<T>::kMaxBufferSize;
// TODO: This should be removed once the new buffer logic controlled by
// THRIFT_FLAG(rocket_parser_dont_hold_buffer_enabled) is stable.
template <class T>
constexpr std::chrono::milliseconds Parser<T>::kDefaultBufferResizeInterval;
template <class T>
constexpr size_t Parser<T>::kStaticBufferSize;
template <class T>
constexpr size_t Parser<T>::kReallocateThreshold;
} // namespace rocket
} // namespace thrift
} // namespace apache
|
amrshennawi/fbthrift
|
thrift/lib/cpp2/Adapt.h
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <functional>
#include <utility>
#include <folly/Traits.h>
namespace apache {
namespace thrift {
namespace adapt_detail {
// Identical to std::declval<const T&>
template <typename T>
const T& cr();
template <typename Adapter, typename AdaptedT, typename NativeT>
void fromThrift(AdaptedT& adapted, NativeT&& native) {
adapted = Adapter::fromThrift(std::forward<NativeT>(native));
}
// The type returned by the adapter for the given thrift type.
template <typename Adapter, typename ThriftT>
using adapted_t = decltype(Adapter::fromThrift(std::declval<ThriftT&&>()));
// Equal op based on the thrift types.
template <typename Adapter, typename AdaptedT>
struct thrift_equal {
constexpr bool operator()(const AdaptedT& lhs, const AdaptedT& rhs) const {
return Adapter::toThrift(lhs) == Adapter::toThrift(rhs);
}
};
// Equal op based on the adapted types, with a fallback on thrift_equal.
template <typename Adapter, typename AdaptedT, typename = void>
struct adapted_equal : thrift_equal<Adapter, AdaptedT> {};
template <typename Adapter, typename AdaptedT>
struct adapted_equal<
Adapter,
AdaptedT,
folly::void_t<decltype(cr<AdaptedT>() == cr<AdaptedT>())>> {
constexpr bool operator()(const AdaptedT& lhs, const AdaptedT& rhs) const {
return lhs == rhs;
}
};
// Equal op based on the adapter, with a fallback on adapted_equal.
template <typename Adapter, typename AdaptedT, typename = void>
struct adapter_equal : adapted_equal<Adapter, AdaptedT> {};
template <typename Adapter, typename AdaptedT>
struct adapter_equal<
Adapter,
AdaptedT,
folly::void_t<decltype(Adapter::equal(cr<AdaptedT>(), cr<AdaptedT>()))>> {
constexpr bool operator()(const AdaptedT& lhs, const AdaptedT& rhs) const {
return Adapter::equal(lhs, rhs);
}
};
// Less op based on the thrift types.
template <typename Adapter, typename AdaptedT>
struct thrift_less {
constexpr bool operator()(const AdaptedT& lhs, const AdaptedT& rhs) const {
return Adapter::toThrift(lhs) < Adapter::toThrift(rhs);
}
};
// Less op based on the adapted types, with a fallback on thrift_less.
template <typename Adapter, typename AdaptedT, typename = void>
struct adapted_less : thrift_less<Adapter, AdaptedT> {};
template <typename Adapter, typename AdaptedT>
struct adapted_less<
Adapter,
AdaptedT,
folly::void_t<decltype(cr<AdaptedT>() < cr<AdaptedT>())>> {
constexpr bool operator()(const AdaptedT& lhs, const AdaptedT& rhs) const {
return lhs < rhs;
}
};
// Less op based on the adapter, with a fallback on adapted_less.
template <typename Adapter, typename AdaptedT, typename = void>
struct adapter_less : adapted_less<Adapter, AdaptedT> {};
template <typename Adapter, typename AdaptedT>
struct adapter_less<
Adapter,
AdaptedT,
folly::void_t<decltype(Adapter::less(cr<AdaptedT>(), cr<AdaptedT>()))>> {
constexpr bool operator()(const AdaptedT& lhs, const AdaptedT& rhs) const {
return Adapter::less(lhs, rhs);
}
};
// Hash based on the thrift type.
template <typename Adapter, typename AdaptedT>
struct thrift_hash {
constexpr size_t operator()(const AdaptedT& value) const {
auto&& tvalue = Adapter::toThrift(value);
return std::hash<folly::remove_cvref_t<decltype(tvalue)>>()(tvalue);
}
};
// Hash based on the adapted types, with a fallback on thrift_hash.
template <typename Adapter, typename AdaptedT, typename = void>
struct adapted_hash : thrift_hash<Adapter, AdaptedT> {};
template <typename Adapter, typename AdaptedT>
struct adapted_hash<
Adapter,
AdaptedT,
folly::void_t<decltype(std::hash<std::decay_t<AdaptedT>>())>>
: std::hash<std::decay_t<AdaptedT>> {};
// Hash based on the adapter, with a fallback on adapted_hash.
template <typename Adapter, typename AdaptedT, typename = void>
struct adapter_hash : adapted_hash<Adapter, AdaptedT> {};
template <typename Adapter, typename AdaptedT>
struct adapter_hash<
Adapter,
AdaptedT,
folly::void_t<decltype(Adapter::hash(cr<AdaptedT>()))>> {
constexpr size_t operator()(const AdaptedT& value) const {
return Adapter::hash(value);
}
};
template <typename Adapter, typename AdaptedT>
constexpr bool equal(const AdaptedT& lhs, const AdaptedT& rhs) {
return adapter_equal<Adapter, AdaptedT>()(lhs, rhs);
}
template <typename Adapter, typename AdaptedT>
constexpr bool not_equal(const AdaptedT& lhs, const AdaptedT& rhs) {
return !adapter_equal<Adapter, AdaptedT>()(lhs, rhs);
}
template <typename Adapter, typename AdaptedT>
constexpr bool less(const AdaptedT& lhs, const AdaptedT& rhs) {
return adapter_less<Adapter, AdaptedT>()(lhs, rhs);
}
template <typename Adapter, typename AdaptedT>
constexpr size_t hash(const AdaptedT& value) {
return adapter_hash<Adapter, AdaptedT>()(value);
}
} // namespace adapt_detail
} // namespace thrift
} // namespace apache
|
amrshennawi/fbthrift
|
thrift/lib/cpp2/transport/rocket/client/RocketClient.h
|
/*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#pragma once
#include <chrono>
#include <memory>
#include <utility>
#include <folly/ExceptionWrapper.h>
#include <folly/Try.h>
#include <folly/container/F14Set.h>
#include <folly/io/async/AsyncSocket.h>
#include <folly/io/async/AsyncTransport.h>
#include <folly/io/async/DelayedDestruction.h>
#include <folly/io/async/EventBase.h>
#include <folly/io/async/EventBaseLocal.h>
#include <thrift/lib/cpp/transport/TTransportException.h>
#include <thrift/lib/cpp2/transport/rocket/Types.h>
#include <thrift/lib/cpp2/transport/rocket/client/RequestContext.h>
#include <thrift/lib/cpp2/transport/rocket/client/RequestContextQueue.h>
#include <thrift/lib/cpp2/transport/rocket/client/RocketStreamServerCallback.h>
#include <thrift/lib/cpp2/transport/rocket/framing/Frames.h>
#include <thrift/lib/cpp2/transport/rocket/framing/Parser.h>
namespace folly {
class IOBuf;
namespace fibers {
class FiberManager;
} // namespace fibers
} // namespace folly
namespace apache {
namespace thrift {
namespace rocket {
class RocketClient : public virtual folly::DelayedDestruction,
private folly::AsyncTransport::WriteCallback {
public:
using FlushList = boost::intrusive::list<
folly::EventBase::LoopCallback,
boost::intrusive::constant_time_size<false>>;
RocketClient(const RocketClient&) = delete;
RocketClient(RocketClient&&) = delete;
RocketClient& operator=(const RocketClient&) = delete;
RocketClient& operator=(RocketClient&&) = delete;
~RocketClient() override;
using Ptr =
std::unique_ptr<RocketClient, folly::DelayedDestruction::Destructor>;
static Ptr create(
folly::EventBase& evb,
folly::AsyncTransport::UniquePtr socket,
std::unique_ptr<SetupFrame> setupFrame);
using WriteSuccessCallback = RequestContext::WriteSuccessCallback;
class RequestResponseCallback : public WriteSuccessCallback {
public:
virtual ~RequestResponseCallback() = default;
virtual void onResponsePayload(folly::Try<Payload>&& response) noexcept = 0;
};
FOLLY_NODISCARD folly::Try<Payload> sendRequestResponseSync(
Payload&& request,
std::chrono::milliseconds timeout,
WriteSuccessCallback* callback);
void sendRequestResponse(
Payload&& request,
std::chrono::milliseconds timeout,
std::unique_ptr<RequestResponseCallback> callback);
class RequestFnfCallback {
public:
virtual ~RequestFnfCallback() = default;
virtual void onWrite(folly::Try<void> writeResult) noexcept = 0;
};
FOLLY_NODISCARD folly::Try<void> sendRequestFnfSync(Payload&& request);
void sendRequestFnf(
Payload&& request, std::unique_ptr<RequestFnfCallback> callback);
void sendRequestStream(
Payload&& request,
std::chrono::milliseconds firstResponseTimeout,
std::chrono::milliseconds chunkTimeout,
int32_t initialRequestN,
StreamClientCallback* clientCallback);
void sendRequestSink(
Payload&& request,
std::chrono::milliseconds firstResponseTimeout,
SinkClientCallback* clientCallback,
bool pageAligned = false,
folly::Optional<CompressionConfig> compressionConfig = folly::none);
FOLLY_NODISCARD bool sendRequestN(StreamId streamId, int32_t n);
void cancelStream(StreamId streamId);
void sendPayload(StreamId streamId, StreamPayload&& payload, Flags flags);
void sendError(StreamId streamId, RocketException&& rex);
void sendComplete(StreamId streamId, bool closeStream);
void sendExtAlignedPage(
StreamId streamId, std::unique_ptr<folly::IOBuf> payload, Flags flags);
FOLLY_NODISCARD bool sendHeadersPush(
StreamId streamId, HeadersPayload&& payload);
// sink error can use different frames depends on server version
FOLLY_NODISCARD bool sendSinkError(
StreamId streamId, StreamPayload&& payload);
bool streamExists(StreamId streamId) const;
// AsyncTransport::WriteCallback implementation
void writeSuccess() noexcept override;
void writeErr(
size_t bytesWritten,
const folly::AsyncSocketException& e) noexcept override;
void setCloseCallback(folly::Function<void()> closeCallback) {
closeCallback_ = std::move(closeCallback);
}
bool isAlive() const {
return clientState_.connState == ConnectionState::CONNECTED;
}
const folly::exception_wrapper& getLastError() const { return error_; }
size_t streams() const { return streams_.size(); }
size_t requests() const { return clientRequests_; }
const folly::AsyncTransport* getTransportWrapper() const {
return socket_.get();
}
folly::AsyncTransport* getTransportWrapper() { return socket_.get(); }
bool isDetachable() const {
if (!evb_) {
return false;
}
evb_->dcheckIsInEventBaseThread();
// Client is only detachable if there are no inflight requests, no active
// streams, and if the underlying transport is detachable, i.e., has no
// inflight writes of its own.
return !writeLoopCallback_.isLoopCallbackScheduled() && !requests_ &&
streams_.empty() && (!socket_ || socket_->isDetachable()) &&
parser_.getReadBufLength() == 0 && !interactions_;
}
void attachEventBase(folly::EventBase& evb);
void detachEventBase();
void setOnDetachable(folly::Function<void()> onDetachable) {
onDetachable_ = std::move(onDetachable);
}
void notifyIfDetachable() {
if (clientState_.connState == ConnectionState::CLOSING && !requests_ &&
streams_.empty()) {
close(transport::TTransportException(
transport::TTransportException::END_OF_FILE,
"Connection closed by server"));
}
if (!onDetachable_ || !isDetachable()) {
return;
}
if (detachableLoopCallback_.isLoopCallbackScheduled()) {
return;
}
evb_->runInLoop(&detachableLoopCallback_);
}
/**
* Set a centrilized list for flushing all pending writes.
*
* By default EventBase itself is used to schedule flush callback at the end
* of the next event loop. If flushList is not null, RocketClient would attach
* callbacks to it intstead, thus granting control over when writes happen to
* the application.
*
* Note: the caller is responsible for making sure that the list outlives the
* client.
*
* Note2: call to detachEventBase() would reset the list back to nullptr.
*/
void setFlushList(FlushList* flushList) { flushList_ = flushList; }
class FlushManager : private folly::EventBase::LoopCallback {
public:
explicit FlushManager(folly::EventBase& evb) : evb_(evb) {}
static FlushManager& getInstance(folly::EventBase& evb) {
return getEventBaseLocal().try_emplace(evb, evb);
}
void enqueueFlush(RocketClient& client);
// has time complexity linear to number of elements in flush list
size_t getNumPendingClients() const { return flushList_.size(); }
private:
void runLoopCallback() noexcept override final;
folly::EventBase& evb_;
FlushList flushList_;
bool rescheduled_{false};
};
void scheduleTimeout(
folly::HHWheelTimer::Callback* callback,
const std::chrono::milliseconds& timeout) {
if (timeout != std::chrono::milliseconds::zero()) {
evb_->timer().scheduleTimeout(callback, timeout);
}
}
void addInteraction() { ++interactions_; }
void terminateInteraction(int64_t id);
// Request connection close and fail all the requests.
void close(folly::exception_wrapper ex) noexcept;
bool incMemoryUsage(uint32_t) { return true; }
void decMemoryUsage(uint32_t) {}
int32_t getServerVersion() const { return serverVersion_; }
folly::EventBase* getEventBase() { return evb_; }
private:
enum class ConnectionState : uint8_t {
CONNECTED, // New requests are allowed
CLOSING, // New requests are not allowed, there are active requests or close
// callback is scheduled.
CLOSED, // New requests are not allowed, there are no active requests.
ERROR, // New requests are not allowed, error is stored in error_, close
// callback is scheduled.
};
struct ClientState {
ConnectionState connState : 2;
bool hitMaxStreamId : 1;
bool hasPendingSetupFrame : 1;
ClientState() {
// Client must be constructed with an already open socket
connState = ConnectionState::CONNECTED;
hitMaxStreamId = false;
hasPendingSetupFrame = true;
}
} clientState_;
int16_t serverVersion_{-1};
StreamId nextStreamId_{1};
// Client requests + internal requests (requestN, cancel, etc).
uint32_t requests_{0};
// Client facing requests (singleRequest(Single|No)Response)
uint32_t clientRequests_{0};
struct ServerCallbackUniquePtr {
explicit ServerCallbackUniquePtr(
std::unique_ptr<RocketStreamServerCallback> ptr) noexcept
: storage_(
reinterpret_cast<intptr_t>(ptr.release()) |
static_cast<intptr_t>(CallbackType::STREAM)) {}
explicit ServerCallbackUniquePtr(
std::unique_ptr<RocketStreamServerCallbackWithChunkTimeout>
ptr) noexcept
: storage_(
reinterpret_cast<intptr_t>(ptr.release()) |
static_cast<intptr_t>(CallbackType::STREAM_WITH_CHUNK_TIMEOUT)) {}
explicit ServerCallbackUniquePtr(
std::unique_ptr<RocketSinkServerCallback> ptr) noexcept
: storage_(
reinterpret_cast<intptr_t>(ptr.release()) |
static_cast<intptr_t>(CallbackType::SINK)) {}
ServerCallbackUniquePtr(ServerCallbackUniquePtr&& other) noexcept
: storage_(std::exchange(other.storage_, 0)) {}
template <typename F>
auto match(F&& f) const {
switch (static_cast<CallbackType>(storage_ & kTypeMask)) {
case CallbackType::STREAM:
return f(reinterpret_cast<RocketStreamServerCallback*>(
storage_ & kPointerMask));
case CallbackType::STREAM_WITH_CHUNK_TIMEOUT:
return f(
reinterpret_cast<RocketStreamServerCallbackWithChunkTimeout*>(
storage_ & kPointerMask));
case CallbackType::SINK:
return f(reinterpret_cast<RocketSinkServerCallback*>(
storage_ & kPointerMask));
default:
folly::assume_unreachable();
};
}
ServerCallbackUniquePtr& operator=(
ServerCallbackUniquePtr&& other) noexcept {
match([](auto* ptr) { delete ptr; });
storage_ = std::exchange(other.storage_, 0);
return *this;
}
~ServerCallbackUniquePtr() {
match([](auto* ptr) { delete ptr; });
}
private:
enum class CallbackType {
STREAM,
STREAM_WITH_CHUNK_TIMEOUT,
SINK,
};
static constexpr intptr_t kTypeMask = 3;
static constexpr intptr_t kPointerMask = ~kTypeMask;
intptr_t storage_;
};
struct StreamMapHasher : private folly::f14::DefaultHasher<StreamId> {
template <typename K>
size_t operator()(const K& key) const {
StreamIdResolver resolver;
return folly::f14::DefaultHasher<StreamId>::operator()(resolver(key));
}
};
struct StreamMapEquals {
template <typename A, typename B>
bool operator()(const A& a, const B& b) const {
StreamIdResolver resolver;
return resolver(a) == resolver(b);
}
};
using StreamMap = folly::F14FastSet<
ServerCallbackUniquePtr,
folly::transparent<StreamMapHasher>,
folly::transparent<StreamMapEquals>>;
StreamMap streams_;
folly::EventBase* evb_;
RequestContextQueue queue_;
class WriteLoopCallback : public folly::EventBase::LoopCallback {
public:
explicit WriteLoopCallback(RocketClient& client) : client_(client) {}
~WriteLoopCallback() override = default;
void runLoopCallback() noexcept override;
private:
RocketClient& client_;
};
WriteLoopCallback writeLoopCallback_;
void scheduleWriteLoopCallback();
FlushList* flushList_{nullptr};
FlushManager* flushManager_{nullptr};
static folly::EventBaseLocal<FlushManager>& getEventBaseLocal();
folly::AsyncTransport::UniquePtr socket_;
folly::Function<void()> onDetachable_;
folly::exception_wrapper error_;
class FirstResponseTimeout : public folly::HHWheelTimer::Callback {
public:
FirstResponseTimeout(RocketClient& client, StreamId streamId)
: client_(client), streamId_(streamId) {}
void timeoutExpired() noexcept override;
private:
RocketClient& client_;
RocketClient::DestructorGuard clientDg_{&client_};
StreamId streamId_;
};
struct StreamIdResolver {
StreamId operator()(StreamId streamId) const { return streamId; }
StreamId operator()(const ServerCallbackUniquePtr& callbackVariant) const {
return callbackVariant.match(
[](const auto* callback) { return callback->streamId(); });
}
};
folly::F14FastMap<StreamId, Payload> bufferedFragments_;
using FirstResponseTimeoutMap =
folly::F14FastMap<StreamId, std::unique_ptr<FirstResponseTimeout>>;
FirstResponseTimeoutMap firstResponseTimeouts_;
Parser<RocketClient> parser_;
class DetachableLoopCallback : public folly::EventBase::LoopCallback {
public:
explicit DetachableLoopCallback(RocketClient& client) : client_(client) {}
void runLoopCallback() noexcept override;
private:
RocketClient& client_;
};
DetachableLoopCallback detachableLoopCallback_;
class CloseLoopCallback : public folly::EventBase::LoopCallback {
public:
explicit CloseLoopCallback(RocketClient& client) : client_(client) {}
void runLoopCallback() noexcept override;
private:
RocketClient& client_;
};
CloseLoopCallback closeLoopCallback_;
class OnEventBaseDestructionCallback
: public folly::EventBase::OnDestructionCallback {
public:
explicit OnEventBaseDestructionCallback(RocketClient& client)
: client_(client) {}
void onEventBaseDestruction() noexcept override final;
private:
RocketClient& client_;
};
OnEventBaseDestructionCallback eventBaseDestructionCallback_;
folly::Function<void()> closeCallback_;
size_t interactions_{0};
std::unique_ptr<SetupFrame> setupFrame_;
protected:
RocketClient(
folly::EventBase& evb,
folly::AsyncTransport::UniquePtr socket,
std::unique_ptr<SetupFrame> setupFrame);
private:
template <class OnError>
class SendFrameContext;
template <typename Frame, typename OnError>
FOLLY_NODISCARD bool sendFrame(Frame&& frame, OnError&& onError);
template <typename InitFunc, typename OnError>
FOLLY_NODISCARD bool sendVersionDependentFrame(
InitFunc&& initFunc, StreamId streamId, OnError&& onError);
FOLLY_NODISCARD folly::Try<void> scheduleWrite(RequestContext& ctx);
StreamId makeStreamId();
template <typename ServerCallback>
void sendRequestStreamChannel(
const StreamId& streamId,
Payload&& request,
std::chrono::milliseconds firstResponseTimeout,
int32_t initialRequestN,
std::unique_ptr<ServerCallback> serverCallback);
void freeStream(StreamId streamId);
void handleFrame(std::unique_ptr<folly::IOBuf> frame);
void handleRequestResponseFrame(
RequestContext& ctx,
FrameType frameType,
std::unique_ptr<folly::IOBuf> frame);
void handleStreamChannelFrame(
StreamId streamId,
FrameType frameType,
std::unique_ptr<folly::IOBuf> frame);
template <typename CallbackType>
StreamChannelStatusResponse handlePayloadFrame(
CallbackType& serverCallback, std::unique_ptr<folly::IOBuf> frame);
template <typename CallbackType>
StreamChannelStatusResponse handleErrorFrame(
CallbackType& serverCallback, std::unique_ptr<folly::IOBuf> frame);
template <typename CallbackType>
StreamChannelStatusResponse handleRequestNFrame(
CallbackType& serverCallback, std::unique_ptr<folly::IOBuf> frame);
template <typename CallbackType>
StreamChannelStatusResponse handleCancelFrame(
CallbackType& serverCallback, std::unique_ptr<folly::IOBuf> frame);
template <typename CallbackType>
StreamChannelStatusResponse handleExtFrame(
CallbackType& serverCallback, std::unique_ptr<folly::IOBuf> frame);
void handleError(RocketException&& rex);
void writeScheduledRequestsToSocket() noexcept;
void maybeScheduleFirstResponseTimeout(
StreamId streamId, std::chrono::milliseconds timeout);
folly::Optional<Payload> bufferOrGetFullPayload(PayloadFrame&& payloadFrame);
bool isFirstResponse(StreamId streamId) const;
void acknowledgeFirstResponse(StreamId);
enum class RequestType { INTERNAL, CLIENT };
FOLLY_NODISCARD auto makeRequestCountGuard(RequestType type) {
++requests_;
if (type == RequestType::CLIENT) {
++clientRequests_;
}
return folly::makeGuard([this, type] {
if (type == RequestType::CLIENT) {
--clientRequests_;
}
if (!--requests_) {
notifyIfDetachable();
}
});
}
class ServerVersionTimeout : public folly::HHWheelTimer::Callback {
public:
explicit ServerVersionTimeout(RocketClient& client) : client_(client) {}
void timeoutExpired() noexcept override {
client_.close(transport::TTransportException(
apache::thrift::transport::TTransportException::TIMED_OUT,
"Server version not reported"));
}
private:
RocketClient& client_;
};
std::unique_ptr<ServerVersionTimeout> serverVersionTimeout_;
void onServerVersionRequired();
void setServerVersion(int32_t serverVersion);
protected:
// Close the connection and fail all the requests *inline*. This should not be
// called inline from any of the callbacks triggered by RocketClient.
void closeNow(apache::thrift::transport::TTransportException ex) noexcept;
private:
bool setError(apache::thrift::transport::TTransportException ex) noexcept;
void closeNowImpl() noexcept;
std::unique_ptr<SetupFrame> moveOutSetupFrame();
template <class T>
friend class Parser;
};
} // namespace rocket
} // namespace thrift
} // namespace apache
|
amrshennawi/fbthrift
|
thrift/compiler/test/fixtures/doctext/gen-cpp2/module_constants.h
|
<reponame>amrshennawi/fbthrift
/**
* Autogenerated by Thrift for src/module.thrift
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated @nocommit
*/
#pragma once
#include <thrift/lib/cpp2/gen/module_constants_h.h>
#include "thrift/compiler/test/fixtures/doctext/gen-cpp2/module_types.h"
namespace cpp2 {
struct module_constants {
// consider using folly::StringPiece instead of std::string whenever possible
// to referencing this statically allocated string constant, in order to
// prevent unnecessary allocations
static constexpr char const * const FOO_ = "foo";
static constexpr char const * FOO() {
return FOO_;
}
static constexpr ::std::int32_t const BAR_ = 123;
static constexpr ::std::int32_t BAR() {
return BAR_;
}
static constexpr ::std::int32_t const BIFF_ = 0;
static constexpr ::std::int32_t BIFF() {
return BIFF_;
}
static constexpr ::std::int32_t const SHOUTY_ = 11;
static constexpr ::std::int32_t SHOUTY() {
return SHOUTY_;
}
};
} // cpp2
|
amrshennawi/fbthrift
|
thrift/compiler/test/fixtures/frozen-struct/gen-cpp2/module_types.h
|
/**
* Autogenerated by Thrift for src/module.thrift
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated @nocommit
*/
#pragma once
#include <thrift/lib/cpp2/gen/module_types_h.h>
#include "thrift/compiler/test/fixtures/frozen-struct/gen-cpp2/include1_types.h"
#include "thrift/compiler/test/fixtures/frozen-struct/gen-cpp2/include2_types.h"
namespace apache {
namespace thrift {
namespace tag {
struct i32Field;
struct strField;
struct listField;
struct mapField;
struct inclAField;
struct inclBField;
struct i32Field;
struct inclEnumB;
} // namespace tag
namespace detail {
#ifndef APACHE_THRIFT_ACCESSOR_i32Field
#define APACHE_THRIFT_ACCESSOR_i32Field
APACHE_THRIFT_DEFINE_ACCESSOR(i32Field);
#endif
#ifndef APACHE_THRIFT_ACCESSOR_strField
#define APACHE_THRIFT_ACCESSOR_strField
APACHE_THRIFT_DEFINE_ACCESSOR(strField);
#endif
#ifndef APACHE_THRIFT_ACCESSOR_listField
#define APACHE_THRIFT_ACCESSOR_listField
APACHE_THRIFT_DEFINE_ACCESSOR(listField);
#endif
#ifndef APACHE_THRIFT_ACCESSOR_mapField
#define APACHE_THRIFT_ACCESSOR_mapField
APACHE_THRIFT_DEFINE_ACCESSOR(mapField);
#endif
#ifndef APACHE_THRIFT_ACCESSOR_inclAField
#define APACHE_THRIFT_ACCESSOR_inclAField
APACHE_THRIFT_DEFINE_ACCESSOR(inclAField);
#endif
#ifndef APACHE_THRIFT_ACCESSOR_inclBField
#define APACHE_THRIFT_ACCESSOR_inclBField
APACHE_THRIFT_DEFINE_ACCESSOR(inclBField);
#endif
#ifndef APACHE_THRIFT_ACCESSOR_i32Field
#define APACHE_THRIFT_ACCESSOR_i32Field
APACHE_THRIFT_DEFINE_ACCESSOR(i32Field);
#endif
#ifndef APACHE_THRIFT_ACCESSOR_inclEnumB
#define APACHE_THRIFT_ACCESSOR_inclEnumB
APACHE_THRIFT_DEFINE_ACCESSOR(inclEnumB);
#endif
} // namespace detail
} // namespace thrift
} // namespace apache
// BEGIN declare_enums
namespace some { namespace ns {
enum class EnumB {
EMPTY = 1,
};
}} // some::ns
namespace std {
template<> struct hash<::some::ns::EnumB> :
::apache::thrift::detail::enum_hash<::some::ns::EnumB> {};
} // std
namespace apache { namespace thrift {
template <> struct TEnumDataStorage<::some::ns::EnumB>;
template <> struct TEnumTraits<::some::ns::EnumB> {
using type = ::some::ns::EnumB;
static constexpr std::size_t const size = 1;
static folly::Range<type const*> const values;
static folly::Range<folly::StringPiece const*> const names;
static char const* findName(type value);
static bool findValue(char const* name, type* out);
static constexpr type min() { return type::EMPTY; }
static constexpr type max() { return type::EMPTY; }
};
}} // apache::thrift
namespace some { namespace ns {
using _EnumB_EnumMapFactory = apache::thrift::detail::TEnumMapFactory<EnumB>;
[[deprecated("use apache::thrift::util::enumNameSafe, apache::thrift::util::enumName, or apache::thrift::TEnumTraits")]]
extern const _EnumB_EnumMapFactory::ValuesToNamesMapType _EnumB_VALUES_TO_NAMES;
[[deprecated("use apache::thrift::TEnumTraits")]]
extern const _EnumB_EnumMapFactory::NamesToValuesMapType _EnumB_NAMES_TO_VALUES;
}} // some::ns
// END declare_enums
// BEGIN forward_declare
namespace some { namespace ns {
class ModuleA;
class ModuleB;
}} // some::ns
// END forward_declare
// BEGIN typedefs
// END typedefs
// BEGIN hash_and_equal_to
// END hash_and_equal_to
THRIFT_IGNORE_ISSET_USE_WARNING_BEGIN
namespace some { namespace ns {
using ::apache::thrift::detail::operator!=;
using ::apache::thrift::detail::operator>;
using ::apache::thrift::detail::operator<=;
using ::apache::thrift::detail::operator>=;
class ModuleA final {
private:
friend struct ::apache::thrift::detail::st::struct_private_access;
// used by a static_assert in the corresponding source
static constexpr bool __fbthrift_cpp2_gen_json = false;
static constexpr bool __fbthrift_cpp2_gen_nimble = false;
static constexpr bool __fbthrift_cpp2_gen_has_thrift_uri = false;
public:
using __fbthrift_cpp2_type = ModuleA;
static constexpr bool __fbthrift_cpp2_is_union =
false;
public:
ModuleA();
// FragileConstructor for use in initialization lists only.
[[deprecated("This constructor is deprecated")]]
ModuleA(apache::thrift::FragileConstructor, ::std::int32_t i32Field__arg, ::std::string strField__arg, ::std::vector<::std::int16_t> listField__arg, ::std::map<::std::string, ::std::int32_t> mapField__arg, ::some::ns::IncludedA inclAField__arg, ::some::ns::IncludedB inclBField__arg);
ModuleA(ModuleA&&) noexcept;
ModuleA(const ModuleA& src);
ModuleA& operator=(ModuleA&&) noexcept;
ModuleA& operator=(const ModuleA& src);
void __clear();
~ModuleA();
private:
::std::int32_t i32Field;
private:
::std::string strField;
private:
::std::vector<::std::int16_t> listField;
private:
::std::map<::std::string, ::std::int32_t> mapField;
private:
::some::ns::IncludedA inclAField;
private:
::some::ns::IncludedB inclBField;
private:
[[deprecated("__isset field is deprecated in Thrift struct. Use _ref() accessors instead.")]]
struct __isset {
std::array<uint8_t,6> array_isset;
template<size_t field_index>
bool __fbthrift_get(folly::index_constant<field_index>) const {
static_assert(field_index < 6, "Isset index is out of boundary");
return array_isset[field_index] == 1;
}
template<size_t field_index>
void __fbthrift_set(folly::index_constant<field_index>, bool isset_flag) {
static_assert(field_index < 6, "Isset index is out of boundary");
array_isset[field_index] = isset_flag ? 1 : 0;
}
} __isset = {};
public:
bool operator==(const ModuleA&) const;
bool operator<(const ModuleA&) const;
template <typename..., typename T = ::std::int32_t>
FOLLY_ERASE ::apache::thrift::field_ref<const T&> i32Field_ref() const& {
return {this->i32Field, __isset.array_isset.at(folly::index_constant<0>())};
}
template <typename..., typename T = ::std::int32_t>
FOLLY_ERASE ::apache::thrift::field_ref<const T&&> i32Field_ref() const&& {
return {std::move(this->i32Field), __isset.array_isset.at(folly::index_constant<0>())};
}
template <typename..., typename T = ::std::int32_t>
FOLLY_ERASE ::apache::thrift::field_ref<T&> i32Field_ref() & {
return {this->i32Field, __isset.array_isset.at(folly::index_constant<0>())};
}
template <typename..., typename T = ::std::int32_t>
FOLLY_ERASE ::apache::thrift::field_ref<T&&> i32Field_ref() && {
return {std::move(this->i32Field), __isset.array_isset.at(folly::index_constant<0>())};
}
template <typename..., typename T = ::std::string>
FOLLY_ERASE ::apache::thrift::field_ref<const T&> strField_ref() const& {
return {this->strField, __isset.array_isset.at(folly::index_constant<1>())};
}
template <typename..., typename T = ::std::string>
FOLLY_ERASE ::apache::thrift::field_ref<const T&&> strField_ref() const&& {
return {std::move(this->strField), __isset.array_isset.at(folly::index_constant<1>())};
}
template <typename..., typename T = ::std::string>
FOLLY_ERASE ::apache::thrift::field_ref<T&> strField_ref() & {
return {this->strField, __isset.array_isset.at(folly::index_constant<1>())};
}
template <typename..., typename T = ::std::string>
FOLLY_ERASE ::apache::thrift::field_ref<T&&> strField_ref() && {
return {std::move(this->strField), __isset.array_isset.at(folly::index_constant<1>())};
}
template <typename..., typename T = ::std::vector<::std::int16_t>>
FOLLY_ERASE ::apache::thrift::field_ref<const T&> listField_ref() const& {
return {this->listField, __isset.array_isset.at(folly::index_constant<2>())};
}
template <typename..., typename T = ::std::vector<::std::int16_t>>
FOLLY_ERASE ::apache::thrift::field_ref<const T&&> listField_ref() const&& {
return {std::move(this->listField), __isset.array_isset.at(folly::index_constant<2>())};
}
template <typename..., typename T = ::std::vector<::std::int16_t>>
FOLLY_ERASE ::apache::thrift::field_ref<T&> listField_ref() & {
return {this->listField, __isset.array_isset.at(folly::index_constant<2>())};
}
template <typename..., typename T = ::std::vector<::std::int16_t>>
FOLLY_ERASE ::apache::thrift::field_ref<T&&> listField_ref() && {
return {std::move(this->listField), __isset.array_isset.at(folly::index_constant<2>())};
}
template <typename..., typename T = ::std::map<::std::string, ::std::int32_t>>
FOLLY_ERASE ::apache::thrift::field_ref<const T&> mapField_ref() const& {
return {this->mapField, __isset.array_isset.at(folly::index_constant<3>())};
}
template <typename..., typename T = ::std::map<::std::string, ::std::int32_t>>
FOLLY_ERASE ::apache::thrift::field_ref<const T&&> mapField_ref() const&& {
return {std::move(this->mapField), __isset.array_isset.at(folly::index_constant<3>())};
}
template <typename..., typename T = ::std::map<::std::string, ::std::int32_t>>
FOLLY_ERASE ::apache::thrift::field_ref<T&> mapField_ref() & {
return {this->mapField, __isset.array_isset.at(folly::index_constant<3>())};
}
template <typename..., typename T = ::std::map<::std::string, ::std::int32_t>>
FOLLY_ERASE ::apache::thrift::field_ref<T&&> mapField_ref() && {
return {std::move(this->mapField), __isset.array_isset.at(folly::index_constant<3>())};
}
template <typename..., typename T = ::some::ns::IncludedA>
FOLLY_ERASE ::apache::thrift::field_ref<const T&> inclAField_ref() const& {
return {this->inclAField, __isset.array_isset.at(folly::index_constant<4>())};
}
template <typename..., typename T = ::some::ns::IncludedA>
FOLLY_ERASE ::apache::thrift::field_ref<const T&&> inclAField_ref() const&& {
return {std::move(this->inclAField), __isset.array_isset.at(folly::index_constant<4>())};
}
template <typename..., typename T = ::some::ns::IncludedA>
FOLLY_ERASE ::apache::thrift::field_ref<T&> inclAField_ref() & {
return {this->inclAField, __isset.array_isset.at(folly::index_constant<4>())};
}
template <typename..., typename T = ::some::ns::IncludedA>
FOLLY_ERASE ::apache::thrift::field_ref<T&&> inclAField_ref() && {
return {std::move(this->inclAField), __isset.array_isset.at(folly::index_constant<4>())};
}
template <typename..., typename T = ::some::ns::IncludedB>
FOLLY_ERASE ::apache::thrift::field_ref<const T&> inclBField_ref() const& {
return {this->inclBField, __isset.array_isset.at(folly::index_constant<5>())};
}
template <typename..., typename T = ::some::ns::IncludedB>
FOLLY_ERASE ::apache::thrift::field_ref<const T&&> inclBField_ref() const&& {
return {std::move(this->inclBField), __isset.array_isset.at(folly::index_constant<5>())};
}
template <typename..., typename T = ::some::ns::IncludedB>
FOLLY_ERASE ::apache::thrift::field_ref<T&> inclBField_ref() & {
return {this->inclBField, __isset.array_isset.at(folly::index_constant<5>())};
}
template <typename..., typename T = ::some::ns::IncludedB>
FOLLY_ERASE ::apache::thrift::field_ref<T&&> inclBField_ref() && {
return {std::move(this->inclBField), __isset.array_isset.at(folly::index_constant<5>())};
}
::std::int32_t get_i32Field() const {
return i32Field;
}
[[deprecated("Use `FOO.i32Field_ref() = BAR;` instead of `FOO.set_i32Field(BAR);`")]]
::std::int32_t& set_i32Field(::std::int32_t i32Field_) {
i32Field = i32Field_;
__isset.__fbthrift_set(folly::index_constant<0>(), true);
return i32Field;
}
const ::std::string& get_strField() const& {
return strField;
}
::std::string get_strField() && {
return std::move(strField);
}
template <typename T_ModuleA_strField_struct_setter = ::std::string>
[[deprecated("Use `FOO.strField_ref() = BAR;` instead of `FOO.set_strField(BAR);`")]]
::std::string& set_strField(T_ModuleA_strField_struct_setter&& strField_) {
strField = std::forward<T_ModuleA_strField_struct_setter>(strField_);
__isset.__fbthrift_set(folly::index_constant<1>(), true);
return strField;
}
const ::std::vector<::std::int16_t>& get_listField() const&;
::std::vector<::std::int16_t> get_listField() &&;
template <typename T_ModuleA_listField_struct_setter = ::std::vector<::std::int16_t>>
[[deprecated("Use `FOO.listField_ref() = BAR;` instead of `FOO.set_listField(BAR);`")]]
::std::vector<::std::int16_t>& set_listField(T_ModuleA_listField_struct_setter&& listField_) {
listField = std::forward<T_ModuleA_listField_struct_setter>(listField_);
__isset.__fbthrift_set(folly::index_constant<2>(), true);
return listField;
}
const ::std::map<::std::string, ::std::int32_t>& get_mapField() const&;
::std::map<::std::string, ::std::int32_t> get_mapField() &&;
template <typename T_ModuleA_mapField_struct_setter = ::std::map<::std::string, ::std::int32_t>>
[[deprecated("Use `FOO.mapField_ref() = BAR;` instead of `FOO.set_mapField(BAR);`")]]
::std::map<::std::string, ::std::int32_t>& set_mapField(T_ModuleA_mapField_struct_setter&& mapField_) {
mapField = std::forward<T_ModuleA_mapField_struct_setter>(mapField_);
__isset.__fbthrift_set(folly::index_constant<3>(), true);
return mapField;
}
const ::some::ns::IncludedA& get_inclAField() const&;
::some::ns::IncludedA get_inclAField() &&;
template <typename T_ModuleA_inclAField_struct_setter = ::some::ns::IncludedA>
[[deprecated("Use `FOO.inclAField_ref() = BAR;` instead of `FOO.set_inclAField(BAR);`")]]
::some::ns::IncludedA& set_inclAField(T_ModuleA_inclAField_struct_setter&& inclAField_) {
inclAField = std::forward<T_ModuleA_inclAField_struct_setter>(inclAField_);
__isset.__fbthrift_set(folly::index_constant<4>(), true);
return inclAField;
}
const ::some::ns::IncludedB& get_inclBField() const&;
::some::ns::IncludedB get_inclBField() &&;
template <typename T_ModuleA_inclBField_struct_setter = ::some::ns::IncludedB>
[[deprecated("Use `FOO.inclBField_ref() = BAR;` instead of `FOO.set_inclBField(BAR);`")]]
::some::ns::IncludedB& set_inclBField(T_ModuleA_inclBField_struct_setter&& inclBField_) {
inclBField = std::forward<T_ModuleA_inclBField_struct_setter>(inclBField_);
__isset.__fbthrift_set(folly::index_constant<5>(), true);
return inclBField;
}
template <class Protocol_>
uint32_t read(Protocol_* iprot);
template <class Protocol_>
uint32_t serializedSize(Protocol_ const* prot_) const;
template <class Protocol_>
uint32_t serializedSizeZC(Protocol_ const* prot_) const;
template <class Protocol_>
uint32_t write(Protocol_* prot_) const;
private:
template <class Protocol_>
void readNoXfer(Protocol_* iprot);
friend class ::apache::thrift::Cpp2Ops<ModuleA>;
friend void swap(ModuleA& a, ModuleA& b);
};
template <class Protocol_>
uint32_t ModuleA::read(Protocol_* iprot) {
auto _xferStart = iprot->getCursorPosition();
readNoXfer(iprot);
return iprot->getCursorPosition() - _xferStart;
}
}} // some::ns
namespace some { namespace ns {
using ::apache::thrift::detail::operator!=;
using ::apache::thrift::detail::operator>;
using ::apache::thrift::detail::operator<=;
using ::apache::thrift::detail::operator>=;
class ModuleB final {
private:
friend struct ::apache::thrift::detail::st::struct_private_access;
// used by a static_assert in the corresponding source
static constexpr bool __fbthrift_cpp2_gen_json = false;
static constexpr bool __fbthrift_cpp2_gen_nimble = false;
static constexpr bool __fbthrift_cpp2_gen_has_thrift_uri = false;
public:
using __fbthrift_cpp2_type = ModuleB;
static constexpr bool __fbthrift_cpp2_is_union =
false;
public:
ModuleB() :
i32Field(),
inclEnumB() {
}
// FragileConstructor for use in initialization lists only.
[[deprecated("This constructor is deprecated")]]
ModuleB(apache::thrift::FragileConstructor, ::std::int32_t i32Field__arg, ::some::ns::EnumB inclEnumB__arg);
ModuleB(ModuleB&&) = default;
ModuleB(const ModuleB&) = default;
ModuleB& operator=(ModuleB&&) = default;
ModuleB& operator=(const ModuleB&) = default;
void __clear();
private:
::std::int32_t i32Field;
private:
::some::ns::EnumB inclEnumB;
private:
[[deprecated("__isset field is deprecated in Thrift struct. Use _ref() accessors instead.")]]
struct __isset {
std::array<uint8_t,2> array_isset;
template<size_t field_index>
bool __fbthrift_get(folly::index_constant<field_index>) const {
static_assert(field_index < 2, "Isset index is out of boundary");
return array_isset[field_index] == 1;
}
template<size_t field_index>
void __fbthrift_set(folly::index_constant<field_index>, bool isset_flag) {
static_assert(field_index < 2, "Isset index is out of boundary");
array_isset[field_index] = isset_flag ? 1 : 0;
}
} __isset = {};
public:
bool operator==(const ModuleB&) const;
bool operator<(const ModuleB&) const;
template <typename..., typename T = ::std::int32_t>
FOLLY_ERASE ::apache::thrift::field_ref<const T&> i32Field_ref() const& {
return {this->i32Field, __isset.array_isset.at(folly::index_constant<0>())};
}
template <typename..., typename T = ::std::int32_t>
FOLLY_ERASE ::apache::thrift::field_ref<const T&&> i32Field_ref() const&& {
return {std::move(this->i32Field), __isset.array_isset.at(folly::index_constant<0>())};
}
template <typename..., typename T = ::std::int32_t>
FOLLY_ERASE ::apache::thrift::field_ref<T&> i32Field_ref() & {
return {this->i32Field, __isset.array_isset.at(folly::index_constant<0>())};
}
template <typename..., typename T = ::std::int32_t>
FOLLY_ERASE ::apache::thrift::field_ref<T&&> i32Field_ref() && {
return {std::move(this->i32Field), __isset.array_isset.at(folly::index_constant<0>())};
}
template <typename..., typename T = ::some::ns::EnumB>
FOLLY_ERASE ::apache::thrift::field_ref<const T&> inclEnumB_ref() const& {
return {this->inclEnumB, __isset.array_isset.at(folly::index_constant<1>())};
}
template <typename..., typename T = ::some::ns::EnumB>
FOLLY_ERASE ::apache::thrift::field_ref<const T&&> inclEnumB_ref() const&& {
return {std::move(this->inclEnumB), __isset.array_isset.at(folly::index_constant<1>())};
}
template <typename..., typename T = ::some::ns::EnumB>
FOLLY_ERASE ::apache::thrift::field_ref<T&> inclEnumB_ref() & {
return {this->inclEnumB, __isset.array_isset.at(folly::index_constant<1>())};
}
template <typename..., typename T = ::some::ns::EnumB>
FOLLY_ERASE ::apache::thrift::field_ref<T&&> inclEnumB_ref() && {
return {std::move(this->inclEnumB), __isset.array_isset.at(folly::index_constant<1>())};
}
::std::int32_t get_i32Field() const {
return i32Field;
}
[[deprecated("Use `FOO.i32Field_ref() = BAR;` instead of `FOO.set_i32Field(BAR);`")]]
::std::int32_t& set_i32Field(::std::int32_t i32Field_) {
i32Field = i32Field_;
__isset.__fbthrift_set(folly::index_constant<0>(), true);
return i32Field;
}
::some::ns::EnumB get_inclEnumB() const {
return inclEnumB;
}
[[deprecated("Use `FOO.inclEnumB_ref() = BAR;` instead of `FOO.set_inclEnumB(BAR);`")]]
::some::ns::EnumB& set_inclEnumB(::some::ns::EnumB inclEnumB_) {
inclEnumB = inclEnumB_;
__isset.__fbthrift_set(folly::index_constant<1>(), true);
return inclEnumB;
}
template <class Protocol_>
uint32_t read(Protocol_* iprot);
template <class Protocol_>
uint32_t serializedSize(Protocol_ const* prot_) const;
template <class Protocol_>
uint32_t serializedSizeZC(Protocol_ const* prot_) const;
template <class Protocol_>
uint32_t write(Protocol_* prot_) const;
private:
template <class Protocol_>
void readNoXfer(Protocol_* iprot);
friend class ::apache::thrift::Cpp2Ops<ModuleB>;
friend void swap(ModuleB& a, ModuleB& b);
};
template <class Protocol_>
uint32_t ModuleB::read(Protocol_* iprot) {
auto _xferStart = iprot->getCursorPosition();
readNoXfer(iprot);
return iprot->getCursorPosition() - _xferStart;
}
}} // some::ns
THRIFT_IGNORE_ISSET_USE_WARNING_END
|
amrshennawi/fbthrift
|
thrift/compiler/test/fixtures/adapter/gen-cpp2/module_for_each_field.h
|
/**
* Autogenerated by Thrift for src/module.thrift
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated @nocommit
*/
#pragma once
#include "thrift/compiler/test/fixtures/adapter/gen-cpp2/module_metadata.h"
#include <thrift/lib/cpp2/visitation/for_each.h>
namespace apache {
namespace thrift {
namespace detail {
template <>
struct ForEachField<::cpp2::Foo> {
template <typename F, typename... T>
void operator()(FOLLY_MAYBE_UNUSED F&& f, FOLLY_MAYBE_UNUSED T&&... t) const {
f(0, static_cast<T&&>(t).intField_ref()...);
f(1, static_cast<T&&>(t).optionalIntField_ref()...);
f(2, static_cast<T&&>(t).intFieldWithDefault_ref()...);
f(3, static_cast<T&&>(t).setField_ref()...);
f(4, static_cast<T&&>(t).optionalSetField_ref()...);
f(5, static_cast<T&&>(t).mapField_ref()...);
f(6, static_cast<T&&>(t).optionalMapField_ref()...);
f(7, static_cast<T&&>(t).binaryField_ref()...);
}
};
template <>
struct ForEachField<::cpp2::Baz> {
template <typename F, typename... T>
void operator()(FOLLY_MAYBE_UNUSED F&& f, FOLLY_MAYBE_UNUSED T&&... t) const {
f(0, static_cast<T&&>(t).intField_ref()...);
f(1, static_cast<T&&>(t).setField_ref()...);
f(2, static_cast<T&&>(t).mapField_ref()...);
f(3, static_cast<T&&>(t).binaryField_ref()...);
}
};
template <>
struct ForEachField<::cpp2::Bar> {
template <typename F, typename... T>
void operator()(FOLLY_MAYBE_UNUSED F&& f, FOLLY_MAYBE_UNUSED T&&... t) const {
f(0, static_cast<T&&>(t).structField_ref()...);
f(1, static_cast<T&&>(t).optionalStructField_ref()...);
f(2, static_cast<T&&>(t).structListField_ref()...);
f(3, static_cast<T&&>(t).optionalStructListField_ref()...);
f(4, static_cast<T&&>(t).unionField_ref()...);
f(5, static_cast<T&&>(t).optionalUnionField_ref()...);
}
};
} // namespace detail
} // namespace thrift
} // namespace apache
|
amrshennawi/fbthrift
|
thrift/compiler/test/fixtures/visitation/gen-cpp2/module_constants.h
|
<reponame>amrshennawi/fbthrift
/**
* Autogenerated by Thrift for src/module.thrift
*
* DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING
* @generated @nocommit
*/
#pragma once
#include <thrift/lib/cpp2/gen/module_constants_h.h>
#include "thrift/compiler/test/fixtures/visitation/gen-cpp2/module_types.h"
namespace test_cpp2 { namespace cpp_reflection {
struct module_constants {
static constexpr ::std::int32_t const constant1_ = 1357;
static constexpr ::std::int32_t constant1() {
return constant1_;
}
// consider using folly::StringPiece instead of std::string whenever possible
// to referencing this statically allocated string constant, in order to
// prevent unnecessary allocations
static constexpr char const * const constant2_ = "hello";
static constexpr char const * constant2() {
return constant2_;
}
static constexpr ::test_cpp2::cpp_reflection::enum1 const constant3_ = ::test_cpp2::cpp_reflection::enum1::field0;
static constexpr ::test_cpp2::cpp_reflection::enum1 constant3() {
return constant3_;
}
static constexpr ::std::int32_t const constant_with_special_name_ = 42;
static constexpr ::std::int32_t constant_with_special_name() {
return constant_with_special_name_;
}
};
}} // test_cpp2::cpp_reflection
|
fatdrop/cordova-kuya-download
|
src/ios/KuyaDownload.h
|
#import <Cordova/CDVPlugin.h>
#import <Cordova/CDVPluginResult.h>
#import <Foundation/Foundation.h>
#import "ASIHTTPRequestDelegate.h"
#import "ASIProgressDelegate.h"
@interface KuyaDownload : CDVPlugin
{
NSMutableDictionary* delegates;
int download_id;
}
@property int download_id;
@property (retain) NSMutableDictionary* delegates;
-(void) emitEvent:(NSString*)evname object:(NSObject*) result;
-(void) commandReply:(CDVInvokedUrlCommand*) command withDictionary:(NSDictionary*) obj;
-(void) commandReply:(CDVInvokedUrlCommand*) command withError:(NSString*) msg;
-(void) commandReply:(CDVInvokedUrlCommand*) command withBool:(Boolean) v;
-(void) init:(CDVInvokedUrlCommand*) command;
-(void) download:(CDVInvokedUrlCommand*)command;
-(void) cancel:(CDVInvokedUrlCommand*)command;
-(void) dealloc;
-(void) pluginInitialize;
@end
@interface KuyaDownloadRequestDelegate : NSObject <ASIHTTPRequestDelegate, ASIProgressDelegate>
{
int download_id;
KuyaDownload* plugin;
CDVInvokedUrlCommand* command;
ASIHTTPRequest* request;
}
@property int download_id;
@property (retain) KuyaDownload* plugin;
@property (retain) CDVInvokedUrlCommand* command;
@property (weak) ASIHTTPRequest* request;
- (void)requestFinished:(ASIHTTPRequest *)request;
- (void)requestFailed:(ASIHTTPRequest *)request;
- (void)request:(ASIHTTPRequest *)request didReceiveBytes:(long long)bytes;
@end
|
masterwebdev/cordova-plugin-camera-video
|
src/ios/VideoTemperatureAndTint.h
|
<reponame>masterwebdev/cordova-plugin-camera-video
#import <AVFoundation/AVFoundation.h>
@interface VideoTemperatureAndTint: NSObject
@property (nonatomic) NSString* mode;
@property (nonatomic) float minTemperature;
@property (nonatomic) float maxTemperature;
@property (nonatomic) float tint;
@end
|
rabbitmouse/ZQSearchController
|
ZQSearchController/Classes/ZQSearch/Controller/ZQSearchNormalViewController.h
|
<filename>ZQSearchController/Classes/ZQSearch/Controller/ZQSearchNormalViewController.h
//
// ZQSearchNormalViewController.h
// ZQSearchController
//
// Created by zzq on 2018/9/25.
// Copyright © 2018年 zzq. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "ZQSearchConst.h"
@interface ZQSearchNormalViewController : UIViewController
- (void)setHotDataSource:(NSArray *)datas;
- (void)refreshHistoryView;
@property (nonatomic, strong) NSMutableArray *historyList;
@property (nonatomic, weak) id<ZQSearchChildViewDelegate> delegate;
@end
|
rabbitmouse/ZQSearchController
|
ZQSearchController/Classes/ZQSearch/View/ZQSearchEditBaseCell.h
|
//
// ZQSearchEditBaseCell.h
// ZQSearchController
//
// Created by zzq on 2018/9/26.
// Copyright © 2018年 zzq. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "ZQSearchConst.h"
@protocol searchEditCellProtocol<NSObject>
- (void)uploadCellWithData:(id)data;
@end
@interface ZQSearchEditBaseCell : UITableViewCell<searchEditCellProtocol>
+ (NSString *)childCellIdentifierWith:(id)key;
+ (CGFloat)heightWithType:(SearchEditType)type;
@end
|
rabbitmouse/ZQSearchController
|
ZQSearchController/Classes/ZQSearch/ZQSearchConst.h
|
<filename>ZQSearchController/Classes/ZQSearch/ZQSearchConst.h
//
// ZQSearchConst.h
// ZQSearchController
//
// Created by zzq on 2018/9/26.
// Copyright © 2018年 zzq. All rights reserved.
//
#ifndef ZQSearchConst_h
#define ZQSearchConst_h
#import <UIKit/UIKit.h>
static NSString *ZQSearchHistorys = @"ZQSearchHistorys";
typedef NS_ENUM(NSUInteger, SearchEditType) {
SearchEditTypeFuzzy = 1,
SearchEditTypeConfirm = 2,
};
@protocol ZQSearchData<NSObject>
@required
@property (nonatomic, copy) NSString *title;
@optional
@property (nonatomic, assign) SearchEditType editType;
@property (nonatomic, strong) UIImage *image;//优先加载image图片
@property (nonatomic, copy) NSString *iconUrl;
@property (nonatomic, copy) NSString *desc;
@end
@protocol ZQSearchChildViewDelegate<NSObject>
- (void)searchChildViewDidScroll;
- (void)searchChildViewDidSelectItem:(id)value;
- (void)searchChildViewDidSelectRow:(id)value;
@end
#define ZQ_SEARCH_HISTORY_CACHE_PATH [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"ZQSearchhistories.plist"] // the path of search record cached
#define ZQSearchWidth [UIScreen mainScreen].bounds.size.width
#define ZQSearchHeight [UIScreen mainScreen].bounds.size.height
//判断iPhoneX所有系列
#define Match_PhoneXAll ({BOOL isPhoneX = NO;\
if (@available(iOS 11.0, *)) {\
isPhoneX = [[UIApplication sharedApplication] delegate].window.safeAreaInsets.bottom > 0.0;\
}\
(isPhoneX);\
})
#define k_Height_NavContentBar 44.0f
#define k_Height_StatusBar (Match_PhoneXAll? 44.0 : 20.0)
#define k_Height_NavBar (Match_PhoneXAll ? 88.0 : 64.0)
#define k_Height_TabBar (Match_PhoneXAll ? 83.0 : 49.0)
#ifndef weakify
#if DEBUG
#if __has_feature(objc_arc)
#define weakify(object) autoreleasepool{} __weak __typeof__(object) weak##_##object = object;
#else
#define weakify(object) autoreleasepool{} __block __typeof__(object) block##_##object = object;
#endif
#else
#if __has_feature(objc_arc)
#define weakify(object) try{} @finally{} {} __weak __typeof__(object) weak##_##object = object;
#else
#define weakify(object) try{} @finally{} {} __block __typeof__(object) block##_##object = object;
#endif
#endif
#endif
#ifndef strongify
#if DEBUG
#if __has_feature(objc_arc)
#define strongify(object) autoreleasepool{} __typeof__(object) object = weak##_##object;
#else
#define strongify(object) autoreleasepool{} __typeof__(object) object = block##_##object;
#endif
#else
#if __has_feature(objc_arc)
#define strongify(object) try{} @finally{} __typeof__(object) object = weak##_##object;
#else
#define strongify(object) try{} @finally{} __typeof__(object) object = block##_##object;
#endif
#endif
#endif
#endif /* ZQSearchConst_h */
|
rabbitmouse/ZQSearchController
|
ZQSearchController/Classes/ZQSearch/View/ZQSearchNormalCell.h
|
//
// ZQSearchNormalCell.h
// ZQSearchController
//
// Created by zzq on 2018/9/25.
// Copyright © 2018年 zzq. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ZQSearchNormalCell : UICollectionViewCell
@property (nonatomic, assign) BOOL heightLight;
@property (nonatomic, copy) NSString *title;
@end
|
rabbitmouse/ZQSearchController
|
ZQSearchController/Classes/ZQSearch/Controller/ZQSearchViewController.h
|
//
// ZQSearchViewController.h
// ZQSearchController
//
// Created by zzq on 2018/9/20.
// Copyright © 2018年 zzq. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "ZQSearchConst.h"
typedef NS_ENUM(NSUInteger, ZQSearchBarStyle) {
ZQSearchBarStyleNone,
ZQSearchBarStyleCannel,
ZQSearchBarStyleBack,
};
typedef NS_ENUM(NSUInteger, ZQSearchState) {
ZQSearchStateNormal,
ZQSearchStateEditing,
ZQSearchStateResult,
};
@protocol ZQSearchViewDelegate<NSObject>
@required
- (void)searchFuzzyResultWithKeyString:(NSString *)keyString Data:(id<ZQSearchData>)data resultController:(UIViewController *)resultController;
@optional
- (void)searchEditViewRefreshWithKeyString:(NSString *)keyString DataBlock:(void(^)(id data))block;
- (void)searchConfirmResultWithKeyString:(NSString *)keyString Data:(id<ZQSearchData>)data resultController:(UIViewController *)resultController;
@end
@interface ZQSearchViewController : UIViewController
- (instancetype)initSearchViewWithHotDatas:(NSArray *)hotList resultController:(UIViewController *)resultController;
@property (nonatomic, weak) id<ZQSearchViewDelegate> delegate;
@property (nonatomic, assign) BOOL closeFuzzyTable;//default is NO, 如果设置为YES,将不显示模糊匹配列表。可以不实现searchEditViewRefreshWithDataBlock和searchConfirmResultWithKeyString这两个代理。
@property (nonatomic, copy) NSString *placeholder;
@end
|
rabbitmouse/ZQSearchController
|
Example/Demo/searchEditModel.h
|
//
// searchEditModel.h
// ZQSearchController
//
// Created by zzq on 2018/9/26.
// Copyright © 2018年 zzq. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "ZQSearchConst.h"
@interface searchEditModel : NSObject<ZQSearchData>
@property (nonatomic, assign) SearchEditType editType;
@property (nonatomic, copy) NSString *iconUrl;
@property (nonatomic, copy) NSString *title;
@property (nonatomic, copy) NSString *desc;
@property (nonatomic, strong) UIImage *image;
@end
|
rabbitmouse/ZQSearchController
|
ZQSearchController/Classes/ZQSearch/View/ZQSearchEditNormalCell.h
|
//
// ZQSearchEditNormalCell.h
// ZQSearchController
//
// Created by zzq on 2018/9/26.
// Copyright © 2018年 zzq. All rights reserved.
//
#import "ZQSearchEditBaseCell.h"
#import "ZQSearchConst.h"
@interface ZQSearchEditNormalCell : ZQSearchEditBaseCell
@end
|
rabbitmouse/ZQSearchController
|
Example/Demo/ResultFuzzyViewController.h
|
//
// ResultFuzzyViewController.h
// ZQSearchController
//
// Created by zzq on 2018/9/28.
// Copyright © 2018年 zzq. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ResultFuzzyViewController : UIViewController
@end
|
rabbitmouse/ZQSearchController
|
ZQSearchController/Classes/ZQSearch/Controller/ZQSearchEditViewController.h
|
<gh_stars>100-1000
//
// ZQSearchEditViewController.h
// ZQSearchController
//
// Created by zzq on 2018/9/26.
// Copyright © 2018年 zzq. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "ZQSearchConst.h"
@interface ZQSearchEditViewController : UIViewController
@property (nonatomic, strong) NSArray<ZQSearchData> *datas;
- (void)refreshSearchEditViewWith:(NSArray<ZQSearchData> *)data;
@property (nonatomic, weak) id<ZQSearchChildViewDelegate> delegate;
@end
|
rabbitmouse/ZQSearchController
|
ZQSearchController/Classes/ZQSearch/View/ZQSearchCollectionReusableView.h
|
<reponame>rabbitmouse/ZQSearchController
//
// ZQSearchCollectionReusableView.h
// ZQSearchController
//
// Created by zzq on 2018/9/25.
// Copyright © 2018年 zzq. All rights reserved.
//
#import <UIKit/UIKit.h>
typedef void(^emptyBlock)(void);
@interface ZQSearchCollectionReusableView : UICollectionReusableView
@property (nonatomic, strong) NSString *title;
- (void)showDeleteHistoryBtn:(BOOL)show CallBack:(void(^)(void))callBack;
@end
|
rabbitmouse/ZQSearchController
|
ZQSearchController/Classes/ZQSearch/Layout/ZQSearchNormalLayout.h
|
//
// ZQSearchNormalLayout.h
// ZQSearchController
//
// Created by zzq on 2018/9/25.
// Copyright © 2018年 zzq. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ZQSearchNormalLayout : UICollectionViewFlowLayout
@property (nonatomic) CGFloat maximumInteritemSpacing;
@end
|
rabbitmouse/ZQSearchController
|
ZQSearchController/Classes/ZQSearch/Category/UIColor+ZQSearch.h
|
<filename>ZQSearchController/Classes/ZQSearch/Category/UIColor+ZQSearch.h
//
// UIColor+ZQSearch.h
// ZQSearchController
//
// Created by zzq on 2018/9/25.
// Copyright © 2018年 zzq. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIColor (ZQSearch)
+ (UIColor *)colorWithHexString:(NSString *)color alpha:(CGFloat)alpha;
@end
|
Krozark/lab
|
ideas/shadows/Constructs.h
|
<reponame>Krozark/lab
#ifndef CONSTRUCTS_H
#define CONSTRUCTS_H
#include <iostream>
class Point2i
{
public:
int x, y;
Point2i(const int &X, const int &Y);
Point2i();
bool operator==(Point2i &other) const;
};
class Point2f
{
public:
float x, y;
Point2f(const float &X, const float &Y);
Point2f();
bool operator==(Point2f &other) const;
};
struct Point3f
{
public:
float x, y, z;
Point3f(const float &X, const float &Y, const float &Z);
Point3f();
bool operator==(Point3f &other) const;
};
class Position2D
{
public:
float x, y;
float angle;
Position2D(const float &X, const float &Y, const float &Angle);
Position2D();
bool operator==(Position2D &other) const;
};
struct Position3D
{
float x, y, z;
float angleX, angleY, angleZ;
Position3D(const float &X, const float &Y, const float &Z,
const float &AngleX, const float &AngleY, const float &AngleZ);
Position3D();
bool operator==(Position3D &other) const;
};
class Vec2f
{
public:
float x, y;
Vec2f();
Vec2f(const float &X, const float &Y);
Vec2f operator*(const float &scale) const;
Vec2f operator/(const float &scale) const;
Vec2f operator+(const Vec2f &other) const;
Vec2f operator-(const Vec2f &other) const;
Vec2f operator-() const;
const Vec2f &operator*=(const float &scale);
const Vec2f &operator/=(const float &scale);
const Vec2f &operator+=(const Vec2f &other);
const Vec2f &operator-=(const Vec2f &other);
float magnitude() const;
float magnitudeSquared() const;
Vec2f normalize() const;
float dot(const Vec2f &other) const;
float cross(const Vec2f &other) const;
};
Vec2f operator*(const float &scale, const Vec2f &v);
std::ostream &operator<<(std::ostream &output, const Vec2f &v);
class Vec3f
{
private:
float v[3];
public:
Vec3f();
Vec3f(float x, float y, float z);
float &operator[](int index);
float operator[](int index) const;
Vec3f operator*(float scale) const;
Vec3f operator/(float scale) const;
Vec3f operator+(const Vec3f &other) const;
Vec3f operator-(const Vec3f &other) const;
Vec3f operator-() const;
const Vec3f &operator*=(float scale);
const Vec3f &operator/=(float scale);
const Vec3f &operator+=(const Vec3f &other);
const Vec3f &operator-=(const Vec3f &other);
float magnitude() const;
float magnitudeSquared() const;
Vec3f normalize() const;
float dot(const Vec3f &other) const;
Vec3f cross(const Vec3f &other) const;
};
void scale_to_01(Vec3f &v);
Vec3f operator*(float scale, const Vec3f &v);
std::ostream &operator<<(std::ostream &output, const Vec3f &v);
#endif
|
Krozark/lab
|
ideas/shadows/AllInclude.h
|
#ifndef ALL_INCLUDE
#define ALL_INCLUDE
#include "SFMLOpenGL.h"
#include "Utilities.h"
#include "Light.h"
#include "LightSystem.h"
#include "ConvexHull.h"
#endif
|
Krozark/lab
|
ideas/shadows/Utilities.h
|
<reponame>Krozark/lab<gh_stars>0
#ifndef UTILITIES_H
#define UTILITIES_H
#include <fstream>
#include <sstream>
const float PI = 3.14159265f;
template <class T> std::string toString(const T& t);
// NOTE: You should probably do some checks to ensure that
// this string contains only numbers. If the string is not
// a valid integer, zero will be returned.
int GetIntVal(std::string strConvert);
double GetDoubleVal(std::string strConvert);
float toRads(float degrees);
float toDegrees(float rads);
void rangeCheckRads(float &rads);
void rangeCheckDegrees(float °rees);
// Useful for having a counter loop around on itself again
template<typename T>
T Wrap(const T& val, const T& size)
{
if(val < 0)
return size + val;
if(val >= size)
return val - size;
return val;
}
#endif
|
Krozark/lab
|
ideas/shadows/ConvexHull.h
|
<filename>ideas/shadows/ConvexHull.h
#ifndef CONVEX_HULL_H
#define CONVEX_HULL_H
#include "SFMLOpenGL.h"
#include "Utilities.h"
#include "Constructs.h"
#include <vector>
struct ConvexHullVertex
{
Point2f position;
// Other information can be added later
};
class ConvexHull
{
public:
std::vector<ConvexHullVertex> vertices;
std::vector<Vec2f> normals;
Point2f worldCenter;
float depth;
float shadowDepthOffset;
ConvexHull();
~ConvexHull();
bool LoadShape(const char* fileName);
Point2f getWorldVertex(unsigned int index);
void CalculateNormals();
void RenderHull();
};
#endif
|
Krozark/lab
|
ideas/shadows/SFMLOpenGL.h
|
#ifndef SDLOPENGL
#define SDLOPENGL
#include <SFML/OpenGL.hpp>
#include <GL/glu.h>
#include <SFML/Graphics.hpp>
#include "Constructs.h"
extern unsigned int window_width, window_height, window_bpp;
struct TextureDesc
{
int width, height;
GLuint hTexture;
~TextureDesc()
{
glDeleteTextures(1, &hTexture);
}
};
// Change viewport
void ViewOrtho(float zNear, float zFar);
void ViewPerspective(float zNear, float zFar);
void ResizeGLScene(GLsizei width, GLsizei height);
bool LoadIMG(const char* filename, TextureDesc &textureInfo);
// Init/shut down
bool InitSDLOpenGL();
// Simple 2D quad drawing function
void Draw2DQuad(const TextureDesc &textureInfo, float tiles);
#endif
|
Krozark/lab
|
ideas/python-android/stt/data/vosk/vosk_api.h
|
# 1 "data/vosk/vosk_api.h"
# 1 "<built-in>"
# 1 "<command-line>"
# 31 "<command-line>"
# 1 "/usr/include/stdc-predef.h" 1 3 4
# 32 "<command-line>" 2
# 1 "data/vosk/vosk_api.h"
# 27 "data/vosk/vosk_api.h"
typedef struct VoskModel VoskModel;
typedef struct VoskSpkModel VoskSpkModel;
typedef struct VoskRecognizer VoskRecognizer;
VoskModel *vosk_model_new(const char *model_path);
void vosk_model_free(VoskModel *model);
int vosk_model_find_word(VoskModel *model, const char *word);
VoskSpkModel *vosk_spk_model_new(const char *model_path);
void vosk_spk_model_free(VoskSpkModel *model);
VoskRecognizer *vosk_recognizer_new(VoskModel *model, float sample_rate);
# 96 "data/vosk/vosk_api.h"
VoskRecognizer *vosk_recognizer_new_spk(VoskModel *model, float sample_rate, VoskSpkModel *spk_model);
# 114 "data/vosk/vosk_api.h"
VoskRecognizer *vosk_recognizer_new_grm(VoskModel *model, float sample_rate, const char *grammar);
# 123 "data/vosk/vosk_api.h"
void vosk_recognizer_set_spk_model(VoskRecognizer *recognizer, VoskSpkModel *spk_model);
# 139 "data/vosk/vosk_api.h"
void vosk_recognizer_set_max_alternatives(VoskRecognizer *recognizer, int max_alternatives);
# 175 "data/vosk/vosk_api.h"
void vosk_recognizer_set_words(VoskRecognizer *recognizer, int words);
# 185 "data/vosk/vosk_api.h"
int vosk_recognizer_accept_waveform(VoskRecognizer *recognizer, const char *data, int length);
int vosk_recognizer_accept_waveform_s(VoskRecognizer *recognizer, const short *data, int length);
int vosk_recognizer_accept_waveform_f(VoskRecognizer *recognizer, const float *data, int length);
# 214 "data/vosk/vosk_api.h"
const char *vosk_recognizer_result(VoskRecognizer *recognizer);
# 228 "data/vosk/vosk_api.h"
const char *vosk_recognizer_partial_result(VoskRecognizer *recognizer);
# 237 "data/vosk/vosk_api.h"
const char *vosk_recognizer_final_result(VoskRecognizer *recognizer);
void vosk_recognizer_reset(VoskRecognizer *recognizer);
void vosk_recognizer_free(VoskRecognizer *recognizer);
# 258 "data/vosk/vosk_api.h"
void vosk_set_log_level(int log_level);
void vosk_gpu_init();
void vosk_gpu_thread_init();
|
Krozark/lab
|
ideas/shadows/Light.h
|
#ifndef LIGHT_H
#define LIGHT_H
#include "SFMLOpenGL.h"
#include "Utilities.h"
#include "Constructs.h"
const float ambientLight = 0.3f;
class Light
{
public:
float intensity;
float radius;
float depth;
Vec2f center;
Light();
~Light();
void renderLightAlpha();
};
#endif
|
Krozark/lab
|
ideas/shadows/LightSystem.h
|
#ifndef LIGHTSYSTEM_H
#define LIGHTSYSTEM_H
#include "Light.h"
#include "ConvexHull.h"
#include <vector>
void MaskShadow(Light* light, ConvexHull* convexHull, float depth);
class LightSystem
{
private:
std::vector<Light*> lights;
std::vector<ConvexHull*> convexHulls;
bool enabled;
public:
LightSystem();
~LightSystem();
void addLight(Light* newLight);
void addConvexHull(ConvexHull* newConvexHull);
void clearLights();
void clearConvexHulls();
void RenderLights();
};
#endif
|
JetLennit/Othello
|
include/game.h
|
<filename>include/game.h<gh_stars>1-10
#ifndef GAME_H
#define GAME_H
#include "SDL.h"
#include "board.h"
const int X_OFFSET = 0;
const int Y_OFFSET = 20;
const int SCALE = 80;
class Game {
public:
bool checkInput();
void update();
void draw();
bool checkInputSDL(int x, int y);
void drawSDL(SDL_Renderer* renderer);
void finish();
bool isOver() const;
void disableShowMoves();
private:
Board board;
int turn = 2;
bool over = false;
bool showMoves = true;
};
#endif
|
JetLennit/Othello
|
include/board.h
|
<reponame>JetLennit/Othello
#ifndef BOARD_H
#define BOARD_H
#include <vector>
const int DIRECTIONS[8][2] = {
{-1, -1},
{ 0, -1},
{ 1, -1},
{-1, 0},
{ 1, 0},
{-1, 1},
{ 0, 1},
{ 1, 1}
};
struct legal_play {
int x = 0;
int y = 0;
bool directions[8] = {};
};
class Board {
public:
Board();
void refreshMoves();
void addMove(int x, int y, int direction, int side);
legal_play getMove(int x, int y, int side);
int checkMove(int x, int y);
bool hasMove(int side);
bool place(int x, int y, int side);
int getTile(int x, int y);
void setTile(int x, int y, int side);
void moveDirection(int &x, int &y, int direction);
bool outOfBounds(int x, int y);
private:
int tiles[8][8] = {};
std::vector<legal_play> legal_moves[2] = {};
};
#endif
|
ofbear/source_guard
|
source_guard/source_guard.c
|
<reponame>ofbear/source_guard
/*
+----------------------------------------------------------------------+
| PHP Version 7 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2018 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: |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifdef HAVE_CONFIG_H
#include "config.h"
#endif
#include "php.h"
#include "php_ini.h"
#include "ext/standard/info.h"
#include "php_source_guard.h"
#include <openssl/evp.h>
#include <openssl/aes.h>
/* If you declare any globals in php_source_guard.h uncomment this:
ZEND_DECLARE_MODULE_GLOBALS(source_guard)
*/
SourceCryptBuffer pl_buffer;
/* True global resources - no need for thread safety here */
static int le_source_guard;
// init
void source_init()
{
if (pl_buffer.fp_r != 0) {
fclose(pl_buffer.fp_r);
}
if (pl_buffer.data_raw != 0) {
efree(pl_buffer.data_raw);
}
if (pl_buffer.data_enc != 0) {
efree(pl_buffer.data_enc);
}
memset(&pl_buffer, 0x00, sizeof(SourceCryptBuffer));
}
// decrypt wrapper
int source_decrypt_openssl(const unsigned char* data_enc, const int len_enc, char* data_raw, int *len_raw)
{
EVP_CIPHER_CTX *ctx;
int len_raw_0 = 0;
int len_raw_1 = 0;
// new
if (!(ctx = EVP_CIPHER_CTX_new())) {
EVP_CIPHER_CTX_free(ctx);
return EVP_FAIL_EVP_NEW;
}
// init
// if you want to change encrypt method, you change "EVP_aes_256_cbc"
// https://www.openssl.org/docs/man1.1.0/crypto/EVP_aes_256_cbc.html
if (!EVP_DecryptInit_ex(ctx, EVP_aes_256_cbc(), NULL, PL_DEFAULT_CRYPTKEY, PL_INITIAL_VECTOR)) {
EVP_CIPHER_CTX_free(ctx);
return ERR_FAIL_EVP_INIT;
}
// Execute
if (!EVP_DecryptUpdate(ctx, (unsigned char *)data_raw, &len_raw_0, data_enc, len_enc)) {
EVP_CIPHER_CTX_free(ctx);
return ERR_FAIL_EVP_UPDATE;
}
// padding
if (!EVP_DecryptFinal_ex(ctx, (unsigned char *)(data_raw + len_raw_0), &len_raw_1)) {
EVP_CIPHER_CTX_free(ctx);
return ERR_FAIL_EVP_FINAL;
}
*len_raw = len_raw_0 + len_raw_1 - 1;
memset(data_raw + *len_raw, 0x00, len_enc - *len_raw);
EVP_CIPHER_CTX_free(ctx);
return ERR_NOTHING;
}
int source_decrypt()
{
struct stat stat_buf;
int ret = ERR_NOTHING;
// get file data
fstat(fileno(pl_buffer.fp_r), &stat_buf);
pl_buffer.len_enc = stat_buf.st_size;
pl_buffer.data_enc = ecalloc(1, sizeof(char) * pl_buffer.len_enc);
fread(pl_buffer.data_enc, pl_buffer.len_enc, 1, pl_buffer.fp_r);
// check php code
if (strstr((const char *)pl_buffer.data_enc, "<?php") != NULL) {
return ERR_NOT_ENCRYPT;
}
// prepare memory for decrypt data
pl_buffer.len_raw = pl_buffer.len_enc;
pl_buffer.data_raw = ecalloc(1, sizeof(char) * pl_buffer.len_raw);
// decrypt
if ((ret = source_decrypt_openssl(pl_buffer.data_enc, pl_buffer.len_enc, pl_buffer.data_raw, &pl_buffer.len_raw)) != ERR_NOTHING) {
return ret;
}
// tag check
if (strstr((const char *)pl_buffer.data_raw, PL_TOOL_NAME) == NULL) {
return ERR_NOT_SOURCE_GUARD;
}
// make file by raw data
pl_buffer.fp_w = tmpfile();
fwrite(pl_buffer.data_raw, pl_buffer.len_raw, 1, pl_buffer.fp_w);
// shift to top ptr
rewind(pl_buffer.fp_w);
return ERR_NOTHING;
}
// origin compiler
ZEND_API zend_op_array *(*org_compile_file)(zend_file_handle *file_handle, int type TSRMLS_DC);
// my compiler
ZEND_API zend_op_array *source_guard_compile_file(zend_file_handle *file_handle, int type TSRMLS_DC)
{
// init
source_init();
// check open
pl_buffer.fp_r = fopen(file_handle->filename, "r");
if (!pl_buffer.fp_r) {
// init
source_init();
return org_compile_file(file_handle, type);
}
// decrypt execute
if (source_decrypt() != ERR_NOTHING) {
// init
source_init();
return org_compile_file(file_handle, type);
}
// close file_handle
switch (file_handle->type)
{
case ZEND_HANDLE_FILENAME:
case ZEND_HANDLE_STREAM:
case ZEND_HANDLE_MAPPED:
default:
// do nothing
break;
case ZEND_HANDLE_FD:
close(file_handle->handle.fd);
break;
case ZEND_HANDLE_FP:
fclose(file_handle->handle.fp);
break;
}
// override setting
file_handle->type = ZEND_HANDLE_FP;
file_handle->opened_path = NULL;
file_handle->handle.fp = pl_buffer.fp_w;
// init
source_init();
return org_compile_file(file_handle, type);
}
/* {{{ PHP_INI
*/
/* Remove comments and fill if you need to have entries in php.ini
PHP_INI_BEGIN()
STD_PHP_INI_ENTRY("source_guard.global_value", "42", PHP_INI_ALL, OnUpdateLong, global_value, zend_source_guard_globals, source_guard_globals)
STD_PHP_INI_ENTRY("source_guard.global_string", "foobar", PHP_INI_ALL, OnUpdateString, global_string, zend_source_guard_globals, source_guard_globals)
PHP_INI_END()
*/
/* }}} */
/* Remove the following function when you have successfully modified config.m4
so that your module can be compiled into PHP, it exists only for testing
purposes. */
/* Every user-visible function in PHP should document itself in the source */
/* {{{ proto string confirm_source_guard_compiled(string arg)
Return a string to confirm that the module is compiled in */
PHP_FUNCTION(confirm_source_guard_compiled)
{
char *arg = NULL;
size_t arg_len, len;
zend_string *strg;
if (zend_parse_parameters(ZEND_NUM_ARGS(), "s", &arg, &arg_len) == FAILURE) {
return;
}
strg = strpprintf(0, "Congratulations! You have successfully modified ext/%.78s/config.m4. Module %.78s is now compiled into PHP.", "source_guard", arg);
RETURN_STR(strg);
}
/* }}} */
/* The previous line is meant for vim and emacs, so it can correctly fold and
unfold functions in source code. See the corresponding marks just before
function definition, where the functions purpose is also documented. Please
follow this convention for the convenience of others editing your code.
*/
/* {{{ php_source_guard_init_globals
*/
/* Uncomment this function if you have INI entries
static void php_source_guard_init_globals(zend_source_guard_globals *source_guard_globals)
{
source_guard_globals->global_value = 0;
source_guard_globals->global_string = NULL;
}
*/
/* }}} */
/* {{{ PHP_MINIT_FUNCTION
*/
PHP_MINIT_FUNCTION(source_guard)
{
CG(compiler_options) |= ZEND_COMPILE_EXTENDED_INFO;
org_compile_file = zend_compile_file;
zend_compile_file = source_guard_compile_file;
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MSHUTDOWN_FUNCTION
*/
PHP_MSHUTDOWN_FUNCTION(source_guard)
{
CG(compiler_options) |= ZEND_COMPILE_EXTENDED_INFO;
zend_compile_file = org_compile_file;
return SUCCESS;
}
/* }}} */
/* Remove if there's nothing to do at request start */
/* {{{ PHP_RINIT_FUNCTION
*/
PHP_RINIT_FUNCTION(source_guard)
{
#if defined(COMPILE_DL_SOURCE_GUARD) && defined(ZTS)
ZEND_TSRMLS_CACHE_UPDATE();
#endif
return SUCCESS;
}
/* }}} */
/* Remove if there's nothing to do at request end */
/* {{{ PHP_RSHUTDOWN_FUNCTION
*/
PHP_RSHUTDOWN_FUNCTION(source_guard)
{
return SUCCESS;
}
/* }}} */
/* {{{ PHP_MINFO_FUNCTION
*/
PHP_MINFO_FUNCTION(source_guard)
{
php_info_print_table_start();
php_info_print_table_header(2, "source_guard support", "enabled");
php_info_print_table_end();
/* Remove comments if you have entries in php.ini
DISPLAY_INI_ENTRIES();
*/
}
/* }}} */
// source_guard
ZEND_BEGIN_ARG_INFO_EX(arginfo_source_guard, 0, 0, 1) // 1 定義名(PHP_FE() マクロの第一引数として指定する文字列)
// 2 未使用
// 3 返却フラグ(1.参照を返す 0.受け取るだけ)
// 4 必須の引数の数
ZEND_ARG_INFO(0, txt) // 1 1.参照渡し 0.値渡し
// 2 仮引数名
ZEND_END_ARG_INFO() // 終了
/* {{{ source_guard_functions[]
*
* Every user visible function must have an entry in source_guard_functions[].
*/
const zend_function_entry source_guard_functions[] = {
PHP_FE(confirm_source_guard_compiled, NULL) /* For testing, remove later. */
PHP_FE_END /* Must be the last line in source_guard_functions[] */
};
/* }}} */
/* {{{ source_guard_module_entry
*/
zend_module_entry source_guard_module_entry = {
STANDARD_MODULE_HEADER,
"source_guard",
source_guard_functions,
PHP_MINIT(source_guard),
PHP_MSHUTDOWN(source_guard),
PHP_RINIT(source_guard), /* Replace with NULL if there's nothing to do at request start */
PHP_RSHUTDOWN(source_guard), /* Replace with NULL if there's nothing to do at request end */
PHP_MINFO(source_guard),
PHP_SOURCE_GUARD_VERSION,
STANDARD_MODULE_PROPERTIES
};
/* }}} */
#ifdef COMPILE_DL_SOURCE_GUARD
#ifdef ZTS
ZEND_TSRMLS_CACHE_DEFINE()
#endif
ZEND_GET_MODULE(source_guard)
#endif
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
|
ofbear/source_guard
|
source_guard/php_source_guard.h
|
/*
+----------------------------------------------------------------------+
| PHP Version 7 |
+----------------------------------------------------------------------+
| Copyright (c) 1997-2018 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: |
+----------------------------------------------------------------------+
*/
/* $Id$ */
#ifndef PHP_SOURCE_GUARD_H
#define PHP_SOURCE_GUARD_H
extern zend_module_entry source_guard_module_entry;
#define phpext_source_guard_ptr &source_guard_module_entry
#define PHP_SOURCE_GUARD_VERSION "0.1.0" /* Replace with version number for your extension */
#ifdef PHP_WIN32
# define PHP_SOURCE_GUARD_API __declspec(dllexport)
#elif defined(__GNUC__) && __GNUC__ >= 4
# define PHP_SOURCE_GUARD_API __attribute__ ((visibility("default")))
#else
# define PHP_SOURCE_GUARD_API
#endif
#ifdef ZTS
#include "TSRM.h"
#endif
/*
Declare any global variables you may need between the BEGIN
and END macros here:
ZEND_BEGIN_MODULE_GLOBALS(source_guard)
zend_long global_value;
char *global_string;
ZEND_END_MODULE_GLOBALS(source_guard)
*/
/* Always refer to the globals in your function as SOURCE_GUARD_G(variable).
You are encouraged to rename these macros something shorter, see
examples in any other php module directory.
*/
#define SOURCE_GUARD_G(v) ZEND_MODULE_GLOBALS_ACCESSOR(source_guard, v)
#if defined(ZTS) && defined(COMPILE_DL_SOURCE_GUARD)
ZEND_TSRMLS_CACHE_EXTERN()
#endif
#define PATH_SIZE (128)
static const int PL_ENCRYPT_BLOCK_SIZE = 16;
static const unsigned char PL_INITIAL_VECTOR[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZ012345"; // change ok
static const unsigned char PL_DEFAULT_CRYPTKEY[] = "<KEY>"; // change ok
static const unsigned char PL_TOOL_NAME[] = "<?php /* SOURCE_GUARD */ ?>";
enum {
ERR_NOTHING = 0,
ERR_NOT_ENCRYPT,
ERR_NOT_SOURCE_GUARD,
EVP_FAIL_EVP_NEW,
ERR_FAIL_EVP_INIT,
ERR_FAIL_EVP_UPDATE,
ERR_FAIL_EVP_FINAL,
};
typedef struct {
char *mode;
char *filename;
FILE *fp_r;
FILE *fp_w;
char *data_raw;
char *data_enc;
int len_raw;
int len_enc;
} SourceCryptBuffer;
void source_init();
int source_decrypt_openssl(const unsigned char* data_enc, const int len_enc, char* data_raw, int *len_raw);
int source_decrypt();
#endif /* PHP_SOURCE_GUARD_H */
/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
* vim600: noet sw=4 ts=4 fdm=marker
* vim<600: noet sw=4 ts=4
*/
|
weebcyberpunk/tictactoe
|
bot_l_patterns.c
|
#include<stdio.h>
int bot_l_patterns(char game[9]) {
/*
* A quick explain: L pattern is how I call
* something like this:
*
* _/O/_
* _/_/O
* _/_/_
*
* The problem is that if O puts on 3, it'll
* have two ways to win. Bot should avoid that
*/
// again, if 10 no l pattern
int house = 10;
// with 1
if (game[1] == 'O') {
if (game[5] == 'O') house = 2;
else if (game[3] == 'O') house = 0;
}
// with 7
if (game[7] == 'O') {
if (game[3] == 'O') house = 6;
else if (game[5] == 'O') house = 8;
}
// wow this was short
// now we return the house
return(house);
}
|
weebcyberpunk/tictactoe
|
tictacbot.c
|
<filename>tictacbot.c<gh_stars>0
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int print_game(char game[9]);
char finish(char game[9]);
int bot(char game[9], int bot_game[9], int round);
int tictacbot() {
char game[9] = { 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b', 'b' };
int bot_game[9];
char player = 'O';
int house;
int round = 0;
char str_house[5];
printf("Player X Computer tic-tac-toe.\n");
print_game(game);
for (;;) {
if (player == 'O') {
for (;;) {
// get house
printf("Enter the number of the house you want to dial: ");
scanf("%s", &str_house);
house = atoi(str_house);
// if "exit"
if (strcmp(str_house, "exit") == 0) {
return(0);
// test valid
} else if ((house > 9) || (house < 1)) {
printf("Invalid house.\n");
continue;
// test dial
} else if (game[house - 1] != 'b') {
printf("This house was already dialed.\n");
continue;
// if valid, dial house
} else {
game[house - 1] = 'O';
player = 'X';
break;
}
}
} else {
house = bot(game, bot_game, round);
game[house] = 'X';
bot_game[round] = house;
player = 'O';
}
round++;
// print the game and test for finish
print_game(game);
char end = finish(game);
if (end == 't') printf("Tie!\n");
else if (end == 'X') printf("Computer's won!\n");
else if (end == 'O') printf("Player's won!\n");
else continue;
if (end != 'b') return(0);
}
}
|
weebcyberpunk/tictactoe
|
bot.c
|
#include<stdio.h>
#include<stdlib.h>
int bot_search_won(char game[9]);
int bot_search_player_won(char game[9]);
int bot_think(char game[9]);
int bot_horse_patterns(char game[9]);
int bot_l_patterns(char game[9]);
int bot_diagonals(char game[9]);
int bot_attack(char game[9]);
int bot(char game[9], int bot_game[9], int round) {
// if 10 no house choosed
int house = 10;
// in first round, decide between 4 and 2
if (round == 1) {
if (game[4] == 'b') house = 4;
else house = 2;
return(house);
}
// search for bot won
house = bot_search_won(game);
if (house != 10) return(house);
house = bot_search_player_won(game);
if (house != 10) return(house);
// think
// first if 2 == X (because 4 == O), 4 and 6 == O, dial 0
if ((game[4] == 'O') && (game[6] == 'O')) return(0);
// now we search the horse patterns
house = bot_horse_patterns(game);
if (house != 10) return(house);
// now we search the l patterns
house = bot_l_patterns(game);
if (house != 10) return(house);
// now we search the diagonals
house = bot_diagonals(game);
if (house != 10) return(house);
// if any defense has been done, we start attacking
house = bot_attack(game);
return(house);
}
|
weebcyberpunk/tictactoe
|
print_game.c
|
#include<stdio.h>
int print_game(char game[9]) {
char view[9] = { '_', '_', '_', '_', '_', '_', '_', '_', '_' };
char num[9] = { '1', '2', '3', '4', '5', '6', '7', '8', '9' };
// if house is dialed
for(int control = 0; control < 9; control++) {
if (game[control] != 'b') {
view[control] = game[control];
num[control] = game[control];
}
}
// show houses
printf("\n");
printf("%c/%c/%c\t%c/%c/%c\n", num[0], num[1], num[2], view[0], view[1], view[2]);
printf("%c/%c/%c\t%c/%c/%c\n", num[3], num[4], num[5], view[3], view[4], view[5]);
printf("%c/%c/%c\t%c/%c/%c\n", num[6], num[7], num[8], view[6], view[7], view[8]);
printf("\n");
return(0);
}
|
weebcyberpunk/tictactoe
|
bot_search_won.c
|
#include<stdio.h>
int bot_search_won(char game[9]) {
// if house == 10 no won
int house = 10;
// with 0
if (game[0] == 'X') {
// 0-1-2
if ((game[1] == 'X') && (game[2] == 'b')) house = 2;
if ((game[2] == 'X') && (game[1] == 'b')) house = 1;
// 0-4-8
if ((game[4] == 'X') && (game[8] == 'b')) house = 8;
if ((game[8] == 'X') && (game[4] == 'b')) house = 4;
// 0-3-6
if ((game[3] == 'X') && (game[6] == 'b')) house = 6;
if ((game[6] == 'X') && (game[3] == 'b')) house = 3;
} else if (game[0] == 'b') {
if ((game[1] == game[2]) && (game[1] == 'X')) house = 0;
if ((game[4] == game[8]) && (game[4] == 'X')) house = 0;
if ((game[3] == game[6]) && (game[3] == 'X')) house = 0;
}
// with 1
if (game[1] == 'X') {
// 1-4-7
if ((game[4] == 'X') && (game[7] == 'b')) house = 7;
if ((game[7] == 'X') && (game[4] == 'b')) house = 4;
} else if (game[1] == 'b') {
if ((game[4] == game[7]) && (game[4] == 'X')) house = 1;
}
// with 2
if (game[2] == 'X') {
// 2-5-8
if ((game[5] == 'X') && (game[8] == 'b')) house = 8;
if ((game[8] == 'X') && (game[5] == 'b')) house = 5;
// 2-4-6
if ((game[4] == 'X') && (game[6] == 'b')) house = 6;
if ((game[6] == 'X') && (game[4] == 'b')) house = 4;
} else if (game[2] == 'b') {
if ((game[5] == game[8]) && (game[5] == 'X')) house = 2;
if ((game[4] == game[6]) && (game[4] == 'X')) house = 2;
}
// with 3
if (game[3] == 'X') {
// 3-4-5
if ((game[4] == 'X') && (game[5] == 'b')) house = 5;
if ((game[5] == 'X') && (game[4] == 'b')) house = 4;
} else if (game[3] == 'b') {
if ((game[4] == game[5]) && (game[4] == 'X')) house = 3;
}
// with 6
if (game[6] == 'X') {
// 6-7-8
if ((game[7] == 'X') && (game[8] == 'b')) house = 8;
if ((game[8] == 'X') && (game[7] == 'b')) house = 7;
} else if (game[6] == 'b') {
if ((game[7] == game[8]) && (game[7] == 'X')) house = 6;
}
return(house);
}
|
weebcyberpunk/tictactoe
|
bot_horse_patterns.c
|
<reponame>weebcyberpunk/tictactoe
#include<stdio.h>
int bot_horse_patterns(char game[9]) {
/*
* A quick explain: horse patterns are what I call when
* the O puts the pieces like this:
*
* O/_/_
* _/_/O
* _/_/_
*
* The problem is that, in this example, if O puts on 3,
* it'll have two options to win. The bot should avoid
* that at all cost.
*/
// again if 10 no horse pattern
int house = 10;
// with 0
if (game[0] == 'O') {
if ((game[5] == 'O') && (game[2] == 'b')) house = 2;
else if ((game[7] == 'O') && (game[6] == 'b')) house = 6;
}
// with 2
if (game[2] == 'O') {
if ((game[3] == 'O') && (game[0] == 'b')) house = 0;
else if ((game[7] == 'O') && (game[8] == 'b')) house = 8;
}
// with 6
if (game[6] == 'O') {
if ((game[1] == 'O') && (game[0] == 'b')) house = 0;
else if ((game[5] == 'O') && (game[8] == 'b')) house = 8;
}
// with 8
if (game[8] == 'O') {
if ((game[1] == 'O') && (game[2] == 'b')) house = 2;
else if ((game[3] == 'O') && (game[6] == 'b')) house = 6;
}
// this was quicker
// now we return the house
return(house);
}
|
weebcyberpunk/tictactoe
|
bot_attack.c
|
#include<stdio.h>
int bot_attack(char game[9]) {
int house = 10;
if (game[4] == 'X') {
if (game[0] == 'b') house = 0;
else if (game[2] == 'b') house = 2;
else if (game[6] == 'b') house = 6;
else if (game[8] == 'b') house = 8;
}
return(house);
}
|
weebcyberpunk/tictactoe
|
finish.c
|
#include<stdio.h>
char finish(char game[9]) {
// if b no one won, if won so x or o, for each player. If t, tie
char finish = 'b';
// test for finish in 0-1-2, 0-3-6 and 0-4-8
if (game[0] != 'b') {
if (
((game[0] == game[1]) && (game[0] == game[2])) ||
((game[0] == game[3]) && (game[0] == game[6])) ||
((game[0] == game[4]) && (game[0] == game[8]))
) finish = game[0];
}
// test for finish in 1-4-7
if (game[1] != 'b') {
if (
(game[1] == game[4]) && (game[1] == game[7])
) finish = game[1];
}
// test for finish in 2-5-8 and 2-4-6
if (game[2] != 'b') {
if (
((game[2] == game[5]) && (game[2] == game[8])) ||
((game[2] == game[4]) && (game[2] == game[6]))
) finish = game[2];
}
// test for finish in 3-4-5
if (game[3] != 'b') {
if (
(game[3] == game[4]) && (game[3] == game[5])
) finish = game[3];
}
// test for finish in 6-7-8
if (game[6] != 'b') {
if (
(game[6] == game[7]) && (game[6] == game[8])
) finish = game[6];
}
// thank gosh this is over
// now we need to see if game ends on a tie
for(int control = 0;; control++) {
if (control == 9) {
finish = 't';
} else if (game[control] == 'b') break;
}
// finally we return the finish
return(finish);
}
|
weebcyberpunk/tictactoe
|
bot_diagonals.c
|
<reponame>weebcyberpunk/tictactoe
#include<stdio.h>
int bot_diagonals(char game[9]) {
/*
* Quick explain: diagonals are like this:
*
* O/_/_
* _/_/_
* _/_/O
*
* The problem is that if the player dial
* 2 or 6 he'll have two ways to win.
*
* Avoiding this is more complicated. Any
* game situation where this can be found,
* the bot will have the middle dialed. So
* to avoid we dial, in this example, 7,
* so the player will be forced to dial 1:
*
* O/O/_
* _/X/_
* _/X/O
*/
// again if 10 no diagonal
int house = 10;
// well checking this is basically a big if
if (((game[0] == 'O') && (game[8] == 'O')) || ((game[2] == 'O') && (game[6] == 'O'))) house = 7;
return(house);
}
|
weebcyberpunk/tictactoe
|
help.c
|
<filename>help.c
#include<stdio.h>
int help() {
FILE *help;
help = fopen("/usr/share/tictactoe/help.txt", "r");
if (help == NULL) {
printf("no help file on /usr/share/tictactoe/help.txt\n");
return(1);
}
for (;;) {
char c = getc(help);
if (c == EOF) break;
printf("%c", c);
}
printf("\n");
fclose(help);
return(0);
}
|
rahulyesantharao/batch-dynamic-kdtree
|
include/kdtree/binary-heap-layout/bhlkdtree.h
|
<reponame>rahulyesantharao/batch-dynamic-kdtree
#ifndef BHLKDTREE_H
#define BHLKDTREE_H
#include "parlay/parallel.h"
#include "parlay/sequence.h"
#include "../shared/kdnode.h"
#include "../shared/kdtree.h"
#include "../shared/utils.h"
#include "../shared/macro.h"
inline bool buildInParallel(size_t num_points) { return num_points >= BHL_BUILD_BASE_CASE; }
// Dynamic (insert + delete) kd-tree with binary-heap layout
template <int dim, class objT, bool parallel = false, bool coarsen = false>
class BHL_KdTree : public KdTree<dim, objT, parallel, coarsen> {
typedef KdTree<dim, objT, parallel, coarsen> BaseTree;
using typename BaseTree::nodeT;
static const auto leaf_size = (coarsen ? CLUSTER_SIZE : 1);
#if (PARTITION_TYPE == PARTITION_OBJECT_MEDIAN)
void buildKdtRecursive(parlay::slice<objT *, objT *> items, int node_idx, int split_dim)
#elif (PARTITION_TYPE == PARTITION_SPATIAL_MEDIAN)
void buildKdtRecursive(parlay::slice<objT *, objT *> items,
parlay::slice<bool *, bool *> flags,
int node_idx,
int split_dim)
#endif
{
if (items.size() <= leaf_size) { // Base Case
assert(items.size() > 0);
new (&this->nodes[node_idx]) nodeT(items);
return;
}
// Recursive Case
bool parallelBuild = parallel && buildInParallel(items.size()); // should we parallelize?
// Make the split
double median;
size_t right_start;
#if (PARTITION_TYPE == PARTITION_OBJECT_MEDIAN)
if (parallelBuild) {
median = parallelMedianPartition<objT>(items, split_dim);
} else {
median = serialMedianPartition<objT>(items, split_dim);
}
right_start = items.size() / 2;
#elif (PARTITION_TYPE == PARTITION_SPATIAL_MEDIAN)
if (parallelBuild) {
median = parallelSpatialPartition<objT>(items, flags, split_dim, right_start);
} else {
median = serialSpatialPartition<objT>(items, split_dim, right_start);
}
#else
throw std::runtime_error("invalid partition type");
#endif
assert(right_start > 0);
// if (right_start == items.size()) {
// std::cout << "(split_dim, median, items.size()) = (" << split_dim << ", " << median << ", "
//<< items.size() << ")" << std::endl;
//}
assert(right_start < items.size());
// place the split
assert(node_idx >= 0);
assert((size_t)node_idx < this->num_nodes());
assert(this->nodes[node_idx].isEmpty());
auto p = new (&this->nodes[node_idx]) nodeT(split_dim, median, items);
// Child functors
auto next_split_dim = (split_dim + 1) % dim;
auto left_f = [&]() {
#if (PARTITION_TYPE == PARTITION_OBJECT_MEDIAN)
auto left_idx = 2 * node_idx + 1;
#elif (PARTITION_TYPE == PARTITION_SPATIAL_MEDIAN)
auto left_idx = node_idx + 1;
#endif
p->setLeft(&this->nodes[left_idx]);
// this->parents[left_idx] = p;
#if (PARTITION_TYPE == PARTITION_OBJECT_MEDIAN)
buildKdtRecursive(items.cut(0, right_start), left_idx, next_split_dim);
#elif (PARTITION_TYPE == PARTITION_SPATIAL_MEDIAN)
buildKdtRecursive(
items.cut(0, right_start), flags.cut(0, right_start), left_idx, next_split_dim);
#endif
};
auto right_f = [&]() {
#if (PARTITION_TYPE == PARTITION_OBJECT_MEDIAN)
auto right_idx = 2 * node_idx + 2;
#elif (PARTITION_TYPE == PARTITION_SPATIAL_MEDIAN)
auto right_idx = node_idx + (2 * right_start);
#endif
p->setRight(&this->nodes[right_idx]);
// this->parents[right_idx] = p;
#if (PARTITION_TYPE == PARTITION_OBJECT_MEDIAN)
buildKdtRecursive(items.cut(right_start, items.size()), right_idx, next_split_dim);
#elif (PARTITION_TYPE == PARTITION_SPATIAL_MEDIAN)
buildKdtRecursive(items.cut(right_start, items.size()),
flags.cut(right_start, flags.size()),
right_idx,
next_split_dim);
#endif
};
// Build Children
if (parallelBuild) {
parlay::par_do(left_f, right_f);
} else {
left_f();
right_f();
}
assert(!p->isLeaf());
p->recomputeBoundingBox();
}
// Base Building Functions
void buildKdt() {
assert(this->size() > leaf_size); // so it's not degenerate
buildKdtRecursive(parlay::slice(this->items.begin(), this->items.begin() + this->size()), 0, 0);
}
void buildKdt(parlay::slice<bool *, bool *> flags) {
assert(this->size() > leaf_size); // so it's not degenerate
buildKdtRecursive(
parlay::slice(this->items.begin(), this->items.begin() + this->size()), flags, 0, 0);
}
// cur_size, build_size, max_size, items are set before this is called
void build() {
assert(this->cur_size != 0);
#if (PARTITION_TYPE == PARTITION_OBJECT_MEDIAN)
buildKdt();
#elif (PARTITION_TYPE == PARTITION_SPATIAL_MEDIAN)
auto n = this->items.size();
auto flags = parlay::sequence<bool>(n);
auto flagSlice = parlay::slice(flags.begin(), flags.end());
buildKdt(flagSlice);
#endif
}
public:
BHL_KdTree(int log2size, bool initialize = true) : BaseTree(log2size) {
if (initialize) this->items = parlay::sequence<objT>(this->max_size);
}
BHL_KdTree(const parlay::slice<const objT *, const objT *> &points) : BaseTree(points) {
this->items = parlay::sequence<objT>(this->max_size);
build(points);
}
BHL_KdTree(const parlay::sequence<objT> &points) : BHL_KdTree(points.cut(0, points.size())) {}
// MODIFY --------------------------------------------
/*!
* Build a new kd-tree in this tree over the input points.
* This function should only be called on an empty tree.
* @param points the list of points to build the tree over.
*/
void build_no_bloom(const parlay::slice<const objT *, const objT *> &points) {
assert(this->cur_size == 0);
size_t n = points.size();
// save the input points into [items]
// TODO: does this parallelize? items.assign(points.begin(), points.end());
this->cur_size = n;
this->build_size = n;
parlay::parallel_for(0, n, [&](size_t i) { this->items[i] = points[i]; });
build();
}
void build(const parlay::slice<const objT *, const objT *> &points) {
assert(this->cur_size == 0);
#ifdef ALL_USE_BLOOM
parlay::par_do([&]() { this->bloom_filter.build(points); }, [&]() { build_no_bloom(points); });
#else
build_no_bloom(points);
#endif
}
// should somehow indicate that inserts aren't allowed
void build(parlay::sequence<objT> &&points) {
assert(this->cur_size == 0);
size_t n = points.size();
this->cur_size = n;
this->build_size = n;
this->items = points;
#ifdef ALL_USE_BLOOM
auto points_copy = this->items;
parlay::par_do([&]() { this->bloom_filter.build(points_copy); }, [&]() { build(); });
#else
build();
#endif
}
void insert(const parlay::slice<const objT *, const objT *> &points) {
if (points.size() == 0) return;
#ifndef NDEBUG
#warning "this is probably bad for runtime - remove later"
if (points.size() > this->capacity() - this->cur_size) {
std::stringstream ss;
ss << "Invalid Insert: (points.size(), max_size, cur_size) = (" << points.size() << ", "
<< this->capacity() << ", " << this->cur_size << ")";
throw std::runtime_error(ss.str());
}
#endif
auto insert_no_bloom = [&]() {
if (this->cur_size == 0) {
build_no_bloom(points);
} else {
// gather points from tree
parlay::sequence<objT> gather(this->cur_size);
[[maybe_unused]] auto num_moved = this->moveElementsTo(gather.cut(0, this->cur_size));
assert(num_moved == gather.size());
parlay::parallel_for(0, gather.size() + points.size(), [&](size_t i) {
if (i < gather.size())
this->items[i] = gather[i]; // reinsert old items
else
this->items[i] = points[i - gather.size()]; // insert new items
});
// set sizes
this->cur_size = gather.size() + points.size();
this->build_size = this->cur_size;
build();
}
};
#ifdef ALL_USE_BLOOM
parlay::par_do([&]() { this->bloom_filter.insert(points); }, [&]() { insert_no_bloom(); });
#else
insert_no_bloom();
#endif
}
template <bool rebuild = true>
#ifdef ALL_USE_BLOOM
void bulk_erase(const parlay::sequence<objT> &points)
#else
void bulk_erase(parlay::sequence<objT> &points)
#endif
{
#ifdef ALL_USE_BLOOM
BaseTree::bulk_erase(points);
#else
if (rebuild) { // NOT logtree!
auto points_copy = points;
BaseTree::bulk_erase(points_copy);
} else {
BaseTree::bulk_erase(points);
}
#endif
if (rebuild) {
auto cursize = this->cur_size;
parlay::sequence<objT> elements(cursize);
this->moveElementsTo(elements.cut(0, cursize));
const auto &const_elements = elements;
build(const_elements.cut(0, cursize));
}
}
};
#endif // BHLKDTREE_H
|
rahulyesantharao/batch-dynamic-kdtree
|
include/kdtree/shared/knnbuffer.h
|
<filename>include/kdtree/shared/knnbuffer.h
#ifndef KDTREE_SHARED_KNNBUFFER_H
#define KDTREE_SHARED_KNNBUFFER_H
// TAKEN with slight modifications FROM
// https://github.mit.edu/yiqiuw/pargeo/blob/master/knnSearch/kdTree/kdtKnn.h Later, need to merge +
// refer to that rather than copying here
#include <common/geometry.h>
namespace knnBuf {
typedef int intT;
typedef double floatT;
template <typename T>
struct elem {
floatT cost; // Non-negative
T entry;
elem(floatT t_cost, T t_entry) : cost(t_cost), entry(t_entry) {}
elem() : cost(std::numeric_limits<floatT>::max()) {}
bool operator<(const elem& b) const {
if (cost < b.cost) return true;
return false;
}
};
template <typename T>
struct buffer {
typedef parlay::slice<elem<T>*, elem<T>*> sliceT;
/*const*/ intT k; // not const because of assignment in dualKnn
intT ptr;
sliceT buf;
bool cached;
buffer() : k(-1), ptr(0), buf(), cached(false) {}
buffer(intT t_k, sliceT t_buf) : k(t_k), ptr(0), buf(t_buf), cached(true) {}
inline void reset() { ptr = 0; }
bool hasK() { return ptr >= k; }
elem<T> keepK() {
if (ptr < k) throw std::runtime_error("Error, kbuffer not enough k.");
if (!cached) { // only need to do this if modified since last call
std::nth_element(buf.begin(), buf.begin() + k - 1, buf.begin() + ptr);
ptr = k;
cached = true;
}
return buf[k - 1];
}
void insert(elem<T> t_elem) {
buf[ptr++] = t_elem;
cached = false;
if (ptr >= (int)buf.size()) keepK();
}
elem<T> operator[](intT i) {
if (i < ptr)
return buf[i];
else
return elem<T>();
}
};
template <int dim>
parlay::sequence<const point<dim>*> bruteforceKnn(const parlay::sequence<point<dim>>& queries,
size_t k) {
auto out = parlay::sequence<elem<const point<dim>*>>(2 * k * queries.size());
auto idx = parlay::sequence<const point<dim>*>(k * queries.size());
parlay::parallel_for(0, queries.size(), [&](size_t i) {
auto q = queries[i];
buffer buf = buffer<const point<dim>*>(k, out.cut(i * 2 * k, (i + 1) * 2 * k));
for (intT j = 0; j < (int)queries.size(); ++j) {
auto p = &queries[j];
buf.insert(elem(q.dist(p), p));
}
buf.keepK();
// store results
for (size_t j = 0; j < k; j++) {
idx[i * k + j] = buf[j].entry;
}
});
return idx;
}
} // namespace knnBuf
#endif // KDTREE_SHARED_KNNBUFFER_H
|
rahulyesantharao/batch-dynamic-kdtree
|
test/log-tree/LT2DDeleteTest.h
|
#ifndef TEST_LOGTREE_LT2DDELETETEST_H
#define TEST_LOGTREE_LT2DDELETETEST_H
#include <gtest/gtest.h>
#include "common/geometryIO.h"
#include <kdtree/log-tree/logtree.h>
class Bulk {
public:
static constexpr bool bulk = true;
};
class NotBulk {
public:
static constexpr bool bulk = false;
};
typedef point<2> pointT;
template <typename Pair>
class LT2DDeleteTest : public ::testing::Test {
public:
const int DIM = 2;
};
TYPED_TEST_SUITE_P(LT2DDeleteTest);
TYPED_TEST_P(LT2DDeleteTest, Delete1) {
using LTree = typename TypeParam::first_type;
constexpr bool bulk = TypeParam::second_type::bulk;
const char* test_file = "../resources/2d-UniformInSphere-1k.pbbs";
int check_dim = readDimensionFromFile(test_file);
ASSERT_EQ(check_dim, this->DIM);
auto points = readPointsFromFile<pointT>(test_file);
LTree tree;
tree.insert(points);
for (size_t i = 0; i < points.size(); i++) {
ASSERT_TRUE(tree.contains(points[i]));
}
const auto num_to_remove = 70;
parlay::sequence<pointT> to_remove(num_to_remove);
for (size_t i = 0; i < num_to_remove; i++) {
to_remove[i] = points[points.size() - 1 - i];
}
tree.template erase<bulk>(to_remove);
for (int i = 0; i < (int)points.size(); i++) {
if (i < (int)points.size() - num_to_remove)
ASSERT_TRUE(tree.contains(points[i]));
else
ASSERT_FALSE(tree.contains(points[i]));
}
}
TYPED_TEST_P(LT2DDeleteTest, Delete2) {
using LTree = typename TypeParam::first_type;
constexpr bool bulk = TypeParam::second_type::bulk;
const char* test_file = "../resources/2d-UniformInSphere-1k.pbbs";
int check_dim = readDimensionFromFile(test_file);
ASSERT_EQ(check_dim, this->DIM);
auto points = readPointsFromFile<pointT>(test_file);
LTree tree;
tree.insert(points);
for (size_t i = 0; i < points.size(); i++) {
ASSERT_TRUE(tree.contains(points[i]));
}
parlay::sequence<pointT> to_remove(points.size() / 2);
for (size_t i = 0; i < points.size() / 2; i++) {
to_remove[i] = points[2 * i];
}
tree.template erase<bulk>(to_remove);
for (size_t i = 0; i < points.size(); i++) {
if (i % 2 == 0)
ASSERT_FALSE(tree.contains(points[i]));
else
ASSERT_TRUE(tree.contains(points[i]));
}
}
// TODO: split this into a value parameterized test or something
TYPED_TEST_P(LT2DDeleteTest, BigDelete1) {
using LTree = typename TypeParam::first_type;
constexpr bool bulk = TypeParam::second_type::bulk;
const char* test_file = "../resources/2d-UniformInSphere-10K.pbbs";
int check_dim = readDimensionFromFile(test_file);
ASSERT_EQ(check_dim, this->DIM);
auto points = readPointsFromFile<pointT>(test_file);
for (int skip = 2; skip < 10; skip++) {
std::cout << " ----- TESTING " << skip << " ----------- " << std::endl;
LTree tree;
tree.insert(points);
for (size_t i = 0; i < points.size(); i++) {
ASSERT_TRUE(tree.contains(points[i]));
}
parlay::sequence<pointT> to_remove((points.size() + (skip - 1)) / skip);
for (size_t i = 0; i < to_remove.size(); i++) {
to_remove[i] = points[skip * i];
}
tree.template erase<bulk>(to_remove);
auto check_present = [&](size_t i) { return tree.contains(points[i]); };
auto check_missing = [&](size_t i) { return !tree.contains(points[i]); };
for (size_t i = 0; i < points.size(); i++) {
if (i % skip == 0)
ASSERT_PRED1(check_missing, i);
else
ASSERT_PRED1(check_present, i);
}
}
}
TYPED_TEST_P(LT2DDeleteTest, BigDelete2) {
using LTree = typename TypeParam::first_type;
constexpr bool bulk = TypeParam::second_type::bulk;
const char* test_file = "../resources/2d-UniformInSphere-10K.pbbs";
int check_dim = readDimensionFromFile(test_file);
ASSERT_EQ(check_dim, this->DIM);
auto points = readPointsFromFile<pointT>(test_file);
for (int skip = 2; skip < 10; skip++) {
std::cout << " ----- TESTING " << skip << " ----------- " << std::endl;
LTree tree;
tree.insert(points);
for (size_t i = 0; i < points.size(); i++) {
ASSERT_TRUE(tree.contains(points[i]));
}
auto num_to_keep = (points.size() + (skip - 1)) / skip;
auto num_to_remove = points.size() - num_to_keep;
parlay::sequence<pointT> to_remove(num_to_remove);
int j = 0;
for (size_t i = 0; i < points.size(); i++) {
if (i % skip == 0) continue;
to_remove[j++] = points[i];
}
ASSERT_EQ(j, num_to_remove); // sanity check
tree.template erase<bulk>(to_remove);
auto check_present = [&](size_t i) { return tree.contains(points[i]); };
auto check_missing = [&](size_t i) { return !tree.contains(points[i]); };
for (size_t i = 0; i < points.size(); i++) {
if (i % skip == 0)
ASSERT_PRED1(check_present, i);
else
ASSERT_PRED1(check_missing, i);
}
}
}
REGISTER_TYPED_TEST_SUITE_P(LT2DDeleteTest, Delete1, Delete2, BigDelete1, BigDelete2);
#endif // TEST_LOGTREE_LT2DDELETETEST_H
|
rahulyesantharao/batch-dynamic-kdtree
|
include/kdtree/shared/bloom.h
|
#ifndef KDTREE_SHARED_BLOOM_H
#define KDTREE_SHARED_BLOOM_H
#define XXH_PRIVATE_API
#include <common/geometry.h>
#include <parlay/parallel.h>
#include <parlay/sequence.h>
#include <xxHash/xxhash.h>
#define ATOMIC_BUCKETS
//#define BIT_VECTOR
template <int dim>
class BloomFilter {
static constexpr int NUM_ARRAYS = 4;
static constexpr int EMPTY_BUCKETS_GRANULARITY = 1024;
static constexpr int FILL_BUCKETS_GRANULARITY = 1024;
#ifdef ATOMIC_BUCKETS
#ifdef BIT_VECTOR
typedef char bucketT;
#else
typedef bool bucketT;
#endif
std::atomic<bucketT> *buckets[NUM_ARRAYS];
#else
std::vector<char> buckets[NUM_ARRAYS];
#endif
typedef point<dim> pointT;
const size_t num_buckets;
const size_t buckets_size;
size_t hash(const pointT &p, int bucket_num) {
auto h = (uint64_t)XXH64(p.x, dim * sizeof(double), bucket_num);
return h % num_buckets;
}
static inline bool bit_set(char val, int bit) { return ((val) & (1 << bit)) != 0; }
static inline char set_bit(char val, int bit) { return ((val) | (1 << bit)); }
bool get(int j, size_t idx) {
#ifdef ATOMIC_BUCKETS
#ifdef BIT_VECTOR
return bit_set(buckets[j][idx / 8], idx % 8);
#else
return buckets[j][idx];
#endif
#else
return buckets[j][idx];
#endif
}
void set(int j, size_t idx) {
if (!get(j, idx)) {
#ifdef ATOMIC_BUCKETS
#ifdef BIT_VECTOR
bucketT exp = buckets[j][idx / 8];
while (!buckets[j][idx / 8].compare_exchange_weak(exp, set_bit(exp, idx % 8)) &&
!bit_set(exp, idx % 8))
;
#else
bucketT exp = 0;
buckets[j][idx].compare_exchange_strong(exp, 1);
#endif
#else
buckets[j][idx] = 1;
#endif
}
}
public:
BloomFilter(size_t num_points)
: num_buckets(num_points * 2),
buckets_size(
#ifdef BIT_VECTOR
(num_points * 2 + 7) / 8
#else
num_points * 2
#endif
) {
// TODO: compute better bound for [num_buckets]
for (int i = 0; i < NUM_ARRAYS; i++) {
#ifdef ATOMIC_BUCKETS
buckets[i] = new std::atomic<bucketT>[buckets_size];
#else
buckets[i].resize(buckets_size, 0);
#endif
}
}
#ifdef ATOMIC_BUCKETS
~BloomFilter() {
for (int i = 0; i < NUM_ARRAYS; i++) {
delete[] buckets[i];
}
}
#endif
void clear() {
// empty buckets
parlay::parallel_for(0, NUM_ARRAYS, [&](size_t i) {
parlay::parallel_for(
0, buckets_size, [&](size_t j) { buckets[i][j] = 0; }, EMPTY_BUCKETS_GRANULARITY);
});
}
template <class R>
void insert(const R &points) {
// set buckets
parlay::parallel_for(
0,
points.size(),
[&](size_t i) {
for (int j = 0; j < NUM_ARRAYS; j++) {
auto idx = hash(points[i], j);
set(j, idx);
}
},
FILL_BUCKETS_GRANULARITY);
}
template <class R>
void build(const R &points) {
clear();
insert(points);
}
bool might_contain(const point<dim> &p) {
for (int i = 0; i < NUM_ARRAYS; i++) {
auto idx = hash(p, i);
if (!get(i, idx)) return false;
}
return true;
}
template <class R>
parlay::sequence<point<dim>> filter(const R &points) {
return parlay::filter(points, [this](const point<dim> &p) { return this->might_contain(p); });
}
};
#endif // KDTREE_SHARED_BLOOM_H
|
rahulyesantharao/batch-dynamic-kdtree
|
include/kdtree/shared/dual.h
|
<reponame>rahulyesantharao/batch-dynamic-kdtree
#ifndef DUAL_H
#define DUAL_H
#include "../cache-oblivious/cokdtree.h"
#include "../log-tree/logtree.h"
#ifdef PRINT_DKNN_TIMINGS
#include "common/get_time.h"
#endif
// Top-level wrappers for calling dual knn
template <int dim, class objT, bool parallel, bool coarsen>
parlay::sequence<const point<dim> *> dualKnn(parlay::sequence<objT> &queries,
const KdTree<dim, objT, parallel, coarsen> &rTree,
int k) {
// construct query tree
#ifdef PRINT_DKNN_TIMINGS
timer t;
#endif
CO_KdTree<dim, objT, parallel, coarsen> qTree((int)std::ceil(std::log2(queries.size())));
qTree.build(std::move(queries));
#ifdef PRINT_DKNN_TIMINGS
std::cout << "[DKNN] Query Tree Construction: " << t.get_next() << "\n";
#endif
auto ret = rTree.dualKnnBase(qTree, k); // call dual knn
queries = std::move(qTree.items); // move the query points back
return ret;
}
template <int NUM_TREES, // the number of static trees
int BUFFER_LOG2_SIZE, // the size of the (dynamic) buffer tree
int dim,
class objT,
bool parallel,
bool coarsen>
parlay::sequence<const point<dim> *> dualKnn(
parlay::sequence<objT> &queries,
const LogTree<NUM_TREES, BUFFER_LOG2_SIZE, dim, objT, parallel, coarsen> &rTree,
int k) {
// construct query tree
#ifdef PRINT_DKNN_TIMINGS
timer t;
#endif
CO_KdTree<dim, objT, parallel, coarsen> qTree((int)std::ceil(std::log2(queries.size())));
qTree.build(std::move(queries));
#ifdef PRINT_DKNN_TIMINGS
std::cout << "[DKNN] Query Tree Construction: " << t.get_next() << "\n";
#endif
auto ret = rTree.dualKnnBase(qTree, k); // call dual knn
queries = std::move(qTree.items); // move the query points back
return ret;
}
template <int dim, class objT, bool parallel, bool coarsenq, bool coarsenr>
#if (DUAL_KNN_MODE == DKNN_ARRAY)
void DualKnnHelper(kdNode<dim, objT, parallel> *Q,
const kdNode<dim, objT, parallel> *R,
const KdTree<dim, objT, parallel, coarsenq> &qTree,
parlay::sequence<double> &dualKnnDists,
const KdTree<dim, objT, parallel, coarsenr> &rTree,
parlay::slice<knnBuf::buffer<const point<dim> *> *,
knnBuf::buffer<const point<dim> *> *> &bufs) {
#else
void DualKnnHelper(kdNode<dim, objT, parallel> *Q,
const kdNode<dim, objT, parallel> *R,
const KdTree<dim, objT, parallel, coarsenq> &qTree,
const KdTree<dim, objT, parallel, coarsenr> &rTree,
parlay::slice<knnBuf::buffer<const point<dim> *> *,
knnBuf::buffer<const point<dim> *> *> &bufs) {
#endif
typedef kdNode<dim, objT, parallel> nodeT;
// if (!Q || !R) return;
assert(Q && R);
auto recurse = [&](kdNode<dim, objT, parallel> *_Q, const kdNode<dim, objT, parallel> *_R) {
#if (DUAL_KNN_MODE == DKNN_ARRAY)
DualKnnHelper(_Q, _R, qTree, dualKnnDists, rTree, bufs);
#else
DualKnnHelper(_Q, _R, qTree, rTree, bufs);
#endif
};
// if either node has only a single child, just forward the call
if (Q->getLeft() && !Q->getRight()) {
recurse(Q->getLeft(), R);
return;
} else if (!Q->getLeft() && Q->getRight()) {
recurse(Q->getRight(), R);
return;
} else if (R->getLeft() && !R->getRight()) {
recurse(Q, R->getLeft());
return;
} else if (!R->getLeft() && R->getRight()) {
recurse(Q, R->getRight());
return;
}
// either a leaf or a node with 2 children
assert(Q->isLeaf() || (Q->getLeft() && Q->getRight()));
assert(R->isLeaf() || (R->getLeft() && R->getRight()));
// order calls based on bbox distance (TODO: does this actually help?)
// used below for the one-sided recursion cases
auto one_sided_recurse =
[&](bool recurseInParallel, nodeT *Q1, const nodeT *R1, nodeT *Q2, const nodeT *R2) {
auto dist1 = KdNodeBoundingBoxDistance(Q1, R1);
auto dist2 = KdNodeBoundingBoxDistance(Q2, R2);
if (dist1 < dist2) { // 1 before 2
if (recurseInParallel) {
parlay::par_do([&]() { recurse(Q1, R1); }, [&]() { recurse(Q2, R2); });
} else {
recurse(Q1, R1);
recurse(Q2, R2);
}
} else { // 2 before 1
if (recurseInParallel) {
parlay::par_do([&]() { recurse(Q2, R2); }, [&]() { recurse(Q1, R1); });
} else {
recurse(Q2, R2);
recurse(Q1, R1);
}
}
};
#if (DUAL_KNN_MODE == DKNN_ARRAY)
if (KdNodeBoundingBoxDistance(Q, R) > dualKnnDists[qTree.node_idx(Q)]) {
#else
if (KdNodeBoundingBoxDistance(Q, R) > Q->dualKnnDist) {
#endif
// definitely no updates here
return;
} else if (Q->isLeaf() && R->isLeaf()) { // reached leaves -> update!
// get the indices of the items in Q
const auto &q_items = qTree.items;
auto q_start = Q->getStartValue() - q_items.begin();
auto q_end = Q->getEndValue() - q_items.begin();
assert(q_end > q_start);
assert(q_start >= 0);
assert(Q->subtree_items.size() == (size_t)(q_end - q_start));
assert(qTree.size() == q_items.size());
// leaves are small -> don't bother parallelizing
double Q_new_radius = 0;
for (auto q_idx = (size_t)q_start; q_idx < (size_t)q_end; q_idx++) {
assert(q_idx >= 0);
assert(q_idx < bufs.size());
auto &q_out = bufs[q_idx];
auto q_radius = q_out.hasK() ? q_out.keepK().cost : std::numeric_limits<double>::max();
// relax in all the points in R
R->knnAddToBuffer(q_items[q_idx], rTree.items.begin(), rTree.present, q_out, q_radius);
// update the new radius
auto q_new_radius = q_out.hasK() ? q_out.keepK().cost : std::numeric_limits<double>::max();
Q_new_radius = std::max(Q_new_radius, q_new_radius);
}
#if (DUAL_KNN_MODE == DKNN_ARRAY)
dualKnnDists[qTree.node_idx(Q)] = Q_new_radius;
#else
Q->update_dual_knn_dist(Q_new_radius);
#endif
} else if (Q->isLeaf()) {
// cannot recurse in parallel because Q is the same in both cases
one_sided_recurse(false, Q, R->getLeft(), Q, R->getRight());
} else if (R->isLeaf()) {
one_sided_recurse(parallel && Q->dualKnnRecurseInParallel(), Q->getLeft(), R, Q->getRight(), R);
#if (DUAL_KNN_MODE == DKNN_ARRAY)
dualKnnDists[qTree.node_idx(Q)] =
std::max(dualKnnDists[qTree.node_idx(Q->left)], dualKnnDists[qTree.node_idx(Q->right)]);
#else
Q->update_dual_knn_dist(std::max(Q->left->dualKnnDist, Q->right->dualKnnDist));
#endif
} else { // neither is leaf, all 4 recursive steps
auto QlRl_dist = KdNodeBoundingBoxDistance(Q->getLeft(), R->getLeft());
auto QlRr_dist = KdNodeBoundingBoxDistance(Q->getLeft(), R->getRight());
// closer R child to Q->getLeft()
auto Ql_R1 = (QlRl_dist < QlRr_dist) ? R->getLeft() : R->getRight();
// further R child to Q->getLeft()
auto Ql_R2 = (QlRl_dist < QlRr_dist) ? R->getRight() : R->getLeft();
auto QrRl_dist = KdNodeBoundingBoxDistance(Q->getRight(), R->getLeft());
auto QrRr_dist = KdNodeBoundingBoxDistance(Q->getRight(), R->getRight());
auto Qr_R1 = (QrRl_dist < QrRr_dist) ? R->getLeft() : R->getRight();
auto Qr_R2 = (QrRl_dist < QrRr_dist) ? R->getRight() : R->getLeft();
if (parallel && (Q->dualKnnRecurseInParallel() || R->dualKnnRecurseInParallel())) {
parlay::par_do([&]() { recurse(Q->getLeft(), Ql_R1); },
[&]() { recurse(Q->getRight(), Qr_R1); });
parlay::par_do([&]() { recurse(Q->getLeft(), Ql_R2); },
[&]() { recurse(Q->getRight(), Qr_R2); });
} else {
recurse(Q->getLeft(), Ql_R1);
recurse(Q->getRight(), Qr_R1);
recurse(Q->getLeft(), Ql_R2);
recurse(Q->getRight(), Qr_R2);
}
#if (DUAL_KNN_MODE == DKNN_ARRAY)
dualKnnDists[qTree.node_idx(Q)] =
std::max(dualKnnDists[qTree.node_idx(Q->left)], dualKnnDists[qTree.node_idx(Q->right)]);
#else
Q->update_dual_knn_dist(std::max(Q->left->dualKnnDist, Q->right->dualKnnDist));
#endif
}
}
#endif // DUAL_H
|
rahulyesantharao/batch-dynamic-kdtree
|
test/log-tree/LT2DStructureTest.h
|
#ifndef TEST_LOGTREE_LT2DSTRUCTURETEST_H
#define TEST_LOGTREE_LT2DSTRUCTURETEST_H
#include <gtest/gtest.h>
#include "common/geometryIO.h"
#include <kdtree/log-tree/logtree.h>
typedef point<2> pointT;
pointT constructPoint(double d) {
constexpr int dim = 2;
double point_buf[dim];
for (int k = 0; k < dim; k++) {
point_buf[k] = d;
}
return pointT(point_buf);
}
template <typename LTree>
class LT2DStructureTest : public ::testing::Test {
public:
const int DIM = 2;
};
TYPED_TEST_SUITE_P(LT2DStructureTest);
TYPED_TEST_P(LT2DStructureTest, LayoutSize32) {
TypeParam tree;
// build over 32 points
constexpr int buf_size = 4;
for (int i = 0; i < 32 / buf_size; i++) {
parlay::sequence<pointT> x(buf_size);
for (int j = 0; j < buf_size; j++) {
x[j] = constructPoint((double)(buf_size * i + j));
}
tree.insert(x);
}
// verify over 32 points
auto tree_mask = tree.getTreeMask();
if (TypeParam::coarsen_)
ASSERT_EQ(tree_mask, 0);
else
ASSERT_EQ(tree_mask, 0b0011); // lazy shifting -> will leave full buffer
for (int i = 0; i < 32; i++) {
ASSERT_TRUE(tree.contains(constructPoint((double)i)));
}
for (int i = 32; i < 100; i++) {
ASSERT_FALSE(tree.contains(constructPoint((double)i)));
}
}
TYPED_TEST_P(LT2DStructureTest, LayoutSize64) {
TypeParam tree;
// build over 64 points
for (int i = 0; i < 32; i++) {
parlay::sequence<pointT> x(2);
for (int j = 0; j < 2; j++) {
x[j] = constructPoint((double)(2 * i + j));
}
tree.insert(x);
}
// verify over 64 points
auto tree_mask = tree.getTreeMask();
if (TypeParam::coarsen_)
ASSERT_EQ(tree_mask, 0b01);
else
ASSERT_EQ(tree_mask, 0b0111); // lazy shifting -> won't move full buffer
for (int i = 0; i < 64; i++) {
ASSERT_TRUE(tree.contains(constructPoint((double)i)));
}
for (int i = 64; i < 200; i++) {
ASSERT_FALSE(tree.contains(constructPoint((double)i)));
}
}
TYPED_TEST_P(LT2DStructureTest, Verify) {
const char* test_file = "../resources/2d-UniformInSphere-1k.pbbs";
int check_dim = readDimensionFromFile(test_file);
ASSERT_EQ(check_dim, this->DIM);
auto points = readPointsFromFile<pointT>(test_file);
TypeParam tree;
tree.insert(points);
// check trees
if (TypeParam::coarsen_)
ASSERT_EQ(tree.getTreeMask(), 0b11111);
else
ASSERT_EQ(tree.getTreeMask(), 0b1111101);
// positive tests
for (const auto& p : points) {
ASSERT_TRUE(tree.contains(p));
}
// negative tests
for (int i = 0; i < 100; i++) {
ASSERT_FALSE(tree.contains(constructPoint((double)i)));
}
}
// Come up with a better abstraction; this is a direct copy of BasicKnn test
TYPED_TEST_P(LT2DStructureTest, BasicKnn2) {
// construct tree
const char* test_file = "../resources/2d-UniformInSphere-1k.pbbs";
int check_dim = readDimensionFromFile(test_file);
ASSERT_EQ(check_dim, this->DIM);
auto points = readPointsFromFile<pointT>(test_file);
TypeParam tree;
tree.insert(points);
ASSERT_EQ(tree.size(), points.size());
// construct brute force solution
constexpr int k = 4;
auto check = knnBuf::bruteforceKnn(points, k);
ASSERT_EQ(check.size(), k * points.size());
for (int i = 0; i < 4; i++) {
decltype(check) res;
if (i == 0) {
res = tree.template knn2<false, false>(points, k);
} else if (i == 1) {
res = tree.template knn2<false, true>(points, k);
} else if (i == 2) {
res = tree.template knn2<true, false>(points, k);
} else {
res = tree.template knn2<true, true>(points, k);
}
// verify result
ASSERT_EQ(res.size(), k * points.size());
for (size_t i = 0; i < points.size(); i++) {
// std::cout << "CHECKING knn FOR " << i << ": " << points[i] << std::endl;
// sort the results for this point
auto res_start = res.begin() + i * k;
auto check_start = check.begin() + i * k;
auto compare = [&](const pointT* l, const pointT* r) {
return l->coordinate(0) < r->coordinate(0);
};
std::sort(check_start, check_start + k, compare);
std::sort(res_start, res_start + k, compare);
for (int j = 0; j < k; j++) {
auto res_pt = **(res_start + j);
auto check_pt = **(check_start + j);
// std::cout << " - " << j << ": " << res_pt << " vs " << check_pt << std::endl;
EXPECT_EQ(res_pt, check_pt) << "dist res, dist check = " << points[i].dist(res_pt) << ", "
<< points[i].dist(check_pt);
}
}
}
}
// Come up with a better abstraction; this is a direct copy of BasicKnn test
TYPED_TEST_P(LT2DStructureTest, BasicKnn3) {
// construct tree
const char* test_file = "../resources/2d-UniformInSphere-1k.pbbs";
int check_dim = readDimensionFromFile(test_file);
ASSERT_EQ(check_dim, this->DIM);
auto points = readPointsFromFile<pointT>(test_file);
TypeParam tree;
tree.insert(points);
ASSERT_EQ(tree.size(), points.size());
// construct brute force solution
constexpr int k = 4;
auto check = knnBuf::bruteforceKnn(points, k);
ASSERT_EQ(check.size(), k * points.size());
for (int i = 0; i < 4; i++) {
decltype(check) res;
if (i == 0) {
res = tree.template knn3<false, false>(points, k);
} else if (i == 1) {
res = tree.template knn3<false, true>(points, k);
} else if (i == 2) {
res = tree.template knn3<true, false>(points, k);
} else {
res = tree.template knn3<true, true>(points, k);
}
// verify result
ASSERT_EQ(res.size(), k * points.size());
for (size_t i = 0; i < points.size(); i++) {
// std::cout << "CHECKING knn FOR " << i << ": " << points[i] << std::endl;
// sort the results for this point
auto res_start = res.begin() + i * k;
auto check_start = check.begin() + i * k;
auto compare = [&](const pointT* l, const pointT* r) {
return l->coordinate(0) < r->coordinate(0);
};
std::sort(check_start, check_start + k, compare);
std::sort(res_start, res_start + k, compare);
for (int j = 0; j < k; j++) {
auto res_pt = **(res_start + j);
auto check_pt = **(check_start + j);
// std::cout << " - " << j << ": " << res_pt << " vs " << check_pt << std::endl;
EXPECT_EQ(res_pt, check_pt) << "dist res, dist check = " << points[i].dist(res_pt) << ", "
<< points[i].dist(check_pt);
}
}
}
}
REGISTER_TYPED_TEST_SUITE_P(
LT2DStructureTest, LayoutSize32, LayoutSize64, Verify, BasicKnn2, BasicKnn3);
#endif // TEST_LOGTREE_LT2DSTRUCTURETEST_H
|
rahulyesantharao/batch-dynamic-kdtree
|
benchmark/utils.h
|
#ifndef BENCHMARK_UTILS_H
#define BENCHMARK_UTILS_H
#include "parlay/random.h"
#include <random>
// --- Taken from parlaylib ---
// Use this macro to avoid accidentally timing the destructors
// of the output produced by algorithms that return data
//
// The expression e is evaluated as if written in the context
// auto result_ = (e);
//
#define RUN_AND_CLEAR(e) \
{ \
auto result_ = (e); \
state.PauseTiming(); \
} \
state.ResumeTiming();
// Define the benchmarks
#define BENCH(NAME, ...) \
BENCHMARK_TEMPLATE(bench_##NAME, ##__VA_ARGS__)->UseRealTime()->Unit(benchmark::kMillisecond)
// --- Data loading ---
template <int dim>
void AddNoise(parlay::sequence<point<dim>>& points) {
std::default_random_engine generator;
std::uniform_real_distribution<double> distribution(0.0, 1e-6);
for (size_t i = 0; i < points.size(); i++) {
for (int d = 0; d < dim; d++) {
points[i][d] += distribution(generator);
}
}
}
template <int dim, bool add_noise = false>
auto LoadFile(const char* filePath) {
[[maybe_unused]] auto read_dim = readDimensionFromFile(filePath);
assert(read_dim == dim);
auto ret = readPointsFromFile<point<dim>>(filePath);
if (add_noise) AddNoise<dim>(ret);
return ret;
}
auto UniformSphere2D_1K() { return LoadFile<2>("datasets/2d-UniformInSphere-1k.pbbs"); }
auto UniformSphere2D_10K() { return LoadFile<2>("datasets/2d-UniformInSphere-10K.pbbs"); }
auto UniformSphere2D_1M() { return LoadFile<2>("datasets/2d-UniformInSphere-1M.pbbs"); }
auto UniformSphere2D_10M() { return LoadFile<2>("datasets/2d-UniformInSphere-10M.pbbs"); }
auto VisualVar5D_100K() { return LoadFile<5>("datasets/5D_VisualVar_100K.pbbs"); }
auto VisualVar5D_1M() { return LoadFile<5>("datasets/5D_VisualVar_1M.pbbs"); }
// Benchmark Datasets
auto UniformFill2D_10M() { return LoadFile<2>("datasets/2D_UniformFill_10M.pbbs"); }
auto UniformFill5D_10M() { return LoadFile<5>("datasets/5D_UniformFill_10M.pbbs"); }
auto UniformFill7D_10M() { return LoadFile<7>("datasets/7D_UniformFill_10M.pbbs"); }
auto VisualVar2D_10M() { return LoadFile<2, true>("datasets/2D_VisualVar_10M.pbbs"); }
auto VisualVar5D_10M() { return LoadFile<5, true>("datasets/5D_VisualVar_10M.pbbs"); }
auto VisualVar7D_10M() { return LoadFile<7, true>("datasets/7D_VisualVar_10M.pbbs"); }
auto GeoLife3D_24M() { return LoadFile<3, true>("datasets/3D_GeoLife_24M.pbbs"); }
auto HouseHold7D_2M() { return LoadFile<7, true>("datasets/7D_HouseHold_2M.pbbs"); }
auto HT10D_1M() { return LoadFile<10, true>("datasets/HT.pbbs"); }
auto CHEM16D_4M() { return LoadFile<16, true>("datasets/CHEM.pbbs"); }
enum DSType {
DS_UNIFORM_FILL, // 0
DS_UNIFORM_SPHERE, // 1
DS_VISUAL_VAR, // 2
DS_GEO_LIFE, // 3
DS_HOUSE_HOLD, // 4
DS_HT, // 5
DS_CHEM // 6
};
template <int dim>
auto BenchmarkDS(__attribute__((unused)) int size,
__attribute__((unused)) DSType ds_type,
bool shuffle = true) {
std::stringstream ss;
ss << "Invalid dim=" << dim << " to BenchmarkDS";
throw std::runtime_error(ss.str());
}
template <>
auto BenchmarkDS<2>(int size, DSType ds_type, bool shuffle) {
parlay::sequence<point<2>> ret;
switch (ds_type) {
case DS_UNIFORM_FILL: {
ret = UniformFill2D_10M();
break;
}
case DS_UNIFORM_SPHERE: {
if (size == 1'000)
ret = UniformSphere2D_1K();
else if (size == 10'000)
ret = UniformSphere2D_10K();
else if (size == 1'000'000)
ret = UniformSphere2D_1M();
else if (size == 10'000'000)
ret = UniformSphere2D_10M();
else
throw std::runtime_error("Invalid size to BenchmarkDS<2>(DS_UNIFORM_SPHERE)");
break;
}
case DS_VISUAL_VAR: {
ret = VisualVar2D_10M();
break;
}
default:
throw std::runtime_error("Invalid type to BenchmarkDS<2>");
}
if (shuffle)
return random_shuffle(ret);
else
return ret;
}
template <>
auto BenchmarkDS<3>(__attribute__((unused)) int size, DSType ds_type, bool shuffle) {
parlay::sequence<point<3>> ret;
switch (ds_type) {
case DS_GEO_LIFE: {
ret = GeoLife3D_24M();
break;
}
default:
throw std::runtime_error("Invalid type to BenchmarkDS<3>");
}
if (shuffle)
return random_shuffle(ret);
else
return ret;
}
template <>
auto BenchmarkDS<5>(int size, DSType ds_type, bool shuffle) {
parlay::sequence<point<5>> ret;
switch (ds_type) {
case DS_UNIFORM_FILL: {
ret = UniformFill5D_10M();
break;
}
case DS_VISUAL_VAR: {
if (size == 100'000)
ret = VisualVar5D_100K();
else if (size == 1'000'000)
ret = VisualVar5D_1M();
else if (size == 10'000'000)
ret = VisualVar5D_10M();
else
throw std::runtime_error("Invalid size to BenchmarkDS<5>(DS_VISUAL_VAR)");
break;
}
default:
throw std::runtime_error("Invalid type to BenchmarkDS<5>");
}
if (shuffle)
return random_shuffle(ret);
else
return ret;
}
template <>
auto BenchmarkDS<7>(__attribute__((unused)) int size, DSType ds_type, bool shuffle) {
parlay::sequence<point<7>> ret;
switch (ds_type) {
case DS_UNIFORM_FILL: {
ret = UniformFill7D_10M();
break;
}
case DS_VISUAL_VAR: {
ret = VisualVar7D_10M();
break;
}
case DS_HOUSE_HOLD: {
ret = HouseHold7D_2M();
break;
}
default:
throw std::runtime_error("Invalid type to BenchmarkDS<7>");
}
if (shuffle)
return random_shuffle(ret);
else
return ret;
}
template <>
auto BenchmarkDS<10>(__attribute__((unused)) int size, DSType ds_type, bool shuffle) {
parlay::sequence<point<10>> ret;
switch (ds_type) {
case DS_HT: {
ret = HT10D_1M();
break;
}
default:
throw std::runtime_error("Invalid type to BenchmarkDS<10>");
}
if (shuffle)
return random_shuffle(ret);
else
return ret;
}
template <>
auto BenchmarkDS<16>(__attribute__((unused)) int size, DSType ds_type, bool shuffle) {
parlay::sequence<point<16>> ret;
switch (ds_type) {
case DS_CHEM: {
ret = CHEM16D_4M();
break;
}
default:
throw std::runtime_error("Invalid type to BenchmarkDS<16>");
}
if (shuffle)
return random_shuffle(ret);
else
return ret;
}
// types
constexpr bool parallel = true;
constexpr bool coarsen = true;
template <int dim>
using COTree_t = CO_KdTree<dim, point<dim>, parallel, coarsen>;
template <int dim>
using BHLTree_t = BHL_KdTree<dim, point<dim>, parallel, coarsen>;
constexpr int NUM_TREES = 21;
constexpr int BUFFER_LOG2_SIZE = 10;
template <int dim>
using LogTree_t = LogTree<NUM_TREES, BUFFER_LOG2_SIZE, dim, point<dim>, parallel, coarsen>;
#endif // BENCHMARK_UTILS_H
|
rahulyesantharao/batch-dynamic-kdtree
|
utils/external/old_pargeo/include/common/IO.h
|
<filename>utils/external/old_pargeo/include/common/IO.h<gh_stars>1-10
// This code is part of the Problem Based Benchmark Suite (PBBS)
// Copyright (c) 2011 <NAME> and the PBBS team
//
// 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.
#pragma once
#include <iostream>
#include <fstream>
#include <string>
#include <string>
#include <cstring>
#include "../parlay/primitives.h"
#include "../parlay/parallel.h"
#include "../parlay/io.h"
#include "get_time.h"
namespace benchIO {
using namespace std;
using parlay::sequence;
using parlay::tabulate;
using parlay::make_slice;
auto is_space = [] (char c) {
switch (c) {
case '\r':
case '\t':
case '\n':
case 0:
case ' ' : return true;
default : return false;
}
};
// parallel code for converting a string to word pointers
// side effects string by setting to null after each word
template <class Seq>
parlay::sequence<char*> stringToWords(Seq &Str) {
size_t n = Str.size();
parlay::parallel_for(0, n, [&] (long i) {
if (is_space(Str[i])) Str[i] = 0;});
// mark start of words
auto FL = parlay::tabulate(n, [&] (long i) -> bool {
return (i==0) ? Str[0] : Str[i] && !Str[i-1];});
// offset for each start of word
auto Offsets = parlay::pack_index<long>(FL);
// pointer to each start of word
auto SA = parlay::tabulate(Offsets.size(), [&] (long j) -> char* {
return Str.begin() + Offsets[j];});
return SA;
}
inline int xToStringLen(parlay::sequence<char> const &a) { return a.size();}
inline void xToString(char* s, parlay::sequence<char> const &a) {
for (int i=0; i < (int)a.size(); i++) s[i] = a[i];}
inline int xToStringLen(__attribute__((unused)) long a) { return 21;}
inline void xToString(char* s, long a) { sprintf(s,"%ld",a);}
inline int xToStringLen(__attribute__((unused)) unsigned long a) { return 21;}
inline void xToString(char* s, unsigned long a) { sprintf(s,"%lu",a);}
inline uint xToStringLen(__attribute__((unused)) uint a) { return 12;}
inline void xToString(char* s, uint a) { sprintf(s,"%u",a);}
inline int xToStringLen(__attribute__((unused)) int a) { return 12;}
inline void xToString(char* s, int a) { sprintf(s,"%d",a);}
inline int xToStringLen(__attribute__((unused)) double a) { return 18;}
inline void xToString(char* s, double a) { sprintf(s,"%.11le", a);}
inline int xToStringLen(__attribute__((unused)) char* a) { return strlen(a)+1;}
inline void xToString(char* s, char* a) { sprintf(s,"%s",a);}
template <class A, class B>
inline int xToStringLen(pair<A,B> a) {
return xToStringLen(a.first) + xToStringLen(a.second) + 1;
}
template <class A, class B>
inline void xToString(char* s, pair<A,B> a) {
int l = xToStringLen(a.first);
xToString(s, a.first);
s[l] = ' ';
xToString(s+l+1, a.second);
}
template <class Seq>
parlay::sequence<char> seqToString(Seq const &A) {
size_t n = A.size();
auto L = parlay::tabulate(n, [&] (size_t i) -> long {
typename Seq::value_type x = A[i];
return xToStringLen(x)+1;});
size_t m;
std::tie(L,m) = parlay::scan(std::move(L));
parlay::sequence<char> B(m+1, (char) 0);
char* Bs = B.begin();
parlay::parallel_for(0, n-1, [&] (long i) {
xToString(Bs + L[i], A[i]);
Bs[L[i+1] - 1] = '\n';
});
xToString(Bs + L[n-1], A[n-1]);
Bs[m] = Bs[m-1] = '\n';
parlay::sequence<char> C = parlay::filter(B, [&] (char c) {return c != 0;});
C[C.size()-1] = 0;
return C;
}
template <class T>
void writeSeqToStream(ofstream& os, parlay::sequence<T> const &A) {
size_t bsize = 10000000;
size_t offset = 0;
size_t n = A.size();
while (offset < n) {
// Generates a string for a sequence of size at most bsize
// and then wrties it to the output stream
parlay::sequence<char> S = seqToString(A.cut(offset, min(offset + bsize, n)));
os.write(S.begin(), S.size()-1);
offset += bsize;
}
}
template <class T>
int writeSeqToFile(string header,
parlay::sequence<T> const &A,
char const *fileName) {
auto a = A[0];
//xToStringLena(a);
ofstream file (fileName, ios::out | ios::binary);
if (!file.is_open()) {
std::cout << "Unable to open file: " << fileName << std::endl;
return 1;
}
file << header << endl;
writeSeqToStream(file, A);
file.close();
return 0;
}
template <class T1, class T2>
int write2SeqToFile(string header,
parlay::sequence<T1> const &A,
parlay::sequence<T2> const &B,
char const *fileName) {
ofstream file (fileName, ios::out | ios::binary);
if (!file.is_open()) {
std::cout << "Unable to open file: " << fileName << std::endl;
return 1;
}
file << header << endl;
writeSeqToStream(file, A);
writeSeqToStream(file, B);
file.close();
return 0;
}
parlay::sequence<char> readStringFromFile(char const *fileName) {
ifstream file (fileName, ios::in | ios::binary | ios::ate);
if (!file.is_open()) {
std::cout << "Unable to open file: " << fileName << std::endl;
abort();
}
long end = file.tellg();
file.seekg (0, ios::beg);
long n = end - file.tellg();
parlay::sequence<char> bytes(n, (char) 0);
file.read (bytes.begin(), n);
file.close();
return bytes;
}
string intHeaderIO = "sequenceInt";
template <class T>
int writeIntSeqToFile(parlay::sequence<T> const &A, char const *fileName) {
return writeSeqToFile(intHeaderIO, A, fileName);
}
sequence<sequence<char>> get_tokens(char const *fileName) {
// parlay::internal::timer t("get_tokens");
// auto S = parlay::chars_from_file(fileName);
auto S = parlay::file_map(fileName);
// t.next("file map");
auto r = parlay::tokens(S, benchIO::is_space);
// t.next("tokens");
return r;
}
template <class T>
parlay::sequence<T> readIntSeqFromFile(char const *fileName) {
auto W = get_tokens(fileName);
string header(W[0].begin(),W[0].end());
if (header != intHeaderIO) {
cout << "readIntSeqFromFile: bad input" << endl;
abort();
}
long n = W.size()-1;
auto A = parlay::tabulate(n, [&] (long i) -> T {
return parlay::chars_to_long(W[i+1]);});
return A;
}
};
|
rahulyesantharao/batch-dynamic-kdtree
|
test/binary-heap-layout/BHL2DStructureTest.h
|
#ifndef TEST_BINARYHEAPLAYOUT_BHLSTRUCTURE2D_H
#define TEST_BINARYHEAPLAYOUT_BHLSTRUCTURE2D_H
#include <gtest/gtest.h>
#include "common/geometryIO.h"
#include <kdtree/binary-heap-layout/bhlkdtree.h>
#include <kdtree/shared/macro.h>
#include "../shared/BasicStructure.h"
template <typename Tree>
class BHL2DStructureTest : public BasicStructure2D<Tree> {
public:
static const int DIM = 2;
};
TYPED_TEST_SUITE_P(BHL2DStructureTest);
TYPED_TEST_P(BHL2DStructureTest, LayoutSize2) {
// create the tree
auto tree = this->CONSTRUCT_2D_SIZE_2();
auto root = tree.root(); // get the root to verify the layout
// Check node types
ASSERT_FALSE(root[0].isLeaf());
ASSERT_TRUE(root[1].isLeaf());
ASSERT_TRUE(root[2].isLeaf());
// Check point counts
ASSERT_EQ(root[0].countPoints(), 2);
ASSERT_EQ(root[1].countPoints(), 1);
ASSERT_EQ(root[2].countPoints(), 1);
// Check memory values
ASSERT_EQ(root[0].getSplitDimension(), 0);
//#ifdef USE_MEDIAN_SELECTION
ASSERT_EQ(root[0].getSplitValue(), 1.0);
//#else
// ASSERT_EQ(root[0].getSplitValue(), 0.5);
//#endif
ASSERT_EQ(root[1].getValues().size(), 1);
ASSERT_EQ(root[1].getValues()[0], this->POINT_ARR_2[0]);
ASSERT_EQ(tree.getNodeValueIdx(&root[1]), std::make_pair(0, 1));
ASSERT_EQ(root[2].getValues().size(), 1);
ASSERT_EQ(root[2].getValues()[0], this->POINT_ARR_2[1]);
ASSERT_EQ(tree.getNodeValueIdx(&root[2]), std::make_pair(1, 2));
// Check memory layout
ASSERT_EQ(root->getLeft(), root + 1);
ASSERT_EQ(root->getRight(), root + 2);
}
TYPED_TEST_P(BHL2DStructureTest, LayoutSize8) {
// create the tree
auto tree = this->CONSTRUCT_2D_SIZE_8();
auto root = tree.root(); // get the root to verify the layout
// Check node types
/* 0
* 1 2
* 3 4 5 6
* 7 8 9 A B C D E
*/
ASSERT_FALSE(root[0].isLeaf());
ASSERT_FALSE(root[1].isLeaf());
ASSERT_FALSE(root[2].isLeaf());
for (int i = 3; i < 7; i++) {
ASSERT_FALSE(root[i].isLeaf());
}
for (int i = 7; i < 15; i++) {
ASSERT_TRUE(root[i].isLeaf());
}
// Check point counts
ASSERT_EQ(root[0].countPoints(), 8);
ASSERT_EQ(root[1].countPoints(), 4);
ASSERT_EQ(root[2].countPoints(), 4);
for (int i = 3; i < 7; i++) {
ASSERT_EQ(root[i].countPoints(), 2);
}
for (int i = 7; i < 15; i++) {
ASSERT_EQ(root[i].countPoints(), 1);
}
// Check memory values - serial case always uses median selection
//#ifdef USE_MEDIAN_SELECTION
double split_values[7] = {4, 2, 6, 1, 3, 5, 7};
//#else
// double split_values[7] = {3.5, 1.5, 5.5, 0.5, 2.5, 4.5, 6.5};
//#endif
ASSERT_EQ(root[0].getSplitDimension(), 0);
ASSERT_EQ(root[0].getSplitValue(), split_values[0]);
ASSERT_EQ(root[1].getSplitDimension(), 1);
ASSERT_EQ(root[1].getSplitValue(), split_values[1]);
ASSERT_EQ(root[2].getSplitDimension(), 1);
ASSERT_EQ(root[2].getSplitValue(), split_values[2]);
ASSERT_EQ(root[3].getSplitDimension(), 0);
ASSERT_EQ(root[3].getSplitValue(), split_values[3]);
ASSERT_EQ(root[4].getSplitDimension(), 0);
ASSERT_EQ(root[4].getSplitValue(), split_values[4]);
ASSERT_EQ(root[5].getSplitDimension(), 0);
ASSERT_EQ(root[5].getSplitValue(), split_values[5]);
ASSERT_EQ(root[6].getSplitDimension(), 0);
ASSERT_EQ(root[6].getSplitValue(), split_values[6]);
for (int i = 0; i < 8; i++) {
ASSERT_EQ(root[i + 7].getValues().size(), 1);
ASSERT_EQ(root[i + 7].getValues()[0], this->POINT_ARR_8[i]);
ASSERT_EQ(tree.getNodeValueIdx(&root[i + 7]), std::make_pair(i, i + 1));
}
// Check memory layout
for (int i = 0; i < 7; i++) {
ASSERT_EQ(root[i].getLeft(), root + 2 * i + 1);
ASSERT_EQ(root[i].getRight(), root + 2 * i + 2);
}
}
REGISTER_TYPED_TEST_SUITE_P(BHL2DStructureTest, LayoutSize2, LayoutSize8);
#endif // TEST_BINARYHEAPLAYOUT_BHLSTRUCTURE2D_H
|
rahulyesantharao/batch-dynamic-kdtree
|
include/kdtree/cache-oblivious/utils.h
|
<filename>include/kdtree/cache-oblivious/utils.h
#ifndef COKD_UTILS_H
#define COKD_UTILS_H
#include "parlay/parallel.h"
#include "parlay/sequence.h"
#include "parlay/primitives.h"
#include "../shared/utils.h"
void funnelSort() {
// TODO: cache-oblivious sorting
}
// kd-tree structure
template <bool coarsen>
inline int numLevels(int num_leaves) {
if (coarsen) num_leaves = (num_leaves + (CLUSTER_SIZE - 1)) / CLUSTER_SIZE;
return 1 + (int)std::ceil(std::log2(num_leaves)); // number of levels
}
inline int numNodesTop(int num_levels) { return (1 << num_levels) - 1; }
inline int numNodesBottom(size_t num_points) { return 2 * num_points - 1; }
inline bool buildTopInParallel(__attribute__((unused)) int num_levels, size_t num_points) {
if (num_points < CO_TOP_BUILD_BASE_CASE) return false;
return true;
}
inline bool buildBottomInParallel(__attribute__((unused)) int num_levels, size_t num_points) {
if (num_points < CO_BOTTOM_BUILD_BASE_CASE) return false;
return true;
}
inline int hyperCeiling(int n) { return 1 << (int)std::ceil(std::log2(n)); }
inline int bottomNumLevels(int total_num_levels) {
return hyperCeiling((total_num_levels + 1) / 2);
}
// compute split points in closed form; see memoized version below
std::vector<size_t> computeSplitPoints(int num_levels, int num_leaves) {
// roughly: the split_points[level] is the order in which elements are placed into this level
auto num_bottom = (1 << (num_levels));
std::vector<size_t> split_points(num_bottom + 1);
split_points[0] = 0;
for (int level = 0; level < num_levels; level++) {
auto offset = (1 << (num_levels - 1 - level)) - 1;
auto adder = (1 << (num_levels - level));
for (int node = 0; node < (1 << level); node++) {
auto cur_index = adder * node + offset + 1;
auto left_endpoint = (node == 0) ? 0 : split_points[cur_index - (offset + 1)];
auto right_endpoint =
(node == (1 << level) - 1) ? num_leaves : split_points[cur_index + (offset + 1)];
split_points[cur_index] = (left_endpoint + right_endpoint) / 2;
}
}
split_points[num_bottom] = num_leaves;
return split_points;
}
std::vector<std::vector<size_t>> split_points;
void initializeSplitPoints(int num_levels) {
assert(num_levels > 1);
if (num_levels < (int)split_points.size()) return; // already done
int level = (int)split_points.size(); // the next level to start populating (because of the +1)
split_points.resize(num_levels + 1); // allocate space for the levels
// base case
if (level == 0) {
split_points[0] = {1};
level++;
}
// Note: this can be computed in closed-form, but it seems like memoizing makes sense?
for (; level <= num_levels; level++) {
auto num_leaves = (1 << level);
split_points[level].resize(num_leaves);
for (int leaf = 0; leaf < num_leaves; leaf++) {
split_points[level][leaf] =
split_points[level - 1][leaf / 2] + ((leaf % 2 == 0) ? (1 << (level - 1)) : 0);
}
}
}
// compute left indices of children at a given level with a given remainder
parlay::sequence<size_t> computeLeftEndpoints(int num_levels,
size_t size_per_leaf,
size_t remainder) {
assert(num_levels < (int)split_points.size());
parlay::sequence<size_t> to_sum(1 + split_points[num_levels].size());
to_sum[0] = 0;
parlay::parallel_for(0, split_points[num_levels].size(), [&](size_t i) {
to_sum[i + 1] = size_per_leaf + ((split_points[num_levels][i] <= remainder) ? 1 : 0);
});
// to_sum -> holds 0 and then the number of points in each child
// - inclusive prefix sum - tells us endpoints for the children
return parlay::scan_inclusive(to_sum);
}
// compute left indices of children at a given level with a given remainder
parlay::sequence<size_t> computeBottomChildSizes(int num_levels,
size_t size_per_leaf,
size_t remainder) {
assert(num_levels < (int)split_points.size());
parlay::sequence<size_t> to_sum(split_points[num_levels].size());
parlay::parallel_for(0, split_points[num_levels].size(), [&](size_t i) {
to_sum[i] =
numNodesBottom(size_per_leaf + ((split_points[num_levels][i] <= remainder) ? 1 : 0));
});
// to_sum -> holds the number of nodes in each child
// - prefix sum - tells us where each child starts in memory
return parlay::scan(to_sum).first;
}
std::vector<std::vector<size_t>> child_indices = {{}};
// child_indices[n]: the indices of the children of a tree with n levels, offset from the root
// -> n levels => 2^{n-1} children, 2^n-1 total nodes
void initializeChildIndices(int num_levels) {
assert(num_levels > 1);
if (num_levels < (int)child_indices.size()) return; // already done
int level = (int)child_indices.size(); // the next level to start populating (because of the +1)
child_indices.resize(num_levels + 1); // allocate space for the levels
// base case
if (level == 1) { // first time initializing
child_indices[1] = {0};
level++;
}
for (; level <= num_levels; level++) {
// if(child_indices[level].size() > 0) continue; // skip completed
auto bottom_num_levels = bottomNumLevels(level);
auto top_num_levels = level - bottom_num_levels;
auto top_tree_size = (1 << (top_num_levels)) - 1;
auto bottom_tree_size = (1 << (bottom_num_levels)) - 1;
auto num_bottom_trees = 1 << (top_num_levels);
for (int subtree = 0; subtree < num_bottom_trees; subtree++) {
for (const auto& child_idx : child_indices[bottom_num_levels]) {
child_indices[level].push_back(top_tree_size + subtree * bottom_tree_size + child_idx);
}
}
}
}
static bool initialized = false;
void initialize(__attribute__((unused)) int num_levels) {
if (!initialized) {
initializeChildIndices(24);
initializeSplitPoints(24);
initialized = true;
}
}
#endif // COKD_UTILS_H
|
rahulyesantharao/batch-dynamic-kdtree
|
test/shared/BasicStructure.h
|
#ifndef TEST_SHARED_BASICSTRUCTURE2D_H
#define TEST_SHARED_BASICSTRUCTURE2D_H
#include <gtest/gtest.h>
#include "common/geometryIO.h"
template <class T>
static auto KEEP_EVEN(const parlay::sequence<T>& seq) {
// construct the points to delete
auto num_even = (seq.size() + 1) / 2;
parlay::sequence<T> to_remove(num_even);
for (size_t i = 0; i < num_even; i++) {
to_remove[i] = seq[2 * i];
}
return to_remove;
}
template <class T>
static auto KEEP_ODD(const parlay::sequence<T>& seq) {
// construct the points to delete
auto num_odd = (seq.size()) / 2;
parlay::sequence<T> to_remove(num_odd);
for (size_t i = 0; i < num_odd; i++) {
to_remove[i] = seq[2 * i + 1];
}
return to_remove;
}
template <class Tree>
class BasicStructure2D : public ::testing::Test {
static const int dim = 2;
public:
static constexpr double POINT_ARR_2[2][2] = {{0, 0}, {1, 1}};
static constexpr double POINT_ARR_8[8][2] = {
{0, 0}, {1, 1}, {2, 2}, {3, 3}, {4, 4}, {5, 5}, {6, 6}, {7, 7}};
static Tree CONSTRUCT_2D_TREE(const double point_array[][2], int num_points) {
std::vector<point<dim>> point_vec(num_points);
for (int i = 0; i < num_points; i++)
point_vec[i] = point<dim>(point_array[i]);
parlay::sequence<point<dim>> points(point_vec.begin(), point_vec.end());
return Tree(points);
}
static Tree CONSTRUCT_2D_SIZE_2() {
constexpr int tree_height = 2;
constexpr int num_points = 1 << (tree_height - 1);
return CONSTRUCT_2D_TREE(POINT_ARR_2, num_points);
}
static Tree CONSTRUCT_2D_SIZE_8() {
constexpr int tree_height = 4;
constexpr int num_points = 1 << (tree_height - 1);
return CONSTRUCT_2D_TREE(POINT_ARR_8, num_points);
}
static parlay::sequence<point<dim>> RESOURCES_1000() {
const char* test_file = "../resources/2d-UniformInSphere-1k.pbbs";
int check_dim = readDimensionFromFile(test_file);
if (check_dim != dim) throw std::runtime_error("Invalid input file!");
return readPointsFromFile<point<dim>>(test_file);
}
static Tree CONSTRUCT_RESOURCES_1000() {
const char* test_file = "../resources/2d-UniformInSphere-1k.pbbs";
int check_dim = readDimensionFromFile(test_file);
if (check_dim != dim) throw std::runtime_error("Invalid input file!");
parlay::sequence<point<dim>> points = readPointsFromFile<point<dim>>(test_file);
return Tree(points);
}
static Tree CONSTRUCT_RESOURCES_1000_EVEN() {
const char* test_file = "../resources/2d-UniformInSphere-1k.pbbs";
int check_dim = readDimensionFromFile(test_file);
if (check_dim != dim) throw std::runtime_error("Invalid input file!");
parlay::sequence<point<dim>> points = readPointsFromFile<point<dim>>(test_file);
const auto to_insert = KEEP_EVEN(points);
Tree ret(10);
ret.insert(to_insert.cut(0, to_insert.size()));
return ret;
}
};
#endif // TEST_SHARED_BASICSTRUCTURE2D_H
|
rahulyesantharao/batch-dynamic-kdtree
|
include/kdtree/shared/macro.h
|
<reponame>rahulyesantharao/batch-dynamic-kdtree<gh_stars>1-10
#ifndef KDTREE_SHARED_MACRO_H
#define KDTREE_SHARED_MACRO_H
//#define PRINT_CONFIG
//#define PRINT_LOGTREE_TIMINGS
//#define PRINT_DKNN_TIMINGS
//#define PRINT_INSERT_TIMINGS
//#define PRINT_DELETE_TIMINGS
//#define PRINT_KDTREE_TIMINGS
//#define PRINT_COKDTREE_TIMINGS
//#define USE_MEDIAN_SELECTION
//#define PRINT_PARALLEL_PARTITION_TIMINGS
//#define ERASE_SEARCH_TIMES
//#define ALL_USE_BLOOM
//#define LOGTREE_USE_BLOOM
//#define BLOOM_FILTER_BUILD_COPY
#define PARTITION_OBJECT_MEDIAN 0
#define PARTITION_SPATIAL_MEDIAN 1
#ifndef PARTITION_TYPE
#define PARTITION_TYPE PARTITION_OBJECT_MEDIAN
#endif
// DUAL KNN MODE
#define DKNN_ATOMIC_LEAF 0
#define DKNN_NONATOMIC_LEAF 1
#define DKNN_ARRAY 2
#ifndef DUAL_KNN_MODE // default if not defined in cmake
#define DUAL_KNN_MODE DKNN_NONATOMIC_LEAF
#endif
// LOGTREE BUFFER
#define BHL_BUFFER 0
#define ARR_BUFFER 1
#define LOGTREE_BUFFER BHL_BUFFER
// LEAF CLUSTER SIZE
#ifndef CLUSTER_SIZE
#define CLUSTER_SIZE 16
#endif
// SERIAL BASE CASES
#ifndef ERASE_BASE_CASE
#define ERASE_BASE_CASE 1000
#endif
#ifndef RANGEQUERY_BASE_CASE
#define RANGEQUERY_BASE_CASE 1000
#endif
#ifndef BOUNDINGBOX_BASE_CASE
#define BOUNDINGBOX_BASE_CASE 1000
#endif
#ifndef DUALKNN_BASE_CASE
#define DUALKNN_BASE_CASE 1000
#endif
#ifndef CO_TOP_BUILD_BASE_CASE
#define CO_TOP_BUILD_BASE_CASE 1000
#endif
#ifndef CO_BOTTOM_BUILD_BASE_CASE
#define CO_BOTTOM_BUILD_BASE_CASE 1000
#endif
#ifndef BHL_BUILD_BASE_CASE
#define BHL_BUILD_BASE_CASE 1000
#endif
#ifdef PRINT_CONFIG
#include <iostream>
void print_config() {
std::cout << "DUAL_KNN_MODE = " << DUAL_KNN_MODE << ";\n"
<< "PARTITION_TYPE = " << PARTITION_TYPE << ";\n"
<< "LOGTREE_BUFFER = " << LOGTREE_BUFFER << ";\n"
<< "CLUSTER_SIZE = " << CLUSTER_SIZE << ";\n"
<< "ERASE_BASE_CASE = " << ERASE_BASE_CASE << ";\n"
<< "RANGEQUERY_BASE_CASE = " << RANGEQUERY_BASE_CASE << ";\n"
<< "BOUNDINGBOX_BASE_CASE = " << BOUNDINGBOX_BASE_CASE << ";\n"
<< "DUALKNN_BASE_CASE = " << DUALKNN_BASE_CASE << ";\n"
<< "CO_TOP_BUILD_BASE_CASE = " << CO_TOP_BUILD_BASE_CASE << ";\n"
<< "CO_BOTTOM_BUILD_BASE_CASE = " << CO_BOTTOM_BUILD_BASE_CASE << ";\n"
<< "BHL_BUILD_BASE_CASE = " << BHL_BUILD_BASE_CASE << std::endl;
}
#else
void print_config() {}
#endif
#endif // KDTREE_SHARED_MACRO_H
|
rahulyesantharao/batch-dynamic-kdtree
|
include/kdtree/shared/utils.h
|
#ifndef KDTREE_SHARED_UTILS_H
#define KDTREE_SHARED_UTILS_H
#include "parlay/parallel.h"
#include "parlay/sequence.h"
#include "parlay/primitives.h"
#include "parlay/monoid.h"
#include "parlay/delayed_sequence.h"
#include "macro.h"
#ifdef DEBUG
#define DEBUG_MSG(str) \
do { \
std::cout << str << std::endl; \
} while (false)
#else
#define DEBUG_MSG(str) \
do { \
} while (false)
#endif
// MEDIAN FINDING FUNCTIONS ------------------------------------------------------------------------
// convention: always puts more on the right hand side (if odd number of items)
// TODO: think about cache-obliviousness?
template <class objT>
static inline int split_n(const parlay::slice<objT *, objT *> &items) {
return items.size() / 2;
}
template <class objT, bool select = false>
static inline double split_val(const parlay::slice<objT *, objT *> &items, int dimension) {
auto split_point = split_n(items);
if (select) { // only have split_point in place, not element before, so can only use it.
return items[split_point].coordinate(dimension);
} else {
return (items[split_point - 1].coordinate(dimension) +
items[split_point].coordinate(dimension)) /
2.0;
}
}
// Implementations: rearrange [items] so that the median is in the middle ---------------------
// sort based implementation
template <class objT, bool parallel>
static inline void medianPartitionSort(parlay::slice<objT *, objT *> &items, int dimension) {
auto compare = [dimension](const objT &l, const objT &r) {
return l.coordinate(dimension) < r.coordinate(dimension);
};
if (parallel) {
parlay::sort_inplace(items, compare);
} else {
std::sort(items.begin(), items.end(), compare);
}
}
// serial select based implementation
template <class objT>
static inline void serialMedianPartitionSelect(parlay::slice<objT *, objT *> &items,
int dimension) {
auto compare = [dimension](const objT &l, const objT &r) {
return l.coordinate(dimension) < r.coordinate(dimension);
};
auto split_point = split_n(items);
std::nth_element(items.begin(), items.begin() + split_point, items.end(), compare);
}
// Top level functions ------------------
// object median
template <class objT>
double parallelMedianPartition(parlay::slice<objT *, objT *> items, int dimension) {
#ifdef USE_MEDIAN_SELECTION
serialMedianPartitionSelect<objT>(items, dimension); // selection-based version
return split_val<objT, true>(items, dimension);
#else
medianPartitionSort<objT, true>(items, dimension); // sort-based version
return split_val(items, dimension);
#endif
}
template <class objT>
double serialMedianPartition(parlay::slice<objT *, objT *> items, int dimension) {
//#ifdef USE_MEDIAN_SELECTION
serialMedianPartitionSelect<objT>(items, dimension); // selection-based version
return split_val<objT, true>(items, dimension);
//#else
// medianPartitionSort<objT, false>(items, dimension); // sort-based version
// return split_val(items, dimension);
//#endif
}
// PARTITION FUNCTIONS -----------------------------------------------------------------------------
template <class objT>
auto serialPartition(parlay::slice<objT *, objT *> points, int dimension, double value) {
auto comp_lambda = [dimension, value](const objT &o) { return o.coordinate(dimension) < value; };
auto ret_it = std::partition(points.begin(), points.end(), comp_lambda);
return ret_it - points.begin();
}
template <class objT>
auto parallelPartition(parlay::slice<objT *, objT *> points,
parlay::slice<bool *, bool *> flags,
int dimension,
double value) {
// construct partition flags (split_two puts false first)
#ifdef PRINT_PARALLEL_PARTITION_TIMINGS
bool print_timings = (points.size() == 2000000);
timer t("parallelPartition");
auto mtime = [&](const std::string &s) {
if (print_timings) t.report(t.get_next(), s);
};
#endif
parlay::parallel_for(0, points.size(), [dimension, value, points, flags](size_t i) {
if (points[i].coordinate(dimension) < value)
flags[i] = false;
else
flags[i] = true;
});
#ifdef PRINT_PARALLEL_PARTITION_TIMINGS
mtime("flags set");
#endif
// perform partition and copy back to original points array
const auto &[res, split_pt] = parlay::internal::split_two(points, flags);
#ifdef PRINT_PARALLEL_PARTITION_TIMINGS
mtime("split2: " + std::to_string(res.size()));
#endif
const size_t num_blocks = parlay::num_workers() * 8;
const size_t block_size = (points.size() + num_blocks - 1) / num_blocks;
parlay::parallel_for(0, num_blocks, [&](size_t i) {
auto start_idx = i * block_size;
auto end_idx = std::min((i + 1) * block_size, points.size());
for (size_t j = start_idx; j < end_idx; j++)
points[j] = res[j];
});
#ifdef PRINT_PARALLEL_PARTITION_TIMINGS
mtime("copyback");
#endif
return split_pt;
}
bool eraseInParallel(size_t num_points) { return num_points >= ERASE_BASE_CASE; }
template <class TT>
struct minmaxm {
using T = std::pair<TT, TT>;
minmaxm() : identity(T(parlay::highest<TT>(), parlay::lowest<TT>())) {}
T identity;
static T f(T a, T b) { return T((std::min)(a.first, b.first), (std::max)(a.second, b.second)); }
};
// other partition functions
template <class objT>
double parallelSpatialPartition(parlay::slice<objT *, objT *> items,
parlay::slice<bool *, bool *> flags,
int dimension,
size_t &split_pt) {
// compute median
// construct sequence of just the relevant coordinates
auto f = parlay::delayed_seq<std::pair<double, double>>(items.size(), [&](size_t i) {
return std::make_pair<double, double>(items[i].coordinate(dimension),
items[i].coordinate(dimension));
});
// find min, max - could do this without delayed_seq if we had a full reduce func (different
// element, return type)
auto [imin, imax] = parlay::reduce(f, minmaxm<double>());
auto imed = (imin + imax) / 2;
// partition
split_pt = parallelPartition(items, flags, dimension, imed);
return imed;
}
template <class objT>
double serialSpatialPartition(parlay::slice<objT *, objT *> items,
int dimension,
size_t &split_pt) {
// compute median
double imin = std::numeric_limits<double>::max();
double imax = std::numeric_limits<double>::lowest();
assert(imax < -2000);
for (const auto &pt : items) {
double val = pt.coordinate(dimension);
imin = std::min(imin, val);
imax = std::max(imax, val);
}
auto imed = (imin + imax) / 2;
// partition
split_pt = serialPartition(items, dimension, imed);
// if (split_pt == items.size()) {
// std::cout << "PROBLEM" << std::endl;
// std::cout << "(split_dim, imin, imax, imed, items.size()) = (" << dimension << ", " << imin
//<< ", " << imax << ", " << imed << ", " << items.size() << ")" << std::endl;
// std::vector<double> vals;
// for (const auto &pt : items) {
// vals.push_back(pt.coordinate(dimension));
//}
// std::sort(vals.begin(), vals.end());
// for (const auto &val : vals) {
// std::cout << val << ", ";
//}
// std::cout << std::endl;
// assert(false);
//}
return imed;
}
#endif // KDTREE_SHARED_UTILS_H
|
valandro/pdp-ufrgs
|
ex03/pi.c
|
#include <omp.h>
#include <stdio.h>
#include <stdlib.h>
#define MAX_THREADS 4
static long steps = 1000000000;
double step;
int main (int argc, const char *argv[]) {
int i,j;
double x;
double pi, sum = 0.0;
double start, delta;
step = 1.0/(double) steps;
for (j=1; j<= MAX_THREADS; j++) {
printf(" running on %d threads: ", j);
omp_set_num_threads(j);
sum = 0.0;
double start = omp_get_wtime();
#pragma omp parallel for reduction(+:sum) private(x)
for (i=0; i < steps; i++) {
x = (i+0.5)*step;
sum += 4.0 / (1.0+x*x);
}
pi = step * sum;
delta = omp_get_wtime() - start;
printf("PI = %.16g computed in %.4g seconds\n", pi, delta);
}
}
|
valandro/pdp-ufrgs
|
ex03/matrix.c
|
#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#define MAX_THREADS 3
void mm_omp(double *A, double *B, double *C, int n)
{
{
int i, j, k;
#pragma omp parallel for private(i,j,k) shared(A,B,C)
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
double dot = 0;
#pragma omp parallel for reduction(+:dot) private(k)
for (k = 0; k < n; k++) {
dot += A[i*n+k]*B[k*n+j];
}
C[i*n+j] = dot;
}
}
}
}
int main() {
int i, n;
double *A, *B, *C, dtime;
n = 750;
A = (double*)malloc(sizeof(double)*n*n);
B = (double*)malloc(sizeof(double)*n*n);
C = (double*)malloc(sizeof(double)*n*n);
for(i=0; i<n*n; i++) {
A[i] = rand()/RAND_MAX;
B[i] = rand() / RAND_MAX;
}
dtime = omp_get_wtime();
omp_set_num_threads(MAX_THREADS);
mm_omp(A,B,C, n);
dtime = omp_get_wtime() - dtime;
printf("%f\n", dtime);
return 0;
}
|
framefreeze/HangDriver
|
GUI_Qt/mainwindow.h
|
<reponame>framefreeze/HangDriver
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QPaintEvent>
#include <QTimer>
#include <QPainter>
#include <QPixmap>
#include <QLabel>
#include <QImage>
#include <opencv2/opencv.hpp>
using namespace cv;
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
public slots:
void open_cam();
void updata_img();
private:
Ui::MainWindow *ui;
QTimer cam_timer;
VideoCapture camera;
Mat frame, fgps;
QImage display, fgps_q;
};
#endif // MAINWINDOW_H
|
ChenThree/GraspNetReal
|
pointnet2/_ext_src/include/cylinder_query.h
|
<gh_stars>1-10
// Author: chenxi-wang
#pragma once
#include <torch/extension.h>
at::Tensor cylinder_query(at::Tensor new_xyz, at::Tensor xyz, at::Tensor rot, const float radius, const float hmin, const float hmax,
const int nsample);
|
ChenThree/GraspNetReal
|
knn/src/cpu/vision.h
|
#pragma once
#include <torch/extension.h>
void knn_cpu(float* ref_dev, int ref_width,
float* query_dev, int query_width,
int height, int k, float* dist_dev, long* ind_dev, long* ind_buf);
|
ng-labo/sqlite-maxminddb
|
sqlite3_maxminddb.c
|
<reponame>ng-labo/sqlite-maxminddb
/*
**
** This SQLite extension implements asn(), org(), cc() functions.
**
** ipmask(), ip6mask() help you translate to prefixes easily.
*/
#include <sqlite3ext.h>
SQLITE_EXTENSION_INIT1
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#ifdef _WIN32
#define HOMEENVNAME "HOMEPATH"
#define PATH_MAX 256
#include "Ws2tcpip.h"
#else
#define HOMEENVNAME "HOME"
#include <linux/limits.h>
#include <arpa/inet.h>
#endif
// maxmind/libmaxminddb
#include "maxminddb.h"
#define MSG_NOTINITIALIZED "sqlite-maxminddb is not initialized"
#ifdef _WIN32
#define MSG_ERRGETADDRINFO "Error from getaddrinfo for %s - %ws"
#else
#define MSG_ERRGETADDRINFO "Error from getaddrinfo for %s - %s"
#endif
#define MSG_ERRLIBMAXMIND "Got an error from libmaxminddb: %s"
#define KW_ASN "autonomous_system_number"
#define KW_ORG "autonomous_system_organization"
#define KW_COUNTRY "country"
#define KW_ISOCODE "iso_code"
bool initialized = false;
MMDB_s mmdb_asn;
MMDB_s mmdb_cnt;
static bool check_lookup(sqlite3_context *context, const char *ipaddress, const int gai_error, const int mmdb_error) {
if (0 != gai_error) {
char msg[4096];
snprintf(msg, 4095, MSG_ERRGETADDRINFO,
ipaddress, gai_strerror(gai_error));
sqlite3_result_error(context, msg, -1);
return true;
}
if (MMDB_SUCCESS != mmdb_error) {
char msg[4096];
snprintf(msg, 4095, MSG_ERRLIBMAXMIND,
MMDB_strerror(mmdb_error));
sqlite3_result_error(context, msg, -1);
return true;
}
return false;
}
static void lookup_asn_org(sqlite3_context *context, const char* ipaddress, const char* keyword) {
assert(keyword != NULL);
int gai_error, mmdb_error;
MMDB_lookup_result_s result =
MMDB_lookup_string(&mmdb_asn, ipaddress, &gai_error, &mmdb_error);
if(check_lookup(context, ipaddress, gai_error, mmdb_error)){
return;
}
char zOut[4096];
zOut[0] = '\0';
if (result.found_entry) {
MMDB_entry_data_s entry_data;
int status =
MMDB_get_value(&result.entry, &entry_data,
keyword, NULL);
if (MMDB_SUCCESS != status) {
//sqlite3_result_error(context, "MMDB_get_value", -1);
//return;
}
else if (entry_data.has_data) {
if(entry_data.type==MMDB_DATA_TYPE_UINT32){
snprintf(zOut, 11, "%u", entry_data.uint32 );
}
if(entry_data.type==MMDB_DATA_TYPE_BYTES||
entry_data.type==MMDB_DATA_TYPE_UTF8_STRING){
size_t m = 4095;
if(entry_data.data_size<m) m = entry_data.data_size + 1;
snprintf(zOut, entry_data.data_size+1, "%s", (const char*) entry_data.bytes );
}
}
}
sqlite3_result_text(context, (char*) zOut, strlen(zOut), SQLITE_TRANSIENT);
}
static void lookup_country(sqlite3_context *context, const char* ipaddress) {
int gai_error, mmdb_error;
MMDB_lookup_result_s result =
MMDB_lookup_string(&mmdb_cnt, ipaddress, &gai_error, &mmdb_error);
if(check_lookup(context, ipaddress, gai_error, mmdb_error)){
return;
}
char zOut[4096];
zOut[0] = '\0';
if (result.found_entry) {
MMDB_entry_data_s entry_data;
int status =
MMDB_get_value(&result.entry, &entry_data,
KW_COUNTRY, KW_ISOCODE, NULL);
if (MMDB_SUCCESS != status) {
}
else if (entry_data.has_data) {
if(entry_data.type==MMDB_DATA_TYPE_BYTES||
entry_data.type==MMDB_DATA_TYPE_UTF8_STRING){
size_t m = 4095;
if(entry_data.data_size<m) m = entry_data.data_size + 1;
snprintf(zOut, entry_data.data_size+1,
"%s", (const char*) entry_data.bytes );
}
}
}
sqlite3_result_text(context, (char*) zOut, strlen(zOut), SQLITE_TRANSIENT);
}
static void asn_impl(
sqlite3_context *context,
int argc,
sqlite3_value **argv)
{
const char *zIn;
assert(argc == 1);
if(!initialized){
sqlite3_result_error(context, MSG_NOTINITIALIZED, -1);
return;
}
if (sqlite3_value_type(argv[0]) == SQLITE_NULL)
{
return;
}
zIn = (const char*)sqlite3_value_text(argv[0]);
// call sqlite3_result_text or sqlite3_result_error
lookup_asn_org(context, zIn, KW_ASN);
}
static void org_impl(
sqlite3_context *context,
int argc,
sqlite3_value **argv)
{
const char *zIn;
assert(argc == 1);
if(!initialized){
sqlite3_result_error(context, MSG_NOTINITIALIZED, -1);
return;
}
if (sqlite3_value_type(argv[0]) == SQLITE_NULL)
{
return;
}
zIn = (const char*) sqlite3_value_text(argv[0]);
// call sqlite3_result_text or sqlite3_result_error
lookup_asn_org(context, zIn, KW_ORG);
}
static void cc_impl(
sqlite3_context *context,
int argc,
sqlite3_value **argv)
{
const char *zIn;
assert(argc == 1);
if(!initialized){
sqlite3_result_error(context, MSG_NOTINITIALIZED, -1);
return;
}
if (sqlite3_value_type(argv[0]) == SQLITE_NULL)
{
return;
}
zIn = (const char*) sqlite3_value_text(argv[0]);
// call sqlite3_result_text or sqlite3_result_error
lookup_country(context, zIn);
}
static void ipmask(sqlite3_context *context, int argc, sqlite3_value **argv) {
const char *ipstr;
int masklength;
struct in_addr in4addr;
char ret[16];
if (argc != 2) {
return;
}
if (sqlite3_value_type(argv[0]) != SQLITE3_TEXT ||
sqlite3_value_type(argv[1]) != SQLITE_INTEGER ) {
return;
}
ipstr = (const char*) sqlite3_value_text(argv[0]);
masklength = sqlite3_value_int(argv[1]);
if (masklength<0 || masklength>32){
sqlite3_result_error(context, "Wrong mask length", -1);
return;
}
if (inet_pton(AF_INET, ipstr, &in4addr) != 1) {
sqlite3_result_error(context, "Passed a malformed IP address", -1);
return;
}
uint32_t mask = 0;
for(int i=0;i<32-masklength;i++){
mask |= (1 << i);
}
mask = ~mask;
in4addr.s_addr &= ntohl(mask);
inet_ntop(AF_INET, &in4addr.s_addr, ret, 16);
sqlite3_result_text(context, (char*) ret, strlen(ret), SQLITE_TRANSIENT);
}
static void ip6mask(sqlite3_context *context, int argc, sqlite3_value **argv) {
const char *ip6str;
int masklength;
struct in6_addr in6addr;
char ret[40];
assert(argc == 2);
if (sqlite3_value_type(argv[0]) != SQLITE3_TEXT) {
return;
}
if (sqlite3_value_type(argv[1]) != SQLITE_INTEGER) {
return;
}
ip6str = (const char*) sqlite3_value_text(argv[0]);
masklength = sqlite3_value_int(argv[1]);
if (masklength<0 || masklength>128){
sqlite3_result_error(context, "Wrong mask length", -1);
return;
}
if (inet_pton(AF_INET6, ip6str, &in6addr) == 0) {
sqlite3_result_error(context, "Passed a malformed IP address", -1);
return;
}
for(int i=128;i>(masklength-1);i--){
in6addr.s6_addr[i / 8] &= ~((char) (1 << (7-(i % 8))));
}
inet_ntop(AF_INET6, in6addr.s6_addr, ret, 40);
sqlite3_result_text(context, (char*) ret, strlen(ret), SQLITE_TRANSIENT);
}
#ifdef _WIN32
__declspec( dllexport )
#endif
int sqlite3_maxminddb_init( sqlite3 *db,
char **pzErrMsg, const sqlite3_api_routines *pApi)
{
int rc = SQLITE_OK;
SQLITE_EXTENSION_INIT2(pApi);
(void)pzErrMsg; /* Unused parameter */
rc = sqlite3_create_function(
db,
"asn",
1,
SQLITE_UTF8,
0,
asn_impl,
0,
0);
if (rc != SQLITE_OK) {
return rc;
}
rc = sqlite3_create_function(
db,
"org",
1,
SQLITE_UTF8,
0,
org_impl,
0,
0);
if (rc != SQLITE_OK) {
return rc;
}
rc = sqlite3_create_function(
db,
"cc",
1,
SQLITE_UTF8,
0,
cc_impl,
0,
0);
if (rc != SQLITE_OK) {
return rc;
}
rc = sqlite3_create_function(
db, "ipmask", 2, SQLITE_UTF8, 0,
ipmask, 0, 0);
if (rc != SQLITE_OK) {
return rc;
}
rc = sqlite3_create_function(
db, "ip6mask", 2, SQLITE_UTF8, 0,
ip6mask, 0, 0);
if (rc != SQLITE_OK) {
return rc;
}
char* HOME = getenv(HOMEENVNAME);
char GEOLITE2_ASN[PATH_MAX];
char GEOLITE2_CNT[PATH_MAX];
sprintf(GEOLITE2_ASN, "%s/.maxminddb/GeoLite2-ASN.mmdb", HOME);
sprintf(GEOLITE2_CNT, "%s/.maxminddb/GeoLite2-Country.mmdb", HOME);
int status_asn = MMDB_open(GEOLITE2_ASN, MMDB_MODE_MMAP, &mmdb_asn);
int status_cnt = MMDB_open(GEOLITE2_CNT, MMDB_MODE_MMAP, &mmdb_cnt);
if (MMDB_SUCCESS != status_asn || MMDB_SUCCESS != status_cnt) {
} else {
initialized = true;
rc = SQLITE_OK;
}
return rc;
}
|
RonxBulld/anvm
|
src/Cpu.h
|
#pragma once
#include "String.h"
class Cpu
{
private:
unsigned int rp, rf, rs, rb, r0, r1, r2, r3;
unsigned int *(regs[8]);
unsigned char *vmem;
StringManager *StrMan;
unsigned int DataPtr;
void CoreDump();
bool GetFlag(unsigned char Flag);
void PutFlag(unsigned char Flag);
bool RunUnit();
void CoreCrash(const char *fmt, ...);
unsigned int GetReg(unsigned int Reg);
void PutReg(unsigned int Reg, unsigned int Data, unsigned int Size);
unsigned int GetMem(unsigned int Addr);
void PutMem(unsigned int Addr, unsigned int Data, unsigned int Size);
unsigned int GetData(unsigned char Addressing, unsigned int Argument);
void PutData(unsigned char Addressing, unsigned int Argument, unsigned int Data, unsigned int DataType);
void Push(unsigned int Data);
unsigned int Pop();
unsigned int InPort(unsigned int Port);
void OutPort(unsigned int Port, unsigned int Argu);
public:
Cpu();
~Cpu();
bool PowerOn;
unsigned int StateBase;
int Run(void *Args);
};
|
RonxBulld/anvm
|
src/Screen.h
|
#pragma once
typedef struct Point
{
int x;
int y;
} Point;
typedef struct Rect
{
int x;
int y;
int w;
int h;
} Rect;
typedef uint32_t Uint32;
typedef uint8_t Uint8;
struct SDL_Window;
struct SDL_Surface;
struct SDL_Point;
struct SDL_Renderer;
struct SDL_PixelFormat;
struct SDL_RWops;
class Screen
{
private:
int width, height;
int FontWidth, FontHeigth;
SDL_Window *MainWnd;
SDL_Surface *ScreenSurface, *buffer;
void *Font, *DebugFont;
void *RefreshThread;
char *FontFile;
bool Transparent;
Uint32 TextColor, BackgroundColor;
Point OutputPosition;
void __set_font(const char *FontFile, const int Size);
Rect ShowText(SDL_Surface *Text, int x, int y, int width, int height, SDL_Surface *Dest);
bool IsUTF8(const void *Str, long Size);
char *GB2312toUTF8(const char *GB2312str);
void CheckPosition();
void DrawDebugLayer(SDL_Surface *dst, float FPS);
public:
Screen(int width, int height);
~Screen();
void StartRefreshThread();
void Refresh(Rect *RefRect = NULL);
void Delay(int ticks);
void SetScreenSize(unsigned int width, unsigned int height);
void GetScreenSize(int *width, int *height);
void CleanScreen();
void Display(const char *Text, int x = -1, int y = -1);
void Display(const int Integer, int x = -1, int y = -1);
void Display(const float Float, int x = -1, int y = -1);
void Display(const char Charactor, int x = -1, int y = -1);
void NewLine();
void SetTransparent(bool value);
Point GetDispPosition();
void SetDispPosition(int x, int y);
SDL_Surface *GetScreenSurface();
void SetTextLocation(int l, int r);
void SetTextColor(Uint32 FrontColor, Uint32 BackColor);
void SetFont(int FontID);
int GetFontWidth();
int GetFontHeigth();
SDL_Window *GetMainWindow();
};
class SDL2Function
{
public:
static void DestroyRenderer(SDL_Renderer *renderer);
static SDL_Surface *CreateRGBSurface(Uint32 flags, int width, int height);
static SDL_PixelFormat *GetFormat(SDL_Surface *surface);
static Uint32 MapRGB(const SDL_PixelFormat *format, Uint8 r, Uint8 g, Uint8 b);
static void FreeSurface(SDL_Surface *surface);
static SDL_Surface *LoadBMP_RW(SDL_RWops *src, int freesrc);
static SDL_RWops *RWFromConstMem(const void *mem, int size);
static int GetSurfaceWidth(SDL_Surface *surface);
static int GetSurfaceHeight(SDL_Surface *surface);
static void *GetSurfacePixels(SDL_Surface *surface);
static bool MustLock(SDL_Surface *surface);
static int LockSurface(SDL_Surface * surface);
static void UnlockSurface(SDL_Surface * surface);
static SDL_Renderer *CreateSoftwareRenderer(SDL_Surface *surface);
static int SetRenderDrawColor(SDL_Renderer *renderer, Uint8 r, Uint8 g, Uint8 b, Uint8 a);
static int GetRenderDrawColor(SDL_Renderer *renderer, Uint8 *r, Uint8 *g, Uint8 *b, Uint8 *a);
static int GetAllowCharNum(const char *str);
};
class SDL2Draw
{
public:
static int FillRect(SDL_Surface *dst, const Rect *rect, Uint32 color);
static int BlitSurfaceWithColorKey(SDL_Surface *src, const Rect *srcrect, SDL_Surface *dst, Rect *dstrect, Uint32 ColorKey);
static int RenderDrawLine(SDL_Renderer *renderer, int x1, int y1, int x2, int y2);
static void RenderPresent(SDL_Renderer *renderer);
static int RenderDrawRect(SDL_Renderer *renderer, const Rect *rect);
};
class SDL2Input
{
public:
static inline int __escape_charactor(int keymod, int key);
static unsigned char KeyPress();
static int WaitKey(bool OnlyKeyboard = false);
static void ShownKeyboard();
static void HiddenKeyboard();
};
|
RonxBulld/anvm
|
src/anvm.h
|
<gh_stars>1-10
#pragma once
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#define MEMSIZE (2*1024*1024)
#define VERSION "anvm 0.03 [by:Rex]"
#define DEFAULTBIN "test.bin"
#include "Cpu.h"
#include "Screen.h"
#include "Input.h"
#include "Gpu.h"
#include "Storage.h"
#include "ErrorLog.h"
// ------ Environment --------
// CPU
extern Cpu *cpu;
// SCREEN
extern Screen *scn;
// MEMORY
extern unsigned char *vmem;
// KEYBOARD
extern Keyboard *keybd;
// GPU
extern Gpu *gpu;
// STORAGE
extern Storage *storage;
|
RonxBulld/anvm
|
src/Input.h
|
<gh_stars>1-10
#pragma once
#include <string>
#include <vector>
class Line
{
public:
Point PrintPosition;
string LineText;
};
class Keyboard
{
private:
unsigned char *GetKeyString();
vector<Line*> *InputBuffer;
int InputNewline(Point Ptr, int ScnWidth, int CharWidth);
public:
Keyboard();
~Keyboard();
unsigned int GetInteger();
unsigned char *GetString();
float GetFloat();
};
|
RonxBulld/anvm
|
src/String.h
|
#pragma once
#include <vector>
#include <list>
#include <string>
using namespace std;
class StringManager
{
private:
string **StringPool;
unsigned int PoolSize;
inline bool EffectiveHandle(unsigned int Handle);
public:
StringManager();
~StringManager();
unsigned int CreateString();
unsigned int ToInt(unsigned int Handle);
void PutString(unsigned int Handle, const unsigned char *Str);
unsigned char *GetString(unsigned int Handle);
string *QuoteString(unsigned int Handle);
void FreeString(unsigned int Handle);
unsigned char *StringLeft(unsigned int Handle, unsigned int Size);
unsigned char *StringRight(unsigned int Handle, unsigned int Size);
unsigned char *StringMid(unsigned int Handle, unsigned int Offset, unsigned int Size);
unsigned int StringFind(unsigned int MasterHandle, unsigned int SubHandle, unsigned int Offset);
bool StringCompare(unsigned int MasterHandle, unsigned int SlaveHandle);
unsigned int StringLength(unsigned int Handle);
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.