repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
aiuno/WingOS
|
libs/utils/sys/raw_msg_system.h
|
<reponame>aiuno/WingOS
#ifndef RAW_MSG_SYSTEM_H
#define RAW_MSG_SYSTEM_H
#include <stddef.h>
#include <stdint.h>
struct raw_msg_request
{
bool valid;
size_t size;
uint8_t *data;
} __attribute__((packed));
struct raw_msg_call_request
{
uint64_t argument[5];
uint64_t return_value;
};
#endif // RAW_MSG_SYSTEM_H
|
aiuno/WingOS
|
unit-test/src/smart_ptr_check.h
|
<filename>unit-test/src/smart_ptr_check.h
#pragma once
int unique_ptr_create_destroy_check();
int unique_ptr_raw_check();
int unique_ptr_operator_check();
int unique_ptr_reset_check();
int unique_ptr_release_check();
int make_unique_check();
|
aiuno/WingOS
|
libs/utils/no_null.h
|
#ifndef NO_NULL_H
#define NO_NULL_H
#include <assert.h>
#include <stddef.h>
#include <utils/type/is_same.h>
namespace utils
{
template <typename T>
class no_null
{
T _value;
public:
static_assert(!is_same<nullptr_t, T>::value, "no null must not be null");
template <typename T2>
no_null(T2 val)
{
static_assert(!is_same<nullptr_t, T2>::value, "no null constructor must not be null");
assert(reinterpret_cast<uintptr_t>(val) != 0);
_value = val;
}
no_null(T val)
{
assert(reinterpret_cast<uintptr_t>(val) != 0);
_value = val;
}
template <typename T2>
no_null &operator=(T2 val)
{
static_assert(!is_same<nullptr_t, T2>::value, "no null constructor must not be null");
assert(reinterpret_cast<uintptr_t>(val) != 0);
_value = val;
}
remove_pointer<T> operator->()
{
return _value;
}
T get() { return _value; };
};
} // namespace utils
#endif // NO_NULL_H
|
aiuno/WingOS
|
unit-test/src/type_trait_check.h
|
<gh_stars>100-1000
#pragma once
int integral_constant_check();
int integral_constant_false_check();
int integral_constant_true_check();
int is_same_check_true();
int is_same_check_false();
int remove_reference_check();
int remove_const_check();
int remove_volatile_check();
int remove_pointer_check();
int is_const_check();
int is_class_check();
int is_enum_check();
int is_union_check();
int is_function_check();
int is_base_of_check();
|
aiuno/WingOS
|
libs/utils/lock.h
|
#ifndef LOCK_H
#define LOCK_H
#include <stddef.h>
#include <stdint.h>
namespace utils
{
enum lock_state
{
LOCK_LOCKED = true,
LOCK_FREE = false,
};
class lock_type
{
bool raw;
public:
lock_type() : raw(LOCK_FREE){}; // by default the lock is free
bool is_locked() const
{
bool res;
__atomic_load(&raw, &res, __ATOMIC_SEQ_CST);
return res;
}
void lock()
{
while (!__sync_bool_compare_and_swap(&raw, LOCK_FREE, LOCK_LOCKED))
{
asm volatile("pause"); // try to not burn the cpu
}
__sync_synchronize();
};
void force_lock()
{
raw = LOCK_LOCKED;
__sync_synchronize();
};
void unlock()
{
__sync_synchronize();
__atomic_store_n(&raw, LOCK_FREE, __ATOMIC_SEQ_CST);
raw = LOCK_FREE;
};
};
class context_lock
{
lock_type &raw;
public:
context_lock(lock_type &val) : raw(val)
{
raw.lock();
}
~context_lock()
{
raw.unlock();
}
};
} // namespace utils
#endif // LOCK_H
|
aiuno/WingOS
|
libs/utils/math.h
|
#ifndef MATH_H
#define MATH_H
namespace utils
{
template <class A>
constexpr A max(const A a, const A b)
{
if (a > b)
{
return a;
}
else
{
return b;
}
}
template <class A>
constexpr A min(const A a, const A b)
{
if (a < b)
{
return a;
}
else
{
return b;
}
}
template <class A>
constexpr A abs(const A a)
{
if (a < 0)
{
return -a;
}
return a;
}
} // namespace utils
#endif // MATH_H
|
aiuno/WingOS
|
kernel/arch/x86_64/device/local_data.h
|
<reponame>aiuno/WingOS
#pragma once
#include <64bit.h>
#include <arch.h>
#include <backtrace.h>
#include <device/apic.h>
#include <gdt.h>
#include <interrupt.h>
#include <mem/virtual.h>
#include <proc/process.h>
#include <smp.h>
#include <stdint.h>
class page_table;
static const uint32_t stack_size = STACK_SIZE;
class cpu
{
public:
uint8_t *syscall_stack;
uint64_t saved_stack;
uint64_t current_processor_id;
idtr cidt;
gdtr cgdt;
tss ctss;
uint8_t stack_data[stack_size] PAGE_ALIGN;
uint8_t *stack_data_interrupt;
uint64_t lapic_id;
page_table *cpu_page_table;
void load_sse(uint8_t *data);
void save_sse(uint8_t *data);
backtrace local_backtrace;
} __attribute__((packed));
//local_data *get_current_data();
//local_data *get_current_data(int id);
extern cpu procData[smp::max_cpu];
inline cpu *get_current_cpu()
{
uint64_t cc = 0;
asm volatile("mov %0, fs \n"
: "=r"(cc));
return &procData[cc];
}
inline cpu *get_current_cpu(int id)
{
return &procData[id];
}
|
aiuno/WingOS
|
kernel/arch/x86_64/device/graphic.h
|
<reponame>aiuno/WingOS
#pragma once
#include <device/general_device.h>
enum framebuff_bpp
{
BPP_24_BIT = 2,
BPP_32_BIT = 3,
};
class basic_framebuffer_graphic_device : public generic_framebuffer
{
protected:
size_t _width;
size_t _height;
void *_addr;
public:
basic_framebuffer_graphic_device(size_t width, size_t height, uintptr_t phys_addr, framebuff_bpp bpp = framebuff_bpp::BPP_32_BIT);
virtual uintptr_t get_addr() { return reinterpret_cast<uintptr_t>(_addr); };
virtual size_t width() { return _width; };
virtual size_t height() { return _height; };
};
|
aiuno/WingOS
|
libs/utils/memory/memory.h
|
<reponame>aiuno/WingOS
#ifndef MEMORY_H
#define MEMORY_H
#include <assert.h>
#include <stddef.h>
#include <string.h>
namespace utils
{
/* NOTE: this is for replacing c function argument
* void f(void* data, size_t size);
* with:
* void f(utils::memory mem);
*
* it's like a unique_ptr, but is different in some ways
*
* NOTE2: the memory_buffer in buffer.h will be removed as it is bad
*/
class memory
{
protected:
size_t _size;
void *_data;
template <typename V, size_t type_size>
void set_impl(const V value)
{
assert(type_size <= _size);
V *d = reinterpret_cast<V *>(data());
for (size_t i = 0; i < _size / type_size; i++)
{
d[i] = value;
}
}
template <typename V>
constexpr void set_impl(const V value)
{
V *d = reinterpret_cast<V *>(data());
for (size_t i = 0; i < _size; i++)
{
d[i] = value;
}
}
public:
memory() : _size(0), _data(nullptr){}; // for creation use static function
memory(const memory &) = delete; // no copy, use memory::copy
memory(memory &&mem)
{
_size = mem._size;
_data = mem.release();
};
template <typename V>
void set(const V value)
{
if constexpr (sizeof(V) == sizeof(uint8_t))
{
set_impl<V>(value); // remove some check for type higher than a byte
}
else
{
set_impl<V, sizeof(V)>(value);
}
}
void set(const memory &from);
void set(const void *data, size_t size);
bool compare(const memory &target) const;
bool operator==(const memory &target) const { return compare(target); };
bool operator!=(const memory &target) const { return !compare(target); };
void *data() { return _data; }
const void *data() const { return _data; }
uint8_t get_byte(size_t idx) const
{
assert(_data);
assert(idx < _size);
return ((uint8_t *)_data)[idx];
};
void set_byte(size_t idx, uint8_t value)
{
assert(_data);
assert(idx < _size);
((uint8_t *)_data)[idx] = value;
};
uint8_t &operator[](size_t index)
{
return ((uint8_t *)_data)[index];
}
const uint8_t operator[](size_t index) const
{
return ((const uint8_t *)_data)[index];
}
size_t size() const { return _size; };
operator const void *() const { return data(); };
operator void *() { return data(); };
operator bool() const { return _data != nullptr; };
void *release();
void destroy();
void give_ownership(void *data, size_t size);
static memory create(size_t size);
// now the memory object has the data AND manage to free it
static memory create_and_give_ownership(void *data, size_t size);
static memory copy(const memory &from);
static memory copy(const void *data, size_t size);
~memory() { destroy(); };
};
} // namespace utils
#endif // MEMORY_H
|
aiuno/WingOS
|
unit-test/src/vector_check.h
|
#pragma once
int wvector_create_check();
int wvector_capacity_check();
int wvector_push_back_check();
int wvector_get_check();
int wvector_remove_check();
int wvector_clear_check();
|
aiuno/WingOS
|
libs/gui/widget.h
|
#pragma once
#include <gui/graphic_system.h>
#include <stddef.h>
#include <utils/container/wvector.h>
namespace gui
{
class widget
{
protected:
int64_t widget_width;
int64_t widget_height;
int64_t widget_x;
int64_t widget_y;
bool widget_should_draw = true;
bool is_position_inside_widget(const pos pos);
bool is_forced_size = false;
public:
bool is_manually_sized()
{
return is_forced_size;
}
long width() { return widget_width; };
long height() { return widget_height; };
long x() { return widget_x; };
long y() { return widget_y; };
widget();
virtual void update_widget(){};
virtual void callback(graphic_system_update_info &info){};
virtual void resize(int64_t new_x, int64_t new_y, int64_t new_width, int64_t new_height)
{
widget_x = new_x;
widget_y = new_y;
widget_width = new_width;
widget_height = new_height;
update_widget();
}
virtual void draw_widget(graphic_context &context) = 0;
virtual bool should_redraw()
{
return widget_should_draw;
}
virtual bool set_should_redraw(bool value)
{
return widget_should_draw;
}
// note: i do void* as c++ doesn't like recursive include
virtual void init_widget(void *new_parent){};
};
enum layout_type
{
LAYOUT_VERTICAL = 0,
LAYOUT_HORIZONTAL = 1,
};
class widget_container : public widget
{
utils::vector<widget *> list;
int layout_type;
size_t _padding;
void *parent;
void relayout();
public:
void set_padding(size_t amount)
{
_padding = amount;
}
size_t padding() const
{
return _padding;
}
widget_container() : widget()
{
list.clear();
set_padding(4);
layout_type = LAYOUT_VERTICAL;
}
virtual void update_widget() override
{
for (size_t i = 0; i < list.size(); i++)
{
(*list[i]).update_widget();
}
}
virtual void callback(graphic_system_update_info &info) override
{
for (size_t i = 0; i < list.size(); i++)
{
(*list[i]).callback(info);
}
}
virtual void draw_widget(graphic_context &context) override;
virtual void init_widget(void *new_parent) override;
virtual void resize(int64_t new_x, int64_t new_y, int64_t new_width, int64_t new_height)
{
widget_x = new_x;
widget_y = new_y;
widget_width = new_width;
widget_height = new_height;
relayout();
update_widget();
}
void add_widget(widget *widget)
{
widget->init_widget(parent);
list.push_back(widget);
relayout();
}
void callback_update(graphic_system_update_info &info)
{
for (size_t i = 0; i < list.size(); i++)
{
(*list[i]).callback(info);
}
}
virtual bool should_redraw()
{
for (size_t i = 0; i < list.size(); i++)
{
if ((*list[i]).should_redraw())
{
return true;
}
}
return false;
}
};
} // namespace gui
|
aiuno/WingOS
|
kernel/generic/kernel.h
|
#pragma once
#include <device/debug/com.h>
#include <stdint.h>
#include <stivale_struct.h>
void _start(struct stivale_struct *bootloader_data);
|
aiuno/WingOS
|
kernel/generic/programm_launcher.h
|
#pragma once
#include <elf_gnu_structure.h>
#include <filesystem/echfs.h> // to do add a global file system
#include <sys/types.h>
#include <utils/sys/programm_exec_info.h>
pid_t launch_programm(const char *path, file_system *file_sys, int argc, const char **argv);
pid_t launch_programm_usr(programm_exec_info *info);
pid_t launch_module(const char *path, file_system *file_sys, int argc, const char **argv);
|
aiuno/WingOS
|
libs/libc/unistd.h
|
#ifndef UNISTD_H
#define UNISTD_H
#include <stdint.h>
#include <time.h>
// FIXME: move it in sys/types.h
typedef long suseconds_t;
unsigned int sleep(unsigned int sec);
suseconds_t usleep(suseconds_t sec);
#endif // UNISTD_H
|
aiuno/WingOS
|
kernel/generic/device/general_device.h
|
#ifndef GENERAL_DEVICE_H
#define GENERAL_DEVICE_H
#include <module/device_generic_driver.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <utils/container/wvector.h>
#include <utils/sys/device_file_info.h>
#define MAX_DEVICE 128
extern const char *device_type_to_str[];
class general_device;
void add_device(general_device *dev);
general_device *get_device(uint32_t id);
uint32_t get_device_count();
template <class end_type>
extern auto find_device() -> end_type *;
#endif // TIMER_DEVICE_H
|
aiuno/WingOS
|
kernel/generic/logging.h
|
#ifndef LOGGING_H
#define LOGGING_H
#include <device/debug/com.h>
#include <device/general_device.h>
#include <stddef.h>
#include <stdint.h>
#include <stdio.h>
#include <string.h>
#include <utility.h>
#include <utils/lock.h>
enum log_state
{
LOG_INFO = 0,
LOG_DEBUG = 1,
LOG_ERROR = 2,
LOG_FATAL = 3,
LOG_WARNING = 4,
LOG_NULL = 5,
};
class range_str
{
public:
const char *rdata;
size_t rlength;
range_str(const char *data, size_t size) : rdata(data), rlength(size){};
};
template <class T>
void log_print_element(T element);
template <>
void log_print_element<>(const char *element);
template <>
void log_print_element<>(char *element);
template <>
void log_print_element<>(char element);
template <>
void log_print_element<>(range_str element);
template <>
void log_print_element<>(int64_t element);
template <>
void log_print_element<>(uint64_t element);
template <>
void log_print_element<>(uint32_t element);
template <>
void log_print_element<>(int element);
template <>
void log_print_element<>(uint16_t element);
template <>
void log_print_element<>(uint8_t element);
template <>
void log_print_element<>(void *element);
template <>
void log_print_element<>(long element);
void print_log_str(const char *d, log_state state);
void slog(const char *msg);
template <typename arg1>
constexpr void slog(const char *msg, arg1 &arg)
{
debug_device *dev = find_device<debug_device>();
size_t length = 0;
for (size_t i = 0; i < strlen(msg); i++)
{
if (i != 0 && msg[i] == '}' && msg[i - 1] == '{')
{
length = i + 1;
break;
}
}
if (length == 0)
{
length = strlen(msg);
dev->echo_out(msg, length);
return;
}
else
{
dev->echo_out(msg, length - 2);
log_print_element<arg1>(arg);
dev->echo_out(msg + length, strlen(msg) - length);
}
}
template <typename arg1, typename... argument>
constexpr void slog(const char *msg, arg1 &arg, argument &...args)
{
debug_device *dev = find_device<debug_device>();
size_t length = 0;
for (size_t i = 0; i < strlen(msg); i++)
{
if (i != 0 && msg[i] == '}' && msg[i - 1] == '{')
{
length = i + 1;
break;
}
}
if (length == 0)
{
length = strlen(msg);
dev->echo_out(msg, length);
return;
}
else
{
if (length - 2 > 0)
{
dev->echo_out(msg, length - 2);
}
log_print_element<arg1>(arg);
return slog(msg + length, args...);
}
}
void start_log();
void end_log();
template <typename... argument>
constexpr void log(const char *d, log_state state, const char *msg, argument... arg)
{
start_log();
print_log_str(d, state);
slog(msg, arg...);
end_log();
};
#endif
|
aiuno/WingOS
|
libs/utils/type/is_same.h
|
#ifndef IS_SAME_H
#define IS_SAME_H
#include <utils/type/integral_constant.h>
#include <utils/type_traits.h>
namespace utils
{
template <class T1, class T2>
class is_same : public false_type
{
};
template <class T1>
class is_same<T1, T1> : public true_type
{
};
} // namespace utils
#endif // IS_SAME_H
|
aiuno/WingOS
|
kernel/arch/x86_64/device/time/rtc.h
|
#ifndef RTC_H
#define RTC_H
#include <stdint.h>
class RTC
{
public:
void init() const; // wait a const init function ? is this legal ?
uint8_t read(int reg) const;
uint8_t get_sec() const;
uint8_t get_min() const;
uint8_t get_hour() const;
uint8_t get_day() const;
uint8_t get_month() const;
uint8_t get_year() const;
uint64_t get_total_sec() const;
static const RTC *the();
};
#endif // RTC_H
|
aiuno/WingOS
|
kernel/generic/backtrace.h
|
<filename>kernel/generic/backtrace.h
#ifndef BACKTRACE_H
#define BACKTRACE_H
#include <arch.h>
class backtrace
{
static const int backtrace_max_entry_count = 32;
backtrace_entry_type entry[backtrace_max_entry_count];
public:
backtrace();
void add_entry(const backtrace_entry_type added_entry);
void dump_backtrace();
} __attribute__((packed));
#endif // BACKTRACE_H
|
aiuno/WingOS
|
libs/utils/sys/syscall_codes.h
|
#pragma once
enum class syscall_codes
{
NULL_SYSCALL = 0, // don't use >:^(
SET_MODULES_CALLS = 1, // each module has a call table, it's like syscall but directly link with the kernel, this syscall is reserved to modules, with the modules call table you can do specific low level operation, this syscall can be called 'only' 1 times
// 2 & 3 are free for use rn
GET_PROCESS_GLOBAL_DATA = 4, // get process global data, if arg1 (target) is nullptr, return self global data, else return a process global data return -1 if there is an error
MEMORY_ALLOC = 6, // pmm alloc
MEMORY_FREE = 7, // pmm free
FILE_OPEN = 8, // open a file
FILE_CLOSE = 9, // close a file
FILE_READ = 10, // read file
FILE_WRITE = 11, // write file
FILE_SEEK = 12, // seek a file
NANO_SLEEP = 13, // sleep the current process
GET_PID = 14, // get current pid
EXEC = 15, // execute a new programm
EXIT = 16, // current process exit
IPC_SERV_EXIST = 17, // check if a server exist
CREATE_SERVER = 18, // try to create a new server
CONNECT_SERVER = 19, // (client) try to connect to a server
ACCEPT_CONNECTION = 20, // (server) try to accept a new connection
IS_CONNECTION_ACCEPTED = 21, // (client) is the connection accepted by the server
DECONNECT = 22, // (client) deconnect from a server
SEND = 23, // send data to a client/server
RECEIVE = 24, // receive data from a client/server
GET_PROC_INFO = 25, // get process information
};
#define SYS_ALLOC_SHARED 0x2
|
aiuno/WingOS
|
libs/utils/sys/device_file_info.h
|
<gh_stars>100-1000
#ifndef DEVICE_FILE_INFO_H
#define DEVICE_FILE_INFO_H
#include <stdint.h>
#define MOUSE_FILE_BUFFER "/dev/mouse"
#define KEYBOARD_FILE_BUFFER "/dev/keyboard"
#define FRAMEBUFFER_FILE_BUFFER "/dev/framebuffer"
struct mouse_buff_info
{
int32_t mouse_x;
int32_t mouse_y;
bool left;
bool right;
bool middle;
} __attribute__((packed));
struct keyboard_buff_info
{
uint16_t button;
uint8_t state;
} __attribute__((packed));
struct framebuffer_buff_info
{
uintptr_t addr;
uint16_t width;
uint16_t height;
} __attribute__((packed));
#endif // DEVICE_FILE_INFO_H
|
aiuno/WingOS
|
libs/kern/process_buffer.h
|
<reponame>aiuno/WingOS
#pragma once
#include <stdint.h>
namespace sys
{
} // namespace sys
|
aiuno/WingOS
|
libs/gui/widget/button.h
|
#pragma once
#include <gui/window.h>
namespace gui
{
class button_widget : public widget
{
const char *button_title;
bool is_hovered;
uint64_t text_length = 0;
gui::window *parent;
bool start_click = false;
uint64_t clicked = 0;
void (*click)(uint64_t click_count);
public:
button_widget();
button_widget(const char *title) __attribute__((__target__("no-sse")));
constexpr void set_click_callback(void (*callback)(uint64_t click_count))
{
click = callback;
}
virtual void update_widget() override;
virtual void draw_widget(graphic_context &context) override;
virtual void init_widget(void *new_parent) override;
};
} // namespace gui
|
aiuno/WingOS
|
unit-test/src/array_check.h
|
#pragma once
int array_creation_check();
int array_access_check();
int array_fill_check();
|
aiuno/WingOS
|
libs/module/module_calls.h
|
<gh_stars>100-1000
#ifndef MODULE_CALLS_H
#define MODULE_CALLS_H
#include <module/device_generic_driver.h>
#include <stddef.h>
#include <stdint.h>
template <typename T, typename... argument>
using mfunc = T (*)(argument...);
#define IO_BIT_SIZE_8 0b0
#define IO_BIT_SIZE_16 0b01
#define IO_BIT_SIZE_32 0b10
#define IO_BIT_SIZE_64 0b11
struct io_func_exec
{
bool write : 1;
uint8_t bit_size : 2;
uint8_t return_result : 1;
uint8_t use_memory : 1;
};
struct module_calls_list
{
mfunc<void> null_func;
mfunc<void, const char *> echo_out;
mfunc<size_t> get_kernel_version;
mfunc<size_t, size_t, size_t, io_func_exec> io_func;
mfunc<int, uint32_t, general_device *> set_device_driver;
mfunc<const general_device *, uint32_t> get_device_driver;
mfunc<int, const char *> set_module_name;
mfunc<bool, size_t, mfunc<void, uint32_t>> add_irq_handler;
} __attribute__((packed));
#ifdef MODULE
void call_init();
void echo_out(const char *data);
size_t get_kern_version();
size_t io_function(size_t addr, size_t write_val, io_func_exec flags);
int set_device_driver(uint32_t id, general_device *as);
const general_device *get_device_driver(uint32_t id);
int set_module_name(const char *name);
int add_irq_handler(size_t irq, mfunc<void, uint32_t> func);
// just equivalent of cli/sti
static inline void enter_low_level_context()
{
asm volatile("cli");
}
static inline void exit_low_level_context()
{
asm volatile("sti");
}
inline void outb(uint16_t port, uint8_t value)
{
asm volatile("out dx, al" ::"a"(value), "d"(port));
}
inline void outw(uint16_t port, uint16_t value)
{
asm volatile("out dx, ax" ::"a"(value), "d"(port));
}
inline void outl(uint16_t port, uint32_t value)
{
asm volatile("out dx, eax" ::"a"(value), "d"(port));
}
inline uint8_t inb(uint16_t port)
{
uint8_t ret;
asm volatile("in al, dx"
: "=a"(ret)
: "d"(port));
return ret;
}
inline uint16_t inw(uint16_t port)
{
uint16_t ret;
asm volatile("in ax, dx"
: "=a"(ret)
: "d"(port));
return ret;
}
inline uint32_t inl(uint16_t port)
{
uint32_t ret;
asm volatile("in eax, dx"
: "=a"(ret)
: "d"(port));
return ret;
}
#endif
#endif // MODULE_CALLS_H
|
picardb/QtRemoteTestClient
|
src/model/network/Network.h
|
#pragma once
#include <QObject>
#include <QTcpSocket>
#include "DnsServiceBrowser.h"
#include "DnsServiceResolver.h"
#include "Request.h"
class Network : public QObject
{
Q_OBJECT
private:
DnsServiceBrowser m_dnsBrowser;
DnsServiceResolver m_dnsResolver;
QTcpSocket m_tcpSocket;
QHostAddress m_address;
int m_port;
QString m_deviceName;
bool m_isConnecting;
public:
Network(QObject *parent = 0);
void startDnsBrowsing() { m_dnsBrowser.start(); }
DnsServiceRecordList* getDnsRecordList() { return m_dnsBrowser.getRecordList(); }
void connectToDevice(int index);
void sendRequest(const Request& request);
private slots:
void onDnsResolverError();
void onDnsResolverResolved(const QHostInfo& hostInfo, int port);
void onSocketConnected();
void onSocketDisconnected();
signals:
void resolvingDnsRecord(const QString& name);
void connecting(const QHostAddress& address, int port);
void connected(const QString& deviceName);
void disconnected();
void error(const QString& msg);
void packetSent();
};
|
picardb/QtRemoteTestClient
|
src/model/network/DnsServiceRecordList.h
|
#pragma once
#include <QAbstractTableModel>
#include "DnsServiceRecord.h"
class DnsServiceRecordList : public QAbstractTableModel
{
private:
QVector<DnsServiceRecord> m_list;
public:
DnsServiceRecordList(QObject *parent = Q_NULLPTR);
int rowCount(const QModelIndex & = QModelIndex()) const;
int columnCount(const QModelIndex & = QModelIndex()) const;
QVariant data(const QModelIndex &index, int role = Qt::DisplayRole) const;
QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const;
void add(const DnsServiceRecord& record);
void remove(const DnsServiceRecord& record);
const DnsServiceRecord& operator[](int index) const { return m_list[index]; }
};
|
picardb/QtRemoteTestClient
|
src/model/network/Request.h
|
<filename>src/model/network/Request.h
#pragma once
#include <QByteArray>
struct Request {
unsigned char system;
unsigned char command;
unsigned int length;
QByteArray data;
};
|
picardb/QtRemoteTestClient
|
src/model/network/DnsServiceBrowser.h
|
<reponame>picardb/QtRemoteTestClient<gh_stars>0
#pragma once
#include <QObject>
#include <QVector>
#include <QSocketNotifier>
#include "dns_sd.h"
#include "DnsServiceRecordList.h"
class DnsServiceBrowser : public QObject
{
Q_OBJECT
private:
DnsServiceRecordList m_recordList;
DNSServiceRef m_serviceRef;
static void DNSSD_API browseCallback(DNSServiceRef sdRef, DNSServiceFlags flags,
uint32_t interfaceIndex, DNSServiceErrorType errorCode,
const char *serviceName, const char *regtype,
const char *replyDomain, void *context );
public:
DnsServiceBrowser(QObject *parent = 0);
void start();
DnsServiceRecordList* getRecordList() { return &m_recordList; }
const DnsServiceRecord& getRecord(int index) const { return m_recordList[index]; }
signals:
void error(const QString& );
private slots:
void onSockNotifierActivated();
};
|
picardb/QtRemoteTestClient
|
src/widgets/MainWindow.h
|
<reponame>picardb/QtRemoteTestClient<filename>src/widgets/MainWindow.h
#pragma once
#include <QMainWindow>
#include "MainWidget.h"
class MainWindow : public QMainWindow
{
Q_OBJECT
private:
MainWidget *m_pCentralWidget;
public:
MainWindow(QWidget *parent = 0);
~MainWindow();
};
|
picardb/QtRemoteTestClient
|
src/widgets/MainWidget.h
|
#pragma once
#include <QWidget>
#include <QHostInfo>
class MainWidget : public QWidget
{
Q_OBJECT
public:
MainWidget(QWidget *parent = 0);
private slots:
void onNetworkError(const QString& msg);
};
|
picardb/QtRemoteTestClient
|
src/model/network/DnsServiceRecord.h
|
#pragma once
#include <QString>
class DnsServiceRecord
{
private:
QString m_name;
QString m_type;
QString m_domain;
quint32 m_interfaceIndex;
public:
enum membersIndexes {
MEMBER_INDEX_NAME = 0,
MEMBER_INDEX_TYPE = 1,
MEMBER_INDEX_DOMAIN = 2,
MEMBER_INDEX_INTERFACE = 3
};
DnsServiceRecord();
DnsServiceRecord(const char name[], const char type[], const char domain[], const quint32 interfaceIndex);
DnsServiceRecord(const DnsServiceRecord& other);
DnsServiceRecord& operator=(const DnsServiceRecord& other);
bool operator==(const DnsServiceRecord& other) const;
const QString& name() const { return m_name; }
const QString& type() const { return m_type; }
const QString& domain() const { return m_domain; }
quint32 interfaceIndex() const { return m_interfaceIndex; }
static int membersCount() { return 4; }
static QString membersName(int index);
};
|
picardb/QtRemoteTestClient
|
src/constants.h
|
#pragma once
#include <QString>
const QString DNS_SD_REG_TYPE = "_qtremote._tcp";
|
picardb/QtRemoteTestClient
|
src/model/control/Control.h
|
#pragma once
#include <QObject>
#include "AudioControl.h"
class Control : public QObject
{
Q_OBJECT
private:
AudioControl m_audio;
public:
Control(QObject *parent = 0);
void audioRaiseVolume(unsigned char percentage) { m_audio.raiseVolume(percentage); }
void audioLowerVolume(unsigned char percentage) { m_audio.lowerVolume(percentage); }
void audioSetVolume(unsigned char percentage) { m_audio.setVolume(percentage); }
void audioMuteVolume() { m_audio.muteVolume(); }
};
|
picardb/QtRemoteTestClient
|
src/model/Model.h
|
<gh_stars>0
#pragma once
#include <QObject>
#include "network/Network.h"
#include "control/Control.h"
class Model : public QObject
{
Q_OBJECT
private:
static Network m_network;
static Control m_control;
public:
static Network& network() { return m_network; }
static Control& control() { return m_control; }
};
|
picardb/QtRemoteTestClient
|
src/model/network/DnsServiceResolver.h
|
<filename>src/model/network/DnsServiceResolver.h
#pragma once
#include <QObject>
#include <QSocketNotifier>
#include <QHostInfo>
#include "DnsServiceRecord.h"
#include "dns_sd.h"
class DnsServiceResolver : public QObject
{
Q_OBJECT
private:
DNSServiceRef m_ref;
int m_port;
static void DNSSD_API resolveCallback(DNSServiceRef, DNSServiceFlags, uint32_t,
DNSServiceErrorType errorCode,
const char *, const char *hosttarget,
uint16_t port, uint16_t, const unsigned char *,
void *context);
public:
DnsServiceResolver(QObject *parent = 0);
void resolveRecord(const DnsServiceRecord& record);
signals:
void error(const QString& );
void resolved(const QHostInfo& hostInfo, int port);
private slots:
void onSockNotifierActivated();
void onHostInfoLookup(const QHostInfo& hostInfo);
void cleanupResolve();
};
|
picardb/QtRemoteTestClient
|
src/model/control/AudioControl.h
|
<reponame>picardb/QtRemoteTestClient
#pragma once
class AudioControl
{
private:
static const unsigned char SYSTEM_ID = 0x01;
static const unsigned char CMD_ID_RAISE_VOL = 0x01;
static const unsigned char CMD_ID_LOWER_VOL = 0x02;
static const unsigned char CMD_ID_SET_VOL = 0x03;
static const unsigned char CMD_ID_MUTE_VOL = 0x04;
public:
AudioControl();
void raiseVolume(unsigned char percentage);
void lowerVolume(unsigned char percentage);
void setVolume(unsigned char percentage);
void muteVolume();
};
|
picardb/QtRemoteTestClient
|
src/widgets/DeviceWidget.h
|
#pragma once
#include <QWidget>
#include <QLabel>
#include <QTableView>
#include <QHostAddress>
class DeviceWidget : public QWidget
{
Q_OBJECT
private:
QLabel *m_pStatusLabel;
QTableView *m_pDeviceList;
protected:
void showEvent(QShowEvent *event);
public:
DeviceWidget(QWidget *parent = 0);
private slots:
void onDeviceListDoubleClicked(const QModelIndex& index);
void onNetworkResolving(const QString& name);
void onNetworkConnecting(const QHostAddress& address, int port);
void onNetworkConnected(const QString& deviceName);
void onNetworkDisconnected();
};
|
picardb/QtRemoteTestClient
|
src/widgets/AudioWidget.h
|
#pragma once
#include <QWidget>
#include <QPushButton>
#include "model/Model.h"
class AudioWidget : public QWidget
{
Q_OBJECT
private:
QPushButton *m_pRaiseButton;
QPushButton *m_pLowerButton;
QPushButton *m_pMuteButton;
public:
AudioWidget(QWidget *parent = 0);
private slots:
void onRaiseButtonClicked() { Model::control().audioRaiseVolume(5); }
void onLowerButtonClicked() { Model::control().audioLowerVolume(5); }
void onMuteButtonClicked() { Model::control().audioMuteVolume(); }
};
|
Korune/KOBaiSiBuDeJie
|
KOBaiSiBuDeJie/ViewController.h
|
<reponame>Korune/KOBaiSiBuDeJie
//
// ViewController.h
// KOBaiSiBuDeJie
//
// Created by Korune on 2017/7/16.
// Copyright © 2017年 Korune. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
|
Krzem5/C-Custom_Lang_Compiler
|
src/compiler/free.c
|
#include <common.h>
#include <free.h>
#include <loader.h>
#include <ast.h>
#include <stdio.h>
#include <stdlib.h>
void free_file_object(FileObject fo){
assert(fo->fp!=NULL);
assert(fo->dt!=NULL);
free(fo->fp);
free(fo->dt);
free(fo);
}
void free_ast_object(ASTObject ast){
free(ast);
}
|
Krzem5/C-Custom_Lang_Compiler
|
src/include/loader.h
|
#ifndef __LOADER_H__
#define __LOADER_H__
#include <common.h>
#include <stdio.h>
typedef struct _SEARCH_PATH_LIST SearchPathList;
typedef struct _FILE_OBJECT* FileObject;
struct _SEARCH_PATH_LIST_ELEM{
uint32_t ln;
char* p;
};
struct _SEARCH_PATH_LIST{
uint32_t ln;
struct _SEARCH_PATH_LIST_ELEM* e;
};
struct _FILE_OBJECT{
size_t fpl;
char* fp;
size_t ln;
uint8_t* dt;
};
extern SearchPathList loader_search_path_list;
void loader_add_search_path(char* p);
FileObject loader_load_file(char* fp);
#endif
|
Krzem5/C-Custom_Lang_Compiler
|
src/compiler/ast.c
|
<gh_stars>0
#include <common.h>
#include <ast.h>
#include <loader.h>
#include <stdlib.h>
#include <stdio.h>
#define CHR_CMP_RET(c,v) \
if (*(fo->dt+t->_off)==c){ \
t->t=AST_TOKEN_TYPE_OPERATOR; \
t->dt.op=v; \
t->_off++; \
return 0; \
}
#define STR_CMP_RET(s,l,_t,tt,tv) \
if (t->_off+l<=fo->ln){ \
for (i=0;i<l;i++){ \
if (*(fo->dt+t->_off+i)!=*(s+i)){ \
i=INTMAX_MAX; \
break; \
} \
} \
if (i!=INTMAX_MAX&&(t->_off+l==fo->ln||(!((*(fo->dt+t->_off+l)>47&&*(fo->dt+t->_off+l)<58)||(*(fo->dt+t->_off+l)>64&&*(fo->dt+t->_off+l)<91)||*(fo->dt+t->_off+l)==95||(*(fo->dt+t->_off+l)>96&&*(fo->dt+t->_off+l)<123)||*(fo->dt+t->_off+l)>126)))){ \
t->t=tt; \
t->dt._t=tv; \
t->_off+=l; \
return 0; \
} \
}
void print_token(ASTToken t){
switch (t.t){
case AST_TOKEN_TYPE_UNKNOWN:
printf("ASTToken = {\n type = AST_TOKEN_TYPE_UNKNOWN,\n err_char = '%c'\n next_offset = %llu\n};\n",t.dt.u,t._off);
break;
case AST_TOKEN_TYPE_STRING:
printf("ASTToken = {\n type = AST_TOKEN_TYPE_STRING,\n str = '%s'\n next_offset = %llu\n};\n",t.dt.s.s,t._off);
break;
case AST_TOKEN_TYPE_CHAR:
printf("ASTToken = {\n type = AST_TOKEN_TYPE_CHAR,\n char = '%c'\n next_offset = %llu\n};\n",t.dt.c,t._off);
break;
case AST_TOKEN_TYPE_INT:
printf("ASTToken = {\n type = AST_TOKEN_TYPE_INT,\n int = %lld\n next_offset = %llu\n};\n",t.dt.i,t._off);
break;
case AST_TOKEN_TYPE_FLOAT:
printf("ASTToken = {\n type = AST_TOKEN_TYPE_FLOAT,\n float = %lf\n next_offset = %llu\n};\n",t.dt.f,t._off);
break;
case AST_TOKEN_TYPE_KEYWORD:
printf("ASTToken = {\n type = AST_TOKEN_TYPE_KEYWORD,\n keyword = 0x%hhx\n next_offset = %llu\n};\n",t.dt.k,t._off);
break;
case AST_TOKEN_TYPE_MODIFIER:
printf("ASTToken = {\n type = AST_TOKEN_TYPE_MODIFIER,\n modifier = 0x%hhx\n next_offset = %llu\n};\n",t.dt.m,t._off);
break;
case AST_TOKEN_TYPE_IDENTIFIER:
printf("ASTToken = {\n type = AST_TOKEN_TYPE_IDENTIFIER,\n identifier = %s\n next_offset = %llu\n};\n",t.dt.id.i,t._off);
break;
case AST_TOKEN_TYPE_OPERATOR:
printf("ASTToken = {\n type = AST_TOKEN_TYPE_OPERATOR,\n operator = 0x%hhx\n next_offset = %llu\n};\n",t.dt.op,t._off);
break;
case AST_TOKEN_TYPE_WHITESPACE:
printf("ASTToken = {\n type = AST_TOKEN_TYPE_WHITESPACE,\n next_offset = %llu\n};\n",t._off);
break;
case AST_TOKEN_TYPE_ERROR:
printf("ASTToken = {\n type = AST_TOKEN_TYPE_ERROR,\n next_offset = %llu\n};\n",t._off);
break;
case AST_TOKEN_TYPE_EOF:
printf("ASTToken = {\n type = AST_TOKEN_TYPE_EOF\n};\n");
break;
}
}
ASTObject ast_parse_file(FileObject fo){
ASTObject o=malloc(sizeof(struct _AST_OBJECT));
o->fo=fo;
ASTToken t={
AST_TOKEN_TYPE_UNKNOWN,
._off=0
};
assert(next_token(fo,&t)==0);
INFO("Starting AST Parsing of File '%s'\n",fo->fp);
while (t.t!=AST_TOKEN_TYPE_EOF){
assert(t.t!=AST_TOKEN_TYPE_UNKNOWN);
bool nt=true;
switch (t.t){
default:
assert(!"Not Implemented!");
break;
case AST_TOKEN_TYPE_UNKNOWN:
assert(!"Not Implemented!");
break;
case AST_TOKEN_TYPE_KEYWORD:
assert(!"Not Implemented!");
break;
case AST_TOKEN_TYPE_MODIFIER:
assert(!"Not Implemented!");
break;
case AST_TOKEN_TYPE_STRING:
case AST_TOKEN_TYPE_CHAR:
case AST_TOKEN_TYPE_INT:
case AST_TOKEN_TYPE_FLOAT:
case AST_TOKEN_TYPE_IDENTIFIER:
case AST_TOKEN_TYPE_OPERATOR:
ast_parse_expression(fo,&t,AST_EXPRESSION_END_TYPE_WHITESPACE_OR_SEMICOLON);
nt=false;
break;
case AST_TOKEN_TYPE_WHITESPACE:
break;
case AST_TOKEN_TYPE_ERROR:
assert(!"Not Implemented!");
break;
}
if (nt==true){
print_token(t);
assert(next_token(fo,&t)==0);
}
}
return o;
}
ASTExpression ast_parse_expression(FileObject fo,ASTToken* t,enum AST_EXPRESSION_END_TYPE et){
ASTExpression o=malloc(sizeof(struct _AST_EXPRESSION));
o->t=AST_EXPRESSION_TYPE_EMPTY;
o->bl=0;
o->b=NULL;
size_t i=0;
ASTExpression co=o;
while (true){
if ((et==AST_EXPRESSION_END_TYPE_WHITESPACE_OR_SEMICOLON&&(t->t==AST_TOKEN_TYPE_WHITESPACE||(t->t==AST_TOKEN_TYPE_OPERATOR&&t->dt.op==AST_TOKEN_OPERATOR_SEMICOLON)))){
break;
}
switch (t->t){
default:
assert(!"Not Implemented!");
break;
case AST_TOKEN_TYPE_UNKNOWN:
assert(!"Not Implemented!");
break;
case AST_TOKEN_TYPE_STRING:
assert(!"Not Implemented!");
break;
case AST_TOKEN_TYPE_CHAR:
assert(!"Not Implemented!");
break;
case AST_TOKEN_TYPE_INT:
assert(!"Not Implemented!");
break;
case AST_TOKEN_TYPE_FLOAT:
assert(!"Not Implemented!");
break;
case AST_TOKEN_TYPE_KEYWORD:
assert(!"Not Implemented!");
break;
case AST_TOKEN_TYPE_MODIFIER:
assert(!"Not Implemented!");
break;
case AST_TOKEN_TYPE_IDENTIFIER:
if (co->t==AST_EXPRESSION_TYPE_EMPTY){
co->t=AST_EXPRESSION_TYPE_CONST;
co->a.t=AST_EXPRESSION_ARG_TYPE_IDENTIFIER;
co->a.v.id.il=t->dt.id.il;
co->a.v.id.i=malloc((t->dt.id.il+1)*sizeof(char));
for (size_t j=0;j<t->dt.id.il+1;j++){
*(co->a.v.id.i+j)=*(t->dt.id.i+j);
}
}
else{
assert(!"Not Implemented!");
}
break;
case AST_TOKEN_TYPE_OPERATOR:
if (t->dt.op==AST_TOKEN_OPERATOR_LEFT_PARENTHESIS){
// if (co->t==AST_EXPRESSION_TYPE_CONST){
// co->t=AST_EXPRESSION_TYPE_CALL;
// assert(co->bl==0);
// co->bl=1;
// co->b=malloc(sizeof(struct _AST_EXPRESSION_ARG));
// co->b->t=AST_EXPRESSION_ARG_TYPE_LIST;
// }
// else{
// assert(!"Not Implemented!");
// }
assert(!"Not Implemented!");
break;
}
ASTToken nt;
enum AST_EXPRESSION_TYPE op=AST_EXPRESSION_TYPE_UNKNOWN;
switch (t->dt.op){
default:
assert(!"Not Implemented!");
break;
case AST_TOKEN_OPERATOR_AMP:
nt._off=t->_off;
assert(next_token(fo,&nt)==0);
assert(0);
break;
case AST_TOKEN_OPERATOR_AT:
nt._off=t->_off;
assert(next_token(fo,&nt)==0);
assert(0);
break;
case AST_TOKEN_OPERATOR_CIRCUMFLEX:
nt._off=t->_off;
assert(next_token(fo,&nt)==0);
assert(0);
break;
case AST_TOKEN_OPERATOR_CLOSE_BRACKET:
nt._off=t->_off;
assert(next_token(fo,&nt)==0);
assert(0);
break;
case AST_TOKEN_OPERATOR_COLON:
nt._off=t->_off;
assert(next_token(fo,&nt)==0);
assert(0);
break;
case AST_TOKEN_OPERATOR_COMMA:
nt._off=t->_off;
assert(next_token(fo,&nt)==0);
assert(0);
break;
case AST_TOKEN_OPERATOR_EQUALS:
nt._off=t->_off;
assert(next_token(fo,&nt)==0);
assert(0);
break;
case AST_TOKEN_OPERATOR_EXCLAMATION_MARK:
nt._off=t->_off;
assert(next_token(fo,&nt)==0);
assert(0);
break;
case AST_TOKEN_OPERATOR_GRATER:
nt._off=t->_off;
assert(next_token(fo,&nt)==0);
assert(0);
break;
case AST_TOKEN_OPERATOR_LEFT_BRACES:
nt._off=t->_off;
assert(next_token(fo,&nt)==0);
assert(0);
break;
case AST_TOKEN_OPERATOR_LESS:
nt._off=t->_off;
assert(next_token(fo,&nt)==0);
assert(0);
break;
case AST_TOKEN_OPERATOR_MINUS:
nt._off=t->_off;
assert(next_token(fo,&nt)==0);
assert(0);
break;
case AST_TOKEN_OPERATOR_MODULO:
nt._off=t->_off;
assert(next_token(fo,&nt)==0);
assert(0);
break;
case AST_TOKEN_OPERATOR_OPEN_BRACKET:
nt._off=t->_off;
assert(next_token(fo,&nt)==0);
assert(0);
break;
case AST_TOKEN_OPERATOR_PERIOD:
nt._off=t->_off;
assert(next_token(fo,&nt)==0);
assert(0);
break;
case AST_TOKEN_OPERATOR_PLUS:
nt._off=t->_off;
assert(next_token(fo,&nt)==0);
assert(0);
break;
case AST_TOKEN_OPERATOR_QUESTION_MARK:
nt._off=t->_off;
assert(next_token(fo,&nt)==0);
assert(0);
break;
case AST_TOKEN_OPERATOR_RIGHT_BRACES:
nt._off=t->_off;
assert(next_token(fo,&nt)==0);
assert(0);
break;
case AST_TOKEN_OPERATOR_RIGHT_PARENTHESIS:
nt._off=t->_off;
assert(next_token(fo,&nt)==0);
assert(0);
break;
case AST_TOKEN_OPERATOR_SEMICOLON:
nt._off=t->_off;
assert(next_token(fo,&nt)==0);
assert(0);
break;
case AST_TOKEN_OPERATOR_SLASH:
nt._off=t->_off;
assert(next_token(fo,&nt)==0);
assert(0);
break;
case AST_TOKEN_OPERATOR_STAR:
nt._off=t->_off;
assert(next_token(fo,&nt)==0);
assert(0);
break;
case AST_TOKEN_OPERATOR_TILDA:
nt._off=t->_off;
assert(next_token(fo,&nt)==0);
assert(0);
break;
case AST_TOKEN_OPERATOR_VERTICAL_BAR:
nt._off=t->_off;
assert(next_token(fo,&nt)==0);
assert(0);
break;
}
assert(op>AST_EXPRESSION_TYPE_CONST);
break;
case AST_TOKEN_TYPE_WHITESPACE:
assert(!"Not Implemented!");
break;
case AST_TOKEN_TYPE_ERROR:
assert(!"Not Implemented!");
break;
}
assert(next_token(fo,t)==0);
print_token(*t);
}
assert(i==0);
return o;
}
uint8_t next_token(FileObject fo,ASTToken* t){
if (t->_off>=fo->ln){
t->t=AST_TOKEN_TYPE_EOF;
return 0;
}
t->t=AST_TOKEN_TYPE_UNKNOWN;
while (*(fo->dt+t->_off)==' '||*(fo->dt+t->_off)=='\t'||*(fo->dt+t->_off)=='\n'||*(fo->dt+t->_off)=='\r'){
t->t=AST_TOKEN_TYPE_WHITESPACE;
t->_off++;
}
if (t->t==AST_TOKEN_TYPE_WHITESPACE){
return 0;
}
if (*(fo->dt+t->_off)=='"'){
t->_off++;
t->t=AST_TOKEN_TYPE_STRING;
t->dt.s.sl=1;
t->dt.s.s=NULL;
uint8_t e=0;
while (*(fo->dt+t->_off)!='"'){
uint8_t c=parse_string_char(fo->dt,&(t->_off),&e);
if (e!=0){
return e;
}
t->dt.s.sl++;
t->dt.s.s=realloc(t->dt.s.s,t->dt.s.sl*sizeof(char));
*(t->dt.s.s+t->dt.s.sl-2)=c;
}
t->dt.s.sl--;
*(t->dt.s.s+t->dt.s.sl)=0;
t->_off++;
return 0;
}
CHR_CMP_RET('&',AST_TOKEN_OPERATOR_AMP)
CHR_CMP_RET('@',AST_TOKEN_OPERATOR_AT)
CHR_CMP_RET('^',AST_TOKEN_OPERATOR_CIRCUMFLEX)
CHR_CMP_RET(']',AST_TOKEN_OPERATOR_CLOSE_BRACKET)
CHR_CMP_RET(':',AST_TOKEN_OPERATOR_COLON)
CHR_CMP_RET(',',AST_TOKEN_OPERATOR_COMMA)
CHR_CMP_RET('=',AST_TOKEN_OPERATOR_EQUALS)
CHR_CMP_RET('!',AST_TOKEN_OPERATOR_EXCLAMATION_MARK)
CHR_CMP_RET('>',AST_TOKEN_OPERATOR_GRATER)
CHR_CMP_RET('{',AST_TOKEN_OPERATOR_LEFT_BRACES)
CHR_CMP_RET('(',AST_TOKEN_OPERATOR_LEFT_PARENTHESIS)
CHR_CMP_RET('<',AST_TOKEN_OPERATOR_LESS)
CHR_CMP_RET('-',AST_TOKEN_OPERATOR_MINUS)
CHR_CMP_RET('%',AST_TOKEN_OPERATOR_MODULO)
CHR_CMP_RET('[',AST_TOKEN_OPERATOR_OPEN_BRACKET)
CHR_CMP_RET('.',AST_TOKEN_OPERATOR_PERIOD)
CHR_CMP_RET('+',AST_TOKEN_OPERATOR_PLUS)
CHR_CMP_RET('?',AST_TOKEN_OPERATOR_QUESTION_MARK)
CHR_CMP_RET('}',AST_TOKEN_OPERATOR_RIGHT_BRACES)
CHR_CMP_RET(')',AST_TOKEN_OPERATOR_RIGHT_PARENTHESIS)
CHR_CMP_RET(';',AST_TOKEN_OPERATOR_SEMICOLON)
CHR_CMP_RET('/',AST_TOKEN_OPERATOR_SLASH)
CHR_CMP_RET('*',AST_TOKEN_OPERATOR_STAR)
CHR_CMP_RET('~',AST_TOKEN_OPERATOR_TILDA)
CHR_CMP_RET('|',AST_TOKEN_OPERATOR_VERTICAL_BAR)
size_t i;
STR_CMP_RET("as",2,k,AST_TOKEN_TYPE_KEYWORD,AST_TOKEN_KEYWORD_AS)
STR_CMP_RET("assert",6,k,AST_TOKEN_TYPE_KEYWORD,AST_TOKEN_KEYWORD_ASSERT)
STR_CMP_RET("class",5,k,AST_TOKEN_TYPE_KEYWORD,AST_TOKEN_KEYWORD_CLASS)
STR_CMP_RET("def",3,k,AST_TOKEN_TYPE_KEYWORD,AST_TOKEN_KEYWORD_DEF)
STR_CMP_RET("debugger",8,k,AST_TOKEN_TYPE_KEYWORD,AST_TOKEN_KEYWORD_DEBUGGER)
STR_CMP_RET("delete",6,k,AST_TOKEN_TYPE_KEYWORD,AST_TOKEN_KEYWORD_DELETE)
STR_CMP_RET("elif",4,k,AST_TOKEN_TYPE_KEYWORD,AST_TOKEN_KEYWORD_ELIF)
STR_CMP_RET("else",4,k,AST_TOKEN_TYPE_KEYWORD,AST_TOKEN_KEYWORD_ELSE)
STR_CMP_RET("for",3,k,AST_TOKEN_TYPE_KEYWORD,AST_TOKEN_KEYWORD_FOR)
STR_CMP_RET("if",2,k,AST_TOKEN_TYPE_KEYWORD,AST_TOKEN_KEYWORD_IF)
STR_CMP_RET("import",6,k,AST_TOKEN_TYPE_KEYWORD,AST_TOKEN_KEYWORD_IMPORT)
STR_CMP_RET("raise",5,k,AST_TOKEN_TYPE_KEYWORD,AST_TOKEN_KEYWORD_RAISE)
STR_CMP_RET("return",6,k,AST_TOKEN_TYPE_KEYWORD,AST_TOKEN_KEYWORD_RETURN)
STR_CMP_RET("while",5,k,AST_TOKEN_TYPE_KEYWORD,AST_TOKEN_KEYWORD_WHILE)
STR_CMP_RET("public",6,m,AST_TOKEN_TYPE_MODIFIER,AST_TOKEN_MODIFIER_PUBLIC)
STR_CMP_RET("private",7,m,AST_TOKEN_TYPE_MODIFIER,AST_TOKEN_MODIFIER_PRIVATE)
STR_CMP_RET("static",6,m,AST_TOKEN_TYPE_MODIFIER,AST_TOKEN_MODIFIER_STATIC)
STR_CMP_RET("export",6,m,AST_TOKEN_TYPE_MODIFIER,AST_TOKEN_MODIFIER_EXPORT)
STR_CMP_RET("frozen",6,m,AST_TOKEN_TYPE_MODIFIER,AST_TOKEN_MODIFIER_FROZEN)
STR_CMP_RET("frozentype",10,m,AST_TOKEN_TYPE_MODIFIER,AST_TOKEN_MODIFIER_FROZENTYPE)
STR_CMP_RET("const",5,m,AST_TOKEN_TYPE_MODIFIER,AST_TOKEN_MODIFIER_CONST)
STR_CMP_RET("operator",8,m,AST_TOKEN_TYPE_MODIFIER,AST_TOKEN_MODIFIER_OPERATOR)
t->dt.id.il=1;
t->dt.id.i=NULL;
while ((*(fo->dt+t->_off)>47&&*(fo->dt+t->_off)<58)||(*(fo->dt+t->_off)>64&&*(fo->dt+t->_off)<91)||*(fo->dt+t->_off)==95||(*(fo->dt+t->_off)>96&&*(fo->dt+t->_off)<123)||*(fo->dt+t->_off)>126){
t->dt.id.il++;
t->dt.id.i=realloc(t->dt.id.i,t->dt.id.il+1);
*((char*)t->dt.id.i+t->dt.id.il-2)=*(fo->dt+t->_off);
t->_off++;
}
if (t->dt.id.il>1){
t->dt.id.il--;
t->t=AST_TOKEN_TYPE_IDENTIFIER;
*(t->dt.id.i+t->dt.id.il)=0;
return 0;
}
assert(t->t==AST_TOKEN_TYPE_UNKNOWN);
t->dt.u=*(fo->dt+t->_off);
return 0;
}
uint8_t parse_string_char(uint8_t* s,size_t* i,uint8_t* e){
*e=0;
if (*(s+*i)=='\\'){
(*i)+=2;
switch (*(s+*i-1)){
case 'b':
return 0x08;
case 'd':
{
uint8_t o=0;
bool f=false;
while (48<=*(s+*i)&&*(s+*i)<=57){
if (o<255){
f=true;
if ((unsigned short)o*10+*(s+*i)-48>255){
o=255;
break;
}
o=o*10+*(s+*i)-48;
}
(*i)++;
}
if (f==false){
*e=2;
return 0;
}
return o;
}
case 'e':
return 0x1b;
case 'f':
return 0x0c;
case 'n':
return 0x0a;
case 'o':
{
uint8_t o=0;
bool f=false;
while (48<=*(s+*i)&&*(s+*i)<=55){
if (o<255){
f=true;
if ((unsigned short)o*8+*(s+*i)-48>255){
o=255;
break;
}
o=o*8+*(s+*i)-48;
}
(*i)++;
}
if (f==false){
*e=3;
return 0;
}
return o;
}
case 'r':
return 0x0d;
case 't':
return 0x09;
case 'v':
return 0x0b;
case 'x':
{
uint8_t o=0;
bool f=false;
while ((48<=*(s+*i)&&*(s+*i)<=57)||(97<=*(s+*i)&&*(s+*i)<=102)){
if (o<255){
f=true;
if ((unsigned short)o*16+(*(s+*i)<=57?*(s+*i)-48:*(s+*i)-87)>255){
o=255;
break;
}
o=o*16+(*(s+*i)<=57?*(s+*i)-48:*(s+*i)-87);
}
(*i)++;
}
if (f==false){
*e=4;
return 0;
}
return o;
}
case '\'':
return 0x27;
case '\"':
return 0x22;
default:
(*i)--;
*e=1;
return 0;
}
}
uint8_t o=*(s+*i);
(*i)++;
return o;
}
|
Krzem5/C-Custom_Lang_Compiler
|
src/compiler/loader.c
|
#include <common.h>
#include <loader.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
SearchPathList loader_search_path_list={
0,
NULL
};
void loader_add_search_path(char* p){
assert(p!=NULL);
uint32_t ln=0;
while (*(p+ln)!=0){
ln++;
}
assert(ln>0);
if (*(p+ln-1)!='/'&&*(p+ln-1)!='\\'){
*(p+ln)='/';
ln++;
}
loader_search_path_list.ln++;
loader_search_path_list.e=realloc(loader_search_path_list.e,loader_search_path_list.ln*sizeof(struct _SEARCH_PATH_LIST_ELEM));
(loader_search_path_list.e+loader_search_path_list.ln-1)->ln=ln;
(loader_search_path_list.e+loader_search_path_list.ln-1)->p=malloc((ln+1)*sizeof(char));
*((loader_search_path_list.e+loader_search_path_list.ln-1)->p+ln)=0;
while (ln>0){
ln--;
*((loader_search_path_list.e+loader_search_path_list.ln-1)->p+ln)=*(p+ln);
}
INFO("Adding Search Path '%s'\n",(loader_search_path_list.e+loader_search_path_list.ln-1)->p);
}
FileObject loader_load_file(char* fp){
assert(fp!=NULL);
INFO("Looking for File '%s'\n",fp);
FileObject o=malloc(sizeof(struct _FILE_OBJECT));
o->fpl=0;
o->fp=NULL;
o->ln=0;
o->dt=NULL;
INFO("Trying '%s'\n",fp);
FILE* f=NULL;
errno_t e=fopen_s(&f,fp,"rb");
if (e!=0){
if (e!=ENOENT){
ERROR("fopen_s returned Error Code '%u'\n",e);
free(o);
return NULL;
}
uint32_t fpln=0;
for (uint32_t i=0;i<loader_search_path_list.ln;i++){
if (fpln==0){
while (*(fp+fpln)!=0){
fpln++;
}
assert(fpln>0);
}
o->fpl=(loader_search_path_list.e+i)->ln+fpln;
o->fp=malloc((o->fpl+1)*sizeof(char));
uint32_t j=0;
for (;j<(loader_search_path_list.e+i)->ln;j++){
*(o->fp+j)=*((loader_search_path_list.e+i)->p+j);
}
for (;j<(loader_search_path_list.e+i)->ln+fpln;j++){
*(o->fp+j)=*(fp+j-(loader_search_path_list.e+i)->ln);
}
*(o->fp+j)=0;
INFO("Trying '%s'\n",o->fp);
e=fopen_s(&f,o->fp,"rb");
if (e==0){
char* tmp=o->fp;
o->fp=malloc(_MAX_PATH*sizeof(char));
assert(_fullpath(o->fp,tmp,_MAX_PATH)!=NULL);
free(tmp);
o->fpl=0;
while (*(o->fp+o->fpl)!=0){
o->fpl++;
}
assert(o->fpl>0);
o->fp=realloc(o->fp,(o->fpl+1)*sizeof(char));
break;
}
free(o->fp);
if (e==ENOENT){
continue;
}
ERROR("fopen_s returned Error Code '%u'\n",e);
free(o);
return NULL;
}
}
else{
o->fp=malloc(_MAX_PATH*sizeof(char));
assert(_fullpath(o->fp,fp,_MAX_PATH)!=NULL);
while (*(o->fp+o->fpl)!=0){
o->fpl++;
}
assert(o->fpl>0);
o->fp=realloc(o->fp,(o->fpl+1)*sizeof(char));
}
if (f==NULL){
free(o);
return NULL;
}
fseek(f,0,SEEK_END);
o->ln=ftell(f);
fseek(f,0,SEEK_SET);
o->dt=malloc(o->ln*sizeof(uint8_t));
assert(fread(o->dt,sizeof(uint8_t),o->ln,f)==o->ln);
fclose(f);
INFO("Found File '%s' as '%s'\n",fp,o->fp);
return o;
}
|
Krzem5/C-Custom_Lang_Compiler
|
src/include/ast.h
|
#ifndef __PARSER_H__
#define __PARSER_H__
#include <common.h>
#include <loader.h>
#include <stdio.h>
typedef struct _AST_TOKEN ASTToken;
typedef struct _AST_EXPRESSION_ARG ASTExpressionArg;
typedef struct _AST_EXPRESSION* ASTExpression;
typedef struct _AST_OBJECT* ASTObject;
enum AST_TOKEN_TYPE{
AST_TOKEN_TYPE_UNKNOWN=0x00,
AST_TOKEN_TYPE_STRING=0x01,
AST_TOKEN_TYPE_CHAR=0x02,
AST_TOKEN_TYPE_INT=0x03,
AST_TOKEN_TYPE_FLOAT=0x04,
AST_TOKEN_TYPE_KEYWORD=0x05,
AST_TOKEN_TYPE_MODIFIER=0x06,
AST_TOKEN_TYPE_IDENTIFIER=0x07,
AST_TOKEN_TYPE_OPERATOR=0x08,
AST_TOKEN_TYPE_WHITESPACE=0x09,
AST_TOKEN_TYPE_ERROR=0xfe,
AST_TOKEN_TYPE_EOF=0xff
};
enum AST_TOKEN_MODIFIER{
AST_TOKEN_MODIFIER_UNKNOWN=0x00,
AST_TOKEN_MODIFIER_PUBLIC=0x01,
AST_TOKEN_MODIFIER_PRIVATE=0x02,
AST_TOKEN_MODIFIER_STATIC=0x04,
AST_TOKEN_MODIFIER_EXPORT=0x08,
AST_TOKEN_MODIFIER_FROZEN=0x10,
AST_TOKEN_MODIFIER_FROZENTYPE=0x20,
AST_TOKEN_MODIFIER_CONST=0x40,
AST_TOKEN_MODIFIER_OPERATOR=0x80
};
enum AST_TOKEN_KEYWORD{
AST_TOKEN_KEYWORD_UNKNOWN=0x00,
AST_TOKEN_KEYWORD_AS=0x01,
AST_TOKEN_KEYWORD_ASSERT=0x02,
AST_TOKEN_KEYWORD_CLASS=0x03,
AST_TOKEN_KEYWORD_DEF=0x04,
AST_TOKEN_KEYWORD_DEBUGGER=0x05,
AST_TOKEN_KEYWORD_DELETE=0x06,
AST_TOKEN_KEYWORD_ELIF=0x07,
AST_TOKEN_KEYWORD_ELSE=0x08,
AST_TOKEN_KEYWORD_FOR=0x09,
AST_TOKEN_KEYWORD_IF=0x0a,
AST_TOKEN_KEYWORD_IMPORT=0x0b,
AST_TOKEN_KEYWORD_RAISE=0x0c,
AST_TOKEN_KEYWORD_RETURN=0x0d,
AST_TOKEN_KEYWORD_WHILE=0x0e
};
enum AST_TOKEN_OPERATOR{
AST_TOKEN_OPERATOR_UNKNOWN=0x00,
AST_TOKEN_OPERATOR_AMP=0x01,
AST_TOKEN_OPERATOR_AT=0x02,
AST_TOKEN_OPERATOR_CIRCUMFLEX=0x03,
AST_TOKEN_OPERATOR_CLOSE_BRACKET=0x04,
AST_TOKEN_OPERATOR_COLON=0x05,
AST_TOKEN_OPERATOR_COMMA=0x06,
AST_TOKEN_OPERATOR_EQUALS=0x07,
AST_TOKEN_OPERATOR_EXCLAMATION_MARK=0x08,
AST_TOKEN_OPERATOR_GRATER=0x09,
AST_TOKEN_OPERATOR_LEFT_BRACES=0x0a,
AST_TOKEN_OPERATOR_LEFT_PARENTHESIS=0x0b,
AST_TOKEN_OPERATOR_LESS=0x0c,
AST_TOKEN_OPERATOR_MINUS=0x0d,
AST_TOKEN_OPERATOR_MODULO=0x0e,
AST_TOKEN_OPERATOR_OPEN_BRACKET=0x0f,
AST_TOKEN_OPERATOR_PERIOD=0x10,
AST_TOKEN_OPERATOR_PLUS=0x11,
AST_TOKEN_OPERATOR_QUESTION_MARK=0x12,
AST_TOKEN_OPERATOR_RIGHT_BRACES=0x13,
AST_TOKEN_OPERATOR_RIGHT_PARENTHESIS=0x14,
AST_TOKEN_OPERATOR_SEMICOLON=0x15,
AST_TOKEN_OPERATOR_SLASH=0x16,
AST_TOKEN_OPERATOR_STAR=0x17,
AST_TOKEN_OPERATOR_TILDA=0x18,
AST_TOKEN_OPERATOR_VERTICAL_BAR=0x19
};
enum AST_EXPRESSION_TYPE{
AST_EXPRESSION_TYPE_UNKNOWN=0x00,
AST_EXPRESSION_TYPE_EMPTY=0x01,
AST_EXPRESSION_TYPE_CONST=0x02,
AST_EXPRESSION_TYPE_LST=0x03,
AST_EXPRESSION_TYPE_ARR=0x04,
AST_EXPRESSION_TYPE_EXPAND=0x05,
AST_EXPRESSION_TYPE_INC=0x06,
AST_EXPRESSION_TYPE_DEC=0x07,
AST_EXPRESSION_TYPE_CALL=0x08,
AST_EXPRESSION_TYPE_SLC=0x09,
AST_EXPRESSION_TYPE_ACS=0x0a,
AST_EXPRESSION_TYPE_DEREF=0xfe,/***************************/
AST_EXPRESSION_TYPE_REF=0xff,/*****************************/
AST_EXPRESSION_TYPE_PLUS=0x0b,
AST_EXPRESSION_TYPE_MINUS=0x0c,
AST_EXPRESSION_TYPE_NOT=0x0d,
AST_EXPRESSION_TYPE_BNOT=0x0e,
AST_EXPRESSION_TYPE_POW=0x0f,
AST_EXPRESSION_TYPE_ROOT=0x10,
AST_EXPRESSION_TYPE_IROOT=0x11,
AST_EXPRESSION_TYPE_MLT=0x12,
AST_EXPRESSION_TYPE_DIV=0x13,
AST_EXPRESSION_TYPE_FDIV=0x14,
AST_EXPRESSION_TYPE_MOD=0x15,
AST_EXPRESSION_TYPE_MMLT=0x16,
AST_EXPRESSION_TYPE_ADD=0x17,
AST_EXPRESSION_TYPE_SUB=0x18,
AST_EXPRESSION_TYPE_LSH=0x19,
AST_EXPRESSION_TYPE_RSH=0x1a,
AST_EXPRESSION_TYPE_LT=0x1b,
AST_EXPRESSION_TYPE_LE=0x1c,
AST_EXPRESSION_TYPE_GT=0x1d,
AST_EXPRESSION_TYPE_GE=0x1e,
AST_EXPRESSION_TYPE_EQ=0x1f,
AST_EXPRESSION_TYPE_NE=0x20,
AST_EXPRESSION_TYPE_BAND=0x21,
AST_EXPRESSION_TYPE_BXOR=0x22,
AST_EXPRESSION_TYPE_BOR=0x23,
AST_EXPRESSION_TYPE_AND=0x24,
AST_EXPRESSION_TYPE_OR=0x25,
AST_EXPRESSION_TYPE_TCOND=0x26,
AST_EXPRESSION_TYPE_EQU=0x27,
AST_EXPRESSION_TYPE_ADD_EQU=0x28,
AST_EXPRESSION_TYPE_SUB_EQU=0x29,
AST_EXPRESSION_TYPE_MLT_EQU=0x2a,
AST_EXPRESSION_TYPE_DIV_EQU=0x2b,
AST_EXPRESSION_TYPE_FDIV_EQU=0x2c,
AST_EXPRESSION_TYPE_MOD_EQU=0x2d,
AST_EXPRESSION_TYPE_MMLT_EQU=0x2e,
AST_EXPRESSION_TYPE_POW_EQU=0x2f,
AST_EXPRESSION_TYPE_ROOT_EQU=0x30,
AST_EXPRESSION_TYPE_IROOT_EQU=0x31,
AST_EXPRESSION_TYPE_LSH_EQU=0x32,
AST_EXPRESSION_TYPE_RSH_EQU=0x33,
AST_EXPRESSION_TYPE_BAND_EQU=0x34,
AST_EXPRESSION_TYPE_BXOR_EQU=0x35,
AST_EXPRESSION_TYPE_BOR_EQU=0x36
};
enum AST_EXPRESSION_ARG_TYPE{
AST_EXPRESSION_ARG_TYPE_UNKNOWN=0x00,
AST_EXPRESSION_ARG_TYPE_EXPRESSION=0x01,
AST_EXPRESSION_ARG_TYPE_STRING=0x02,
AST_EXPRESSION_ARG_TYPE_CHAR=0x03,
AST_EXPRESSION_ARG_TYPE_INT=0x04,
AST_EXPRESSION_ARG_TYPE_FLOAT=0x05,
AST_EXPRESSION_ARG_TYPE_IDENTIFIER=0x06
};
enum AST_EXPRESSION_END_TYPE{
AST_EXPRESSION_END_TYPE_WHITESPACE_OR_SEMICOLON=0x00,
AST_EXPRESSION_END_TYPE_SEMICOLON=0x01,
AST_EXPRESSION_END_TYPE_COLON=0x02
};
struct _AST_TOKEN{
enum AST_TOKEN_TYPE t;
union _AST_TOKEN_DATA{
char u;
struct _AST_TOKEN_DATA_STRING{
size_t sl;
char* s;
} s;
char c;
int64_t i;
double f;
enum AST_TOKEN_KEYWORD k;
enum AST_TOKEN_MODIFIER m;
struct _AST_TOKEN_DATA_IDENTIFIER{
size_t il;
char* i;
} id;
enum AST_TOKEN_OPERATOR op;
} dt;
size_t _off;
};
struct _AST_EXPRESSION_ARG{
enum AST_EXPRESSION_ARG_TYPE t;
union _AST_EXPRESSION_ARG_VALUE{
struct _AST_EXPRESSION* ex;
struct _AST_EXPRESSION_ARG_VALUE_STRING{
size_t sl;
char* s;
} s;
char c;
int64_t i;
double f;
struct _AST_EXPRESSION_ARG_VALUE_IDENTIFIER{
size_t il;
char* i;
} id;
} v;
};
struct _AST_EXPRESSION{
enum AST_EXPRESSION_TYPE t;
ASTExpressionArg a;
uint8_t bl;
ASTExpressionArg* b;
};
struct _AST_OBJECT{
FileObject fo;
};
ASTObject ast_parse_file(FileObject fo);
ASTExpression ast_parse_expression(FileObject fo,ASTToken* t,enum AST_EXPRESSION_END_TYPE);
uint8_t next_token(FileObject fo,ASTToken* t);
uint8_t parse_string_char(uint8_t* s,size_t* i,uint8_t* e);
#endif
|
Krzem5/C-Custom_Lang_Compiler
|
src/include/free.h
|
<reponame>Krzem5/C-Custom_Lang_Compiler<filename>src/include/free.h<gh_stars>0
#ifndef __FREE_H__
#define __FREE_H__
#include <loader.h>
#include <ast.h>
void free_file_object(FileObject fo);
void free_ast_object(ASTObject ast);
#endif
|
Krzem5/C-Custom_Lang_Compiler
|
src/include/compiler.h
|
<reponame>Krzem5/C-Custom_Lang_Compiler<gh_stars>0
#ifndef __COMPILER_H__
#define __COMPILER_H__
int compiler_run_all(int argc,const char** argv);
#endif
|
Krzem5/C-Custom_Lang_Compiler
|
src/include/common.h
|
#ifndef __COMMON_H__
#define __COMMON_H__
#include <stdint.h>
#include <limits.h>
#include <signal.h>
#ifdef NULL
#undef NULL
#endif
#define NULL ((void*)0)
#define bool _Bool
#define true 1
#define false 0
#define assert(x) \
do{ \
if (!(x)){ \
printf("%s: Line %u (%s): %s: Assertion Failed\n",__FILE__,__LINE__,__func__,#x); \
raise(SIGABRT); \
} \
} while (0)
#define INFO(f,...) printf("[INFO] " f,__VA_ARGS__)
#define WARN(f,...) printf("[WARN] " f,__VA_ARGS__)
#define ERROR(f,...) fprintf(stderr,"[ERROR] " f,__VA_ARGS__)
#endif
|
Krzem5/C-Custom_Lang_Compiler
|
src/include/custom_lang_compiler.h
|
#ifndef __CUSTOM_LANG_COMPILER_H__
#define __CUSTOM_LANG_COMPILER_H__ 1
//
#endif
|
Krzem5/C-Custom_Lang_Compiler
|
src/compiler/compiler.c
|
<reponame>Krzem5/C-Custom_Lang_Compiler<filename>src/compiler/compiler.c
#include <common.h>
#include <compiler.h>
#include <loader.h>
#include <free.h>
#include <stdio.h>
#include <stdlib.h>
int compiler_run_all(int argc,const char** argv){
uint32_t fpll=0;
char** fpl=NULL;
for (int i=1;i<argc;i++){
size_t j=0;
while (*(*(argv+i)+j)=='\t'||*(*(argv+i)+j)=='\n'||*(*(argv+i)+j)=='\r'){
j++;
}
if (*(*(argv+i)+j)==0){
continue;
}
if (*(*(argv+i)+j)=='-'){
j++;
switch (*(*(argv+i)+j)){
case 'I':
loader_add_search_path((char*)*(argv+i)+j+1);
break;
default:
ERROR("Unknown Switch '%s'\n",*(argv+i));
return 1;
}
}
else{
fpll++;
fpl=realloc(fpl,fpll*sizeof(char*));
*(fpl+fpll-1)=(char*)*(argv+i);
}
}
if (fpll==0){
ERROR("No Files Specified. Stopping compilation.\n");
return 1;
}
for (uint32_t i=0;i<fpll;i++){
FileObject f=loader_load_file(*(fpl+i));
if (f==NULL){
ERROR("File '%s' not Found within the Provided Search Path.\n",*(fpl+i));
return 1;
}
ASTObject ast=ast_parse_file(f);
if (ast==NULL){
ERROR("AST ERROR!\n");
return 1;
}
free_ast_object(ast);
free_file_object(f);
}
free(fpl);
return 0;
}
|
Krzem5/C-Custom_Lang_Compiler
|
src/main.c
|
<filename>src/main.c<gh_stars>0
#include <compiler.h>
int main(int argc,const char** argv){
return compiler_run_all(argc,argv);
}
|
a64091937/STM32_Basic_Test1
|
User/rcc/bsp_clkconfig.h
|
#ifndef __CLKCONFIG_H
#define __CLKCONFIG_H
#include "stm32f4xx.h"
void HSE_SetSysClock(uint32_t m, uint32_t n, uint32_t p, uint32_t q);
void HSI_SetSysClock(uint32_t m, uint32_t n, uint32_t p, uint32_t q);
void MCO1_GPIO_Config(void);
void MCO2_GPIO_Config(void);
#endif /* __CLKCONFIG_H */
|
FenomenCoyote/Redes
|
Practica2.2/ejercicio8/Chat.h
|
<reponame>FenomenCoyote/Redes<filename>Practica2.2/ejercicio8/Chat.h<gh_stars>0
#ifndef _CHAT_H
#define _CHAT_H
#include <string>
#include <unistd.h>
#include <string.h>
#include <vector>
#include <memory>
#include "Serializable.h"
#include "Socket.h"
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
/**
* Mensaje del protocolo de la aplicación de Chat
*
* +-------------------+
* | Tipo: uint8_t | 0 (login), 1 (mensaje), 2 (logout)
* +-------------------+
* | Nick: char[8] | Nick incluido el char terminación de cadena '\0'
* +-------------------+
* | |
* | Mensaje: char[80] | Mensaje incluido el char terminación de cadena '\0'
* | |
* +-------------------+
*
*/
class ChatMessage: public Serializable
{
public:
static const size_t MESSAGE_SIZE = sizeof(char) * 88 + sizeof(uint8_t);
enum MessageType
{
LOGIN = 0,
MESSAGE = 1,
LOGOUT = 2
};
ChatMessage(){};
~ChatMessage() {}
ChatMessage(const std::string& n, const std::string& m):nick(n),message(m){};
void to_bin();
int from_bin(char * bobj);
uint8_t type;
std::string nick;
std::string message;
};
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
/**
* Clase para el servidor de chat
*/
class ChatServer
{
public:
ChatServer(const char * s, const char * p): socket(s, p)
{
socket.bind();
};
/**
* Thread principal del servidor recive mensajes en el socket y
* lo distribuye a los clientes. Mantiene actualizada la lista de clientes
*/
void do_messages();
private:
/**
* Lista de clientes conectados al servidor de Chat, representados por
* su socket
*/
std::vector<std::unique_ptr<Socket>> clients;
/**
* Socket del servidor
*/
Socket socket;
};
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
/**
* Clase para el cliente de chat
*/
class ChatClient
{
public:
/**
* @param s dirección del servidor
* @param p puerto del servidor
* @param n nick del usuario
*/
ChatClient(const char * s, const char * p, const char * n):socket(s, p),
nick(n){};
/**
* Envía el mensaje de login al servidor
*/
void login();
/**
* Envía el mensaje de logout al servidor
*/
void logout();
/**
* Rutina principal para el Thread de E/S. Lee datos de STDIN (std::getline)
* y los envía por red vía el Socket.
*/
void input_thread();
/**
* Rutina del thread de Red. Recibe datos de la red y los "renderiza"
* en STDOUT
*/
void net_thread();
private:
/**
* Socket para comunicar con el servidor
*/
Socket socket;
/**
* Nick del usuario
*/
std::string nick;
};
#endif
|
bananita/Echoes
|
Echoes/Echoes/MBERequest.h
|
<reponame>bananita/Echoes<filename>Echoes/Echoes/MBERequest.h
//
// MBERequest.h
// Echoes
//
// Created by <NAME> on 04.06.2015.
// Copyright (c) 2015 SO MANY APPS. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface MBERequest : NSObject <NSCopying>
@property NSString *URL;
@property NSString *method;
@property NSDictionary *headers;
- (NSDictionary *)dictionary;
- (instancetype)initWithDictionary:(NSDictionary*)dictionary;
- (instancetype)initWithURLRequest:(NSURLRequest *)request;
@end
|
bananita/Echoes
|
Echoes/Echoes/MBECurrentRecordingSetProvider.h
|
<gh_stars>0
//
// MBECurrentRecordingSetProvider.h
// Echoes
//
// Created by <NAME> on 04.06.2015.
// Copyright (c) 2015 SO MANY APPS. All rights reserved.
//
#import <Foundation/Foundation.h>
#import "MBERequest.h"
#import "MBERecord.h"
@interface MBECurrentRecordingSetProvider : NSObject
@property NSMutableDictionary *recordings;
+ (void)addRecord:(MBERecord *)record forRequest:(MBERequest *)request;
+ (MBERecord *)recordForRequest:(MBERequest *)request;
+ (BOOL)isRecordForRequest:(MBERequest *)request;
+ (void)save;
+ (instancetype)sharedInstance;
@end
|
bananita/Echoes
|
Echoes/Echoes/MBERecord.h
|
<filename>Echoes/Echoes/MBERecord.h
//
// MBERecord.h
// Echoes
//
// Created by <NAME> on 04.06.2015.
// Copyright (c) 2015 SO MANY APPS. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface MBERecord : NSObject
@property NSDictionary *headers;
@property NSUInteger statusCode;
@property NSData *data;
- (NSDictionary *)dictionary;
- (instancetype)initWithDictionary:(NSDictionary*)dictionary;
@end
|
bananita/Echoes
|
Echoes/Echoes/MBEReplayingProtocol.h
|
//
// MBEReplayingProtocol.h
// Echoes
//
// Created by <NAME> on 04.06.2015.
// Copyright (c) 2015 SO MANY APPS. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface MBEReplayingProtocol : NSURLProtocol
@end
|
bananita/Echoes
|
Echoes/ViewController.h
|
//
// ViewController.h
// Echoes
//
// Created by <NAME> on 04.06.2015.
// Copyright (c) 2015 SO MANY APPS. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
@end
|
bananita/Echoes
|
Echoes/Echoes/Echoes.h
|
<filename>Echoes/Echoes/Echoes.h
//
// Echoes.h
// Echoes
//
// Created by <NAME> on 04.06.2015.
// Copyright (c) 2015 SO MANY APPS. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface Echoes : NSObject
@property BOOL recording;
@property NSString *currentRecordingName;
+ (void)startWithRecordingEnabled:(BOOL)recordingEnabled;
+ (void)setCurrentRecordingName:(NSString *)name;
+ (void)stop;
+ (instancetype)sharedInstance;
@end
|
Garciaj007/AEngine
|
AEngine/src/Core/Utils.h
|
#pragma once
#include "Graphics/Mesh.h"
class Utils
{
public:
static std::string ReadTextFile(const char*);
};
|
Garciaj007/AEngine
|
AEngine/src/Scene/IScene.h
|
<gh_stars>0
#pragma once
#include "Systems/EntityComponent.h"
class IScene
{
public:
explicit IScene() = default;
virtual ~IScene() = default;
virtual bool Initialize() = 0;
virtual void Update(const float) = 0;
virtual void Render() const = 0;
virtual void ResizeUpdate() const = 0;
virtual void Destroy() const = 0;
protected:
std::unique_ptr<EntityManager> sceneEntityManagerPtr;
friend std::default_delete<IScene>;
};
|
Garciaj007/AEngine
|
AEngine/src/Graphics/TextureHandler.h
|
#pragma once
struct Texture
{
GLuint textureId = 0;
int width = 0;
int height = 0;
int colorChannels = 0;
};
class TextureHandler
{
public:
TextureHandler(const TextureHandler&) = delete;
TextureHandler(TextureHandler&&) = delete;
TextureHandler& operator=(const TextureHandler&) = delete;
TextureHandler& operator=(TextureHandler&&) = delete;
static TextureHandler* GetInstance();
[[nodiscard]] static GLuint GetTextureId(const std::string& textureName)
{
const auto textureIt = textures.find(textureName);
if (textureIt == textures.end()) return 0;
return textureIt->second->textureId;
}
/*[[nodiscard]] inline Texture* GetTexture(const std::string& textureName)
{
return textures.find(textureName)->second;
}*/
static void CreateTexture(const std::string& textureName, const std::string& path);
void Destroy() const;
private:
TextureHandler() = default;
~TextureHandler();
static std::map<std::string, std::unique_ptr<Texture>> textures;
static std::unique_ptr<TextureHandler> instance;
friend std::default_delete<TextureHandler>;
};
|
Garciaj007/AEngine
|
AEngine/src/Physics/CollisionDetection.h
|
<reponame>Garciaj007/AEngine<gh_stars>0
#pragma once
#include "Graphics/Camera.h"
struct BoundingBox;
struct Ray;
class CollisionDetection
{
public:
CollisionDetection() = delete;
~CollisionDetection() = delete;
static Ray ViewportPointToRay(glm::vec2, glm::vec2, Camera*);
static bool RayCastHit(Ray&, BoundingBox*);
private:
static bool RayCastCheckAxis(float, float, float, float, float&, float&);
};
|
Garciaj007/AEngine
|
AEngine/src/Graphics/Camera.h
|
<filename>AEngine/src/Graphics/Camera.h
#pragma once
#include "Systems/EntityComponent.h"
#include "Components/Transform.h"
#include <Rendering\Frustum.h>
class Camera final : public Component
{
public:
Camera() = default;
Camera(float, glm::vec2, bool lookAtEnabled = true);
void Start() override;
void Update(const float dt) override;
void ResizeUpdate() override;
void AddLight(Entity* light) { lights.emplace_back(light); }
[[nodiscard]] inline std::vector<Entity*> GetLights() const { return lights; }
[[nodiscard]] inline glm::vec2 GetClippingPlanes() const { return clipPlanes; }
[[nodiscard]] inline glm::vec3 GetPosition() const { return transformPtr->position; }
[[nodiscard]] inline glm::mat4 GetPerspectiveMatrix() const { return perspective; }
[[nodiscard]] inline glm::mat4 GetOrthographicMatrix() const { return orthographic; }
[[nodiscard]] inline glm::mat4 GetViewMatrix() const
{
//return glm::lookAt(transformPtr->position, glm::normalize(transformPtr->position - glm::vec3(0.0f)), up);
return transformPtr->GetOrientationMatrix();
}
private:
void UpdateCameraOrientation();
std::vector<Entity*> lights;
Frustum frustum;
Transform* transformPtr;
bool lookAtEnabled = true;
float fov = 0;
glm::mat4 perspective, orthographic;
glm::vec2 clipPlanes;
glm::vec3 forward, up, right;
glm::vec3 worldUp;
};
|
Garciaj007/AEngine
|
AEngine/src/Graphics/MaterialHandler.h
|
#pragma once
class MaterialHandler
{
public:
struct Material
{
GLuint diffuseMap = 0;
float roughness = 0.0f;
float transparency = 0.0f;
glm::vec3 ambientColor = glm::vec3(1.0f);
glm::vec3 diffuseColor = glm::vec3(1.0f);
glm::vec3 specularColor = glm::vec3(1.0f);
};
MaterialHandler(const MaterialHandler&) = delete;
MaterialHandler(MaterialHandler&&) = delete;
MaterialHandler& operator=(const MaterialHandler&) = delete;
MaterialHandler& operator=(MaterialHandler&&) = delete;
static MaterialHandler* GetInstance();
void AddMaterial(std::string, Material);
Material GetMaterial(std::string);
void Clear();
private:
MaterialHandler() = default;
~MaterialHandler();
static std::map<std::string, Material> materials;
static std::unique_ptr<MaterialHandler> instance;
friend std::default_delete<MaterialHandler>;
};
|
Garciaj007/AEngine
|
AEngine/src/Core/Logger.h
|
<reponame>Garciaj007/AEngine
#pragma once
class Logger
{
public:
enum class MessageSeverity : unsigned short {
RAD_NONE,
RAD_INFO,
RAD_TRACE,
RAD_ERROR,
RAD_WARNING,
RAD_FATAL_ERROR,
};
Logger(const Logger&) = delete;
Logger(Logger&&) = delete;
Logger& operator=(const Logger&) = delete;
Logger& operator=(Logger&&) = delete;
Logger() = delete;
static void Log(const MessageSeverity, const std::string&, const std::string&, const int);
private:
static MessageSeverity type;
static std::string msg;
};
#define LOG_INFO(msg, fileName, line) { Logger::Log(Logger::MessageSeverity::RAD_INFO, msg, fileName, line); }
#define LOG_TRACE(msg, fileName, line) { Logger::Log(Logger::MessageSeverity::RAD_TRACE, msg, fileName, line); }
#define LOG_ERROR(msg, fileName, line) { Logger::Log(Logger::MessageSeverity::RAD_ERROR, msg, fileName, line); }
#define LOG_WARNING(msg, fileName, line) { Logger::Log(Logger::MessageSeverity::RAD_WARNING, msg, fileName, line); }
#define LOG_FATAL_ERROR(msg, fileName, line) { Logger::Log(Logger::MessageSeverity::RAD_FATAL_ERROR, msg, fileName, line); }
|
Garciaj007/AEngine
|
AEngine/src/Rendering/SceneGraph.h
|
#pragma once
class Model;
class Entity;
class GameObject;
class SceneGraph
{
public:
SceneGraph(const SceneGraph&) = delete;
SceneGraph(SceneGraph&&) = delete;
SceneGraph& operator=(const SceneGraph&) = delete;
SceneGraph& operator=(SceneGraph) = delete;
static SceneGraph* GetInstance();
void AddModel(Model*);
void AddGameObject(class GameObject*, std::string);
class GameObject* GetGameObjects(std::string);
void Update(float dt);
void Render();
void Destroy() const;
static std::map<std::string, std::unique_ptr<GameObject>>& GetGameObjects() { return gameObjects; }
private:
SceneGraph() = default;
~SceneGraph();
static std::map<GLuint, std::vector<Model*>> shaderModels;
static std::map<std::string, std::unique_ptr<GameObject>> gameObjects;
static std::unique_ptr<SceneGraph> instance;
friend std::default_delete<SceneGraph>;
};
|
Garciaj007/AEngine
|
AEngine/src/Events/IEvent.h
|
<reponame>Garciaj007/AEngine
#pragma once
#include <Core/AEpch.h>
template <typename... Args>
class ISubscriber
{
public:
virtual ~ISubscriber() = default;
virtual void Invoke(Args... args) = 0;
virtual bool IsInstanceOf(void* signature) = 0;
};
template <typename T, typename... Args>
class Subscriber : public ISubscriber<Args...>
{
public:
Subscriber(T* t, void(T::*func)(Args...)) : t(t), func(func) {}
void Invoke(Args... args) final { (t->*func)(args...); }
bool IsInstanceOf(void* signature) final { return signature == static_cast<void*>(t); }
private:
T* t;
void(T::*func)(Args...);
};
class IEvent
{
public:
virtual void UnSubscribe(void* t) = 0;
};
template <typename... Args>
class Event : public IEvent
{
public:
void Execute(Args... args)
{
for(auto& func : subscribers)
func->Invoke(args...);
}
template <typename T>
void Subscribe(T* t, void(T::*func)(Args... args))
{
auto subscriber = new Subscriber<T, Args...>(t, func);
subscribers.push_back(std::unique_ptr<ISubscriber<Args...>>(subscriber));
}
void UnSubscribe(void* t) final
{
auto subscriberToRemove = std::remove_if(
subscribers.begin(), subscribers.end(),
[t](auto& s) { return s->IsInstanceOf(t); }
);
subscribers.erase(subscriberToRemove, subscribers.end());
}
private:
std::vector<std::unique_ptr<ISubscriber<Args...>>> subscribers;
};
template<typename Derived>
class EventListener
{
public:
~EventListener()
{
for(auto& e : events) e->UnSubscribe(static_cast<void*>(this));
}
template<typename... Args>
void Listen(Event<Args...>& e, void(Derived::*methodToListen)(Args... args))
{
e.Subscribe(static_cast<Derived*>(this), methodToListen);
events.push_back(&e);
}
private:
std::vector<IEvent*> events;
};
|
Garciaj007/AEngine
|
AEngine/src/Graphics/Light.h
|
#pragma once
#include "Systems/EntityComponent.h"
struct Light final : Component
{
Light(const float ambient, const float diffuse, const glm::vec3 color) : ambient(ambient),
diffuse(diffuse),
color(color)
{}
float ambient, diffuse;
glm::vec3 color;
};
|
Garciaj007/AEngine
|
AEngine/src/Graphics/ObjLoader.h
|
#pragma once
#include "Graphics/Mesh.h"
#include "Physics/BoundingBox.h"
class ObjLoader
{
public:
~ObjLoader();
void LoadMeshData(const std::string& fileName);
void LoadMeshData(const std::string& fileName, const std::string& matName);
[[nodiscard]] std::vector<Vertex> GetVertices() const { return meshVertices; }
[[nodiscard]] std::vector<GLuint> GetIndices() const { return indices; }
[[nodiscard]] std::vector<Mesh> GetMeshData() const { return meshes; }
private:
std::vector<glm::vec3> vertices = std::vector<glm::vec3>();
std::vector<glm::vec3> normals = std::vector<glm::vec3>();
std::vector<glm::vec2> uvCoords = std::vector<glm::vec2>();
std::vector<GLuint> indices = std::vector<GLuint>();
std::vector<GLuint> normalIndices = std::vector<GLuint>();
std::vector<GLuint> uvIndices = std::vector<GLuint>();
std::vector<Vertex> meshVertices = std::vector<Vertex>();
std::vector<Mesh> meshes = std::vector<Mesh>();
MaterialHandler::Material currentMaterial;
void PostProcessing();
void LoadMaterial(const std::string& fileName);
void LoadMaterialLibrary(const std::string& matPath) const;
};
|
Garciaj007/AEngine
|
AEngine/src/Graphics/MaterialLoader.h
|
#pragma once
class MaterialLoader
{
public:
static void LoadMaterial(const std::string& materialPath);
static GLuint LoadMaterialTexture(const std::string& textureFileName);
};
|
Garciaj007/AEngine
|
AEngine/src/Rendering/Frustum.h
|
<reponame>Garciaj007/AEngine
#pragma once
#include "Physics/BoundingBox.h"
struct Plane {
glm::vec4 plane;
glm::vec3 normal;
float distance;
Plane() = default;
explicit Plane(const glm::vec4 plane) : plane(plane), normal(glm::vec3(plane)), distance(plane.w) {}
};
class Frustum {
public:
enum Planes
{
BOTTOM_P, TOP_P, NEAR_P, FAR_P, LEFT_P, RIGHT_P
};
void CreateFrustum(glm::mat4);
bool Cull(BoundingBox*);
private:
Plane frustumPlanes[6];
glm::vec3 GetPositiveVertex(const glm::vec3, BoundingBox*);
glm::vec3 GetNegativeVertex(const glm::vec3, BoundingBox*);
};
|
Garciaj007/AEngine
|
AEngine/src/Physics/CollisionHandler.h
|
#pragma once
class GameObject;
class Camera;
class CollisionHandler
{
public:
CollisionHandler(const CollisionHandler&) = delete;
CollisionHandler(CollisionHandler&&) = delete;
CollisionHandler& operator=(const CollisionHandler&) = delete;
CollisionHandler& operator=(CollisionHandler&&) = delete;
static CollisionHandler* GetInstance();
void CreateHandler(Camera*);
void AddGameObject(GameObject*);
void Update(glm::vec2, int);
void Render();
void Destroy();
private:
CollisionHandler() = default;
~CollisionHandler() = default;
static std::vector<GameObject*> colliders;
static std::vector<GameObject*> previousCollisions;
static Camera* cameraPtr;
static class Ray ray;
static std::unique_ptr<CollisionHandler> instance;
friend std::default_delete<CollisionHandler>;
};
|
Garciaj007/AEngine
|
AEngine/src/Resources/ResourceManager.h
|
<filename>AEngine/src/Resources/ResourceManager.h
//#pragma once
//
//#include "Systems/EntityComponent.h"
//
////template <typename... Args>
////struct IAssetBuilder
////{
//// virtual ~IAssetBuilder() = default;
//// virtual bool CreateAsset() = 0;
////};
////
////template <typename... Args>
////class ModelBuilder final : IAssetBuilder<Args...>
////{
//// ModelBuilder() = default;
//// explicit ModelBuilder(Args... args);
//// ~ModelBuilder() override;
////
//// bool CreateAsset() override;
////};
////
////struct AssetBuilderInfo
////{
//// std::vector<AssetBuilderInfo*> entitiesAttached;
//// std::vector<Component*> componentsAttached;
////};
//
//class ResourceManager
//{
//public:
// ResourceManager(const ResourceManager&) = delete;
// ResourceManager(ResourceManager&&) = delete;
// ResourceManager& operator=(const ResourceManager&) = delete;
// ResourceManager& operator=(ResourceManager&&) = delete;
//
// static ResourceManager* GetInstance(EntityManager* manager);
//
// void CreateModel(std::string, std::string);
//private:
// explicit ResourceManager(EntityManager* manager) : manager(manager) { }
// ~ResourceManager();
//
// EntityManager* manager = nullptr;
// std::map<std::string, class Model*> models;
//
// static std::unique_ptr<ResourceManager> instance;
// friend std::default_delete<ResourceManager>;
//};
//
//
//
//
//
//
|
Garciaj007/AEngine
|
AEngine/src/Events/MouseEvent.h
|
<reponame>Garciaj007/AEngine
#pragma once
#include "IEvent.h"
class MouseEventListener : public EventListener<MouseEventListener>
{
public:
void OnMouseMovedEvent(double, double);
void OnMouseButtonEvent(int, int, int);
void OnMouseScrollEvent(double);
void OnMousePressedEvent(int button);
void OnMouseReleasedEvent(int button);
void OnMousePollEvent(float dt);
static glm::vec2 previousMousePosition;
static glm::vec2 currentMousePosition;
static glm::vec2 offsetMousePosition;
static glm::vec2 mousePosition;
static float scrollPosition;
static bool firstGather;
};
struct MouseEventDispatcher
{
MouseEventDispatcher() = default;
MouseEventDispatcher(const MouseEventDispatcher&) = delete;
MouseEventDispatcher(MouseEventDispatcher&&) = delete;
MouseEventDispatcher& operator=(const MouseEventDispatcher&) = delete;
MouseEventDispatcher& operator=(MouseEventDispatcher) = delete;
static MouseEventDispatcher* GetDispatcher();
void MousePollUpdate(float dt);
void RegisterCallbacks(GLFWwindow*);
Event<double, double> mouseMovedEvent;
Event<int, int, int> mouseButtonEvent;
Event<int> mouseButtonPressedEvent;
Event<int> mouseButtonReleasedEvent;
Event<double> mouseScrollEvent;
Event<float> mousePollUpdateEvent;
private:
static std::unique_ptr<MouseEventDispatcher> dispatcher;
MouseEventListener mouseEventListener;
void BindListeners();
void SetGlfwMouseCallbacks(GLFWwindow*);
};
|
Garciaj007/AEngine
|
AEngine/src/Graphics/Shader.h
|
<reponame>Garciaj007/AEngine
#pragma once
class ShaderHandler
{
public:
ShaderHandler(const ShaderHandler&) = delete;
ShaderHandler(ShaderHandler&&) = delete;
ShaderHandler& operator=(const ShaderHandler&) = delete;
ShaderHandler& operator=(ShaderHandler&&) = delete;
static ShaderHandler* GetInstance();
GLuint GetShaderProgram(const char*);
void CreateProgram(const char*, const char*, const char*);
private:
ShaderHandler() = default;
~ShaderHandler();
static std::unique_ptr<ShaderHandler> instance;
friend std::default_delete<ShaderHandler>;
static std::map<const char*, GLuint> programs;
static GLuint CreateShader(GLenum, std::string&, const char*);
};
|
Garciaj007/AEngine
|
AEngine/src/Physics/Ray.h
|
<reponame>Garciaj007/AEngine<filename>AEngine/src/Physics/Ray.h
#pragma once
#include <Core/AEpch.h>
#include "BoundingBox.h"
#include "CollisionDetection.h"
#include "Graphics/ShaderHandler.h"
struct Ray
{
Ray() = default;
Ray(const glm::vec3 origin, const glm::vec3 direction, const glm::vec2 dimensions) :
origin(origin), direction(direction), dimensions(dimensions) { }
Ray(const Ray& otherRay) { origin = otherRay.origin; direction = otherRay.direction; dimensions = otherRay.dimensions; }
Ray& operator=(const Ray& otherRay) { origin = otherRay.origin; direction = otherRay.direction; dimensions = otherRay.dimensions; return *this; }
bool IsColliding(BoundingBox* boundingBox)
{
intersection = -1.0f;
return CollisionDetection::RayCastHit(*this, boundingBox);
}
void Render(Camera* cameraPtr) const
{
glm::vec2 points[2];
points[0] = origin;
points[1] = origin + direction * dimensions.y;
const auto program = ShaderHandler::GetInstance()->GetShaderProgram("BasicShader");
glUseProgram(program);
glUniformMatrix4fv(glGetUniformLocation(program, "view"), 1, GL_FALSE, glm::value_ptr(cameraPtr->GetViewMatrix()));
glUniformMatrix4fv(glGetUniformLocation(program, "projection"), 1, GL_FALSE, glm::value_ptr(cameraPtr->GetPerspectiveMatrix()));
GLuint vao, vbo;
glGenVertexArrays(1, &vao);
glGenBuffers(1, &vbo);
glBindVertexArray(vao);
glBindBuffer(GL_ARRAY_BUFFER, vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(glm::vec3) * 2, &points[0], GL_STATIC_DRAW);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3, static_cast<GLvoid*>(nullptr));
glEnableVertexAttribArray(0);
glDrawArrays(GL_LINE, 0, static_cast<GLsizei>(2));
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
glUseProgram(0);
}
glm::vec3 origin = glm::vec3(0.0f);
glm::vec3 direction = glm::vec3(0.0f);
glm::vec2 dimensions = glm::vec3(0.0f);
float intersection = 0;
};
|
Garciaj007/AEngine
|
AEngine/src/Rendering/GameObject.h
|
#pragma once
#include "Core/Logger.h"
class CollisionHandler;
class Model;
class EntityManager;
struct BoundingBox;
class GameObject
{
public:
GameObject() = default;
GameObject(EntityManager*, Model*);
GameObject(EntityManager*, struct TransformData&, Model*);
~GameObject();
void Update(float) const;
void Render() const;
void SetName(const std::string& name) { this->name = name; }
[[nodiscard]] std::string GetName() const { return name; }
[[nodiscard]] BoundingBox* GetCollider() const { return boundingBoxPtr; }
[[nodiscard]] bool GetHit() const { return isHit; }
private:
std::string name = std::string();
std::unique_ptr<Model> modelPtr;
friend CollisionHandler;
void SetHit(const bool hit, const int mouseBtn)
{
isHit = hit;
LOG_INFO(GetName() + std::string("On Ray Collider Hit : Button Pressed ") + std::to_string(mouseBtn), "Gameobject.h", __LINE__);
}
bool isHit = false;
class Entity* entity = nullptr;
class Transform* transformPtr = nullptr;
BoundingBox* boundingBoxPtr = nullptr;
};
|
Garciaj007/AEngine
|
AEngine/src/Graphics/Mesh.h
|
<reponame>Garciaj007/AEngine<filename>AEngine/src/Graphics/Mesh.h
#pragma once
#include <Core/AEpch.h>
#include "MaterialHandler.h"
struct Vertex {
glm::vec3 position;
glm::vec3 normal;
glm::vec3 color;
glm::vec2 uvCoords;
};
struct Mesh
{
std::vector<Vertex> vertices = std::vector<Vertex>();
std::vector<GLuint> indices = std::vector<GLuint>();
MaterialHandler::Material material;
};
struct MeshRenderData
{
GLuint vao = 0;
GLuint vbo = 0;
};
|
Garciaj007/AEngine
|
AEngine/src/Graphics/Model.h
|
<gh_stars>0
#pragma once
#include "Mesh.h"
class Camera;
struct ModelData
{
class Entity* camera = nullptr;
GLuint shaderProgram = 0;
std::string objPath = std::string();
std::string materialPath = std::string();
};
class Model
{
public:
explicit Model(const ModelData&);
explicit Model(ModelData&&);
~Model();
void Render();
void Render(size_t index);
[[nodiscard]] std::vector<Mesh> GetMeshes() const { return meshes; }
[[nodiscard]] GLuint GetShaderProgram() const { return modelData.shaderProgram; }
void SetModelMatrix(const glm::mat4 modelMatrix){ this->modelMatrix = modelMatrix; }
private:
ModelData modelData;
std::vector<MeshRenderData> renderMeshData;
std::vector<Mesh> meshes;
void GenBuffers();
void BindVertexBuffers();
void SetUniformData(size_t index);
class ObjLoader* objLoader = nullptr;
glm::mat4 modelMatrix;
};
|
Garciaj007/AEngine
|
AEngine/src/Window/Window.h
|
<reponame>Garciaj007/AEngine
#pragma once
class Window
{
public:
Window();
~Window();
Window(const Window&) = delete;
Window(Window&&) = delete;
Window& operator=(const Window&) = delete;
Window& operator=(Window&&) = delete;
// ====================================================
bool Create(std::string, std::pair<GLuint, GLuint>);
// ====================================================
[[nodiscard]] inline GLFWwindow* GetWindow() const { return window; }
[[nodiscard]] inline GLuint GetWidth() const { return width; }
[[nodiscard]] inline GLuint GetHeight() const { return height; }
[[nodiscard]] inline void SetDimensions(std::pair<GLuint, GLuint> dimensions)
{
width = dimensions.first; height = dimensions.second;
}
inline void SetVSync(bool vsyncEnabled) const
{
if (vsyncEnabled) glfwSwapInterval(1); else glfwSwapInterval(0);
}
private:
GLuint width, height;
GLFWwindow* window;
std::string name;
};
|
Garciaj007/AEngine
|
AEngine/src/Core/AEApplication.h
|
<filename>AEngine/src/Core/AEApplication.h
#pragma once
class AEApplication
{
public:
AEApplication(const AEApplication&) = delete;
AEApplication(AEApplication&&) = delete;
AEApplication& operator=(const AEApplication&) = delete;
AEApplication& operator=(AEApplication&&) = delete;
bool Initialize();
void Run() const;
void ResizeUpdate() const;
void Destroy() const;
static AEApplication* GetInstance();
[[nodiscard]] glm::vec2 GetWindowSize() const;
private:
AEApplication() = default;
~AEApplication();
void BuildScene(class IScene*);
void Update() const;
void Render() const;
bool sceneActive = false;
std::unique_ptr<class IScene> scenePtr;
std::unique_ptr<class Window> windowPtr;
std::unique_ptr<class Timer> graphicsTimerPtr;
static std::unique_ptr<AEApplication> instance;
friend std::default_delete<AEApplication>;
};
|
Garciaj007/AEngine
|
AEngine/src/Core/AEpch.h
|
<filename>AEngine/src/Core/AEpch.h<gh_stars>0
#pragma once
#include <Windows.h>
#include <iostream>
#include <fstream>
#include <sstream>
#include <memory>
#include <algorithm>
#include <utility>
#include <functional>
#include <bitset>
#include <array>
#include <ctime>
#include <ratio>
#include <chrono>
#include <string>
#include <vector>
#include <map>
#include <unordered_map>
#include <unordered_set>
#include <glm.hpp>
#include <gtc/quaternion.hpp>
#include <gtc/type_ptr.hpp>
#include <gtx/string_cast.hpp>
#include <gtx/matrix_decompose.hpp>
#include <gtc/matrix_transform.hpp>
#include <gtc/quaternion.hpp>
#include <glad/glad.h>
#include <GLFW/glfw3.h>
#define RESOURCES(path) { return "src/Resources" + path; }
constexpr float Magnitude(const glm::vec3 v){ return (v.x * v.x) + (v.y * v.y) + (v.z * v.z);}
constexpr void Maximum(const glm::vec3& v, glm::vec3& max)
{
max.x = v.x > max.x ? v.x : max.x;
max.y = v.y > max.y ? v.y : max.y;
max.z = v.z > max.z ? v.z : max.z;
}
constexpr void Minimum(const glm::vec3& v, glm::vec3& min)
{
min.x = v.x < min.x ? v.x : min.x;
min.y = v.y < min.y ? v.y : min.y;
min.z = v.z < min.z ? v.z : min.z;
}
//#define XR_USE_PLATFORM_WIN32
//#define XR_USE_GRAPHICS_API_OPENGL
//#include <openxr/openxr.h>
//#include <openxr/openxr_platform.h>
|
Garciaj007/AEngine
|
AEngine/src/Scene/CubeScene.h
|
<reponame>Garciaj007/AEngine
#pragma once
#include "Scene/IScene.h"
class CubeScene final : public IScene
{
public:
virtual bool Initialize() override;
virtual void Update(const float dt) override;
virtual void Render() const override;
virtual void ResizeUpdate() const override;
private:
Entity* cubeEntityPtr = nullptr;
Entity* cameraEntityPtr = nullptr;
};
|
Garciaj007/AEngine
|
AEngine/src/Physics/BoundingBox.h
|
<reponame>Garciaj007/AEngine
#pragma once
#include <Systems/EntityComponent.h>
#include "Graphics/Mesh.h"
#include "Graphics/Model.h"
#include "Components/Transform.h"
#include "Rendering/GameObject.h"
constexpr void LimitScale(glm::vec3& v)
{
v.x = v.x < 1.0f ? v.x / 2.0f : v.x;
v.y = v.y < 1.0f ? v.y / 2.0f : v.y;
v.z = v.z < 1.0f ? v.z / 2.0f : v.z;
}
struct BoundingBox final : Component
{
explicit BoundingBox(const std::vector<Mesh>& meshes) : meshes(meshes){}
void Start() override
{
transformPtr = boundEntity->GetComponent<Transform>();
for(const auto& mesh : meshes)
{
for(auto vertex : mesh.vertices)
{
Minimum(vertex.position, minimum);
Maximum(vertex.position, maximum);
}
}
transformedMinimum = minimum;
transformedMaximum = maximum;
}
void Update(const float dt) override
{
auto scaleFactor = transformPtr->scale;
LimitScale(scaleFactor);
transformedMaximum = maximum * scaleFactor;
transformedMinimum = minimum * scaleFactor;
//std::cout << "Model Scale: "<< glm::to_string(scaleFactor) << std::endl;
}
void Render() override
{
}
void Print() const
{
std::cout << "Bounding Box Min: " << glm::to_string(minimum) << std::endl
<< "Bounding Box Max: " << glm::to_string(maximum) << std::endl;
}
void PrintT() const
{
std::cout << "Bounding Box Min: " << glm::to_string(transformedMinimum) << std::endl
<< "Bounding Box Max: " << glm::to_string(transformedMaximum) << std::endl;
}
glm::vec3 maximum = glm::vec3(0.0f);
glm::vec3 minimum = glm::vec3(1.0f);
glm::vec3 transformedMaximum = glm::vec3(0.0f);
glm::vec3 transformedMinimum = glm::vec3(1.0f);
std::vector<Mesh> meshes;
Transform* transformPtr = nullptr;
};
|
Garciaj007/AEngine
|
AEngine/src/Scene/ModelScene.h
|
#pragma once
#include "Scene/IScene.h"
#include "Rendering/GameObject.h"
class SceneGraph;
class ModelScene final : public IScene
{
public:
virtual bool Initialize() override;
virtual void Update(const float dt) override;
virtual void Render() const override;
virtual void ResizeUpdate() const override;
virtual void Destroy() const override;
void HandleMouseReleasedEvent(int);
private:
Entity* cameraEntityPtr = nullptr;
Entity* lightEntityPtr = nullptr;
};
|
Garciaj007/AEngine
|
AEngine/src/Components/Transform.h
|
<reponame>Garciaj007/AEngine
#pragma once
#include <Core/AEpch.h>
#include "Systems/EntityComponent.h"
struct TransformData
{
glm::vec3 position = glm::vec3(0.0f);
glm::vec3 scale = glm::vec3(1.0f);
glm::quat rotation = glm::quat(glm::vec4(0.0f));
};
class Transform final : public Component
{
public:
Transform() : position(glm::vec3(0)),
angleAxis(glm::vec3(0.0f, 1.0f, 0.0f)),
eulerAngles(glm::vec3(0)), scale(glm::vec3(1.0f)) {}
explicit Transform(glm::vec3 position,
glm::vec3 scale = glm::vec3(1.0f),
glm::quat rotation = glm::quat(glm::vec4(0.0f))) :
rotation(rotation), position(position), angleAxis(glm::vec3(0.0f, 1.0f, 0.0f)),
eulerAngles(glm::vec3(0)), scale(scale) {}
explicit Transform(const TransformData& data) : rotation(data.rotation), position(data.position),
angleAxis(glm::vec3(0.0f, 1.0f, 0.0f)), eulerAngles(glm::vec3(0.0f)),
scale(data.scale) {}
explicit Transform(TransformData&& data) : rotation(data.rotation), position(data.position),
angleAxis(glm::vec3(0.0f, 1.0f, 0.0f)), eulerAngles(glm::vec3(0.0f)),
scale(data.scale) {}
[[nodiscard]] glm::vec3 GetEuler() const { return eulerAngles; }
[[nodiscard]] glm::mat4 GetTransformMatrix() const
{
auto transformMatrix = glm::mat4(1.0f);
transformMatrix = GetTranslationMatrix(transformMatrix);
transformMatrix = GetRotationMatrix(transformMatrix);
transformMatrix = GetScalingMatrix(transformMatrix);
return transformMatrix;
}
[[nodiscard]] glm::mat4 GetOrientationMatrix() const
{
auto matrix = glm::mat4(1.0f);
matrix = GetRotationMatrix(matrix);
matrix = GetTranslationMatrix(matrix);
return matrix;
}
void Start() override { ConvertRotation(); }
void Update(const float dt) override { ConvertRotation(); }
float angle = 0;
glm::quat rotation = glm::quat(glm::vec4(0.0f));
glm::vec3 position;
glm::vec3 angleAxis;
glm::vec3 eulerAngles;
glm::vec3 scale;
private:
[[nodiscard]] glm::mat4 GetTranslationMatrix(const glm::mat4 mat) const
{
return glm::translate(mat, position);
}
[[nodiscard]] glm::mat4 GetRotationMatrix(const glm::mat4 mat) const
{
return mat * glm::mat4_cast(rotation);
}
[[nodiscard]] glm::mat4 GetScalingMatrix(const glm::mat4 mat) const
{
return glm::scale(mat, scale);
}
void ConvertRotation() { eulerAngles = glm::eulerAngles(rotation); }
};
|
Garciaj007/AEngine
|
AEngine/src/Core/Timer.h
|
<reponame>Garciaj007/AEngine
#pragma once
#include <Core/AEpch.h>
#include "AEApplication.h"
#include "Logger.h"
class Timer
{
public:
typedef void(AEApplication::*TimerAction)()const;
Timer(const double rate) : sleepTime(GetSleepTime(rate)), previousTime(glfwGetTime()),
tickTime(previousTime), currentTime(0),
actionToPerform(nullptr), instance(nullptr),
deltaTime(0), frames(0)
{ }
~Timer() {}
Timer(Timer&) = delete;
void operator=(Timer const&) = delete;
void Update()
{
currentTime = glfwGetTime();
if (currentTime - previousTime >= sleepTime)
{
frames++;
deltaTime = currentTime - previousTime;
previousTime = glfwGetTime();
if (actionToPerform) (instance->*actionToPerform)();
}
if (currentTime - tickTime >= 1.0)
{
LOG_TRACE(std::to_string(frames) + "fps | " + std::to_string(deltaTime * 1000) + "ms", __FILE__, __LINE__);
tickTime += 1.0;
frames = 0;
}
}
[[nodiscard]] inline double GetDeltaTime() const { return deltaTime; }
[[nodiscard]] inline double GetCurrentTime() const { return currentTime; }
inline void SetTimerAction(TimerAction action, AEApplication* instance)
{
actionToPerform = action; this->instance = instance;
}
protected:
static inline double GetSleepTime(const double fps) { return 1.0 / fps; }
protected:
double currentTime;
double previousTime;
double deltaTime;
double sleepTime;
double tickTime;
unsigned int frames;
TimerAction actionToPerform;
AEApplication* instance;
};
|
Garciaj007/AEngine
|
AEngine/src/Systems/EntityComponent.h
|
<gh_stars>0
#pragma once
#include <Core/AEpch.h>
class Component;
class Entity;
class EntityManager;
using ComponentTypeID = std::size_t;
using EntityGroup = std::size_t;
inline ComponentTypeID getNewComponentTypeID()
{
static ComponentTypeID id = 0u;
return id++;
}
template <typename T> inline ComponentTypeID getComponentTypeID() noexcept
{
static ComponentTypeID typeID = getNewComponentTypeID();
return typeID;
}
constexpr std::size_t maxComponents = 64;
constexpr std::size_t maxGroups = 32;
using ComponentBitset = std::bitset<maxComponents>;
using GroupBitset = std::bitset<maxGroups>;
using ComponentArray = std::array<Component*, maxComponents>;
class Component
{
public:
Component() : boundEntity(nullptr) { }
virtual ~Component() = default;
virtual void Start() {}
virtual void Update(const float dt) {}
virtual void Render() {}
virtual void ResizeUpdate() {}
Entity* boundEntity;
};
class Entity
{
public:
Entity() = delete;
explicit Entity(EntityManager& manager) : manager(manager) { }
void Update(const float dt)
{
for (auto& c: components) c->Update(dt);
}
void Render()
{
for (auto& c : components) c->Render();
}
void ResizeUpdate()
{
for (auto& c : components) c->ResizeUpdate();
}
void Destroy() { active = false; }
[[nodiscard]] bool isActive() const { return active; }
bool hasGroup(EntityGroup group)
{
return groupBitset[group];
}
void addGroup(EntityGroup group);
void removeGroup(EntityGroup group)
{
groupBitset[group] = false;
}
template <typename T>
[[nodiscard]] bool hasComponent() const
{
return componentBitset[getComponentTypeID<T>];
}
template <typename T, typename ...TArgs>
T* AddComponent(TArgs&& ... componentArgs)
{
std::unique_ptr<T> newComponentPtr = std::make_unique<T>(std::forward<TArgs>(componentArgs)...);
newComponentPtr->boundEntity = this;
components.emplace_back(std::move(newComponentPtr));
auto c = components.at(components.size() - 1).get();
componentArray[getComponentTypeID<T>()] = c;
componentBitset[getComponentTypeID<T>()] = true;
c->Start();
return static_cast<T*>(c);
}
template<typename T> T* GetComponent() const
{
auto componentPtr(componentArray[getComponentTypeID<T>()]);
return static_cast<T*>(componentPtr);
}
private:
std::vector<std::unique_ptr<Component>> components;
EntityManager& manager;
GroupBitset groupBitset;
ComponentArray componentArray = ComponentArray();
ComponentBitset componentBitset;
bool active = true;
};
class EntityManager
{
public:
EntityManager() = default;
~EntityManager()
{
for (auto& entity : entities) entity->Destroy();
SeekAndDestroy();
}
void Update(const float dt)
{
for (auto& entity : entities) entity->Update(dt);
}
void Render()
{
for (auto& entity : entities) entity->Render();
}
void ResizeUpdate()
{
for (auto& entity : entities) entity->ResizeUpdate();
}
void AddToGroup(Entity* entity, EntityGroup group)
{
groupedEntities[group].emplace_back(entity);
}
std::vector<Entity*> & getGroup(EntityGroup group)
{
return groupedEntities[group];
}
void SeekAndDestroy()
{
for (auto i(0u); i < maxGroups; i++)
{
auto& v(groupedEntities[i]);
v.erase(
std::remove_if(std::begin(v), std::end(v), [i](Entity* entity)
{
return !entity->isActive() || entity->hasGroup(i);
}), std::end(v));
}
entities.erase(std::remove_if(std::begin(entities), std::end(entities),
[](const std::unique_ptr<Entity>& entity)
{
return !entity->isActive();
}
), std::end(entities));
}
Entity* CreateAndAddEntity()
{
std::unique_ptr<Entity> entityPtr = std::make_unique<Entity>(*this);
entities.emplace_back(std::move(entityPtr));
return entities.at(entities.size() - 1).get();
}
template <typename ...T, typename ...TArgs>
Entity* CreateAndAddEntity(TArgs&& ...componentArgs)
{
std::unique_ptr<Entity> entityPtr = std::make_unique<Entity>(*this);
entityPtr->AddComponent<T>(componentArgs);
entities.emplace_back(std::move(entityPtr));
return entities.at(entities.size() - 1).get();
}
private:
std::vector<std::unique_ptr<Entity>> entities;
std::array<std::vector<Entity*>, maxGroups> groupedEntities;
};
|
abhinav-upadhyay/spell
|
dictionary.c
|
#define _GNU_SOURCE
#include <ctype.h>
#include <err.h>
#include <errno.h>
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "spellutil.h"
typedef struct word_count {
int value;
} count;
static void
usage(void)
{
fprintf(stderr, "Usage: dictionary -i InputFile -o outputFile\n");
exit(1);
}
static char *
print_count(void *data)
{
count *wc = (count *) data;
char *s;
asprintf(&s, "%d", wc->value);
return s;
}
static void
free_count(void *data)
{
free(data);
}
static void
to_lower(char *s)
{
char c;
char *t = s;
if (s == NULL) {
return;
}
for (int i = 0; i < strlen(s); i++) {
c = s[i];
s[i] = tolower(c);
}
}
static int
is_upper(char *s)
{
while (*s) {
if (isupper(*s++)) {
continue;
}
/* not uppercase string */
return 0;
}
/* uppercase string */
return 1;
}
static char *
sanitize_string(char *s)
{
size_t len = strlen(s);
int i = 0;
if (s[0] == '(' && s[len - 1] == ')') {
s[len - 1] = 0;
s++;
}
if (is_upper(s)) {
return NULL;
}
char *ret = malloc(len + 1);
memset(ret, 0, len + 1);
while(*s) {
/*
* Detect apostrophe and stop copying characters immediately
*/
if ((*s == '\'') && (
!strncmp(s + 1, "s", 1) ||
!strncmp(s + 1, "es", 2) ||
!strncmp(s + 1, "m", 1) ||
!strncmp(s + 1, "d", 1) ||
!strncmp(s + 1, "ll", 2))) {
break;
}
/*
* If the word contains a dot in between that suggests it is either
* an abbreviation or somekind of a URL. Do not bother with such words.
*/
if (*s == '.') {
free(ret);
return NULL;
}
// Why bother with words which contain other characters or numerics?
if (!isalpha(*s)) {
free(ret);
return NULL;
}
ret[i++] = *s++;
}
ret[i] = 0;
return ret;
}
static int
is_valid(char *word)
{
if (!strcmp(word, " ") ||
!strcmp(word, "\n") ||
!strcmp(word, "\t")) {
return 1;
}
return 0;
}
int
parse_file(const char *filename, spell_hashtable *table)
{
int _errno;
size_t len = 0;
size_t wordlen;
ssize_t read;
char *word = NULL;
char *line = NULL;
char *templine;
count *c;
count *default_count;
FILE *file = fopen(filename, "r");
if (file == NULL) {
_errno = errno;
fprintf(stderr, "fopen failed for file %s", filename);
return errno;
}
while ((read = getline(&line, &len, file)) != -1) {
// TODO Use a more sophisitcated tokenization,
// perhaps preprocess with a stemmer algorithm first
line[read - 1] = 0;
templine = line;
while (*templine) {
wordlen = strcspn(templine, " \"\',;-:.\u2014");
templine[wordlen] = 0;
word = templine;
templine += wordlen + 1;
char *sanitized_word = sanitize_string(word);
if (sanitized_word == NULL) {
continue;
}
if (strlen(sanitized_word) == 0) {
free(sanitized_word);
continue;
}
to_lower(sanitized_word);
// See if this word is already in the table,
// if yes, then increment the count,
// otherwise add the word to the table.
c = (count *) spell_hashtable_get(table, sanitized_word);
if (c == NULL) {
default_count = malloc(sizeof(count));
default_count->value = 1;
spell_hashtable_add(table, sanitized_word, default_count);
} else {
c->value++;
}
free(sanitized_word);
}
}
free(line);
fclose(file);
return 0;
}
int
main(int argc, char **argv)
{
char ch;
char *input_file = NULL;
char *output_file = NULL;
while ((ch = getopt(argc, argv, "i:o:")) != -1) {
switch (ch) {
case 'i':
input_file = optarg;
break;
case 'o':
output_file = optarg;
break;
case '?':
default:
usage();
}
}
if (!input_file || !output_file) {
usage();
}
spell_hashtable *table = spell_hashtable_init(1024);
if (table == NULL) {
errx(EXIT_FAILURE, "Failed to initialize the hash table");
}
parse_file(input_file, table);
spell_hashtable_dump(table, output_file, print_count);
spell_hashtable_free(table, free_count);
}
|
abhinav-upadhyay/spell
|
spell_hash_test.c
|
#define _GNU_SOURCE
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "spellutil.h"
typedef struct int_struct {
int i;
} int_struct;
static void
test_spell_hash_init()
{
spell_hashtable *table = spell_hashtable_init(63);
assert(table != NULL);
assert(table->size == 64);
assert(table->nfree == 64);
printf("[PASSED] test_spell_hash\n");
spell_hashtable_free(table, NULL);
}
static void
test_spell_hash_add_one()
{
char *key1 = "hello world";
char *val1 = "foo bar";
spell_hashtable *table = spell_hashtable_init(1);
spell_hashtable_add(table, key1, val1);
char *val2 = spell_hashtable_get(table, key1);
assert(strcmp(val1, val2) == 0);
spell_hashtable_free(table, NULL);
printf("[PASSED] test_spell_hash_add_one\n");
}
static void
test_spell_hash_add_multi()
{
char *key1 = "hello world";
char *val1 = "foo bar";
char *key2 = "a";
char *val2 = "b";
char *key3 = "b ";
char *val3 = "d";
spell_hashtable *table = spell_hashtable_init(1);
spell_hashtable_add(table, key1, val1);
spell_hashtable_add(table, key2, val2);
spell_hashtable_add(table, key3, val3);
assert(strcmp(val1, spell_hashtable_get(table, key1)) == 0);
assert(strcmp(val2, spell_hashtable_get(table, key2)) == 0);
assert(strcmp(val3, spell_hashtable_get(table, key3)) == 0);
spell_hashtable_free(table, NULL);
printf("[PASSED] test_spell_hash_add_multi\n");
}
static void
test_spell_hash_get()
{
char *key1 = "hello world";
char *val1 = "foo bar";
char *key2 = "a";
char *val2 = "b";
char *key3 = "c";
char *val3 = "d";
spell_hashtable *table = spell_hashtable_init(1);
spell_hashtable_add(table, key1, val1);
spell_hashtable_add(table, key2, val2);
spell_hashtable_add(table, key3, val3);
char *getval1 = spell_hashtable_get(table, key1);
char *getval2 = spell_hashtable_get(table, key2);
char *getval3 = spell_hashtable_get(table, key3);
assert(strcmp(getval1, val1) == 0);
assert(strcmp(getval2, val2) == 0);
assert(strcmp(getval3, val3) == 0);
spell_hashtable_free(table, NULL);
printf("[PASSED] test_spell_hash_get\n");
}
static void
test_spell_hash_update()
{
char *key1 = "hello world";
int val1 = 1;
int val2 = 2;
spell_hashtable *table = spell_hashtable_init(32);
spell_hashtable_add(table, key1, &val1);
assert(*(int *) spell_hashtable_get(table, key1) == val1);
spell_hashtable_add(table, key1, &val2);
assert(*(int *) spell_hashtable_get(table, key1) == val2);
spell_hashtable_free(table, NULL);
printf("[PASSED] test_spell_hash_update\n");
}
static int
count_digits(int x, int ndigits)
{
int i;
if (x < 10) {
return ndigits + 1;
}
return count_digits(x / 10, ndigits + 1);
}
static char *
itos(int x)
{
int ndigits = count_digits(x, 0);
char *s = malloc(ndigits + 1);
int i;
int n = x;
s[ndigits] = 0;
for (i = ndigits - 1; i >= 0; i--) {
s[i] = n % 10 + 48;
n /= 10;
}
return s;
}
static void
test_spell_hash_resize()
{
int i;
spell_hashtable *table = spell_hashtable_init(1);
for (i = 0; i < table->size; i++) {
char *k = itos(i);
spell_hashtable_add(table, k, &i);
free(k);
}
assert(table->size == SPELL_HASHTABLE_INIT_SIZE);
assert(table->nfree == 0);
spell_hashtable_add(table, "33", "33");
assert(table->size == 2 * SPELL_HASHTABLE_INIT_SIZE);
spell_hashtable_free(table, NULL);
printf("[PASSED] test_spell_hash_resize\n");
}
static spell_hashtable *
generate_hashtable(int limit)
{
int i;
int_struct *s;
spell_hashtable *table = spell_hashtable_init(limit);
for (i = 0; i < limit; i++) {
char *k = itos(i);
s = malloc(sizeof(int_struct));
s->i = i;
spell_hashtable_add(table, k, (void *)s);
free(k);
}
return table;
}
static char *
print_struct_int(void *data)
{
char *s;
int_struct *d = (int_struct *) data;
asprintf(&s, "%d", d->i);
return s;
}
static void
test_spell_hash_dump()
{
const int SIZE = 65;
spell_hashtable *table = generate_hashtable(SIZE);
spell_hashtable_dump(table, "table.dump", print_struct_int);
spell_hashtable_free(table, free);
}
static void
test_spell_hash_remove()
{
spell_hashtable *table = generate_hashtable(1);
srand(time(NULL));
int r;
char *k;
// r = (rand() % 25) + 1;
// k = itos(r);
//assert(k != NULL);
//assert(table != NULL);
spell_hashtable_remove(table, "0", free);
assert(spell_hashtable_get(table, "0") == NULL);
//free(k);
spell_hashtable_free(table, free);
printf("[PASSED] test_spell_hash_remove\n");
}
int
main(int argc, char **argv)
{
test_spell_hash_init();
test_spell_hash_add_one();
test_spell_hash_add_multi();
test_spell_hash_get();
test_spell_hash_resize();
test_spell_hash_update();
test_spell_hash_dump();
test_spell_hash_remove();
}
|
abhinav-upadhyay/spell
|
spellutil.c
|
<filename>spellutil.c
#include <assert.h>
#include <err.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <string.h>
#include "spellutil.h"
spell_list_node *
spell_list_init(void *data)
{
spell_list_node *head = malloc(sizeof(spell_list_node));
if (head == NULL) {
return NULL;
}
head->next = NULL;
head->data = data;
return head;
}
int
spell_list_add_head(spell_list_node **phead, void *data)
{
spell_list_node *tail;
spell_list_node *head;
spell_list_node *new_node;
head = *phead;
new_node = malloc(sizeof(spell_list_node));
if (new_node == NULL) {
return -1;
}
new_node->next = head;
new_node->data = data;
*phead = new_node;
return 0;
}
void
spell_list_free(spell_list_node **phead, void (*free_data) (void *))
{
spell_list_node *n;
spell_list_node *head;
spell_list_node *next;
if (!phead || !*phead) {
return;
}
head = *phead;
n = head;
while (n) {
next = n->next;
if (free_data) {
free_data(n->data);
}
free(n);
n = next;
}
*phead = NULL;
}
void
spell_list_remove(spell_list_node **phead, spell_list_node *node, void (*pfree) (void *))
{
if (!phead || !node) {
return;
}
spell_list_node *head = *phead;
spell_list_node *iter = head;
spell_list_node *temp_node;
/*
* if the node to be deleted is the head of the linked list
*/
if (node == head) {
*phead = head->next;
if (pfree) {
if (head->data) {
pfree(head->data);
}
}
free(head);
return;
}
while (iter) {
if (iter->next == node) {
iter->next = iter->next->next;
if (pfree) {
if (node->data) {
pfree(node->data);
}
}
free(node);
return;
}
iter = iter->next;
}
}
spell_list_node *
spell_list_get(spell_list_node *head, void *data, int (*compare) (const void*, const void*))
{
spell_list_node *iter = head;
while (iter) {
if (compare(iter->data, data) == 0) {
return iter;
}
iter = iter->next;
}
return NULL;
}
spell_list_node *
spell_list_get_tail(spell_list_node *head)
{
spell_list_node *i = head;
if (i == NULL) {
return NULL;
}
while (i->next) {
i = i->next;
}
return i;
}
unsigned long
compute_hash(unsigned char *str, size_t bound)
{
unsigned long hash = 5381;
int c;
while ((c = *str++)) {
hash = ((hash << 5) + hash) + c; // hash*33 + c
}
return hash % bound;
}
spell_hashtable *
spell_hashtable_init(size_t n)
{
if (n <= 0) {
return NULL;
}
size_t init_size = n > SPELL_HASHTABLE_INIT_SIZE? n + (n % 2): SPELL_HASHTABLE_INIT_SIZE;
spell_hashtable *hashtable = malloc(sizeof(spell_hashtable));
if (hashtable == NULL) {
return NULL;
}
hashtable->array = malloc(init_size * sizeof(spell_list_node *));
if (hashtable->array == NULL) {
free(hashtable);
return NULL;
}
memset(hashtable->array, 0, init_size * sizeof(spell_list_node *));
hashtable->size = init_size;
hashtable->nfree = init_size;
return hashtable;
}
static keyval*
generate_new_keyval(char *key, void *val)
{
keyval *kv = malloc(sizeof(keyval));
if (kv == NULL) {
return NULL;
}
kv->key = strdup(key);
kv->val = val;
return kv;
}
static void
free_entry_list(spell_list_node *head, void(*valfree) (void *))
{
spell_list_node *n;
spell_list_node *next;
n = head;
while (n) {
next = n->next;
keyval *kv = (keyval *) n->data;
free(kv->key);
if (valfree) {
valfree(kv->val);
}
free(kv);
free(n);
n = next;
}
}
static void
free_table_array(spell_list_node **array, size_t size, void (*pfree) (void *))
{
for (int i = 0; i < size ; i++) {
spell_list_node *entry = array[i];
if (entry == NULL) {
continue;
}
free_entry_list(entry, pfree);
}
free(array);
}
static void
resize_table(spell_hashtable *table)
{
int i;
size_t newsize = 2 * table->size;
size_t oldsize = table->size;
spell_list_node **ptr = malloc(newsize * sizeof(spell_list_node *));
if (ptr == NULL) {
return;
}
spell_list_node **old_array = table->array;
table->array = ptr;
table->size = newsize;
table->nfree = newsize;
for (i = 0; i < newsize; i++) {
table->array[i] = NULL;
}
for (i = 0; i < oldsize; i++) {
spell_list_node *n = old_array[i];
while(n) {
keyval *kv = (keyval *) n->data;
spell_hashtable_add(table, kv->key, kv->val);
n = n->next;
}
}
free_table_array(old_array, oldsize, NULL);
}
static int
hash_compare_data(const void *d1, const void *d2)
{
const keyval *kv1 = (const keyval *)d1;
const keyval *kv2 = (const keyval *)d2;
return strcmp(kv1->key, kv2->key);
}
void
spell_hashtable_add(spell_hashtable *table, char *key, void *val)
{
if (key == NULL || table == NULL) {
return;
}
if (table->nfree == 0) {
resize_table(table);
}
unsigned long index = compute_hash((unsigned char *) key, table->size);
spell_list_node *entry_list = table->array[index];
if (entry_list == NULL) {
keyval *kv = generate_new_keyval(key, val);
if (kv == NULL) {
warnx("Failed to generate a new key value pair for key: %s", key);
return;
}
table->array[index] = spell_list_init(kv);
table->nfree--;
return;
}
spell_list_node *node = entry_list;
keyval *dummy_kv = generate_new_keyval(key, NULL);
spell_list_node *existing_key = spell_list_get(entry_list, dummy_kv, hash_compare_data);
free(dummy_kv->key);
free(dummy_kv);
if (existing_key != NULL) {
keyval *data = (keyval *) node->data;
data->val = val;
return;
}
keyval *kv = generate_new_keyval(key, val);
if (kv == NULL) {
warnx("Failed to generate a new key value pair for key: %s", key);
return;
}
spell_list_add_head(&table->array[index], kv);
table->nfree--;
}
void *
spell_hashtable_get(spell_hashtable *table, char *key)
{
spell_list_node *n;
keyval *dummy_kv;
keyval *kv;
if (!key) {
warnx("Trying to get value for NULL key from the table");
return NULL;
}
unsigned long index = compute_hash((unsigned char *)key, table->size);
spell_list_node *entry = table->array[index];
if (entry == NULL) {
return NULL;
}
dummy_kv = malloc(sizeof(keyval));
if (dummy_kv == NULL) {
return NULL;
}
dummy_kv->key = key;
n = spell_list_get(entry, dummy_kv, hash_compare_data);
free(dummy_kv);
if (n == NULL) {
return NULL;
}
kv = (keyval *) n->data;
if (kv != NULL) {
assert(kv->key != NULL);
assert(strcmp(kv->key, key) == 0);
return kv->val;
}
return NULL;
}
static void
hash_free(void *keyval_pair)
{
keyval *kv = (keyval *) keyval_pair;
if (!kv) {
warnx("Trying to free a NULL key value pair");
return;
}
assert(kv->key != NULL);
free(kv->key);
}
void
spell_hashtable_remove(spell_hashtable *table, char *key, void (*pfree) (void *))
{
spell_list_node *n;
keyval *dummy_kv;
keyval *val;
unsigned long index = compute_hash((unsigned char *)key, table->size);
if (table->array[index] == NULL) {
return;
}
spell_list_node *entry = table->array[index];
dummy_kv = malloc(sizeof(keyval));
if (dummy_kv == NULL) {
return;
}
dummy_kv->key = key;
n = spell_list_get(entry, dummy_kv, hash_compare_data);
if (n == NULL) {
free(dummy_kv);
return;
}
val = n->data;
spell_list_remove(&entry, n, hash_free);
pfree(val->val);
free(val);
if (entry == NULL) {
table->array[index] = NULL;
}
free(dummy_kv);
}
static void
free_keyval(void *d)
{
keyval *kv = (keyval *) d;
free(kv->key);
}
void
spell_hashtable_free(spell_hashtable *table, void (*pfree) (void *))
{
if (table == NULL) {
return;
}
free_table_array(table->array, table->size, pfree);
free(table);
}
/*
* Returns a list of all the keys stored in the table.
* The caller needs to make sure not to free the table till
* the table is being accessed as all the pointers in the key are
* same as the ones stored in the table and will be invalidated
* as soon as the table is freed. When freeing the list pass NULL
* as the 2nd parameter to the spell_list_free function.
*/
static spell_list_node *
spell_hashtable_get_keys(spell_hashtable *table)
{
if (table == NULL) {
return NULL;
}
int i;
spell_list_node *keylist_head = NULL;
for (i = 0; i < table->size ; i++) {
spell_list_node *entry = table->array[i];
if (entry == NULL) {
continue;
}
while (entry) {
assert(entry->data);
keyval *kv = (keyval *) entry->data;
char *key = kv->key;
assert(key);
/* Caller has to make sure not to free the hashtable till
* this list is being accessed as the pointers in the keylist
* are pointing to the same objects which are in the table.
*/
spell_list_add_head(&keylist_head, key);
assert(keylist_head->data);
entry = entry->next;
}
}
return keylist_head;
}
/*
* Returns a list of all the values stored in the table.
* The caller needs to make sure not to free the table till
* the table is being accessed as all the pointers in the list are
* same as the ones stored in the table and will be invalidated
* as soon as the table is freed. When freeing the list pass NULL
* as the 2nd parameter to the spell_list_free function.
*/
static spell_list_node *
spell_hashtable_get_values(spell_hashtable *table)
{
if (table == NULL) {
return NULL;
}
int i;
spell_list_node *valuelist_head = NULL;
for (i = 0; i < table->size ; i++) {
spell_list_node *entry = table->array[i];
if (entry == NULL) {
continue;
}
while (entry) {
if (!entry->data) {
entry = entry->next;
continue;
}
keyval *kv = (keyval *) entry->data;
void *data = kv->val;
spell_list_add_head(&valuelist_head, data);
entry = entry->next;
}
}
return valuelist_head;
}
/*
* Returns a list of all the key value pairs stored in the table.
* The data field of the list entries is a keyval struct, where
* the key field contains the key and the val key contains the value
* object.
* The caller needs to make sure not to free the table till
* the table is being accessed as all the pointers in the list are
* same as the ones stored in the table and will be invalidated
* as soon as the table is freed. When freeing the list pass NULL
* as the 2nd parameter to the spell_list_free function.
*/
spell_list_node *
spell_hashtable_get_key_values(spell_hashtable *table)
{
if (table == NULL) {
return NULL;
}
int i;
spell_list_node *keyvaluelist_head = NULL;
for (i = 0; i < table->size ; i++) {
spell_list_node *entry = table->array[i];
if (entry == NULL) {
continue;
}
while (entry) {
if (!entry->data) {
entry = entry->next;
continue;
}
keyval *kv = (keyval *) entry->data;
spell_list_add_head(&keyvaluelist_head, kv);
entry = entry->next;
}
}
return keyvaluelist_head;
}
/**
* Dump the content of the hashtable into a file in a new line separated format where each
* line contains one key value pair.
* The function requires a pointer to a function which can return a string representation of the
* value object stored in the hashtable.
* The function also assumes that all the values stored in the table are of same type and the same
* function can be used to get the string representation in order to write to the file. In case this
* assumption does not hold true, do not use this function.
*/
void
spell_hashtable_dump(spell_hashtable *table, const char *filename, char *(*print) (void *))
{
if (table == NULL) {
return;
}
FILE *file = fopen(filename, "w");
if (file == NULL) {
warn("Failed to open file %s for writing.", filename);
return;
}
spell_list_node *keyvaluelist_head = spell_hashtable_get_key_values(table);
if (keyvaluelist_head == NULL) {
fclose(file);
warnx("Failed to read all the key value pairs from the table.");
return;
}
spell_list_node *node = keyvaluelist_head;
while (node != NULL) {
keyval *kv = node->data;
if (kv == NULL) {
node = node->next;
continue;
}
char *val = print(kv->val);
fprintf(file, "%s %s\n", kv->key, val);
free(val);
node = node->next;
}
fclose(file);
spell_list_free(&keyvaluelist_head, NULL);
}
|
abhinav-upadhyay/spell
|
libspell.h
|
<filename>libspell.h
#ifndef LIBSPELL_H
#define LIBSPELL_H
char *spell(char *);
char *get_suggestions(char *);
#endif
|
abhinav-upadhyay/spell
|
spell_list_test.c
|
<filename>spell_list_test.c
#include <assert.h>
#include <stdio.h>
#include <string.h>
#include "spellutil.h"
static void
test_list_init()
{
spell_list_node *n = NULL;
printf("[PASSED] test_list_init\n");
spell_list_free(&n, NULL);
}
static void
test_list_add_one()
{
int j = 20;
spell_list_node *n = NULL;
int status = spell_list_add_head(&n, &j);
assert(n->next == NULL);
assert(*(int *)n->data == j);
printf("[PASSED] test_list_add_one\n");
spell_list_free(&n, NULL);
}
static void
test_list_add_head_multi()
{
int i = 0;
int j = 1;
int k = 2;
int l = 3;
spell_list_node *head = spell_list_init(&i);
spell_list_add_head(&head, &j);
spell_list_add_head(&head, &k);
spell_list_add_head(&head, &l);
assert(*(int *) head->data == l);
assert(* (int *) head->next->data == k);
assert(* (int *) head->next->next->data == j);
assert(* (int *) head->next->next->next->data == i);
spell_list_free(&head, NULL);
printf("[PASSED] test_list_add_head_multi\n");
}
static void
test_list_free_one()
{
spell_list_node *n = NULL;
spell_list_free(&n, NULL);
assert(n == NULL);
printf("[PASSED] test_list_free_one\n");
}
static void
test_list_remove_head()
{
spell_list_node *n = NULL;
spell_list_remove(&n, n, NULL);
assert(n == NULL);
printf("[PASSED] test_list_remove_head\n");
}
static void
test_list_get_tail()
{
spell_list_node *n = NULL;
char *a = "a";
char *b = "b";
char *c = "c";
spell_list_add_head(&n, a);
spell_list_add_head(&n, b);
spell_list_add_head(&n, c);
spell_list_node *tail = spell_list_get_tail(n);
assert(tail->data == a);
assert(tail->next == NULL);
spell_list_free(&n, NULL);
printf("[PASSED] test_list_get_tail\n");
}
static int
node_compare(const void *d1, const void *d2)
{
const char *s1 = (const char *) d1;
const char *s2 = (const char *) d2;
return strcmp(s1, s2);
}
static void
test_list_get_middle()
{
spell_list_node *n = NULL;
char *a = "a";
char *b = "b";
char *c = "c";
spell_list_add_head(&n, a);
spell_list_add_head(&n, b);
spell_list_add_head(&n, c);
spell_list_node *mid_node = spell_list_get(n, "a", node_compare);
assert(mid_node != NULL);
spell_list_free(&n, NULL);
printf("[PASSED] test_list_get_middle\n");
}
static void
test_list_remove_tail()
{
int j = 20;
int k = 30;
char *s = "hello";
char *t = "world";
spell_list_node *tail;
spell_list_node *n = NULL;
spell_list_add_head(&n, &j);
spell_list_add_head(&n, &k);
spell_list_add_head(&n, s);
spell_list_add_head(&n, t);
tail = spell_list_get_tail(n);
assert(*(int *) tail->data == j);
spell_list_remove(&n, tail, NULL);
tail = spell_list_get_tail(n);
assert(*(int *) tail->data == k);
spell_list_free(&n, NULL);
printf("[PASSED] test_list_remove_tail\n");
}
static void
test_list_remove_one_element_list()
{
int j = 20;
spell_list_node *tail;
spell_list_node *n = NULL;
spell_list_add_head(&n, &j);
tail = spell_list_get_tail(n);
assert(*(int *) tail->data == j);
spell_list_remove(&n, tail, NULL);
tail = spell_list_get_tail(n);
assert(tail== NULL);
assert(n == NULL);
// spell_list_free(&n, NULL);
printf("[PASSED] test_list_remove_one_element_list\n");
}
static void
test_list_remove_middle()
{
spell_list_node *to_be_deleted;
spell_list_node *prev;
spell_list_node *next;
spell_list_node *n = NULL;
char *a = "a";
char *b = "b";
char *c = "c";
char *d = "d";
spell_list_add_head(&n, a);
spell_list_add_head(&n, b);
spell_list_add_head(&n, c);
spell_list_add_head(&n, d);
prev = n;
to_be_deleted = prev->next;
next = to_be_deleted->next;
while ((char *) to_be_deleted->data != c) {
prev = to_be_deleted;
to_be_deleted = to_be_deleted->next;
next = to_be_deleted->next;
}
spell_list_remove(&n, to_be_deleted, NULL);
assert(prev->next == next);
spell_list_free(&n, NULL);
printf("[PASSED] test_list_remove_middle\n");
}
int main
(int argc, char **argv)
{
test_list_init();
test_list_add_one();
test_list_free_one();
test_list_get_tail();
test_list_get_middle();
test_list_remove_head();
test_list_remove_tail();
test_list_remove_middle();
test_list_remove_one_element_list();
}
|
abhinav-upadhyay/spell
|
libspell.c
|
<reponame>abhinav-upadhyay/spell
#include <assert.h>
#include <err.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "libspell.h"
#include "spellutil.h"
#define N_PERMUTATIONS(n) 54 * n +25
typedef struct set {
char *a;
char *b;
} set;
typedef struct count {
int count;
} count;
static spell_list_node *
edits1 (char *word)
{
int i;
int len_a;
int len_b;
char alphabet;
int n = strlen(word);
set splits[n + 1];
char *candidate;
/* calculate number of possible permutations and allocate memory */
size_t size = N_PERMUTATIONS(n);
char **candidates = malloc (size * sizeof(char *));
spell_list_node *candidates_list = spell_list_init(NULL);
/* Start by generating a split up of the characters in the word */
for (i = 0; i < n + 1; i++) {
splits[i].a = (char *) malloc(i + 1);
splits[i].b = (char *) malloc(n - i + 1);
memcpy(splits[i].a, word, i);
memcpy(splits[i].b, word + i, n - i + 1);
splits[i].a[i] = 0;
}
/* Now generate all the permutations at maximum edit distance of 1.
* counter keeps track of the current index position in the array candidates
* where the next permutation needs to be stored.
*/
for (i = 0; i < n + 1; i++) {
len_a = strlen(splits[i].a);
len_b = strlen(splits[i].b);
assert(len_a + len_b == n);
/* Deletes */
if (i < n) {
candidate = malloc(n);
memcpy(candidate, splits[i].a, len_a);
if (len_b -1 > 0)
memcpy(candidate + len_a , splits[i].b + 1, len_b - 1);
candidate[n - 1] =0;
spell_list_add_head(&candidates_list, candidate);
}
/* Transposes */
if (i < n - 1) {
candidate = malloc(n + 1);
memcpy(candidate, splits[i].a, len_a);
if (len_b >= 1)
memcpy(candidate + len_a, splits[i].b + 1, 1);
if (len_b >= 1)
memcpy(candidate + len_a + 1, splits[i].b, 1);
if (len_b >= 2)
memcpy(candidate + len_a + 2, splits[i].b + 2, len_b - 2);
candidate[n] = 0;
spell_list_add_head(&candidates_list, candidate);
}
/* For replaces and inserts, run a loop from 'a' to 'z' */
for (alphabet = 'a'; alphabet <= 'z'; alphabet++) {
/* Replaces */
if (i < n) {
candidate = malloc(n + 1);
memcpy(candidate, splits[i].a, len_a);
memcpy(candidate + len_a, &alphabet, 1);
if (len_b - 1 >= 1)
memcpy(candidate + len_a + 1, splits[i].b + 1, len_b - 1);
candidate[n] = 0;
spell_list_add_head(&candidates_list, candidate);
}
/* Inserts */
candidate = malloc(n + 2);
memcpy(candidate, splits[i].a, len_a);
memcpy(candidate + len_a, &alphabet, 1);
if (len_b >=1)
memcpy(candidate + len_a + 1, splits[i].b, len_b);
candidate[n + 1] = 0;
spell_list_add_head(&candidates_list, candidate);
}
}
for (i = 0; i < n + 1; i++) {
free(splits[i].a);
free(splits[i].b);
}
return candidates_list;
}
static spell_hashtable *
parse_dictionary(const char *dictionary_filename)
{
FILE *dictionary_file = fopen(dictionary_filename, "r");
if (dictionary_file == NULL) {
warn("Failed to open %s", dictionary_filename);
return NULL;
}
spell_hashtable *dict = spell_hashtable_init(4096);
size_t len = 0;
size_t wordlen;
ssize_t read;
char *word = NULL;
char *line = NULL;
char *str_word_frequency;
int word_frequency;
count *c;
while ((read = getline(&line, &len, dictionary_file)) != -1) {
line[read - 1] = 0;
str_word_frequency = strchr(line, ' ');
*str_word_frequency++ = 0;
word = line;
word_frequency = atoi(str_word_frequency);
c = malloc(sizeof(count));
c->count = word_frequency;
spell_hashtable_add(dict, word, c);
}
free(line);
fclose(dictionary_file);
return dict;
}
|
abhinav-upadhyay/spell
|
spellutil.h
|
<reponame>abhinav-upadhyay/spell
#ifndef SPELLUTIL_H
#define SPELLUTIL_H
#include <sys/types.h>
#include <stdbool.h>
#define SPELL_HASHTABLE_INIT_SIZE 32
typedef struct spell_list_node {
struct spell_list_node *next;
void *data;
} spell_list_node;
typedef struct spell_hashtable_t {
spell_list_node **array;
size_t size;
size_t nfree;
} spell_hashtable;
typedef struct keyval {
char *key;
void *val;
} keyval;
spell_list_node *spell_list_init(void *);
int spell_list_add_head(spell_list_node **, void *);
void spell_list_remove(spell_list_node **, spell_list_node *, void (*) (void *));
void spell_list_free(spell_list_node **, void (*) (void *));
spell_list_node *spell_list_get_tail(spell_list_node *);
spell_list_node *spell_list_get(spell_list_node *, void *, int (*) (const void *, const void*));
spell_hashtable *spell_hashtable_init(size_t);
void spell_hashtable_add(spell_hashtable *, char *, void *);
void spell_hashtable_remove(spell_hashtable *, char *, void (*)(void *));
void *spell_hashtable_get(spell_hashtable *, char *);
void spell_hashtable_free(spell_hashtable *, void (*) (void *));
void spell_hashtable_dump(spell_hashtable *, const char *, char *(*print) (void *));
spell_list_node * spell_hashtable_get_key_values(spell_hashtable *);
#endif
|
msakai/haskell_cudd
|
c_sources/cuddwrap.c
|
#include <stdio.h>
#include <math.h>
#include <assert.h>
#include "util.h"
#include "cudd.h"
//Function wrappers around macros
DdNode *wrappedRegular(DdNode *f){
assert(f);
return Cudd_Regular(f);
}
void wrappedCuddRef(DdNode *f){
assert(f);
Cudd_Ref(f);
}
int wrappedCuddIsComplement(DdNode *f){
return Cudd_IsComplement(f);
}
//Garbage collection hooks
int preGCHook_sample(DdManager *dd, const char *str, void *data){
printf("Performing %s garbage collection...", str);
return 1;
}
int postGCHook_sample(DdManager *dd, const char *str, void *data){
printf("%s GC done\n", str);
return 1;
}
//Wrappers around enumeration of satisfying assignments and prime implicants
int **allSat(DdManager *m, DdNode *n, int *nterms, int *nvars){
CUDD_VALUE_TYPE value;
DdGen *gen;
int *cube;
int size = Cudd_ReadSize(m);
int num = ceil(Cudd_CountPathsToNonZero(n));
int i=0;
*nterms = num;
*nvars = size;
int **result = malloc(sizeof(int *)*num);
assert(result);
Cudd_ForeachCube(m, n, gen, cube, value){
result[i] = malloc(sizeof(int *)*size);
assert(result[i]);
int j;
for(j=0; j<size; j++){
result[i][j] = cube[j];
}
i++;
}
return result;
}
int *oneSat(DdManager *m, DdNode *n, int *nvars){
CUDD_VALUE_TYPE value;
DdGen *gen;
int *cube;
int size = Cudd_ReadSize(m);
int j;
*nvars = size;
gen = Cudd_FirstCube(m, n, &cube, &value);
if (Cudd_IsGenEmpty(gen)) {
Cudd_GenFree (gen);
return NULL;
}
int *result = malloc(sizeof(int) * size);
assert(result);
for(j=0; j<size; j++){
result[j] = cube[j];
}
Cudd_GenFree (gen);
return result;
}
int *onePrime(DdManager *m, DdNode *l, DdNode *u, int *nvars){
DdGen *gen;
int *cube;
int size = Cudd_ReadSize(m);
int j;
*nvars = size;
gen = Cudd_FirstPrime(m, l, u, &cube);
if (Cudd_IsGenEmpty(gen)) {
Cudd_GenFree (gen);
return NULL;
}
int *result = malloc(sizeof(int) * size);
assert(result);
for(j=0; j<size; j++){
result[j] = cube[j];
}
Cudd_GenFree (gen);
return result;
}
|
sbalk/tensorflow
|
tensorflow/contrib/lite/delegates/eager/test_util.h
|
/* Copyright 2018 The TensorFlow Authors. All Rights Reserved.
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 TENSORFLOW_CONTRIB_LITE_DELEGATES_EAGER_TEST_UTIL_H_
#define TENSORFLOW_CONTRIB_LITE_DELEGATES_EAGER_TEST_UTIL_H_
#include "tensorflow/c/c_api_internal.h"
#include "tensorflow/contrib/lite/kernels/test_util.h"
namespace tflite {
namespace eager {
namespace testing {
enum TfOpType {
kUnpack,
kIdentity,
kAdd,
kMul,
// Represents an op that does not exist in TensorFlow.
kNonExistent,
// Represents an valid TensorFlow op where the NodeDef is incompatible.
kIncompatibleNodeDef,
};
// This class creates models with TF and TFLite ops. In order to use this class
// to test the Eager delegate, implement a function that calls
// interpreter->ModifyGraphWithDelegate.
class EagerModelTest : public ::testing::Test {
public:
EagerModelTest() {}
~EagerModelTest() {}
bool Invoke();
// Sets the tensor's values at the given index.
void SetValues(int tensor_index, const std::vector<float>& values);
// Returns the tensor's values at the given index.
std::vector<float> GetValues(int tensor_index);
// Sets the tensor's shape at the given index.
void SetShape(int tensor_index, const std::vector<int>& values);
// Returns the tensor's shape at the given index.
std::vector<int> GetShape(int tensor_index);
const TestErrorReporter& error_reporter() const { return error_reporter_; }
// Adds `num_tensor` tensors to the model. `inputs` contains the indices of
// the input tensors and `outputs` contains the indices of the output
// tensors. All tensors are set to have `type` and `dims`.
void AddTensors(int num_tensors, const std::vector<int>& inputs,
const std::vector<int>& outputs, const TfLiteType& type,
const std::vector<int>& dims);
// Adds a TFLite Mul op. `inputs` contains the indices of the input tensors
// and `outputs` contains the indices of the output tensors.
void AddTfLiteMulOp(const std::vector<int>& inputs,
const std::vector<int>& outputs);
// Adds a TensorFlow op. `inputs` contains the indices of the
// input tensors and `outputs` contains the indices of the output tensors.
// This function is limited to the set of ops defined in TfOpType.
void AddTfOp(TfOpType op, const std::vector<int>& inputs,
const std::vector<int>& outputs);
protected:
std::unique_ptr<Interpreter> interpreter_;
TestErrorReporter error_reporter_;
private:
void AddTfOp(const char* tflite_name, const string& tf_name,
const string& nodedef_str, const std::vector<int>& inputs,
const std::vector<int>& outputs);
std::vector<std::vector<uint8_t>> flexbuffers_;
};
} // namespace testing
} // namespace eager
} // namespace tflite
#endif // TENSORFLOW_CONTRIB_LITE_DELEGATES_EAGER_TEST_UTIL_H_
|
depp/raycast
|
src/imath.c
|
<filename>src/imath.c
#include "imath.h"
#include "defs.h"
static const unsigned short SIN_TABLE[65] = {
0, 804, 1608, 2411, 3212, 4011, 4808, 5602,
6393, 7180, 7962, 8740, 9513, 10279, 11040, 11794,
12540, 13280, 14011, 14734, 15448, 16152, 16847, 17532,
18206, 18869, 19521, 20161, 20789, 21404, 22007, 22596,
23172, 23733, 24281, 24813, 25331, 25834, 26321, 26792,
27247, 27686, 28107, 28512, 28900, 29271, 29623, 29958,
30275, 30574, 30854, 31116, 31359, 31583, 31788, 31973,
32140, 32287, 32415, 32523, 32612, 32681, 32730, 32760,
32768
};
int isin(int x)
{
int ABITS = 16, QBITS = 2, TBITS = 6,
FBITS = ABITS - QBITS - TBITS,
Q = 1 << TBITS, F = 1 << FBITS;
int q = (x >> (ABITS - QBITS)) & 3,
i = (x >> (ABITS - QBITS - TBITS)) & (Q - 1), j = x & (F - 1);
int a1, a2;
switch (q) {
case 0:
a1 = SIN_TABLE[i];
a2 = SIN_TABLE[i+1];
break;
case 1:
a1 = SIN_TABLE[Q - i];
a2 = SIN_TABLE[Q - 1 - i];
break;
case 2:
a1 = -SIN_TABLE[i];
a2 = -SIN_TABLE[i + 1];
break;
case 3:
a1 = -SIN_TABLE[Q - i];
a2 = -SIN_TABLE[Q - 1 - i];
break;
}
return (a1 * (F - j) + a2 * j + F) >> (FBITS + 1);
}
int icos(int x)
{
return isin(x + 0x4000);
}
unsigned ilog2(unsigned x)
{
unsigned i;
for (i = 0; i < 32 && (1U << i) < x; ++i);
return i;
}
#if defined(ISIN_TEST)
#include <stdio.h>
#include <math.h>
int main(int argc, char *argv[])
{
int i;
double maxd = 0, err = 0, x, d;
for (i = 0; i < (1 << 16); ++i) {
x = sin(i * (atan(1) * 8 / 65536.0));
d = fabs(x - isin(i) / 16384.0);
if (d > maxd)
maxd = d;
err += d * d;
}
printf(
"error max: %f\n"
"error dev: %f\n",
maxd,
sqrt(err / 65536.0));
return 0;
}
#endif
|
depp/raycast
|
src/texture.h
|
<filename>src/texture.h
/* Each "pixels[n]" pointer points to a 32-bit texture with dimensions
(w >> n) by (h >> n), with minimum width and height 1. The
textures are stored as columns starting with the top left
pixel. */
struct texture {
unsigned wbits, hbits;
unsigned count;
void *pixels[];
};
enum {
TEXTURE_COLUMN = 1 << 0,
TEXTURE_COLOR = 1 << 1
};
void texture_load(struct texture **tex, const char *path);
void texture_make(struct texture **tex, unsigned char *ptr,
unsigned w, unsigned h, unsigned rb, unsigned flags);
extern struct texture *g_textures[3];
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.