hexsha stringlengths 40 40 | size int64 5 1.05M | ext stringclasses 588
values | lang stringclasses 305
values | max_stars_repo_path stringlengths 3 363 | max_stars_repo_name stringlengths 5 118 | max_stars_repo_head_hexsha stringlengths 40 40 | max_stars_repo_licenses listlengths 1 10 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringdate 2015-01-01 00:00:35 2022-03-31 23:43:49 ⌀ | max_stars_repo_stars_event_max_datetime stringdate 2015-01-01 12:37:38 2022-03-31 23:59:52 ⌀ | max_issues_repo_path stringlengths 3 363 | max_issues_repo_name stringlengths 5 118 | max_issues_repo_head_hexsha stringlengths 40 40 | max_issues_repo_licenses listlengths 1 10 | max_issues_count float64 1 134k ⌀ | max_issues_repo_issues_event_min_datetime stringlengths 24 24 ⌀ | max_issues_repo_issues_event_max_datetime stringlengths 24 24 ⌀ | max_forks_repo_path stringlengths 3 363 | max_forks_repo_name stringlengths 5 135 | max_forks_repo_head_hexsha stringlengths 40 40 | max_forks_repo_licenses listlengths 1 10 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringdate 2015-01-01 00:01:02 2022-03-31 23:27:27 ⌀ | max_forks_repo_forks_event_max_datetime stringdate 2015-01-03 08:55:07 2022-03-31 23:59:24 ⌀ | content stringlengths 5 1.05M | avg_line_length float64 1.13 1.04M | max_line_length int64 1 1.05M | alphanum_fraction float64 0 1 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
3d8d1356ac7555e38accef6b33aa80014c42bd73 | 182 | h | C | zipscript/include/postdel.h | mvangoor/pzs-ng | 97445d99d119b40559f917899459e69f655e4f67 | [
"BSD-3-Clause"
] | 2 | 2017-05-11T16:40:38.000Z | 2020-08-30T02:32:27.000Z | zipscript/include/postdel.h | bioboy/pzs-ng | d8903b7d048be0f36f30c99d5718c6175b20d07a | [
"BSD-3-Clause"
] | null | null | null | zipscript/include/postdel.h | bioboy/pzs-ng | d8903b7d048be0f36f30c99d5718c6175b20d07a | [
"BSD-3-Clause"
] | 2 | 2019-02-14T06:31:03.000Z | 2020-01-13T19:23:57.000Z | #ifndef POSTDEL_H
#define POSTDEL_H
#include "objects.h"
/* COMMENT THESE */
void writelog(GLOBAL *, char *, char *);
unsigned char get_filetype_postdel(GLOBAL *, char *);
#endif
| 16.545455 | 53 | 0.714286 |
0d2f9a741c76661b6f04419f07a700646b60f361 | 17,501 | h | C | include/fast_io_core_impl/to.h | clayne/fast_io | 1d7e12ea551d87e187a5a8881d9227ba3ea3b8a0 | [
"MIT"
] | 157 | 2021-07-12T07:19:15.000Z | 2022-02-16T02:22:45.000Z | include/fast_io_core_impl/to.h | clayne/fast_io | 1d7e12ea551d87e187a5a8881d9227ba3ea3b8a0 | [
"MIT"
] | 7 | 2021-08-02T05:06:23.000Z | 2021-12-26T10:32:18.000Z | include/fast_io_core_impl/to.h | clayne/fast_io | 1d7e12ea551d87e187a5a8881d9227ba3ea3b8a0 | [
"MIT"
] | 15 | 2021-07-17T19:58:14.000Z | 2021-12-30T15:37:32.000Z | #pragma once
namespace fast_io
{
namespace details
{
template<std::integral char_type,typename state,typename T,typename Arg1,typename ...Args>
#if __has_cpp_attribute(gnu::always_inline)
[[gnu::always_inline]]
#elif __has_cpp_attribute(msvc::forceinline)
[[msvc::forceinline]]
#endif
inline constexpr void inplace_to_decay_context_impl(io_reference_wrapper<dynamic_io_buffer<char_type>> buffer,state& s,T t,Arg1 arg,Args... args)
{
::fast_io::details::decay::print_control<false>(buffer,arg);
char_type *buffer_beg{buffer.ptr->buffer_begin};
char_type const *buffer_begin{buffer_beg};
char_type const *buffer_curr{buffer.ptr->buffer_curr};
auto [it,ec]=scan_context_define(io_reserve_type<char_type,T>,s,buffer_begin,buffer_curr,t);
if(it!=buffer_curr)
{
if(ec!=::fast_io::parse_code::ok)
::fast_io::throw_parse_code(ec);
return;
}
if constexpr(sizeof...(Args)!=0)
{
buffer.ptr->buffer_curr=buffer_beg;
inplace_to_decay_context_impl(buffer,s,t,args...);
}
else
{
::fast_io::parse_code p{scan_context_eof_define(io_reserve_type<char_type,T>,s,t)};
if(p!=::fast_io::parse_code::ok)
::fast_io::throw_parse_code(p);
}
}
template<std::integral char_type,typename state,typename T,typename Arg1,typename ...Args>
#if __has_cpp_attribute(gnu::always_inline)
[[gnu::always_inline]]
#elif __has_cpp_attribute(msvc::forceinline)
[[msvc::forceinline]]
#endif
inline constexpr void inplace_to_decay_buffer_scatter_context_impl(state& s,T t,Arg1 arg,Args... args)
{
basic_io_scatter_t<char_type> scatter{print_scatter_define(io_reserve_type<char_type,Arg1>,arg)};
char_type const* buffer_begin{scatter.base};
char_type const* buffer_curr{buffer_begin+scatter.len};
auto [it,ec]=scan_context_define(io_reserve_type<char_type,T>,s,buffer_begin,buffer_curr,t);
if(it!=buffer_curr)
{
if(ec!=::fast_io::parse_code::ok)
throw_parse_code(ec);
return;
}
if constexpr(sizeof...(Args)!=0)
{
inplace_to_decay_buffer_scatter_context_impl<char_type>(s,t,args...);
}
else
{
::fast_io::parse_code p{scan_context_eof_define(io_reserve_type<char_type,T>,s,t)};
if(p!=::fast_io::parse_code::ok)
throw_parse_code(p);
}
}
template<std::integral char_type,typename state,typename T,typename Arg1,typename ...Args>
#if __has_cpp_attribute(gnu::always_inline)
[[gnu::always_inline]]
#elif __has_cpp_attribute(msvc::forceinline)
[[msvc::forceinline]]
#endif
inline constexpr void inplace_to_decay_buffer_context_impl(char_type* buffer,state& s,T t,Arg1 arg,Args... args)
{
if constexpr(scatter_printable<char_type,Arg1>&&((scatter_printable<char_type,Args>&&...)))
{
inplace_to_decay_buffer_scatter_context_impl<char_type>(s,t,arg,args...);
}
else
{
char_type const* buffer_begin;
char_type const* buffer_curr;
if constexpr(scatter_printable<char_type,Arg1>)
{
auto scatter{print_scatter_define(io_reserve_type<char_type,Arg1>,arg)};
buffer_begin=scatter.base;
buffer_curr=buffer_begin+scatter.len;
}
else
{
buffer_curr=print_reserve_define(io_reserve_type<char_type,Arg1>,buffer,arg);
buffer_begin=buffer;
}
auto [it,ec]=scan_context_define(io_reserve_type<char_type,T>,s,buffer_begin,buffer_curr,t);
if(it!=buffer_curr)
{
if(ec!=::fast_io::parse_code::ok)
throw_parse_code(ec);
return;
}
if constexpr(sizeof...(Args)!=0)
{
inplace_to_decay_buffer_context_impl(buffer,s,t,args...);
}
else
{
parse_code p{scan_context_eof_define(io_reserve_type<char_type,T>,s,t)};
if(p!=parse_code::ok)
throw_parse_code(p);
}
}
}
template<std::integral char_type,bool ln,typename T,typename... Args>
inline constexpr std::size_t calculate_print_normal_maxium_size_main(std::size_t mx_value) noexcept
{
std::size_t val{};
if constexpr(ln&&(sizeof...(Args)==0))
++val;
if constexpr(reserve_printable<char_type,T>)
{
constexpr std::size_t size{print_reserve_size(io_reserve_type<char_type,T>)};
static_assert(size!=SIZE_MAX,"overflow");
val+=size;
}
if(mx_value<val)
mx_value=val;
if constexpr((sizeof...(Args)==0))
return mx_value;
else
return calculate_print_normal_maxium_size_main<char_type,ln,Args...>(mx_value);
}
template<std::integral char_type,bool ln,typename... Args>
inline constexpr std::size_t calculate_print_normal_maxium_size() noexcept
{
return calculate_print_normal_maxium_size_main<char_type,ln,Args...>(0);
}
template<std::integral char_type,bool ln,typename T,typename... Args>
inline constexpr std::size_t calculate_print_normal_dynamic_maxium_main(std::size_t mx_value,T t,Args... args) noexcept
{
if constexpr(dynamic_reserve_printable<char_type,T>)
{
std::size_t size{print_reserve_size(io_reserve_type<char_type,T>,t)};
if constexpr(ln&&(sizeof...(Args)==0))
{
if(size==SIZE_MAX)
fast_terminate();
++size;
}
if(mx_value<size)
mx_value=size;
}
if constexpr((sizeof...(Args)==0))
return mx_value;
else
return calculate_print_normal_dynamic_maxium_main<char_type,ln>(mx_value,args...);
}
template<std::integral char_type,typename T>
inline constexpr void deal_with_single_to(char_type const* buffer_begin,char_type const* buffer_end,T t)
{
auto code{scan_contiguous_define(io_reserve_type<char_type,T>,buffer_begin,buffer_end,t).code};
if(code!=parse_code::ok)
throw_parse_code(code);
}
template<std::integral char_type,typename T,typename Arg>
inline constexpr void to_deal_with_contiguous_single_scatter(T t,Arg arg)
{
basic_io_scatter_t<char_type> scatter{print_scatter_define(io_reserve_type<char_type,Arg>,arg)};
auto base{scatter.base};
deal_with_single_to<char_type>(base,base+scatter.len,t);
}
template<std::integral char_type,typename T,typename... Args>
inline constexpr char_type* to_impl_with_reserve_recursive(char_type* p,T t,Args ...args)
{
if constexpr(scatter_printable<char_type,T>)
{
p=copy_scatter(print_scatter_define(io_reserve_type<char_type,T>,t),p);
}
else
{
p=print_reserve_define(io_reserve_type<char_type,T>,p,t);
}
if constexpr(sizeof...(Args)==0)
{
return p;
}
else
{
return to_impl_with_reserve_recursive<char_type>(p,args...);
}
}
template<std::integral char_type,typename T,typename... Args>
inline constexpr std::size_t calculate_scatter_dynamic_reserve_size_with_scatter([[maybe_unused]] T t,Args... args)
{
if constexpr(dynamic_reserve_printable<char_type,T>)
{
std::size_t res{print_reserve_size(io_reserve_type<char_type,T>,t)};
if constexpr(sizeof...(Args)==0)
return res;
else
return ::fast_io::details::intrinsics::add_or_overflow_die(res,calculate_scatter_dynamic_reserve_size_with_scatter<char_type>(args...));
}
else if constexpr(scatter_printable<char_type,T>)
{
std::size_t res{print_scatter_define(io_reserve_type<char_type,std::remove_cvref_t<T>>,t).len};
if constexpr(sizeof...(Args)==0)
return res;
else
return ::fast_io::details::intrinsics::add_or_overflow_die(res,calculate_scatter_dynamic_reserve_size_with_scatter<char_type>(args...));
}
else
{
if constexpr(sizeof...(Args)==0)
return 0;
else
return calculate_scatter_dynamic_reserve_size_with_scatter<char_type>(args...);
}
}
template<typename char_type,typename T,typename ...Args>
concept inplace_to_decay_detect = std::integral<char_type>&&(sizeof...(Args)!=0&&print_freestanding_decay_okay_character_type_no_status<char_type,Args...>&&(contiguous_scanable<char_type,T>||context_scanable<char_type,T>));
}
template<std::integral char_type,typename T,typename ...Args>
inline constexpr void basic_inplace_to_decay(T t,Args... args)
{
constexpr bool failed{::fast_io::details::inplace_to_decay_detect<char_type,T,Args...>};
if constexpr(failed)
{
if constexpr(((reserve_printable<char_type,Args>||dynamic_reserve_printable<char_type,Args>||scatter_printable<char_type,Args>)&&...))
{
constexpr bool all_scatters{((scatter_printable<char_type,Args>)&&...)};
constexpr bool no_need_dynamic_reserve{((reserve_printable<char_type,Args>||scatter_printable<char_type,Args>)&&...)};
if constexpr(context_scanable<char_type,T>&&(!(contiguous_scanable<char_type,T>&&sizeof...(args)==1)))
{
typename std::remove_cvref_t<decltype(scan_context_type(io_reserve_type<char_type,T>))>::type state;
if constexpr(all_scatters)
{
::fast_io::details::inplace_to_decay_buffer_scatter_context_impl<char_type>(state,t,args...);
}
else if constexpr(no_need_dynamic_reserve)
{
constexpr std::size_t maximum_reserve_size{::fast_io::details::calculate_print_normal_maxium_size<char_type,false,Args...>()};
char_type buffer[maximum_reserve_size];
::fast_io::details::inplace_to_decay_buffer_context_impl<char_type>(buffer,state,t,args...);
}
else
{
std::size_t const maximum_reserve_size{::fast_io::details::calculate_print_normal_dynamic_maxium_main<char_type,false>(0,args...)};
::fast_io::details::local_operator_new_array_ptr<char_type> heap_buffer(maximum_reserve_size);
::fast_io::details::inplace_to_decay_buffer_context_impl<char_type>(heap_buffer.ptr,state,t,args...);
}
}
else if constexpr(contiguous_scanable<char_type,T>)
{
if constexpr(all_scatters&&sizeof...(Args)==1)//crucial for performance
{
::fast_io::details::to_deal_with_contiguous_single_scatter<char_type>(t,args...);
}
else if constexpr(((reserve_printable<char_type,Args>)&&...))
{
constexpr std::size_t total_size{::fast_io::details::decay::calculate_scatter_reserve_size<char_type,Args...>()};
char_type buffer[total_size];
auto ret{::fast_io::details::to_impl_with_reserve_recursive(buffer,args...)};
::fast_io::details::deal_with_single_to<char_type>(buffer,ret,t);
}
else
{
std::size_t const maximum_reserve_size{::fast_io::details::calculate_scatter_dynamic_reserve_size_with_scatter<char_type>(args...)};
::fast_io::details::local_operator_new_array_ptr<char_type> heap_buffer(maximum_reserve_size);
auto ret{::fast_io::details::to_impl_with_reserve_recursive(heap_buffer.ptr,args...)};
::fast_io::details::deal_with_single_to<char_type>(heap_buffer.ptr,ret,t);
}
}
}
else
{
dynamic_io_buffer<char_type> buffer;
auto ref{io_ref(buffer)};
if constexpr(context_scanable<char_type,T>&&(!(contiguous_scanable<char_type,T>&&sizeof...(args)==1)))
{
typename std::remove_cvref_t<decltype(scan_context_type(io_reserve_type<char_type,T>))>::type state;
::fast_io::details::inplace_to_decay_context_impl(ref,state,t,args...);
}
else if constexpr(contiguous_scanable<char_type,T>)
{
::fast_io::print_freestanding_decay_no_status<false>(ref,args...);
::fast_io::details::deal_with_single_to<char_type>(buffer.buffer_begin,buffer.buffer_curr,t);
}
else
{
constexpr bool type_error{context_scanable<char_type,T>};
static_assert(type_error,"scan type error");
}
}
}
else
{
static_assert(failed,"either somes args not printable or some type not detectable");
}
}
namespace details
{
template<std::integral char_type,typename T,typename ...Args>
requires ::fast_io::details::inplace_to_decay_detect<char_type,T,Args...>
inline constexpr void basic_inplace_to_decay_model(T,Args...)
{
}
template<typename char_type,typename T,typename ...Args>
concept can_do_inplace_to = requires(T& t,Args&& ...args)
{
::fast_io::details::basic_inplace_to_decay_model<char_type>(::fast_io::io_scan_forward<char_type>(::fast_io::io_scan_alias(t)),io_print_forward<char_type>(io_print_alias(args))...);
};
}
template<std::integral char_type,typename T,typename ...Args>
inline constexpr void basic_inplace_to(T&& t,Args&& ...args)
{
constexpr bool failed{::fast_io::details::can_do_inplace_to<char_type,T,Args...>};
if constexpr(failed)
{
::fast_io::basic_inplace_to_decay<char_type>(::fast_io::io_scan_forward<char_type>(::fast_io::io_scan_alias(t)),io_print_forward<char_type>(io_print_alias(args))...);
}
else
{
static_assert(failed,"either somes args not printable or some type not detectable");
}
}
template<typename T,typename ...Args>
inline constexpr void inplace_to(T&& t,Args&& ...args)
{
constexpr bool failed{::fast_io::details::can_do_inplace_to<char,T,Args...>};
if constexpr(failed)
{
::fast_io::basic_inplace_to_decay<char>(::fast_io::io_scan_forward<char>(::fast_io::io_scan_alias(t)),io_print_forward<char>(io_print_alias(args))...);
}
else
{
static_assert(failed,"either somes args not printable or some type not detectable");
}
}
template<typename T,typename ...Args>
inline constexpr void winplace_to(T&& t,Args&& ...args)
{
constexpr bool failed{::fast_io::details::can_do_inplace_to<wchar_t,T,Args...>};
if constexpr(failed)
{
::fast_io::basic_inplace_to_decay<wchar_t>(::fast_io::io_scan_forward<wchar_t>(::fast_io::io_scan_alias(t)),io_print_forward<wchar_t>(io_print_alias(args))...);
}
else
{
static_assert(failed,"either somes args not printable or some type not detectable");
}
}
template<typename T,typename ...Args>
inline constexpr void u8inplace_to(T&& t,Args&& ...args)
{
constexpr bool failed{::fast_io::details::can_do_inplace_to<char8_t,T,Args...>};
if constexpr(failed)
{
::fast_io::basic_inplace_to_decay<char8_t>(::fast_io::io_scan_forward<char8_t>(::fast_io::io_scan_alias(t)),io_print_forward<char8_t>(io_print_alias(args))...);
}
else
{
static_assert(failed,"either somes args not printable or some type not detectable");
}
}
template<typename T,typename ...Args>
inline constexpr T u16inplace_to(T&& t,Args&& ...args)
{
constexpr bool failed{::fast_io::details::can_do_inplace_to<char16_t,T,Args...>};
if constexpr(failed)
{
::fast_io::basic_inplace_to_decay<char16_t>(::fast_io::io_scan_forward<char16_t>(::fast_io::io_scan_alias(t)),io_print_forward<char16_t>(io_print_alias(args))...);
}
else
{
static_assert(failed,"either somes args not printable or some type not detectable");
return T();
}
}
template<typename T,typename ...Args>
inline constexpr T u32inplace_to(T&& t,Args&& ...args)
{
constexpr bool failed{::fast_io::details::can_do_inplace_to<char32_t,T,Args...>};
if constexpr(failed)
{
::fast_io::basic_inplace_to_decay<char32_t>(::fast_io::io_scan_forward<char32_t>(::fast_io::io_scan_alias(t)),io_print_forward<char32_t>(io_print_alias(args))...);
}
else
{
static_assert(failed,"either somes args not printable or some type not detectable");
return T();
}
}
template<std::integral char_type,typename T,typename ...Args>
inline constexpr T basic_to_decay(Args... args)
{
constexpr bool failed{::fast_io::details::can_do_inplace_to<char_type,T,Args...>};
if constexpr(sizeof...(Args)==0)
{
return T();
}
else if constexpr(failed)
{
if constexpr(std::is_scalar_v<T>)
{
T v{};
basic_inplace_to_decay<char_type>(::fast_io::io_scan_forward<char_type>(::fast_io::io_scan_alias(v)),args...);
return v;
}
else
{
T v;
basic_inplace_to_decay<char_type>(::fast_io::io_scan_forward<char_type>(::fast_io::io_scan_alias(v)),args...);
return v;
}
}
else
{
static_assert(failed,"either somes args not printable or some type not detectable");
return T();
}
}
template<std::integral char_type,typename T,typename ...Args>
inline constexpr T basic_to(Args&& ...args)
{
constexpr bool failed{::fast_io::details::can_do_inplace_to<char_type,T,Args...>};
if constexpr(failed)
{
return ::fast_io::basic_to_decay<char_type,T>(io_print_forward<char_type>(io_print_alias(args))...);
}
else
{
static_assert(failed,"either somes args not printable or some type not detectable");
return T();
}
}
template<typename T,typename ...Args>
inline constexpr T to(Args&& ...args)
{
constexpr bool failed{::fast_io::details::can_do_inplace_to<char,T,Args...>};
if constexpr(failed)
{
return ::fast_io::basic_to_decay<char,T>(io_print_forward<char>(io_print_alias(args))...);
}
else
{
static_assert(failed,"either somes args not printable or some type not detectable");
return T();
}
}
template<typename T,typename ...Args>
inline constexpr T wto(Args&& ...args)
{
constexpr bool failed{::fast_io::details::can_do_inplace_to<wchar_t,T,Args...>};
if constexpr(failed)
{
return ::fast_io::basic_to_decay<wchar_t,T>(io_print_forward<wchar_t>(io_print_alias(args))...);
}
else
{
static_assert(failed,"either somes args not printable or some type not detectable");
return T();
}
}
template<typename T,typename ...Args>
inline constexpr T u8to(Args&& ...args)
{
constexpr bool failed{::fast_io::details::can_do_inplace_to<char8_t,T,Args...>};
if constexpr(failed)
{
return ::fast_io::basic_to_decay<char8_t,T>(io_print_forward<char8_t>(io_print_alias(args))...);
}
else
{
static_assert(failed,"either somes args not printable or some type not detectable");
return T();
}
}
template<typename T,typename ...Args>
inline constexpr T u16to(Args&& ...args)
{
constexpr bool failed{::fast_io::details::can_do_inplace_to<char16_t,T,Args...>};
if constexpr(failed)
{
return ::fast_io::basic_to_decay<char16_t,T>(io_print_forward<char16_t>(io_print_alias(args))...);
}
else
{
static_assert(failed,"either somes args not printable or some type not detectable");
return T();
}
}
template<typename T,typename ...Args>
inline constexpr T u32to(Args&& ...args)
{
constexpr bool failed{::fast_io::details::can_do_inplace_to<char32_t,T,Args...>};
if constexpr(failed)
{
return ::fast_io::basic_to_decay<char32_t,T>(io_print_forward<char32_t>(io_print_alias(args))...);
}
else
{
static_assert(failed,"either somes args not printable or some type not detectable");
return T();
}
}
}
| 32.349353 | 223 | 0.745786 |
b8c98d7501dbc336e442b7fcb76afa55e74ee830 | 1,843 | h | C | VS/Utils/VS_SingletonManager.h | vectorstorm/vectorstorm | 7306214108b23fa97d4a1a598197bbaa52c17d3a | [
"Zlib"
] | 19 | 2017-04-03T09:06:21.000Z | 2022-03-05T19:06:07.000Z | VS/Utils/VS_SingletonManager.h | vectorstorm/vectorstorm | 7306214108b23fa97d4a1a598197bbaa52c17d3a | [
"Zlib"
] | 2 | 2019-05-24T14:40:07.000Z | 2020-04-15T01:10:23.000Z | VS/Utils/VS_SingletonManager.h | vectorstorm/vectorstorm | 7306214108b23fa97d4a1a598197bbaa52c17d3a | [
"Zlib"
] | 2 | 2020-03-08T07:14:49.000Z | 2020-03-09T10:39:52.000Z | /*
* VS_SingletonManager.h
* MMORPG2
*
* Created by Trevor Powell on 23/05/09.
* Copyright 2009 Trevor Powell. All rights reserved.
*
*/
#ifndef VS_SINGLETON_MANAGER_H
#define VS_SINGLETON_MANAGER_H
#include "VS_HashTable.h"
// The behaviour of static members inside templated classes inside libraries is undefined by
// the C standard, and some compilers (most notably GCC compilers before the 3.0 series)
// give each library its own static members for these templated classes which are referenced
// both by library code and by game code. To get around this problem, we have the
// vsSingletonManager, which (although using the singleton pattern), is not templated via
// the vsSingleton template, and so doesn't have this static data problem.
//
// The vsSingletonManager stores a hash table of currently existing singletons. vsSingleton
// talks to it when people try to access an apparently non-existant singleton, to check whether
// perhaps this build has been compiled by a compiler which has provided separate static variable
// space for the library than for the game code.. and will retrieve the singleton pointers so that
// the same pointer can be set in both sets of static data, if that turns out to be the case.
//
// Note that this requires RTTI to be enabled, in order to work, as we use the requested singleton's
// RTTI type name as our key into the hash table.
class vsSingletonManager
{
static vsSingletonManager * s_instance;
vsHashTable<void *> m_table;
public:
vsSingletonManager();
~vsSingletonManager();
void RegisterSingleton(void *singleton, const vsString &name);
void UnregisterSingleton(void *singleton, const vsString &name);
void * GetSingleton(const vsString &name);
static vsSingletonManager * Instance() { return s_instance; }
};
#endif // VS_SINGLETON_MANAGER_H
| 36.86 | 100 | 0.7656 |
ef03b66f8d52b54bb67de17b1bdce91992070c45 | 10,193 | h | C | os/arch/arm/include/amebad/irq.h | ziyik/TizenRT-1 | d510c03303fcfa605bc12c60f826fa5642bbe406 | [
"Apache-2.0"
] | 511 | 2017-03-29T09:14:09.000Z | 2022-03-30T23:10:29.000Z | os/arch/arm/include/amebad/irq.h | ziyik/TizenRT-1 | d510c03303fcfa605bc12c60f826fa5642bbe406 | [
"Apache-2.0"
] | 4,673 | 2017-03-29T10:43:43.000Z | 2022-03-31T08:33:44.000Z | os/arch/arm/include/amebad/irq.h | ziyik/TizenRT-1 | d510c03303fcfa605bc12c60f826fa5642bbe406 | [
"Apache-2.0"
] | 642 | 2017-03-30T20:45:33.000Z | 2022-03-24T17:07:33.000Z | /****************************************************************************
*
* Copyright 2020 Samsung Electronics 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.
*
****************************************************************************/
/****************************************************************************
*
* Copyright (C) 2020 Gregory Nutt. All rights reserved.
* Author: Gregory Nutt <gnutt@nuttx.org>
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
* 3. Neither the name NuttX nor the names of its contributors may be
* used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
****************************************************************************/
#include <tinyara/config.h>
#define NR_IRQS 80
/************************************************************************************
* Pre-processor Definitions
************************************************************************************/
/* IRQ numbers. The IRQ number corresponds vector number and hence map directly to
* bits in the NVIC. This does, however, waste several words of memory in the IRQ
* to handle mapping tables.
*/
/* Processor Exceptions (vectors 0-15) */
#define AMEBAD_IRQ_RESERVED (0) /* Reserved vector (only used with CONFIG_DEBUG) */
/* Vector 0: Reset stack pointer value */
/* Vector 1: Reset (not handler as an IRQ) */
#define AMEBAD_IRQ_NMI (2) /* Vector 2: Non-Maskable Interrupt (NMI) */
#define AMEBAD_IRQ_HARDFAULT (3) /* Vector 3: Hard fault */
#define AMEBAD_IRQ_MEMFAULT (4) /* Vector 4: Memory management (MPU) */
#define AMEBAD_IRQ_BUSFAULT (5) /* Vector 5: Bus fault */
#define AMEBAD_IRQ_USAGEFAULT (6) /* Vector 6: Usage fault */
/* Vectors 7-10: Reserved */
#define AMEBAD_IRQ_SVCALL (11) /* Vector 11: SVC call */
#define AMEBAD_IRQ_DBGMONITOR (12) /* Vector 12: Debug Monitor */
/* Vector 13: Reserved */
#define AMEBAD_IRQ_PENDSV (14) /* Vector 14: Pendable system service request */
#define AMEBAD_IRQ_SYSTICK (15) /* Vector 15: System tick */
/* External interrupts (vectors >= 16). These definitions are chip-specific */
#define AMEBAD_IRQ_FIRST (16) /* Vector number of the first external interrupt */
#define AMEBAD_IRQ_SYSTEM_ON (AMEBAD_IRQ_FIRST + 0) /*!< 0 SYS Interrupt for wakeup from power save */
#define AMEBAD_IRQ_WDG (AMEBAD_IRQ_FIRST + 1) /*!< 1 Watch dog global insterrupt */
#define AMEBAD_IRQ_RXI300 (AMEBAD_IRQ_FIRST + 2) /*!< 2 RXI300 interrupt */
#define AMEBAD_IRQ_UART_LOG (AMEBAD_IRQ_FIRST + 3) /*!< 3 log uart intr */
#define AMEBAD_IRQ_GPIOA (AMEBAD_IRQ_FIRST + 4) /*!< 4 GPIOA portA global interrupt */
#define AMEBAD_IRQ_RTC (AMEBAD_IRQ_FIRST + 5) /*!< 5 rtc timer interrupt */
#define AMEBAD_IRQ_I2C0 (AMEBAD_IRQ_FIRST + 6) /*!< 6 I2C0 global interrupt */
#define AMEBAD_IRQ_SPI_FLASH (AMEBAD_IRQ_FIRST + 7) /*!< 7 SPI Flash global interrupt */
#define AMEBAD_IRQ_GPIOB (AMEBAD_IRQ_FIRST + 8) /*!< 8 GPIOB portA global interrupt */
#define AMEBAD_IRQ_UARTLP (AMEBAD_IRQ_FIRST + 9) /*!< 9 UART0 global interrupt */
#define AMEBAD_IRQ_KEYSCAN (AMEBAD_IRQ_FIRST + 10) /*!< 10 KEYSCAN interrupt */
#define AMEBAD_IRQ_CTOUCH (AMEBAD_IRQ_FIRST + 11) /*!< 11 Cap-Touch interrupt */
#define AMEBAD_IRQ_BOR2 (AMEBAD_IRQ_FIRST + 12) /*!< 12 BOR2 interrupt */
#define AMEBAD_IRQ_SGPIO (AMEBAD_IRQ_FIRST + 13) /*!< 13 SGPIO interrupt */
#define AMEBAD_IRQ_IPC (AMEBAD_IRQ_FIRST + 14) /*!< 14 IPC_KM0 interrupt */
#define AMEBAD_IRQ_ADC (AMEBAD_IRQ_FIRST + 15) /*!< 15 adc interrupt */
#define AMEBAD_IRQ_QDECODER (AMEBAD_IRQ_FIRST + 16) /*!< 16 Q-DECODER interrupt */
#define AMEBAD_IRQ_TIMER0 (AMEBAD_IRQ_FIRST + 17) /*!< 17 Timer0 global interrupt */
#define AMEBAD_IRQ_TIMER1 (AMEBAD_IRQ_FIRST + 18) /*!< 18 Timer1 global interrupt */
#define AMEBAD_IRQ_TIMER2 (AMEBAD_IRQ_FIRST + 19) /*!< 19 Timer2 global interrupt */
#define AMEBAD_IRQ_TIMER3 (AMEBAD_IRQ_FIRST + 20) /*!< 20 Timer3 global interrupt */
#define AMEBAD_IRQ_TIMER4 (AMEBAD_IRQ_FIRST + 21) /*!< 21 Timer4 global interrupt */
#define AMEBAD_IRQ_TIMER5 (AMEBAD_IRQ_FIRST + 22) /*!< 22 Timer5 global interrupt */
#define AMEBAD_IRQ_LCDC (AMEBAD_IRQ_FIRST + 23) /*!< 23 LCDC interrupt */
#define AMEBAD_IRQ_USB_OTG (AMEBAD_IRQ_FIRST + 24) /*!< 24 USOC interrupt */
#define AMEBAD_IRQ_SDIO_DEVICE (AMEBAD_IRQ_FIRST + 25) /*!< 25 SDIO device global interrupt */
#define AMEBAD_IRQ_SDIO_HOST (AMEBAD_IRQ_FIRST + 26) /*!< 26 SDIO host global interrupt */
#define AMEBAD_IRQ_CRYPTO (AMEBAD_IRQ_FIRST + 27) /*!< 27 IPsec global interrupt */
#define AMEBAD_IRQ_I2S0_PCM0 (AMEBAD_IRQ_FIRST + 28) /*!< 28 I2S0 global interrupt */
#define AMEBAD_IRQ_PWR_DOWN (AMEBAD_IRQ_FIRST + 29) /*!< 29 power down enable interrupt */
#define AMEBAD_IRQ_ADC_COMP (AMEBAD_IRQ_FIRST + 30) /*!< 30 ADC compare interrupt */
#define AMEBAD_IRQ_WL_DMA (AMEBAD_IRQ_FIRST + 31) /*!< 31 Wlan Host global interrupt */
#define AMEBAD_IRQ_WL_PROTOCOL (AMEBAD_IRQ_FIRST + 32) /*!< 32 Wlan Firmware Wlan global interrupt */
#define AMEBAD_IRQ_PSRAMC (AMEBAD_IRQ_FIRST + 33) /*!< 33 PSRAM controller interrupt */
#define AMEBAD_IRQ_UART0 (AMEBAD_IRQ_FIRST + 34) /*!< 34 UART0 global interrupt */
#define AMEBAD_IRQ_UART1 (AMEBAD_IRQ_FIRST + 35) /*!< 35 UART1 BT UART global interrupt */
#define AMEBAD_IRQ_SPI0 (AMEBAD_IRQ_FIRST + 36) /*!< 36 SPI0 global interrupt for communication spi */
#define AMEBAD_IRQ_SPI1 (AMEBAD_IRQ_FIRST + 37) /*!< 37 SPI1 global interrupt for communication spi */
#define AMEBAD_IRQ_USI (AMEBAD_IRQ_FIRST + 38) /*!< 38 USI global interrupt */
#define AMEBAD_IRQ_IR (AMEBAD_IRQ_FIRST + 39) /*!< 39 IR global interrupt */
#define AMEBAD_IRQ_BT2WL_STS (AMEBAD_IRQ_FIRST + 40) /*!< 40 BT to WL Status Interrupt */
#define AMEBAD_IRQ_GDMA0_CHANNEL0 (AMEBAD_IRQ_FIRST + 41) /*!< 41 GDMA0 channel 0 global interrupt */
#define AMEBAD_IRQ_GDMA0_CHANNEL1 (AMEBAD_IRQ_FIRST + 42) /*!< 42 GDMA0 channel 1 global interrupt */
#define AMEBAD_IRQ_GDMA0_CHANNEL2 (AMEBAD_IRQ_FIRST + 43) /*!< 43 GDMA0 channel 2 global interrupt */
#define AMEBAD_IRQ_GDMA0_CHANNEL3 (AMEBAD_IRQ_FIRST + 44) /*!< 44 GDMA0 channel 3 global interrupt */
#define AMEBAD_IRQ_GDMA0_CHANNEL4 (AMEBAD_IRQ_FIRST + 45) /*!< 45 GDMA0 channel 4 global interrupt */
#define AMEBAD_IRQ_GDMA0_CHANNEL5 (AMEBAD_IRQ_FIRST + 46) /*!< 46 GDMA0 channel 5 global interrupt */
#define AMEBAD_IRQ_S_CRYPTO (AMEBAD_IRQ_FIRST + 50) /*!< 50 IPsec global interrupt */
#define AMEBAD_IRQ_S_RXI300 (AMEBAD_IRQ_FIRST + 51) /*!< 51 RXI300 interrupt */
#define AMEBAD_IRQ_S_GDMA0_CHANNEL0 (AMEBAD_IRQ_FIRST + 52) /*!< 52 GDMA0 channel 0 global interrupt */
#define AMEBAD_IRQ_S_GDMA0_CHANNEL1 (AMEBAD_IRQ_FIRST + 53) /*!< 53 GDMA0 channel 1 global interrupt */
#define AMEBAD_IRQ_S_GDMA0_CHANNEL2 (AMEBAD_IRQ_FIRST + 54) /*!< 54 GDMA0 channel 2 global interrupt */
#define AMEBAD_IRQ_S_GDMA0_CHANNEL3 (AMEBAD_IRQ_FIRST + 55) /*!< 55 GDMA0 channel 3 global interrupt */
#define AMEBAD_IRQ_S_GDMA0_CHANNEL4 (AMEBAD_IRQ_FIRST + 56) /*!< 56 GDMA0 channel 4 global interrupt */
#define AMEBAD_IRQ_S_GDMA0_CHANNEL5 (AMEBAD_IRQ_FIRST + 57) /*!< 57 GDMA0 channel 5 global interrupt */
| 70.784722 | 122 | 0.619445 |
efa8992f9d62741a5ca538df163e6f6df059cdff | 252 | h | C | gala-gopher/src/probes/extends/ebpf.probe/src/include/args.h | manas-rust/A-ops | 12badd8a1856d8b27a15961b85cb9b84c88e262a | [
"MulanPSL-1.0"
] | null | null | null | gala-gopher/src/probes/extends/ebpf.probe/src/include/args.h | manas-rust/A-ops | 12badd8a1856d8b27a15961b85cb9b84c88e262a | [
"MulanPSL-1.0"
] | null | null | null | gala-gopher/src/probes/extends/ebpf.probe/src/include/args.h | manas-rust/A-ops | 12badd8a1856d8b27a15961b85cb9b84c88e262a | [
"MulanPSL-1.0"
] | null | null | null | #ifndef __GOPHER_ARGS_H__
#define __GOPHER_ARGS_H__
#define MAX_PATH_LEN 512
struct probe_params {
unsigned int period;
char elf_path[MAX_PATH_LEN];
};
int args_parse(int argc, char **argv, char *opt_str, struct probe_params* params);
#endif
| 21 | 82 | 0.769841 |
89729ad5f7a0a65e7925547dd6868403c4f1349e | 500 | h | C | src/gui/PRArtworkController.h | musicman3320/Pandorita | 7d63abde20ba00eeee71117d93145561d6aa9c14 | [
"MIT"
] | 4 | 2015-02-04T18:42:32.000Z | 2015-10-21T09:36:35.000Z | src/gui/PRArtworkController.h | musicman3320/Pandorita | 7d63abde20ba00eeee71117d93145561d6aa9c14 | [
"MIT"
] | 2 | 2016-01-25T20:05:09.000Z | 2016-08-27T18:36:57.000Z | src/gui/PRArtworkController.h | musicman3320/Pandorita | 7d63abde20ba00eeee71117d93145561d6aa9c14 | [
"MIT"
] | null | null | null | //
// PRArtworkView.h
// Pandorita
//
// Created by Chris O'Neill on 2/20/12.
// Copyright 2012 __MyCompanyName__. All rights reserved.
//
#import <Cocoa/Cocoa.h>
#import "PRSong.h"
@interface PRArtworkController : NSObject <NSURLConnectionDelegate, NSSplitViewDelegate>
{
IBOutlet NSImageView *imageView;
NSMutableData *responseData;
NSURLConnection *connection;
NSData *artworkData;
}
- (NSData *)artworkData;
- (void)loadImageFromSong:(PRSong *)song;
- (void)clearArtwork;
@end
| 16.666667 | 88 | 0.734 |
372ec3e52d162ed8a318846cdb4956914102ee81 | 997 | h | C | PrivateFrameworks/AssistantServices/AceObject-AFSecurityDigestibleChunksProvider.h | phatblat/macOSPrivateFrameworks | 9047371eb80f925642c8a7c4f1e00095aec66044 | [
"MIT"
] | 17 | 2018-11-13T04:02:58.000Z | 2022-01-20T09:27:13.000Z | PrivateFrameworks/AssistantServices/AceObject-AFSecurityDigestibleChunksProvider.h | phatblat/macOSPrivateFrameworks | 9047371eb80f925642c8a7c4f1e00095aec66044 | [
"MIT"
] | 3 | 2018-04-06T02:02:27.000Z | 2018-10-02T01:12:10.000Z | PrivateFrameworks/AssistantServices/AceObject-AFSecurityDigestibleChunksProvider.h | phatblat/macOSPrivateFrameworks | 9047371eb80f925642c8a7c4f1e00095aec66044 | [
"MIT"
] | 1 | 2018-09-28T13:54:23.000Z | 2018-09-28T13:54:23.000Z | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "AceObject.h"
#import "AFAnalyticsContextVending.h"
#import "AFSecurityDigestibleChunksProviding.h"
@class NSString;
@interface AceObject (AFSecurityDigestibleChunksProvider) <AFSecurityDigestibleChunksProviding, AFAnalyticsContextVending>
- (void)af_enumerateDigestibleChunksWithOptions:(unsigned long long)arg1 usingBlock:(CDUnknownBlockType)arg2;
- (id)af_dialogIdentifiersForAnalyticsContext;
- (void)af_addEntriesToAnalyticsContext:(id)arg1;
- (id)af_analyticsContext;
- (BOOL)_af_isKindOfDictationRequest;
- (id)af_speakableText;
- (id)af_text;
- (id)af_dialogIdentifier;
- (BOOL)af_isUserUtterance;
- (BOOL)af_isUtterance;
// Remaining properties
@property(readonly, copy) NSString *debugDescription;
@property(readonly, copy) NSString *description;
@property(readonly) unsigned long long hash;
@property(readonly) Class superclass;
@end
| 30.212121 | 122 | 0.792377 |
881ec6b64e48688fc1cfc9bfcb164d2f9d5da68f | 1,245 | h | C | Robus/inc/robus.h | Luos-io/Luos | c346d831f8f46f15c0c0ad8e93aef4974744909b | [
"Apache-2.0"
] | 176 | 2020-04-27T07:46:44.000Z | 2022-03-30T14:54:39.000Z | Robus/inc/robus.h | Luos-io/Luos | c346d831f8f46f15c0c0ad8e93aef4974744909b | [
"Apache-2.0"
] | 72 | 2020-04-27T12:47:52.000Z | 2022-03-24T09:29:06.000Z | Robus/inc/robus.h | Luos-io/Luos | c346d831f8f46f15c0c0ad8e93aef4974744909b | [
"Apache-2.0"
] | 15 | 2020-05-12T07:02:29.000Z | 2022-01-20T16:11:38.000Z | /******************************************************************************
* @file robus
* @brief User functionalities of the robus communication protocol
* @author Luos
* @version 0.0.0
******************************************************************************/
#ifndef _ROBUS_H_
#define _ROBUS_H_
#include <stdint.h>
#include "robus_struct.h"
/*******************************************************************************
* Definitions
******************************************************************************/
/*******************************************************************************
* Variables
******************************************************************************/
/*******************************************************************************
* Function
******************************************************************************/
void Robus_Init(memory_stats_t *memory_stats);
void Robus_Loop(void);
ll_service_t *Robus_ServiceCreate(uint16_t type);
void Robus_ServicesClear(void);
error_return_t Robus_SendMsg(ll_service_t *ll_service, msg_t *msg);
uint16_t Robus_TopologyDetection(ll_service_t *ll_service);
node_t *Robus_GetNode(void);
void Robus_Flush(void);
#endif /* _ROBUS_H_ */
| 37.727273 | 80 | 0.37751 |
69855c48ee04fae7eaa730c418a65745be0239bd | 1,739 | h | C | SDKs/CryCode/3.8.1/CryEngine/CryScriptSystem/LuaDebuggerResource.h | amrhead/FireNET | 34d439aa0157b0c895b20b2b664fddf4f9b84af1 | [
"BSD-2-Clause"
] | 4 | 2017-12-18T20:10:16.000Z | 2021-02-07T21:21:24.000Z | SDKs/CryCode/3.7.0/CryEngine/CryScriptSystem/LuaDebuggerResource.h | amrhead/FireNET | 34d439aa0157b0c895b20b2b664fddf4f9b84af1 | [
"BSD-2-Clause"
] | null | null | null | SDKs/CryCode/3.7.0/CryEngine/CryScriptSystem/LuaDebuggerResource.h | amrhead/FireNET | 34d439aa0157b0c895b20b2b664fddf4f9b84af1 | [
"BSD-2-Clause"
] | 3 | 2019-03-11T21:36:15.000Z | 2021-02-07T21:21:26.000Z | //{{NO_DEPENDENCIES}}
// Microsoft Visual C++ generated include file.
// Used by LuaDebugger.rc
//
#define IDC_LUADBG 102
#define IDB_TREE_VIEW 104
#define IDI_LUADBG 105
#define IDM_ABOUT 109
#define ID_DEBUG_TOGGLEBREAKPOINT 110
#define ID_DEBUG_STEPOVER 111
#define ID_DEBUG_STEPINTO 112
#define ID_DEBUG_RUN 113
#define ID_DEBUG_BREAK 114
#define ID_DEBUG_STOP 115
#define IDD_ABOUTBOX 117
#define ID_EDIT_GOTOLINE 122
#define IDR_LUADGB_ACCEL 124
#define ID_FILE_RELOAD 126
#define IDD_GOTO 127
#define IDD_GOTO_FUNC 128
#define IDC_EDIT1 1001
#define IDC_LIST_FUNC 1002
#define IDM_EXIT 1018
#define ID_DEBUG_DISABLE 40020
#define ID_DEBUG_ERRORS 40021
#define ID_DEBUG_ENABLE 40022
#define ID_BUTTON40071 40071
#define ID_DEBUG_DELETEALLBREAKPOINTS 40076
#define ID_DEBUG_STEPOUT 40077
#define ID_VIEW_RESET_VIEW 40085
#define ID_DEBUG_ACTIVATEC 40086
#define ID_EDIT_GOTO 40087
#define ID_EDIT_GOTO_FUNC 40089
#define ID_EDIT_GOTOFUNC 40091
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 129
#define _APS_NEXT_COMMAND_VALUE 40092
#define _APS_NEXT_CONTROL_VALUE 1003
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
| 37.804348 | 47 | 0.587694 |
e600a97b9afc776e8b0201260b017ab2d6ef0da2 | 3,110 | h | C | NFServer/NFWorldChatPlugin/NFCWorldChatGroupModule.h | y11en/NoahGameFrame | a9f174712cbbde5f74669aaeebd7527d0dfffd76 | [
"Apache-2.0"
] | null | null | null | NFServer/NFWorldChatPlugin/NFCWorldChatGroupModule.h | y11en/NoahGameFrame | a9f174712cbbde5f74669aaeebd7527d0dfffd76 | [
"Apache-2.0"
] | null | null | null | NFServer/NFWorldChatPlugin/NFCWorldChatGroupModule.h | y11en/NoahGameFrame | a9f174712cbbde5f74669aaeebd7527d0dfffd76 | [
"Apache-2.0"
] | null | null | null | // -------------------------------------------------------------------------
// @FileName : NFCWorldChatGroupModule.h
// @Author : LvSheng.Huang
// @Date : 2015-05-24 08:51
// @Module : NFCWorldChatGroupModule
//
// -------------------------------------------------------------------------
#ifndef NFC_WORLD_CHAT_GROUP_MODULE_H
#define NFC_WORLD_CHAT_GROUP_MODULE_H
#include "NFComm/NFCore/NFMap.h"
#include "NFComm/NFPluginModule/NFIKernelModule.h"
#include "NFComm/NFPluginModule/NFIWorldChatGroupModule.h"
#include "NFComm/NFPluginModule/NFIUUIDModule.h"
#include "NFComm/NFPluginModule/NFIClusterModule.h"
#include "NFComm/NFPluginModule/NFIDataProcessModule.h"
#include "NFComm/NFPluginModule/NFIWorldNet_ServerModule.h"
#include "NFComm/NFPluginModule/NFILogModule.h"
class NFCWorldChatGroupModule
: public NFIWorldChatGroupModule
{
public:
NFCWorldChatGroupModule(NFIPluginManager* p)
{
pPluginManager = p;
mstrGroupTalble = "ChatGroup";
mContainerID = 2;
}
virtual bool Init();
virtual bool Shut();
virtual bool Execute();
virtual bool AfterInit();
public:
virtual bool JoinGroup(const NFGUID& self, const NFGUID& xGroupID);
virtual const NFGUID CreateGroup(const NFGUID& self);
virtual bool QuitGroup(const NFGUID& self, const NFGUID& xGroupID);
virtual bool DeleteGroup(const NFGUID& self, const NFGUID& xGroupID);
virtual NF_SHARE_PTR<NFIObject> GetGroup(const NFGUID& self);
virtual bool GetOnlineMember(const NFGUID& self, const NFGUID& xGroupID, NFCDataList& varMemberList, NFCDataList& varGameList);
virtual bool Online(const NFGUID& self, const NFGUID& xGroupID, const int& nGameID);
virtual bool Offeline(const NFGUID& self, const NFGUID& xGroupID);
protected:
void OnReqCreateChatGroupProcess(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen);
void OnReqJoineChatGroupProcess(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen);
void OnReqLeaveChatGroupProcess(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen);
void OnReqSubscriptionChatGroupProcess(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen);
void OnReqCancelSubscriptionChatGroupProcess(const int nSockIndex, const int nMsgID, const char* msg, const uint32_t nLen);
protected:
void CheckLoadGuild(const NFGUID& self, const NFGUID& xGuild);
int OnGuildClassEvent(const NFGUID& self, const std::string& strClassName, const CLASS_OBJECT_EVENT eClassEvent, const NFIDataList& var);
int OnSaveGroupheartEvent(const NFGUID& self , const std::string& strHeartName, const float fTime, const int nCount);
protected:
NFIKernelModule* m_pKernelModule;
NFIUUIDModule* m_pUUIDModule;
NFIClusterModule* m_pClusterSQLModule;
NFIDataProcessModule* m_pDataProcessModule;
NFIWorldNet_ServerModule* m_pWorldNet_ServerModule;
NFILogModule* m_pLogModule;
private:
std::string mstrGroupTalble;
int mContainerID;
};
#endif | 42.60274 | 141 | 0.719293 |
26e2896eb7be12eed1dc8525444a444506bb747f | 1,978 | h | C | src/headers/memory.h | oluigipo/untitled | 6972d1797a80a10e8e22df405900a491749042d8 | [
"MIT"
] | null | null | null | src/headers/memory.h | oluigipo/untitled | 6972d1797a80a10e8e22df405900a491749042d8 | [
"MIT"
] | null | null | null | src/headers/memory.h | oluigipo/untitled | 6972d1797a80a10e8e22df405900a491749042d8 | [
"MIT"
] | null | null | null | #pragma once
#include "types.h"
// NOTE(luigi): if any memory allocation with those functions fail, a message
// box will popup to the user telling what occured, and then exit
// the application.
void* mem_alloc(usize size);
void* mem_alloc_zero(usize count, usize size);
void* mem_realloc(void* p, usize size);
void* mem_reallod_zero(void* p, usize count, usize size);
void mem_free(void* p);
//~ Arena Allocator
typedef struct Arena Arena;
struct Arena {
usize head;
usize size;
void* buffer;
};
func void arena_init(Arena* restrict arena, usize size);
func void arena_deinit(Arena* restrict arena);
func void* arena_alloc(Arena* restrict arena, usize size);
func void* arena_alloc_zero(Arena* restrict arena, usize size);
func void arena_clear(Arena* restrict arena);
//~ Stack Allocator
typedef struct Stack Stack;
struct Stack {
usize size;
struct StackHeader* header;
void* buffer;
};
struct StackHeader {
struct StackHeader* previous;
usize size;
}
#if X86
__attribute__((aligned(16)))
#endif
;
func void stack_init(Stack* stack, usize size);
func void stack_deinit(Stack* stack);
func void* stack_push(Stack* stack, usize size);
func void* stack_push_zero(Stack* stack, usize size);
#define stack_alloc stack_push
#define stack_alloc_zero stack_push_zero
func void stack_free(Stack* stack, void* ptr);
func void stack_pop(Stack* stack);
func void stack_clear(Stack* stack);
//~ Pool Allocator
typedef struct MemoryPool MemoryPool;
struct MemoryPool {
usize count;
usize size;
void* buffer;
struct MemoryPoolHeader* next;
};
struct MemoryPoolHeader {
struct MemoryPoolHeader* next;
}
#if X86
__attribute__((aligned(16)))
#endif
;
func void pool_init(MemoryPool* pool, usize chunkSize, usize chunkCount);
func void pool_deinit(MemoryPool* pool);
func void* pool_alloc(MemoryPool* pool);
func void* pool_alloc_zero(MemoryPool* pool);
func void pool_free(MemoryPool* pool, void* ptr);
func void pool_clear(MemoryPool* pool);
| 25.358974 | 78 | 0.754297 |
505c5aee3240635c38c33e283ef1ad475b244ffc | 2,894 | h | C | bsp.h | jeyoung/arm-experiments | 127e9f16a291310d49b358176e2986f4caecb409 | [
"BSD-2-Clause"
] | null | null | null | bsp.h | jeyoung/arm-experiments | 127e9f16a291310d49b358176e2986f4caecb409 | [
"BSD-2-Clause"
] | null | null | null | bsp.h | jeyoung/arm-experiments | 127e9f16a291310d49b358176e2986f4caecb409 | [
"BSD-2-Clause"
] | null | null | null | #define RCC 0x40023800UL
#define RCC_CFGR *((volatile unsigned long *)((RCC)+0x08UL))
#define RCC_AHB1ENR *((volatile unsigned long *)((RCC)+0x30UL))
#define RCC_APB1ENR *((volatile unsigned long *)((RCC)+0x40UL))
#define RCC_APB2ENR *((volatile unsigned long *)((RCC)+0x44UL))
#define GPIOA 0x40020000UL
#define GPIOA_MODER *((volatile unsigned long *)((GPIOA)+0x00UL))
#define GPIOA_OTYPER *((volatile unsigned long *)((GPIOA)+0x04UL))
#define GPIOA_ODR *((volatile unsigned long *)((GPIOA)+0x14UL))
#define STK 0xE000E010UL
#define STK_CTRL *((volatile unsigned long *)((STK)+0x00UL))
#define STK_LOAD *((volatile unsigned long *)((STK)+0x04UL))
#define STK_VAL *((volatile unsigned long *)((STK)+0x08UL))
#define STK_CALIB *((volatile unsigned long *)((STK)+0x0CUL))
#define NVIC_ISE 0xE000E100UL
#define NVIC_ISER0 *((volatile unsigned long *)((NVIC_ISE)+0x00UL))
#define NVIC_ICE 0xE000E180UL
#define NVIC_ICER0 *((volatile unsigned long *)((NVIC_ICE)+0x00UL))
#define NVIC_ISP 0xE000E200UL
#define NVIC_ISPR0 *((volatile unsigned long *)((NVIC_ISP)+0x00UL))
#define NVIC_ICP 0xE000E280UL
#define NVIC_ICPR0 *((volatile unsigned long *)((NVIC_ICP)+0x00UL))
#define NVIC_IAB 0xE000E300UL
#define NVIC_IABR0 *((volatile unsigned long *)((NVIC_IAB)+0x00UL))
#define TIM1 0x40010000UL
#define TIM1_CR1 *((volatile unsigned long *)((TIM1)+0x00UL))
#define TIM1_DIER *((volatile unsigned long *)((TIM1)+0x0CUL))
#define TIM1_SR *((volatile unsigned long *)((TIM1)+0x10UL))
#define TIM1_EGR *((volatile unsigned long *)((TIM1)+0x14UL))
#define TIM1_CNT *((volatile unsigned long *)((TIM1)+0x24UL))
#define TIM1_PSC *((volatile unsigned long *)((TIM1)+0x28UL))
#define TIM1_ARR *((volatile unsigned long *)((TIM1)+0x2CUL))
#define TIM1_RCR *((volatile unsigned long *)((TIM1)+0x30UL))
#define TIM2 0x40000000UL
#define TIM2_CR1 *((volatile unsigned long *)((TIM2)+0x00UL))
#define TIM2_DIER *((volatile unsigned long *)((TIM2)+0x0CUL))
#define TIM2_SR *((volatile unsigned long *)((TIM2)+0x10UL))
#define TIM2_EGR *((volatile unsigned long *)((TIM2)+0x14UL))
#define TIM2_CNT *((volatile unsigned long *)((TIM2)+0x24UL))
#define TIM2_PSC *((volatile unsigned long *)((TIM2)+0x28UL))
#define TIM2_ARR *((volatile unsigned long *)((TIM2)+0x2CUL))
void init(void);
void nmi_handler(void);
void hardfault_handler(void);
void memfault_handler(void);
void busfault_handler(void);
void usagefault_handler(void);
void svc_handler(void);
void debug_handler(void);
void pendsv_handler(void);
void systick_handler(void);
void tim1update_handler(void);
void tim1trigger_handler(void);
void tim2global_handler(void);
| 43.848485 | 72 | 0.670007 |
5091bdd455c3cbf0b30b4a558e8e97ada160d8e2 | 319 | h | C | include/core/freebsd/kqueue/Handle.type.h | likebot0/core.h | a9afaa09966c027098160b807666b78af9123644 | [
"Unlicense"
] | null | null | null | include/core/freebsd/kqueue/Handle.type.h | likebot0/core.h | a9afaa09966c027098160b807666b78af9123644 | [
"Unlicense"
] | null | null | null | include/core/freebsd/kqueue/Handle.type.h | likebot0/core.h | a9afaa09966c027098160b807666b78af9123644 | [
"Unlicense"
] | null | null | null | #ifndef _core_freebsd_kqueue_Handle
#define _core_freebsd_kqueue_Handle ::core_freebsd_kqueue_Handle
struct core_freebsd_kqueue_Handle;
#include <core/Product.type.h>
struct core_freebsd_kqueue_Handle : _core_Product<int> {
using Base_object = _core_Product<int>;
using Base_object::Base_object;
};
#endif
| 21.266667 | 64 | 0.811912 |
76bfc52290cfa570a53bccc48a8d28bbfdce1179 | 1,734 | h | C | src/asn/rrc/ASN_RRC_BandCombination-v1560.h | aligungr/ue-ran-sim | 564f9d228723f03adfa2b02df2ea019bdf305085 | [
"MIT"
] | 16 | 2020-04-16T02:07:37.000Z | 2020-07-23T10:48:27.000Z | src/asn/rrc/ASN_RRC_BandCombination-v1560.h | aligungr/ue-ran-sim | 564f9d228723f03adfa2b02df2ea019bdf305085 | [
"MIT"
] | 8 | 2020-07-13T17:11:35.000Z | 2020-08-03T16:46:31.000Z | src/asn/rrc/ASN_RRC_BandCombination-v1560.h | aligungr/ue-ran-sim | 564f9d228723f03adfa2b02df2ea019bdf305085 | [
"MIT"
] | 9 | 2020-03-04T15:05:08.000Z | 2020-07-30T06:18:18.000Z | /*
* Generated by asn1c-0.9.29 (http://lionet.info/asn1c)
* From ASN.1 module "NR-RRC-Definitions"
* found in "asn/nr-rrc-15.6.0.asn1"
* `asn1c -fcompound-names -pdu=all -findirect-choice -fno-include-deps -gen-PER -no-gen-OER -no-gen-example -D rrc`
*/
#ifndef _ASN_RRC_BandCombination_v1560_H_
#define _ASN_RRC_BandCombination_v1560_H_
#include <asn_application.h>
/* Including external dependencies */
#include <NativeEnumerated.h>
#include <constr_SEQUENCE.h>
#ifdef __cplusplus
extern "C" {
#endif
/* Dependencies */
typedef enum ASN_RRC_BandCombination_v1560__ne_DC_BC {
ASN_RRC_BandCombination_v1560__ne_DC_BC_supported = 0
} e_ASN_RRC_BandCombination_v1560__ne_DC_BC;
/* Forward declarations */
struct ASN_RRC_CA_ParametersNRDC;
struct ASN_RRC_CA_ParametersEUTRA_v1560;
struct ASN_RRC_CA_ParametersNR_v1560;
/* ASN_RRC_BandCombination-v1560 */
typedef struct ASN_RRC_BandCombination_v1560 {
long *ne_DC_BC; /* OPTIONAL */
struct ASN_RRC_CA_ParametersNRDC *ca_ParametersNRDC; /* OPTIONAL */
struct ASN_RRC_CA_ParametersEUTRA_v1560 *ca_ParametersEUTRA_v1560; /* OPTIONAL */
struct ASN_RRC_CA_ParametersNR_v1560 *ca_ParametersNR_v1560; /* OPTIONAL */
/* Context for parsing across buffer boundaries */
asn_struct_ctx_t _asn_ctx;
} ASN_RRC_BandCombination_v1560_t;
/* Implementation */
/* extern asn_TYPE_descriptor_t asn_DEF_ASN_RRC_ne_DC_BC_2; // (Use -fall-defs-global to expose) */
extern asn_TYPE_descriptor_t asn_DEF_ASN_RRC_BandCombination_v1560;
extern asn_SEQUENCE_specifics_t asn_SPC_ASN_RRC_BandCombination_v1560_specs_1;
extern asn_TYPE_member_t asn_MBR_ASN_RRC_BandCombination_v1560_1[4];
#ifdef __cplusplus
}
#endif
#endif /* _ASN_RRC_BandCombination_v1560_H_ */
#include <asn_internal.h>
| 31.527273 | 117 | 0.809689 |
f79178fba41832a9bac028a506a6a6753c98a3ca | 273 | c | C | InfixToPostfix1.c | MBadriNarayanan/DataStructuresLab | 5c53442b16677282fb0cf18932644c9661032084 | [
"MIT"
] | null | null | null | InfixToPostfix1.c | MBadriNarayanan/DataStructuresLab | 5c53442b16677282fb0cf18932644c9661032084 | [
"MIT"
] | 1 | 2020-07-09T20:31:45.000Z | 2020-07-09T20:31:45.000Z | InfixToPostfix1.c | MBadriNarayanan/DataStructures | 5c53442b16677282fb0cf18932644c9661032084 | [
"MIT"
] | null | null | null | #include"InfixToPostfix.h"
int main()
{
char exp[25];
printf("\n\n Infix To Postfix \n\n");
printf(" Enter A Expression : ");
scanf("%s",exp);
printf("\n\n The Postfix Expression Is \n\n");
infixToPostfix(exp);
printf("\n\n\n");
return 0;
}
| 21 | 50 | 0.578755 |
a1797bb3ecd67ac57755e73c6865be762eec377e | 1,373 | c | C | ch9-1.c | Xi-Plus/KUAS-Computer-Programming-Homework | cc1329d93a4b8054cf3cfd5bf8b4dacacbe5eaf9 | [
"MIT"
] | null | null | null | ch9-1.c | Xi-Plus/KUAS-Computer-Programming-Homework | cc1329d93a4b8054cf3cfd5bf8b4dacacbe5eaf9 | [
"MIT"
] | null | null | null | ch9-1.c | Xi-Plus/KUAS-Computer-Programming-Homework | cc1329d93a4b8054cf3cfd5bf8b4dacacbe5eaf9 | [
"MIT"
] | null | null | null | #include<stdio.h>
char inputmode(){
char mode;
while(1){
printf("a. add s.subtract\n");
printf("m. mulitply d.divide\n");
printf("q. quit\n");
printf("Enter the operation of your choices:");
scanf("%c", &mode);
fflush(stdin);
switch(mode){
case 'a':case 'A':
case 's':case 'S':
case 'm':case 'M':
case 'd':case 'D':
case 'q':case 'Q':
return mode;
}
printf("Error!\n");
}
}
void ans(char mode, double a, double b){
switch(mode){
case 'a':case 'A':
printf("%lf + %lf = %lf\n", a, b, a+b);
break;
case 's':case 'S':
printf("%lf - %lf = %lf\n", a, b, a-b);
break;
case 'm':case 'M':
printf("%lf * %lf = %lf\n", a, b, a*b);
break;
case 'd':case 'D':
printf("%lf / %lf = %lf\n", a, b, a/b);
break;
}
}
int main(){
char mode;
char s[100];
while(mode=inputmode()){
if(mode=='q'||mode=='Q')break;
double a,b;
while(1){
printf("Enter first number:");
if(scanf("%lf", &a)==1)
break;
scanf("%s", &s);
printf("Error! %s is not a number.\n", s);
}
while(1){
printf("Enter second number:");
if(scanf("%lf", &b)!=1){
scanf("%s", &s);
printf("Error! %s is not a number.\n", s);
} else if((mode=='d'||mode=='D')&&b==0) {
printf("Error! Second number cannot be 0.\n");
} else {
break;
}
}
ans(mode, a, b);
fflush(stdin);
}
printf("Bye!\n");
}
| 20.191176 | 50 | 0.514931 |
ddad1d4072e73ec1f82eeb58ef211d575169a733 | 80,407 | c | C | sdk-6.5.20/src/soc/dnx/pemladrv/pemladrv_meminfo_init.c | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | sdk-6.5.20/src/soc/dnx/pemladrv/pemladrv_meminfo_init.c | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null | sdk-6.5.20/src/soc/dnx/pemladrv/pemladrv_meminfo_init.c | copslock/broadcom_cpri | 8e2767676e26faae270cf485591902a4c50cf0c5 | [
"Spencer-94"
] | null | null | null |
/*
* This license is set out in https://raw.githubusercontent.com/Broadcom-Network-Switching-Software/OpenBCM/master/Legal/LICENSE file.
*
* Copyright 2007-2020 Broadcom Inc. All rights reserved.
*/
#include "pemladrv_physical_access.h"
#include "pemladrv_logical_access.h"
#include "pemladrv_meminfo_init.h"
#include "pemladrv_meminfo_access.h"
#include "pemladrv_cfg_api_defines.h"
#ifndef BCM_DNX_SUPPORT
#include "pemladrv_debug/pemladrv_debug.h"
#define TRUE true
#define FALSE false
#endif
#ifdef BCM_DNX_SUPPORT
#include "soc/register.h"
#include "soc/mem.h"
#include "soc/drv.h"
#ifdef BCM_SHARED_LIB_SDK
#include <src/sal/appl/pre_compiled_bridge_router_pemla_init_db.h>
#else
#include <soc/dnx/pemladrv/auto_generated/dbx_pre_compiled_ucode.h>
#endif
#endif
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <limits.h>
#include <stdbool.h>
#ifdef _MSC_VER
#if (_MSC_VER >= 1400)
#pragma warning(push)
#pragma warning(disable: 4996)
#endif
#endif
extern ApiInfo api_info[MAX_NOF_UNITS];
unsigned int* hexstr2uints(char *str, unsigned int *len)
{
char *ptr, *start_value;
int array_size = 0;
unsigned int* arr;
unsigned int* curr_entry_val;
int nibble_ndx;
unsigned int curr_nibble;
*len = strtoul(str, &ptr, 10);
ptr = ptr + 2;
start_value = ptr;
array_size = ((*len % 32) == 0) ? *len / 32 : *len / 32 + 1;
arr = (unsigned int*)sal_alloc(array_size * 4, "");
memset(arr, 0, array_size * 4);
for (nibble_ndx = 0, ptr = str + strlen(str) - 1; ptr >= start_value; --ptr, ++nibble_ndx)
{
curr_entry_val = arr + (nibble_ndx / 8);
curr_nibble = (*ptr <= 'F' && *ptr >= 'A') ? *ptr - 'A' + 10
: (*ptr <= 'f' && *ptr >= 'a') ? *ptr -'a' + 10
: *ptr - '0';
*curr_entry_val |= (curr_nibble<<((nibble_ndx % 8) *4));
}
return arr;
}
unsigned int hexstr2addr(char *str, unsigned int *block_id)
{
unsigned int addr;
unsigned int len;
unsigned int* addr_arr;
addr_arr = hexstr2uints(str, &len);
addr = addr_arr[0];
*block_id = addr_arr[1];
sal_free(addr_arr);
return addr;
}
int parse_meminfo_definition_file(int unit, int restore_after_reset, uint32 use_file, const char *rel_file_path, const char *file_name)
{
int ret_val = 0;
int read_lines = 1;
#ifndef BCM_SHARED_LIB_SDK
FILE *fp = NULL;
char *line = NULL;
int line_no = 1;
char **lines = NULL;
#else
const char *line = NULL;
int line_no = 0;
#endif
int in_comment = 0;
#ifndef BCM_SHARED_LIB_SDK
if(use_file)
{
if ((fp = fopen(file_name, "r")) == NULL)
{
return UINT_MAX;
}
line = (char*)sal_alloc(sizeof(*line)*512, "");
}
else
{
lines = pre_compiled_pemla_db_ucode_get(unit, rel_file_path);
if (lines == NULL) {read_lines = -1;}
}
#endif
init_api_info(unit);
while(read_lines >= 0) {
#ifndef BCM_SHARED_LIB_SDK
if(use_file)
{
memset(line, 0, sizeof(*line)*512);
if(fgets(line, sizeof(*line)*512, fp) == NULL) {read_lines = -1; continue;}
}
else
{
line = lines[line_no];
if(line == NULL) {read_lines = -1; continue;}
}
#else
if((line = pre_compiled_bridge_router_pemla_db_string[line_no]) != NULL) {read_lines = -1; continue;}
#endif
if (strlen(line) == 0) {line_no = line_no + 1; continue;}
if (strstr(line, END_COMMENT) != 0) { in_comment = 0; ++line_no; continue;}
if (strstr(line, START_COMMENT) != 0) { in_comment = 1; ++line_no; continue;}
if (in_comment) { ++line_no; continue;}
if ((strncmp(line, KEYWORD_UCODE_MEM_WRITE_INFO, KEYWORD_UCODE_MEM_WRITE_INFO_SIZE) == 0) && !restore_after_reset ) { dnx_pemladrv_mem_line_write(unit, line); ++line_no; continue; }
if ((strncmp(line, KEYWORD_UCODE_REG_WRITE_INFO, KEYWORD_UCODE_REG_WRITE_INFO_SIZE) == 0) && !restore_after_reset ) { dnx_pemladrv_reg_line_write(unit, line); ++line_no; continue; }
if (strncmp(line, KEYWORD_DB, KEYWORD_DB_SIZE) == 0) { dnx_pemladrv_db_info_insert(unit, line) ; ++line_no; continue; }
if (strncmp(line, KEYWORD_KEY, KEYWORD_KEY_SIZE) == 0) { dnx_pemladrv_db_field_info_insert(unit, line) ; ++line_no; continue; }
if (strncmp(line, KEYWORD_RESULT, KEYWORD_RESULT_SIZE) == 0) { dnx_pemladrv_db_field_info_insert(unit, line) ; ++line_no; continue; }
if (strncmp(line, KEYWORD_DB_DIRECT_INFO, KEYWORD_DB_DIRECT_INFO_SIZE) == 0) { dnx_pemladrv_direct_result_chunk_insert(unit, line) ; ++line_no; continue; }
if (strncmp(line, KEYWORD_DB_TCAM_KEY_INFO, KEYWORD_DB_TCAM_KEY_INFO_SIZE) == 0) { dnx_pemladrv_tcam_key_chunk_insert(unit, line); ++line_no; continue; }
if (strncmp(line, KEYWORD_DB_TCAM_RESULT_INFO, KEYWORD_DB_TCAM_RESULT_INFO_SIZE) == 0) { dnx_pemladrv_tcam_result_chunk_insert(unit, line); ++line_no; continue; }
if (strncmp(line, KEYWORD_DB_EXACT_MATCH_KEY_INFO, KEYWORD_DB_EXACT_MATCH_KEY_INFO_SIZE) == 0) { dnx_pemladrv_em_key_chunk_insert(unit, line); ++line_no; continue; }
if (strncmp(line, KEYWORD_DB_EXACT_MATCH_RESULT_INFO, KEYWORD_DB_EXACT_MATCH_RESULT_INFO_SIZE) == 0) { dnx_pemladrv_em_result_chunk_insert(unit, line); ++line_no; continue; }
if (strncmp(line, KEYWORD_DB_LONGEST_PERFIX_MATCH_KEY_INFO, KEYWORD_DB_LONGEST_PERFIX_MATCH_KEY_INFO_SIZE) == 0) { dnx_pemladrv_lpm_key_chunk_insert(unit, line); ++line_no; continue; }
if (strncmp(line, KEYWORD_DB_LONGEST_PERFIX_MATCH_RESULT_INFO, KEYWORD_DB_LONGEST_PERFIX_MATCH_RESULT_INFO_SIZE) == 0) { dnx_pemladrv_lpm_result_chunk_insert(unit, line); ++line_no; continue; }
if (strncmp(line, KEYWORD_VIRTUAL_REGISTER_MAPPING, KEYWORD_REGISTER_INFO_SIZE) == 0) { dnx_pemladrv_register_insert(unit, line); ++line_no; continue; }
if (strncmp(line, KEYWORD_REG_AND_DBS_NUM_INFO, KEYWORD_REG_AND_DBS_NUM_INFO_SIZE) == 0) { dnx_pemladrv_dnx_init_all_db_arr_by_size(unit, line) ; ++line_no; continue; }
if (strncmp(line, KEYWORD_DB_SINGLE_CHUNCK_INFO, KEYWORD_DB_SINGLE_CHUNCK_INFO_SIZE) == 0) { dnx_pemladrv_init_logical_db_chunk_mapper(unit, line) ; ++line_no; continue; }
if (strncmp(line, KEYWORD_VIRTUAL_REGISTER_NOF_FIELDS, KEYWORD_VIRTUAL_REGISTER_NOF_FIELDS_SIZE) == 0) { dnx_pemladrv_init_reg_field_info(unit, line) ; ++line_no; continue; }
if (strncmp(line, KEYWORD_VIRTUAL_REGISTER_FIELD_NOF_MAPPINGS, KEYWORD_VIRTUAL_REGISTER_FIELD_NOF_MAPPINGS_SIZE) == 0) { dnx_pemladrv_init_reg_field_mapper(unit, line) ; ++line_no; continue; }
#ifndef BCM_DNX_SUPPORT
if (strncmp(line, KEYWORD_DEBUG_LOAD_DBUS, KEYWORD_DEBUG_LOAD_DBUS_SIZE) == 0) { debug_load_dbus_info_insert(line) ; ++line_no; continue; }
if (strncmp(line, KEYWORD_DEBUG_UPDATE_DBUS, KEYWORD_DEBUG_UPDATE_DBUS_SIZE) == 0) { debug_update_dbus_info_insert(line) ; ++line_no; continue; }
if (strncmp(line, KEYWORD_DEBUG_FIFO_DESC, KEYWORD_DEBUG_FIFO_DESC_SIZE) == 0) { debug_fifo_field_desc_info_insert(line) ; ++line_no; continue; }
if (strncmp(line, KEYWORD_DEBUG_FIFOCONFIG_INFO, KEYWORD_DEBUG_FIFOCONFIG_INFO_SIZE) == 0) { debug_fifoconfig_reg_info_insert(line) ; ++line_no; continue; }
if (strncmp(line, KEYWORD_DEBUG_LOAD_DBUS_NAME, KEYWORD_DEBUG_LOAD_DBUS_NAME_SIZE) == 0) { debug_load_dbus_name_info_insert(line) ; ++line_no; continue; }
if (strncmp(line, KEYWORD_DEBUG_UPDATE_DBUS_NAME, KEYWORD_DEBUG_UPDATE_DBUS_NAME_SIZE) == 0) { debug_update_dbus_name_info_insert(line) ; ++line_no; continue; }
if (strncmp(line, KEYWORD_DEBUG_CBUS_NAME, KEYWORD_DEBUG_CBUS_NAME_SIZE) == 0) { debug_cbus_dbus_name_info_insert(line) ; ++line_no; continue; }
#endif
if (strncmp(line, KEYWORD_PEM_VER, KEYWORD_PEM_VER_SIZE) == 0) { init_pem_version_control(unit, line) ; ++line_no; continue; }
if (strncmp(line, KEYWORD_PEM_APPLET_REG, KEYWORD_PEM_APPLET_REG_SIZE) == 0) { init_pem_applet_reg(unit, line) ; ++line_no; continue; }
if (strncmp(line, KEYWORD_PEM_APPLET_MEM, KEYWORD_PEM_APPLET_MEM_SIZE) == 0) { init_pem_applet_mem(unit, line) ; ++line_no; continue; }
if (strncmp(line, KEYWORD_GENERAL_INFO_FOR_APPLET, KEYWORD_GENERAL_INFO_FOR_APPLET_SIZE) == 0) { init_meminfo_array_for_applets(unit, line) ; ++line_no; continue; }
if (strncmp(line, KEYWORD_MEMINFO_FOR_APPLET, KEYWORD_MEMINFO_FOR_APPLET_SIZE) == 0) { insert_meminfo_to_array_for_applets(unit, line) ; ++line_no; continue; }
if (strncmp(line, KEYWORD_UCODE_DUMP_SINGLE_VIRTUAL_WIRE_MAPPING, KEYWORD_UCODE_DUMP_SINGLE_VIRTUAL_WIRE_MAPPING_SIZE) == 0) { dnx_pemladrv_vw_mapping_insert(unit, line) ; ++line_no; continue; }
if (strncmp(line, KEYWORD_UCODE_VIRTUAL_WIRE_MAPPING_INFO, KEYWORD_UCODE_VIRTUAL_WIRE_MAPPING_INFO_SIZE) == 0) { dnx_pemladrv_init_vw_info(unit, line) ; ++line_no; continue; }
if (strncmp(line, KEYWORD_UCODE_DUMP_NOF_VIRTUAL_WIRES, KEYWORD_UCODE_DUMP_NOF_VIRTUAL_WIRES_SIZE) == 0) { dnx_pemladrv_init_vw_arr_by_size(unit, line) ; ++line_no; continue; }
++line_no;
}
#ifndef BCM_SHARED_LIB_SDK
if(use_file)
{
fclose(fp);
sal_free(line);
}
#endif
if (restore_after_reset)
dnx_pemladrv_read_physical_and_update_cache(unit);
return ret_val;
}
void init_api_info(const int unit)
{
if((api_info[unit].db_direct_container.nof_direct_dbs) ||
(api_info[unit].db_em_container.nof_em_dbs) ||
(api_info[unit].db_lpm_container.nof_lpm_dbs) ||
(api_info[unit].db_tcam_container.nof_tcam_dbs) ||
(api_info[unit].vw_container.nof_virtual_wires) ||
(api_info[unit].reg_container.nof_registers) ||
(api_info[unit].version_info.iterator))
free_api_info(unit);
}
void free_api_info(const int unit)
{
free_db_direct_container(unit);
free_db_tcam_container(unit);
free_db_lpm_container(unit);
free_db_em_container(unit);
free_vw_container(unit);
free_reg_container(unit);
free_version_info(unit);
}
void free_db_direct_container(const int unit) {
unsigned int i;
for (i = 0; i < api_info[unit].db_direct_container.nof_direct_dbs; ++i)
{
if (NULL == api_info[unit].db_direct_container.db_direct_info_arr[i].result_chunk_mapper_matrix_arr){
continue;
}
free_logical_direct_info(&api_info[unit].db_direct_container.db_direct_info_arr[i]);
}
sal_free(api_info[unit].db_direct_container.db_direct_info_arr);
api_info[unit].db_direct_container.db_direct_info_arr = NULL;
api_info[unit].db_direct_container.nof_direct_dbs = 0;
}
void free_db_tcam_container(const int unit)
{
unsigned int i;
for (i = 0; i < api_info[unit].db_tcam_container.nof_tcam_dbs; ++i)
{
if (NULL == api_info[unit].db_tcam_container.db_tcam_info_arr[i].result_chunk_mapper_matrix_arr){
sal_free(api_info[unit].db_tcam_container.db_tcam_info_arr[i].key_field_bit_range_arr);
sal_free(api_info[unit].db_tcam_container.db_tcam_info_arr[i].result_field_bit_range_arr);
api_info[unit].db_tcam_container.db_tcam_info_arr[i].key_field_bit_range_arr = NULL;
api_info[unit].db_tcam_container.db_tcam_info_arr[i].result_field_bit_range_arr = NULL;
continue;
}
free_logical_tcam_info(&api_info[unit].db_tcam_container.db_tcam_info_arr[i]);
}
sal_free(api_info[unit].db_tcam_container.db_tcam_info_arr);
api_info[unit].db_tcam_container.db_tcam_info_arr = NULL;
api_info[unit].db_tcam_container.nof_tcam_dbs = 0;
}
void free_db_lpm_container(const int unit)
{
unsigned int i;
for (i = 0; i < api_info[unit].db_lpm_container.nof_lpm_dbs; ++i)
{
if (NULL == api_info[unit].db_lpm_container.db_lpm_info_arr[i].logical_lpm_info.result_chunk_mapper_matrix_arr){
sal_free(api_info[unit].db_lpm_container.db_lpm_info_arr[i].logical_lpm_info.key_field_bit_range_arr);
sal_free(api_info[unit].db_lpm_container.db_lpm_info_arr[i].logical_lpm_info.result_field_bit_range_arr);
api_info[unit].db_lpm_container.db_lpm_info_arr[i].logical_lpm_info.key_field_bit_range_arr = NULL;
api_info[unit].db_lpm_container.db_lpm_info_arr[i].logical_lpm_info.result_field_bit_range_arr = NULL;
continue;
}
free_logical_lpm_info(&api_info[unit].db_lpm_container.db_lpm_info_arr[i]);
}
sal_free(api_info[unit].db_lpm_container.db_lpm_info_arr);
api_info[unit].db_lpm_container.db_lpm_info_arr = NULL;
api_info[unit].db_lpm_container.nof_lpm_dbs = 0;
}
void free_db_em_container(const int unit)
{
unsigned int i;
for (i = 0; i < api_info[unit].db_em_container.nof_em_dbs; ++i)
{
if (NULL == api_info[unit].db_em_container.db_em_info_arr[i].logical_em_info.result_chunk_mapper_matrix_arr){
sal_free(api_info[unit].db_em_container.db_em_info_arr[i].logical_em_info.key_field_bit_range_arr);
sal_free(api_info[unit].db_em_container.db_em_info_arr[i].logical_em_info.result_field_bit_range_arr);
api_info[unit].db_em_container.db_em_info_arr[i].logical_em_info.key_field_bit_range_arr = NULL;
api_info[unit].db_em_container.db_em_info_arr[i].logical_em_info.result_field_bit_range_arr = NULL;
continue;
}
free_logical_em_info(&api_info[unit].db_em_container.db_em_info_arr[i]);
}
sal_free(api_info[unit].db_em_container.db_em_info_arr);
api_info[unit].db_em_container.db_em_info_arr = NULL;
api_info[unit].db_em_container.nof_em_dbs = 0;
}
void free_vw_container(const int unit)
{
unsigned int i;
for (i = 0; i < api_info[unit].vw_container.nof_virtual_wires; ++i)
{
if (NULL == api_info[unit].vw_container.vw_info_arr[i].vw_mappings_arr){
continue;
}
free_vw_mapping_info(&api_info[unit].vw_container.vw_info_arr[i]);
}
sal_free(api_info[unit].vw_container.vw_info_arr);
api_info[unit].vw_container.vw_info_arr = NULL;
api_info[unit].vw_container.nof_virtual_wires = 0;
}
void free_reg_container(const int unit)
{
unsigned int i;
for (i = 0; i < api_info[unit].reg_container.nof_registers; ++i)
{
if (!api_info[unit].reg_container.reg_info_arr[i].is_mapped){
continue;
}
free_logical_reg_info(&api_info[unit].reg_container.reg_info_arr[i]);
}
sal_free(api_info[unit].reg_container.reg_info_arr);
api_info[unit].reg_container.reg_info_arr = NULL;
api_info[unit].reg_container.nof_registers = 0;
}
void free_version_info(const int unit){
memset(api_info[unit].version_info.chuck_lib_date_str, 0, MAX_NAME_LENGTH);
memset(api_info[unit].version_info.chuck_lib_signature_str, 0, MAX_NAME_LENGTH);
memset(api_info[unit].version_info.device_lib_date_str, 0, MAX_NAME_LENGTH);
memset(api_info[unit].version_info.device_lib_signature_str, 0, MAX_NAME_LENGTH);
memset(api_info[unit].version_info.device_str, 0, MAX_NAME_LENGTH);
memset(api_info[unit].version_info.version_info_str, 0, 5000);
memset(api_info[unit].version_info.version_str, 0, MAX_NAME_LENGTH);
api_info[unit].version_info.iterator = 0;
}
void free_logical_direct_info(LogicalDirectInfo* logical_direct_info)
{
free_chunk_mapper_matrix(logical_direct_info->nof_chunk_matrices,
logical_direct_info->result_chunk_mapper_matrix_arr);
sal_free(logical_direct_info->field_bit_range_arr);
logical_direct_info->field_bit_range_arr = NULL;
}
void free_logical_tcam_info(LogicalTcamInfo* logical_tcam_info)
{
free_chunk_mapper_matrix(logical_tcam_info->nof_chunk_matrices, logical_tcam_info->key_chunk_mapper_matrix_arr);
free_chunk_mapper_matrix(logical_tcam_info->nof_chunk_matrices, logical_tcam_info->result_chunk_mapper_matrix_arr);
sal_free(logical_tcam_info->key_field_bit_range_arr);
sal_free(logical_tcam_info->result_field_bit_range_arr);
logical_tcam_info->key_field_bit_range_arr = NULL;
logical_tcam_info->result_field_bit_range_arr = NULL;
}
void free_logical_lpm_info(LogicalLpmInfo* logical_lpm_info)
{
free_logical_tcam_info(&logical_lpm_info->logical_lpm_info);
free_lpm_cache(&logical_lpm_info->lpm_cache);
}
void free_logical_em_info(LogicalEmInfo* logical_em_info)
{
free_logical_tcam_info(&logical_em_info->logical_em_info);
free_em_cache(&logical_em_info->em_cache);
}
void free_vw_mapping_info(VirtualWireInfo* vw_info_arr){
sal_free(vw_info_arr->vw_mappings_arr);
vw_info_arr->vw_mappings_arr = NULL;
}
void free_logical_reg_info(LogicalRegInfo* logical_reg_info)
{
for (unsigned int i = 0; i < logical_reg_info->nof_fields; ++i){
free_reg_field_info(&logical_reg_info->reg_field_info_arr[i]);
}
sal_free(logical_reg_info->reg_field_info_arr);
logical_reg_info->reg_field_info_arr = NULL;
sal_free(logical_reg_info->reg_field_bit_range_arr);
logical_reg_info->reg_field_bit_range_arr = NULL;
}
void free_reg_field_info(LogicalRegFieldInfo* reg_field_info)
{
sal_free(reg_field_info->reg_field_mapping_arr);
reg_field_info->reg_field_mapping_arr = NULL;
}
void free_chunk_mapper_matrix(const int nof_implamentations,
LogicalDbChunkMapperMatrix* chunk_mapper_matrix)
{
int implamentation_index;
unsigned int row_index, col_index;
for (implamentation_index = 0; implamentation_index < nof_implamentations; ++implamentation_index)
{
for (row_index = 0; row_index < chunk_mapper_matrix->nof_rows_in_chunk_matrix; ++row_index)
{
for (col_index = 0; col_index < chunk_mapper_matrix->nof_cols_in_chunk_matrix; ++col_index)
{
sal_free(chunk_mapper_matrix[implamentation_index].db_chunk_mapper[row_index][col_index]);
}
sal_free(chunk_mapper_matrix[implamentation_index].db_chunk_mapper[row_index]);
}
sal_free(chunk_mapper_matrix[implamentation_index].db_chunk_mapper);
}
sal_free(chunk_mapper_matrix);
}
void free_lpm_cache(LpmDbCache* lpm_cache)
{
sal_free(lpm_cache->lpm_key_entry_arr);
sal_free(lpm_cache->lpm_result_entry_arr);
sal_free(lpm_cache->lpm_key_entry_prefix_length_arr);
sal_free(lpm_cache->physical_entry_occupation);
}
void free_em_cache(EmDbCache* em_cache)
{
sal_free(em_cache->em_key_entry_arr);
sal_free(em_cache->em_result_entry_arr);
sal_free(em_cache->physical_entry_occupation);
}
void fast_atoi(char * str, unsigned int strlen, unsigned int nof_chunks, unsigned int* val, bool* is_equal_to_zero)
{
int temp=0;
int i = strlen + 1;
int j = 0;
char* ptr = str + strlen - 1;
int g_six[8] = { 1, 16, 256, 4096, 65536, 1048576, 16777216, 268435456 };
while (i>1) {
if (*ptr >= '0' && *ptr <= '9')
temp = *ptr-- - '0';
else if (*ptr >= 'A' && *ptr <= 'F') {
temp = *ptr-- - 'A' + 0x0a;
}
else if (*ptr >= 'a' && *ptr <= 'f') {
temp = *ptr-- - 'a' + 0x0a;
}
else
assert(false);
if (temp != 0)
*is_equal_to_zero = FALSE;
val[j / NOF_BYTES_IN_WORD] = val[j / NOF_BYTES_IN_WORD] + (g_six[j % NOF_BYTES_IN_WORD] * temp);
i--;
j++;
}
}
void dnx_pemladrv_mem_line_write(int unit, const char* line) {
char pem_mem_address[MEM_ADDR_LENGTH];
char str_value[MAX_MEM_DATA_LENGTH];
char shtut[MAX_SHTUT_LENGTH];
int width_in_bits;
char key_word[MAX_NAME_LENGTH], pem_mem_name[MAX_NAME_LENGTH];
unsigned int phy_mem_idx, block_id;
unsigned int pem_mem_address_val;
unsigned int data_value[MAX_DATA_VALUE_ARRAY] = { 0 };
unsigned int data_nof_chunks;
unsigned int strlen;
bool is_equal_to_zero = TRUE;
phy_mem_t phy_mem;
if (sscanf(line, "%s %s %s %u %d %2s %s", key_word, pem_mem_name, pem_mem_address,
&phy_mem_idx, &width_in_bits, shtut, str_value) != PEM_NOF_MEM_WRITE_TOKEN)
{
printf("Bad ucode line format. Skip and continue with next line.\n");
}
else
{
pem_mem_address_val = hexstr2addr(pem_mem_address, &block_id);
data_nof_chunks = (width_in_bits % NOF_BITS_IN_WORD == 0) ? width_in_bits / NOF_BITS_IN_WORD : width_in_bits / NOF_BITS_IN_WORD + 1;
strlen = (width_in_bits % NOF_BITS_REPRESENTED_BY_CHAR == 0) ? width_in_bits / NOF_BITS_REPRESENTED_BY_CHAR : width_in_bits / NOF_BITS_REPRESENTED_BY_CHAR + 1;
fast_atoi(str_value, strlen, data_nof_chunks, data_value, &is_equal_to_zero);
if (is_equal_to_zero)
return;
phy_mem.block_identifier = block_id;
phy_mem.is_reg = 0;
phy_mem.mem_address = pem_mem_address_val + phy_mem_idx;
phy_mem.mem_width_in_bits = (unsigned int)width_in_bits;
phy_mem.reserve = 0;
pem_write(unit, &phy_mem, 1, data_value);
}
}
void dnx_pemladrv_reg_line_write(int unit, const char* line) {
char pem_reg_address[MEM_ADDR_LENGTH];
char str_value[MAX_MEM_DATA_LENGTH];
char shtut[MAX_SHTUT_LENGTH];
int width_in_bits;
char key_word[MAX_NAME_LENGTH], pem_reg_name[MAX_NAME_LENGTH];
phy_mem_t phy_mem;
unsigned int block_id, pem_reg_address_val;
unsigned int data_value[MAX_DATA_VALUE_ARRAY] = { 0 };
unsigned int data_nof_chunks;
unsigned int strlen;
bool is_equal_to_zero = FALSE;
if (sscanf(line, "%s %s %s %d %2s %s", key_word, pem_reg_name, pem_reg_address, &width_in_bits, shtut, str_value) != PEM_NOF_REG_WRITE_TOKEN) {
printf("Bad ucode line format. Skip and continue with next line\n.");
}
else {
pem_reg_address_val = hexstr2addr(pem_reg_address, &block_id);
data_nof_chunks = (width_in_bits % NOF_BITS_IN_WORD == 0) ? width_in_bits / NOF_BITS_IN_WORD : width_in_bits / NOF_BITS_IN_WORD + 1;
strlen = (width_in_bits % NOF_BITS_REPRESENTED_BY_CHAR == 0) ? width_in_bits / NOF_BITS_REPRESENTED_BY_CHAR : width_in_bits / NOF_BITS_REPRESENTED_BY_CHAR + 1;
fast_atoi(str_value, strlen, data_nof_chunks, data_value, &is_equal_to_zero);
phy_mem.block_identifier = block_id;
phy_mem.is_reg = 1;
phy_mem.mem_address = pem_reg_address_val;
phy_mem.mem_width_in_bits = (unsigned int)width_in_bits;
phy_mem.reserve = 0;
pem_write(unit, &phy_mem, 0, data_value);
}
}
void dnx_pemladrv_db_info_insert(const int unit, const char* line) {
char key_word[MAX_NAME_LENGTH],db_type[MAX_NAME_LENGTH], db_name[MAX_NAME_LENGTH];
int db_id, nof_entries, key_width, result_width;
int nof_key_fields, nof_result_fields;
if (sscanf( line, "%s %s %s %d %d %d %d %d %d ", key_word, db_type, db_name, &db_id, &nof_entries, &key_width, &result_width, &nof_key_fields, &nof_result_fields) != PEM_NOF_DB_TOKEN) {
printf("Bad line format. Skip and continue with next line.\n");
return;
}
else {
if ((strcmp(db_type, KEYWORD_DB_DIRECT) == 0)) {
strncpy(api_info[unit].db_direct_container.db_direct_info_arr[db_id].name, db_name, strlen(db_name));
api_info[unit].db_direct_container.db_direct_info_arr[db_id].name[strlen(db_name)] = '\0';
api_info[unit].db_direct_container.db_direct_info_arr[db_id].total_nof_entries = nof_entries;
api_info[unit].db_direct_container.db_direct_info_arr[db_id].total_result_width = result_width;
api_info[unit].db_direct_container.db_direct_info_arr[db_id].nof_fields = nof_result_fields;
api_info[unit].db_direct_container.db_direct_info_arr[db_id].result_chunk_mapper_matrix_arr = NULL;
init_logical_fields_location(&api_info[unit].db_direct_container.db_direct_info_arr[db_id].field_bit_range_arr, nof_result_fields);
}
if ((strcmp(db_type, KEYWORD_DB_TCAM) == 0)) {
strncpy(api_info[unit].db_tcam_container.db_tcam_info_arr[db_id].name, db_name, strlen(db_name));
api_info[unit].db_tcam_container.db_tcam_info_arr[db_id].name[strlen(db_name)] = '\0';
api_info[unit].db_tcam_container.db_tcam_info_arr[db_id].total_nof_entries = nof_entries;
api_info[unit].db_tcam_container.db_tcam_info_arr[db_id].total_key_width = key_width;
api_info[unit].db_tcam_container.db_tcam_info_arr[db_id].total_result_width = result_width;
api_info[unit].db_tcam_container.db_tcam_info_arr[db_id].nof_fields_in_key = nof_key_fields;
api_info[unit].db_tcam_container.db_tcam_info_arr[db_id].nof_fields_in_result = nof_result_fields;
api_info[unit].db_tcam_container.db_tcam_info_arr[db_id].key_chunk_mapper_matrix_arr = NULL;
api_info[unit].db_tcam_container.db_tcam_info_arr[db_id].result_chunk_mapper_matrix_arr = NULL;
init_logical_fields_location(&(api_info[unit].db_tcam_container.db_tcam_info_arr[db_id].key_field_bit_range_arr), nof_key_fields);
init_logical_fields_location(&(api_info[unit].db_tcam_container.db_tcam_info_arr[db_id].result_field_bit_range_arr), nof_result_fields);
}
if ((strcmp(db_type, KEYWORD_DB_EM) == 0)) {
strncpy(api_info[unit].db_em_container.db_em_info_arr[db_id].logical_em_info.name, db_name, strlen(db_name));
api_info[unit].db_em_container.db_em_info_arr[db_id].logical_em_info.name[strlen(db_name)] = '\0';
api_info[unit].db_em_container.db_em_info_arr[db_id].logical_em_info.total_nof_entries = nof_entries;
api_info[unit].db_em_container.db_em_info_arr[db_id].logical_em_info.total_key_width = key_width;
api_info[unit].db_em_container.db_em_info_arr[db_id].logical_em_info.total_result_width = result_width;
api_info[unit].db_em_container.db_em_info_arr[db_id].logical_em_info.nof_fields_in_key = nof_key_fields;
api_info[unit].db_em_container.db_em_info_arr[db_id].logical_em_info.nof_fields_in_result = nof_result_fields;
api_info[unit].db_em_container.db_em_info_arr[db_id].logical_em_info.key_chunk_mapper_matrix_arr = NULL;
api_info[unit].db_em_container.db_em_info_arr[db_id].logical_em_info.result_chunk_mapper_matrix_arr = NULL;
init_logical_fields_location(&(api_info[unit].db_em_container.db_em_info_arr[db_id].logical_em_info.key_field_bit_range_arr), nof_key_fields);
init_logical_fields_location(&(api_info[unit].db_em_container.db_em_info_arr[db_id].logical_em_info.result_field_bit_range_arr), nof_result_fields);
}
if ((strcmp(db_type, KEYWORD_DB_LPM) == 0)) {
strncpy(api_info[unit].db_lpm_container.db_lpm_info_arr[db_id].logical_lpm_info.name, db_name, strlen(db_name));
api_info[unit].db_lpm_container.db_lpm_info_arr[db_id].logical_lpm_info.name[strlen(db_name)] = '\0';
api_info[unit].db_lpm_container.db_lpm_info_arr[db_id].logical_lpm_info.total_nof_entries = nof_entries;
api_info[unit].db_lpm_container.db_lpm_info_arr[db_id].logical_lpm_info.total_key_width = key_width;
api_info[unit].db_lpm_container.db_lpm_info_arr[db_id].logical_lpm_info.total_result_width = result_width;
api_info[unit].db_lpm_container.db_lpm_info_arr[db_id].logical_lpm_info.nof_fields_in_key = nof_result_fields;
api_info[unit].db_lpm_container.db_lpm_info_arr[db_id].logical_lpm_info.nof_fields_in_result = nof_result_fields;
api_info[unit].db_lpm_container.db_lpm_info_arr[db_id].logical_lpm_info.key_chunk_mapper_matrix_arr = NULL;
api_info[unit].db_lpm_container.db_lpm_info_arr[db_id].logical_lpm_info.result_chunk_mapper_matrix_arr = NULL;
init_logical_fields_location(&(api_info[unit].db_lpm_container.db_lpm_info_arr[db_id].logical_lpm_info.key_field_bit_range_arr), nof_key_fields);
init_logical_fields_location(&(api_info[unit].db_lpm_container.db_lpm_info_arr[db_id].logical_lpm_info.result_field_bit_range_arr), nof_result_fields);
}
}
}
void dnx_pemladrv_db_field_info_insert(const int unit, const char* line) {
char key_word[MAX_NAME_LENGTH], db_name_debug[MAX_NAME_LENGTH], field_name_debug[MAX_NAME_LENGTH], db_type[MAX_NAME_LENGTH];
int db_id, field_id, lsb_bit, msb_bit;
if (sscanf( line, "%s %s %s %d %s %d %d %d", key_word, db_name_debug, db_type, &db_id, field_name_debug, &field_id, &lsb_bit, &msb_bit) != PEM_NOF_KEY_FIELD_TOKEN) {
printf("Bad line format. Skip and continue with next line.\n");
return;
}
if ((strcmp(key_word, KEYWORD_KEY) == 0))
db_key_field_info_insert(unit, db_type, db_id, field_id, lsb_bit, msb_bit);
else if((strcmp(key_word, KEYWORD_RESULT) == 0))
db_result_field_info_insert(unit, db_type, db_id, field_id, lsb_bit, msb_bit);
return;
}
void db_key_field_info_insert(const int unit, const char* db_type, const int db_id, const int field_id, const int lsb_bit, const int msb_bit) {
if ((strcmp(db_type, KEYWORD_DB_TCAM) == 0)) {
api_info[unit].db_tcam_container.db_tcam_info_arr[db_id].key_field_bit_range_arr[field_id].lsb = lsb_bit;
api_info[unit].db_tcam_container.db_tcam_info_arr[db_id].key_field_bit_range_arr[field_id].msb = msb_bit;
}
else if ((strcmp(db_type, KEYWORD_DB_EM) == 0)) {
api_info[unit].db_em_container.db_em_info_arr[db_id].logical_em_info.key_field_bit_range_arr[field_id].lsb = lsb_bit;
api_info[unit].db_em_container.db_em_info_arr[db_id].logical_em_info.key_field_bit_range_arr[field_id].msb = msb_bit;
}
else if ((strcmp(db_type, KEYWORD_DB_LPM) == 0)) {
if (field_id == 0) {
api_info[unit].db_lpm_container.db_lpm_info_arr[db_id].logical_lpm_info.key_field_bit_range_arr[field_id].lsb = lsb_bit;
api_info[unit].db_lpm_container.db_lpm_info_arr[db_id].logical_lpm_info.key_field_bit_range_arr[field_id].msb = msb_bit;
}
}
}
void db_result_field_info_insert(const int unit, const char* db_type, const int db_id, const int field_id, const int lsb_bit, const int msb_bit) {
if ((strcmp(db_type, KEYWORD_DB_DIRECT) == 0)) {
api_info[unit].db_direct_container.db_direct_info_arr[db_id].field_bit_range_arr[field_id].lsb = lsb_bit;
api_info[unit].db_direct_container.db_direct_info_arr[db_id].field_bit_range_arr[field_id].msb = msb_bit;
}
else if ((strcmp(db_type, KEYWORD_DB_TCAM) == 0)) {
api_info[unit].db_tcam_container.db_tcam_info_arr[db_id].result_field_bit_range_arr[field_id].lsb = lsb_bit;
api_info[unit].db_tcam_container.db_tcam_info_arr[db_id].result_field_bit_range_arr[field_id].msb = msb_bit;
}
else if ((strcmp(db_type, KEYWORD_DB_EM) == 0)) {
api_info[unit].db_em_container.db_em_info_arr[db_id].logical_em_info.result_field_bit_range_arr[field_id].lsb = lsb_bit;
api_info[unit].db_em_container.db_em_info_arr[db_id].logical_em_info.result_field_bit_range_arr[field_id].msb = msb_bit;
}
else if ((strcmp(db_type, KEYWORD_DB_LPM) == 0)) {
if (field_id == 0) {
api_info[unit].db_lpm_container.db_lpm_info_arr[db_id].logical_lpm_info.result_field_bit_range_arr[field_id].lsb = lsb_bit;
api_info[unit].db_lpm_container.db_lpm_info_arr[db_id].logical_lpm_info.result_field_bit_range_arr[field_id].msb = msb_bit;
}
}
}
void is_field_mapped_update(const int num_of_fields, FieldBitRange* field_bit_range_arr , DbChunkMapper*const chunk_info_ptr) {
int i;
unsigned int chunk_lsb_bit = chunk_info_ptr->virtual_mem_width_offset;
unsigned int chunk_msb_bit = chunk_lsb_bit + chunk_info_ptr->chunk_width - 1;
for (i = 0; i < num_of_fields; ++i) {
if (field_bit_range_arr[i].msb < chunk_lsb_bit && field_bit_range_arr[i].lsb > chunk_msb_bit )
continue;
else
field_bit_range_arr[i].is_field_mapped = 1;
}
}
void dnx_pemladrv_direct_result_chunk_insert(const int unit, const char* line) {
unsigned int db_id;
DbChunkMapper* chunk_info_ptr = (DbChunkMapper*)sal_calloc(chunk_info_ptr, 1, sizeof(DbChunkMapper));
db_id = build_direct_chunk_from_ucode(unit, line, chunk_info_ptr);
if (db_id == UINT_MAX) {
printf("failed to insert chunk.\n");
sal_free(chunk_info_ptr);
return;
}
if (db_id > api_info[unit].db_direct_container.nof_direct_dbs){
printf("Wrong Db_id. check NOF_DBS in ucode file.\n");
sal_free(chunk_info_ptr);
return;
}
db_chunk_insert(api_info[unit].db_direct_container.db_direct_info_arr[db_id].result_chunk_mapper_matrix_arr, chunk_info_ptr);
is_field_mapped_update(api_info[unit].db_direct_container.db_direct_info_arr[db_id].nof_fields,
api_info[unit].db_direct_container.db_direct_info_arr[db_id].field_bit_range_arr,
chunk_info_ptr);
}
void dnx_pemladrv_tcam_key_chunk_insert(const int unit, const char* line) {
unsigned int db_id;
DbChunkMapper* chunk_info_ptr = (DbChunkMapper*)sal_calloc(chunk_info_ptr, 1, sizeof(DbChunkMapper));
db_id = build_cam_key_chunk_from_ucode(line, chunk_info_ptr);
if (db_id == UINT_MAX) {
printf("failed to insert chunk.\n");
sal_free(chunk_info_ptr);
return;
}
if (db_id > api_info[unit].db_tcam_container.nof_tcam_dbs){
printf("Wrong Db_id. check NOF_DBS in ucode file.\n");
sal_free(chunk_info_ptr);
return;
}
db_chunk_insert(api_info[unit].db_tcam_container.db_tcam_info_arr[db_id].key_chunk_mapper_matrix_arr, chunk_info_ptr);
is_field_mapped_update(api_info[unit].db_tcam_container.db_tcam_info_arr[db_id].nof_fields_in_key,
api_info[unit].db_tcam_container.db_tcam_info_arr[db_id].key_field_bit_range_arr,
chunk_info_ptr);
}
void dnx_pemladrv_tcam_result_chunk_insert(const int unit, const char* line) {
unsigned int db_id;
DbChunkMapper* chunk_info_ptr = (DbChunkMapper*)sal_calloc(chunk_info_ptr, 1, sizeof(DbChunkMapper));
db_id = build_cam_result_chunk_from_ucode(line, chunk_info_ptr);
if (db_id == UINT_MAX) {
printf("failed to insert chunk.\n");
sal_free(chunk_info_ptr);
return;
}
if (db_id > api_info[unit].db_tcam_container.nof_tcam_dbs){
printf("Wrong Db_id. check NOF_DBS in ucode file.\n");
sal_free(chunk_info_ptr);
return;
}
db_chunk_insert(api_info[unit].db_tcam_container.db_tcam_info_arr[db_id].result_chunk_mapper_matrix_arr, chunk_info_ptr);
is_field_mapped_update(api_info[unit].db_tcam_container.db_tcam_info_arr[db_id].nof_fields_in_result,
api_info[unit].db_tcam_container.db_tcam_info_arr[db_id].result_field_bit_range_arr,
chunk_info_ptr);
}
void dnx_pemladrv_em_key_chunk_insert(const int unit, const char* line) {
unsigned int db_id;
DbChunkMapper* chunk_info_ptr = (DbChunkMapper*)sal_calloc(chunk_info_ptr, 1, sizeof(DbChunkMapper));
db_id = build_cam_key_chunk_from_ucode(line, chunk_info_ptr);
if (db_id == UINT_MAX) {
printf("failed to insert chunk.\n");
sal_free(chunk_info_ptr);
return;
}
if (db_id > api_info[unit].db_em_container.nof_em_dbs){
printf("Wrong Db_id. check NOF_DBS in ucode file.\n");
sal_free(chunk_info_ptr);
return;
}
db_chunk_insert(api_info[unit].db_em_container.db_em_info_arr[db_id].logical_em_info.key_chunk_mapper_matrix_arr, chunk_info_ptr);
is_field_mapped_update(api_info[unit].db_em_container.db_em_info_arr[db_id].logical_em_info.nof_fields_in_key,
api_info[unit].db_em_container.db_em_info_arr[db_id].logical_em_info.key_field_bit_range_arr,
chunk_info_ptr);
}
void dnx_pemladrv_em_result_chunk_insert(const int unit, const char* line) {
unsigned int db_id;
DbChunkMapper* chunk_info_ptr = (DbChunkMapper*)sal_calloc(chunk_info_ptr, 1, sizeof(DbChunkMapper));
db_id = build_cam_result_chunk_from_ucode(line, chunk_info_ptr);
if (db_id == UINT_MAX) {
printf("failed to insert chunk.\n");
sal_free(chunk_info_ptr);
return;
}
if (db_id > api_info[unit].db_em_container.nof_em_dbs){
printf("Wrong Db_id. check NOF_DBS in ucode file.\n");
sal_free(chunk_info_ptr);
return;
}
db_chunk_insert(api_info[unit].db_em_container.db_em_info_arr[db_id].logical_em_info.result_chunk_mapper_matrix_arr, chunk_info_ptr);
is_field_mapped_update(api_info[unit].db_em_container.db_em_info_arr[db_id].logical_em_info.nof_fields_in_result,
api_info[unit].db_em_container.db_em_info_arr[db_id].logical_em_info.result_field_bit_range_arr,
chunk_info_ptr);
}
void dnx_pemladrv_lpm_key_chunk_insert(const int unit, const char* line) {
unsigned int db_id;
DbChunkMapper* chunk_info_ptr = (DbChunkMapper*)sal_calloc(chunk_info_ptr, 1, sizeof(DbChunkMapper));
db_id = build_cam_key_chunk_from_ucode(line, chunk_info_ptr);
if (db_id == UINT_MAX) {
printf("failed to insert chunk.\n");
sal_free(chunk_info_ptr);
return;
}
if (db_id > api_info[unit].db_lpm_container.nof_lpm_dbs){
printf("Wrong Db_id. check NOF_DBS in ucode file.\n");
sal_free(chunk_info_ptr);
return;
}
db_chunk_insert(api_info[unit].db_lpm_container.db_lpm_info_arr[db_id].logical_lpm_info.key_chunk_mapper_matrix_arr, chunk_info_ptr);
is_field_mapped_update(api_info[unit].db_lpm_container.db_lpm_info_arr[db_id].logical_lpm_info.nof_fields_in_key,
api_info[unit].db_lpm_container.db_lpm_info_arr[db_id].logical_lpm_info.key_field_bit_range_arr,
chunk_info_ptr);
}
void dnx_pemladrv_lpm_result_chunk_insert(const int unit, const char* line) {
unsigned int db_id;
DbChunkMapper* chunk_info_ptr = (DbChunkMapper*)sal_calloc(chunk_info_ptr, 1, sizeof(DbChunkMapper));
db_id = build_cam_result_chunk_from_ucode(line, chunk_info_ptr);
if (db_id == UINT_MAX) {
printf("failed to insert chunk.\n");
sal_free(chunk_info_ptr);
return;
}
if (db_id > api_info[unit].db_lpm_container.nof_lpm_dbs){
printf("Wrong Db_id. check NOF_DBS in ucode file.\n");
sal_free(chunk_info_ptr);
return;
}
db_chunk_insert(api_info[unit].db_lpm_container.db_lpm_info_arr[db_id].logical_lpm_info.result_chunk_mapper_matrix_arr, chunk_info_ptr);
is_field_mapped_update(api_info[unit].db_lpm_container.db_lpm_info_arr[db_id].logical_lpm_info.nof_fields_in_result,
api_info[unit].db_lpm_container.db_lpm_info_arr[db_id].logical_lpm_info.result_field_bit_range_arr,
chunk_info_ptr);
}
unsigned int build_direct_chunk_from_ucode(const int unit, const char* line, DbChunkMapper* chunk_info_ptr) {
char pem_mem_address[44];
unsigned int pem_mem_width;
unsigned int curr_offset, previous_chunks_to_add;
unsigned int db_id, field_id, field_width, pe_matrix_col, phy_mem_idx, mem_start_row, mem_start_colomn, implementation_index;
unsigned int index_range[2], bits_range[2], db_dim[2];
unsigned int core_id, is_ingress;
char key_word[MAX_NAME_LENGTH],db_type[MAX_NAME_LENGTH], db_name_debug[MAX_NAME_LENGTH], field_name_debug[MAX_NAME_LENGTH];
char pem_mem_name[MAX_NAME_LENGTH];
char colon, x;
if (sscanf( line, "%s %s %d %s %d %u %d%c%d %d%c%d %d%c%d %s %d %d %s %s %d %d %d %d %d %d",
key_word, db_name_debug, (int *) &db_id, field_name_debug, (int *) &field_id, &field_width,
(int *) &db_dim[DB_ROWS], &x, (int *) &db_dim[DB_COLUMNS],
(int *) &index_range[PEM_RANGE_HIGH_LIMIT], &colon,(int *) &index_range[PEM_RANGE_LOW_LIMIT],
(int *) &bits_range[PEM_RANGE_HIGH_LIMIT], &colon,(int *) &bits_range[PEM_RANGE_LOW_LIMIT],
db_type, (int *) &pe_matrix_col, (int *) &phy_mem_idx, pem_mem_name, pem_mem_address,
(int *) &mem_start_row, (int *) &mem_start_colomn, (int *) &pem_mem_width, (int *) &is_ingress, (int *) &core_id,
(int *) &implementation_index) < PEM_NOF_DB_DIRECT_INFO_TOKEN) {
printf("Bad line format. Skip and continue with next line.\n");
return UINT_MAX;
}
else {
curr_offset = api_info[unit].db_direct_container.db_direct_info_arr[db_id].field_bit_range_arr[field_id].lsb;
chunk_info_ptr->chunk_matrix_row_ndx = index_range[PEM_RANGE_LOW_LIMIT] / PEM_CFG_API_MAP_CHUNK_N_ENTRIES;
previous_chunks_to_add = (curr_offset > 0 )? 1 + (curr_offset - 1)/PEM_CFG_API_MAP_CHUNK_WIDTH : curr_offset / PEM_CFG_API_MAP_CHUNK_WIDTH;
chunk_info_ptr->chunk_matrix_col_ndx = (bits_range[PEM_RANGE_LOW_LIMIT] / PEM_CFG_API_MAP_CHUNK_WIDTH) + previous_chunks_to_add;
chunk_info_ptr->chunk_matrix_ndx = implementation_index;
chunk_info_ptr->chunk_entries = index_range[PEM_RANGE_HIGH_LIMIT] - index_range[PEM_RANGE_LOW_LIMIT] + 1;
chunk_info_ptr->chunk_width = bits_range[PEM_RANGE_HIGH_LIMIT] - bits_range[PEM_RANGE_LOW_LIMIT] + 1;
chunk_info_ptr->phy_mem_addr = hexstr2addr(pem_mem_address, &chunk_info_ptr->mem_block_id);
chunk_info_ptr->phy_mem_entry_offset = mem_start_row;
chunk_info_ptr->phy_mem_index = phy_mem_idx;
chunk_info_ptr->phy_mem_name = (char*)sal_alloc(strlen(pem_mem_name) + 1, "");
strncpy(chunk_info_ptr->phy_mem_name, pem_mem_name, strlen(pem_mem_name));
chunk_info_ptr->phy_mem_name[strlen(pem_mem_name)] = '\0';
chunk_info_ptr->phy_mem_width = pem_mem_width;
chunk_info_ptr->phy_mem_width_offset = mem_start_colomn;
chunk_info_ptr->phy_pe_matrix_col = pe_matrix_col;
chunk_info_ptr->virtual_mem_entry_offset = index_range[PEM_RANGE_LOW_LIMIT];
chunk_info_ptr->virtual_mem_width_offset = bits_range[PEM_RANGE_LOW_LIMIT] + curr_offset;
chunk_info_ptr->is_ingress = is_ingress;
return db_id;
}
}
unsigned int build_cam_key_chunk_from_ucode(const char* line, DbChunkMapper* chunk_info_ptr) {
char pem_mem_address[44];
unsigned int pem_mem_width, mem_nof_rows_debug, total_width;
unsigned int db_id, pe_matrix_col, phy_mem_idx, mem_start_row, valid_col, implementation_index;
unsigned int mem_valid_coloms, mem_mask_st_col, mem_key_st_col;
unsigned int index_range[2], mask_bit_range[2], key_bit_range[2];
unsigned int core_id, is_ingress;
char key_word[MAX_NAME_LENGTH],db_type[MAX_NAME_LENGTH], db_name_debug[MAX_NAME_LENGTH], field_name_debug[MAX_NAME_LENGTH];
char pem_mem_name[MAX_NAME_LENGTH];
char colon, x;
unsigned int ret;
ret = UINT_MAX;
if (sscanf( line, "%s %s %d %s %d%c%d %d%c%d %d %d%c%d %d%c%d %s %d %d %s %s %d %d %d %d %d %d %d %d ",
key_word, db_name_debug, (int *) &db_id, field_name_debug, (int *) &mem_nof_rows_debug, &x,
(int *) &total_width, (int *) &index_range[PEM_RANGE_HIGH_LIMIT], &colon,
(int *) &index_range[PEM_RANGE_LOW_LIMIT], (int *) &valid_col,
(int *) &mask_bit_range[PEM_RANGE_HIGH_LIMIT], &colon, (int *) &mask_bit_range[PEM_RANGE_LOW_LIMIT],
(int *) &key_bit_range[PEM_RANGE_HIGH_LIMIT], &colon,(int *) &key_bit_range[PEM_RANGE_LOW_LIMIT],
db_type, (int *) &pe_matrix_col, (int *) &phy_mem_idx, pem_mem_name, pem_mem_address,
(int *) &mem_start_row, (int *) &mem_valid_coloms, (int *) &mem_mask_st_col, (int *) &mem_key_st_col,
(int *)&pem_mem_width, (int *)&is_ingress, (int *)&core_id, (int *)&implementation_index) < PEM_NOF_DB_CAM_KEY_MAPPING_INFO_TOKEN) {
printf("Bad line format. Skip and continue with next line.\n");
ret = UINT_MAX;
}
else {
chunk_info_ptr->chunk_matrix_row_ndx = index_range[PEM_RANGE_LOW_LIMIT] / PEM_CFG_API_CAM_TCAM_CHUNK_N_ENTRIES;
chunk_info_ptr->chunk_matrix_col_ndx = key_bit_range[PEM_RANGE_LOW_LIMIT] / PEM_CFG_API_CAM_TCAM_CHUNK_WIDTH;
chunk_info_ptr->chunk_matrix_ndx = implementation_index;
chunk_info_ptr->chunk_entries = index_range[PEM_RANGE_HIGH_LIMIT] - index_range[PEM_RANGE_LOW_LIMIT] + 1;
chunk_info_ptr->chunk_width = key_bit_range[PEM_RANGE_HIGH_LIMIT] - key_bit_range[PEM_RANGE_LOW_LIMIT] + 1;
chunk_info_ptr->phy_mem_addr = hexstr2addr(pem_mem_address, &chunk_info_ptr->mem_block_id);
chunk_info_ptr->phy_mem_entry_offset = mem_start_row;
chunk_info_ptr->phy_mem_index = phy_mem_idx;
chunk_info_ptr->phy_mem_name = (char*)sal_alloc(strlen(pem_mem_name) + 1, "");
strncpy(chunk_info_ptr->phy_mem_name, pem_mem_name, strlen(pem_mem_name));
chunk_info_ptr->phy_mem_name[strlen(pem_mem_name)] = '\0';
chunk_info_ptr->phy_mem_width = pem_mem_width;
chunk_info_ptr->phy_mem_width_offset = mem_key_st_col;
chunk_info_ptr->phy_pe_matrix_col = pe_matrix_col;
chunk_info_ptr->virtual_mem_entry_offset = index_range[PEM_RANGE_LOW_LIMIT];
chunk_info_ptr->virtual_mem_width_offset = key_bit_range[PEM_RANGE_LOW_LIMIT];
chunk_info_ptr->is_ingress = is_ingress;
return db_id;
}
return (ret);
}
unsigned int build_cam_result_chunk_from_ucode(const char* line, DbChunkMapper* chunk_info_ptr) {
char pem_mem_address[44];
unsigned int pem_mem_width, mem_nof_rows_debug, total_width;
unsigned int db_id, pe_matrix_col, phy_mem_idx, mem_start_row, mem_start_colomn, implementation_index;
unsigned int index_range[2], bits_range[2];
unsigned int core_id, is_ingress;
char key_word[MAX_NAME_LENGTH], db_type[MAX_NAME_LENGTH], db_name_debug[MAX_NAME_LENGTH], field_name_debug[MAX_NAME_LENGTH];
char pem_mem_name[MAX_NAME_LENGTH];
char colon, x;
if (sscanf( line, "%s %s %d %s %d%c%d %d%c%d %d%c%d %s %d %d %d %s %s %d %d %d %d %d ",
key_word, db_name_debug, (int *) &db_id, field_name_debug, (int *) &mem_nof_rows_debug, &x,
(int *) &total_width, (int *) &index_range[PEM_RANGE_HIGH_LIMIT], &colon,
(int *) &index_range[PEM_RANGE_LOW_LIMIT], (int *) &bits_range[PEM_RANGE_HIGH_LIMIT], &colon,
(int *) &bits_range[PEM_RANGE_LOW_LIMIT], db_type, (int *) &pe_matrix_col,
(int *) &pem_mem_width, (int *) &phy_mem_idx, pem_mem_name, pem_mem_address,
(int *) &mem_start_row, (int *) &mem_start_colomn, (int *) &is_ingress, (int *) &core_id,
(int *) &implementation_index) < PEM_NOF_DB_CAM_RESULT_MAPPING_INFO_TOKEN) {
printf("Bad line format. Skip and continue with next line.\n");
return UINT_MAX;
}
else {
chunk_info_ptr->chunk_matrix_row_ndx = index_range[PEM_RANGE_LOW_LIMIT] / PEM_CFG_API_CAM_RESULT_CHUNK_N_ENTRIES;
chunk_info_ptr->chunk_matrix_col_ndx = bits_range[PEM_RANGE_LOW_LIMIT] / PEM_CFG_API_CAM_RESULT_CHUNK_WIDTH;
chunk_info_ptr->chunk_matrix_ndx = implementation_index;
chunk_info_ptr->chunk_entries = index_range[PEM_RANGE_HIGH_LIMIT] - index_range[PEM_RANGE_LOW_LIMIT] + 1;
chunk_info_ptr->chunk_width = bits_range[PEM_RANGE_HIGH_LIMIT] - bits_range[PEM_RANGE_LOW_LIMIT] + 1;
chunk_info_ptr->phy_mem_addr = hexstr2addr(pem_mem_address, &chunk_info_ptr->mem_block_id);
chunk_info_ptr->phy_mem_entry_offset = mem_start_row;
chunk_info_ptr->phy_mem_index = phy_mem_idx;
chunk_info_ptr->phy_mem_name = (char*)sal_alloc(strlen(pem_mem_name) + 1, "");
strncpy(chunk_info_ptr->phy_mem_name, pem_mem_name, strlen(pem_mem_name));
chunk_info_ptr->phy_mem_name[strlen(pem_mem_name)] = '\0';
chunk_info_ptr->phy_mem_width = pem_mem_width;
chunk_info_ptr->phy_mem_width_offset = mem_start_colomn;
chunk_info_ptr->phy_pe_matrix_col = pe_matrix_col;
chunk_info_ptr->virtual_mem_entry_offset = index_range[PEM_RANGE_LOW_LIMIT];
chunk_info_ptr->virtual_mem_width_offset = bits_range[PEM_RANGE_LOW_LIMIT];
chunk_info_ptr->is_ingress = is_ingress;
return db_id;
}
}
void dnx_pemladrv_register_insert(const int unit, const char* line) {
char pem_mem_address[44];
unsigned int field_id;
unsigned int virtual_field_lsb;
unsigned int virtual_field_msb;
unsigned int pem_mem_line;
unsigned int pem_mem_offset;
unsigned int pem_mem_total_width;
unsigned int reg_id;
unsigned int mapping_id;
unsigned int is_industrial_tcam;
unsigned int is_ingress;
unsigned int core_id;
unsigned int mapping_width;
char key_word[MAX_NAME_LENGTH], db_type[MAX_NAME_LENGTH], reg_name[MAX_NAME_LENGTH], field_name_debug[MAX_NAME_LENGTH], pem_mem_name[MAX_NAME_LENGTH];
char colon;
if (sscanf(line, "%s %s %d %d %s %d %d %d%c%d %s %s %s %d %d %d %d %d %d",
key_word, reg_name, (int *)®_id, (int *)&mapping_id, field_name_debug, (int *)&field_id,
(int *)&mapping_width, (int *)&virtual_field_msb, &colon, (int *)&virtual_field_lsb,
db_type, pem_mem_name, pem_mem_address,
(int *)&pem_mem_line, (int *)&pem_mem_offset, (int *)&pem_mem_total_width, (int *)&is_industrial_tcam, (int *)&is_ingress, (int *)&core_id) < PEM_NOF_REGISTER_INFO_TOKEN) {
printf("Bad line format. Skip and continue with next line.\n");
printf("build_register_mapping_from_ucode: bad line format!!! line = %s\n", line);
return;
}
else {
RegFieldMapper* reg_field_mapping_ptr = &(api_info[unit].reg_container.reg_info_arr[reg_id].reg_field_info_arr[field_id].reg_field_mapping_arr[mapping_id]);
api_info[unit].reg_container.reg_info_arr[reg_id].is_mapped = 1;
strncpy(reg_field_mapping_ptr->register_name, reg_name, strlen(reg_name));
reg_field_mapping_ptr->register_name[strlen(reg_name)] = '\0';
reg_field_mapping_ptr->field_id = field_id;
reg_field_mapping_ptr->cfg_mapper_width = mapping_width;
reg_field_mapping_ptr->virtual_field_lsb = virtual_field_lsb;
reg_field_mapping_ptr->virtual_field_msb = virtual_field_msb;
reg_field_mapping_ptr->pem_mem_address = hexstr2addr(pem_mem_address, ®_field_mapping_ptr->pem_mem_block_id);
reg_field_mapping_ptr->pem_mem_offset = pem_mem_offset;
reg_field_mapping_ptr->pem_mem_total_width = pem_mem_total_width;
reg_field_mapping_ptr->mapping_id = mapping_id;
reg_field_mapping_ptr->is_industrial_tcam = is_industrial_tcam;
reg_field_mapping_ptr->is_ingress = is_ingress;
reg_field_mapping_ptr->core_id = core_id;
if(SOC_IS_J2P(unit))
{
reg_field_mapping_ptr->is_mem = (pem_mem_line != -1);
reg_field_mapping_ptr->pem_mem_line = (pem_mem_line == -1) ? 0 : pem_mem_line;
}
else
{
reg_field_mapping_ptr->is_mem = (pem_mem_offset != -1);
reg_field_mapping_ptr->pem_mem_line = pem_mem_line;
}
return;
}
}
void db_chunk_insert(LogicalDbChunkMapperMatrix* logical_db_mapper, DbChunkMapper*const chunk_info_ptr) {
logical_db_mapper[chunk_info_ptr->chunk_matrix_ndx].db_chunk_mapper[chunk_info_ptr->chunk_matrix_row_ndx][chunk_info_ptr->chunk_matrix_col_ndx] = chunk_info_ptr;
}
void dnx_pemladrv_init_logical_db_chunk_mapper(const int unit, const char* line){
int db_id, nof_key_chunk_rows, nof_key_chunk_cols, nof_result_chunk_rows, nof_result_chunk_cols, nof_implementations;
char db_name[40];
if ((strncmp(line + KEYWORD_DB_SINGLE_CHUNCK_INFO_SIZE + 1, KEYWORD_DB_DIRECT, KEYWORD_DB_DIRECT_SIZE) == 0)) {
if (sscanf( line, "%s %d %d %d %d ", db_name, &db_id, &nof_result_chunk_rows, &nof_result_chunk_cols, &nof_implementations) != DB_SINGLE_CHUNCK_INFO_DIRECT_TOKEN) {
printf("Bad line format. Skip and continue with next line.\n");
return;
}
if (api_info[unit].db_direct_container.db_direct_info_arr[db_id].result_chunk_mapper_matrix_arr != NULL) {
realloc_logical_db_mapper_matrix(&api_info[unit].db_direct_container.db_direct_info_arr[db_id].result_chunk_mapper_matrix_arr, nof_result_chunk_cols, nof_implementations);
return;
}
init_logical_db_mapper_matrix(&api_info[unit].db_direct_container.db_direct_info_arr[db_id].result_chunk_mapper_matrix_arr, nof_result_chunk_rows, nof_result_chunk_cols, nof_implementations);
api_info[unit].db_direct_container.db_direct_info_arr[db_id].nof_chunk_matrices = nof_implementations;
}
else {
if (sscanf(line, "%s %d %d %d %d %d %d ", db_name, &db_id, &nof_key_chunk_rows, &nof_key_chunk_cols, &nof_result_chunk_rows, &nof_result_chunk_cols, &nof_implementations) != DB_SINGLE_CHUNCK_INFO_MAP_TOKEN) {
printf("Bad line format. Skip and continue with next line.\n");
return;
}
if ((strncmp(line + KEYWORD_DB_SINGLE_CHUNCK_INFO_SIZE + 1, KEYWORD_DB_TCAM, KEYWORD_DB_TCAM_SIZE) == 0)) {
init_logical_db_mapper_matrix(&api_info[unit].db_tcam_container.db_tcam_info_arr[db_id].key_chunk_mapper_matrix_arr, nof_key_chunk_rows, nof_key_chunk_cols, nof_implementations);
init_logical_db_mapper_matrix(&api_info[unit].db_tcam_container.db_tcam_info_arr[db_id].result_chunk_mapper_matrix_arr, nof_result_chunk_rows, nof_result_chunk_cols, nof_implementations);
api_info[unit].db_tcam_container.db_tcam_info_arr[db_id].nof_chunk_matrices = nof_implementations;
}
else if ((strncmp(line + KEYWORD_DB_SINGLE_CHUNCK_INFO_SIZE + 1, KEYWORD_DB_EM, KEYWORD_DB_EM_SIZE) == 0)) {
init_logical_db_mapper_matrix(&api_info[unit].db_em_container.db_em_info_arr[db_id].logical_em_info.key_chunk_mapper_matrix_arr, nof_key_chunk_rows, nof_key_chunk_cols, nof_implementations);
init_logical_db_mapper_matrix(&api_info[unit].db_em_container.db_em_info_arr[db_id].logical_em_info.result_chunk_mapper_matrix_arr, nof_result_chunk_rows, nof_result_chunk_cols, nof_implementations);
init_em_cache(&api_info[unit].db_em_container.db_em_info_arr[db_id].em_cache);
api_info[unit].db_em_container.db_em_info_arr[db_id].em_cache.next_free_index = 0;
api_info[unit].db_em_container.db_em_info_arr[db_id].logical_em_info.nof_chunk_matrices = nof_implementations;
}
else if ((strncmp(line + KEYWORD_DB_SINGLE_CHUNCK_INFO_SIZE + 1, KEYWORD_DB_LPM, KEYWORD_DB_LPM_SIZE) == 0)) {
init_logical_db_mapper_matrix(&api_info[unit].db_lpm_container.db_lpm_info_arr[db_id].logical_lpm_info.key_chunk_mapper_matrix_arr, nof_key_chunk_rows, nof_key_chunk_cols, nof_implementations);
init_logical_db_mapper_matrix(&api_info[unit].db_lpm_container.db_lpm_info_arr[db_id].logical_lpm_info.result_chunk_mapper_matrix_arr, nof_result_chunk_rows, nof_result_chunk_cols, nof_implementations);
init_lpm_cache(&api_info[unit].db_lpm_container.db_lpm_info_arr[db_id].lpm_cache);
api_info[unit].db_lpm_container.db_lpm_info_arr[db_id].logical_lpm_info.nof_chunk_matrices = nof_implementations;
}
}
}
void init_logical_db_mapper_matrix(LogicalDbChunkMapperMatrix** logical_db_mapper_matrix_ptr, const int nof_chunk_rows, const int nof_chunk_cols, const int nof_implementations) {
int i, j;
LogicalDbChunkMapperMatrix* logical_db_mapper_matrix;
*logical_db_mapper_matrix_ptr = (LogicalDbChunkMapperMatrix*)sal_calloc((*logical_db_mapper_matrix_ptr), nof_implementations, sizeof(LogicalDbChunkMapperMatrix));
logical_db_mapper_matrix = *logical_db_mapper_matrix_ptr;
for ( i = 0; i < nof_implementations; i = i + 1 ) {
logical_db_mapper_matrix[i].nof_cols_in_chunk_matrix = nof_chunk_cols;
logical_db_mapper_matrix[i].nof_rows_in_chunk_matrix= nof_chunk_rows;
logical_db_mapper_matrix[i].db_chunk_mapper = (DbChunkMapper***)sal_calloc(logical_db_mapper_matrix[i].db_chunk_mapper, nof_chunk_rows, sizeof(DbChunkMapper**));
for ( j = 0; j < nof_chunk_rows; j = j + 1 ) {
logical_db_mapper_matrix[i].db_chunk_mapper[j] = (DbChunkMapper**)sal_calloc(logical_db_mapper_matrix[i].db_chunk_mapper[j], nof_chunk_cols, sizeof(DbChunkMapper*));
}
}
}
void realloc_logical_db_mapper_matrix(LogicalDbChunkMapperMatrix** logical_db_mapper_matrix_ptr, const int nof_chunk_cols_to_add, const int nof_implementations) {
int i, j, nof_chunk_cols, nof_chunk_rows;
LogicalDbChunkMapperMatrix* logical_db_mapper_matrix;
logical_db_mapper_matrix = *logical_db_mapper_matrix_ptr;
for( i = 0; i < nof_implementations; ++i) {
nof_chunk_rows = logical_db_mapper_matrix[i].nof_rows_in_chunk_matrix;
nof_chunk_cols = logical_db_mapper_matrix[i].nof_cols_in_chunk_matrix;
nof_chunk_cols += nof_chunk_cols_to_add;
logical_db_mapper_matrix[i].nof_cols_in_chunk_matrix = nof_chunk_cols;
for(j = 0; j < nof_chunk_rows; ++j) {
logical_db_mapper_matrix[i].db_chunk_mapper[j] = (DbChunkMapper**)realloc(logical_db_mapper_matrix[i].db_chunk_mapper[j], nof_chunk_cols * sizeof(DbChunkMapper*));
}
}
return;
}
void init_logical_fields_location(FieldBitRange** field_bit_range_arr, const int nof_fields) {
(*field_bit_range_arr) = (FieldBitRange*)sal_calloc((*field_bit_range_arr), nof_fields, sizeof(FieldBitRange));
}
void dnx_pemladrv_init_reg_field_info(const int unit, const char* line) {
char key_word[MAX_NAME_LENGTH];
int reg_id, nof_fields, register_total_width, is_binded;
if (sscanf(line, "%s %d %d %d %d", key_word, ®_id, &nof_fields, ®ister_total_width, &is_binded) != VIRTUAL_REGISTER_NOF_FIELDS_TOKEN) {
printf("Bad line format. Skip and continue with next line.\n");
return;
}
else {
api_info[unit].reg_container.reg_info_arr[reg_id].is_mapped = 1;
api_info[unit].reg_container.reg_info_arr[reg_id].nof_fields = nof_fields;
api_info[unit].reg_container.reg_info_arr[reg_id].register_total_width = register_total_width;
api_info[unit].reg_container.reg_info_arr[reg_id].is_binded = is_binded;
api_info[unit].reg_container.reg_info_arr[reg_id].reg_field_info_arr = (LogicalRegFieldInfo*)sal_calloc(api_info[unit].reg_container.reg_info_arr[reg_id].reg_field_info_arr, nof_fields, sizeof(LogicalRegFieldInfo));
api_info[unit].reg_container.reg_info_arr[reg_id].reg_field_bit_range_arr = (FieldBitRange*) sal_calloc(api_info[unit].reg_container.reg_info_arr[reg_id].reg_field_bit_range_arr, nof_fields, sizeof(FieldBitRange));
}
}
void dnx_pemladrv_init_reg_field_mapper(const int unit, const char* line) {
char key_word[MAX_NAME_LENGTH];
int reg_id, field_id, nof_mappings, lsb_bit, msb_bit;
if (sscanf( line, "%s %d %d %d %d %d", key_word, ®_id, &field_id, &lsb_bit, &msb_bit, &nof_mappings) != VIRTUAL_REGISTER_FIELD_NOF_MAPPINGS_TOKEN) {
printf("Bad line format. Skip and continue with next line.\n");
return;
}
else {
api_info[unit].reg_container.reg_info_arr[reg_id].reg_field_info_arr[field_id].nof_mappings = nof_mappings;
api_info[unit].reg_container.reg_info_arr[reg_id].reg_field_bit_range_arr[field_id].is_field_mapped = (nof_mappings > 0) ? 1 : 0;
api_info[unit].reg_container.reg_info_arr[reg_id].reg_field_bit_range_arr[field_id].lsb = lsb_bit;
api_info[unit].reg_container.reg_info_arr[reg_id].reg_field_bit_range_arr[field_id].msb = msb_bit;
api_info[unit].reg_container.reg_info_arr[reg_id].reg_field_info_arr[field_id].reg_field_mapping_arr = (RegFieldMapper*)sal_calloc(api_info[unit].reg_container.reg_info_arr[reg_id].reg_field_info_arr[field_id].reg_field_mapping_arr, nof_mappings, sizeof(RegFieldMapper));
}
}
void init_meminfo_array_for_applets(const int unit, const char* line) {
char key_word[MAX_NAME_LENGTH];
unsigned int nof_mems;
int core_idx;
sscanf( line, "%s %u", key_word, &nof_mems);
api_info[unit].applet_info.currently_writing_applets_bit = 0;
for (core_idx=0; core_idx < PEM_CFG_API_NOF_CORES_DYNAMIC; ++core_idx) {
api_info[unit].applet_info.nof_pending_applets[core_idx][0] = 0;
api_info[unit].applet_info.nof_pending_applets[core_idx][1] = 0;
}
api_info[unit].applet_info.meminfo_curr_array_size = 0;
api_info[unit].applet_info.meminfo_array_for_applet = (PemMemInfoForApplet**)sal_alloc(nof_mems*sizeof(PemMemInfoForApplet*),"");
}
void insert_meminfo_to_array_for_applets(const int unit, const char* line) {
char key_word[MAX_NAME_LENGTH], mem_name[MAX_NAME_LENGTH];
char pem_reg_address[44];
unsigned int relevant_stage, u_mem_address, block_id;
unsigned long long final_address;
int nof_entries_currently_in_array = api_info[unit].applet_info.meminfo_curr_array_size;
PemMemInfoForApplet* mem_info;
sscanf( line, "%s %s %s %u", key_word, mem_name, pem_reg_address, &relevant_stage);
u_mem_address = hexstr2addr(pem_reg_address, &block_id);
final_address = block_id;
final_address <<= 32;
final_address |= u_mem_address;
final_address >>= 16;
mem_info = (PemMemInfoForApplet*)malloc(sizeof(PemMemInfoForApplet));
mem_info->address = (unsigned int)final_address;
strncpy(mem_info->name, mem_name, strlen(mem_name));
mem_info->name[strlen(mem_name)] = '\0';
mem_info->stage_relevant_for = relevant_stage;
api_info[unit].applet_info.meminfo_array_for_applet[nof_entries_currently_in_array] = mem_info;
api_info[unit].applet_info.meminfo_curr_array_size++;
}
void init_pem_version_control(const int unit, const char* line) {
char pem_reg_address[MEM_ADDR_LENGTH];
char str_value[MAX_MEM_DATA_LENGTH];
char shtut[MAX_SHTUT_LENGTH];
int width_in_bits;
char key_word[MAX_NAME_LENGTH], pem_reg_name[MAX_NAME_LENGTH];
unsigned int data_value = 0;
bool is_equal_to_zero = FALSE;
if (sscanf(line, "%s %s %s %d %2s %s", key_word, pem_reg_name, pem_reg_address, &width_in_bits, shtut, str_value) != PEM_NOF_REG_WRITE_TOKEN) {
printf("Bad ucode line format. Skip and continue with next line.\n");
}
else
{
fast_atoi(str_value, 8, 1, &data_value, &is_equal_to_zero);
strncpy(api_info[unit].version_info.spare_registers_addr_arr[api_info[unit].version_info.iterator], pem_reg_address, strlen(pem_reg_address));
api_info[unit].version_info.spare_registers_addr_arr[api_info[unit].version_info.iterator][strlen(pem_reg_address)] = '\0';
api_info[unit].version_info.spare_registers_values_arr[api_info[unit].version_info.iterator] = data_value;
api_info[unit].version_info.iterator++;
dnx_pemladrv_reg_line_write(unit, line);
}
}
void init_pem_applet_reg(const int unit, const char* line) {
char key_word[MAX_NAME_LENGTH], name[MAX_NAME_LENGTH], address_s[MAX_NAME_LENGTH];
unsigned int ingress0_egress_1, address, block_id, width_in_bits;
int core;
sscanf( line, "%s %s %u %s %u", key_word, name, &ingress0_egress_1, address_s, &width_in_bits);
address = hexstr2addr(address_s, &block_id);
core = get_core_from_memory_address(unit, address);
assert(core >= 0);
api_info[unit].applet_info.applet_reg_info[core][ingress0_egress_1].address = address;
api_info[unit].applet_info.applet_reg_info[core][ingress0_egress_1].block_id = block_id;
api_info[unit].applet_info.applet_reg_info[core][ingress0_egress_1].is_ingress0_egress1 = ingress0_egress_1;
api_info[unit].applet_info.applet_reg_info[core][ingress0_egress_1].length_in_bits = width_in_bits;
strncpy(api_info[unit].applet_info.applet_reg_info[core][ingress0_egress_1].name, name, strlen(name));
api_info[unit].applet_info.applet_reg_info[core][ingress0_egress_1].name[strlen(name)] = '\0';
}
void init_pem_applet_mem(const int unit, const char* line) {
char key_word[MAX_NAME_LENGTH], name[MAX_NAME_LENGTH], address_s[MAX_NAME_LENGTH];
unsigned int ingress0_egress_1, address, block_id, width_in_bits;
int core;
sscanf( line, "%s %s %u %s %u", key_word, name, &ingress0_egress_1, address_s, &width_in_bits);
address = hexstr2addr(address_s, &block_id);
core = get_core_from_memory_address(unit, address);
assert(core >= 0);
api_info[unit].applet_info.applet_mem_info[core][ingress0_egress_1].address = address;
api_info[unit].applet_info.applet_mem_info[core][ingress0_egress_1].block_id = block_id;
api_info[unit].applet_info.applet_mem_info[core][ingress0_egress_1].is_ingress0_egress1 = ingress0_egress_1;
api_info[unit].applet_info.applet_mem_info[core][ingress0_egress_1].length_in_bits = width_in_bits;
strncpy(api_info[unit].applet_info.applet_mem_info[core][ingress0_egress_1].name, name, strlen(name));
api_info[unit].applet_info.applet_mem_info[core][ingress0_egress_1].name[strlen(name)] = '\0';
}
void init_em_cache(EmDbCache* em_cache_info){
int i;
em_cache_info->em_key_entry_arr = (unsigned int**)sal_calloc(em_cache_info->em_key_entry_arr, PEM_CFG_API_CAM_TCAM_CHUNK_N_ENTRIES, sizeof(unsigned int*));
em_cache_info->em_result_entry_arr = (unsigned int**)sal_calloc(em_cache_info->em_result_entry_arr, PEM_CFG_API_CAM_TCAM_CHUNK_N_ENTRIES, sizeof(unsigned int*));
for(i = 0; i < PEM_CFG_API_CAM_TCAM_CHUNK_N_ENTRIES; ++i) {
em_cache_info->em_key_entry_arr[i] = (unsigned int*)sal_calloc(em_cache_info->em_key_entry_arr[i], 1, sizeof(unsigned int));
em_cache_info->em_result_entry_arr[i] = (unsigned int*)sal_calloc(em_cache_info->em_result_entry_arr[i], 1, sizeof(unsigned int));
}
em_cache_info->physical_entry_occupation = (unsigned char*)sal_calloc(em_cache_info->physical_entry_occupation, PEM_CFG_API_CAM_TCAM_CHUNK_N_ENTRIES, sizeof(unsigned char));
}
void init_lpm_cache(LpmDbCache* lpm_cache_info){
int i;
lpm_cache_info->lpm_key_entry_arr = (unsigned int**)sal_calloc(lpm_cache_info->lpm_key_entry_arr, PEM_CFG_API_CAM_TCAM_CHUNK_N_ENTRIES, sizeof(unsigned int*));
lpm_cache_info->lpm_result_entry_arr = (unsigned int**)sal_calloc(lpm_cache_info->lpm_result_entry_arr, PEM_CFG_API_CAM_TCAM_CHUNK_N_ENTRIES, sizeof(unsigned int*));
for(i = 0; i < PEM_CFG_API_CAM_TCAM_CHUNK_N_ENTRIES; ++i) {
lpm_cache_info->lpm_key_entry_arr[i] = (unsigned int*)sal_calloc(lpm_cache_info->lpm_key_entry_arr[i], 1, sizeof(unsigned int));
lpm_cache_info->lpm_result_entry_arr[i] = (unsigned int*)sal_calloc(lpm_cache_info->lpm_result_entry_arr[i], 1, sizeof(unsigned int));
}
lpm_cache_info->lpm_key_entry_prefix_length_arr = (unsigned int*)sal_calloc(lpm_cache_info->lpm_key_entry_prefix_length_arr, PEM_CFG_API_CAM_TCAM_CHUNK_N_ENTRIES, sizeof(unsigned int));
lpm_cache_info->physical_entry_occupation = (unsigned char*)sal_calloc(lpm_cache_info->physical_entry_occupation, PEM_CFG_API_CAM_TCAM_CHUNK_N_ENTRIES, sizeof(unsigned char));
}
void dnx_pemladrv_vw_mapping_insert(const int unit, const char* line){
char key_word[MAX_NAME_LENGTH];
char physical_wire_name[MAX_NAME_LENGTH];
int vw_id, vw_msb, vw_lsb, physical_wire_lsb, mapping_id;
if (sscanf(line, "%s %d %d %d %d %s %d", key_word, &vw_id, &mapping_id, &vw_msb, &vw_lsb, physical_wire_name, &physical_wire_lsb) != VIRTUAL_WIRE_MAPPING_NOF_FIELDS_TOKEN) {
printf("Bad line format. Skip and continue with next line.\n");
return;
}
else {
strncpy(api_info[unit].vw_container.vw_info_arr[vw_id].vw_mappings_arr[mapping_id].physical_wire_name, physical_wire_name, strlen(physical_wire_name));
api_info[unit].vw_container.vw_info_arr[vw_id].vw_mappings_arr[mapping_id].physical_wire_name[strlen(physical_wire_name)] = '\0';
api_info[unit].vw_container.vw_info_arr[vw_id].vw_mappings_arr[mapping_id].virtual_wire_msb = vw_msb;
api_info[unit].vw_container.vw_info_arr[vw_id].vw_mappings_arr[mapping_id].virtual_wire_lsb = vw_lsb;
api_info[unit].vw_container.vw_info_arr[vw_id].vw_mappings_arr[mapping_id].physical_wire_lsb = physical_wire_lsb;
}
}
void dnx_pemladrv_init_vw_info(const int unit, const char* line){
char key_word[MAX_NAME_LENGTH];
char vw_name[MAX_NAME_LENGTH];
int vw_id, nof_mappings, vw_width, start_stage, end_stage;
if (sscanf(line, "%s %d %s %d %d %d %d", key_word, &vw_id, vw_name, &vw_width, &nof_mappings, &start_stage, &end_stage) != VIRTUAL_WIRE_INFO_NOF_FIELDS_TOKEN) {
printf("Bad line format. Skip and continue with next line.\n");
return;
}
else {
strncpy(api_info[unit].vw_container.vw_info_arr[vw_id].virtual_wire_name, vw_name, strlen(vw_name));
api_info[unit].vw_container.vw_info_arr[vw_id].virtual_wire_name[strlen(vw_name)] = '\0';
api_info[unit].vw_container.vw_info_arr[vw_id].width_in_bits = vw_width;
api_info[unit].vw_container.vw_info_arr[vw_id].start_stage = start_stage;
api_info[unit].vw_container.vw_info_arr[vw_id].end_stage = end_stage;
api_info[unit].vw_container.vw_info_arr[vw_id].nof_mappings= nof_mappings;
api_info[unit].vw_container.vw_info_arr[vw_id].vw_mappings_arr = (VirtualWireMappingInfo*)sal_calloc(api_info[unit].vw_container.vw_info_arr[vw_id].vw_mappings_arr, nof_mappings, sizeof(VirtualWireMappingInfo));
}
}
void dnx_pemladrv_init_vw_arr_by_size(const int unit, const char* line){
int nof_vws;
char key_word[MAX_NAME_LENGTH];
sscanf(line, "%s %d ", key_word, &nof_vws);
vr_mapping_info_init(unit, nof_vws);
}
int db_direct_write_command(int unit, const char* write_command);
int db_tcam_write_command(int unit, const char* write_command);
int db_lpm_write_command(int unit, const char* write_command);
int db_em_write_command(int unit, const char* write_command);
int reg_write_command(int unit, const char* write_command);
int program_select_tcam_write_command(int unit, const char* write_command);
int init_dbs_content_and_program_selection_tcams_from_write_commands_file(
int unit,
const char* write_commands_file_name)
{
FILE* fp = NULL;
int ret_val = 0;
char line[512];
int line_no = 1;
int in_comment = 0;
if (NULL == (fp = fopen(write_commands_file_name, "r")))
return -1;
while((fgets(line, sizeof(line), fp) != NULL) && (ret_val >= 0)) {
if (strlen(line) == 0) {line_no = line_no + 1; continue;}
if (strstr(line, END_COMMENT) != 0) { in_comment = 0; ++line_no; continue;}
if (strstr(line, START_COMMENT) != 0) { in_comment = 1; ++line_no; continue;}
if (in_comment) { ++line_no; continue;}
if (strncmp(line, KEYWORD_DB_DIRECT_WRITE_COMMAND, KEYWORD_DB_DIRECT_WRITE_COMMAND_SIZE) == 0) { db_direct_write_command(unit, line); ++line_no; continue; }
if (strncmp(line, KEYWORD_DB_TCAM_WRITE_COMMAND, KEYWORD_DB_TCAM_WRITE_COMMAND_SIZE) == 0) { db_tcam_write_command(unit, line); ++line_no; continue; }
if (strncmp(line, KEYWORD_DB_LPM_WRITE_COMMAND, KEYWORD_DB_LPM_WRITE_COMMAND_SIZE) == 0) { db_lpm_write_command(unit, line); ++line_no; continue; }
if (strncmp(line, KEYWORD_DB_EM_WRITE_COMMAND, KEYWORD_DB_EM_WRITE_COMMAND_SIZE) == 0) { db_em_write_command(unit, line); ++line_no; continue; }
if (strncmp(line, KEYWORD_REG_WRITE_COMMAND, KEYWORD_REG_WRITE_COMMAND_SIZE) == 0) { reg_write_command(unit, line); ++line_no; continue; }
if (strncmp(line, KEYWORD_PROGRAM_SELECT_CONFIG_WRITE_COMMAND, KEYWORD_PROGRAM_SELECT_CONFIG_WRITE_COMMAND_SIZE) == 0) { program_select_tcam_write_command(unit, line); ++line_no; continue; }
++line_no;
}
fclose(fp);
return ret_val;
}
int db_direct_write_command(
int unit,
const char* write_command)
{
char key_word[MAX_NAME_LENGTH], res_value_s[MAX_NAME_LENGTH] ;
unsigned int db_id, row_ndx, res_len;
unsigned int* res_value;
pemladrv_mem_t* result_mem_access;
unsigned int nof_fields_in_res;
const FieldBitRange* bit_range;
int ret_val = 0;
if (sscanf( write_command, "%s %u %u %s", key_word, &db_id, &row_ndx, res_value_s) != 4) {
printf("Bad ucode line format. Skip and continue with next line\n.");
return -1;
} else {
res_value = hexstr2uints(res_value_s, &res_len);
}
nof_fields_in_res = api_info[unit].db_direct_container.db_direct_info_arr[db_id].nof_fields;
bit_range = api_info[unit].db_direct_container.db_direct_info_arr[db_id].field_bit_range_arr;
ret_val |= dnx_pemladrv_allocate_pemladrv_mem_struct(&result_mem_access, nof_fields_in_res, bit_range);
dnx_set_pem_mem_accesss_fldbuf(0, res_value, bit_range, result_mem_access);
ret_val |= pemladrv_direct_write(0, db_id, row_ndx, result_mem_access);
dnx_pemladrv_free_pemladrv_mem_struct(&result_mem_access);
sal_free(res_value);
return ret_val;
}
int db_tcam_write_command(
int unit,
const char* write_command)
{
char key_word[MAX_NAME_LENGTH], key_value_s[MAX_NAME_LENGTH], mask_value_s[MAX_NAME_LENGTH], res_value_s[MAX_NAME_LENGTH] ;
unsigned int db_id, row_ndx, len;
unsigned int *key_value, *mask_value, *res_value;
pemladrv_mem_t *key_mem_access, *mask_mem_access, *result_mem_access, *valid_mem_access;
unsigned int nof_fields_in_res, nof_fields_in_key;
const FieldBitRange* key_bit_range, *result_bit_range;
FieldBitRange valid_bit_range;
int ret_val = 0;
const unsigned int valid_bit = 1;
valid_bit_range.lsb = 0;
valid_bit_range.msb = 0;
valid_bit_range.is_field_mapped = 1;
if (sscanf( write_command, "%s %u %u %s %s %s", key_word, &db_id, &row_ndx, key_value_s, mask_value_s, res_value_s) != 6) {
printf("Bad ucode line format. Skip and continue with next line\n.");
return -1;
} else {
key_value = hexstr2uints(key_value_s, &len);
mask_value = hexstr2uints(mask_value_s, &len);
res_value = hexstr2uints(res_value_s, &len);
}
nof_fields_in_key = api_info[unit].db_tcam_container.db_tcam_info_arr[db_id].nof_fields_in_key;
nof_fields_in_res = api_info[unit].db_tcam_container.db_tcam_info_arr[db_id].nof_fields_in_result;
key_bit_range = api_info[unit].db_tcam_container.db_tcam_info_arr[db_id].key_field_bit_range_arr;
result_bit_range = api_info[unit].db_tcam_container.db_tcam_info_arr[db_id].result_field_bit_range_arr;
ret_val |= dnx_pemladrv_allocate_pemladrv_mem_struct(&key_mem_access, nof_fields_in_key, key_bit_range);
ret_val |= dnx_pemladrv_allocate_pemladrv_mem_struct(&mask_mem_access, nof_fields_in_key, key_bit_range);
ret_val |= dnx_pemladrv_allocate_pemladrv_mem_struct(&result_mem_access, nof_fields_in_res, result_bit_range);
ret_val |= dnx_pemladrv_allocate_pemladrv_mem_struct(&valid_mem_access, 1, &valid_bit_range);
dnx_set_pem_mem_accesss_fldbuf(0, key_value, key_bit_range, key_mem_access);
dnx_set_pem_mem_accesss_fldbuf(0, mask_value, key_bit_range, mask_mem_access);
dnx_set_pem_mem_accesss_fldbuf(0, res_value, result_bit_range, result_mem_access);
dnx_set_pem_mem_accesss_fldbuf(0, &valid_bit, &valid_bit_range, valid_mem_access);
ret_val |= pemladrv_tcam_write(0, db_id, row_ndx, key_mem_access, mask_mem_access, valid_mem_access, result_mem_access);
dnx_pemladrv_free_pemladrv_mem_struct(&key_mem_access);
dnx_pemladrv_free_pemladrv_mem_struct(&mask_mem_access);
dnx_pemladrv_free_pemladrv_mem_struct(&result_mem_access);
dnx_pemladrv_free_pemladrv_mem_struct(&valid_mem_access);
sal_free(key_value);
sal_free(mask_value);
sal_free(res_value);
return ret_val;
}
int db_lpm_write_command(
int unit,
const char* write_command)
{
char key_word[MAX_NAME_LENGTH], key_value_s[MAX_NAME_LENGTH], res_value_s[MAX_NAME_LENGTH] ;
unsigned int db_id, nof_bits_in_prefix, len;
unsigned int *key_value, *res_value;
pemladrv_mem_t *key_mem_access, *result_mem_access;
unsigned int nof_fields_in_res, nof_fields_in_key;
const FieldBitRange* key_bit_range, *result_bit_range;
int ret_val = 0;
int index;
if (sscanf( write_command, "%s %u %s %u %s", key_word, &db_id, key_value_s, &nof_bits_in_prefix, res_value_s) != 5) {
printf("Bad ucode line format. Skip and continue with next line\n.");
return -1;
} else {
key_value = hexstr2uints(key_value_s, &len);
res_value = hexstr2uints(res_value_s, &len);
}
nof_fields_in_key = api_info[unit].db_lpm_container.db_lpm_info_arr[db_id].logical_lpm_info.nof_fields_in_key;
nof_fields_in_res = api_info[unit].db_lpm_container.db_lpm_info_arr[db_id].logical_lpm_info.nof_fields_in_result;
key_bit_range = api_info[unit].db_lpm_container.db_lpm_info_arr[db_id].logical_lpm_info.key_field_bit_range_arr;
result_bit_range = api_info[unit].db_lpm_container.db_lpm_info_arr[db_id].logical_lpm_info.result_field_bit_range_arr;
ret_val |= dnx_pemladrv_allocate_pemladrv_mem_struct(&key_mem_access, nof_fields_in_key, key_bit_range);
ret_val |= dnx_pemladrv_allocate_pemladrv_mem_struct(&result_mem_access, nof_fields_in_res, result_bit_range);
dnx_set_pem_mem_accesss_fldbuf(0, key_value, key_bit_range, key_mem_access);
dnx_set_pem_mem_accesss_fldbuf(0, res_value, result_bit_range, result_mem_access);
ret_val |= pemladrv_lpm_insert(0, db_id, key_mem_access, nof_bits_in_prefix, result_mem_access, &index);
dnx_pemladrv_free_pemladrv_mem_struct(&key_mem_access);
dnx_pemladrv_free_pemladrv_mem_struct(&result_mem_access);
sal_free(key_value);
sal_free(res_value);
return ret_val;
}
int db_em_write_command(
int unit,
const char* write_command)
{
char key_word[MAX_NAME_LENGTH], key_value_s[MAX_NAME_LENGTH], res_value_s[MAX_NAME_LENGTH] ;
unsigned int db_id, len;
unsigned int *key_value, *res_value;
pemladrv_mem_t *key_mem_access, *result_mem_access;
unsigned int nof_fields_in_res, nof_fields_in_key;
const FieldBitRange* key_bit_range, *result_bit_range;
int ret_val = 0;
int index;
if (sscanf( write_command, "%s %u %s %s", key_word, &db_id, key_value_s, res_value_s) != 4) {
printf("Bad ucode line format. Skip and continue with next line\n.");
return -1;
} else {
key_value = hexstr2uints(key_value_s, &len);
res_value = hexstr2uints(res_value_s, &len);
}
nof_fields_in_key = api_info[unit].db_em_container.db_em_info_arr[db_id].logical_em_info.nof_fields_in_key;
nof_fields_in_res = api_info[unit].db_em_container.db_em_info_arr[db_id].logical_em_info.nof_fields_in_result;
key_bit_range = api_info[unit].db_em_container.db_em_info_arr[db_id].logical_em_info.key_field_bit_range_arr;
result_bit_range = api_info[unit].db_em_container.db_em_info_arr[db_id].logical_em_info.result_field_bit_range_arr;
ret_val |= dnx_pemladrv_allocate_pemladrv_mem_struct(&key_mem_access, nof_fields_in_key, key_bit_range);
ret_val |= dnx_pemladrv_allocate_pemladrv_mem_struct(&result_mem_access, nof_fields_in_res, result_bit_range);
dnx_set_pem_mem_accesss_fldbuf(0, key_value, key_bit_range, key_mem_access);
dnx_set_pem_mem_accesss_fldbuf(0, res_value, result_bit_range, result_mem_access);
ret_val |= pemladrv_em_insert(0, db_id, key_mem_access, result_mem_access, &index);
dnx_pemladrv_free_pemladrv_mem_struct(&key_mem_access);
dnx_pemladrv_free_pemladrv_mem_struct(&result_mem_access);
sal_free(key_value);
sal_free(res_value);
return ret_val;
}
int reg_write_command(
int unit, const char* write_command)
{
char key_word[MAX_NAME_LENGTH], reg_value_s[MAX_NAME_LENGTH] ;
unsigned int reg_id, len;
unsigned int* reg_data;
pemladrv_mem_t* data_mem_access;
unsigned int nof_fields_in_res;
const FieldBitRange* bit_range;
int ret_val = 0;
if (sscanf( write_command, "%s %u %s", key_word, ®_id, reg_value_s) != 3) {
printf("Bad ucode line format. Skip and continue with next line\n.");
return -1;
} else {
reg_data = hexstr2uints(reg_value_s, &len);
}
nof_fields_in_res = api_info[unit].reg_container.reg_info_arr[reg_id].nof_fields;
bit_range = api_info[unit].reg_container.reg_info_arr[reg_id].reg_field_bit_range_arr;
ret_val |= dnx_pemladrv_allocate_pemladrv_mem_struct(&data_mem_access, nof_fields_in_res, bit_range);
dnx_set_pem_mem_accesss_fldbuf(0, reg_data, bit_range, data_mem_access);
ret_val |= pemladrv_reg_write(0, reg_id, data_mem_access);
dnx_pemladrv_free_pemladrv_mem_struct(&data_mem_access);
sal_free(reg_data);
return ret_val;
}
int program_select_tcam_write_command(
int unit,
const char* write_command)
{
char key_word[MAX_NAME_LENGTH], mem_address_s[MAX_NAME_LENGTH], entry_val_s[MAX_NAME_LENGTH] ;
unsigned int block_id, value_length, pem_mem_address_val, row_ndx;
unsigned int* data_value;
int ret_val = 0;
phy_mem_t mem_write;
if (sscanf( write_command, "%s %s %u %s", key_word, mem_address_s, &row_ndx, entry_val_s) != 4) {
printf("Bad ucode line format. Skip and continue with next line\n.");
return -1;
} else {
pem_mem_address_val = hexstr2addr(mem_address_s, &block_id);
data_value = hexstr2uints(entry_val_s, &value_length);
}
mem_write.block_identifier = block_id;
mem_write.mem_address = pem_mem_address_val + row_ndx;
mem_write.mem_width_in_bits = value_length;
mem_write.reserve = 0;
mem_write.is_reg = 0;
#ifdef BCM_DNX_SUPPORT
ret_val = pem_write(unit, &mem_write, 0, data_value);
#endif
sal_free(data_value);
return ret_val;
}
| 48.909367 | 275 | 0.746726 |
1f5a1a92d0c2b35bc83966e5d8c6d81ad0f4109e | 1,465 | h | C | DarkSpace/GadgetScript.h | SnipeDragon/darkspace | b6a1fa0a29d3559b158156e7b96935bd0a832ee3 | [
"MIT"
] | 1 | 2016-05-22T21:28:29.000Z | 2016-05-22T21:28:29.000Z | DarkSpace/GadgetScript.h | SnipeDragon/darkspace | b6a1fa0a29d3559b158156e7b96935bd0a832ee3 | [
"MIT"
] | null | null | null | DarkSpace/GadgetScript.h | SnipeDragon/darkspace | b6a1fa0a29d3559b158156e7b96935bd0a832ee3 | [
"MIT"
] | null | null | null | /*
GadgetScript.h
(c)2000 Palestar Inc, Richard Lyle
*/
#ifndef GADGETSCRIPT_H
#define GADGETSCRIPT_H
#include "Resource/Text.h"
#include "NounGadget.h"
#include "GameDll.h"
//----------------------------------------------------------------------------
class DLL GadgetScript : public NounGadget
{
public:
DECLARE_WIDGET_CLASS();
DECLARE_PROPERTY_LIST();
// Construction
GadgetScript();
// Noun interface
void initialize();
// NounGadget interface
Type type() const; // get gadget type
dword hotkey() const; // gadget hotkey
CharString status() const; // status of the gadget (displayed on the icon)
CharString description() const; // get description of this gadget
int useModeCount() const; // how many different modes are available
int useMode() const; // what is the current user mode
bool useTarget() const;
void useMode( int mode ); // set use mode
bool usable( Noun * pTarget,
bool shift ) const; // can gadget be used on target
void use( dword when, Noun * pTarget,
bool shift); // use gadget
// Mutators
void loadScripts();
private:
// Data
int m_Mode;
// non-serialized
Array< Text::Ref > m_Scripts;
// Helpers
Text * getScript() const;
};
//----------------------------------------------------------------------------
#endif
//----------------------------------------------------------------------------
// EOF
| 23.629032 | 82 | 0.545392 |
875bef94674a2b5ec781e1ef8161f401b23dcedd | 910 | h | C | CompilerSource/Parser/SyntaxAnalyzer.h | sampad1370/SimpleCompiler | 9b2488e761d150303de6e656a60444ac6d111bfd | [
"MIT"
] | null | null | null | CompilerSource/Parser/SyntaxAnalyzer.h | sampad1370/SimpleCompiler | 9b2488e761d150303de6e656a60444ac6d111bfd | [
"MIT"
] | null | null | null | CompilerSource/Parser/SyntaxAnalyzer.h | sampad1370/SimpleCompiler | 9b2488e761d150303de6e656a60444ac6d111bfd | [
"MIT"
] | null | null | null | #pragma once
#include"../Compiler.h"
namespace CompilerPackage
{
class Compiler;
class LexicalAnalyzer;
struct ActionGoto
{
std::string instruction;//! "Si","Ri","Ei","Gi";that "i" is number
};
class SyntaxAnalyser
{
friend class Compiler;
Compiler* m_Comiler = nullptr;
LexicalAnalyzer *m_lexc = nullptr;
::BaseEngine::Core::Array::HashTable<std::string, SymbolsTable>* m_TokenTable = nullptr; // a pointer to m_TokenTable in Compiler class
/* parser variable */
std::string** m_ParseTable;
::BaseEngine::Core::Array::Map<std::string, int> m_ColumnMap;
::BaseEngine::Core::Array::DArrayPointer<std::pair<std::string, std::pair<int,std::string>>> m_Production;
void LoadParseTable(char* ConfigFile);
::BaseEngine::Core::Tree::tree<DataToken> m_ParseTree;
public:
SyntaxAnalyser(Compiler* ref, char* ConfigFile = "ParserCofig.xml");
~SyntaxAnalyser();
void* Parse();
};
} | 29.354839 | 137 | 0.714286 |
c6f1c4e8291ce88a63f0fc69a07ef34ed52fb5f2 | 548 | h | C | include/il2cpp/System/Collections/Generic/List/Enumerator_NoteIcon_.h | martmists-gh/BDSP | d6326c5d3ad9697ea65269ed47aa0b63abac2a0a | [
"MIT"
] | 1 | 2022-01-15T20:20:27.000Z | 2022-01-15T20:20:27.000Z | include/il2cpp/System/Collections/Generic/List/Enumerator_NoteIcon_.h | martmists-gh/BDSP | d6326c5d3ad9697ea65269ed47aa0b63abac2a0a | [
"MIT"
] | null | null | null | include/il2cpp/System/Collections/Generic/List/Enumerator_NoteIcon_.h | martmists-gh/BDSP | d6326c5d3ad9697ea65269ed47aa0b63abac2a0a | [
"MIT"
] | null | null | null | #pragma once
#include "il2cpp.h"
void System_Collections_Generic_List_Enumerator_NoteIcon___Dispose (System_Collections_Generic_List_Enumerator_NoteIcon__o __this, const MethodInfo* method_info);
bool System_Collections_Generic_List_Enumerator_NoteIcon___MoveNext (System_Collections_Generic_List_Enumerator_NoteIcon__o __this, const MethodInfo* method_info);
Dpr_Contest_NoteIcon_o* System_Collections_Generic_List_Enumerator_NoteIcon___get_Current (System_Collections_Generic_List_Enumerator_NoteIcon__o __this, const MethodInfo* method_info);
| 68.5 | 185 | 0.912409 |
051218bbecefe10e7b2462b5e4339f7d51ac0303 | 1,359 | h | C | DataCollector/mozilla/xulrunner-sdk/include/mozilla/dom/HTMLPictureElement.h | andrasigneczi/TravelOptimiser | b08805f97f0823fd28975a36db67193386aceb22 | [
"Apache-2.0"
] | 1 | 2016-04-20T08:35:44.000Z | 2016-04-20T08:35:44.000Z | DataCollector/mozilla/xulrunner-sdk/include/mozilla/dom/HTMLPictureElement.h | andrasigneczi/TravelOptimiser | b08805f97f0823fd28975a36db67193386aceb22 | [
"Apache-2.0"
] | null | null | null | DataCollector/mozilla/xulrunner-sdk/include/mozilla/dom/HTMLPictureElement.h | andrasigneczi/TravelOptimiser | b08805f97f0823fd28975a36db67193386aceb22 | [
"Apache-2.0"
] | null | null | null | /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set ts=8 sts=2 et sw=2 tw=80: */
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef mozilla_dom_HTMLPictureElement_h
#define mozilla_dom_HTMLPictureElement_h
#include "mozilla/Attributes.h"
#include "nsIDOMHTMLPictureElement.h"
#include "nsGenericHTMLElement.h"
#include "mozilla/dom/HTMLUnknownElement.h"
namespace mozilla {
namespace dom {
class HTMLPictureElement final : public nsGenericHTMLElement,
public nsIDOMHTMLPictureElement
{
public:
explicit HTMLPictureElement(already_AddRefed<mozilla::dom::NodeInfo>& aNodeInfo);
// nsISupports
NS_DECL_ISUPPORTS_INHERITED
// nsIDOMHTMLPictureElement
NS_DECL_NSIDOMHTMLPICTUREELEMENT
virtual nsresult Clone(mozilla::dom::NodeInfo* aNodeInfo, nsINode** aResult) const override;
virtual void RemoveChildAt(uint32_t aIndex, bool aNotify) override;
static bool IsPictureEnabled();
protected:
virtual ~HTMLPictureElement();
virtual JSObject* WrapNode(JSContext* aCx, JS::Handle<JSObject*> aGivenProto) override;
};
} // namespace dom
} // namespace mozilla
#endif // mozilla_dom_HTMLPictureElement_h
| 29.543478 | 94 | 0.746873 |
dc66ca90947a3867be507c4445aa8673c7048074 | 241 | h | C | ZT_IM_SDK/Classes/SDKKit/Category/UIImage+ZTKit.h | ztthgly/mobile-ios-im-sdk | ac6fe077f43dfaa043efa688f835106aecfabf0c | [
"MIT"
] | 2 | 2018-07-31T06:51:18.000Z | 2018-08-01T08:09:04.000Z | ZT_IM_SDK/Classes/SDKKit/Category/UIImage+ZTKit.h | ztthgly/mobile-ios-im-sdk | ac6fe077f43dfaa043efa688f835106aecfabf0c | [
"MIT"
] | 1 | 2019-03-05T06:00:21.000Z | 2019-04-19T02:52:49.000Z | ZT_IM_SDK/Classes/SDKKit/Category/UIImage+ZTKit.h | ztthgly/mobile-ios-im-sdk | ac6fe077f43dfaa043efa688f835106aecfabf0c | [
"MIT"
] | 1 | 2021-01-07T05:51:06.000Z | 2021-01-07T05:51:06.000Z | //
// UIImage+ZTKit.h
// ZT_IM_SDK_Example
//
// Created by Deemo on 2018/5/22.
// Copyright © 2018年 ICSOC. All rights reserved.
//
#import <UIKit/UIKit.h>
@interface UIImage (ZTKit)
- (UIImage *)imageByResizeToSize:(CGSize)size;
@end
| 17.214286 | 49 | 0.688797 |
6b0561b8d7b64929d4c352e5be48746cfd2c0316 | 3,177 | c | C | main/graphics.c | pr8x/esp32_led_panel_I2S | 30efa75df9d862fb1776a61321b2ab66ebc3e57b | [
"Apache-2.0"
] | 21 | 2019-04-11T22:16:17.000Z | 2022-01-25T12:44:40.000Z | main/graphics.c | mutex36/esp32_led_panel_i2c | 30efa75df9d862fb1776a61321b2ab66ebc3e57b | [
"Apache-2.0"
] | 2 | 2018-08-22T17:35:18.000Z | 2019-02-28T20:51:59.000Z | main/graphics.c | mutex36/esp32_led_panel_i2c | 30efa75df9d862fb1776a61321b2ab66ebc3e57b | [
"Apache-2.0"
] | 8 | 2019-04-08T06:15:08.000Z | 2021-06-11T09:05:46.000Z | #include "graphics.h"
#include "driver.h"
#include "gamma_correction.h"
#include <string.h> //memset()
static unsigned char* buffer;
static unsigned char* fb;
static unsigned char* bb;
static TaskHandle_t task_handle;
static const char* LOG_TAG = "Graphics";
void graphics_init() {
driver_init();
fs_init();
//combined back and front buffer
buffer = (unsigned char*)malloc(2 * BUFFER_SIZE);
assert(buffer && "failed to allocate front/back buffer");
memset(buffer, 0, 2 * BUFFER_SIZE);
bb = buffer;
fb = buffer + BUFFER_SIZE;
ESP_LOGI(LOG_TAG, "front/back buffer allocated: fb: %d bb: %d", (int)fb, (int)bb);
driver_run();
driver_set_buffer(fb);
}
void graphics_shutdown() {
driver_shutdown();
graphics_stop();
free(buffer);
fs_shutdown();
ESP_LOGI(LOG_TAG, "shutdown");
}
void graphics_swap_buffer() {
unsigned char* tmp = bb;
bb = fb;
fb = tmp;
}
void sampler_load(sampler_t* sampler) {
ESP_LOGI(LOG_TAG, "Loading sampler %s", sampler->file);
sampler->_gif = gd_open_gif(sampler->file);
assert(sampler->_gif && "gd_open_gif() failed");
sampler->_buffer = malloc(sampler->_gif->width * sampler->_gif->height * 3);
assert(sampler->_buffer && "malloc() failed");
}
void sampler_unload(sampler_t* sampler) {
free(sampler->_buffer);
gd_close_gif(sampler->_gif);
ESP_LOGI(LOG_TAG, "Unloaded sampler %s", sampler->file);
}
void sampler_tick(sampler_t* sampler) {
if (gd_get_frame(sampler->_gif)) {
gd_render_frame(sampler->_gif, sampler->_buffer);
} else if (sampler->loop) {
gd_rewind(sampler->_gif);
sampler_tick(sampler);
}
vTaskDelay(sampler->anim_speed / portTICK_PERIOD_MS); //animation delay
}
void module_task(module_t* module) {
ESP_LOGI(LOG_TAG, "task running on core %d", xPortGetCoreID());
if (module->sampler)
sampler_load(module->sampler);
for(;;) {
if (ulTaskNotifyTake(pdTRUE, 0))
break;
if (module->sampler)
sampler_tick(module->sampler);
for (int y = 0; y < 32; ++y) {
for (int x = 0; x < 64; ++x) {
vec2 uv = { x / 64.0f, y / 32.0f };
vec4 out = { 0.0f, 0.0f, 0.0f, 1.0f };
(*((module_func_t)module->fn))(&uv, &out, module->sampler);
unsigned char* p = bb + ((x + y * 64) * 3);
float alpha = out.w * 255;
p[0] = gamma8[(int)(out.x * alpha)];
p[1] = gamma8[(int)(out.y * alpha)];
p[2] = gamma8[(int)(out.z * alpha)];
}
}
driver_set_buffer(fb);
graphics_swap_buffer();
}
if (module->sampler)
sampler_unload(module->sampler);
ESP_LOGI(LOG_TAG, "task stopped");
vTaskDelete(NULL);
}
void graphics_run(module_t* module) {
graphics_stop();
xTaskCreatePinnedToCore(module_task,
"module_task", 10000, (void*) module, 80, &task_handle, 1);
}
void graphics_stop() {
if (task_handle)
xTaskNotifyGive(task_handle);
//TODO: actually wait for task to end
vTaskDelay(200 / portTICK_PERIOD_MS);
} | 25.829268 | 86 | 0.600881 |
8ccbbdabdc48603ac34960e5364ecc6d534c8157 | 1,211 | h | C | NFComm/NFNoSqlPlugin/NFCNoSqlModule.h | zh423328/NFServer | 2b94df566a2552366a81bd4c48d6552306b07fc3 | [
"Apache-2.0"
] | 1 | 2021-07-08T05:33:50.000Z | 2021-07-08T05:33:50.000Z | NFComm/NFNoSqlPlugin/NFCNoSqlModule.h | zh423328/NFServer | 2b94df566a2552366a81bd4c48d6552306b07fc3 | [
"Apache-2.0"
] | null | null | null | NFComm/NFNoSqlPlugin/NFCNoSqlModule.h | zh423328/NFServer | 2b94df566a2552366a81bd4c48d6552306b07fc3 | [
"Apache-2.0"
] | 1 | 2021-07-08T05:34:59.000Z | 2021-07-08T05:34:59.000Z | // -------------------------------------------------------------------------
// @FileName : NFCNoSqlModule.h
// @Author : LvSheng.Huang
// @Date : 2013-10-11
// @Module : NFCNoSqlModule
//
// -------------------------------------------------------------------------
#ifndef NFC_DATANOSQL_MODULE_H
#define NFC_DATANOSQL_MODULE_H
#include "NFCNoSqlDriver.h"
#include "NFComm/NFPluginModule/NFPlatform.h"
#include "NFComm/NFPluginModule/NFIPluginManager.h"
#include "NFComm/NFPluginModule/NFINoSqlModule.h"
class NFCNoSqlModule
: public NFINoSqlModule
{
public:
NFCNoSqlModule(NFIPluginManager* p);
virtual ~NFCNoSqlModule();
virtual bool Init();
virtual bool Shut();
virtual bool Execute(const float fLasFrametime, const float fStartedTime);
virtual bool AfterInit();
virtual bool ConnectSql(const std::string& strIP);
virtual bool ConnectSql(const std::string& strIP, const int nPort, const std::string& strPass);
virtual NFINoSqlDriver* GetDriver()
{
return m_pNoSqlDriver;
}
protected:
NFINoSqlDriver* m_pNoSqlDriver;//player property
};
#endif | 27.522727 | 97 | 0.582164 |
bcbd4dfd9c3a0f24b20c6f2101a66098065bd364 | 314 | h | C | test/core/ControllerTestCommand.h | saadshams/puremvc-c-multicore-framework | 938b9fc8e1d1968ee3d5fe2249a2e91c9c67d1c4 | [
"BSD-3-Clause"
] | null | null | null | test/core/ControllerTestCommand.h | saadshams/puremvc-c-multicore-framework | 938b9fc8e1d1968ee3d5fe2249a2e91c9c67d1c4 | [
"BSD-3-Clause"
] | null | null | null | test/core/ControllerTestCommand.h | saadshams/puremvc-c-multicore-framework | 938b9fc8e1d1968ee3d5fe2249a2e91c9c67d1c4 | [
"BSD-3-Clause"
] | null | null | null | #ifndef PUREMVC_CONTROLLERTESTCOMMAND_H
#define PUREMVC_CONTROLLERTESTCOMMAND_H
#include "interfaces/SimpleCommand.h"
/**
* A SimpleCommand struct used by ControllerTest.
*
* @see ControllerTest
* @see ControllerTestVO
*/
SimpleCommand *NewControllerTestCommand();
#endif //PUREMVC_CONTROLLERTESTCOMMAND_H
| 20.933333 | 49 | 0.808917 |
efd8d400232f415e79773cb9fc7d34afdc8212b8 | 6,356 | h | C | System/Library/CoreServices/SpringBoard/PrivateHeaders/SBLockScreenSettings.h | lechium/iPhoneOS_12.1.1_Headers | aac688b174273dfcbade13bab104461f463db772 | [
"MIT"
] | 12 | 2019-06-02T02:42:41.000Z | 2021-04-13T07:22:20.000Z | System/Library/CoreServices/SpringBoard/PrivateHeaders/SBLockScreenSettings.h | lechium/iPhoneOS_12.1.1_Headers | aac688b174273dfcbade13bab104461f463db772 | [
"MIT"
] | null | null | null | System/Library/CoreServices/SpringBoard/PrivateHeaders/SBLockScreenSettings.h | lechium/iPhoneOS_12.1.1_Headers | aac688b174273dfcbade13bab104461f463db772 | [
"MIT"
] | 3 | 2019-06-11T02:46:10.000Z | 2019-12-21T14:58:16.000Z | //
// Generated by class-dump 3.5 (64 bit).
//
// class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2013 by Steve Nygard.
//
#import "SBUISettings.h"
@class NSString, SBAnimationSettings, SBBounceSettings, SBDashBoardScrollModifierSettings, SBHorizontalScrollFailureRecognizerSettings, SBLockScreenMesaSettings, SBLockScreenPasscodeSettings;
@interface SBLockScreenSettings : SBUISettings
{
_Bool _showNowPlaying; // 8 = 0x8
_Bool _showContinuityIcon; // 9 = 0x9
_Bool _showUserPicture; // 10 = 0xa
_Bool _showLogoutButton; // 11 = 0xb
_Bool _showThermalTrap; // 12 = 0xc
_Bool _showBlockedUI; // 13 = 0xd
_Bool _showResetRestore; // 14 = 0xe
_Bool _showEmergencyDialer; // 15 = 0xf
_Bool _showDisconnectAccessory; // 16 = 0x10
_Bool _alwaysPutPluginsBelowScrollView; // 17 = 0x11
_Bool _killsInsecureDrawingApps; // 18 = 0x12
int _continuityIconType; // 20 = 0x14
SBBounceSettings *_verticalBounceSettings; // 24 = 0x18
SBBounceSettings *_horizontalBounceSettings; // 32 = 0x20
SBLockScreenPasscodeSettings *_passcodeSettings; // 40 = 0x28
SBLockScreenMesaSettings *_mesaSettings; // 48 = 0x30
SBHorizontalScrollFailureRecognizerSettings *_horizontalScrollFailureRecognizerSettings; // 56 = 0x38
SBDashBoardScrollModifierSettings *_dashBoardScrollModifierSettings; // 64 = 0x40
SBAnimationSettings *_unlockToPhoneWallpaperOutSettings; // 72 = 0x48
SBAnimationSettings *_unlockToPhoneWallpaperInSettings; // 80 = 0x50
SBAnimationSettings *_unlockWallpaperOutSettings; // 88 = 0x58
SBAnimationSettings *_unlockWallpaperInSettings; // 96 = 0x60
double _mainToCameraViewSlideCompletionPercentage; // 104 = 0x68
double _mainToTodayViewSlideCompletionPercentage; // 112 = 0x70
double _unlockSlideForIdleTimerDisabledPercentage; // 120 = 0x78
double _unlockSlideForIdleTimerDisabledPercentageIPad; // 128 = 0x80
double _notificationScrollForIdleTimerDisabledOffset; // 136 = 0x88
double _notificationScrollForIdleTimerDisabledOffsetIPad; // 144 = 0x90
double _appGrabberSlideUpVelocityThreshold; // 152 = 0x98
double _unlockSwipeWallpaperAlpha; // 160 = 0xa0
NSString *_lockScreenCode; // 168 = 0xa8
}
+ (void)_restartSpringBoard; // IMP=0x000000010013bb38
+ (id)settingsControllerModule; // IMP=0x000000010013a0e0
@property(copy, nonatomic) NSString *lockScreenCode; // @synthesize lockScreenCode=_lockScreenCode;
@property _Bool killsInsecureDrawingApps; // @synthesize killsInsecureDrawingApps=_killsInsecureDrawingApps;
@property _Bool alwaysPutPluginsBelowScrollView; // @synthesize alwaysPutPluginsBelowScrollView=_alwaysPutPluginsBelowScrollView;
@property double unlockSwipeWallpaperAlpha; // @synthesize unlockSwipeWallpaperAlpha=_unlockSwipeWallpaperAlpha;
@property double appGrabberSlideUpVelocityThreshold; // @synthesize appGrabberSlideUpVelocityThreshold=_appGrabberSlideUpVelocityThreshold;
@property double notificationScrollForIdleTimerDisabledOffsetIPad; // @synthesize notificationScrollForIdleTimerDisabledOffsetIPad=_notificationScrollForIdleTimerDisabledOffsetIPad;
@property double notificationScrollForIdleTimerDisabledOffset; // @synthesize notificationScrollForIdleTimerDisabledOffset=_notificationScrollForIdleTimerDisabledOffset;
@property double unlockSlideForIdleTimerDisabledPercentageIPad; // @synthesize unlockSlideForIdleTimerDisabledPercentageIPad=_unlockSlideForIdleTimerDisabledPercentageIPad;
@property double unlockSlideForIdleTimerDisabledPercentage; // @synthesize unlockSlideForIdleTimerDisabledPercentage=_unlockSlideForIdleTimerDisabledPercentage;
@property double mainToTodayViewSlideCompletionPercentage; // @synthesize mainToTodayViewSlideCompletionPercentage=_mainToTodayViewSlideCompletionPercentage;
@property double mainToCameraViewSlideCompletionPercentage; // @synthesize mainToCameraViewSlideCompletionPercentage=_mainToCameraViewSlideCompletionPercentage;
@property(retain) SBAnimationSettings *unlockWallpaperInSettings; // @synthesize unlockWallpaperInSettings=_unlockWallpaperInSettings;
@property(retain) SBAnimationSettings *unlockWallpaperOutSettings; // @synthesize unlockWallpaperOutSettings=_unlockWallpaperOutSettings;
@property(retain) SBAnimationSettings *unlockToPhoneWallpaperInSettings; // @synthesize unlockToPhoneWallpaperInSettings=_unlockToPhoneWallpaperInSettings;
@property(retain) SBAnimationSettings *unlockToPhoneWallpaperOutSettings; // @synthesize unlockToPhoneWallpaperOutSettings=_unlockToPhoneWallpaperOutSettings;
@property(retain) SBDashBoardScrollModifierSettings *dashBoardScrollModifierSettings; // @synthesize dashBoardScrollModifierSettings=_dashBoardScrollModifierSettings;
@property(retain) SBHorizontalScrollFailureRecognizerSettings *horizontalScrollFailureRecognizerSettings; // @synthesize horizontalScrollFailureRecognizerSettings=_horizontalScrollFailureRecognizerSettings;
@property(retain) SBLockScreenMesaSettings *mesaSettings; // @synthesize mesaSettings=_mesaSettings;
@property(retain) SBLockScreenPasscodeSettings *passcodeSettings; // @synthesize passcodeSettings=_passcodeSettings;
@property(retain) SBBounceSettings *horizontalBounceSettings; // @synthesize horizontalBounceSettings=_horizontalBounceSettings;
@property(retain) SBBounceSettings *verticalBounceSettings; // @synthesize verticalBounceSettings=_verticalBounceSettings;
@property _Bool showDisconnectAccessory; // @synthesize showDisconnectAccessory=_showDisconnectAccessory;
@property _Bool showEmergencyDialer; // @synthesize showEmergencyDialer=_showEmergencyDialer;
@property _Bool showResetRestore; // @synthesize showResetRestore=_showResetRestore;
@property _Bool showBlockedUI; // @synthesize showBlockedUI=_showBlockedUI;
@property _Bool showThermalTrap; // @synthesize showThermalTrap=_showThermalTrap;
@property _Bool showLogoutButton; // @synthesize showLogoutButton=_showLogoutButton;
@property _Bool showUserPicture; // @synthesize showUserPicture=_showUserPicture;
@property int continuityIconType; // @synthesize continuityIconType=_continuityIconType;
@property _Bool showContinuityIcon; // @synthesize showContinuityIcon=_showContinuityIcon;
@property _Bool showNowPlaying; // @synthesize showNowPlaying=_showNowPlaying;
- (void).cxx_destruct; // IMP=0x000000010013c018
- (void)setDefaultValues; // IMP=0x0000000100139ca0
@end
| 75.666667 | 206 | 0.839364 |
4011dba11f137a6a258361d465894c717e085504 | 1,008 | h | C | windows/pw5e.official/Chap23/NetTime/resource.h | nnaabbcc/exercise | 255fd32b39473b3d0e7702d4b1a8a97bed2a68f8 | [
"MIT"
] | 1 | 2016-11-23T08:18:08.000Z | 2016-11-23T08:18:08.000Z | windows/pw5e.official/Chap23/NetTime/resource.h | nnaabbcc/exercise | 255fd32b39473b3d0e7702d4b1a8a97bed2a68f8 | [
"MIT"
] | null | null | null | windows/pw5e.official/Chap23/NetTime/resource.h | nnaabbcc/exercise | 255fd32b39473b3d0e7702d4b1a8a97bed2a68f8 | [
"MIT"
] | 1 | 2016-11-23T08:17:34.000Z | 2016-11-23T08:17:34.000Z | //{{NO_DEPENDENCIES}}
// Microsoft Developer Studio generated include file.
// Used by NetTime.rc
//
#define IDC_TEXTOUT 101
#define IDC_SERVER1 1001
#define IDC_SERVER2 1002
#define IDC_SERVER3 1003
#define IDC_SERVER4 1004
#define IDC_SERVER5 1005
#define IDC_SERVER6 1006
#define IDC_SERVER7 1007
#define IDC_SERVER8 1008
#define IDC_SERVER9 1009
#define IDC_SERVER10 1010
#define IDC_SERVER 1011
#define IDC_CLOSE 1012
// Next default values for new objects
//
#ifdef APSTUDIO_INVOKED
#ifndef APSTUDIO_READONLY_SYMBOLS
#define _APS_NEXT_RESOURCE_VALUE 104
#define _APS_NEXT_COMMAND_VALUE 40001
#define _APS_NEXT_CONTROL_VALUE 1013
#define _APS_NEXT_SYMED_VALUE 101
#endif
#endif
| 34.758621 | 54 | 0.561508 |
90e4761cc829755c49bbde227bc8d9b81a689f20 | 201 | h | C | Library/ObjC/CYNBaseComponent/CYNBaseComponent/Classes/View/YTAnimationHeader.h | sch1111878/Awesome-iOS | 3313d5ab8e3ffc547e9096a0e98a8d95bb9d23cb | [
"MIT"
] | null | null | null | Library/ObjC/CYNBaseComponent/CYNBaseComponent/Classes/View/YTAnimationHeader.h | sch1111878/Awesome-iOS | 3313d5ab8e3ffc547e9096a0e98a8d95bb9d23cb | [
"MIT"
] | null | null | null | Library/ObjC/CYNBaseComponent/CYNBaseComponent/Classes/View/YTAnimationHeader.h | sch1111878/Awesome-iOS | 3313d5ab8e3ffc547e9096a0e98a8d95bb9d23cb | [
"MIT"
] | null | null | null | //
// YTAnimationHeader.h
// CYNBaseComponent-CYNBaseComponent
//
// Created by Cyandnow on 2018/7/5.
//
#import <MJRefresh/MJRefresh.h>
@interface YTAnimationHeader : MJRefreshNormalHeader
@end
| 15.461538 | 52 | 0.746269 |
90ec89f4c326be7f655e747c3b605545f37d2301 | 72,532 | c | C | src/storage/gstor/gstor_sys_def.c | opengauss-mirror/DCC | b32ae696df92d2d1d7d261de0153acaa34080588 | [
"MulanPSL-1.0"
] | null | null | null | src/storage/gstor/gstor_sys_def.c | opengauss-mirror/DCC | b32ae696df92d2d1d7d261de0153acaa34080588 | [
"MulanPSL-1.0"
] | null | null | null | src/storage/gstor/gstor_sys_def.c | opengauss-mirror/DCC | b32ae696df92d2d1d7d261de0153acaa34080588 | [
"MulanPSL-1.0"
] | null | null | null | /*
* Copyright (c) 2022 Huawei Technologies Co.,Ltd.
*
* openGauss is licensed under Mulan PSL v2.
* You can use this software according to the terms and conditions of the Mulan PSL v2.
* You may obtain a copy of Mulan PSL v2 at:
*
* http://license.coscl.org.cn/MulanPSL2
*
* THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
* EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
* MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
* See the Mulan PSL v2 for more details.
* -------------------------------------------------------------------------
*
* gstor_sys_def.c
* load instance realization
*
* IDENTIFICATION
* src/storage/gstor/gstor_sys_def.c
*
* -------------------------------------------------------------------------
*/
#include "gstor_sys_def.h"
#include "knl_context.h"
#include "gstor_instance.h"
#ifdef __cplusplus
extern "C" {
#endif
#define DEFAULT_LOG_FILE 3
#define DEFAULT_CTRL_FILE 3
#define DEFAULT_USER_FILE 3
#define DEFAULT_SWAP_FILE 2
static const text_t g_user = { (char*)"SYS", 3 };
static const text_t g_db = { (char*)"DCC_DB", 6 };
// SYS_CONSTRAINT_DEFS
column_def_t g_consdef_cols[] = {
{ { .str = (char*)"USER#", .len = 5 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ { .str = (char*)"TABLE#", .len = 6 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ { .str = (char*)"CONS_NAME", .len = 9 }, GS_TYPE_VARCHAR, 64, GS_FALSE },
{ { .str = (char*)"CONS_TYPE", .len = 9 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ { .str = (char*)"COLS", .len = 4 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ { .str = (char*)"COL_LIST", .len = 8 }, GS_TYPE_VARCHAR, 128, GS_TRUE },
{ { .str = (char*)"IND#", .len = 4 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ { .str = (char*)"REF_USER#", .len = 9 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ { .str = (char*)"REF_TABLE#", .len = 10 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ { .str = (char*)"REF_CONS", .len = 8 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ { .str = (char*)"COND_TEXT", .len = 9 }, GS_TYPE_VARCHAR, 2048, GS_TRUE },
{ { .str = (char*)"COND_DATA", .len = 9 }, GS_TYPE_BINARY, 4096, GS_TRUE },
{ { .str = (char*)"FLAGS", .len = 5 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ { .str = (char*)"REFACT", .len = 6 }, GS_TYPE_INTEGER, 4, GS_TRUE }
};
text_t g_consdef_idx01_cols[] = {
{ .str = (char*)"USER#", .len = 5 },
{ .str = (char*)"TABLE#", .len = 6 }
};
text_t g_consdef_idx02_cols[] = {
{ .str = (char*)"REF_USER#", .len = 9 },
{ .str = (char*)"REF_TABLE#", .len = 10 }
};
text_t g_consdef_idx03_cols[] = {
{.str = (char*)"USER#", .len = 5 },
{.str = (char*)"CONS_NAME", .len = 9 }
};
#define CONSDEF_COL_COUNT (sizeof(g_consdef_cols) / sizeof(column_def_t))
#define CONSDEF_IDX01_COL_COUNT (sizeof(g_consdef_idx01_cols) / sizeof(text_t))
#define CONSDEF_IDX02_COL_COUNT (sizeof(g_consdef_idx02_cols) / sizeof(text_t))
#define CONSDEF_IDX03_COL_COUNT (sizeof(g_consdef_idx03_cols) / sizeof(text_t))
static index_def_t g_consdef_indexes[] = {
{ {.str = (char*)"IX_CONSDEF$001", .len = 14 }, g_consdef_idx01_cols, CONSDEF_IDX01_COL_COUNT, GS_FALSE },
{ {.str = (char*)"IX_CONSDEF$002", .len = 14 }, g_consdef_idx02_cols, CONSDEF_IDX02_COL_COUNT, GS_FALSE },
{ {.str = (char*)"IX_CONSDEF$003", .len = 14 }, g_consdef_idx03_cols, CONSDEF_IDX03_COL_COUNT, GS_TRUE }
};
// SYS_GARBAGE_SEGMENTS
column_def_t g_garbage_segments_cols[] = {
{ { .str = (char*)"UID", .len = 3 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ { .str = (char*)"OID", .len = 3 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ { .str = (char*)"INDEX_ID", .len = 8 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ { .str = (char*)"COLUMN_ID", .len = 9 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ { .str = (char*)"SPACE", .len = 5 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ { .str = (char*)"ENTRY", .len = 5 }, GS_TYPE_BIGINT, 8, GS_TRUE },
{ { .str = (char*)"ORG_SCN", .len = 7 }, GS_TYPE_BIGINT, 8, GS_TRUE },
{ { .str = (char*)"SEG_SCN", .len = 7 }, GS_TYPE_BIGINT, 8, GS_TRUE },
{ { .str = (char*)"INITRANS", .len = 8 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ { .str = (char*)"PCTFREE", .len = 7 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ { .str = (char*)"OP_TYPE", .len = 7 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ { .str = (char*)"REUSE", .len = 5 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ { .str = (char*)"SERIAL", .len = 6 }, GS_TYPE_BIGINT, 8, GS_TRUE },
{ { .str = (char*)"SPARE2", .len = 6 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ { .str = (char*)"SPARE3", .len = 6 }, GS_TYPE_INTEGER, 4, GS_TRUE }
};
text_t g_garbage_segment_idx01_cols[] = {
{ .str = (char*)"UID", .len = 3 },
{ .str = (char*)"OID", .len = 3 }
};
#define GARBAGE_SEGMENTS_COL_COUNT (sizeof(g_garbage_segments_cols) / sizeof(column_def_t))
#define GARBAGE_SEGMENT_IDX01_COL_COUNT (sizeof(g_garbage_segment_idx01_cols) / sizeof(text_t))
static index_def_t g_garbage_segment_indexes[] = {{{.str = (char *)"IX_GARBAGE_SEGMENT$001", .len = 22},
g_garbage_segment_idx01_cols,
GARBAGE_SEGMENT_IDX01_COL_COUNT,
GS_FALSE}};
// SYS_INSTANCE_INFO
column_def_t g_sys_instance_info_cols[] = {
{ {.str = (char*)"NAME", .len = 4 }, GS_TYPE_VARCHAR, 64, GS_FALSE },
{ {.str = (char*)"VALUE", .len = 5 }, GS_TYPE_BIGINT, 8, GS_FALSE }
};
text_t g_sys_instance_info_idx01_cols[] = {
{.str = (char*)"NAME", .len = 4 }
};
#define SYS_INSTANCE_INFO_COL_COUNT (sizeof(g_sys_instance_info_cols) / sizeof(column_def_t))
#define SYS_INSTANCE_INFO_IDX01_COL_COUNT (sizeof(g_sys_instance_info_idx01_cols) / sizeof(text_t))
static index_def_t g_sys_instance_info_indexes[] = {{{.str = (char *)"IDX_SYS_INSTANCE_INFO_001", .len = 25},
g_sys_instance_info_idx01_cols,
SYS_INSTANCE_INFO_IDX01_COL_COUNT,
GS_TRUE}};
// SYS_LOBS
column_def_t g_sys_lobs_cols[] = {
{ {.str = (char*)"USER#", .len = 5 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"TABLE#", .len = 6 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"COLUMN#", .len = 7 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"SPACE#", .len = 6 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"ENTRY", .len = 5 }, GS_TYPE_BIGINT, 8, GS_TRUE },
{ {.str = (char*)"ORG_SCN", .len = 7 }, GS_TYPE_BIGINT, 8, GS_TRUE },
{ {.str = (char*)"CHG_SCN", .len = 7 }, GS_TYPE_BIGINT, 8, GS_TRUE },
{ {.str = (char*)"CHUNK", .len = 5 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"PCTVERSION", .len = 10 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"RETENSION", .len = 9 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"FLAGS", .len = 5 }, GS_TYPE_INTEGER, 4, GS_TRUE }
};
text_t g_sys_lobs_idx01_cols[] = {
{.str = (char*)"USER#", .len = 5 },
{.str = (char*)"TABLE#", .len = 6 },
{.str = (char*)"COLUMN#", .len = 7 }
};
#define SYS_LOBS_COL_COUNT (sizeof(g_sys_lobs_cols) / sizeof(column_def_t))
#define SYS_LOBS_IDX01_COL_COUNT (sizeof(g_sys_lobs_idx01_cols) / sizeof(text_t))
static index_def_t g_sys_lobs_indexes[] = {
{ {.str = (char*)"IX_LOB$001", .len = 10 }, g_sys_lobs_idx01_cols, SYS_LOBS_IDX01_COL_COUNT, GS_TRUE }
};
// SYS_DISTRIBUTE_STRATEGIES
column_def_t g_distribute_strategy_cols[] = {
{ {.str = (char*)"USER#", .len = 5 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"TABLE#", .len = 6 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"DIST_DATA", .len = 9 }, GS_TYPE_VARCHAR, 1024, GS_FALSE },
{ {.str = (char*)"BUCKETS", .len = 7 }, GS_TYPE_BLOB, 8000, GS_TRUE },
{ {.str = (char*)"SLICE_COUNT", .len = 11 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"FROZEN_STATUS", .len = 13 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"DIST_TEXT", .len = 9 }, GS_TYPE_VARCHAR, 1024, GS_TRUE }
};
text_t g_distribute_strategy_idx01_cols[] = {
{.str = (char*)"USER#", .len = 5 },
{.str = (char*)"TABLE#", .len = 6 }
};
#define DISTRIBUTE_STRATEGY_COL_COUNT (sizeof(g_distribute_strategy_cols) / sizeof(column_def_t))
#define DISTRIBUTE_STRATEGY_IDX01_COL_COUNT (sizeof(g_distribute_strategy_idx01_cols) / sizeof(text_t))
static index_def_t g_distribute_strategy_indexes[] = {{{.str = (char *)"IX_DISTRIBUTE_STRATEGY$001", .len = 26},
g_distribute_strategy_idx01_cols,
DISTRIBUTE_STRATEGY_IDX01_COL_COUNT,
GS_TRUE}};
// SYS_POLICIES
column_def_t g_sys_policies_cols[] = {
{ {.str = (char*)"OBJ_SCHEMA_ID", .len = 13 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"OBJ_NAME", .len = 8 }, GS_TYPE_VARCHAR, 64, GS_FALSE },
{ {.str = (char*)"PNAME", .len = 5 }, GS_TYPE_VARCHAR, 64, GS_FALSE },
{ {.str = (char*)"PF_SCHEMA", .len = 9 }, GS_TYPE_VARCHAR, 64, GS_FALSE },
{ {.str = (char*)"PF_NAME", .len = 7 }, GS_TYPE_VARCHAR, 128, GS_FALSE },
{ {.str = (char*)"STMT_TYPE", .len = 9 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"PTYPE", .len = 5 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"CHK_OPTION", .len = 10 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"ENABLE", .len = 6 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"LONG_PREDICATE", .len = 14 }, GS_TYPE_INTEGER, 4, GS_FALSE }
};
text_t g_sys_policies_idx01_cols[] = {
{.str = (char*)"OBJ_SCHEMA_ID", .len = 13 },
{.str = (char*)"OBJ_NAME", .len = 8 },
{.str = (char*)"PNAME", .len = 5 }
};
#define SYS_POLICIES_COL_COUNT (sizeof(g_sys_policies_cols) / sizeof(column_def_t))
#define SYS_POLICIES_IDX01_COL_COUNT (sizeof(g_sys_policies_idx01_cols) / sizeof(text_t))
static index_def_t g_sys_policies_indexes[] = {{{.str = (char *)"IDX_SYS_POLICY_001", .len = 18},
g_sys_policies_idx01_cols,
SYS_POLICIES_IDX01_COL_COUNT,
GS_TRUE}};
// SYS_DDM
column_def_t g_sys_ddm_cols[] = {
{ {.str = (char*)"USER#", .len = 5 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"TABLE#", .len = 6 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"COLUMN#", .len = 7 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"RULE_NAME", .len = 9 }, GS_TYPE_VARCHAR, 64, GS_TRUE },
{ {.str = (char*)"TYPE_NAME", .len = 9 }, GS_TYPE_VARCHAR, 64, GS_TRUE },
{ {.str = (char*)"PARAM", .len = 5 }, GS_TYPE_VARCHAR, 1024, GS_TRUE }
};
text_t g_sys_ddm_idx01_cols[] = {
{.str = (char*)"USER#", .len = 5 },
{.str = (char*)"TABLE#", .len = 6 },
{.str = (char*)"COLUMN#", .len = 7 }
};
text_t g_sys_ddm_idx02_cols[] = {
{.str = (char*)"USER#", .len = 5 },
{.str = (char*)"TABLE#", .len = 6 },
{.str = (char*)"RULE_NAME", .len = 9 }
};
#define SYS_DDM_COL_COUNT (sizeof(g_sys_ddm_cols) / sizeof(column_def_t))
#define SYS_DDM_IDX01_COL_COUNT (sizeof(g_sys_ddm_idx01_cols) / sizeof(text_t))
#define SYS_DDM_IDX02_COL_COUNT (sizeof(g_sys_ddm_idx02_cols) / sizeof(text_t))
static index_def_t g_sys_ddm_indexes[] = {
{ {.str = (char*)"IDX_DDM_001", .len = 11 }, g_sys_ddm_idx01_cols, SYS_DDM_IDX01_COL_COUNT, GS_FALSE },
{ {.str = (char*)"IDX_DDM_002", .len = 11 }, g_sys_ddm_idx02_cols, SYS_DDM_IDX02_COL_COUNT, GS_FALSE }
};
// SYS_DML_STATS
column_def_t g_sys_dml_stats_cols[] = {
{ {.str = (char*)"USER#", .len = 5 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"TABLE#", .len = 6 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"INSERTS", .len = 7 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"UPDATES", .len = 7 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"DELETES", .len = 7 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"MODIFY_TIME", .len = 11 }, GS_TYPE_TIMESTAMP, 8, GS_FALSE },
{ {.str = (char*)"FLAGS", .len = 5 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"DROP_SEGMENTS", .len = 13 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"PARTED", .len = 6 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"PART#", .len = 5 }, GS_TYPE_INTEGER, 4, GS_TRUE }
};
text_t g_sys_dml_stats_idx01_cols[] = {
{.str = (char*)"USER#", .len = 5 },
{.str = (char*)"TABLE#", .len = 6 },
};
text_t g_sys_dml_stats_idx02_cols[] = {
{.str = (char*)"MODIFY_TIME#", .len = 11 }
};
text_t g_sys_dml_stats_idx03_cols[] = {
{.str = (char*)"USER#", .len = 5 },
{.str = (char*)"TABLE#", .len = 6 },
{.str = (char*)"PART#", .len = 5 }
};
#define SYS_DML_STATS_COL_COUNT (sizeof(g_sys_dml_stats_cols) / sizeof(column_def_t))
#define SYS_DML_STATS_IDX01_COL_COUNT (sizeof(g_sys_dml_stats_idx01_cols) / sizeof(text_t))
#define SYS_DML_STATS_IDX02_COL_COUNT (sizeof(g_sys_dml_stats_idx02_cols) / sizeof(text_t))
#define SYS_DML_STATS_IDX03_COL_COUNT (sizeof(g_sys_dml_stats_idx03_cols) / sizeof(text_t))
static index_def_t g_sys_dml_stats_indexes[] = {
{ {.str = (char*)"IX_MODS_001", .len = 11 }, g_sys_dml_stats_idx01_cols, SYS_DML_STATS_IDX01_COL_COUNT, GS_FALSE },
{ {.str = (char*)"IX_MODS_002", .len = 11 }, g_sys_dml_stats_idx02_cols, SYS_DML_STATS_IDX02_COL_COUNT, GS_FALSE },
{ {.str = (char*)"IX_MODS_003", .len = 11 }, g_sys_dml_stats_idx03_cols, SYS_DML_STATS_IDX03_COL_COUNT, GS_TRUE },
};
// SYS_SHADOW_INDEXES
column_def_t g_shadow_indexes_cols[] = {
{ {.str = (char*)"USER#", .len = 5 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"TABLE#", .len = 6 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"ID", .len = 2 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"NAME", .len = 4 }, GS_TYPE_VARCHAR, 64, GS_FALSE },
{ {.str = (char*)"SPACE#", .len = 6 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"SEQUENCE#", .len = 9 }, GS_TYPE_BIGINT, 8, GS_FALSE },
{ {.str = (char*)"ENTRY", .len = 5 }, GS_TYPE_BIGINT, 8, GS_FALSE },
{ {.str = (char*)"IS_PRIMARY", .len = 10 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"IS_UNIQUE", .len = 9 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"TYPE", .len = 4 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"COLS", .len = 4 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"COL_LIST", .len = 8 }, GS_TYPE_VARCHAR, 128, GS_FALSE },
{ {.str = (char*)"INITRANS", .len = 8 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"CR_MODE", .len = 7 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"FLAGS", .len = 5 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"PARTED", .len = 6 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"PCTFREE", .len = 7 }, GS_TYPE_INTEGER, 4, GS_FALSE }
};
text_t g_shadow_indexes_idx01_cols[] = {
{.str = (char*)"USER#", .len = 5 },
{.str = (char*)"TABLE#", .len = 6 }
};
#define SHADOW_INDEXES_COL_COUNT (sizeof(g_shadow_indexes_cols) / sizeof(column_def_t))
#define SHADOW_INDEXES_IDX01_COL_COUNT (sizeof(g_shadow_indexes_idx01_cols) / sizeof(text_t))
static index_def_t g_shadow_indexes_indexes[] = {{{.str = (char *)"IX_SHADOW_INDEX$_001", .len = 20},
g_shadow_indexes_idx01_cols,
SHADOW_INDEXES_IDX01_COL_COUNT,
GS_TRUE}};
// SYS_SHADOW_INDEX_PARTS
column_def_t g_shw_indexpart_cols[] = {
{ {.str = (char*)"USER#", .len = 5 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"TABLE#", .len = 6 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"INDEX#", .len = 6 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"PART#", .len = 5 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"NAME", .len = 4 }, GS_TYPE_VARCHAR, 64, GS_FALSE },
{ {.str = (char*)"HIBOUNDLEN", .len = 10 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"HIBOUNDVAL", .len = 10 }, GS_TYPE_VARCHAR, 4000, GS_TRUE },
{ {.str = (char*)"SPACE#", .len = 6 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"ORG_SCN", .len = 7 }, GS_TYPE_BIGINT, 8, GS_FALSE },
{ {.str = (char*)"ENTRY", .len = 5 }, GS_TYPE_BIGINT, 8, GS_FALSE },
{ {.str = (char*)"INITRANS", .len = 8 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"PCTFREE", .len = 7 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"FLAGS", .len = 5 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"BHIBOUNDVAL", .len = 11 }, GS_TYPE_BINARY, 4000, GS_TRUE },
{ {.str = (char*)"PARENT_PART#", .len = 12 }, GS_TYPE_INTEGER, 4, GS_TRUE }
};
text_t g_shw_indexpart_idx01_cols[] = {
{.str = (char*)"USER#", .len = 5 },
{.str = (char*)"TABLE#", .len = 6 },
{.str = (char*)"INDEX#", .len = 6 },
{.str = (char*)"PART#", .len = 6 },
{.str = (char*)"PARENT_PART#", .len = 12 }
};
#define SHW_INDEXPART_COL_COUNT (sizeof(g_shw_indexpart_cols) / sizeof(column_def_t))
#define SHW_INDEXPART_IDX01_COL_COUNT (sizeof(g_shw_indexpart_idx01_cols) / sizeof(text_t))
static index_def_t g_shw_indexpart_indexes[] = {{{.str = (char *)"IX_SHW_INDEXPART$001", .len = 20},
g_shw_indexpart_idx01_cols,
SHW_INDEXPART_IDX01_COL_COUNT,
GS_FALSE}};
// SYS_TABLE_PARTS
column_def_t g_table_parts_cols[] = {
{ {.str = (char*)"USER#", .len = 5 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"TABLE#", .len = 6 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"PART#", .len = 5 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"NAME", .len = 4 }, GS_TYPE_VARCHAR, 64, GS_FALSE },
{ {.str = (char*)"HIBOUNDLEN", .len = 10 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"HIBOUNDVAL", .len = 10 }, GS_TYPE_VARCHAR, 4000, GS_TRUE },
{ {.str = (char*)"SPACE#", .len = 6 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"ORG_SCN", .len = 7 }, GS_TYPE_BIGINT, 8, GS_FALSE },
{ {.str = (char*)"ENTRY", .len = 5 }, GS_TYPE_BIGINT, 8, GS_FALSE },
{ {.str = (char*)"INITRANS", .len = 8 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"PCTFREE", .len = 7 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"FLAGS", .len = 5 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"BHIBOUNDVAL", .len = 11 }, GS_TYPE_BINARY, 4000, GS_TRUE },
{ {.str = (char*)"ROWCNT", .len = 6 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"BLKCNT", .len = 6 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"EMPCNT", .len = 6 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"AVGRLN", .len = 6 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"SAMPLESIZE", .len = 10 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"ANALYZETIME", .len = 11 }, GS_TYPE_DATE, 8, GS_TRUE },
{ {.str = (char*)"SUBPARTCNT", .len = 10 }, GS_TYPE_INTEGER, 4, GS_TRUE }
};
text_t g_table_parts_idx01_cols[] = {
{.str = (char*)"USER#", .len = 5 },
{.str = (char*)"TABLE#", .len = 6 },
{.str = (char*)"PART#", .len = 6 }
};
#define TABLE_PARTS_COL_COUNT (sizeof(g_table_parts_cols) / sizeof(column_def_t))
#define TABLE_PARTS_IDX01_COL_COUNT (sizeof(g_table_parts_idx01_cols) / sizeof(text_t))
static index_def_t g_table_parts_indexes[] = {
{ {.str = (char*)"IX_TABLEPART$001", .len = 16 }, g_table_parts_idx01_cols, TABLE_PARTS_IDX01_COL_COUNT, GS_TRUE }
};
// SYS_SUB_TABLE_PARTS
column_def_t g_subtable_parts_cols[] = {
{ {.str = (char*)"USER#", .len = 5 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"TABLE#", .len = 6 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"SUBPART#", .len = 8 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"NAME", .len = 4 }, GS_TYPE_VARCHAR, 64, GS_FALSE },
{ {.str = (char*)"HIBOUNDLEN", .len = 10 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"HIBOUNDVAL", .len = 10 }, GS_TYPE_VARCHAR, 4000, GS_TRUE },
{ {.str = (char*)"SPACE#", .len = 6 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"ORG_SCN", .len = 7 }, GS_TYPE_BIGINT, 8, GS_FALSE },
{ {.str = (char*)"ENTRY", .len = 5 }, GS_TYPE_BIGINT, 8, GS_FALSE },
{ {.str = (char*)"INITRANS", .len = 8 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"PCTFREE", .len = 7 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"FLAGS", .len = 5 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"BHIBOUNDVAL", .len = 11 }, GS_TYPE_BINARY, 4000, GS_TRUE },
{ {.str = (char*)"ROWCNT", .len = 6 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"BLKCNT", .len = 6 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"EMPCNT", .len = 6 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"AVGRLN", .len = 6 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"SAMPLESIZE", .len = 10 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"ANALYZETIME", .len = 11 }, GS_TYPE_DATE, 8, GS_TRUE },
{ {.str = (char*)"PARENT_PART#", .len = 12 }, GS_TYPE_INTEGER, 4, GS_FALSE }
};
text_t g_subtable_parts_idx01_cols[] = {
{.str = (char*)"USER#", .len = 5 },
{.str = (char*)"TABLE#", .len = 6 },
{.str = (char*)"PARENT_PART#", .len = 12 },
{.str = (char*)"SUBPART#", .len = 8 }
};
text_t g_subtable_parts_idx02_cols[] = {
{.str = (char*)"USER#", .len = 5 },
{.str = (char*)"TABLE#", .len = 6 },
{.str = (char*)"NAME", .len = 4 }
};
#define SUBTABLE_PARTS_COL_COUNT (sizeof(g_subtable_parts_cols) / sizeof(column_def_t))
#define SUBTABLE_PARTS_IDX01_COL_COUNT (sizeof(g_subtable_parts_idx01_cols) / sizeof(text_t))
#define SUBTABLE_PARTS_IDX02_COL_COUNT (sizeof(g_subtable_parts_idx02_cols) / sizeof(text_t))
static index_def_t g_subtable_parts_indexes[] = {
{{.str = (char *)"IX_SUBTABLEPART$001", .len = 19},
g_subtable_parts_idx01_cols,
SUBTABLE_PARTS_IDX01_COL_COUNT,
GS_TRUE},
{{.str = (char *)"IX_SUBTABLEPART$002", .len = 19},
g_subtable_parts_idx02_cols,
SUBTABLE_PARTS_IDX02_COL_COUNT,
GS_TRUE}};
// SYS_PENDING_TRANS
column_def_t g_pending_trans_cols[] = {
{ {.str = (char*)"GLOBAL_TRAN_ID", .len = 14 }, GS_TYPE_VARCHAR, 256, GS_FALSE },
{ {.str = (char*)"LOCAL_TRAN_ID", .len = 13 }, GS_TYPE_BIGINT, 8, GS_TRUE },
{ {.str = (char*)"TLOCK_LOBS", .len = 10 }, GS_TYPE_BINARY, 4000, GS_TRUE },
{ {.str = (char*)"TLOCK_LOBS_EXT", .len = 14 }, GS_TYPE_BLOB, 8000, GS_TRUE },
{ {.str = (char*)"FORMAT_ID", .len = 9 }, GS_TYPE_BIGINT, 8, GS_TRUE },
{ {.str = (char*)"BRANCH_ID", .len = 9 }, GS_TYPE_VARCHAR, 128, GS_TRUE },
{ {.str = (char*)"OWNER", .len = 5 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"PREPARE_SCN", .len = 11 }, GS_TYPE_BIGINT, 8, GS_TRUE },
{ {.str = (char*)"COMMIT_SCN", .len = 10 }, GS_TYPE_BIGINT, 8, GS_TRUE }
};
#define PENDING_TRANS_COL_COUNT (sizeof(g_pending_trans_cols) / sizeof(column_def_t))
// SYS_TMP_SEG_STATS
column_def_t g_tmp_seg_stats_cols[] = {
{ {.str = (char*)"ORG_SCN", .len = 7 }, GS_TYPE_BIGINT, 8, GS_FALSE },
{ {.str = (char*)"UID", .len = 3 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"OID", .len = 3 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"LOGIC_READS", .len = 11 }, GS_TYPE_BIGINT, 8, GS_TRUE },
{ {.str = (char*)"PHYSICAL_WRITES", .len = 15 }, GS_TYPE_BIGINT, 8, GS_TRUE },
{ {.str = (char*)"PHYSICAL_READS", .len = 14 }, GS_TYPE_BIGINT, 8, GS_TRUE },
{ {.str = (char*)"ITL_WAITS", .len = 9 }, GS_TYPE_BIGINT, 8, GS_TRUE },
{ {.str = (char*)"BUF_BUSY_WAITS", .len = 14 }, GS_TYPE_BIGINT, 8, GS_TRUE },
{ {.str = (char*)"ROW_LOCK_WAITS", .len = 14 }, GS_TYPE_BIGINT, 8, GS_TRUE }
};
text_t g_object_idx01_cols[] = {
{.str = (char*)"ORG_SCN", .len = 7 }
};
text_t g_object_idx02_cols[] = {
{.str = (char*)"UID", .len = 3 },
{.str = (char*)"OID", .len = 3 }
};
#define TMP_SEG_STATS_COL_COUNT (sizeof(g_tmp_seg_stats_cols) / sizeof(column_def_t))
#define OBJECT_IDX01_COL_COUNT (sizeof(g_object_idx01_cols) / sizeof(text_t))
#define OBJECT_IDX02_COL_COUNT (sizeof(g_object_idx02_cols) / sizeof(text_t))
static index_def_t g_tmp_seg_stats_indexes[] = {
{ {.str = (char*)"IDX_OBJECT01", .len = 12 }, g_object_idx01_cols, OBJECT_IDX01_COL_COUNT, GS_TRUE },
{ {.str = (char*)"IDX_OBJECT", .len = 10 }, g_object_idx02_cols, OBJECT_IDX02_COL_COUNT, GS_FALSE }
};
// SYS_TEMP_HISTGRAM
column_def_t g_temp_histgram_cols[] = {
{ {.str = (char*)"USER#", .len = 5 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"TABLE#", .len = 6 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"COL#", .len = 4 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"BUCKET", .len = 6 }, GS_TYPE_VARCHAR, 4000, GS_TRUE },
{ {.str = (char*)"ENDPOINT", .len = 8 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"PART#", .len = 5 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"EPVALUE", .len = 7 }, GS_TYPE_VARCHAR, 1000, GS_TRUE },
{ {.str = (char*)"SPARE1", .len = 6 }, GS_TYPE_BIGINT, 8, GS_TRUE },
{ {.str = (char*)"SPARE2", .len = 6 }, GS_TYPE_BIGINT, 8, GS_TRUE },
{ {.str = (char*)"SPARE3", .len = 6 }, GS_TYPE_BIGINT, 8, GS_TRUE }
};
text_t g_temp_histgram_idx01_cols[] = {
{.str = (char*)"USER#", .len = 5 },
{.str = (char*)"TABLE#", .len = 6 },
{.str = (char*)"COL#", .len = 4 },
{.str = (char*)"PART#", .len = 5 },
{.str = (char*)"ENDPOINT", .len = 8 }
};
#define TEMP_HISTGRAM_COL_COUNT (sizeof(g_temp_histgram_cols) / sizeof(column_def_t))
#define TEMP_HISTGRAM_IDX01_COL_COUNT (sizeof(g_temp_histgram_idx01_cols) / sizeof(text_t))
static index_def_t g_temp_histgram_indexes[] = {{{.str = (char *)"IX_TEMP_HIST_003", .len = 16},
g_temp_histgram_idx01_cols,
TEMP_HISTGRAM_IDX01_COL_COUNT,
GS_FALSE}};
// SYS_TEMP_HISTGRAM_ABSTR
column_def_t g_temp_hist_abstr_cols[] = {
{ {.str = (char*)"USER#", .len = 5 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"TAB#", .len = 4 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"COL#", .len = 4 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"BUCKET_NUM", .len = 10 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"ROW_NUM", .len = 7 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"NULL_NUM", .len = 8 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"ANALYZE_TIME", .len = 12 }, GS_TYPE_DATE, 8, GS_TRUE },
{ {.str = (char*)"MINVALUE", .len = 8 }, GS_TYPE_VARCHAR, 4000, GS_TRUE },
{ {.str = (char*)"MAXVALUE", .len = 8 }, GS_TYPE_VARCHAR, 4000, GS_TRUE },
{ {.str = (char*)"DIST_NUM", .len = 8 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"DENSITY", .len = 7 }, GS_TYPE_REAL, 8, GS_TRUE },
{ {.str = (char*)"SPARE1", .len = 6 }, GS_TYPE_BIGINT, 8, GS_TRUE },
{ {.str = (char*)"SPARE2", .len = 6 }, GS_TYPE_BIGINT, 8, GS_TRUE },
{ {.str = (char*)"SPARE3", .len = 6 }, GS_TYPE_BIGINT, 8, GS_TRUE },
{ {.str = (char*)"SPARE4", .len = 6 }, GS_TYPE_BIGINT, 8, GS_TRUE }
};
text_t g_temp_hist_abstr_idx01_cols[] = {
{.str = (char*)"ANALYZE_TIME", .len = 12 }
};
text_t g_temp_hist_abstr_idx02_cols[] = {
{.str = (char*)"USER#", .len = 5 },
{.str = (char*)"TAB#", .len = 4 },
{.str = (char*)"COL#", .len = 4 },
{.str = (char*)"SPARE1", .len = 6 }
};
#define TEMP_HIST_ABSTR_COL_COUNT (sizeof(g_temp_hist_abstr_cols) / sizeof(column_def_t))
#define TEMP_HIST_ABSTR_IDX01_COL_COUNT (sizeof(g_temp_hist_abstr_idx01_cols) / sizeof(text_t))
#define TEMP_HIST_ABSTR_IDX02_COL_COUNT (sizeof(g_temp_hist_abstr_idx02_cols) / sizeof(text_t))
static index_def_t g_temp_hist_abstr_indexes[] = {
{{.str = (char *)"IX_TEMP_HIST_HEAD_002", .len = 21},
g_temp_hist_abstr_idx01_cols,
TEMP_HIST_ABSTR_IDX01_COL_COUNT,
GS_FALSE},
{{.str = (char *)"IX_TEMP_HIST_HEAD_003", .len = 21},
g_temp_hist_abstr_idx02_cols,
TEMP_HIST_ABSTR_IDX02_COL_COUNT,
GS_TRUE}};
// SYS_DUMMY
column_def_t g_sys_dummy_cols[] = {
{ {.str = (char*)"DUMMY", .len = 5 }, GS_TYPE_VARCHAR, 1, GS_FALSE },
};
#define SYS_DUMMY_COL_COUNT (sizeof(g_sys_dummy_cols) / sizeof(column_def_t))
// SYS_PRIVS
column_def_t g_sys_privs_cols[] = {
{ {.str = (char*)"GRANTEE_ID", .len = 10 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"GRANTEE_TYPE", .len = 12 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"PRIVILEGE", .len = 9 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"ADMIN_OPTION", .len = 12 }, GS_TYPE_INTEGER, 4, GS_FALSE },
};
text_t g_sys_privs_idx01_cols[] = {
{.str = (char*)"GRANTEE_ID", .len = 10 },
{.str = (char*)"GRANTEE_TYPE", .len = 12 },
{.str = (char*)"PRIVILEGE", .len = 9 }
};
#define SYS_PRIVS_COL_COUNT (sizeof(g_sys_privs_cols) / sizeof(column_def_t))
#define SYS_PRIVS_IDX01_COL_COUNT (sizeof(g_sys_privs_idx01_cols) / sizeof(text_t))
static index_def_t g_sys_privs_indexes[] = {
{ {.str = (char*)"IX_SYS_PRIVS$_001", .len = 17 }, g_sys_privs_idx01_cols, SYS_PRIVS_IDX01_COL_COUNT, GS_TRUE }
};
// SYS_ROLES
column_def_t g_sys_roles_cols[] = {
{ {.str = (char*)"ID", .len = 2 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"OWNER_UID", .len = 9 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"NAME", .len = 4 }, GS_TYPE_VARCHAR, 64, GS_FALSE },
{ {.str = (char*)"PASSWORD", .len = 8 }, GS_TYPE_VARCHAR, 256, GS_TRUE },
};
text_t g_sys_roles_idx01_cols[] = {
{.str = (char*)"ID", .len = 2 },
{.str = (char*)"NAME", .len = 4 }
};
text_t g_sys_roles_idx02_cols[] = {
{.str = (char*)"OWNER_UID", .len = 9 }
};
#define SYS_ROLES_COL_COUNT (sizeof(g_sys_roles_cols) / sizeof(column_def_t))
#define SYS_ROLES_IDX01_COL_COUNT (sizeof(g_sys_roles_idx01_cols) / sizeof(text_t))
#define SYS_ROLES_IDX02_COL_COUNT (sizeof(g_sys_roles_idx02_cols) / sizeof(text_t))
static index_def_t g_sys_roles_indexes[] = {
{ {.str = (char*)"IX_ROLES$_001", .len = 13 }, g_sys_roles_idx01_cols, SYS_ROLES_IDX01_COL_COUNT, GS_TRUE },
{ {.str = (char*)"IX_ROLES$_002", .len = 13 }, g_sys_roles_idx02_cols, SYS_ROLES_IDX02_COL_COUNT, GS_FALSE }
};
// SYS_PROFILE
column_def_t g_sys_profile_cols[] = {
{ {.str = (char*)"NAME", .len = 4 }, GS_TYPE_VARCHAR, 64, GS_FALSE },
{ {.str = (char*)"PROFILE#", .len = 8 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"RESOURCE#", .len = 9 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"THRESHOLD", .len = 9 }, GS_TYPE_INTEGER, 4, GS_FALSE },
};
text_t g_sys_profile_idx01_cols[] = {
{.str = (char*)"PROFILE#", .len = 8 },
{.str = (char*)"RESOURCE#", .len = 9 }
};
#define SYS_PROFILE_COL_COUNT (sizeof(g_sys_profile_cols) / sizeof(column_def_t))
#define SYS_PROFILE_IDX01_COL_COUNT (sizeof(g_sys_profile_idx01_cols) / sizeof(text_t))
static index_def_t g_sys_profile_indexes[] = {
{ {.str = (char*)"IX_PROFILE$_001", .len = 15 }, g_sys_profile_idx01_cols, SYS_PROFILE_IDX01_COL_COUNT, GS_TRUE }
};
// SYS_USER_HISTORY
column_def_t g_user_history_cols[] = {
{ {.str = (char*)"USER#", .len = 5 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"PASSWORD", .len = 8 }, GS_TYPE_BINARY, 512, GS_TRUE },
{ {.str = (char*)"PASSWORD_DATE", .len = 13 }, GS_TYPE_DATE, 8, GS_TRUE }
};
text_t g_user_history_idx01_cols[] = {
{.str = (char*)"USER#", .len = 5 },
{.str = (char*)"PASSWORD_DATE", .len = 13 }
};
#define USER_HISTORY_COL_COUNT (sizeof(g_user_history_cols) / sizeof(column_def_t))
#define USER_HISTORY_IDX01_COL_COUNT (sizeof(g_user_history_idx01_cols) / sizeof(text_t))
static index_def_t g_user_history_indexes[] = {{{.str = (char *)"IX_USER_HISTORY$001", .len = 19},
g_user_history_idx01_cols,
USER_HISTORY_IDX01_COL_COUNT,
GS_TRUE}};
// SYS_TENANTS
column_def_t g_sys_tenants_cols[] = {
{ {.str = (char*)"TENANT_ID", .len = 9 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"NAME", .len = 4 }, GS_TYPE_VARCHAR, 32, GS_FALSE },
{ {.str = (char*)"DATA_SPACE#", .len = 11 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"SPACE_NUM", .len = 9 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"SPACE_BITMAP", .len = 12 }, GS_TYPE_RAW, 256, GS_FALSE },
{ {.str = (char*)"CTIME", .len = 5 }, GS_TYPE_DATE, 8, GS_FALSE },
{ {.str = (char*)"OPTIONS", .len = 7 }, GS_TYPE_RAW, 128, GS_TRUE }
};
text_t g_sys_tenants_idx01_cols[] = {
{.str = (char*)"TENANT_ID", .len = 9 },
};
text_t g_sys_tenants_idx02_cols[] = {
{.str = (char*)"NAME", .len = 4 }
};
#define SYS_TENANTS_COL_COUNT (sizeof(g_sys_tenants_cols) / sizeof(column_def_t))
#define SYS_TENANTS_IDX01_COL_COUNT (sizeof(g_sys_tenants_idx01_cols) / sizeof(text_t))
#define SYS_TENANTS_IDX02_COL_COUNT (sizeof(g_sys_tenants_idx02_cols) / sizeof(text_t))
static index_def_t g_sys_tenants_indexes[] = {
{{.str = (char *)"IDX_SYS_TENANT_001", .len = 18}, g_sys_tenants_idx01_cols, SYS_TENANTS_IDX01_COL_COUNT, GS_TRUE},
{{.str = (char *)"IDX_SYS_TENANT_002", .len = 18}, g_sys_tenants_idx02_cols, SYS_TENANTS_IDX02_COL_COUNT, GS_TRUE}};
// SYS_VIEWS
column_def_t g_sys_views_cols[] = {
{ {.str = (char*)"USER#", .len = 5 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"ID", .len = 2 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"NAME", .len = 4 }, GS_TYPE_VARCHAR, 64, GS_FALSE },
{ {.str = (char*)"COLS", .len = 4 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"FLAGS", .len = 5 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"ORG_SCN", .len = 7 }, GS_TYPE_BIGINT, 8, GS_TRUE },
{ {.str = (char*)"CHG_SCN", .len = 7 }, GS_TYPE_BIGINT, 8, GS_TRUE },
{ {.str = (char*)"TEXT_LENGTH", .len = 11}, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"TEXT", .len = 4 }, GS_TYPE_CLOB, 8000, GS_FALSE },
{ {.str = (char*)"SQL_TYPE", .len = 8 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"OBJ#", .len = 4 }, GS_TYPE_INTEGER, 4, GS_FALSE }
};
text_t g_sys_views_idx01_cols[] = {
{.str = (char*)"USER#", .len = 5 },
{.str = (char*)"NAME", .len = 4 },
};
text_t g_sys_views_idx02_cols[] = {
{.str = (char*)"USER#", .len = 5 },
{.str = (char*)"ID", .len = 2 },
};
#define SYS_VIEWS_COL_COUNT (sizeof(g_sys_views_cols) / sizeof(column_def_t))
#define SYS_VIEWS_IDX01_COL_COUNT (sizeof(g_sys_views_idx01_cols) / sizeof(text_t))
#define SYS_VIEWS_IDX02_COL_COUNT (sizeof(g_sys_views_idx02_cols) / sizeof(text_t))
static index_def_t g_sys_views_indexes[] = {
{ {.str = (char*)"IX_VIEW$001", .len = 11 }, g_sys_views_idx01_cols, SYS_VIEWS_IDX01_COL_COUNT, GS_TRUE },
{ {.str = (char*)"IX_VIEW$002", .len = 11 }, g_sys_views_idx02_cols, SYS_VIEWS_IDX02_COL_COUNT, GS_TRUE }
};
// SYS_SYNONYMS
column_def_t g_sys_synonyms_cols[] = {
{ {.str = (char*)"USER#", .len = 5 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"ID", .len = 2 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"ORG_SCN", .len = 7 }, GS_TYPE_BIGINT, 8, GS_TRUE },
{ {.str = (char*)"CHG_SCN", .len = 7 }, GS_TYPE_BIGINT, 8, GS_TRUE },
{ {.str = (char*)"SYNONYM_NAME", .len = 12}, GS_TYPE_VARCHAR, 64, GS_FALSE },
{ {.str = (char*)"TABLE_OWNER", .len = 11}, GS_TYPE_VARCHAR, 64, GS_FALSE },
{ {.str = (char*)"TABLE_NAME", .len = 10}, GS_TYPE_VARCHAR, 64, GS_FALSE },
{ {.str = (char*)"FLAGS", .len = 5 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"TYPE", .len = 4 }, GS_TYPE_INTEGER, 4, GS_FALSE }
};
text_t g_sys_synonyms_idx01_cols[] = {
{.str = (char*)"USER#", .len = 5 },
{.str = (char*)"SYNONYM_NAME", .len = 12 },
};
text_t g_sys_synonyms_idx02_cols[] = {
{.str = (char*)"USER#", .len = 5 },
{.str = (char*)"ID", .len = 2 },
};
#define SYS_SYNONYMS_COL_COUNT (sizeof(g_sys_synonyms_cols) / sizeof(column_def_t))
#define SYS_SYNONYMS_IDX01_COL_COUNT (sizeof(g_sys_synonyms_idx01_cols) / sizeof(text_t))
#define SYS_SYNONYMS_IDX02_COL_COUNT (sizeof(g_sys_synonyms_idx02_cols) / sizeof(text_t))
static index_def_t g_sys_synonyms_indexes[] = {
{ {.str = (char*)"IX_SYNONYM$001", .len = 14 }, g_sys_synonyms_idx01_cols, SYS_SYNONYMS_IDX01_COL_COUNT, GS_TRUE },
{ {.str = (char*)"IX_SYNONYM$002", .len = 14 }, g_sys_synonyms_idx02_cols, SYS_SYNONYMS_IDX02_COL_COUNT, GS_FALSE }
};
// SYS_USER_ROLES
column_def_t g_user_roles_cols[] = {
{ {.str = (char*)"GRANTEE_ID", .len = 10 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"GRANTEE_TYPE", .len = 12 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"GRANTED_ROLE_ID", .len = 15 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"ADMIN_OPTION", .len = 12 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"DEFAULT_ROLE", .len = 12 }, GS_TYPE_INTEGER, 4, GS_TRUE }
};
text_t g_user_roles_idx01_cols[] = {
{.str = (char*)"GRANTEE_ID", .len = 10 },
{.str = (char*)"GRANTEE_TYPE", .len = 12 },
{.str = (char*)"GRANTED_ROLE_ID", .len = 15 }
};
text_t g_user_roles_idx02_cols[] = {
{.str = (char*)"GRANTED_ROLE_ID", .len = 15 }
};
#define USER_ROLES_COL_COUNT (sizeof(g_user_roles_cols) / sizeof(column_def_t))
#define USER_ROLES_IDX01_COL_COUNT (sizeof(g_user_roles_idx01_cols) / sizeof(text_t))
#define USER_ROLES_IDX02_COL_COUNT (sizeof(g_user_roles_idx02_cols) / sizeof(text_t))
static index_def_t g_user_roles_indexes[] = {
{ {.str = (char*)"IX_USER_ROLES$_001", .len = 18 }, g_user_roles_idx01_cols, USER_ROLES_IDX01_COL_COUNT, GS_TRUE },
{ {.str = (char*)"IX_USER_ROLES$_002", .len = 18 }, g_user_roles_idx02_cols, USER_ROLES_IDX02_COL_COUNT, GS_FALSE }
};
// SYS_OBJECT_PRIVS
column_def_t g_object_privs_cols[] = {
{ {.str = (char*)"GRANTEE", .len = 7 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"GRANTEE_TYPE", .len = 12}, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"OBJECT_OWNER", .len = 12}, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"OBJECT_NAME", .len = 11}, GS_TYPE_VARCHAR, 64, GS_FALSE },
{ {.str = (char*)"OBJECT_TYPE", .len = 11}, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"PRIVILEGE", .len = 9 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"GRANTABLE", .len = 9 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"GRANTOR", .len = 7 }, GS_TYPE_INTEGER, 4, GS_FALSE }
};
text_t g_object_privs_idx01_cols[] = {
{.str = (char*)"GRANTEE", .len = 7 },
{.str = (char*)"GRANTEE_TYPE", .len = 12 },
{.str = (char*)"OBJECT_OWNER", .len = 12 },
{.str = (char*)"OBJECT_NAME", .len = 11 },
{.str = (char*)"OBJECT_TYPE", .len = 11 },
{.str = (char*)"PRIVILEGE", .len = 9 }
};
text_t g_object_privs_idx02_cols[] = {
{.str = (char*)"OBJECT_OWNER", .len = 12 },
{.str = (char*)"OBJECT_NAME", .len = 11 },
{.str = (char*)"OBJECT_TYPE", .len = 11 }
};
text_t g_object_privs_idx03_cols[] = {
{.str = (char*)"GRANTOR", .len = 7 },
{.str = (char*)"OBJECT_OWNER", .len = 12 },
{.str = (char*)"OBJECT_NAME", .len = 11 },
{.str = (char*)"OBJECT_TYPE", .len = 11 },
{.str = (char*)"PRIVILEGE", .len = 9 },
};
#define OBJECT_PRIVS_COL_COUNT (sizeof(g_object_privs_cols) / sizeof(column_def_t))
#define OBJECT_PRIVS_IDX01_COL_COUNT (sizeof(g_object_privs_idx01_cols) / sizeof(text_t))
#define OBJECT_PRIVS_IDX02_COL_COUNT (sizeof(g_object_privs_idx02_cols) / sizeof(text_t))
#define OBJECT_PRIVS_IDX03_COL_COUNT (sizeof(g_object_privs_idx03_cols) / sizeof(text_t))
static index_def_t g_object_privs_indexes[] = {
{{.str = (char *)"IX_OBJECT_PRIVS$_001", .len = 18},
g_object_privs_idx01_cols,
OBJECT_PRIVS_IDX01_COL_COUNT,
GS_TRUE},
{{.str = (char *)"IX_OBJECT_PRIVS$_002", .len = 18},
g_object_privs_idx02_cols,
OBJECT_PRIVS_IDX02_COL_COUNT,
GS_FALSE},
{{.str = (char *)"IX_OBJECT_PRIVS$_004", .len = 18},
g_object_privs_idx03_cols,
OBJECT_PRIVS_IDX03_COL_COUNT,
GS_FALSE}};
// SYS_DISTRIBUTE_RULES
column_def_t g_distribute_rules_cols[] = {
{ {.str = (char*)"UID", .len = 3 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"ID", .len = 2 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"DIST_DATA", .len = 9 }, GS_TYPE_VARCHAR, 1024, GS_FALSE },
{ {.str = (char*)"BUCKETS", .len = 7 }, GS_TYPE_BLOB, 8000, GS_TRUE },
{ {.str = (char*)"NAME", .len = 4 }, GS_TYPE_VARCHAR, 64, GS_FALSE },
{ {.str = (char*)"ORG_SCN", .len = 7 }, GS_TYPE_BIGINT, 8, GS_TRUE },
{ {.str = (char*)"CHG_SCN", .len = 7 }, GS_TYPE_BIGINT, 8, GS_TRUE },
{ {.str = (char*)"COLUMNS", .len = 7 }, GS_TYPE_VARCHAR, 1024, GS_TRUE },
{ {.str = (char*)"COLUMN_COUNT", .len = 12}, GS_TYPE_INTEGER, 4, GS_FALSE }
};
text_t g_distribute_rules_idx01_cols[] = {
{.str = (char*)"NAME", .len = 4 }
};
text_t g_distribute_rules_idx02_cols[] = {
{.str = (char*)"ID", .len = 2 }
};
text_t g_distribute_rules_idx03_cols[] = {
{.str = (char*)"UID", .len = 3 }
};
#define DISTRIBUTE_RULES_COL_COUNT (sizeof(g_distribute_rules_cols) / sizeof(column_def_t))
#define DISTRIBUTE_RULES_IDX01_COL_COUNT (sizeof(g_distribute_rules_idx01_cols) / sizeof(text_t))
#define DISTRIBUTE_RULES_IDX02_COL_COUNT (sizeof(g_distribute_rules_idx02_cols) / sizeof(text_t))
#define DISTRIBUTE_RULES_IDX03_COL_COUNT (sizeof(g_distribute_rules_idx03_cols) / sizeof(text_t))
static index_def_t g_distribute_rules_indexes[] = {
{{.str = (char *)"IX_DISTRIBUTE_RULE$001", .len = 22},
g_distribute_rules_idx01_cols,
DISTRIBUTE_RULES_IDX01_COL_COUNT,
GS_FALSE},
{{.str = (char *)"IX_DISTRIBUTE_RULE$002", .len = 22},
g_distribute_rules_idx02_cols,
DISTRIBUTE_RULES_IDX02_COL_COUNT,
GS_FALSE},
{{.str = (char *)"IX_DISTRIBUTE_RULE$003", .len = 22},
g_distribute_rules_idx03_cols,
DISTRIBUTE_RULES_IDX03_COL_COUNT,
GS_FALSE}};
// SYS_LINKS
column_def_t g_sys_links_cols[] = {
{ {.str = (char*)"OWNER#", .len = 6 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"NAME", .len = 4 }, GS_TYPE_VARCHAR, 128, GS_FALSE },
{ {.str = (char*)"CTIME", .len = 5 }, GS_TYPE_DATE, 8, GS_FALSE },
{ {.str = (char*)"NODE_ID", .len = 7 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"HOST", .len = 4 }, GS_TYPE_VARCHAR, 2000, GS_TRUE },
{ {.str = (char*)"USERID", .len = 6 }, GS_TYPE_VARCHAR, 64, GS_TRUE },
{ {.str = (char*)"PASSWORD", .len = 8 }, GS_TYPE_VARCHAR, 512, GS_TRUE }
};
text_t g_sys_links_idx01_cols[] = {
{.str = (char*)"OWNER#", .len = 6 },
{.str = (char*)"NAME", .len = 4 }
};
#define SYS_LINKS_COL_COUNT (sizeof(g_sys_links_cols) / sizeof(column_def_t))
#define SYS_LINKS_IDX01_COL_COUNT (sizeof(g_sys_links_idx01_cols) / sizeof(text_t))
static index_def_t g_sys_links_indexes[] = {
{ {.str = (char*)"IX_LINK$001", .len = 11 }, g_sys_links_idx01_cols, SYS_LINKS_IDX01_COL_COUNT, GS_TRUE }
};
// SYS_USER_PRIVS
column_def_t g_user_privs_cols[] = {
{ {.str = (char*)"UID", .len = 3 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"GRANTOR", .len = 7 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"GRANTEE", .len = 7 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"PRIVILEGE", .len = 9 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"OPTION", .len = 6 }, GS_TYPE_INTEGER, 4, GS_TRUE }
};
text_t g_user_privs_idx01_cols[] = {
{.str = (char*)"UID", .len = 3 },
{.str = (char*)"GRANTEE", .len = 7 },
{.str = (char*)"PRIVILEGE", .len = 9 }
};
#define USER_PRIVS_COL_COUNT (sizeof(g_user_privs_cols) / sizeof(column_def_t))
#define USER_PRIVS_IDX01_COL_COUNT (sizeof(g_user_privs_idx01_cols) / sizeof(text_t))
static index_def_t g_user_privs_indexes[] = {
{ {.str = (char*)"IX_USER_PRIVS$_001", .len = 18 }, g_user_privs_idx01_cols, USER_PRIVS_IDX01_COL_COUNT, GS_TRUE }
};
// SYS_RECYCLEBIN
column_def_t g_recyclebin_cols[] = {
{ {.str = (char*)"ID", .len = 2 }, GS_TYPE_BIGINT, 8, GS_FALSE },
{ {.str = (char*)"NAME", .len = 4 }, GS_TYPE_VARCHAR, 30, GS_FALSE },
{ {.str = (char*)"USER#", .len = 5 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"ORG_NAME", .len = 8 }, GS_TYPE_VARCHAR, 64, GS_FALSE },
{ {.str = (char*)"PARTITION_NAME", .len = 14 }, GS_TYPE_VARCHAR, 64, GS_TRUE },
{ {.str = (char*)"TYPE# ", .len = 5 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"OPERATION#", .len = 10 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"SPACE#", .len = 6 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"ENTRY", .len = 5 }, GS_TYPE_BIGINT, 8, GS_TRUE },
{ {.str = (char*)"FLAGS", .len = 5 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"ORG_SCN", .len = 7 }, GS_TYPE_BIGINT, 8, GS_FALSE },
{ {.str = (char*)"REC_SCN", .len = 7 }, GS_TYPE_BIGINT, 8, GS_FALSE },
{ {.str = (char*)"TCHG_SCN", .len = 8 }, GS_TYPE_BIGINT, 8, GS_TRUE },
{ {.str = (char*)"BASE_ID", .len = 7 }, GS_TYPE_BIGINT, 8, GS_FALSE },
{ {.str = (char*)"PURGE_ID", .len = 8 }, GS_TYPE_BIGINT, 8, GS_FALSE },
};
text_t g_recyclebin_idx01_cols[] = {
{.str = (char*)"ID", .len = 3 }
};
text_t g_recyclebin_idx02_cols[] = {
{.str = (char*)"BASE_ID", .len = 7 },
{.str = (char*)"PURGE_ID", .len = 8 }
};
text_t g_recyclebin_idx03_cols[] = {
{.str = (char*)"SPACE#", .len = 6 }
};
text_t g_recyclebin_idx04_cols[] = {
{.str = (char*)"USER#", .len = 5 }
};
#define RECYCLEBIN_COL_COUNT (sizeof(g_recyclebin_cols) / sizeof(column_def_t))
#define RECYCLEBIN_IDX01_COL_COUNT (sizeof(g_recyclebin_idx01_cols) / sizeof(text_t))
#define RECYCLEBIN_IDX02_COL_COUNT (sizeof(g_recyclebin_idx02_cols) / sizeof(text_t))
#define RECYCLEBIN_IDX03_COL_COUNT (sizeof(g_recyclebin_idx03_cols) / sizeof(text_t))
#define RECYCLEBIN_IDX04_COL_COUNT (sizeof(g_recyclebin_idx04_cols) / sizeof(text_t))
static index_def_t g_recyclebin_indexes[] = {
{ {.str = (char*)"IX_RB$001", .len = 9 }, g_recyclebin_idx01_cols, RECYCLEBIN_IDX01_COL_COUNT, GS_TRUE },
{ {.str = (char*)"IX_RB$002", .len = 9 }, g_recyclebin_idx02_cols, RECYCLEBIN_IDX02_COL_COUNT, GS_FALSE },
{ {.str = (char*)"IX_RB$003", .len = 9 }, g_recyclebin_idx03_cols, RECYCLEBIN_IDX03_COL_COUNT, GS_FALSE },
{ {.str = (char*)"IX_RB$004", .len = 9 }, g_recyclebin_idx04_cols, RECYCLEBIN_IDX04_COL_COUNT, GS_FALSE }
};
// SYS_BACKUP_SETS
column_def_t g_backup_set_cols[] = {
{ {.str = (char*)"RECID", .len = 5 }, GS_TYPE_BIGINT, 8, GS_FALSE },
{ {.str = (char*)"TYPE", .len = 4 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"STAGE", .len = 5 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"STATUS", .len = 6 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"INCREMENTAL_LEVEL", .len = 17 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"TAG ", .len = 3 }, GS_TYPE_VARCHAR, 64, GS_FALSE },
{ {.str = (char*)"SCN", .len = 3 }, GS_TYPE_BIGINT, 8, GS_FALSE },
{ {.str = (char*)"LSN", .len = 3 }, GS_TYPE_BIGINT, 8, GS_FALSE },
{ {.str = (char*)"DEVICE_TYPE", .len = 11 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"BASE_TAG", .len = 8 }, GS_TYPE_VARCHAR, 64, GS_FALSE },
{ {.str = (char*)"DIR", .len = 3 }, GS_TYPE_VARCHAR, 256, GS_FALSE },
{ {.str = (char*)"RESETLOGS", .len = 9 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"POLICY", .len = 6 }, GS_TYPE_VARCHAR, 128, GS_FALSE },
{ {.str = (char*)"RCY_ASN", .len = 7 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"RCY_OFFSET", .len = 10 }, GS_TYPE_BIGINT, 8, GS_FALSE },
{ {.str = (char*)"RCY_LFN", .len = 7 }, GS_TYPE_BIGINT, 8, GS_FALSE },
{ {.str = (char*)"LRP_ASN", .len = 7 }, GS_TYPE_INTEGER, 4, GS_FALSE },
{ {.str = (char*)"LRP_OFFSET", .len = 10 }, GS_TYPE_BIGINT, 8, GS_FALSE },
{ {.str = (char*)"LRP_LFN", .len = 7 }, GS_TYPE_BIGINT, 8, GS_FALSE },
{ {.str = (char*)"START_TIME", .len = 10 }, GS_TYPE_TIMESTAMP, 8, GS_FALSE },
{ {.str = (char*)"COMPLETION_TIME", .len = 15 }, GS_TYPE_TIMESTAMP, 8, GS_FALSE },
};
text_t g_backup_set_idx01_cols[] = {
{.str = (char*)"RECID", .len = 5 }
};
text_t g_backup_set_idx02_cols[] = {
{.str = (char*)"TAG", .len = 3 }
};
#define BACKUP_SET_COL_COUNT (sizeof(g_backup_set_cols) / sizeof(column_def_t))
#define BACKUP_SET_IDX01_COL_COUNT (sizeof(g_backup_set_idx01_cols) / sizeof(text_t))
#define BACKUP_SET_IDX02_COL_COUNT (sizeof(g_backup_set_idx02_cols) / sizeof(text_t))
static index_def_t g_backup_set_indexes[] = {
{ {.str = (char*)"IX_BACKUP_SET$001", .len = 17 }, g_backup_set_idx01_cols, BACKUP_SET_IDX01_COL_COUNT, GS_TRUE },
{ {.str = (char*)"IX_BACKUP_SET$002", .len = 17 }, g_backup_set_idx02_cols, BACKUP_SET_IDX02_COL_COUNT, GS_TRUE },
};
// SYS_HISTGRAM_ABSTR
column_def_t g_histgram_abstr_cols[] = {
{ {.str = (char*)"USER#", .len = 5 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"TAB#", .len = 4 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"COL#", .len = 4 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"BUCKET_NUM", .len = 10 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"ROW_NUM", .len = 7 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"NULL_NUM ", .len = 8 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"ANALYZE_TIME", .len = 12 }, GS_TYPE_DATE, 8, GS_TRUE },
{ {.str = (char*)"MINVALUE", .len = 8 }, GS_TYPE_VARCHAR, 4000, GS_TRUE },
{ {.str = (char*)"MAXVALUE", .len = 8 }, GS_TYPE_VARCHAR, 4000, GS_TRUE },
{ {.str = (char*)"DIST_NUM", .len = 8 }, GS_TYPE_INTEGER, 4, GS_TRUE },
{ {.str = (char*)"DENSITY", .len = 7 }, GS_TYPE_REAL, 8, GS_TRUE },
{ {.str = (char*)"SPARE1", .len = 6 }, GS_TYPE_BIGINT, 8, GS_TRUE },
{ {.str = (char*)"SPARE2", .len = 6 }, GS_TYPE_BIGINT, 8, GS_TRUE },
{ {.str = (char*)"SPARE3", .len = 6 }, GS_TYPE_BIGINT, 8, GS_TRUE },
{ {.str = (char*)"SPARE4", .len = 6 }, GS_TYPE_BIGINT, 8, GS_TRUE },
};
text_t g_histgram_abstr_idx01_cols[] = {
{.str = (char*)"ANALYZE_TIME", .len = 12 }
};
text_t g_histgram_abstr_idx02_cols[] = {
{.str = (char*)"USER#", .len = 5 },
{.str = (char*)"TAB#", .len = 4 },
{.str = (char*)"COL#", .len = 4 },
{.str = (char*)"SPARE1", .len = 6 },
{.str = (char*)"SPARE2", .len = 6 }
};
#define HISTGRAM_ABSTR_COL_COUNT (sizeof(g_histgram_abstr_cols) / sizeof(column_def_t))
#define HISTGRAM_ABSTR_IDX01_COL_COUNT (sizeof(g_histgram_abstr_idx01_cols) / sizeof(text_t))
#define HISTGRAM_ABSTR_IDX02_COL_COUNT (sizeof(g_histgram_abstr_idx02_cols) / sizeof(text_t))
static index_def_t g_histgram_abstr_indexes[] = {
{{.str = (char *)"IX_HIST_HEAD_002", .len = 16},
g_histgram_abstr_idx01_cols,
HISTGRAM_ABSTR_IDX01_COL_COUNT,
GS_FALSE},
{{.str = (char *)"IX_HIST_HEAD_003", .len = 16},
g_histgram_abstr_idx02_cols,
HISTGRAM_ABSTR_IDX02_COL_COUNT,
GS_TRUE},
};
/************************************table define end*************************************/
status_t knl_open_sys_database(knl_session_t *session)
{
knl_alterdb_def_t def;
MEMS_RETURN_IFERR(memset_s(&def, sizeof(knl_alterdb_def_t), 0, sizeof(knl_alterdb_def_t)));
def.action = STARTUP_DATABASE_OPEN;
return knl_alter_database(session, &def);
}
static status_t build_space_datafile(knl_session_t *session, char *home,
galist_t *list, char *name, uint32 count, int64 size, bool32 autoextend)
{
knl_device_def_t *dev_def = NULL;
for (uint32 i = 1; i <= count; i++) {
GS_RETURN_IFERR(cm_galist_new(list, sizeof(knl_device_def_t), (pointer_t *)&dev_def));
dev_def->name.str = cm_push(session->stack, GS_FILE_NAME_BUFFER_SIZE);
if (dev_def->name.str == NULL) {
return GS_ERROR;
}
if (count > 1) {
PRTS_RETURN_IFERR(snprintf_s(dev_def->name.str, GS_FILE_NAME_BUFFER_SIZE, GS_FILE_NAME_BUFFER_SIZE - 1,
"%s/data/%s%u", home, name, i));
} else {
PRTS_RETURN_IFERR(snprintf_s(dev_def->name.str, GS_FILE_NAME_BUFFER_SIZE, GS_FILE_NAME_BUFFER_SIZE - 1,
"%s/data/%s", home, name));
}
dev_def->name.len = (uint32)strlen(dev_def->name.str);
dev_def->size = size;
dev_def->autoextend.enabled = autoextend;
if (dev_def->autoextend.enabled) {
dev_def->autoextend.nextsize = SIZE_M(16);
}
}
return GS_SUCCESS;
}
static inline status_t build_ctrlfile(knl_session_t *session, char *home, galist_t *list)
{
text_t *ctrl_file = NULL;
for (uint32 i = 1; i <= DEFAULT_CTRL_FILE; i++) {
GS_RETURN_IFERR(cm_galist_new(list, sizeof(text_t), (pointer_t *)&ctrl_file));
ctrl_file->str = cm_push(session->stack, GS_FILE_NAME_BUFFER_SIZE);
if (ctrl_file->str == NULL) {
return GS_ERROR;
}
PRTS_RETURN_IFERR(snprintf_s(ctrl_file->str, GS_FILE_NAME_BUFFER_SIZE, GS_FILE_NAME_BUFFER_SIZE - 1,
"%s/data/ctrl%u", home, i));
ctrl_file->len = (uint32)strlen(ctrl_file->str);
}
return GS_SUCCESS;
}
static status_t build_create_database_def(knl_session_t *session, char *home, knl_database_def_t *def)
{
int64 space_size = (int64)g_instance->attr.space_size;
MEMS_RETURN_IFERR(memset_s(def, sizeof(knl_database_def_t), 0, sizeof(knl_database_def_t)));
cm_galist_init(&def->ctrlfiles, session->stack, cm_stack_alloc);
cm_galist_init(&def->logfiles, session->stack, cm_stack_alloc);
cm_galist_init(&def->undo_space.datafiles, session->stack, cm_stack_alloc);
cm_galist_init(&def->system_space.datafiles, session->stack, cm_stack_alloc);
cm_galist_init(&def->swap_space.datafiles, session->stack, cm_stack_alloc);
cm_galist_init(&def->user_space.datafiles, session->stack, cm_stack_alloc);
cm_galist_init(&def->temp_space.datafiles, session->stack, cm_stack_alloc);
cm_galist_init(&def->temp_undo_space.datafiles, session->stack, cm_stack_alloc);
cm_galist_init(&def->sysaux_space.datafiles, session->stack, cm_stack_alloc);
def->name = g_db;
def->system_space.name = g_system;
def->system_space.type = SPACE_TYPE_SYSTEM | SPACE_TYPE_DEFAULT;
def->undo_space.name = g_undo;
def->undo_space.type = SPACE_TYPE_UNDO | SPACE_TYPE_DEFAULT;
def->swap_space.name = g_swap;
def->swap_space.type = SPACE_TYPE_TEMP | SPACE_TYPE_SWAP | SPACE_TYPE_DEFAULT;
def->user_space.name = g_users;
def->user_space.type = SPACE_TYPE_USERS | SPACE_TYPE_DEFAULT;
def->temp_space.name = g_temp;
def->temp_space.type = SPACE_TYPE_TEMP | SPACE_TYPE_USERS | SPACE_TYPE_DEFAULT;
def->temp_undo_space.name = g_temp_undo;
def->temp_undo_space.type = SPACE_TYPE_UNDO | SPACE_TYPE_TEMP | SPACE_TYPE_DEFAULT;
def->sysaux_space.name = g_sysaux;
def->sysaux_space.type = SPACE_TYPE_SYSAUX | SPACE_TYPE_DEFAULT;
// ctrl file
GS_RETURN_IFERR(build_ctrlfile(session, home, &def->ctrlfiles));
// log file
GS_RETURN_IFERR(
build_space_datafile(session, home, &def->logfiles, "redo", DEFAULT_LOG_FILE, space_size, GS_FALSE));
// SYSTEM
GS_RETURN_IFERR(
build_space_datafile(session, home, &def->system_space.datafiles, "system", 1, space_size, GS_TRUE));
// UNDO
GS_RETURN_IFERR(build_space_datafile(session, home, &def->undo_space.datafiles, "undo", 1, space_size, GS_TRUE));
// DEFAULT
GS_RETURN_IFERR(build_space_datafile(
session, home, &def->user_space.datafiles, "user", DEFAULT_USER_FILE, space_size, GS_TRUE));
// TEMPORARY
GS_RETURN_IFERR(build_space_datafile(
session, home, &def->swap_space.datafiles, "swap", DEFAULT_SWAP_FILE, space_size, GS_TRUE));
// SYSAUX
GS_RETURN_IFERR(
build_space_datafile(session, home, &def->sysaux_space.datafiles, "sysaux", 1, space_size, GS_FALSE));
def->arch_mode = ARCHIVE_LOG_ON;
return GS_SUCCESS;
}
status_t knl_create_sys_database(knl_session_t *knl_session, char *home)
{
knl_database_def_t def;
CM_SAVE_STACK(knl_session->stack);
if (build_create_database_def(knl_session, home, &def) != GS_SUCCESS) {
CM_RESTORE_STACK(knl_session->stack);
return GS_ERROR;
}
if (knl_create_database(knl_session, &def) != GS_SUCCESS) {
CM_RESTORE_STACK(knl_session->stack);
return GS_ERROR;
}
CM_RESTORE_STACK(knl_session->stack);
return GS_SUCCESS;
}
static status_t build_index_def(
knl_session_t *session, const table_def_t *table_def, const index_def_t *index_def, knl_index_def_t *def)
{
knl_index_col_def_t *column = NULL;
def->user = g_user;
def->name = index_def->name;
def->table = table_def->name;
def->space = *table_def->space;
def->unique = index_def->is_unique;
def->cr_mode = CR_PAGE;
def->options |= CREATE_IF_NOT_EXISTS;
cm_galist_init(&def->columns, session->stack, cm_stack_alloc);
for (uint32 i = 0; i < index_def->col_count; i++) {
GS_RETURN_IFERR(cm_galist_new(&def->columns, sizeof(knl_index_col_def_t), (void **)&column));
MEMS_RETURN_IFERR(memset_s(column, sizeof(knl_index_col_def_t), 0, sizeof(knl_index_col_def_t)));
column->name = index_def->cols[i];
column->mode = SORT_MODE_ASC;
}
return GS_SUCCESS;
}
static status_t knl_create_sys_index(knl_session_t *session, table_def_t *table_def, index_def_t *index_def)
{
knl_index_def_t def;
MEMS_RETURN_IFERR(memset_s(&def, sizeof(knl_index_def_t), 0, sizeof(knl_index_def_t)));
CM_SAVE_STACK(session->stack);
if (build_index_def(session, table_def, index_def, &def) != GS_SUCCESS) {
CM_RESTORE_STACK(session->stack);
return GS_ERROR;
}
status_t status = knl_create_index(session, &def);
CM_RESTORE_STACK(session->stack);
return status;
}
static status_t build_table_def(knl_session_t *session, table_def_t *table_def, knl_table_def_t *def)
{
knl_column_def_t *column = NULL;
def->name = table_def->name;
def->sysid = table_def->sysid;
def->space = *table_def->space;
def->type = table_def->type;
def->schema = g_user;
def->cr_mode = CR_PAGE;
def->options |= CREATE_IF_NOT_EXISTS;
cm_galist_init(&def->columns, session->stack, cm_stack_alloc);
cm_galist_init(&def->constraints, session->stack, cm_stack_alloc);
for (uint32 i = 0; i < table_def->col_count; i++) {
GS_RETURN_IFERR(cm_galist_new(&def->columns, sizeof(knl_column_def_t), (pointer_t *)&column));
MEMS_RETURN_IFERR(memset_s(column, sizeof(knl_column_def_t), 0, sizeof(knl_column_def_t)));
column->name = table_def->cols[i].name;
cm_galist_init(&column->ref_columns, session->stack, cm_stack_alloc);
column->table = (void *)&def;
column->has_null = GS_TRUE;
column->primary = GS_FALSE;
column->nullable = table_def->cols[i].nullable;
column->typmod.size = table_def->cols[i].size;
column->typmod.datatype = table_def->cols[i].type;
}
return GS_SUCCESS;
}
static status_t knl_create_sys_table(knl_session_t *session, table_def_t *table_def)
{
knl_table_def_t def;
MEMS_RETURN_IFERR(memset_s(&def, sizeof(knl_table_def_t), 0, sizeof(knl_table_def_t)));
CM_SAVE_STACK(session->stack);
if (build_table_def(session, table_def, &def) != GS_SUCCESS) {
CM_RESTORE_STACK(session->stack);
return GS_ERROR;
}
status_t status = knl_create_table(session, &def);
CM_RESTORE_STACK(session->stack);
return status;
}
static status_t knl_load_sys_def(knl_session_t *session, text_t *table)
{
knl_alter_sys_def_t def;
MEMS_RETURN_IFERR(memset_s(&def, sizeof(knl_alter_sys_def_t), 0, sizeof(knl_alter_sys_def_t)));
def.action = ALSYS_LOAD_DC;
MEMS_RETURN_IFERR(strncpy_s(def.value, GS_PARAM_BUFFER_SIZE, table->str, table->len));
MEMS_RETURN_IFERR(strncpy_s(def.param, GS_NAME_BUFFER_SIZE, g_user.str, g_user.len));
return knl_load_sys_dc(session, &def);
}
static inline status_t knl_create_table_func(knl_session_t *knl_session, table_def_t *table_def)
{
if (knl_create_sys_table(knl_session, table_def) != GS_SUCCESS) {
return GS_ERROR;
}
for (uint32 i = 0; i < table_def->index_count; i++) {
GS_RETURN_IFERR(knl_create_sys_index(knl_session, table_def, &table_def->index[i]));
}
return knl_load_sys_def(knl_session, &table_def->name);
}
static table_def_t g_sys_tables[] = {
{{.str = (char *)"SYS_LOBS", .len = 8},
g_sys_lobs_cols,
SYS_LOBS_COL_COUNT,
(text_t *)&g_system,
SYS_LOB_ID,
1,
g_sys_lobs_indexes,
TABLE_TYPE_HEAP},
{{.str = (char *)"SYS_RECYCLEBIN", .len = 14},
g_recyclebin_cols,
RECYCLEBIN_COL_COUNT,
(text_t *)&g_system,
SYS_RB_ID,
4,
g_recyclebin_indexes,
TABLE_TYPE_HEAP},
{{.str = (char *)"SYS_CONSTRAINT_DEFS", .len = 19},
g_consdef_cols,
CONSDEF_COL_COUNT,
(text_t *)&g_system,
SYS_CONSDEF_ID,
3,
g_consdef_indexes,
TABLE_TYPE_HEAP},
{{.str = (char *)"SYS_VIEWS", .len = 9},
g_sys_views_cols,
SYS_VIEWS_COL_COUNT,
(text_t *)&g_system,
SYS_VIEW_ID,
2,
g_sys_views_indexes,
TABLE_TYPE_HEAP},
{{.str = (char *)"SYS_DUMMY", .len = 9},
g_sys_dummy_cols,
SYS_DUMMY_COL_COUNT,
(text_t *)&g_system,
DUAL_ID,
0,
NULL,
TABLE_TYPE_HEAP},
{{.str = (char *)"SYS_PENDING_TRANS", .len = 17},
g_pending_trans_cols,
PENDING_TRANS_COL_COUNT,
(text_t *)&g_system,
SYS_PENDING_TRANS_ID,
0,
NULL,
TABLE_TYPE_HEAP},
{{.str = (char *)"SYS_SYNONYMS", .len = 12},
g_sys_synonyms_cols,
SYS_SYNONYMS_COL_COUNT,
(text_t *)&g_system,
SYS_SYN_ID,
2,
g_sys_synonyms_indexes,
TABLE_TYPE_HEAP},
{{.str = (char *)"SYS_PRIVS", .len = 9},
g_sys_privs_cols,
SYS_PRIVS_COL_COUNT,
(text_t *)&g_system,
SYS_PRIVS_ID,
1,
g_sys_privs_indexes,
TABLE_TYPE_HEAP},
{{.str = (char *)"SYS_OBJECT_PRIVS", .len = 16},
g_object_privs_cols,
OBJECT_PRIVS_COL_COUNT,
(text_t *)&g_system,
OBJECT_PRIVS_ID,
3,
g_object_privs_indexes,
TABLE_TYPE_HEAP},
{{.str = (char *)"SYS_USER_ROLES", .len = 14},
g_user_roles_cols,
USER_ROLES_COL_COUNT,
(text_t *)&g_system,
SYS_USER_ROLES_ID,
2,
g_user_roles_indexes,
TABLE_TYPE_HEAP},
{{.str = (char *)"SYS_ROLES", .len = 9},
g_sys_roles_cols,
SYS_ROLES_COL_COUNT,
(text_t *)&g_system,
SYS_ROLES_ID,
2,
g_sys_roles_indexes,
TABLE_TYPE_HEAP},
{{.str = (char *)"SYS_TABLE_PARTS", .len = 15},
g_table_parts_cols,
TABLE_PARTS_COL_COUNT,
(text_t *)&g_system,
SYS_TABLEPART_ID,
1,
g_table_parts_indexes,
TABLE_TYPE_HEAP},
{{.str = (char *)"SYS_SHADOW_INDEXES", .len = 18},
g_shadow_indexes_cols,
SHADOW_INDEXES_COL_COUNT,
(text_t *)&g_system,
SYS_SHADOW_INDEX_ID,
1,
g_shadow_indexes_indexes,
TABLE_TYPE_HEAP},
{{.str = (char *)"SYS_PROFILE", .len = 11},
g_sys_profile_cols,
SYS_PROFILE_COL_COUNT,
(text_t *)&g_system,
SYS_PROFILE_ID,
1,
g_sys_profile_indexes,
TABLE_TYPE_HEAP},
{{.str = (char *)"SYS_SHADOW_INDEX_PARTS", .len = 22},
g_shw_indexpart_cols,
SHW_INDEXPART_COL_COUNT,
(text_t *)&g_system,
SYS_SHADOW_INDEXPART_ID,
1,
g_shw_indexpart_indexes,
TABLE_TYPE_HEAP},
{{.str = (char *)"SYS_BACKUP_SETS", .len = 15},
g_backup_set_cols,
BACKUP_SET_COL_COUNT,
(text_t *)&g_system,
SYS_BACKUP_SET_ID,
2,
g_backup_set_indexes,
TABLE_TYPE_HEAP},
{{.str = (char *)"SYS_DISTRIBUTE_STRATEGIES", .len = 25},
g_distribute_strategy_cols,
DISTRIBUTE_STRATEGY_COL_COUNT,
(text_t *)&g_system,
SYS_DISTRIBUTE_STRATEGY_ID,
1,
g_distribute_strategy_indexes,
TABLE_TYPE_HEAP},
{{.str = (char *)"SYS_GARBAGE_SEGMENTS", .len = 20},
g_garbage_segments_cols,
GARBAGE_SEGMENTS_COL_COUNT,
(text_t *)&g_system,
SYS_GARBAGE_SEGMENT_ID,
1,
g_garbage_segment_indexes,
TABLE_TYPE_HEAP},
{{.str = (char *)"SYS_USER_HISTORY", .len = 16},
g_user_history_cols,
USER_HISTORY_COL_COUNT,
(text_t *)&g_system,
SYS_USER_HISTORY_ID,
1,
g_user_history_indexes,
TABLE_TYPE_HEAP},
{{.str = (char *)"SYS_DML_STATS", .len = 13},
g_sys_dml_stats_cols,
SYS_DML_STATS_COL_COUNT,
(text_t *)&g_system,
SYS_MON_MODS_ALL_ID,
3,
g_sys_dml_stats_indexes,
TABLE_TYPE_HEAP},
{{.str = (char *)"SYS_LINKS", .len = 9},
g_sys_links_cols,
SYS_LINKS_COL_COUNT,
(text_t *)&g_system,
SYS_LINK_ID,
1,
g_sys_links_indexes,
TABLE_TYPE_HEAP},
{{.str = (char *)"SYS_DISTRIBUTE_RULES", .len = 20},
g_distribute_rules_cols,
DISTRIBUTE_RULES_COL_COUNT,
(text_t *)&g_system,
SYS_DISTRIBUTE_RULE_ID,
3,
g_distribute_rules_indexes,
TABLE_TYPE_HEAP},
{{.str = (char *)"SYS_TMP_SEG_STATS", .len = 17},
g_tmp_seg_stats_cols,
TMP_SEG_STATS_COL_COUNT,
(text_t *)&g_swap,
SYS_TMP_SEG_STAT_ID,
2,
g_tmp_seg_stats_indexes,
TABLE_TYPE_TRANS_TEMP},
{{.str = (char *)"SYS_SUB_TABLE_PARTS", .len = 19},
g_subtable_parts_cols,
SUBTABLE_PARTS_COL_COUNT,
(text_t *)&g_system,
SYS_SUB_TABLE_PARTS_ID,
2,
g_subtable_parts_indexes,
TABLE_TYPE_HEAP},
{{.str = (char *)"SYS_DDM", .len = 7},
g_sys_ddm_cols,
SYS_DDM_COL_COUNT,
(text_t *)&g_system,
SYS_DDM_ID,
2,
g_sys_ddm_indexes,
TABLE_TYPE_HEAP},
{{.str = (char *)"SYS_POLICIES", .len = 12},
g_sys_policies_cols,
SYS_POLICIES_COL_COUNT,
(text_t *)&g_system,
SYS_POLICY_ID,
1,
g_sys_policies_indexes,
TABLE_TYPE_HEAP},
{{.str = (char *)"SYS_USER_PRIVS", .len = 14},
g_user_privs_cols,
USER_PRIVS_COL_COUNT,
(text_t *)&g_system,
SYS_USER_PRIVS_ID,
1,
g_user_privs_indexes,
TABLE_TYPE_HEAP},
{{.str = (char *)"SYS_TENANTS", .len = 11},
g_sys_tenants_cols,
SYS_TENANTS_COL_COUNT,
(text_t *)&g_system,
SYS_TENANTS_ID,
2,
g_sys_tenants_indexes,
TABLE_TYPE_HEAP},
{{.str = (char *)"SYS_INSTANCE_INFO", .len = 17},
g_sys_instance_info_cols,
SYS_INSTANCE_INFO_COL_COUNT,
(text_t *)&g_system,
SYS_INSTANCE_INFO_ID,
1,
g_sys_instance_info_indexes,
TABLE_TYPE_HEAP},
{{.str = (char *)"SYS_TEMP_HISTGRAM", .len = 17},
g_temp_histgram_cols,
TEMP_HISTGRAM_COL_COUNT,
(text_t *)&g_sysaux,
SYS_TEMP_HISTGRAM_ID,
1,
g_temp_histgram_indexes,
TABLE_TYPE_HEAP},
{{.str = (char *)"SYS_TEMP_HISTGRAM_ABSTR", .len = 23},
g_temp_hist_abstr_cols,
TEMP_HIST_ABSTR_COL_COUNT,
(text_t *)&g_sysaux,
SYS_TEMP_HIST_HEAD_ID,
2,
g_temp_hist_abstr_indexes,
TABLE_TYPE_HEAP},
{{.str = (char *)"SYS_HISTGRAM_ABSTR", .len = 18},
g_histgram_abstr_cols,
HISTGRAM_ABSTR_COL_COUNT,
(text_t *)&g_sysaux,
SYS_HIST_HEAD_ID,
2,
g_histgram_abstr_indexes,
TABLE_TYPE_HEAP},
};
static inline status_t knl_build_sys_tables(knl_session_t *session)
{
uint32 sys_table_count = sizeof(g_sys_tables) / sizeof(table_def_t);
for (uint32 i = 0; i < sys_table_count; ++i) {
GS_RETURN_IFERR(knl_create_table_func(session, &g_sys_tables[i]));
}
return GS_SUCCESS;
}
static inline status_t knl_create_role_func(knl_session_t *session, char *name)
{
knl_role_def_t def;
def.owner_uid = 0;
def.password[0] = '\0';
def.is_encrypt = GS_FALSE;
int32 ret = sprintf_s(def.name, GS_NAME_BUFFER_SIZE, "%s", name);
knl_securec_check_ss(ret);
return knl_create_role(session, &def);
}
static char *g_sys_roles[] = {
(char*)"DBA",
(char*)"RESOURCE"
};
static inline status_t knl_build_sys_roles(knl_session_t *session)
{
uint32 sys_role_count = sizeof(g_sys_roles) / sizeof(char*);
for (uint32 i = 0; i < sys_role_count; ++i) {
GS_RETURN_IFERR(knl_create_role_func(session, g_sys_roles[i]));
}
return GS_SUCCESS;
}
status_t knl_build_sys_objects(knl_handle_t handle)
{
knl_session_t *session = (knl_session_t*)handle;
if (knl_build_sys_tables(session) != GS_SUCCESS) {
return GS_ERROR;
}
if (knl_build_sys_roles(session) != GS_SUCCESS) {
return GS_ERROR;
}
return GS_SUCCESS;
}
status_t knl_create_user_table(knl_session_t * session, table_def_t *table)
{
return knl_create_table_func(session, table);
}
#ifdef __cplusplus
}
#endif
| 45.275905 | 120 | 0.592621 |
4236fd5a10a133984e37b40375b0c8aade3d10ae | 2,166 | c | C | lib/libft/src/ft_split_whitespaces.c | Tabascow01/Fillit-42 | 8ccb932e306c7126fb66b1ae5d0fa19b6edd924c | [
"MIT"
] | null | null | null | lib/libft/src/ft_split_whitespaces.c | Tabascow01/Fillit-42 | 8ccb932e306c7126fb66b1ae5d0fa19b6edd924c | [
"MIT"
] | null | null | null | lib/libft/src/ft_split_whitespaces.c | Tabascow01/Fillit-42 | 8ccb932e306c7126fb66b1ae5d0fa19b6edd924c | [
"MIT"
] | null | null | null | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ft_split_whitespaces.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: mrembusc <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2016/11/12 12:25:47 by mrembusc #+# #+# */
/* Updated: 2016/11/12 12:26:41 by mrembusc ### ########.fr */
/* */
/* ************************************************************************** */
static int ft_count_words(char *str)
{
int i;
int words;
i = 0;
words = 0;
while (str[i])
{
if (str[i] != ' ' && str[i] != '\n' && str[i] != '\t')
{
if (str[i + 1] == ' ' || str[i + 1] == '\n' || str[i + 1] == '\t'
|| str[i + 1] == '\0')
words++;
}
i++;
}
return (words + 1);
}
static int ft_count_letters(char *str)
{
int i;
int letters;
i = 0;
letters = 0;
while (str[i] == ' ' || str[i] == '\n' || str[i] == '\t')
i++;
while (str[i] != ' ' && str[i] != '\n' && str[i] != '\t' && str[i] != '\0')
{
letters++;
i++;
}
return (letters + 1);
}
static char *ft_copy(char *str, int *k)
{
int i;
char *tab;
i = 0;
if (!(tab = (char*)malloc(sizeof(char) * ft_count_letters(&str[*k]))))
return (NULL);
while (str[*k] != ' ' && str[*k] != '\n' && str[*k] != '\t' &&
str[*k] != '\0')
{
tab[i] = str[*k];
i++;
*k += 1;
}
tab[i] = '\0';
return (tab);
}
char **ft_split_whitespaces(char *str)
{
char **tab;
int i;
int k;
i = 0;
k = 0;
if (!(tab = (char**)malloc(sizeof(char*) * (ft_count_words(str)))))
return (NULL);
while (str[k])
{
while (str[k] == ' ' || str[k] == '\n' || str[k] == '\t')
k++;
if (str[k])
{
tab[i] = ft_copy(str, &k);
i++;
}
}
tab[i] = 0;
return (tab);
}
| 23.543478 | 80 | 0.303324 |
0970ee206e71b6a50f25d8321f82a13cd1ee3a6f | 564 | h | C | src/debug/logUtils.h | mitos-drg/lo28 | fe5446f0d74557f93798e4cc9c290e55303ad811 | [
"Zlib"
] | null | null | null | src/debug/logUtils.h | mitos-drg/lo28 | fe5446f0d74557f93798e4cc9c290e55303ad811 | [
"Zlib"
] | null | null | null | src/debug/logUtils.h | mitos-drg/lo28 | fe5446f0d74557f93798e4cc9c290e55303ad811 | [
"Zlib"
] | null | null | null | //
// Copyright (C) 2021 by Mikolaj Mijakowski (Mitos), for further legal details see LICENSE.md
//
#pragma once
#include <debug/log.h>
#ifdef DEBUG
#define info(message, ...) LogInfo("lo28", message, ##__VA_ARGS__)
#define success(message, ...) LogSuccess("lo28", message, ##__VA_ARGS__)
#define warn(message, ...) LogWarn("lo28", message, ##__VA_ARGS__)
#define error(message, ...) LogError("lo28", message, ##__VA_ARGS__)
#else
#define info(message, ...)
#define success(message, ...)
#define warn(message, ...)
#define error(message, ...)
#endif // DEBUG | 25.636364 | 93 | 0.684397 |
51c284e248e658da08da41e9b481077642f772c5 | 1,507 | h | C | System/Library/PrivateFrameworks/PhotoLibraryServices.framework/PLReframeService.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | 2 | 2021-11-02T09:23:27.000Z | 2022-03-28T08:21:57.000Z | System/Library/PrivateFrameworks/PhotoLibraryServices.framework/PLReframeService.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | null | null | null | System/Library/PrivateFrameworks/PhotoLibraryServices.framework/PLReframeService.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | 1 | 2022-03-28T08:21:59.000Z | 2022-03-28T08:21:59.000Z | /*
* This header is generated by classdump-dyld 1.5
* on Friday, April 30, 2021 at 11:36:00 AM Mountain Standard Time
* Operating System: Version 13.5.1 (Build 17F80)
* Image Source: /System/Library/PrivateFrameworks/PhotoLibraryServices.framework/PhotoLibraryServices
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley.
*/
@protocol OS_dispatch_queue;
#import <PhotoLibraryServices/PhotoLibraryServices-Structs.h>
@class NSProgress, PLPhotoLibraryBundle, PLPhotoLibrary, PLDeferredPhotoFinalizer, NSObject;
@interface PLReframeService : NSObject {
os_unfair_lock_s _lock;
Aq _cancellationGenerationCounter;
NSProgress* _currentProgress;
PLPhotoLibraryBundle* _libraryBundle;
PLPhotoLibrary* _photoLibrary;
PLDeferredPhotoFinalizer* _deferredPhotoFinalizer;
NSObject*<OS_dispatch_queue> _serializationQueue;
}
@property (nonatomic,readonly) NSObject*<OS_dispatch_queue> serializationQueue; //@synthesize serializationQueue=_serializationQueue - In the implementation block
-(id)photoLibrary;
-(id)initWithLibraryBundle:(id)arg1 ;
-(id)deferredPhotoFinalizer;
-(id)enqueueReframeRequestForAssetUUID:(id)arg1 imageConversionClient:(id)arg2 videoConversionClient:(id)arg3 isOnDemand:(BOOL)arg4 completionHandler:(/*^block*/id)arg5 ;
-(NSObject*<OS_dispatch_queue>)serializationQueue;
@end
| 44.323529 | 175 | 0.739881 |
b6fc2d089c1d29fe8e2ab7df309ff1f40184a178 | 3,083 | h | C | components/freertos/esp_additions/include/freertos/task_snapshot.h | iPlon-org/esp-idf | a5227db2a75102ca1a17860188c3c352a529a01b | [
"Apache-2.0"
] | 5 | 2021-11-22T06:47:54.000Z | 2022-01-04T06:58:43.000Z | components/freertos/esp_additions/include/freertos/task_snapshot.h | iPlon-org/esp-idf | a5227db2a75102ca1a17860188c3c352a529a01b | [
"Apache-2.0"
] | null | null | null | components/freertos/esp_additions/include/freertos/task_snapshot.h | iPlon-org/esp-idf | a5227db2a75102ca1a17860188c3c352a529a01b | [
"Apache-2.0"
] | 3 | 2021-08-07T09:17:31.000Z | 2022-03-20T21:54:52.000Z | /*
* SPDX-FileCopyrightText: 2015-2021 Espressif Systems (Shanghai) CO LTD
*
* SPDX-License-Identifier: Apache-2.0
*/
#pragma once
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#if ( configENABLE_TASK_SNAPSHOT == 1 )
#ifdef __cplusplus
extern "C" {
#endif
/**
* Check `freertos_tasks_c_additions.h` file for more info
* about these functions declaration.
*/
UBaseType_t pxTCBGetSize ( void );
ListItem_t* pxTCBGetStateListItem ( void *pxTCB );
StackType_t* pxTCBGetStartOfStack ( void *pxTCB );
StackType_t* pxTCBGetTopOfStack ( void *pxTCB );
StackType_t* pxTCBGetEndOfStack ( void *pxTCB );
List_t* pxListGetReadyTask ( UBaseType_t idx );
List_t* pxListGetReadyPendingTask ( UBaseType_t idx );
List_t* pxGetDelayedTaskList ( void );
List_t* pxGetOverflowDelayedTaskList ( void );
List_t* pxGetTasksWaitingTermination ( void );
List_t* pxGetSuspendedTaskList ( void );
/**
* Used with the uxTaskGetSnapshotAll() function to save memory snapshot of each task in the system.
* We need this struct because TCB_t is defined (hidden) in tasks.c.
*/
typedef struct xTASK_SNAPSHOT
{
void *pxTCB; /*!< Address of task control block. */
StackType_t *pxTopOfStack; /*!< Points to the location of the last item placed on the tasks stack. */
StackType_t *pxEndOfStack; /*!< Points to the end of the stack. pxTopOfStack < pxEndOfStack, stack grows hi2lo
pxTopOfStack > pxEndOfStack, stack grows lo2hi*/
} TaskSnapshot_t;
/*
* This function fills array with TaskSnapshot_t structures for every task in the system.
* Used by panic handling code to get snapshots of all tasks in the system.
* Only available when configENABLE_TASK_SNAPSHOT is set to 1.
* @param pxTaskSnapshotArray Pointer to array of TaskSnapshot_t structures to store tasks snapshot data.
* @param uxArraySize Size of tasks snapshots array.
* @param pxTcbSz Pointer to store size of TCB.
* @return Number of elements stored in array.
*/
UBaseType_t uxTaskGetSnapshotAll( TaskSnapshot_t * const pxTaskSnapshotArray, const UBaseType_t uxArraySize, UBaseType_t * const pxTcbSz );
/*
* This function iterates over all tasks in the system.
* Used by panic handling code to iterate over tasks in the system.
* Only available when configENABLE_TASK_SNAPSHOT is set to 1.
* @note This function should not be used while FreeRTOS is running (as it doesn't acquire any locks).
* @param pxTask task handle.
* @return Handle for the next task. If pxTask is NULL, returns hadnle for the first task.
*/
TaskHandle_t pxTaskGetNext( TaskHandle_t pxTask );
/*
* This function fills TaskSnapshot_t structure for specified task.
* Used by panic handling code to get snapshot of a task.
* Only available when configENABLE_TASK_SNAPSHOT is set to 1.
* @note This function should not be used while FreeRTOS is running (as it doesn't acquire any locks).
* @param pxTask task handle.
* @param pxTaskSnapshot address of TaskSnapshot_t structure to fill.
*/
void vTaskGetSnapshot( TaskHandle_t pxTask, TaskSnapshot_t *pxTaskSnapshot );
#ifdef __cplusplus
}
#endif
#endif
| 37.144578 | 139 | 0.759001 |
2288a7f1d39be1a48e2de3634d22ffe7df62fbbd | 7,885 | h | C | bsp_for_art-badge/rt-thread/libcpu/sim/sim.h | Rbb666/SDK | cdf0bfeeb35b989ccf13c41b9625059de5fec87b | [
"Apache-2.0"
] | null | null | null | bsp_for_art-badge/rt-thread/libcpu/sim/sim.h | Rbb666/SDK | cdf0bfeeb35b989ccf13c41b9625059de5fec87b | [
"Apache-2.0"
] | null | null | null | bsp_for_art-badge/rt-thread/libcpu/sim/sim.h | Rbb666/SDK | cdf0bfeeb35b989ccf13c41b9625059de5fec87b | [
"Apache-2.0"
] | null | null | null | /*
* SPDX-License-Identifier: Apache-2.0
*
* Change Logs:
* Date Author Notes
* 2021-04-18 tyx first implementation
*/
#ifndef __SIM_H__
#define __SIM_H__
#include <sim_type.h>
#ifdef __cplusplus
extern "C" {
#endif
#define SIM_PATH_MAXN (4096)
#define SIM_INTERRUPT_MAX (256)
#define SIM_ALIGN(size, align) (((size) + (align) - 1) & ~((align) - 1))
#define SIM_ALIGN_DOWN(size, align) ((size) & ~((align) - 1))
#define SIM_WAITING_FOREVER (-1)
#define SIM_WAITING_NO (0)
/* mem api */
sim_pointer_t sim_malloc(sim_size_t size);
void sim_free(sim_pointer_t ptr);
// thread def
typedef sim_object_t sim_thread_t;
// thread api
sim_err_t sim_thread_init(sim_thread_t* thread, int (*func)(sim_pointer_t),
sim_pointer_t priv, sim_size_t stack_size);
void sim_thread_deinit(sim_thread_t* thread);
sim_err_t sim_thread_suspend(sim_thread_t* thread);
sim_err_t sim_thread_resume(sim_thread_t* thread);
sim_long_t sim_thread_identifier(sim_thread_t* thread);
sim_err_t sim_thread_setaffinity(sim_thread_t* thread, sim_ulong_t affinity_mask);
sim_ulong_t sim_thread_getaffinity(sim_thread_t* thread);
sim_err_t sim_thread_setname(sim_thread_t* thread, sim_char_t const* name);
typedef sim_object_t sim_context_t;
// thread context
sim_err_t sim_context_init(sim_context_t* ctx);
void sim_context_deinit(sim_context_t* ctx);
sim_err_t sim_context_get(sim_context_t* ctx, sim_thread_t* thread);
sim_err_t sim_context_set(sim_context_t* ctx, sim_thread_t* thread);
//time
void sim_usleep(sim_time_t us);
void sim_msleep(sim_time_t ms);
void sim_sleep(sim_time_t s);
sim_time_t sim_mtime(void);
sim_time_t sim_utime(void);
// timer def
typedef sim_object_t sim_timer_t;
//timer api
sim_err_t sim_timer_init(sim_timer_t* timer, sim_time_t time, sim_bool_t periodic,
void(*func)(sim_pointer_t), sim_pointer_t priv);
void sim_timer_deinit(sim_timer_t* timer);
sim_err_t sim_timer_stop(sim_timer_t* timer);
sim_err_t sim_timer_start(sim_timer_t* timer);
sim_bool_t sim_timer_isactive(sim_timer_t* timer);
//semaphore def
typedef sim_object_t sim_sem_t;
//semaphore api
sim_err_t sim_sem_init(sim_sem_t* sem, sim_size_t value);
void sim_sem_deinit(sim_sem_t* sem);
sim_err_t sim_sem_take(sim_sem_t* sem, sim_time_t timeout);
sim_err_t sim_sem_release(sim_sem_t* sem);
//mutex def
typedef sim_object_t sim_mutex_t;
//mutex api
sim_err_t sim_mutex_init(sim_mutex_t* mutex);
void sim_mutex_deinit(sim_mutex_t* mutex);
sim_err_t sim_mutex_get(sim_mutex_t* mutex, sim_time_t timeout);
sim_err_t sim_mutex_put(sim_mutex_t* mutex);
//critical def
typedef sim_object_t sim_critical_t;
//critical
sim_err_t sim_critical_init(sim_critical_t* critical);
void sim_critical_deinit(sim_critical_t* critical);
sim_err_t sim_critical_enter(sim_critical_t* critical);
sim_err_t sim_critical_leave(sim_critical_t* critical);
//atomic32 def
typedef sim_long_t volatile sim_atomic_t;
//atomic api
sim_long_t sim_atomic_compare_and_swap(sim_atomic_t* des, sim_long_t cmp, sim_long_t exc);
//cpu api
void sim_cpu_yield(void);
sim_size_t sim_cpu_count(void);
//event def
typedef sim_object_t sim_event_t;
//event api
sim_err_t sim_event_init(sim_event_t* event, sim_bool_t auto_clear);
void sim_event_deinit(sim_event_t* event);
sim_err_t sim_event_wait(sim_event_t* event, sim_time_t timeout);
sim_err_t sim_event_set(sim_event_t* event);
sim_err_t sim_event_reset(sim_event_t* event);
//queue def
typedef sim_object_t sim_queue_t;
//queue api
sim_err_t sim_queue_init(sim_queue_t* queue, sim_size_t msg_size);
void sim_queue_deinit(sim_queue_t* queue);
sim_size_t sim_queue_push(sim_queue_t* queue, sim_pointer_t *msg, sim_size_t size);
sim_size_t sim_queue_pop(sim_queue_t* queue, sim_pointer_t* msg, sim_size_t size, sim_time_t timeout);
sim_size_t sim_queue_len(sim_queue_t* queue);
//console def
#define SIM_STDOUT 1
#define SIM_STDIN 2
#define SIM_STDERR 3
typedef sim_object_t sim_console_t;
//console api
sim_err_t sim_console_redirect(sim_console_t* console, sim_type_t type);
sim_size_t sim_console_read(sim_console_t* console, sim_byte_t* data, sim_size_t max_size);
sim_size_t sim_console_write(sim_console_t* console, sim_byte_t* data, sim_size_t size);
//std api
sim_size_t sim_stdout(sim_byte_t* data, sim_size_t size);
sim_size_t sim_stderr(sim_byte_t* data, sim_size_t size);
sim_size_t sim_stdint(sim_byte_t* data, sim_size_t max_size);
//file def
#define SIM_FILE_MODE_IFMT 0xF000 // File type mask
#define SIM_FILE_MODE_IFDIR 0x4000 // Directory
#define SIM_FILE_MODE_IFCHR 0x2000 // Character special
#define SIM_FILE_MODE_IFIFO 0x1000 // Pipe
#define SIM_FILE_MODE_IFREG 0x8000 // Regular
#define SIM_FILE_MODE_IREAD 0x0100 // Read permission, owner
#define SIM_FILE_MODE_IWRITE 0x0080 // Write permission, owner
#define SIM_FILE_MODE_IEXEC 0x0040 // Execute/search permission, owner
#define SIM_FILE_SEEK_CUR 1
#define SIM_FILE_SEEK_END 2
#define SIM_FILE_SEEK_SET 0
#define SIM_FILE_O_RDONLY 0x0000 // open for reading only
#define SIM_FILE_O_WRONLY 0x0001 // open for writing only
#define SIM_FILE_O_RDWR 0x0002 // open for reading and writing
#define SIM_FILE_O_APPEND 0x0008 // writes done at eof
#define SIM_FILE_O_CREAT 0x0100 // create and open file
#define SIM_FILE_O_TRUNC 0x0200 // open and truncate
#define SIM_FILE_O_EXCL 0x0400 // open only if file doesn't already exist
typedef struct __sim_file_stat_t
{
sim_flag_t mode;
sim_uint64_t size;
sim_time_t atime;
sim_time_t mtime;
sim_time_t ctime;
}sim_file_stat_t;
typedef sim_object_t sim_file_t;
//file api
sim_err_t sim_file_open(sim_file_t* file, sim_char_t const* path, sim_flag_t oflags);
void sim_file_close(sim_file_t* file);
sim_int64_t sim_file_read(sim_file_t* file, sim_pointer_t buff, sim_size_t size);
sim_int64_t sim_file_write(sim_file_t* file, sim_cpointer_t buff, sim_size_t size);
sim_int64_t sim_file_seek(sim_file_t* file, sim_off_t offset, sim_flag_t mode);
sim_err_t sim_file_flush(sim_file_t* file);
sim_err_t sim_file_rename(sim_char_t const* new_path, sim_char_t const* old_path);
sim_err_t sim_file_remove(sim_char_t const* path);
sim_err_t sim_file_stat(sim_char_t const* path, sim_file_stat_t* stat);
//directory def
typedef struct __sim_directory_space_t
{
sim_uint64_t blocks;
sim_uint64_t bfree;
sim_uint64_t bsize;
}sim_dir_space_t;
typedef sim_bool_t(*sim_dir_walk_func_t)(sim_char_t const*, sim_file_stat_t*, sim_pointer_t);
//directory api
sim_err_t sim_directory_create(sim_char_t const* path, sim_bool_t recursion);
sim_err_t sim_directory_delete(sim_char_t const* path);
sim_err_t sim_directory_space(sim_char_t const* path, sim_dir_space_t* space);
sim_err_t sim_directory_getfiles(sim_char_t const* path, sim_dir_walk_func_t func, sim_pointer_t priv);
//spilock
typedef struct __sim_spinlock_t
{
sim_atomic_t lock;
}sim_spinlock_t;
void sim_spinlock_init(sim_spinlock_t* lock);
void sim_spinlock_lock(sim_spinlock_t* lock);
void sim_spinlock_unlock(sim_spinlock_t* lock);
sim_bool_t sim_spinlock_islock(sim_spinlock_t* lock);
sim_bool_t sim_spinlock_trylock(sim_spinlock_t* lock);
//systick api
void sim_systick_init(sim_time_t tick_per);
void sim_systick_deinit(void);
//interrupt api
void sim_interrupt_server_run(void);
void sim_interrupt_server_stop(void);
void sim_interrupt_enable(long level);
long sim_interrupt_disable(void);
void sim_interrupt_trigger(long index);
void sim_interrupt_schedule_trigger(void);
void sim_interrupt_systick_trigger(void);
void sim_interrupt_schedule_handler(void);
void sim_interrupt_dispatch(long vector);
void sim_interrupt_systick(void);
void sim_interrupt_context_load(sim_handle_t handle[64]);
void sim_interrupt_context_store(sim_handle_t handle[64]);
void sim_shutdown(void);
#ifdef __cplusplus
}
#endif
#endif
| 33.553191 | 103 | 0.802029 |
61270d0912cda7e80cd173092cb8304a25abe51e | 245 | h | C | xianglegou/Classes/Function/User/Interface/ViewController/Mine/GC_MineViewController.h | lieonCX/XGG | 7af459d3d32535d63e3d6e9126df12db1f3e5724 | [
"MIT"
] | null | null | null | xianglegou/Classes/Function/User/Interface/ViewController/Mine/GC_MineViewController.h | lieonCX/XGG | 7af459d3d32535d63e3d6e9126df12db1f3e5724 | [
"MIT"
] | null | null | null | xianglegou/Classes/Function/User/Interface/ViewController/Mine/GC_MineViewController.h | lieonCX/XGG | 7af459d3d32535d63e3d6e9126df12db1f3e5724 | [
"MIT"
] | null | null | null | //
// GC_MineViewController.h
// Rebate
//
// Created by mini3 on 17/3/22.
// Copyright © 2017年 Rebate. All rights reserved.
//
// 首页界面
//
#import "Hen_BaseViewController.h"
@interface GC_MineViewController : Hen_BaseViewController
@end
| 15.3125 | 57 | 0.710204 |
2408020639043aace2c336bae9614a4e5074994a | 827 | h | C | Plugins/ObjectDeliverer/Source/ObjectDeliverer/Public/PacketRule/PacketRuleFixedLength.h | ayumax/CommNet | 02846b9b7533e548e61a81cd76780456362cc069 | [
"MIT"
] | 110 | 2019-02-19T18:50:23.000Z | 2022-03-26T10:45:36.000Z | Plugins/ObjectDeliverer/Source/ObjectDeliverer/Public/PacketRule/PacketRuleFixedLength.h | dlvrydryvr/ObjectDeliverer | e52a88412d4f5c363c612d0a3ac172d4bc8cd74a | [
"MIT"
] | 36 | 2019-01-22T15:08:36.000Z | 2021-12-13T13:43:08.000Z | Plugins/ObjectDeliverer/Source/ObjectDeliverer/Public/PacketRule/PacketRuleFixedLength.h | ayumax/CommNet | 02846b9b7533e548e61a81cd76780456362cc069 | [
"MIT"
] | 25 | 2019-02-19T15:42:07.000Z | 2022-03-17T09:41:50.000Z | // Copyright 2019 ayumax. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "PacketRule.h"
#include "PacketRuleFixedLength.generated.h"
UCLASS(BlueprintType, Blueprintable)
class OBJECTDELIVERER_API UPacketRuleFixedLength : public UPacketRule
{
GENERATED_BODY()
public:
UPacketRuleFixedLength();
~UPacketRuleFixedLength();
virtual void Initialize() override;
virtual void MakeSendPacket(const TArray<uint8>& BodyBuffer) override;
virtual void NotifyReceiveData(const TArray<uint8>& DataBuffer) override;
virtual int32 GetWantSize() override;
virtual UPacketRule* Clone() override;
public:
UPROPERTY(BlueprintReadWrite, EditAnywhere, meta = (ExposeOnSpawn = true), Category = "ObjectDeliverer|PacketRule")
int32 FixedSize = 128;
private:
UPROPERTY(Transient)
TArray<uint8> BufferForSend;
};
| 25.84375 | 116 | 0.794438 |
f9758a755ff4a4165f2dfda4b3a2c13a1a9094d7 | 1,217 | h | C | third_party/NordicSemiconductor/libraries/nrf_cc310/include/dx_reg_base_host.h | yuzhyang/openthread | 38f206c6708d8fc7eae21db6ff3e3a50a2053b58 | [
"BSD-3-Clause"
] | 1 | 2018-09-25T15:27:26.000Z | 2018-09-25T15:27:26.000Z | third_party/NordicSemiconductor/libraries/nrf_cc310/include/dx_reg_base_host.h | yuzhyang/openthread | 38f206c6708d8fc7eae21db6ff3e3a50a2053b58 | [
"BSD-3-Clause"
] | null | null | null | third_party/NordicSemiconductor/libraries/nrf_cc310/include/dx_reg_base_host.h | yuzhyang/openthread | 38f206c6708d8fc7eae21db6ff3e3a50a2053b58 | [
"BSD-3-Clause"
] | 1 | 2019-08-03T17:35:08.000Z | 2019-08-03T17:35:08.000Z | /****************************************************************************
* This confidential and proprietary software may be used only as authorized *
* by a licensing agreement from ARM Israel. *
* Copyright (C) 2015 ARM Limited or its affiliates. All rights reserved. *
* The entire notice above must be reproduced on all authorized copies and *
* copies may only be made to the extent permitted by a licensing agreement *
* from ARM Israel. *
*****************************************************************************/
#ifndef __DX_REG_BASE_HOST_H__
#define __DX_REG_BASE_HOST_H__
/* Identify platform: Xilinx Zynq7000 ZC706 */
#define DX_PLAT_ZYNQ7000 1
#define DX_PLAT_ZYNQ7000_ZC706 1
/* SEP core clock frequency in MHz */
#define DX_SEP_FREQ_MHZ 64
#define DX_BASE_CC 0x5002B000
#define DX_BASE_ENV_REGS 0x40008000
#define DX_BASE_ENV_CC_MEMORIES 0x40008000
#define DX_BASE_ENV_FLASH 0x40008700
#define DX_BASE_ENV_PERF_RAM 0x40009000
#define DX_BASE_HOST_RGF 0x0UL
#define DX_BASE_CRY_KERNEL 0x0UL
#define DX_BASE_ROM 0x40000000
#define DX_BASE_RNG 0x0000UL
#endif /*__DX_REG_BASE_HOST_H__*/
| 38.03125 | 78 | 0.640099 |
8460391045e8735a40ebfcd12a793cd895a64c20 | 1,909 | c | C | main.c | Mandrilux/base64-crypt | 8897ad05c2db4930526105d11fc1293b9030eda3 | [
"Apache-2.0"
] | null | null | null | main.c | Mandrilux/base64-crypt | 8897ad05c2db4930526105d11fc1293b9030eda3 | [
"Apache-2.0"
] | null | null | null | main.c | Mandrilux/base64-crypt | 8897ad05c2db4930526105d11fc1293b9030eda3 | [
"Apache-2.0"
] | null | null | null | #include "data.h"
int main(int ac, char **argv)
{
char *str_bin = NULL;
int *tab_letter = NULL;
int len_tab = 0;
if (ac != 2)
return (return_error("Usage : [str_to_crypt_to_base64]", EXIT_FAILURE));
if ((str_bin = str_to_bin(argv[1])) == NULL)
return return_error("[-] ERROR MEMORY", EXIT_FAILURE);
printf("Step 1 : %s\n", str_bin);
if ((str_bin = adjust(str_bin)) == NULL)
return return_error("[-] ERROR MEMORY", EXIT_FAILURE);
printf("Step 2 : %s\n", str_bin);
if ((tab_letter = bin_to_int(str_bin, &len_tab)) == NULL)
return return_error("[-] ERROR MEMORY", EXIT_FAILURE);
free(str_bin);
display_code(tab_letter, len_tab);
return EXIT_SUCCESS;
}
char *adjust(char *str)
{
int res;
int add;
char *tmp;
int start;
if ((res = (strlen(str)) % 6) == 0)
return (str);
add = 6 - res;
start = strlen(str);
if ((tmp = realloc(str,sizeof(char) * (strlen(str) + 1 + add))) == NULL)
return (NULL);
while (add-- > 0)
tmp[start++] = '0';
tmp[start] = '\0';
return tmp;
}
char *str_to_bin(char *str)
{
int i = 7;
int k = -1;
int t = 0;
char *str_bin = NULL;
str_bin = calloc(strlen(str) * (8 + 1), sizeof(char));
if (str_bin == NULL)
return (NULL);
while (str[++k] != '\0')
{
while (i >= 0)
{
if (((str[k] >> i) & 1) == 1)
str_bin[t] = '1';
else
str_bin[t] = '0';
t++;
i--;
}
i = 7;
}
return str_bin;
}
int *bin_to_int(char *str, int *len_tab)
{
int *tab_letter;
int flag = 5;
int i = -1;
int tmp_add = 0;
int indice = 0;
*len_tab = strlen(str) / 6;
if ((tab_letter = calloc(*len_tab, sizeof(int))) == NULL)
return (NULL);
while (str[++i] != '\0')
{
if (str[i] == '1')
tmp_add += pow(2.0, (double)flag);
if (--flag == -1)
{
tab_letter[indice] = tmp_add;
indice++;
flag = 5;
tmp_add = 0;
}
}
return tab_letter;
}
| 20.094737 | 76 | 0.549502 |
3b0f4168d92df3c2bfb4502b33b4c0bc449670d8 | 608 | h | C | Example/Classes/Model/ZQPhotoModel.h | AngleZhou/PhotoAlbum | c00d413fb74078d9a06988b6fa1a9980926f6cac | [
"MIT"
] | 16 | 2016-07-23T02:36:14.000Z | 2020-09-14T01:48:05.000Z | Example/Classes/Model/ZQPhotoModel.h | AngleZhou/PhotoAlbum | c00d413fb74078d9a06988b6fa1a9980926f6cac | [
"MIT"
] | 1 | 2016-09-26T08:03:33.000Z | 2018-07-15T13:17:50.000Z | Example/Classes/Model/ZQPhotoModel.h | AngleZhou/PhotoAlbum | c00d413fb74078d9a06988b6fa1a9980926f6cac | [
"MIT"
] | 11 | 2016-09-14T05:47:22.000Z | 2020-05-16T03:21:32.000Z | //
// CTPhotoModel.h
// PhotoAlbum
//
// Created by ZhouQian on 16/6/2.
// Copyright © 2016年 ZhouQian. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>
#import <Photos/Photos.h>
@interface ZQPhotoModel : NSObject
@property (nonatomic, strong) PHAsset *asset;
@property (nonatomic, strong) NSData *data;
@property (nonatomic, assign) NSTimeInterval duration;
@property (nonatomic, assign) BOOL bSelected;
@property (nonatomic, assign) int32_t requestID;
//@property (nonatomic, strong) UIImage *videoCoverImage;
- (instancetype)initWithPHAsset:(PHAsset *)asset;
@end
| 24.32 | 57 | 0.743421 |
fe1e98d536d9c9c6fb123c7f01cefceac89b522f | 846 | h | C | align.h | MadPidgeon/Graph-Isomorphism | 30fb35a6faad8bda0663d49aff2fca1f2f69c56d | [
"MIT"
] | null | null | null | align.h | MadPidgeon/Graph-Isomorphism | 30fb35a6faad8bda0663d49aff2fca1f2f69c56d | [
"MIT"
] | null | null | null | align.h | MadPidgeon/Graph-Isomorphism | 30fb35a6faad8bda0663d49aff2fca1f2f69c56d | [
"MIT"
] | null | null | null | #pragma once
#include <map>
#include "configuration.h"
#include "ext.h"
#include "permutation.h"
typedef std::map<std::vector<int>,int> inv_gamma_t;
typedef std::deque<std::vector<int>> gamma_t;
typedef int rtype2;
template<typename T>
Either<rtype2,Empty> align( const T& Xx, const T& Xy ) {
throw;
return Empty();
}
Permutation pullback( Permutation sigma_bar, const inv_gamma_t& inv_gamma, const gamma_t& gamma );
/*
template<>
Either<rtype2,Empty> Align<ColoredPartition>( const ColoredPartition& Xx, const ColoredPartition& Xy, const inv_gamma_t& inv_gamma, const gamma_t& gamma ) {
// 1.
// TO DO: check alternating type
Either<Permutation,Empty> r = Xx.getIsomorphism( Xy );
if( r.isSecond() )
return Empty();
Permutation sigma_bar = r.getFirst();
// 2.
std::cout << pullback( sigma_bar, inv_gamma, gamma );
return 0;
}*/ | 26.4375 | 156 | 0.719858 |
b620b7d7dc4d9b7d763743704f1ac80d3f89b162 | 29,571 | h | C | librpc/test/client_read_ops_test.h | Mu-L/confluo | e9b8621e99f56b1adf5675c4296c006d89e6e582 | [
"Apache-2.0"
] | 1,398 | 2018-12-05T19:13:15.000Z | 2022-03-29T08:26:03.000Z | librpc/test/client_read_ops_test.h | Mu-L/confluo | e9b8621e99f56b1adf5675c4296c006d89e6e582 | [
"Apache-2.0"
] | 53 | 2018-10-21T03:28:25.000Z | 2021-03-16T03:50:54.000Z | librpc/test/client_read_ops_test.h | Mu-L/confluo | e9b8621e99f56b1adf5675c4296c006d89e6e582 | [
"Apache-2.0"
] | 208 | 2018-10-28T03:05:46.000Z | 2022-02-06T06:16:37.000Z | #ifndef RPC_TEST_READ_OPS_TEST_H_
#define RPC_TEST_READ_OPS_TEST_H_
#include <iostream>
#include "gtest/gtest.h"
#include "atomic_multilog.h"
#include "rpc_client.h"
#include "rpc_server.h"
#include "rpc_test_utils.h"
#define MAX_RECORDS 2560U
#define DATA_SIZE 64U
using namespace ::confluo::rpc;
using namespace ::confluo;
class ClientReadOpsTest : public testing::Test {
public:
const std::string SERVER_ADDRESS = "127.0.0.1";
const int SERVER_PORT = 9090;
static void generate_bytes(uint8_t *buf, size_t len, uint64_t val) {
uint8_t val_uint8 = (uint8_t) (val % 256);
for (uint32_t i = 0; i < len; i++)
buf[i] = val_uint8;
}
void test_read(atomic_multilog *mlog, rpc_client &client) {
std::vector<int64_t> offsets;
for (int64_t i = 0; i < MAX_RECORDS; i++) {
generate_bytes(data_, DATA_SIZE, static_cast<uint64_t>(i));
int64_t offset = static_cast<int64_t>(mlog->append(data_));
offsets.push_back(offset);
}
record_data buf;
for (uint64_t i = 0; i < MAX_RECORDS; i++) {
client.read(buf, offsets[i]);
ASSERT_EQ(mlog->record_size(), buf.size());
uint8_t *data = reinterpret_cast<uint8_t *>(&buf[0]);
ASSERT_TRUE(data != nullptr);
uint8_t expected = static_cast<uint8_t>(i % 256);
for (uint32_t j = 0; j < DATA_SIZE; j++) {
ASSERT_EQ(expected, data[j]);
}
}
ASSERT_EQ(MAX_RECORDS, client.num_records());
}
static std::vector<column_t> s;
struct rec {
int64_t ts;
bool a;
int8_t b;
int16_t c;
int32_t d;
int64_t e;
float f;
double g;
char h[16];
}__attribute__((packed));
static rec r;
static void *record(bool a, int8_t b, int16_t c, int32_t d, int64_t e, float f, double g, const char *h) {
int64_t ts = utils::time_utils::cur_ns();
r = {ts, a, b, c, d, e, f, g, {}};
size_t len = std::min(static_cast<size_t>(16), strlen(h));
memcpy(r.h, h, len);
for (size_t i = len; i < 16; i++) {
r.h[i] = '\0';
}
return reinterpret_cast<void *>(&r);
}
static void *record(int64_t ts, bool a, int8_t b, int16_t c, int32_t d, int64_t e, float f, double g, const char *h) {
r = {ts, a, b, c, d, e, f, g, {}};
size_t len = std::min(static_cast<size_t>(16), strlen(h));
memcpy(r.h, h, len);
for (size_t i = len; i < 16; i++) {
r.h[i] = '\0';
}
return reinterpret_cast<void *>(&r);
}
static confluo_store *simple_table_store(const std::string &multilog_name,
storage::storage_mode id) {
auto store = new confluo_store("/tmp");
store->create_atomic_multilog(
multilog_name,
schema_builder().add_column(primitive_types::STRING_TYPE(DATA_SIZE), "msg").get_columns(),
id);
return store;
}
static std::vector<column_t> schema() {
schema_builder builder;
builder.add_column(primitive_types::BOOL_TYPE(), "a");
builder.add_column(primitive_types::CHAR_TYPE(), "b");
builder.add_column(primitive_types::SHORT_TYPE(), "c");
builder.add_column(primitive_types::INT_TYPE(), "d");
builder.add_column(primitive_types::LONG_TYPE(), "e");
builder.add_column(primitive_types::FLOAT_TYPE(), "f");
builder.add_column(primitive_types::DOUBLE_TYPE(), "g");
builder.add_column(primitive_types::STRING_TYPE(16), "h");
return builder.get_columns();
}
static record_batch build_batch(const atomic_multilog &mlog) {
record_batch_builder builder = mlog.get_batch_builder();
builder.add_record(record(false, '0', 0, 0, 0, 0.0, 0.01, "abc"));
builder.add_record(record(true, '1', 10, 2, 1, 0.1, 0.02, "defg"));
builder.add_record(record(false, '2', 20, 4, 10, 0.2, 0.03, "hijkl"));
builder.add_record(record(true, '3', 30, 6, 100, 0.3, 0.04, "mnopqr"));
builder.add_record(
record(false, '4', 40, 8, 1000, 0.4, 0.05, "stuvwx"));
builder.add_record(record(true, '5', 50, 10, 10000, 0.5, 0.06, "yyy"));
builder.add_record(
record(false, '6', 60, 12, 100000, 0.6, 0.07, "zzz"));
builder.add_record(
record(true, '7', 70, 14, 1000000, 0.7, 0.08, "zzz"));
return builder.get_batch();
}
static record_batch build_batch(const atomic_multilog &mlog, int64_t ts) {
record_batch_builder builder = mlog.get_batch_builder();
builder.add_record(record(ts, false, '0', 0, 0, 0, 0.0, 0.01, "abc"));
builder.add_record(record(ts, true, '1', 10, 2, 1, 0.1, 0.02, "defg"));
builder.add_record(record(ts, false, '2', 20, 4, 10, 0.2, 0.03, "hijkl"));
builder.add_record(record(ts, true, '3', 30, 6, 100, 0.3, 0.04, "mnopqr"));
builder.add_record(
record(ts, false, '4', 40, 8, 1000, 0.4, 0.05, "stuvwx"));
builder.add_record(record(ts, true, '5', 50, 10, 10000, 0.5, 0.06, "yyy"));
builder.add_record(
record(ts, false, '6', 60, 12, 100000, 0.6, 0.07, "zzz"));
builder.add_record(
record(ts, true, '7', 70, 14, 1000000, 0.7, 0.08, "zzz"));
return builder.get_batch();
}
std::shared_ptr<TServer> create_server(confluo_store *store) {
auto num_workers = configuration_params::MAX_CONCURRENCY() - 1;
return rpc_server::create(store, SERVER_ADDRESS, SERVER_PORT, num_workers);
}
protected:
uint8_t data_[DATA_SIZE];
virtual void SetUp() override {
thread_manager::register_thread();
}
virtual void TearDown() override {
thread_manager::deregister_thread();
}
};
ClientReadOpsTest::rec ClientReadOpsTest::r;
std::vector<column_t> ClientReadOpsTest::s = schema();
TEST_F(ClientReadOpsTest, ReadInMemoryTest) {
std::string multilog_name = "my_multilog";
auto store = simple_table_store(multilog_name, storage::IN_MEMORY);
auto server = create_server(store);
std::thread serve_thread([&server] {
server->serve();
});
rpc_test_utils::wait_till_server_ready(SERVER_ADDRESS, SERVER_PORT);
rpc_client client(SERVER_ADDRESS, SERVER_PORT);
client.set_current_atomic_multilog(multilog_name);
test_read(store->get_atomic_multilog(multilog_name), client);
client.disconnect();
server->stop();
if (serve_thread.joinable()) {
serve_thread.join();
}
}
TEST_F(ClientReadOpsTest, ReadDurableTest) {
std::string multilog_name = "my_multilog";
auto store = simple_table_store(multilog_name, storage::DURABLE);
auto server = create_server(store);
std::thread serve_thread([&server] {
server->serve();
});
rpc_test_utils::wait_till_server_ready(SERVER_ADDRESS, SERVER_PORT);
rpc_client client(SERVER_ADDRESS, SERVER_PORT);
client.set_current_atomic_multilog(multilog_name);
test_read(store->get_atomic_multilog(multilog_name), client);
client.disconnect();
server->stop();
if (serve_thread.joinable()) {
serve_thread.join();
}
}
TEST_F(ClientReadOpsTest, ReadDurableRelaxedTest) {
std::string multilog_name = "my_multilog";
auto store = simple_table_store(multilog_name, storage::DURABLE_RELAXED);
auto server = create_server(store);
std::thread serve_thread([&server] {
server->serve();
});
rpc_test_utils::wait_till_server_ready(SERVER_ADDRESS, SERVER_PORT);
rpc_client client(SERVER_ADDRESS, SERVER_PORT);
client.set_current_atomic_multilog(multilog_name);
test_read(store->get_atomic_multilog(multilog_name), client);
client.disconnect();
server->stop();
if (serve_thread.joinable()) {
serve_thread.join();
}
}
TEST_F(ClientReadOpsTest, AdHocFilterTest) {
std::string multilog_name = "my_multilog";
auto store = new confluo_store("/tmp");
store->create_atomic_multilog(multilog_name, schema(), storage::IN_MEMORY);
auto mlog = store->get_atomic_multilog(multilog_name);
mlog->add_index("a");
mlog->add_index("b");
mlog->add_index("c", 10);
mlog->add_index("d", 2);
mlog->add_index("e", 100);
mlog->add_index("f", 0.1);
mlog->add_index("g", 0.01);
mlog->add_index("h");
mlog->append(record(false, '0', 0, 0, 0, 0.0, 0.01, "abc"));
mlog->append(record(true, '1', 10, 2, 1, 0.1, 0.02, "defg"));
mlog->append(record(false, '2', 20, 4, 10, 0.2, 0.03, "hijkl"));
mlog->append(record(true, '3', 30, 6, 100, 0.3, 0.04, "mnopqr"));
mlog->append(record(false, '4', 40, 8, 1000, 0.4, 0.05, "stuvwx"));
mlog->append(record(true, '5', 50, 10, 10000, 0.5, 0.06, "yyy"));
mlog->append(record(false, '6', 60, 12, 100000, 0.6, 0.07, "zzz"));
mlog->append(record(true, '7', 70, 14, 1000000, 0.7, 0.08, "zzz"));
auto server = create_server(store);
std::thread serve_thread([&server] {
server->serve();
});
rpc_test_utils::wait_till_server_ready(SERVER_ADDRESS, SERVER_PORT);
rpc_client client(SERVER_ADDRESS, SERVER_PORT);
client.set_current_atomic_multilog(multilog_name);
size_t i = 0;
for (auto r = client.execute_filter("a == true"); r.has_more(); ++r) {
ASSERT_EQ(true, r.get().at(1).value().to_data().as<bool>());
i++;
}
ASSERT_EQ(static_cast<size_t>(4), i);
i = 0;
for (auto r = client.execute_filter("b > 4"); r.has_more(); ++r) {
ASSERT_TRUE(r.get().at(2).value().to_data().as<int8_t>() > '4');
i++;
}
ASSERT_EQ(static_cast<size_t>(3), i);
i = 0;
for (auto r = client.execute_filter("c <= 30"); r.has_more(); ++r) {
ASSERT_TRUE(r.get().at(3).value().to_data().as<int16_t>() <= 30);
i++;
}
ASSERT_EQ(static_cast<size_t>(4), i);
i = 0;
for (auto r = client.execute_filter("d == 0"); r.has_more(); ++r) {
ASSERT_TRUE(r.get().at(4).value().to_data().as<int32_t>() == 0);
i++;
}
ASSERT_EQ(static_cast<size_t>(1), i);
i = 0;
for (auto r = client.execute_filter("e <= 100"); r.has_more(); ++r) {
ASSERT_TRUE(r.get().at(5).value().to_data().as<int64_t>() <= 100);
i++;
}
ASSERT_EQ(static_cast<size_t>(4), i);
i = 0;
for (auto r = client.execute_filter("f > 0.1"); r.has_more(); ++r) {
ASSERT_TRUE(r.get().at(6).value().to_data().as<float>() > 0.1);
i++;
}
ASSERT_EQ(static_cast<size_t>(6), i);
i = 0;
for (auto r = client.execute_filter("g < 0.06"); r.has_more(); ++r) {
ASSERT_TRUE(r.get().at(7).value().to_data().as<double>() < 0.06);
i++;
}
ASSERT_EQ(static_cast<size_t>(5), i);
i = 0;
for (auto r = client.execute_filter("h == zzz"); r.has_more(); ++r) {
ASSERT_TRUE(
r.get().at(8).value().to_data().as<std::string>().substr(0, 3)
== "zzz");
i++;
}
ASSERT_EQ(static_cast<size_t>(2), i);
i = 0;
for (auto r = client.execute_filter("a == true && b > 4"); r.has_more();
++r) {
ASSERT_EQ(true, r.get().at(1).value().to_data().as<bool>());
ASSERT_TRUE(r.get().at(2).value().to_data().as<int8_t>() > '4');
i++;
}
ASSERT_EQ(static_cast<size_t>(2), i);
i = 0;
for (auto r = client.execute_filter("a == true && (b > 4 || c <= 30)");
r.has_more(); ++r) {
ASSERT_EQ(true, r.get().at(1).value().to_data().as<bool>());
ASSERT_TRUE(
r.get().at(2).value().to_data().as<int8_t>() > '4'
|| r.get().at(3).value().to_data().as<int16_t>() <= 30);
i++;
}
ASSERT_EQ(static_cast<size_t>(4), i);
i = 0;
for (auto r = client.execute_filter("a == true && (b > 4 || f > 0.1)");
r.has_more(); ++r) {
ASSERT_EQ(true, r.get().at(1).value().to_data().as<bool>());
ASSERT_TRUE(
r.get().at(2).value().to_data().as<int8_t>() > '4'
|| r.get().at(6).value().to_data().as<float>() > 0.1);
i++;
}
ASSERT_EQ(static_cast<size_t>(3), i);
client.disconnect();
server->stop();
if (serve_thread.joinable()) {
serve_thread.join();
}
}
TEST_F(ClientReadOpsTest, FilterAggregateTriggerTest) {
if (configuration_params::MAX_CONCURRENCY() < 2) {
LOG_WARN << "Need at least 2 cores to run this test, skipping...";
return; // TODO: Replace this with GTEST_SKIP when v1.8.2 is released
}
std::string multilog_name = "my_multilog";
auto store = new confluo_store("/tmp");
store->create_atomic_multilog(multilog_name, schema(), storage::IN_MEMORY);
auto mlog = store->get_atomic_multilog(multilog_name);
mlog->add_filter("filter1", "a == true");
mlog->add_filter("filter2", "b > 4");
mlog->add_filter("filter3", "c <= 30");
mlog->add_filter("filter4", "d == 0");
mlog->add_filter("filter5", "e <= 100");
mlog->add_filter("filter6", "f > 0.1");
mlog->add_filter("filter7", "g < 0.06");
mlog->add_filter("filter8", "h == zzz");
mlog->add_aggregate("agg1", "filter1", "SUM(d)");
mlog->add_aggregate("agg2", "filter2", "SUM(d)");
mlog->add_aggregate("agg3", "filter3", "SUM(d)");
mlog->add_aggregate("agg4", "filter4", "SUM(d)");
mlog->add_aggregate("agg5", "filter5", "SUM(d)");
mlog->add_aggregate("agg6", "filter6", "SUM(d)");
mlog->add_aggregate("agg7", "filter7", "SUM(d)");
mlog->add_aggregate("agg8", "filter8", "SUM(d)");
mlog->install_trigger("trigger1", "agg1 >= 10");
mlog->install_trigger("trigger2", "agg2 >= 10");
mlog->install_trigger("trigger3", "agg3 >= 10");
mlog->install_trigger("trigger4", "agg4 >= 10");
mlog->install_trigger("trigger5", "agg5 >= 10");
mlog->install_trigger("trigger6", "agg6 >= 10");
mlog->install_trigger("trigger7", "agg7 >= 10");
mlog->install_trigger("trigger8", "agg8 >= 10");
int64_t now_ns = time_utils::cur_ns();
int64_t beg = now_ns / configuration_params::TIME_RESOLUTION_NS();
int64_t end = beg;
mlog->append(record(now_ns, false, '0', 0, 0, 0, 0.0, 0.01, "abc"));
mlog->append(record(now_ns, true, '1', 10, 2, 1, 0.1, 0.02, "defg"));
mlog->append(record(now_ns, false, '2', 20, 4, 10, 0.2, 0.03, "hijkl"));
mlog->append(record(now_ns, true, '3', 30, 6, 100, 0.3, 0.04, "mnopqr"));
mlog->append(record(now_ns, false, '4', 40, 8, 1000, 0.4, 0.05, "stuvwx"));
mlog->append(record(now_ns, true, '5', 50, 10, 10000, 0.5, 0.06, "yyy"));
mlog->append(record(now_ns, false, '6', 60, 12, 100000, 0.6, 0.07, "zzz"));
mlog->append(record(now_ns, true, '7', 70, 14, 1000000, 0.7, 0.08, "zzz"));
auto server = create_server(store);
std::thread serve_thread([&server] {
server->serve();
});
rpc_test_utils::wait_till_server_ready(SERVER_ADDRESS, SERVER_PORT);
rpc_client client = rpc_client(SERVER_ADDRESS, SERVER_PORT);
client.set_current_atomic_multilog(multilog_name);
// Test filters
size_t i = 0;
for (auto r = client.query_filter("filter1", beg, end); r.has_more(); ++r) {
ASSERT_EQ(true, r.get().at(1).value().to_data().as<bool>());
i++;
}
ASSERT_EQ(static_cast<size_t>(4), i);
i = 0;
for (auto r = client.query_filter("filter2", beg, end); r.has_more(); ++r) {
ASSERT_TRUE(r.get().at(2).value().to_data().as<int8_t>() > '4');
i++;
}
ASSERT_EQ(static_cast<size_t>(3), i);
i = 0;
for (auto r = client.query_filter("filter3", beg, end); r.has_more(); ++r) {
ASSERT_TRUE(r.get().at(3).value().to_data().as<int16_t>() <= 30);
i++;
}
ASSERT_EQ(static_cast<size_t>(4), i);
i = 0;
for (auto r = client.query_filter("filter4", beg, end); r.has_more(); ++r) {
ASSERT_TRUE(r.get().at(4).value().to_data().as<int32_t>() == 0);
i++;
}
ASSERT_EQ(static_cast<size_t>(1), i);
i = 0;
for (auto r = client.query_filter("filter5", beg, end); r.has_more(); ++r) {
ASSERT_TRUE(r.get().at(5).value().to_data().as<int64_t>() <= 100);
i++;
}
ASSERT_EQ(static_cast<size_t>(4), i);
i = 0;
for (auto r = client.query_filter("filter6", beg, end); r.has_more(); ++r) {
ASSERT_TRUE(r.get().at(6).value().to_data().as<float>() > 0.1);
i++;
}
ASSERT_EQ(static_cast<size_t>(6), i);
i = 0;
for (auto r = client.query_filter("filter7", beg, end); r.has_more(); ++r) {
ASSERT_TRUE(r.get().at(7).value().to_data().as<double>() < 0.06);
i++;
}
ASSERT_EQ(static_cast<size_t>(5), i);
i = 0;
for (auto r = client.query_filter("filter8", beg, end); r.has_more(); ++r) {
ASSERT_TRUE(
r.get().at(8).value().to_data().as<std::string>().substr(0, 3)
== "zzz");
i++;
}
ASSERT_EQ(static_cast<size_t>(2), i);
i = 0;
for (auto r = client.query_filter("filter1", beg, end, "b > 4"); r.has_more();
++r) {
ASSERT_EQ(true, r.get().at(1).value().to_data().as<bool>());
ASSERT_TRUE(r.get().at(2).value().to_data().as<int8_t>() > '4');
i++;
}
ASSERT_EQ(static_cast<size_t>(2), i);
i = 0;
for (auto r = client.query_filter("filter1", beg, end, "b > 4 || c <= 30");
r.has_more(); ++r) {
ASSERT_EQ(true, r.get().at(1).value().to_data().as<bool>());
ASSERT_TRUE(
r.get().at(2).value().to_data().as<int8_t>() > '4'
|| r.get().at(3).value().to_data().as<int16_t>() <= 30);
i++;
}
ASSERT_EQ(static_cast<size_t>(4), i);
i = 0;
for (auto r = client.query_filter("filter1", beg, end, "b > 4 || f > 0.1");
r.has_more(); ++r) {
ASSERT_EQ(true, r.get().at(1).value().to_data().as<bool>());
ASSERT_TRUE(
r.get().at(2).value().to_data().as<int8_t>() > '4'
|| r.get().at(6).value().to_data().as<float>() > 0.1);
i++;
}
ASSERT_EQ(static_cast<size_t>(3), i);
// Test aggregates
std::string val1 = client.get_aggregate("agg1", beg, end);
ASSERT_TRUE("double(32.000000)" == val1);
std::string val2 = client.get_aggregate("agg2", beg, end);
ASSERT_TRUE("double(36.000000)" == val2);
std::string val3 = client.get_aggregate("agg3", beg, end);
ASSERT_TRUE("double(12.000000)" == val3);
std::string val4 = client.get_aggregate("agg4", beg, end);
ASSERT_TRUE("double(0.000000)" == val4);
std::string val5 = client.get_aggregate("agg5", beg, end);
ASSERT_TRUE("double(12.000000)" == val5);
std::string val6 = client.get_aggregate("agg6", beg, end);
ASSERT_TRUE("double(54.000000)" == val6);
std::string val7 = client.get_aggregate("agg7", beg, end);
ASSERT_TRUE("double(20.000000)" == val7);
std::string val8 = client.get_aggregate("agg8", beg, end);
ASSERT_TRUE("double(26.000000)" == val8);
// Test triggers
sleep(1); // To make sure all triggers have been evaluated
size_t alert_count = 0;
for (auto alerts = client.get_alerts(beg, end); alerts.has_more(); ++alerts) {
LOG_INFO << "Alert: " << alerts.get();
alert_count++;
}
ASSERT_EQ(size_t(7), alert_count);
// TODO: more rigorous testing on alert values.
auto a1 = client.get_alerts(beg, end, "trigger1");
ASSERT_TRUE(!a1.empty());
auto a2 = client.get_alerts(beg, end, "trigger2");
ASSERT_TRUE(!a2.empty());
auto a3 = client.get_alerts(beg, end, "trigger3");
ASSERT_TRUE(!a3.empty());
auto a4 = client.get_alerts(beg, end, "trigger4");
ASSERT_TRUE(a4.empty());
auto a5 = client.get_alerts(beg, end, "trigger5");
ASSERT_TRUE(!a5.empty());
auto a6 = client.get_alerts(beg, end, "trigger6");
ASSERT_TRUE(!a6.empty());
auto a7 = client.get_alerts(beg, end, "trigger7");
ASSERT_TRUE(!a7.empty());
auto a8 = client.get_alerts(beg, end, "trigger8");
ASSERT_TRUE(!a8.empty());
client.disconnect();
server->stop();
if (serve_thread.joinable()) {
serve_thread.join();
}
}
TEST_F(ClientReadOpsTest, BatchAdHocFilterTest) {
std::string multilog_name = "my_multilog";
auto store = new confluo_store("/tmp");
store->create_atomic_multilog(multilog_name, schema(), storage::IN_MEMORY);
auto mlog = store->get_atomic_multilog(multilog_name);
mlog->add_index("a");
mlog->add_index("b");
mlog->add_index("c", 10);
mlog->add_index("d", 2);
mlog->add_index("e", 100);
mlog->add_index("f", 0.1);
mlog->add_index("g", 0.01);
mlog->add_index("h");
record_batch batch = build_batch(*mlog);
mlog->append_batch(batch);
auto server = create_server(store);
std::thread serve_thread([&server] {
server->serve();
});
rpc_test_utils::wait_till_server_ready(SERVER_ADDRESS, SERVER_PORT);
rpc_client client(SERVER_ADDRESS, SERVER_PORT);
client.set_current_atomic_multilog(multilog_name);
size_t i = 0;
for (auto r = client.execute_filter("a == true"); r.has_more(); ++r) {
ASSERT_EQ(true, r.get().at(1).value().to_data().as<bool>());
i++;
}
ASSERT_EQ(static_cast<size_t>(4), i);
i = 0;
for (auto r = client.execute_filter("b > 4"); r.has_more(); ++r) {
ASSERT_TRUE(r.get().at(2).value().to_data().as<int8_t>() > '4');
i++;
}
ASSERT_EQ(static_cast<size_t>(3), i);
i = 0;
for (auto r = client.execute_filter("c <= 30"); r.has_more(); ++r) {
ASSERT_TRUE(r.get().at(3).value().to_data().as<int16_t>() <= 30);
i++;
}
ASSERT_EQ(static_cast<size_t>(4), i);
i = 0;
for (auto r = client.execute_filter("d == 0"); r.has_more(); ++r) {
ASSERT_TRUE(r.get().at(4).value().to_data().as<int32_t>() == 0);
i++;
}
ASSERT_EQ(static_cast<size_t>(1), i);
i = 0;
for (auto r = client.execute_filter("e <= 100"); r.has_more(); ++r) {
ASSERT_TRUE(r.get().at(5).value().to_data().as<int64_t>() <= 100);
i++;
}
ASSERT_EQ(static_cast<size_t>(4), i);
i = 0;
for (auto r = client.execute_filter("f > 0.1"); r.has_more(); ++r) {
ASSERT_TRUE(r.get().at(6).value().to_data().as<float>() > 0.1);
i++;
}
ASSERT_EQ(static_cast<size_t>(6), i);
i = 0;
for (auto r = client.execute_filter("g < 0.06"); r.has_more(); ++r) {
ASSERT_TRUE(r.get().at(7).value().to_data().as<double>() < 0.06);
i++;
}
ASSERT_EQ(static_cast<size_t>(5), i);
i = 0;
for (auto r = client.execute_filter("h == zzz"); r.has_more(); ++r) {
ASSERT_TRUE(
r.get().at(8).value().to_data().as<std::string>().substr(0, 3)
== "zzz");
i++;
}
ASSERT_EQ(static_cast<size_t>(2), i);
i = 0;
for (auto r = client.execute_filter("a == true && b > 4"); r.has_more();
++r) {
ASSERT_EQ(true, r.get().at(1).value().to_data().as<bool>());
ASSERT_TRUE(r.get().at(2).value().to_data().as<int8_t>() > '4');
i++;
}
ASSERT_EQ(static_cast<size_t>(2), i);
i = 0;
for (auto r = client.execute_filter("a == true && (b > 4 || c <= 30)");
r.has_more(); ++r) {
ASSERT_EQ(true, r.get().at(1).value().to_data().as<bool>());
ASSERT_TRUE(
r.get().at(2).value().to_data().as<int8_t>() > '4'
|| r.get().at(3).value().to_data().as<int16_t>() <= 30);
i++;
}
ASSERT_EQ(static_cast<size_t>(4), i);
i = 0;
for (auto r = client.execute_filter("a == true && (b > 4 || f > 0.1)");
r.has_more(); ++r) {
ASSERT_EQ(true, r.get().at(1).value().to_data().as<bool>());
ASSERT_TRUE(
r.get().at(2).value().to_data().as<int8_t>() > '4'
|| r.get().at(6).value().to_data().as<float>() > 0.1);
i++;
}
ASSERT_EQ(static_cast<size_t>(3), i);
client.disconnect();
server->stop();
if (serve_thread.joinable()) {
serve_thread.join();
}
}
TEST_F(ClientReadOpsTest, BatchFilterAggregateTriggerTest) {
if (configuration_params::MAX_CONCURRENCY() < 2) {
LOG_WARN << "Need at least 2 cores to run this test, skipping...";
return; // TODO: Replace this with GTEST_SKIP when v1.8.2 is released
}
std::string multilog_name = "my_multilog";
auto store = new confluo_store("/tmp");
store->create_atomic_multilog(multilog_name, schema(), storage::IN_MEMORY);
auto mlog = store->get_atomic_multilog(multilog_name);
mlog->add_filter("filter1", "a == true");
mlog->add_filter("filter2", "b > 4");
mlog->add_filter("filter3", "c <= 30");
mlog->add_filter("filter4", "d == 0");
mlog->add_filter("filter5", "e <= 100");
mlog->add_filter("filter6", "f > 0.1");
mlog->add_filter("filter7", "g < 0.06");
mlog->add_filter("filter8", "h == zzz");
mlog->add_aggregate("agg1", "filter1", "SUM(d)");
mlog->add_aggregate("agg2", "filter2", "SUM(d)");
mlog->add_aggregate("agg3", "filter3", "SUM(d)");
mlog->add_aggregate("agg4", "filter4", "SUM(d)");
mlog->add_aggregate("agg5", "filter5", "SUM(d)");
mlog->add_aggregate("agg6", "filter6", "SUM(d)");
mlog->add_aggregate("agg7", "filter7", "SUM(d)");
mlog->add_aggregate("agg8", "filter8", "SUM(d)");
mlog->install_trigger("trigger1", "agg1 >= 10");
mlog->install_trigger("trigger2", "agg2 >= 10");
mlog->install_trigger("trigger3", "agg3 >= 10");
mlog->install_trigger("trigger4", "agg4 >= 10");
mlog->install_trigger("trigger5", "agg5 >= 10");
mlog->install_trigger("trigger6", "agg6 >= 10");
mlog->install_trigger("trigger7", "agg7 >= 10");
mlog->install_trigger("trigger8", "agg8 >= 10");
int64_t now_ns = time_utils::cur_ns();
int64_t beg = now_ns / configuration_params::TIME_RESOLUTION_NS();
int64_t end = beg;
record_batch batch = build_batch(*mlog, now_ns);
mlog->append_batch(batch);
auto server = create_server(store);
std::thread serve_thread([&server] {
server->serve();
});
rpc_test_utils::wait_till_server_ready(SERVER_ADDRESS, SERVER_PORT);
rpc_client client(SERVER_ADDRESS, SERVER_PORT);
client.set_current_atomic_multilog(multilog_name);
// Test filters
size_t i = 0;
for (auto r = client.query_filter("filter1", beg, end); r.has_more(); ++r) {
ASSERT_EQ(true, r.get().at(1).value().to_data().as<bool>());
i++;
}
ASSERT_EQ(static_cast<size_t>(4), i);
i = 0;
for (auto r = client.query_filter("filter2", beg, end); r.has_more(); ++r) {
ASSERT_TRUE(r.get().at(2).value().to_data().as<int8_t>() > '4');
i++;
}
ASSERT_EQ(static_cast<size_t>(3), i);
i = 0;
for (auto r = client.query_filter("filter3", beg, end); r.has_more(); ++r) {
ASSERT_TRUE(r.get().at(3).value().to_data().as<int16_t>() <= 30);
i++;
}
ASSERT_EQ(static_cast<size_t>(4), i);
i = 0;
for (auto r = client.query_filter("filter4", beg, end); r.has_more(); ++r) {
ASSERT_TRUE(r.get().at(4).value().to_data().as<int32_t>() == 0);
i++;
}
ASSERT_EQ(static_cast<size_t>(1), i);
i = 0;
for (auto r = client.query_filter("filter5", beg, end); r.has_more(); ++r) {
ASSERT_TRUE(r.get().at(5).value().to_data().as<int64_t>() <= 100);
i++;
}
ASSERT_EQ(static_cast<size_t>(4), i);
i = 0;
for (auto r = client.query_filter("filter6", beg, end); r.has_more(); ++r) {
ASSERT_TRUE(r.get().at(6).value().to_data().as<float>() > 0.1);
i++;
}
ASSERT_EQ(static_cast<size_t>(6), i);
i = 0;
for (auto r = client.query_filter("filter7", beg, end); r.has_more(); ++r) {
ASSERT_TRUE(r.get().at(7).value().to_data().as<double>() < 0.06);
i++;
}
ASSERT_EQ(static_cast<size_t>(5), i);
i = 0;
for (auto r = client.query_filter("filter8", beg, end); r.has_more(); ++r) {
ASSERT_TRUE(
r.get().at(8).value().to_data().as<std::string>().substr(0, 3)
== "zzz");
i++;
}
ASSERT_EQ(static_cast<size_t>(2), i);
i = 0;
for (auto r = client.query_filter("filter1", beg, end, "b > 4"); r.has_more();
++r) {
ASSERT_EQ(true, r.get().at(1).value().to_data().as<bool>());
ASSERT_TRUE(r.get().at(2).value().to_data().as<int8_t>() > '4');
i++;
}
ASSERT_EQ(static_cast<size_t>(2), i);
i = 0;
for (auto r = client.query_filter("filter1", beg, end, "b > 4 || c <= 30");
r.has_more(); ++r) {
ASSERT_EQ(true, r.get().at(1).value().to_data().as<bool>());
ASSERT_TRUE(
r.get().at(2).value().to_data().as<int8_t>() > '4'
|| r.get().at(3).value().to_data().as<int16_t>() <= 30);
i++;
}
ASSERT_EQ(static_cast<size_t>(4), i);
i = 0;
for (auto r = client.query_filter("filter1", beg, end, "b > 4 || f > 0.1");
r.has_more(); ++r) {
ASSERT_EQ(true, r.get().at(1).value().to_data().as<bool>());
ASSERT_TRUE(
r.get().at(2).value().to_data().as<int8_t>() > '4'
|| r.get().at(6).value().to_data().as<float>() > 0.1);
i++;
}
ASSERT_EQ(static_cast<size_t>(3), i);
// Test aggregates
std::string val1 = client.get_aggregate("agg1", beg, end);
ASSERT_TRUE("double(32.000000)" == val1);
std::string val2 = client.get_aggregate("agg2", beg, end);
ASSERT_TRUE("double(36.000000)" == val2);
std::string val3 = client.get_aggregate("agg3", beg, end);
ASSERT_TRUE("double(12.000000)" == val3);
std::string val4 = client.get_aggregate("agg4", beg, end);
ASSERT_TRUE("double(0.000000)" == val4);
std::string val5 = client.get_aggregate("agg5", beg, end);
ASSERT_TRUE("double(12.000000)" == val5);
std::string val6 = client.get_aggregate("agg6", beg, end);
ASSERT_TRUE("double(54.000000)" == val6);
std::string val7 = client.get_aggregate("agg7", beg, end);
ASSERT_TRUE("double(20.000000)" == val7);
std::string val8 = client.get_aggregate("agg8", beg, end);
ASSERT_TRUE("double(26.000000)" == val8);
// Test triggers
sleep(1); // To make sure all triggers have been evaluated
size_t alert_count = 0;
for (auto alerts = client.get_alerts(beg, end); alerts.has_more(); ++alerts) {
LOG_INFO << "Alert: " << alerts.get();
alert_count++;
}
ASSERT_EQ(size_t(7), alert_count);
// TODO: more rigorous testing on alert values.
auto a1 = client.get_alerts(beg, end, "trigger1");
ASSERT_TRUE(!a1.empty());
auto a2 = client.get_alerts(beg, end, "trigger2");
ASSERT_TRUE(!a2.empty());
auto a3 = client.get_alerts(beg, end, "trigger3");
ASSERT_TRUE(!a3.empty());
auto a4 = client.get_alerts(beg, end, "trigger4");
ASSERT_TRUE(a4.empty());
auto a5 = client.get_alerts(beg, end, "trigger5");
ASSERT_TRUE(!a5.empty());
auto a6 = client.get_alerts(beg, end, "trigger6");
ASSERT_TRUE(!a6.empty());
auto a7 = client.get_alerts(beg, end, "trigger7");
ASSERT_TRUE(!a7.empty());
auto a8 = client.get_alerts(beg, end, "trigger8");
ASSERT_TRUE(!a8.empty());
client.disconnect();
server->stop();
if (serve_thread.joinable()) {
serve_thread.join();
}
}
#endif /* RPC_TEST_READ_OPS_TEST_H_ */
| 32.966555 | 120 | 0.61655 |
7df78d9d19eed3f2fb7309c1470025945387ec28 | 3,248 | c | C | fourth_semester/Sysopy/Zadanie7/zad1/src/customers.c | MajronMan/agh_stuff | d045e3bd47ac17880526203d9993d9b2389a9ffe | [
"Unlicense"
] | 2 | 2019-03-02T19:31:57.000Z | 2019-04-03T19:54:39.000Z | fourth_semester/Sysopy/Zadanie7/zad1/src/customers.c | MajronMan/agh_stuff | d045e3bd47ac17880526203d9993d9b2389a9ffe | [
"Unlicense"
] | null | null | null | fourth_semester/Sysopy/Zadanie7/zad1/src/customers.c | MajronMan/agh_stuff | d045e3bd47ac17880526203d9993d9b2389a9ffe | [
"Unlicense"
] | 1 | 2019-04-03T18:26:50.000Z | 2019-04-03T18:26:50.000Z | #include "customers.h"
int main(int argc, char **argv) {
CHECK_UNEQUAL("main", argc, 3,
"Usage: ./customers customers_count haircuts_count")
customers_count = (unsigned int) atoi(argv[1]);
haircuts_count = (unsigned int) atoi(argv[2]);
pid_t *pids = calloc(customers_count, sizeof(pid_t));
GET_SEMAPHORE(queue_sem_id, QUEUE_SEM_KEYGEN)
GET_SEMAPHORE(seat_sem_id, SEAT_SEM_KEYGEN)
GET_SEMAPHORE(pillow_sem_id, PILLOW_SEM_KEYGEN)
GET_SHARED_Q(q, queue_mem_id, QUEUE_MEM_KEYGEN)
for (int i = 0; i < customers_count; i++) {
CHECK_NEGATIVE("create_customer", (pids[i] = fork()),
"Cannot create new customer process")
if (pids[i] == 0) {
do_customer_stuff();
printf("%d is free!\n", getpid());
exit(0);
}
}
wait(NULL);
free(pids);
shmdt(q);
return 0;
}
void do_customer_stuff() {
pid_t my_pid = getpid();
my_haircuts = 0;
printf("%d is gonna do some customer stuff at %10.ld\n", my_pid, get_timestamp());
while (my_haircuts < haircuts_count) {
printf("%d is gonna get a haircut at %10.ld\n", my_pid, get_timestamp());
if (in_da_shop()) {
wait_for_barber();
while(wait_for_sigusr) {
sigsuspend(&sig_old_mask);
}
sigprocmask(SIG_UNBLOCK, &sig_mask, NULL);
printf("%d is leaving the shop with awesome haircut at %10.ld\n", my_pid, get_timestamp());
} else {
printf("%d is leaving the shop due to lack of space at %10.ld\n", my_pid, get_timestamp());
my_haircuts++;
}
}
}
char in_da_shop() {
sembuf semaphore;
pid_t my_pid = getpid();
char result;
prolaag(queue_sem_id, &semaphore);
if (!is_empty(q)) {
printf("%d sees there are people waiting and joins queue at %.10ld\n", my_pid, get_timestamp());
result = push(q, my_pid);
verhoog(queue_sem_id, &semaphore);
} else {
prolaag(seat_sem_id, &semaphore);
if (q->seat > 0) {
printf("%d sees seat is taken and joins queue at %.10ld\n",
my_pid, get_timestamp());
result = push(q, my_pid);
verhoog(queue_sem_id, &semaphore);
verhoog(seat_sem_id, &semaphore);
} else {
prolaag(pillow_sem_id, &semaphore);
if (q->pillow <= 0) {
printf("%d sees barber is not asleep and joins queue at %.10ld\n",
my_pid, get_timestamp());
result = push(q, my_pid);
verhoog(queue_sem_id, &semaphore);
verhoog(seat_sem_id, &semaphore);
verhoog(pillow_sem_id, &semaphore);
} else {
printf("%d sees barber %d is sleeping and wakes him at %.10ld\n",
my_pid, q->pillow, get_timestamp());
push(q, my_pid);
kill(q->pillow, SIGUSR1);
verhoog(queue_sem_id, &semaphore);
verhoog(seat_sem_id, &semaphore);
verhoog(pillow_sem_id, &semaphore);
result = 1;
}
}
}
return result;
}
void wait_for_barber() {
CHECK_NEGATIVE("wait_for_barber", signal(SIGUSR1, handler), "Cannot create SIGUSR1 handler")
sigfillset(&sig_mask);
sigdelset(&sig_mask, SIGUSR1);
sigprocmask(SIG_BLOCK, &sig_mask, &sig_old_mask);
wait_for_sigusr = 1;
}
void handler(int sig) {
if (sig == SIGUSR1) {
my_haircuts++;
wait_for_sigusr = 0;
}
}
| 28.743363 | 100 | 0.628079 |
47a748054161483a26314a4073c168fccc08d169 | 5,066 | c | C | src/sbbs3/asc2ans.c | jonny290/synchronet | 012a39d00a3160a593ef5923fdc1ee95e0497083 | [
"Artistic-2.0"
] | 1 | 2017-07-18T03:56:48.000Z | 2017-07-18T03:56:48.000Z | src/sbbs3/asc2ans.c | jonny290/synchronet | 012a39d00a3160a593ef5923fdc1ee95e0497083 | [
"Artistic-2.0"
] | null | null | null | src/sbbs3/asc2ans.c | jonny290/synchronet | 012a39d00a3160a593ef5923fdc1ee95e0497083 | [
"Artistic-2.0"
] | null | null | null | /* asc2ans.c */
/* Converts Synchronet Ctrl-A codes into ANSI escape sequences */
/* $Id: asc2ans.c,v 1.6 2014/01/05 06:37:39 rswindell Exp $ */
/****************************************************************************
* @format.tab-size 4 (Plain Text/Source Code File Header) *
* @format.use-tabs true (see http://www.synchro.net/ptsc_hdr.html) *
* *
* Copyright 2014 Rob Swindell - http://www.synchro.net/copyright.html *
* *
* This program is free software; you can redistribute it and/or *
* modify it under the terms of the GNU General Public License *
* as published by the Free Software Foundation; either version 2 *
* of the License, or (at your option) any later version. *
* See the GNU General Public License for more details: gpl.txt or *
* http://www.fsf.org/copyleft/gpl.html *
* *
* Anonymous FTP access to the most recent released source is available at *
* ftp://vert.synchro.net, ftp://cvs.synchro.net and ftp://ftp.synchro.net *
* *
* Anonymous CVS access to the development source and modification history *
* is available at cvs.synchro.net:/cvsroot/sbbs, example: *
* cvs -d :pserver:anonymous@cvs.synchro.net:/cvsroot/sbbs login *
* (just hit return, no password is necessary) *
* cvs -d :pserver:anonymous@cvs.synchro.net:/cvsroot/sbbs checkout src *
* *
* For Synchronet coding style and modification guidelines, see *
* http://www.synchro.net/source.html *
* *
* You are encouraged to submit any modifications (preferably in Unix diff *
* format) via e-mail to mods@synchro.net *
* *
* Note: If this box doesn't appear square, then you need to fix your tabs. *
****************************************************************************/
#include <stdio.h>
#include <ctype.h> /* toupper */
#include <string.h> /* strcmp */
#define CTRL_A '\1'
#define ANSI fprintf(out,"\x1b[")
static void print_usage(const char* prog)
{
char revision[16];
sscanf("$Revision: 1.6 $", "%*s %s", revision);
fprintf(stderr,"\nSynchronet Ctrl-A-Code to ANSI-Terminal-Sequence Conversion Utility v%s\n",revision);
fprintf(stderr,"\nusage: %s infile.asc [outfile.ans] [[option] [...]]\n",prog);
fprintf(stderr,"\noptions:\n\n");
fprintf(stderr,"-strip strip Ctrl-A codes without ANSI equivalent, e.g. pause, delay\n");
}
int main(int argc, char **argv)
{
int ch;
int i;
int strip=0;
FILE* in=stdin;
FILE* out=stdout;
if(argc<2) {
print_usage(argv[0]);
return(0);
}
for(i=1; i<argc; i++) {
if(argv[i][0]=='-') {
if(strcmp(argv[i], "-strip") == 0)
strip = 1;
else {
print_usage(argv[0]);
return 0;
}
} else if(in==stdin) {
if((in=fopen(argv[i],"rb"))==NULL) {
perror(argv[i]);
return(1);
}
} else if(out==stdout) {
if((out=fopen(argv[i],"wb"))==NULL) {
perror(argv[i]);
return(1);
}
}
}
while((ch=fgetc(in))!=EOF) {
if(ch==CTRL_A) { /* ctrl-a */
ch=fgetc(in);
if(ch==EOF || toupper(ch)=='Z') /* EOF */
break;
if(ch>0x7f) { /* move cursor right x columns */
int cnt=ch-0x7f;
ANSI;
if(cnt>1)
fprintf(out,"%u",cnt);
fputc('C',out);
continue;
}
switch(toupper(ch)) {
case 'A':
fputc('\1',out);
break;
case '<':
fputc('\b',out);
break;
case '>':
ANSI;
fputc('K',out);
break;
case '[':
fputc('\r',out);
break;
case ']':
fputc('\n',out);
break;
case 'L':
ANSI;
fprintf(out,"2J"); /* clear screen */
ANSI;
fprintf(out,"H"); /* home cursor */
break;
case '-':
case '_':
case 'N':
ANSI;
fprintf(out,"0m");
break;
case 'H':
ANSI;
fprintf(out,"1m");
break;
case 'I':
ANSI;
fprintf(out,"5m");
break;
case 'K':
ANSI;
fprintf(out,"30m");
break;
case 'R':
ANSI;
fprintf(out,"31m");
break;
case 'G':
ANSI;
fprintf(out,"32m");
break;
case 'Y':
ANSI;
fprintf(out,"33m");
break;
case 'B':
ANSI;
fprintf(out,"34m");
break;
case 'M':
ANSI;
fprintf(out,"35m");
break;
case 'C':
ANSI;
fprintf(out,"36m");
break;
case 'W':
ANSI;
fprintf(out,"37m");
break;
case '0':
ANSI;
fprintf(out,"40m");
break;
case '1':
ANSI;
fprintf(out,"41m");
break;
case '2':
ANSI;
fprintf(out,"42m");
break;
case '3':
ANSI;
fprintf(out,"43m");
break;
case '4':
ANSI;
fprintf(out,"44m");
break;
case '5':
ANSI;
fprintf(out,"45m");
break;
case '6':
ANSI;
fprintf(out,"46m");
break;
case '7':
ANSI;
fprintf(out,"47m");
break;
default:
if(!strip)
fprintf(out,"\1%c",ch);
break;
}
}
else
fputc(ch,out);
}
return(0);
}
| 22.923077 | 104 | 0.522306 |
70419cf8c84f829f69d7957257957e93b5bf041a | 2,675 | h | C | Source/UtilsDevice/UtEspresso/espresso_sparse_int.h | keshbach/PEP | 75071aee89a718d318e13c55eee9eb5b9ae4e987 | [
"Apache-2.0"
] | 1 | 2021-12-11T14:21:55.000Z | 2021-12-11T14:21:55.000Z | Source/UtilsDevice/UtEspresso/espresso_sparse_int.h | keshbach/PEP | 75071aee89a718d318e13c55eee9eb5b9ae4e987 | [
"Apache-2.0"
] | null | null | null | Source/UtilsDevice/UtEspresso/espresso_sparse_int.h | keshbach/PEP | 75071aee89a718d318e13c55eee9eb5b9ae4e987 | [
"Apache-2.0"
] | 1 | 2021-06-23T14:01:55.000Z | 2021-06-23T14:01:55.000Z | /***************************************************************************/
/* Copyright (c) 1988, 1989, Regents of the University of California. */
/* All rights reserved. */
/***************************************************************************/
#if !defined(espresso_sparse_int_h)
#define espresso_sparse_int_h
/*
* sorted, double-linked list insertion
*
* type: object type
*
* first, last: fields (in header) to head and tail of the list
* count: field (in header) of length of the list
*
* next, prev: fields (in object) to link next and previous objects
* value: field (in object) which controls the order
*
* newval: value field for new object
* e: an object to use if insertion needed (set to actual value used)
*/
#define MSorted_Insert(type, first, last, count, next, prev, value, newval, e) \
if (last == 0) \
{ \
e->value = newval; \
first = e; \
last = e; \
e->next = 0; \
e->prev = 0; \
count++; \
} \
else if (last->value < newval) \
{ \
e->value = newval; \
last->next = e; \
e->prev = last; \
last = e; \
e->next = 0; \
count++; \
} \
else if (first->value > newval) \
{ \
e->value = newval; \
first->prev = e; \
e->next = first; \
first = e; \
e->prev = 0; \
count++; \
} \
else \
{ \
type *p; \
for(p = first; p->value < newval; p = p->next) \
; \
if (p->value > newval) \
{ \
e->value = newval; \
p = p->prev; \
p->next->prev = e; \
e->next = p->next; \
p->next = e; \
e->prev = p; \
count++; \
} \
else \
{ \
e = p; \
} \
}
/*
* double linked-list deletion
*/
#define MDLL_Unlink(p, first, last, next, prev, count) \
{ \
if (p->prev == 0) \
{ \
first = p->next; \
} \
else \
{ \
p->prev->next = p->next; \
} \
if (p->next == 0) \
{ \
last = p->prev; \
} \
else \
{ \
p->next->prev = p->prev; \
} \
count--; \
}
void sm_col_remove_element(register TPSM_Col pcol, register TPSM_Element p);
#endif /* end of espresso_sparse_int_h */
/***************************************************************************/
/* Copyright (c) 1988, 1989, Regents of the University of California. */
/* All rights reserved. */
/***************************************************************************/
| 25.47619 | 80 | 0.403364 |
4a6aab017ab0b9d872cd04277c2aa354f8f42a4b | 929 | h | C | AICSE-demo-student/demo/style_transfer_bcl/src/offline/include/data_provider.h | iuming/AI_Computer_Systems | b47c4914a23acfdc469e1a80735bf68191b2acba | [
"MIT"
] | 5 | 2020-12-07T03:16:49.000Z | 2022-01-08T13:59:20.000Z | AICSE-demo-student/demo/style_transfer_bcl/src/offline/include/data_provider.h | iuming/AI_Computer_Systems | b47c4914a23acfdc469e1a80735bf68191b2acba | [
"MIT"
] | 21 | 2020-09-25T22:41:00.000Z | 2022-03-12T00:50:43.000Z | AICSE-demo-student/demo/style_transfer_bcl/src/offline/include/data_provider.h | iuming/AI_Computer_Systems | b47c4914a23acfdc469e1a80735bf68191b2acba | [
"MIT"
] | 1 | 2022-02-18T09:01:43.000Z | 2022-02-18T09:01:43.000Z | #ifndef DATA_PROVIDER_H_
#define DATA_PROVIDER_H_
#include "data_transfer.h"
namespace StyleTransfer {
class DataProvider {
public:
DataProvider(std::string file_list_);
bool get_image_file();
cv::Mat convert_color_space(std::string file_path);
cv::Mat resize_image(const cv::Mat& source);
cv::Mat convert_float(cv::Mat img);
cv::Mat subtract_mean(cv::Mat float_image);
void set_mean();
void split_image(DataTransfer* DataT);
~DataProvider();
void run(DataTransfer* DataT);
private:
std::vector<std::string> image_list;
std::string file_list;
int image_num;
int image_channel;
cv::Mat mean_;
int batch_size;
}; // class DataProvider
} // namespace StyleTransfer
#endif // DATA_PROVIDER_H_
| 27.323529 | 63 | 0.579117 |
0bd84c145e228716b121194177ad4472b55152e4 | 191 | h | C | MyTilemapEditor/BrushUI/IntInput.h | sam830917/MyTilemapEditor | ef5524f816984c34e1cf2b4b5f75f5ed88666a00 | [
"BSD-2-Clause"
] | 6 | 2021-04-06T21:12:29.000Z | 2021-05-31T21:54:51.000Z | MyTilemapEditor/BrushUI/IntInput.h | sam830917/MyTilemapEditor | ef5524f816984c34e1cf2b4b5f75f5ed88666a00 | [
"BSD-2-Clause"
] | null | null | null | MyTilemapEditor/BrushUI/IntInput.h | sam830917/MyTilemapEditor | ef5524f816984c34e1cf2b4b5f75f5ed88666a00 | [
"BSD-2-Clause"
] | null | null | null | #pragma once
#include <QSpinBox>
class IntInput : public QSpinBox
{
public:
IntInput();
IntInput( int* connectInt );
IntInput( int value );
~IntInput();
private:
int* m_connectInt;
}; | 12.733333 | 32 | 0.696335 |
f2cb1f40770f400c3865b934918189c64103e4f2 | 2,283 | h | C | p2/P2.h | medina325/Computer-Graphics-Homework---RayTracer-Renderer-with-BVH | 62d95109c7358a1f9c004138a9007d91cba47987 | [
"Apache-2.0"
] | null | null | null | p2/P2.h | medina325/Computer-Graphics-Homework---RayTracer-Renderer-with-BVH | 62d95109c7358a1f9c004138a9007d91cba47987 | [
"Apache-2.0"
] | null | null | null | p2/P2.h | medina325/Computer-Graphics-Homework---RayTracer-Renderer-with-BVH | 62d95109c7358a1f9c004138a9007d91cba47987 | [
"Apache-2.0"
] | null | null | null | #ifndef __P2_h
#define __P2_h
#include "GLRenderer.h"
#include "SceneEditor.h"
#include "core/Flags.h"
#include "SceneObject.h"
using namespace cg;
class P2: public GLWindow
{
public:
P2(int width, int height):
GLWindow{"cg2019 - P2", width, height},
_program{"P2"},
_emptyCount{0},
_boxCount{0},
_sphereCount{0},
_cameraCount{0}
{
// do nothing
}
/// Initialize the app.
void initialize() override;
/// Update the GUI.
void gui() override;
/// Render the scene.
void render() override;
private:
enum ViewMode
{
Editor = 0,
Renderer = 1
};
enum class MoveBits
{
Left = 1,
Right = 2,
Forward = 4,
Back = 8,
Up = 16,
Down = 32
};
enum class DragBits
{
Rotate = 1,
Pan = 2
};
int _boxCount;
int _emptyCount;
int _sphereCount;
int _cameraCount;
GLSL::Program _program;
Reference<Scene> _scene;
Reference<SceneEditor> _editor;
Reference<GLRenderer> _renderer;
SceneNode* _current{};
Color _selectedWireframeColor{255, 102, 0};
Flags<MoveBits> _moveFlags{};
Flags<DragBits> _dragFlags{};
int _pivotX;
int _pivotY;
int _mouseX;
int _mouseY;
bool _showAssets{true};
bool _showEditorView{true};
ViewMode _viewMode{ViewMode::Editor};
static MeshMap _defaultMeshes;
void buildScene();
void mainMenu();
void fileMenu();
void showOptions();
void focus(SceneObject*);
void showHierarchy(std::list<cg::Reference<SceneObject>>::const_iterator itSceneObj);
void hierarchyWindow();
void inspectorWindow();
void assetsWindow();
void editorView();
void sceneGui();
void sceneObjectGui();
void objectGui();
void editorViewGui();
void inspectPrimitive(Primitive&);
void inspectCamera(Camera&);
void addComponentButton(SceneObject&);
void drawPrimitive(Primitive&);
void drawCamera_and_Axes(const Reference<SceneObject>&);
void renderAll(Camera* vp);
void renderScene();
void preview();
void renderEditorView();
bool windowResizeEvent(int, int) override;
bool keyInputEvent(int, int, int) override;
bool scrollEvent(double, double) override;
bool mouseButtonInputEvent(int, int, int) override;
bool mouseMoveEvent(double, double) override;
static void buildDefaultMeshes();
}; // P2
#endif // __P2_h
| 19.184874 | 86 | 0.689444 |
4adaecbba23ff30eb2a0f7a02298a5c7fe3e6baa | 651 | h | C | System/Library/PrivateFrameworks/UIFoundation.framework/NSTextLocationPrivate.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | 2 | 2021-11-02T09:23:27.000Z | 2022-03-28T08:21:57.000Z | System/Library/PrivateFrameworks/UIFoundation.framework/NSTextLocationPrivate.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | null | null | null | System/Library/PrivateFrameworks/UIFoundation.framework/NSTextLocationPrivate.h | lechium/iOS1351Headers | 6bed3dada5ffc20366b27f7f2300a24a48a6284e | [
"MIT"
] | 1 | 2022-03-28T08:21:59.000Z | 2022-03-28T08:21:59.000Z | /*
* This header is generated by classdump-dyld 1.5
* on Friday, April 30, 2021 at 11:34:55 AM Mountain Standard Time
* Operating System: Version 13.5.1 (Build 17F80)
* Image Source: /System/Library/PrivateFrameworks/UIFoundation.framework/UIFoundation
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley.
*/
@class NSString;
@protocol NSTextLocationPrivate <NSTextLocation>
@property (copy,readonly) NSString * type;
@optional
-(NSString *)type;
@end
| 34.263158 | 130 | 0.603687 |
2877e3e0256e16564a8af829f1b211d8374929d2 | 2,518 | h | C | hooks_CoreFoundation.h | JunesiPhone/iSpy | 42b56992f525d0885caaa65b1310c49fd3924691 | [
"Apache-2.0"
] | 392 | 2015-01-02T06:06:48.000Z | 2022-03-12T16:39:09.000Z | hooks_CoreFoundation.h | iamshreeram/iSpy | 42b56992f525d0885caaa65b1310c49fd3924691 | [
"Apache-2.0"
] | 11 | 2015-02-15T09:53:10.000Z | 2020-05-28T07:32:55.000Z | hooks_CoreFoundation.h | iamshreeram/iSpy | 42b56992f525d0885caaa65b1310c49fd3924691 | [
"Apache-2.0"
] | 109 | 2015-01-05T07:57:20.000Z | 2022-01-28T01:52:43.000Z |
/*
****************************************
*** CoreFoundation function hooking. ***
****************************************
Once a function is hooked, its original (unhooked) version is saved in the orig_* pointers.
We can use these to call the original unhooked functions.
The format for hooking C calls is:
FUNCNAME - the function we're hooking
bf_FUNCNAME - our new function. Overrides FUNCNAME. Define it below, along with the other bf_* functions.
orig_FUNCNAME - pointer to original FUNCNAME. We can call this :)
The orig_FUNCNAME return types and argument lists must match the original EXACTLY.
(unless you're a hardcore motherfucker and are deliberately munging data types for an epic hack. Caveat emptor.)
Consult man pages and/or other documentation for copy pasta. I got most of these from man.
*/
//
// Declarations of replacement funcs
//
Boolean bf_CFReadStreamSetProperty(CFReadStreamRef stream, CFStringRef propertyName, CFTypeRef propertyValue);
Boolean bf_CFWriteStreamSetProperty(CFWriteStreamRef stream, CFStringRef propertyName, CFTypeRef propertyValue);
CFIndex bf_CFReadStreamRead(CFReadStreamRef stream, UInt8 *buffer, CFIndex bufferLength);
CFIndex bf_CFWriteStreamWrite(CFWriteStreamRef stream, const UInt8 *buffer, CFIndex bufferLength);
CFURLRef bf_CFURLCreateWithString(CFAllocatorRef allocator, CFStringRef URLString, CFURLRef baseURL);
Boolean bf_CFReadStreamOpen(CFReadStreamRef stream);
Boolean bf_CFWriteStreamOpen(CFWriteStreamRef stream);
void bf_CFStreamCreatePairWithSocketToHost(CFAllocatorRef alloc, CFStringRef host, UInt32 port, CFReadStreamRef *readStream, CFWriteStreamRef *writeStream);
void bf_CFStreamCreatePairWithPeerSocketSignature(CFAllocatorRef alloc, const CFSocketSignature *signature, CFReadStreamRef *readStream, CFWriteStreamRef *writeStream);
void bf_CFStreamCreatePairWithSocket(CFAllocatorRef alloc, CFSocketNativeHandle sock, CFReadStreamRef *readStream, CFWriteStreamRef *writeStream);
CFReadStreamRef bf_CFReadStreamCreateWithBytesNoCopy(CFAllocatorRef alloc, const UInt8 *bytes, CFIndex length, CFAllocatorRef bytesDeallocator);
SecCertificateRef bf_SecCertificateCreateWithData(CFAllocatorRef allocator, CFDataRef data);
CFDictionaryRef bf_CFNetworkCopySystemProxySettings(void);
CFHTTPMessageRef bf_CFHTTPMessageCreateRequest(CFAllocatorRef alloc, CFStringRef requestMethod, CFURLRef url, CFStringRef httpVersion);
CFReadStreamRef bf_CFReadStreamCreateForHTTPRequest(CFAllocatorRef alloc, CFHTTPMessageRef request);
| 61.414634 | 168 | 0.812947 |
4f506091b1be13dd59aae37d9017c3f351acca46 | 70 | h | C | ordenacao/bs.h | alanrps/dicionario_anagramas_ed2 | 634b8b7fc94f5556c546e5537283aeae45578b7d | [
"MIT"
] | null | null | null | ordenacao/bs.h | alanrps/dicionario_anagramas_ed2 | 634b8b7fc94f5556c546e5537283aeae45578b7d | [
"MIT"
] | null | null | null | ordenacao/bs.h | alanrps/dicionario_anagramas_ed2 | 634b8b7fc94f5556c546e5537283aeae45578b7d | [
"MIT"
] | null | null | null | void bubble_sort(char *str);
void bubble_sort_palavras(ILISTA* lista); | 35 | 41 | 0.814286 |
9e83034057d9137fee7b7191a92eda19c3708358 | 398 | h | C | Example/Pods/Target Support Files/RJNetworking/RJNetworking-umbrella.h | RonnieJia/RJLoginMoudle | 97046e1af71dd75fbd6c1e396be6d2ba5d5e1882 | [
"MIT"
] | null | null | null | Example/Pods/Target Support Files/RJNetworking/RJNetworking-umbrella.h | RonnieJia/RJLoginMoudle | 97046e1af71dd75fbd6c1e396be6d2ba5d5e1882 | [
"MIT"
] | null | null | null | Example/Pods/Target Support Files/RJNetworking/RJNetworking-umbrella.h | RonnieJia/RJLoginMoudle | 97046e1af71dd75fbd6c1e396be6d2ba5d5e1882 | [
"MIT"
] | null | null | null | #ifdef __OBJC__
#import <UIKit/UIKit.h>
#else
#ifndef FOUNDATION_EXPORT
#if defined(__cplusplus)
#define FOUNDATION_EXPORT extern "C"
#else
#define FOUNDATION_EXPORT extern
#endif
#endif
#endif
#import "RJHTTPResponse.h"
#import "RJHTTPSessionManager.h"
#import "RJHTTPUrl.h"
FOUNDATION_EXPORT double RJNetworkingVersionNumber;
FOUNDATION_EXPORT const unsigned char RJNetworkingVersionString[];
| 19.9 | 66 | 0.819095 |
b121195cc598c6a9f4dccd6bbe21580e187ad7c9 | 15,280 | c | C | dir600b_v2.03/kernels/rt305x/drivers/ata/sata_svw.c | ghsecuritylab/DIR600B2 | 78510ce13e037c430c84b4cdc7f49939481fe894 | [
"BSD-2-Clause"
] | 1 | 2019-07-21T01:58:19.000Z | 2019-07-21T01:58:19.000Z | dir600b_v2.03/kernels/rt305x/drivers/ata/sata_svw.c | ghsecuritylab/DIR600B2 | 78510ce13e037c430c84b4cdc7f49939481fe894 | [
"BSD-2-Clause"
] | null | null | null | dir600b_v2.03/kernels/rt305x/drivers/ata/sata_svw.c | ghsecuritylab/DIR600B2 | 78510ce13e037c430c84b4cdc7f49939481fe894 | [
"BSD-2-Clause"
] | 3 | 2016-06-13T13:20:56.000Z | 2019-12-05T02:31:23.000Z | /*
* sata_svw.c - ServerWorks / Apple K2 SATA
*
* Maintained by: Benjamin Herrenschmidt <benh@kernel.crashing.org> and
* Jeff Garzik <jgarzik@pobox.com>
* Please ALWAYS copy linux-ide@vger.kernel.org
* on emails.
*
* Copyright 2003 Benjamin Herrenschmidt <benh@kernel.crashing.org>
*
* Bits from Jeff Garzik, Copyright RedHat, Inc.
*
* This driver probably works with non-Apple versions of the
* Broadcom chipset...
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, or (at your option)
* any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*
*
* libata documentation is available via 'make {ps|pdf}docs',
* as Documentation/DocBook/libata.*
*
* Hardware documentation available under NDA.
*
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/pci.h>
#include <linux/init.h>
#include <linux/blkdev.h>
#include <linux/delay.h>
#include <linux/interrupt.h>
#include <linux/device.h>
#include <scsi/scsi_host.h>
#include <linux/libata.h>
#ifdef CONFIG_PPC_OF
#include <asm/prom.h>
#include <asm/pci-bridge.h>
#endif /* CONFIG_PPC_OF */
#define DRV_NAME "sata_svw"
#define DRV_VERSION "2.1"
enum {
K2_FLAG_NO_ATAPI_DMA = (1 << 29),
/* Taskfile registers offsets */
K2_SATA_TF_CMD_OFFSET = 0x00,
K2_SATA_TF_DATA_OFFSET = 0x00,
K2_SATA_TF_ERROR_OFFSET = 0x04,
K2_SATA_TF_NSECT_OFFSET = 0x08,
K2_SATA_TF_LBAL_OFFSET = 0x0c,
K2_SATA_TF_LBAM_OFFSET = 0x10,
K2_SATA_TF_LBAH_OFFSET = 0x14,
K2_SATA_TF_DEVICE_OFFSET = 0x18,
K2_SATA_TF_CMDSTAT_OFFSET = 0x1c,
K2_SATA_TF_CTL_OFFSET = 0x20,
/* DMA base */
K2_SATA_DMA_CMD_OFFSET = 0x30,
/* SCRs base */
K2_SATA_SCR_STATUS_OFFSET = 0x40,
K2_SATA_SCR_ERROR_OFFSET = 0x44,
K2_SATA_SCR_CONTROL_OFFSET = 0x48,
/* Others */
K2_SATA_SICR1_OFFSET = 0x80,
K2_SATA_SICR2_OFFSET = 0x84,
K2_SATA_SIM_OFFSET = 0x88,
/* Port stride */
K2_SATA_PORT_OFFSET = 0x100,
board_svw4 = 0,
board_svw8 = 1,
};
static const struct k2_board_info {
unsigned int n_ports;
unsigned long port_flags;
} k2_board_info[] = {
/* board_svw4 */
{ 4, K2_FLAG_NO_ATAPI_DMA },
/* board_svw8 */
{ 8, K2_FLAG_NO_ATAPI_DMA },
};
static u8 k2_stat_check_status(struct ata_port *ap);
static int k2_sata_check_atapi_dma(struct ata_queued_cmd *qc)
{
if (qc->ap->flags & K2_FLAG_NO_ATAPI_DMA)
return -1; /* ATAPI DMA not supported */
return 0;
}
static u32 k2_sata_scr_read (struct ata_port *ap, unsigned int sc_reg)
{
if (sc_reg > SCR_CONTROL)
return 0xffffffffU;
return readl((void __iomem *) ap->ioaddr.scr_addr + (sc_reg * 4));
}
static void k2_sata_scr_write (struct ata_port *ap, unsigned int sc_reg,
u32 val)
{
if (sc_reg > SCR_CONTROL)
return;
writel(val, (void __iomem *) ap->ioaddr.scr_addr + (sc_reg * 4));
}
static void k2_sata_tf_load(struct ata_port *ap, const struct ata_taskfile *tf)
{
struct ata_ioports *ioaddr = &ap->ioaddr;
unsigned int is_addr = tf->flags & ATA_TFLAG_ISADDR;
if (tf->ctl != ap->last_ctl) {
writeb(tf->ctl, ioaddr->ctl_addr);
ap->last_ctl = tf->ctl;
ata_wait_idle(ap);
}
if (is_addr && (tf->flags & ATA_TFLAG_LBA48)) {
writew(tf->feature | (((u16)tf->hob_feature) << 8),
ioaddr->feature_addr);
writew(tf->nsect | (((u16)tf->hob_nsect) << 8),
ioaddr->nsect_addr);
writew(tf->lbal | (((u16)tf->hob_lbal) << 8),
ioaddr->lbal_addr);
writew(tf->lbam | (((u16)tf->hob_lbam) << 8),
ioaddr->lbam_addr);
writew(tf->lbah | (((u16)tf->hob_lbah) << 8),
ioaddr->lbah_addr);
} else if (is_addr) {
writew(tf->feature, ioaddr->feature_addr);
writew(tf->nsect, ioaddr->nsect_addr);
writew(tf->lbal, ioaddr->lbal_addr);
writew(tf->lbam, ioaddr->lbam_addr);
writew(tf->lbah, ioaddr->lbah_addr);
}
if (tf->flags & ATA_TFLAG_DEVICE)
writeb(tf->device, ioaddr->device_addr);
ata_wait_idle(ap);
}
static void k2_sata_tf_read(struct ata_port *ap, struct ata_taskfile *tf)
{
struct ata_ioports *ioaddr = &ap->ioaddr;
u16 nsect, lbal, lbam, lbah, feature;
tf->command = k2_stat_check_status(ap);
tf->device = readw(ioaddr->device_addr);
feature = readw(ioaddr->error_addr);
nsect = readw(ioaddr->nsect_addr);
lbal = readw(ioaddr->lbal_addr);
lbam = readw(ioaddr->lbam_addr);
lbah = readw(ioaddr->lbah_addr);
tf->feature = feature;
tf->nsect = nsect;
tf->lbal = lbal;
tf->lbam = lbam;
tf->lbah = lbah;
if (tf->flags & ATA_TFLAG_LBA48) {
tf->hob_feature = feature >> 8;
tf->hob_nsect = nsect >> 8;
tf->hob_lbal = lbal >> 8;
tf->hob_lbam = lbam >> 8;
tf->hob_lbah = lbah >> 8;
}
}
/**
* k2_bmdma_setup_mmio - Set up PCI IDE BMDMA transaction (MMIO)
* @qc: Info associated with this ATA transaction.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*/
static void k2_bmdma_setup_mmio (struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
unsigned int rw = (qc->tf.flags & ATA_TFLAG_WRITE);
u8 dmactl;
void __iomem *mmio = (void __iomem *) ap->ioaddr.bmdma_addr;
/* load PRD table addr. */
mb(); /* make sure PRD table writes are visible to controller */
writel(ap->prd_dma, mmio + ATA_DMA_TABLE_OFS);
/* specify data direction, triple-check start bit is clear */
dmactl = readb(mmio + ATA_DMA_CMD);
dmactl &= ~(ATA_DMA_WR | ATA_DMA_START);
if (!rw)
dmactl |= ATA_DMA_WR;
writeb(dmactl, mmio + ATA_DMA_CMD);
/* issue r/w command if this is not a ATA DMA command*/
if (qc->tf.protocol != ATA_PROT_DMA)
ap->ops->exec_command(ap, &qc->tf);
}
/**
* k2_bmdma_start_mmio - Start a PCI IDE BMDMA transaction (MMIO)
* @qc: Info associated with this ATA transaction.
*
* LOCKING:
* spin_lock_irqsave(host lock)
*/
static void k2_bmdma_start_mmio (struct ata_queued_cmd *qc)
{
struct ata_port *ap = qc->ap;
void __iomem *mmio = (void __iomem *) ap->ioaddr.bmdma_addr;
u8 dmactl;
/* start host DMA transaction */
dmactl = readb(mmio + ATA_DMA_CMD);
writeb(dmactl | ATA_DMA_START, mmio + ATA_DMA_CMD);
/* There is a race condition in certain SATA controllers that can
be seen when the r/w command is given to the controller before the
host DMA is started. On a Read command, the controller would initiate
the command to the drive even before it sees the DMA start. When there
are very fast drives connected to the controller, or when the data request
hits in the drive cache, there is the possibility that the drive returns a part
or all of the requested data to the controller before the DMA start is issued.
In this case, the controller would become confused as to what to do with the data.
In the worst case when all the data is returned back to the controller, the
controller could hang. In other cases it could return partial data returning
in data corruption. This problem has been seen in PPC systems and can also appear
on an system with very fast disks, where the SATA controller is sitting behind a
number of bridges, and hence there is significant latency between the r/w command
and the start command. */
/* issue r/w command if the access is to ATA*/
if (qc->tf.protocol == ATA_PROT_DMA)
ap->ops->exec_command(ap, &qc->tf);
}
static u8 k2_stat_check_status(struct ata_port *ap)
{
return readl((void __iomem *) ap->ioaddr.status_addr);
}
#ifdef CONFIG_PPC_OF
/*
* k2_sata_proc_info
* inout : decides on the direction of the dataflow and the meaning of the
* variables
* buffer: If inout==FALSE data is being written to it else read from it
* *start: If inout==FALSE start of the valid data in the buffer
* offset: If inout==FALSE offset from the beginning of the imaginary file
* from which we start writing into the buffer
* length: If inout==FALSE max number of bytes to be written into the buffer
* else number of bytes in the buffer
*/
static int k2_sata_proc_info(struct Scsi_Host *shost, char *page, char **start,
off_t offset, int count, int inout)
{
struct ata_port *ap;
struct device_node *np;
int len, index;
/* Find the ata_port */
ap = ata_shost_to_port(shost);
if (ap == NULL)
return 0;
/* Find the OF node for the PCI device proper */
np = pci_device_to_OF_node(to_pci_dev(ap->host->dev));
if (np == NULL)
return 0;
/* Match it to a port node */
index = (ap == ap->host->ports[0]) ? 0 : 1;
for (np = np->child; np != NULL; np = np->sibling) {
const u32 *reg = get_property(np, "reg", NULL);
if (!reg)
continue;
if (index == *reg)
break;
}
if (np == NULL)
return 0;
len = sprintf(page, "devspec: %s\n", np->full_name);
return len;
}
#endif /* CONFIG_PPC_OF */
static struct scsi_host_template k2_sata_sht = {
.module = THIS_MODULE,
.name = DRV_NAME,
.ioctl = ata_scsi_ioctl,
.queuecommand = ata_scsi_queuecmd,
.can_queue = ATA_DEF_QUEUE,
.this_id = ATA_SHT_THIS_ID,
.sg_tablesize = LIBATA_MAX_PRD,
.cmd_per_lun = ATA_SHT_CMD_PER_LUN,
.emulated = ATA_SHT_EMULATED,
.use_clustering = ATA_SHT_USE_CLUSTERING,
.proc_name = DRV_NAME,
.dma_boundary = ATA_DMA_BOUNDARY,
.slave_configure = ata_scsi_slave_config,
.slave_destroy = ata_scsi_slave_destroy,
#ifdef CONFIG_PPC_OF
.proc_info = k2_sata_proc_info,
#endif
.bios_param = ata_std_bios_param,
};
static const struct ata_port_operations k2_sata_ops = {
.port_disable = ata_port_disable,
.tf_load = k2_sata_tf_load,
.tf_read = k2_sata_tf_read,
.check_status = k2_stat_check_status,
.exec_command = ata_exec_command,
.dev_select = ata_std_dev_select,
.check_atapi_dma = k2_sata_check_atapi_dma,
.bmdma_setup = k2_bmdma_setup_mmio,
.bmdma_start = k2_bmdma_start_mmio,
.bmdma_stop = ata_bmdma_stop,
.bmdma_status = ata_bmdma_status,
.qc_prep = ata_qc_prep,
.qc_issue = ata_qc_issue_prot,
.data_xfer = ata_data_xfer,
.freeze = ata_bmdma_freeze,
.thaw = ata_bmdma_thaw,
.error_handler = ata_bmdma_error_handler,
.post_internal_cmd = ata_bmdma_post_internal_cmd,
.irq_handler = ata_interrupt,
.irq_clear = ata_bmdma_irq_clear,
.irq_on = ata_irq_on,
.irq_ack = ata_irq_ack,
.scr_read = k2_sata_scr_read,
.scr_write = k2_sata_scr_write,
.port_start = ata_port_start,
};
static void k2_sata_setup_port(struct ata_ioports *port, void __iomem *base)
{
port->cmd_addr = base + K2_SATA_TF_CMD_OFFSET;
port->data_addr = base + K2_SATA_TF_DATA_OFFSET;
port->feature_addr =
port->error_addr = base + K2_SATA_TF_ERROR_OFFSET;
port->nsect_addr = base + K2_SATA_TF_NSECT_OFFSET;
port->lbal_addr = base + K2_SATA_TF_LBAL_OFFSET;
port->lbam_addr = base + K2_SATA_TF_LBAM_OFFSET;
port->lbah_addr = base + K2_SATA_TF_LBAH_OFFSET;
port->device_addr = base + K2_SATA_TF_DEVICE_OFFSET;
port->command_addr =
port->status_addr = base + K2_SATA_TF_CMDSTAT_OFFSET;
port->altstatus_addr =
port->ctl_addr = base + K2_SATA_TF_CTL_OFFSET;
port->bmdma_addr = base + K2_SATA_DMA_CMD_OFFSET;
port->scr_addr = base + K2_SATA_SCR_STATUS_OFFSET;
}
static int k2_sata_init_one (struct pci_dev *pdev, const struct pci_device_id *ent)
{
static int printed_version;
struct device *dev = &pdev->dev;
struct ata_probe_ent *probe_ent;
void __iomem *mmio_base;
const struct k2_board_info *board_info =
&k2_board_info[ent->driver_data];
int rc;
int i;
if (!printed_version++)
dev_printk(KERN_DEBUG, &pdev->dev, "version " DRV_VERSION "\n");
/*
* If this driver happens to only be useful on Apple's K2, then
* we should check that here as it has a normal Serverworks ID
*/
rc = pcim_enable_device(pdev);
if (rc)
return rc;
/*
* Check if we have resources mapped at all (second function may
* have been disabled by firmware)
*/
if (pci_resource_len(pdev, 5) == 0)
return -ENODEV;
/* Request and iomap PCI regions */
rc = pcim_iomap_regions(pdev, 1 << 5, DRV_NAME);
if (rc == -EBUSY)
pcim_pin_device(pdev);
if (rc)
return rc;
rc = pci_set_dma_mask(pdev, ATA_DMA_MASK);
if (rc)
return rc;
rc = pci_set_consistent_dma_mask(pdev, ATA_DMA_MASK);
if (rc)
return rc;
probe_ent = devm_kzalloc(dev, sizeof(*probe_ent), GFP_KERNEL);
if (probe_ent == NULL)
return -ENOMEM;
probe_ent->dev = pci_dev_to_dev(pdev);
INIT_LIST_HEAD(&probe_ent->node);
probe_ent->sht = &k2_sata_sht;
probe_ent->port_flags = ATA_FLAG_SATA | ATA_FLAG_NO_LEGACY |
ATA_FLAG_MMIO | board_info->port_flags;
probe_ent->port_ops = &k2_sata_ops;
probe_ent->n_ports = 4;
probe_ent->irq = pdev->irq;
probe_ent->irq_flags = IRQF_SHARED;
probe_ent->iomap = pcim_iomap_table(pdev);
/* We don't care much about the PIO/UDMA masks, but the core won't like us
* if we don't fill these
*/
probe_ent->pio_mask = 0x1f;
probe_ent->mwdma_mask = 0x7;
probe_ent->udma_mask = 0x7f;
mmio_base = probe_ent->iomap[5];
/* different controllers have different number of ports - currently 4 or 8 */
/* All ports are on the same function. Multi-function device is no
* longer available. This should not be seen in any system. */
for (i = 0; i < board_info->n_ports; i++)
k2_sata_setup_port(&probe_ent->port[i],
mmio_base + i * K2_SATA_PORT_OFFSET);
/* Clear a magic bit in SCR1 according to Darwin, those help
* some funky seagate drives (though so far, those were already
* set by the firmware on the machines I had access to)
*/
writel(readl(mmio_base + K2_SATA_SICR1_OFFSET) & ~0x00040000,
mmio_base + K2_SATA_SICR1_OFFSET);
/* Clear SATA error & interrupts we don't use */
writel(0xffffffff, mmio_base + K2_SATA_SCR_ERROR_OFFSET);
writel(0x0, mmio_base + K2_SATA_SIM_OFFSET);
pci_set_master(pdev);
if (!ata_device_add(probe_ent))
return -ENODEV;
devm_kfree(dev, probe_ent);
return 0;
}
/* 0x240 is device ID for Apple K2 device
* 0x241 is device ID for Serverworks Frodo4
* 0x242 is device ID for Serverworks Frodo8
* 0x24a is device ID for BCM5785 (aka HT1000) HT southbridge integrated SATA
* controller
* */
static const struct pci_device_id k2_sata_pci_tbl[] = {
{ PCI_VDEVICE(SERVERWORKS, 0x0240), board_svw4 },
{ PCI_VDEVICE(SERVERWORKS, 0x0241), board_svw4 },
{ PCI_VDEVICE(SERVERWORKS, 0x0242), board_svw8 },
{ PCI_VDEVICE(SERVERWORKS, 0x024a), board_svw4 },
{ PCI_VDEVICE(SERVERWORKS, 0x024b), board_svw4 },
{ }
};
static struct pci_driver k2_sata_pci_driver = {
.name = DRV_NAME,
.id_table = k2_sata_pci_tbl,
.probe = k2_sata_init_one,
.remove = ata_pci_remove_one,
};
static int __init k2_sata_init(void)
{
return pci_register_driver(&k2_sata_pci_driver);
}
static void __exit k2_sata_exit(void)
{
pci_unregister_driver(&k2_sata_pci_driver);
}
MODULE_AUTHOR("Benjamin Herrenschmidt");
MODULE_DESCRIPTION("low-level driver for K2 SATA controller");
MODULE_LICENSE("GPL");
MODULE_DEVICE_TABLE(pci, k2_sata_pci_tbl);
MODULE_VERSION(DRV_VERSION);
module_init(k2_sata_init);
module_exit(k2_sata_exit);
| 29.328215 | 86 | 0.715249 |
7f8b8200bd9567e815a35b59dc79d4ed8467192b | 1,149 | h | C | weighters/weight_minervaq2qe.h | MinervaExpt/MAT-MINERvA | a142702563260d8f21c1dbd7b739364823ad38e7 | [
"MIT"
] | null | null | null | weighters/weight_minervaq2qe.h | MinervaExpt/MAT-MINERvA | a142702563260d8f21c1dbd7b739364823ad38e7 | [
"MIT"
] | 4 | 2021-08-31T17:17:12.000Z | 2021-10-29T19:41:39.000Z | weighters/weight_minervaq2qe.h | MinervaExpt/MAT-MINERvA | a142702563260d8f21c1dbd7b739364823ad38e7 | [
"MIT"
] | null | null | null | #ifndef weight_minervaq2qe_h
#define weight_minervaq2qe_h
#include <fstream> //ifstream
#include <iostream> //cout
#include <TString.h>
#include <TH3D.h>
#include <TH2D.h>
#include <TH1D.h>
#include <TFile.h>
#include <cmath>
#include <cassert>
#include "PlotUtils/MnvH1D.h"
#include "PlotUtils/MnvVertErrorBand.h"
//For Compatibility with ROOT compiler
//uncomment the following:
//#define ROOT
/*!
This is a class for taking a q2qe value and reweighting values based on the 2D ME q2qe data/mc ratio.
*/
namespace PlotUtils{
class weight_minervaq2qe
{
public:
//Constructor: Read in params from a filename
weight_minervaq2qe(const TString f) { read(f); } //Read in params from files
TFile* fQ2QERatio;
TH1D *hQ2QERatio;
// MINERvA holds kinematics in MeV, but all these functions require GeV
// So make sure you pass them in GeV.
double getWeight(const double q2qe); //in GeV2
//Initializer
void read(TString filename);
private:
double getWeightInternal(const double q2qe); //in GeV2
};
}
#endif
| 22.529412 | 104 | 0.661445 |
fa34411d74abf04df0d7e1d79d77b4f22dbc3c76 | 4,788 | h | C | source/ff.ui/source/render_device.h | spadapet/ff_game_library | f1bf00f90adde66c2c2aa35b109fe61b8d2c6352 | [
"MIT"
] | null | null | null | source/ff.ui/source/render_device.h | spadapet/ff_game_library | f1bf00f90adde66c2c2aa35b109fe61b8d2c6352 | [
"MIT"
] | null | null | null | source/ff.ui/source/render_device.h | spadapet/ff_game_library | f1bf00f90adde66c2c2aa35b109fe61b8d2c6352 | [
"MIT"
] | null | null | null | #pragma once
#if DXVER == 11
namespace ff::internal::ui
{
class render_device : public Noesis::RenderDevice, private ff::dxgi::device_child_base
{
public:
render_device(bool srgb);
virtual ~render_device() override;
// Noesis::RenderDevice
virtual const Noesis::DeviceCaps& GetCaps() const override;
virtual Noesis::Ptr<Noesis::RenderTarget> CreateRenderTarget(const char* label, uint32_t width, uint32_t height, uint32_t sample_count, bool needs_stencil) override;
virtual Noesis::Ptr<Noesis::RenderTarget> CloneRenderTarget(const char* label, Noesis::RenderTarget* surface) override;
virtual Noesis::Ptr<Noesis::Texture> CreateTexture(const char* label, uint32_t width, uint32_t height, uint32_t mip_count, Noesis::TextureFormat::Enum format, const void** data) override;
virtual void UpdateTexture(Noesis::Texture* texture, uint32_t level, uint32_t x, uint32_t y, uint32_t width, uint32_t height, const void* data) override;
virtual void BeginOffscreenRender() override;
virtual void EndOffscreenRender() override;
virtual void BeginOnscreenRender() override;
virtual void EndOnscreenRender() override;
virtual void SetRenderTarget(Noesis::RenderTarget* surface) override;
virtual void ResolveRenderTarget(Noesis::RenderTarget* surface, const Noesis::Tile* tiles, uint32_t tile_count) override;
virtual void* MapVertices(uint32_t bytes) override;
virtual void UnmapVertices() override;
virtual void* MapIndices(uint32_t bytes) override;
virtual void UnmapIndices() override;
virtual void DrawBatch(const Noesis::Batch& batch) override;
private:
// device_child_base
virtual bool reset() override;
enum class msaa_samples_t { x1, x2, x4, x8, x16, Count };
enum class texture_slot_t { Pattern, Ramps, Image, Glyphs, Shadow, PaletteImage, Palette, Count };
struct vertex_shader_t
{
ID3D11VertexShader* shader();
std::string_view resource_name;
Microsoft::WRL::ComPtr<ID3D11VertexShader> shader_;
};
struct vertex_shader_and_layout_t : public vertex_shader_t
{
ID3D11InputLayout* layout();
Microsoft::WRL::ComPtr<ID3D11InputLayout> layout_;
uint32_t layout_index;
};
struct pixel_shader_t
{
ID3D11PixelShader* shader();
std::string_view resource_name;
Microsoft::WRL::ComPtr<ID3D11PixelShader> shader_;
};
struct sampler_state_t
{
ID3D11SamplerState* state();
Noesis::SamplerState params;
Microsoft::WRL::ComPtr<ID3D11SamplerState> state_;
};
struct vertex_and_pixel_program_t
{
int8_t vertex_shader_index;
int8_t pixel_shader_index;
};
static Microsoft::WRL::ComPtr<ID3D11InputLayout> create_layout(uint32_t format, std::string_view vertex_resource_name);
void create_buffers();
void create_state_objects();
void create_shaders();
void clear_textures();
void set_shaders(const Noesis::Batch& batch);
void set_buffers(const Noesis::Batch& batch);
void set_render_state(const Noesis::Batch& batch);
void set_textures(const Noesis::Batch& batch);
Noesis::DeviceCaps caps;
// Device
std::array<ID3D11ShaderResourceView*, static_cast<size_t>(texture_slot_t::Count)> null_textures;
#ifdef _DEBUG
std::shared_ptr<ff::texture> empty_texture_rgb;
std::shared_ptr<ff::texture> empty_texture_palette;
#endif
// Buffers
std::shared_ptr<ff_dx::buffer> buffer_vertices;
std::shared_ptr<ff_dx::buffer> buffer_indices;
std::shared_ptr<ff_dx::buffer> buffer_vertex_cb[2];
std::shared_ptr<ff_dx::buffer> buffer_pixel_cb[3];
uint32_t vertex_cb_hash[2];
uint32_t pixel_cb_hash[3];
// Shaders
vertex_and_pixel_program_t programs[Noesis::Shader::Count];
vertex_shader_and_layout_t vertex_stages[21];
pixel_shader_t pixel_shaders[52];
pixel_shader_t resolve_ps[static_cast<size_t>(msaa_samples_t::Count) - 1];
vertex_shader_t quad_vs;
// State
Microsoft::WRL::ComPtr<ID3D11RasterizerState> rasterizer_states[2];
Microsoft::WRL::ComPtr<ID3D11RasterizerState> rasterizer_state_scissor;
Microsoft::WRL::ComPtr<ID3D11BlendState> blend_states[6];
Microsoft::WRL::ComPtr<ID3D11BlendState> blend_state_no_color;
Microsoft::WRL::ComPtr<ID3D11DepthStencilState> depth_stencil_states[5];
sampler_state_t sampler_states[64];
};
}
#endif
| 39.570248 | 195 | 0.678363 |
fa47574f5c1028d8bda89b230eb57aa1622b57ab | 2,492 | c | C | test/test_pointers.c | chapman-cs510-2017f/cw-10-krista-atabak | e2d7e632b748cbcbedc8ed96d9954246bbe55073 | [
"MIT"
] | null | null | null | test/test_pointers.c | chapman-cs510-2017f/cw-10-krista-atabak | e2d7e632b748cbcbedc8ed96d9954246bbe55073 | [
"MIT"
] | null | null | null | test/test_pointers.c | chapman-cs510-2017f/cw-10-krista-atabak | e2d7e632b748cbcbedc8ed96d9954246bbe55073 | [
"MIT"
] | null | null | null | #include <stdio.h>
#include <math.h>
#include "minunit.h"
#include "../src/structs/structs.h"
/* It is unwise to compare the equality of floats
* As such, one defines a tolerance EPSILON that indicates
* the smallest deviation between two floats that one will accept
* before declaring the floats unequal
*/
#define EPSILON 1e-15
/* Note: structure of test file taken from minunit example at
* http://www.jera.com/techinfo/jtns/jtn002.html
*/
// Needed for minunit to function properly
int tests_run = 0;
/* Check equality between COMP values
* The size of the absolute value of the difference indicates equality
*/
int is_equal(COMP x, COMP y) {
return fabs(x - y) < EPSILON;
}
/* Notice return type of a string (i.e., char *)
* The default value is 0, which is an empty (null) string
* If the test fails, it replaces this return with an error string
*/
static char * test_pass_by_value() {
/* This uses the macro defined in minunit.h
* which performs the Boolean test, and returns the error
* message string if it fails
*/
COMP x = 0, y = 0, z = 0;
VEC3 v = {x, y, z};
VEC3 w = modifyVec3(v, 15.0);
mu_assert("error, v.x != 0.0", is_equal(v.x, x));
mu_assert("error, v.y != 0.0", is_equal(v.y, y));
mu_assert("error, v.z != 0.0", is_equal(v.z, z));
mu_assert("error, w.x != 15.0", is_equal(w.x, 15.0));
return 0;
}
static char * test_pass_by_reference() {
COMP x = 0, y = 0;
VEC2 v = {x, y};
setVec2(&v, 15.0, 10.0);
mu_assert("error, v.x != 0.0", is_equal(v.x, 15));
mu_assert("error, v.y != 0.0", is_equal(v.y, 10));
return 0;
}
/* all_tests collects a set of tests defined above, and runs them
*/
static char * all_tests() {
mu_run_test(test_pass_by_value);
mu_run_test(test_pass_by_reference);
return 0;
}
/* A test file should be executable, so has a main function
* Note that it runs all the tests above, and prints output accordingly
*/
int main(int argc, char **argv) {
// String to store all test results
char *result = all_tests();
// If the result is not null, there is at least one error
if (result != 0) {
// print the errors
printf("%s\n", result);
}
else {
// or inform user that tests passed
printf("ALL TESTS PASSED\n");
}
// Show count of run tests
printf("Tests run: %d\n", tests_run);
// The return code is the boolean of whether all tests passed
return result != 0;
}
| 29.666667 | 71 | 0.640048 |
3222a62b55a00d4b0ca38d92b95e3468dde5224c | 2,043 | h | C | TBSpringboard/SpringBoard/TBCollectionViewFlowLayout.h | TimBao/TBSpringBoard | b5a78421ea954998e3c6c65a1dfcac7ca1889c48 | [
"Apache-2.0"
] | 16 | 2016-01-05T07:00:11.000Z | 2021-02-23T10:23:37.000Z | TBSpringboard/SpringBoard/TBCollectionViewFlowLayout.h | TimBao/TBSpringBoard | b5a78421ea954998e3c6c65a1dfcac7ca1889c48 | [
"Apache-2.0"
] | null | null | null | TBSpringboard/SpringBoard/TBCollectionViewFlowLayout.h | TimBao/TBSpringBoard | b5a78421ea954998e3c6c65a1dfcac7ca1889c48 | [
"Apache-2.0"
] | 3 | 2016-03-19T03:15:53.000Z | 2016-12-09T01:39:45.000Z | //
// TBCollectionViewHelper.h
// TBSpringboard
//
// Created by baotim on 16/1/5.
// Copyright © 2016年 tbao. All rights reserved.
//
#import <UIKit/UIKit.h>
@protocol TBCollectionViewFlowLayoutDataSource <UICollectionViewDataSource>
@optional
/**
* Can indexPath in collectionView be moved.
*
* @param collectionView desktop or folder
* @param indexPath
*/
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemAtIndexPath:(NSIndexPath *)indexPath;
/**
* Can move fromIndexPath in collectionView to the destination indexPath.
*
* @param collectionView desktop or folder
* @param fromIndexPath source IndexPath
* @param toIndexPath destination IndexPath
*/
- (BOOL)collectionView:(UICollectionView *)collectionView canMoveItemFromIndexPath:(NSIndexPath *)fromIndexPath
toIndexPath:(NSIndexPath *)toIndexPath;
/**
* You can do some animation or preview the move result.
*
* @param collectionView desktop or folder
* @param fromIndexPath source IndexPath
* @param toIndexPath destination IndexPath
*/
- (void)collectionView:(UICollectionView *)collectionView willMoveItemFromIndexPath:(NSIndexPath *)fromIndexPath
toIndexPath:(NSIndexPath *)toIndexPath;
/**
* Move fromIndexPath item into another item or folder which indexPath is intoIndexPath.
*
* @param collectionView desktop
* @param fromIndexPath
* @param intoIndexPath
*/
- (void)collectionView:(UICollectionView *)collectionView didMoveItemFromIndexPath:(NSIndexPath *)fromIndexPath intoIndexPath:(NSIndexPath *)intoIndexPath;
/**
* Will move item out of folder view.
*
* @param collectionView folder view
* @param indexPath indexPath in forlder view.
*/
- (void)collectionView:(UICollectionView *)collectionView willMoveItemAtIndexPathOutofEdge:(NSIndexPath *)indexPath;
@end
@interface TBCollectionViewFlowLayout : UICollectionViewFlowLayout
@property (nonatomic, strong) UICollectionView *desktopView;
@property (nonatomic, strong) UICollectionView *folderView;
@end
| 30.044118 | 155 | 0.761136 |
c59b72a4f0b0cc9e09af962994d0e6f4fabb9165 | 56,869 | h | C | hybridse/src/vm/runner.h | Kanekanekane/OpenMLDB | 301114cdfd652233352fa814c4d529bd953ab7ae | [
"Apache-2.0"
] | null | null | null | hybridse/src/vm/runner.h | Kanekanekane/OpenMLDB | 301114cdfd652233352fa814c4d529bd953ab7ae | [
"Apache-2.0"
] | 8 | 2021-05-20T05:04:46.000Z | 2021-10-02T14:55:11.000Z | hybridse/src/vm/runner.h | Kanekanekane/OpenMLDB | 301114cdfd652233352fa814c4d529bd953ab7ae | [
"Apache-2.0"
] | 1 | 2021-05-24T07:24:55.000Z | 2021-05-24T07:24:55.000Z | /*
* Copyright 2021 4Paradigm
*
* 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 HYBRIDSE_SRC_VM_RUNNER_H_
#define HYBRIDSE_SRC_VM_RUNNER_H_
#include <map>
#include <memory>
#include <set>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "base/fe_status.h"
#include "codec/fe_row_codec.h"
#include "node/node_manager.h"
#include "vm/catalog.h"
#include "vm/catalog_wrapper.h"
#include "vm/core_api.h"
#include "vm/mem_catalog.h"
#include "vm/physical_op.h"
namespace hybridse {
namespace vm {
using base::Status;
using codec::Row;
using codec::RowView;
using vm::DataHandler;
using vm::PartitionHandler;
using vm::Schema;
using vm::TableHandler;
using vm::Window;
class Runner;
class RunnerContext;
class FnGenerator {
public:
explicit FnGenerator(const FnInfo& info)
: fn_(info.fn_ptr()),
fn_schema_(*info.fn_schema()),
row_view_(fn_schema_) {
for (int32_t idx = 0; idx < fn_schema_.size(); idx++) {
idxs_.push_back(idx);
}
}
virtual ~FnGenerator() {}
inline const bool Valid() const { return nullptr != fn_; }
const int8_t* fn_;
const Schema fn_schema_;
const RowView row_view_;
std::vector<int32_t> idxs_;
};
class RowProjectFun : public ProjectFun {
public:
explicit RowProjectFun(const int8_t* fn) : ProjectFun(), fn_(fn) {}
~RowProjectFun() {}
Row operator()(const Row& row, const Row& parameter) const override {
return CoreAPI::RowProject(fn_, row, parameter, false);
}
const int8_t* fn_;
};
class ProjectGenerator : public FnGenerator {
public:
explicit ProjectGenerator(const FnInfo& info)
: FnGenerator(info), fun_(info.fn_ptr()) {}
virtual ~ProjectGenerator() {}
const Row Gen(const Row& row, const Row& parameter);
RowProjectFun fun_;
};
class ConstProjectGenerator : public FnGenerator {
public:
explicit ConstProjectGenerator(const FnInfo& info)
: FnGenerator(info), fun_(info.fn_ptr()) {}
virtual ~ConstProjectGenerator() {}
const Row Gen(const Row& parameter);
RowProjectFun fun_;
};
class AggGenerator : public FnGenerator {
public:
explicit AggGenerator(const FnInfo& info) : FnGenerator(info) {}
virtual ~AggGenerator() {}
const Row Gen(const codec::Row& parameter_row, std::shared_ptr<TableHandler> table);
};
class WindowProjectGenerator : public FnGenerator {
public:
explicit WindowProjectGenerator(const FnInfo& info) : FnGenerator(info) {}
virtual ~WindowProjectGenerator() {}
const Row Gen(const uint64_t key, const Row row, const codec::Row& parameter_row, const bool is_instance,
size_t append_slices, Window* window);
};
class KeyGenerator : public FnGenerator {
public:
explicit KeyGenerator(const FnInfo& info) : FnGenerator(info) {}
virtual ~KeyGenerator() {}
const std::string Gen(const Row& row, const Row& parameter);
const std::string GenConst(const Row& parameter);
};
class OrderGenerator : public FnGenerator {
public:
explicit OrderGenerator(const FnInfo& info) : FnGenerator(info) {}
virtual ~OrderGenerator() {}
const int64_t Gen(const Row& row);
};
class ConditionGenerator : public FnGenerator {
public:
explicit ConditionGenerator(const FnInfo& info) : FnGenerator(info) {}
virtual ~ConditionGenerator() {}
const bool Gen(const Row& row, const Row& parameter) const;
};
class RangeGenerator {
public:
explicit RangeGenerator(const Range& range)
: ts_gen_(range.fn_info()), window_range_() {
if (range.frame_ != nullptr) {
switch (range.frame()->frame_type()) {
case node::kFrameRows:
window_range_.frame_type_ =
Window::WindowFrameType::kFrameRows;
break;
case node::kFrameRowsRange:
window_range_.frame_type_ =
Window::WindowFrameType::kFrameRowsRange;
break;
case node::kFrameRowsMergeRowsRange:
window_range_.frame_type_ =
Window::WindowFrameType::kFrameRowsMergeRowsRange;
default: {
window_range_.frame_type_ =
Window::WindowFrameType::kFrameRowsMergeRowsRange;
break;
}
}
window_range_.start_offset_ = range.frame_->GetHistoryRangeStart();
window_range_.end_offset_ = range.frame_->GetHistoryRangeEnd();
window_range_.start_row_ =
(-1 * range.frame_->GetHistoryRowsStart());
window_range_.end_row_ = (-1 * range.frame_->GetHistoryRowsEnd());
window_range_.max_size_ = range.frame_->frame_maxsize();
}
}
virtual ~RangeGenerator() {}
const bool Valid() const { return ts_gen_.Valid(); }
OrderGenerator ts_gen_;
WindowRange window_range_;
};
class FilterKeyGenerator {
public:
explicit FilterKeyGenerator(const Key& filter_key)
: filter_key_(filter_key.fn_info()) {}
virtual ~FilterKeyGenerator() {}
const bool Valid() const { return filter_key_.Valid(); }
std::shared_ptr<TableHandler> Filter(const Row& parameter, std::shared_ptr<TableHandler> table,
const std::string& request_keys) {
if (!filter_key_.Valid()) {
return table;
}
auto mem_table =
std::shared_ptr<MemTimeTableHandler>(new MemTimeTableHandler());
mem_table->SetOrderType(table->GetOrderType());
auto iter = table->GetIterator();
if (iter) {
iter->SeekToFirst();
while (iter->Valid()) {
std::string keys = filter_key_.Gen(iter->GetValue(), parameter);
if (request_keys == keys) {
mem_table->AddRow(iter->GetKey(), iter->GetValue());
}
iter->Next();
}
}
return mem_table;
}
const std::string GetKey(const Row& row, const Row& parameter) {
return filter_key_.Valid() ? filter_key_.Gen(row, parameter) : "";
}
KeyGenerator filter_key_;
};
class PartitionGenerator {
public:
explicit PartitionGenerator(const Key& partition)
: key_gen_(partition.fn_info()) {}
virtual ~PartitionGenerator() {}
const bool Valid() const { return key_gen_.Valid(); }
std::shared_ptr<PartitionHandler> Partition(
std::shared_ptr<DataHandler> input, const Row& parameter);
std::shared_ptr<PartitionHandler> Partition(
std::shared_ptr<PartitionHandler> table, const Row& parameter);
std::shared_ptr<PartitionHandler> Partition(
std::shared_ptr<TableHandler> table, const Row& parameter);
const std::string GetKey(const Row& row, const Row& parameter) { return key_gen_.Gen(row, parameter); }
private:
KeyGenerator key_gen_;
};
class SortGenerator {
public:
explicit SortGenerator(const Sort& sort)
: is_valid_(sort.ValidSort()),
is_asc_(sort.is_asc()),
order_gen_(sort.fn_info()) {}
virtual ~SortGenerator() {}
const bool Valid() const { return is_valid_; }
std::shared_ptr<DataHandler> Sort(std::shared_ptr<DataHandler> input,
const bool reverse = false);
std::shared_ptr<PartitionHandler> Sort(
std::shared_ptr<PartitionHandler> partition,
const bool reverse = false);
std::shared_ptr<TableHandler> Sort(std::shared_ptr<TableHandler> table,
const bool reverse = false);
const OrderGenerator& order_gen() const { return order_gen_; }
private:
bool is_valid_;
bool is_asc_;
OrderGenerator order_gen_;
};
class IndexSeekGenerator {
public:
explicit IndexSeekGenerator(const Key& key)
: index_key_gen_(key.fn_info()) {}
virtual ~IndexSeekGenerator() {}
std::shared_ptr<TableHandler> SegmnetOfConstKey(
const Row& parameter,
std::shared_ptr<DataHandler> input);
std::shared_ptr<TableHandler> SegmentOfKey(
const Row& row, const Row& parameter, std::shared_ptr<DataHandler> input);
const bool Valid() const { return index_key_gen_.Valid(); }
private:
KeyGenerator index_key_gen_;
};
class FilterGenerator : public PredicateFun {
public:
explicit FilterGenerator(const Filter& filter)
: condition_gen_(filter.condition_.fn_info()),
index_seek_gen_(filter.index_key_) {}
const bool Valid() const {
return index_seek_gen_.Valid() || condition_gen_.Valid();
}
std::shared_ptr<DataHandler> Filter(std::shared_ptr<TableHandler> table,
const Row& parameter);
std::shared_ptr<DataHandler> Filter(
std::shared_ptr<PartitionHandler> table, const Row& parameter);
bool operator()(const Row& row, const Row& parameter) const override {
if (!condition_gen_.Valid()) {
return true;
}
return condition_gen_.Gen(row, parameter);
}
private:
ConditionGenerator condition_gen_;
IndexSeekGenerator index_seek_gen_;
};
class WindowGenerator {
public:
explicit WindowGenerator(const WindowOp& window)
: window_op_(window),
partition_gen_(window.partition_),
sort_gen_(window.sort_),
range_gen_(window.range_) {}
virtual ~WindowGenerator() {}
const int64_t OrderKey(const Row& row) {
return range_gen_.ts_gen_.Gen(row);
}
const WindowOp window_op_;
PartitionGenerator partition_gen_;
SortGenerator sort_gen_;
RangeGenerator range_gen_;
};
class RequestWindowGenertor {
public:
explicit RequestWindowGenertor(const RequestWindowOp& window)
: window_op_(window),
filter_gen_(window.partition_),
sort_gen_(window.sort_),
range_gen_(window.range_.fn_info()),
index_seek_gen_(window.index_key_) {}
virtual ~RequestWindowGenertor() {}
std::shared_ptr<TableHandler> GetRequestWindow(
const Row& row, const Row& parameter, std::shared_ptr<DataHandler> input) {
auto segment = index_seek_gen_.SegmentOfKey(row, parameter, input);
if (filter_gen_.Valid()) {
auto filter_key = filter_gen_.GetKey(row, parameter);
segment = filter_gen_.Filter(parameter, segment, filter_key);
}
if (sort_gen_.Valid()) {
segment = sort_gen_.Sort(segment, true);
}
return segment;
}
RequestWindowOp window_op_;
FilterKeyGenerator filter_gen_;
SortGenerator sort_gen_;
OrderGenerator range_gen_;
IndexSeekGenerator index_seek_gen_;
}; // namespace vm
enum RunnerType {
kRunnerData,
kRunnerRequest,
kRunnerGroup,
kRunnerFilter,
kRunnerOrder,
kRunnerGroupAndSort,
kRunnerConstProject,
kRunnerTableProject,
kRunnerRowProject,
kRunnerSimpleProject,
kRunnerSelectSlice,
kRunnerGroupAgg,
kRunnerAgg,
kRunnerWindowAgg,
kRunnerRequestUnion,
kRunnerPostRequestUnion,
kRunnerIndexSeek,
kRunnerLastJoin,
kRunnerConcat,
kRunnerRequestRunProxy,
kRunnerRequestLastJoin,
kRunnerBatchRequestRunProxy,
kRunnerLimit,
kRunnerUnknow,
};
inline const std::string RunnerTypeName(const RunnerType& type) {
switch (type) {
case kRunnerData:
return "DATA";
case kRunnerRequest:
return "REQUEST";
case kRunnerGroup:
return "GROUP";
case kRunnerGroupAndSort:
return "GROUP_AND_SORT";
case kRunnerFilter:
return "FILTER";
case kRunnerConstProject:
return "CONST_PROJECT";
case kRunnerTableProject:
return "TABLE_PROJECT";
case kRunnerRowProject:
return "ROW_PROJECT";
case kRunnerSimpleProject:
return "SIMPLE_PROJECT";
case kRunnerSelectSlice:
return "SELECT_SLICE";
case kRunnerGroupAgg:
return "GROUP_AGG_PROJECT";
case kRunnerAgg:
return "AGG_PROJECT";
case kRunnerWindowAgg:
return "WINDOW_AGG_PROJECT";
case kRunnerRequestUnion:
return "REQUEST_UNION";
case kRunnerPostRequestUnion:
return "POST_REQUEST_UNION";
case kRunnerIndexSeek:
return "INDEX_SEEK";
case kRunnerLastJoin:
return "LASTJOIN";
case kRunnerConcat:
return "CONCAT";
case kRunnerRequestLastJoin:
return "REQUEST_LASTJOIN";
case kRunnerLimit:
return "LIMIT";
case kRunnerRequestRunProxy:
return "REQUEST_RUN_PROXY";
case kRunnerBatchRequestRunProxy:
return "BATCH_REQUEST_RUN_PROXY";
default:
return "UNKNOW";
}
}
class Runner : public node::NodeBase<Runner> {
public:
explicit Runner(const int32_t id)
: id_(id),
type_(kRunnerUnknow),
limit_cnt_(0),
is_lazy_(false),
need_cache_(false),
need_batch_cache_(false),
producers_(),
output_schemas_() {}
Runner(const int32_t id, const RunnerType type,
const vm::SchemasContext* output_schemas)
: id_(id),
type_(type),
limit_cnt_(0),
is_lazy_(false),
need_cache_(false),
need_batch_cache_(false),
producers_(),
output_schemas_(output_schemas) {}
Runner(const int32_t id, const RunnerType type,
const vm::SchemasContext* output_schemas, const int32_t limit_cnt)
: id_(id),
type_(type),
limit_cnt_(limit_cnt),
is_lazy_(false),
need_cache_(false),
need_batch_cache_(false),
producers_(),
output_schemas_(output_schemas) {}
virtual ~Runner() {}
void AddProducer(Runner* runner) { producers_.push_back(runner); }
bool SetProducer(size_t idx, Runner* runner) {
if (idx >= producers_.size()) {
return false;
}
producers_[idx] = runner;
return true;
}
const std::vector<Runner*>& GetProducers() const { return producers_; }
virtual void PrintRunnerInfo(std::ostream& output,
const std::string& tab) const {
output << tab << "[" << id_ << "]" << RunnerTypeName(type_);
if (is_lazy_) {
output << " lazy";
}
}
virtual void Print(std::ostream& output, const std::string& tab,
std::set<int32_t>* visited_ids) const { // NOLINT
PrintRunnerInfo(output, tab);
PrintCacheInfo(output);
if (nullptr != visited_ids &&
visited_ids->find(id_) != visited_ids->cend()) {
output << "\n";
output << " " << tab << "...";
return;
}
if (nullptr != visited_ids) {
visited_ids->insert(id_);
}
if (!producers_.empty()) {
for (auto producer : producers_) {
output << "\n";
producer->Print(output, " " + tab, visited_ids);
}
}
}
const bool need_cache() { return need_cache_; }
const bool need_batch_cache() { return need_batch_cache_; }
void EnableCache() { need_cache_ = true; }
void DisableCache() { need_cache_ = false; }
void EnableBatchCache() { need_batch_cache_ = true; }
void DisableBatchCache() { need_batch_cache_ = false; }
const int32_t id_;
const RunnerType type_;
const int32_t limit_cnt_;
virtual std::shared_ptr<DataHandler> Run(
RunnerContext& ctx, // NOLINT
const std::vector<std::shared_ptr<DataHandler>>& inputs) = 0;
virtual std::shared_ptr<DataHandlerList> BatchRequestRun(
RunnerContext& ctx); // NOLINT
virtual std::shared_ptr<DataHandler> RunWithCache(
RunnerContext& ctx); // NOLINT
static int64_t GetColumnInt64(const int8_t* buf, const RowView* view,
int pos, type::Type type);
static bool GetColumnBool(const int8_t* buf, const RowView* view, int idx,
type::Type type);
static Row RowConstProject(
const int8_t* fn, const bool need_free = false);
static Row RowProject(const int8_t* fn, const hybridse::codec::Row& row, const hybridse::codec::Row& parameter,
const bool need_free);
static Row WindowProject(const int8_t* fn, const uint64_t key,
const Row row, const Row& parameter,
const bool is_instance,
size_t append_slices, Window* window);
static Row GroupbyProject(const int8_t* fn, const Row& parameter, TableHandler* table);
static const Row RowLastJoinTable(size_t left_slices, const Row& left_row,
size_t right_slices,
std::shared_ptr<TableHandler> right_table,
const hybridse::codec::Row& parameter,
SortGenerator& right_sort, // NOLINT
ConditionGenerator& filter); // NOLINT
static std::shared_ptr<TableHandler> TableReverse(
std::shared_ptr<TableHandler> table);
static void PrintData(std::ostringstream& oss,
const vm::SchemasContext* schema_list,
std::shared_ptr<DataHandler> data);
static const bool IsProxyRunner(const RunnerType& type) {
return kRunnerRequestRunProxy == type ||
kRunnerBatchRequestRunProxy == type;
}
static bool ExtractRows(std::shared_ptr<DataHandlerList> handlers,
std::vector<Row>& out_rows); // NOLINT
static bool ExtractRow(std::shared_ptr<DataHandler> handler,
Row* out_row); // NOLINT
static bool ExtractRows(std::shared_ptr<DataHandler> handler,
std::vector<Row>& out_rows); // NOLINT
const vm::SchemasContext* output_schemas() const { return output_schemas_; }
void set_output_schemas(const vm::SchemasContext* schemas) {
output_schemas_ = schemas;
}
virtual const std::string GetTypeName() const {
return RunnerTypeName(type_);
}
virtual bool Equals(const Runner* other) const { return this == other; }
protected:
bool is_lazy_;
void PrintCacheInfo(std::ostream& output) const {
if (need_cache_ && need_batch_cache_) {
output << " (cache_enable, batch_common)";
} else if (need_cache_) {
output << " (cache_enable)";
} else if (need_batch_cache_) {
output << " (batch_common)";
}
}
bool need_cache_;
bool need_batch_cache_;
std::vector<Runner*> producers_;
const vm::SchemasContext* output_schemas_;
};
class IteratorStatus {
public:
IteratorStatus() : is_valid_(false), key_(0) {}
explicit IteratorStatus(uint64_t key) : is_valid_(true), key_(key) {}
virtual ~IteratorStatus() {}
static int32_t PickIteratorWithMininumKey(
std::vector<IteratorStatus>* status_list_ptr);
static int32_t PickIteratorWithMaximizeKey(
std::vector<IteratorStatus>* status_list_ptr);
void MarkInValid() {
is_valid_ = false;
key_ = 0;
}
void set_key(uint64_t key) { key_ = key; }
bool is_valid_;
uint64_t key_;
}; // namespace vm
class InputsGenerator {
public:
InputsGenerator() : inputs_cnt_(0), input_runners_() {}
virtual ~InputsGenerator() {}
std::vector<std::shared_ptr<DataHandler>> RunInputs(
RunnerContext& ctx); // NOLINT
const bool Valid() const { return 0 != inputs_cnt_; }
void AddInput(Runner* runner) {
input_runners_.push_back(runner);
inputs_cnt_++;
}
size_t inputs_cnt_;
std::vector<Runner*> input_runners_;
};
class WindowUnionGenerator : public InputsGenerator {
public:
WindowUnionGenerator() : InputsGenerator() {}
virtual ~WindowUnionGenerator() {}
std::vector<std::shared_ptr<PartitionHandler>> PartitionEach(
std::vector<std::shared_ptr<DataHandler>> union_inputs,
const Row& parameter);
void AddWindowUnion(const WindowOp& window_op, Runner* runner) {
windows_gen_.push_back(WindowGenerator(window_op));
AddInput(runner);
}
std::vector<WindowGenerator> windows_gen_;
};
class RequestWindowUnionGenerator : public InputsGenerator {
public:
RequestWindowUnionGenerator() : InputsGenerator() {}
virtual ~RequestWindowUnionGenerator() {}
std::vector<std::shared_ptr<PartitionHandler>> PartitionEach(
std::vector<std::shared_ptr<DataHandler>> union_inputs);
void AddWindowUnion(const RequestWindowOp& window_op, Runner* runner) {
windows_gen_.push_back(RequestWindowGenertor(window_op));
AddInput(runner);
}
std::vector<std::shared_ptr<TableHandler>> GetRequestWindows(
const Row& row, const Row& parameter,
std::vector<std::shared_ptr<DataHandler>> union_inputs) {
std::vector<std::shared_ptr<TableHandler>> union_segments(inputs_cnt_);
if (!windows_gen_.empty()) {
for (size_t i = 0; i < inputs_cnt_; i++) {
union_segments[i] =
windows_gen_[i].GetRequestWindow(row, parameter, union_inputs[i]);
}
}
return union_segments;
}
std::vector<RequestWindowGenertor> windows_gen_;
};
class JoinGenerator {
public:
explicit JoinGenerator(const Join& join, size_t left_slices,
size_t right_slices)
: condition_gen_(join.condition_.fn_info()),
left_key_gen_(join.left_key_.fn_info()),
right_group_gen_(join.right_key_),
index_key_gen_(join.index_key_.fn_info()),
right_sort_gen_(join.right_sort_),
left_slices_(left_slices),
right_slices_(right_slices) {}
virtual ~JoinGenerator() {}
bool TableJoin(std::shared_ptr<TableHandler> left, std::shared_ptr<TableHandler> right,
const Row& parameter,
std::shared_ptr<MemTimeTableHandler> output); // NOLINT
bool TableJoin(std::shared_ptr<TableHandler> left, std::shared_ptr<PartitionHandler> right,
const Row& parameter,
std::shared_ptr<MemTimeTableHandler> output); // NOLINT
bool PartitionJoin(std::shared_ptr<PartitionHandler> left,
std::shared_ptr<TableHandler> right,
const Row& parameter,
std::shared_ptr<MemPartitionHandler> output); // NOLINT
bool PartitionJoin(std::shared_ptr<PartitionHandler> left,
std::shared_ptr<PartitionHandler> right,
const Row& parameter,
std::shared_ptr<MemPartitionHandler>); // NOLINT
Row RowLastJoin(const Row& left_row, std::shared_ptr<DataHandler> right, const Row& parameter);
Row RowLastJoinDropLeftSlices(const Row& left_row, std::shared_ptr<DataHandler> right, const Row& parameter);
ConditionGenerator condition_gen_;
KeyGenerator left_key_gen_;
PartitionGenerator right_group_gen_;
KeyGenerator index_key_gen_;
SortGenerator right_sort_gen_;
private:
Row RowLastJoinPartition(
const Row& left_row,
std::shared_ptr<PartitionHandler> partition,
const Row& parameter);
Row RowLastJoinTable(const Row& left_row,
std::shared_ptr<TableHandler> table,
const Row& parameter);
size_t left_slices_;
size_t right_slices_;
};
class WindowJoinGenerator : public InputsGenerator {
public:
WindowJoinGenerator() : InputsGenerator() {}
virtual ~WindowJoinGenerator() {}
void AddWindowJoin(const Join& join, size_t left_slices, Runner* runner) {
size_t right_slices = runner->output_schemas()->GetSchemaSourceSize();
joins_gen_.push_back(JoinGenerator(join, left_slices, right_slices));
AddInput(runner);
}
std::vector<std::shared_ptr<DataHandler>> RunInputs(
RunnerContext& ctx); // NOLINT
Row Join(
const Row& left_row,
const std::vector<std::shared_ptr<DataHandler>>& join_right_tables,
const Row& parameter);
std::vector<JoinGenerator> joins_gen_;
};
class DataRunner : public Runner {
public:
DataRunner(const int32_t id, const SchemasContext* schema,
std::shared_ptr<DataHandler> data_hander)
: Runner(id, kRunnerData, schema), data_handler_(data_hander) {}
~DataRunner() {}
virtual std::shared_ptr<DataHandler> Run(
RunnerContext& ctx, // NOLINT
const std::vector<std::shared_ptr<DataHandler>>& inputs);
std::shared_ptr<DataHandlerList> BatchRequestRun(
RunnerContext& ctx) override; // NOLINT
const std::shared_ptr<DataHandler> data_handler_;
};
class RequestRunner : public Runner {
public:
RequestRunner(const int32_t id, const SchemasContext* schema)
: Runner(id, kRunnerRequest, schema) {}
~RequestRunner() {}
virtual std::shared_ptr<DataHandler> Run(
RunnerContext& ctx, // NOLINT
const std::vector<std::shared_ptr<DataHandler>>& inputs);
std::shared_ptr<DataHandlerList> BatchRequestRun(
RunnerContext& ctx); // NOLINT
};
class GroupRunner : public Runner {
public:
GroupRunner(const int32_t id, const SchemasContext* schema,
const int32_t limit_cnt, const Key& group)
: Runner(id, kRunnerGroup, schema, limit_cnt), partition_gen_(group) {}
~GroupRunner() {}
std::shared_ptr<DataHandler> Run(
RunnerContext& ctx, // NOLINT
const std::vector<std::shared_ptr<DataHandler>>& inputs)
override; // NOLINT
PartitionGenerator partition_gen_;
};
class FilterRunner : public Runner {
public:
FilterRunner(const int32_t id, const SchemasContext* schema,
const int32_t limit_cnt, const Filter& filter)
: Runner(id, kRunnerFilter, schema, limit_cnt), filter_gen_(filter) {
is_lazy_ = true;
}
~FilterRunner() {}
std::shared_ptr<DataHandler> Run(
RunnerContext& ctx, // NOLINT
const std::vector<std::shared_ptr<DataHandler>>& inputs)
override; // NOLINT
FilterGenerator filter_gen_;
};
class SortRunner : public Runner {
public:
SortRunner(const int32_t id, const SchemasContext* schema,
const int32_t limit_cnt, const Sort& sort)
: Runner(id, kRunnerOrder, schema, limit_cnt), sort_gen_(sort) {}
~SortRunner() {}
std::shared_ptr<DataHandler> Run(
RunnerContext& ctx, // NOLINT
const std::vector<std::shared_ptr<DataHandler>>& inputs)
override; // NOLINT
SortGenerator sort_gen_;
};
class ConstProjectRunner : public Runner {
public:
ConstProjectRunner(const int32_t id, const SchemasContext* schema,
const int32_t limit_cnt, const FnInfo& fn_info)
: Runner(id, kRunnerConstProject, schema, limit_cnt),
project_gen_(fn_info) {}
~ConstProjectRunner() {}
std::shared_ptr<DataHandler> Run(
RunnerContext& ctx, // NOLINT
const std::vector<std::shared_ptr<DataHandler>>& inputs)
override; // NOLINT
ConstProjectGenerator project_gen_;
};
class TableProjectRunner : public Runner {
public:
TableProjectRunner(const int32_t id, const SchemasContext* schema,
const int32_t limit_cnt, const FnInfo& fn_info)
: Runner(id, kRunnerTableProject, schema, limit_cnt),
project_gen_(fn_info) {}
~TableProjectRunner() {}
std::shared_ptr<DataHandler> Run(
RunnerContext& ctx, // NOLINT
const std::vector<std::shared_ptr<DataHandler>>& inputs)
override; // NOLINT
ProjectGenerator project_gen_;
};
class RowProjectRunner : public Runner {
public:
RowProjectRunner(const int32_t id, const SchemasContext* schema,
const int32_t limit_cnt, const FnInfo& fn_info)
: Runner(id, kRunnerRowProject, schema, limit_cnt),
project_gen_(fn_info) {}
~RowProjectRunner() {}
std::shared_ptr<DataHandler> Run(
RunnerContext& ctx, // NOLINT
const std::vector<std::shared_ptr<DataHandler>>& inputs)
override; // NOLINT
ProjectGenerator project_gen_;
};
class SimpleProjectRunner : public Runner {
public:
SimpleProjectRunner(const int32_t id, const SchemasContext* schema,
const int32_t limit_cnt, const FnInfo& fn_info)
: Runner(id, kRunnerSimpleProject, schema, limit_cnt),
project_gen_(fn_info) {
is_lazy_ = true;
}
SimpleProjectRunner(const int32_t id, const SchemasContext* schema,
const int32_t limit_cnt,
const ProjectGenerator& project_gen)
: Runner(id, kRunnerSimpleProject, schema, limit_cnt),
project_gen_(project_gen) {
is_lazy_ = true;
}
~SimpleProjectRunner() {}
std::shared_ptr<DataHandler> Run(
RunnerContext& ctx, // NOLINT
const std::vector<std::shared_ptr<DataHandler>>& inputs)
override; // NOLINT
ProjectGenerator project_gen_;
};
class SelectSliceRunner : public Runner {
public:
SelectSliceRunner(const int32_t id, const SchemasContext* schema,
const int32_t limit_cnt, size_t slice)
: Runner(id, kRunnerSelectSlice, schema, limit_cnt),
get_slice_fn_(slice) {
is_lazy_ = true;
}
std::shared_ptr<DataHandler> Run(
RunnerContext& ctx, // NOLINT
const std::vector<std::shared_ptr<DataHandler>>& inputs) override;
size_t slice() const { return get_slice_fn_.slice_; }
private:
struct GetSliceFn : public ProjectFun {
explicit GetSliceFn(size_t slice) : slice_(slice) {}
Row operator()(const Row& row, const Row& parameter) const override;
size_t slice_;
} get_slice_fn_;
};
class GroupAggRunner : public Runner {
public:
GroupAggRunner(const int32_t id, const SchemasContext* schema,
const int32_t limit_cnt, const Key& group,
const FnInfo& project)
: Runner(id, kRunnerGroupAgg, schema, limit_cnt),
group_(group.fn_info()),
agg_gen_(project) {}
~GroupAggRunner() {}
std::shared_ptr<DataHandler> Run(
RunnerContext& ctx, // NOLINT
const std::vector<std::shared_ptr<DataHandler>>& inputs)
override; // NOLINT
KeyGenerator group_;
AggGenerator agg_gen_;
};
class AggRunner : public Runner {
public:
AggRunner(const int32_t id, const SchemasContext* schema,
const int32_t limit_cnt, const FnInfo& fn_info)
: Runner(id, kRunnerAgg, schema, limit_cnt), agg_gen_(fn_info) {}
~AggRunner() {}
std::shared_ptr<DataHandler> Run(
RunnerContext& ctx, // NOLINT
const std::vector<std::shared_ptr<DataHandler>>& inputs)
override; // NOLINT
AggGenerator agg_gen_;
};
class WindowAggRunner : public Runner {
public:
WindowAggRunner(const int32_t id, const SchemasContext* schema,
const int32_t limit_cnt, const WindowOp& window_op,
const FnInfo& fn_info, const bool instance_not_in_window,
const bool exclude_current_time,
const bool need_append_input)
: Runner(id, kRunnerWindowAgg, schema, limit_cnt),
instance_not_in_window_(instance_not_in_window),
exclude_current_time_(exclude_current_time),
need_append_input_(need_append_input),
append_slices_(need_append_input ? schema->GetSchemaSourceSize() : 0),
instance_window_gen_(window_op),
windows_union_gen_(),
windows_join_gen_(),
window_project_gen_(fn_info) {}
~WindowAggRunner() {}
void AddWindowJoin(const Join& join, size_t left_slices, Runner* runner) {
windows_join_gen_.AddWindowJoin(join, left_slices, runner);
}
void AddWindowUnion(const WindowOp& window, Runner* runner) {
windows_union_gen_.AddWindowUnion(window, runner);
}
std::shared_ptr<DataHandler> Run(
RunnerContext& ctx, // NOLINT
const std::vector<std::shared_ptr<DataHandler>>& inputs)
override; // NOLINT
void RunWindowAggOnKey(
const Row& parameter,
std::shared_ptr<PartitionHandler> instance_partition,
std::vector<std::shared_ptr<PartitionHandler>> union_partitions,
std::vector<std::shared_ptr<DataHandler>> joins, const std::string& key,
std::shared_ptr<MemTableHandler> output_table);
const bool instance_not_in_window_;
const bool exclude_current_time_;
const bool need_append_input_;
const size_t append_slices_;
WindowGenerator instance_window_gen_;
WindowUnionGenerator windows_union_gen_;
WindowJoinGenerator windows_join_gen_;
WindowProjectGenerator window_project_gen_;
};
class RequestUnionRunner : public Runner {
public:
RequestUnionRunner(const int32_t id, const SchemasContext* schema,
const int32_t limit_cnt, const Range& range,
bool exclude_current_time, bool output_request_row)
: Runner(id, kRunnerRequestUnion, schema, limit_cnt),
range_gen_(range),
exclude_current_time_(exclude_current_time),
output_request_row_(output_request_row) {}
std::shared_ptr<DataHandler> Run(
RunnerContext& ctx, // NOLINT
const std::vector<std::shared_ptr<DataHandler>>& inputs)
override; // NOLINT
static std::shared_ptr<TableHandler> RequestUnionWindow(
const Row& request,
std::vector<std::shared_ptr<TableHandler>> union_segments,
int64_t request_ts, const WindowRange& window_range,
const bool output_request_row, const bool exclude_current_time);
void AddWindowUnion(const RequestWindowOp& window, Runner* runner) {
windows_union_gen_.AddWindowUnion(window, runner);
}
RequestWindowUnionGenerator windows_union_gen_;
RangeGenerator range_gen_;
bool exclude_current_time_;
bool output_request_row_;
};
class PostRequestUnionRunner : public Runner {
public:
PostRequestUnionRunner(const int32_t id, const SchemasContext* schema,
const Range& request_ts)
: Runner(id, kRunnerPostRequestUnion, schema),
request_ts_gen_(request_ts.fn_info()) {}
std::shared_ptr<DataHandler> Run(
RunnerContext& ctx, // NOLINT
const std::vector<std::shared_ptr<DataHandler>>& inputs)
override; // NOLINT
private:
OrderGenerator request_ts_gen_;
};
class LastJoinRunner : public Runner {
public:
LastJoinRunner(const int32_t id, const SchemasContext* schema,
const int32_t limit_cnt, const Join& join,
size_t left_slices, size_t right_slices)
: Runner(id, kRunnerLastJoin, schema, limit_cnt),
join_gen_(join, left_slices, right_slices) {}
~LastJoinRunner() {}
std::shared_ptr<DataHandler> Run(
RunnerContext& ctx, // NOLINT
const std::vector<std::shared_ptr<DataHandler>>& inputs)
override; // NOLINT
JoinGenerator join_gen_;
};
class RequestLastJoinRunner : public Runner {
public:
RequestLastJoinRunner(const int32_t id, const SchemasContext* schema,
const int32_t limit_cnt, const Join& join,
const size_t left_slices, const size_t right_slices,
const bool output_right_only)
: Runner(id, kRunnerRequestLastJoin, schema, limit_cnt),
join_gen_(join, left_slices, right_slices),
output_right_only_(output_right_only) {}
~RequestLastJoinRunner() {}
std::shared_ptr<DataHandler> Run(
RunnerContext& ctx, // NOLINT
const std::vector<std::shared_ptr<DataHandler>>& inputs); // NOLINT
virtual void PrintRunnerInfo(std::ostream& output,
const std::string& tab) const {
output << tab << "[" << id_ << "]" << RunnerTypeName(type_);
if (is_lazy_) {
output << " lazy";
}
if (output_right_only_) {
output << " OUTPUT_RIGHT_ONLY";
}
}
JoinGenerator join_gen_;
const bool output_right_only_;
};
class ConcatRunner : public Runner {
public:
ConcatRunner(const int32_t id, const SchemasContext* schema,
const int32_t limit_cnt)
: Runner(id, kRunnerConcat, schema, limit_cnt) {
is_lazy_ = true;
}
~ConcatRunner() {}
std::shared_ptr<DataHandler> Run(
RunnerContext& ctx, // NOLINT
const std::vector<std::shared_ptr<DataHandler>>& inputs)
override; // NOLINT
};
class LimitRunner : public Runner {
public:
LimitRunner(int32_t id, const SchemasContext* schema, int32_t limit_cnt)
: Runner(id, kRunnerLimit, schema, limit_cnt) {}
~LimitRunner() {}
std::shared_ptr<DataHandler> Run(
RunnerContext& ctx, // NOLINT
const std::vector<std::shared_ptr<DataHandler>>& inputs); // NOLINT
};
class ProxyRequestRunner : public Runner {
public:
ProxyRequestRunner(int32_t id, uint32_t task_id,
const SchemasContext* schema_ctx)
: Runner(id, kRunnerRequestRunProxy, schema_ctx),
task_id_(task_id),
index_input_(nullptr) {
is_lazy_ = true;
}
ProxyRequestRunner(int32_t id, uint32_t task_id, Runner* index_input,
const SchemasContext* schema_ctx)
: Runner(id, kRunnerRequestRunProxy, schema_ctx),
task_id_(task_id),
index_input_(index_input) {
is_lazy_ = true;
}
~ProxyRequestRunner() {}
std::shared_ptr<DataHandler> Run(
RunnerContext& ctx, // NOLINT
const std::vector<std::shared_ptr<DataHandler>>& inputs) override;
std::shared_ptr<DataHandlerList> BatchRequestRun(
RunnerContext& ctx) override; // NOLINT
virtual void PrintRunnerInfo(std::ostream& output,
const std::string& tab) const {
output << tab << "[" << id_ << "]" << RunnerTypeName(type_)
<< "(TASK_ID=" << task_id_ << ")";
if (is_lazy_) {
output << " lazy";
}
}
virtual void Print(std::ostream& output, const std::string& tab,
std::set<int32_t>* visited_ids) const { // NOLINT
PrintRunnerInfo(output, tab);
PrintCacheInfo(output);
if (nullptr != index_input_) {
output << "\n " << tab << "proxy_index_input:\n";
index_input_->Print(output, " " + tab + "+-", nullptr);
}
if (nullptr != visited_ids &&
visited_ids->find(id_) != visited_ids->cend()) {
output << "\n";
output << " " << tab << "...";
return;
}
if (nullptr != visited_ids) {
visited_ids->insert(id_);
}
if (!producers_.empty()) {
for (auto producer : producers_) {
output << "\n";
producer->Print(output, " " + tab, visited_ids);
}
}
}
const int32_t task_id() const { return task_id_; }
private:
std::shared_ptr<DataHandlerList> RunBatchInput(
RunnerContext& ctx, // NOLINT
std::shared_ptr<DataHandlerList> input,
std::shared_ptr<DataHandlerList> index_input);
std::shared_ptr<DataHandler> RunWithRowInput(RunnerContext& ctx, // NOLINT
const Row& row,
const Row& index_row);
std::shared_ptr<TableHandler> RunWithRowsInput(
RunnerContext& ctx, // NOLINT
const std::vector<Row>& rows, const std::vector<Row>& index_rows,
const bool request_is_common);
uint32_t task_id_;
Runner* index_input_;
};
class ClusterTask;
class RouteInfo {
public:
RouteInfo()
: index_(),
index_key_(),
index_key_input_runner_(nullptr),
input_(),
table_handler_() {}
RouteInfo(const std::string index,
std::shared_ptr<TableHandler> table_handler)
: index_(index),
index_key_(),
index_key_input_runner_(nullptr),
input_(),
table_handler_(table_handler) {}
RouteInfo(const std::string index, const Key& index_key,
std::shared_ptr<ClusterTask> input,
std::shared_ptr<TableHandler> table_handler)
: index_(index),
index_key_(index_key),
index_key_input_runner_(nullptr),
input_(input),
table_handler_(table_handler) {}
~RouteInfo() {}
const bool IsCompleted() const {
return table_handler_ && !index_.empty() && index_key_.ValidKey();
}
const bool IsCluster() const { return table_handler_ && !index_.empty(); }
static const bool EqualWith(const RouteInfo& info1,
const RouteInfo& info2) {
return info1.input_ == info2.input_ &&
info1.table_handler_ == info2.table_handler_ &&
info1.index_ == info2.index_ &&
node::ExprEquals(info1.index_key_.keys_, info2.index_key_.keys_);
}
const std::string ToString() const {
if (IsCompleted()) {
std::ostringstream oss;
oss << ", routing index = " << table_handler_->GetDatabase() << "."
<< table_handler_->GetName() << "." << index_ << ", "
<< index_key_.ToString();
return oss.str();
} else {
return "";
}
}
std::string index_;
Key index_key_;
Runner* index_key_input_runner_;
std::shared_ptr<ClusterTask> input_;
std::shared_ptr<TableHandler> table_handler_;
};
// task info of cluster job
// partitoin/index info
// index key generator
// request generator
class ClusterTask {
public:
ClusterTask() : root_(nullptr), input_runners_(), route_info_() {}
explicit ClusterTask(Runner* root)
: root_(root), input_runners_(), route_info_() {}
ClusterTask(Runner* root, const std::shared_ptr<TableHandler> table_handler,
std::string index)
: root_(root), input_runners_(), route_info_(index, table_handler) {}
ClusterTask(Runner* root, const std::vector<Runner*>& input_runners,
const RouteInfo& route_info)
: root_(root), input_runners_(input_runners), route_info_(route_info) {}
~ClusterTask() {}
void Print(std::ostream& output, const std::string& tab) const {
output << route_info_.ToString() << "\n";
if (nullptr == root_) {
output << tab << "NULL RUNNER\n";
} else {
std::set<int32_t> visited_ids;
root_->Print(output, tab, &visited_ids);
}
}
void ResetInputs(std::shared_ptr<ClusterTask> input) {
for (auto input_runner : input_runners_) {
input_runner->SetProducer(0, route_info_.input_->GetRoot());
}
route_info_.index_key_input_runner_ = route_info_.input_->GetRoot();
route_info_.input_ = input;
}
Runner* GetRoot() const { return root_; }
void SetRoot(Runner* root) { root_ = root; }
Runner* GetInputRunner(size_t idx) const {
return idx >= input_runners_.size() ? nullptr : input_runners_[idx];
}
Runner* GetIndexKeyInput() const {
return route_info_.index_key_input_runner_;
}
std::shared_ptr<ClusterTask> GetInput() const { return route_info_.input_; }
Key GetIndexKey() const { return route_info_.index_key_; }
void SetIndexKey(const Key& key) { route_info_.index_key_ = key; }
void SetInput(std::shared_ptr<ClusterTask> input) {
route_info_.input_ = input;
}
const bool IsValid() const { return nullptr != root_; }
const bool IsCompletedClusterTask() const {
return IsValid() && route_info_.IsCompleted();
}
const bool IsUnCompletedClusterTask() const {
return IsClusterTask() && !route_info_.IsCompleted();
}
const bool IsClusterTask() const { return route_info_.IsCluster(); }
const std::string& index() { return route_info_.index_; }
std::shared_ptr<TableHandler> table_handler() {
return route_info_.table_handler_;
}
// Cluster tasks with same input runners and index keys can be merged
static const bool TaskCanBeMerge(const ClusterTask& task1,
const ClusterTask& task2) {
return RouteInfo::EqualWith(task1.route_info_, task2.route_info_);
}
static const ClusterTask TaskMerge(Runner* root, const ClusterTask& task1,
const ClusterTask& task2) {
return TaskMergeToLeft(root, task1, task2);
}
static const ClusterTask TaskMergeToLeft(Runner* root,
const ClusterTask& task1,
const ClusterTask& task2) {
std::vector<Runner*> input_runners;
for (auto runner : task1.input_runners_) {
input_runners.push_back(runner);
}
for (auto runner : task2.input_runners_) {
input_runners.push_back(runner);
}
return ClusterTask(root, input_runners, task1.route_info_);
}
static const ClusterTask TaskMergeToRight(Runner* root,
const ClusterTask& task1,
const ClusterTask& task2) {
std::vector<Runner*> input_runners;
for (auto runner : task1.input_runners_) {
input_runners.push_back(runner);
}
for (auto runner : task2.input_runners_) {
input_runners.push_back(runner);
}
return ClusterTask(root, input_runners, task2.route_info_);
}
static const Runner* GetRequestInput(const ClusterTask& task) {
if (!task.IsValid()) {
return nullptr;
}
auto input_task = task.GetInput();
if (input_task) {
return input_task->GetRoot();
}
return nullptr;
}
const RouteInfo& GetRouteInfo() const { return route_info_; }
protected:
Runner* root_;
std::vector<Runner*> input_runners_;
RouteInfo route_info_;
};
class ClusterJob {
public:
ClusterJob()
: tasks_(), main_task_id_(-1), sql_(""), common_column_indices_() {}
explicit ClusterJob(const std::string& sql, const std::string& db,
const std::set<size_t>& common_column_indices)
: tasks_(),
main_task_id_(-1),
sql_(sql),
db_(db),
common_column_indices_(common_column_indices) {}
ClusterTask GetTask(int32_t id) {
if (id < 0 || id >= static_cast<int32_t>(tasks_.size())) {
LOG(WARNING) << "fail get task: task " << id << " not exist";
return ClusterTask();
}
return tasks_[id];
}
ClusterTask GetMainTask() { return GetTask(main_task_id_); }
int32_t AddTask(const ClusterTask& task) {
if (!task.IsValid()) {
LOG(WARNING) << "fail to add invalid task";
return -1;
}
tasks_.push_back(task);
return tasks_.size() - 1;
}
bool AddRunnerToTask(Runner* runner, const int32_t id) {
if (id < 0 || id >= static_cast<int32_t>(tasks_.size())) {
LOG(WARNING) << "fail update task: task " << id << " not exist";
return false;
}
runner->AddProducer(tasks_[id].GetRoot());
tasks_[id].SetRoot(runner);
return true;
}
void AddMainTask(const ClusterTask& task) { main_task_id_ = AddTask(task); }
void Reset() { tasks_.clear(); }
const size_t GetTaskSize() const { return tasks_.size(); }
const bool IsValid() const { return !tasks_.empty(); }
const int32_t main_task_id() const { return main_task_id_; }
const std::string& sql() const { return sql_; }
const std::string& db() const { return db_; }
void Print(std::ostream& output, const std::string& tab) const {
if (tasks_.empty()) {
output << "EMPTY CLUSTER JOB\n";
return;
}
for (size_t i = 0; i < tasks_.size(); i++) {
if (main_task_id_ == static_cast<int32_t>(i)) {
output << "MAIN TASK ID " << i;
} else {
output << "TASK ID " << i;
}
tasks_[i].Print(output, tab);
output << "\n";
}
}
const std::set<size_t>& common_column_indices() const {
return common_column_indices_;
}
void Print() const { this->Print(std::cout, " "); }
private:
std::vector<ClusterTask> tasks_;
int32_t main_task_id_;
std::string sql_;
std::string db_;
std::set<size_t> common_column_indices_;
};
class RunnerBuilder {
enum TaskBiasType { kLeftBias, kRightBias, kNoBias };
public:
explicit RunnerBuilder(node::NodeManager* nm, const std::string& sql,
const std::string& db,
bool support_cluster_optimized,
const std::set<size_t>& common_column_indices,
const std::set<size_t>& batch_common_node_set)
: nm_(nm),
support_cluster_optimized_(support_cluster_optimized),
id_(0),
cluster_job_(sql, db, common_column_indices),
task_map_(),
proxy_runner_map_(),
batch_common_node_set_(batch_common_node_set) {}
virtual ~RunnerBuilder() {}
ClusterTask RegisterTask(PhysicalOpNode* node, ClusterTask task) {
task_map_[node] = task;
if (batch_common_node_set_.find(node->node_id()) !=
batch_common_node_set_.end()) {
task.GetRoot()->EnableBatchCache();
}
return task;
}
ClusterTask Build(PhysicalOpNode* node, // NOLINT
Status& status); // NOLINT
ClusterJob BuildClusterJob(PhysicalOpNode* node,
Status& status) { // NOLINT
id_ = 0;
cluster_job_.Reset();
auto task = // NOLINT whitespace/braces
Build(node, status);
if (!status.isOK()) {
return cluster_job_;
}
if (task.IsCompletedClusterTask()) {
auto proxy_task = BuildProxyRunnerForClusterTask(task);
if (!proxy_task.IsValid()) {
status.code = common::kExecutionPlanError;
status.msg = "Fail to build proxy cluster task";
LOG(WARNING) << status;
return cluster_job_;
}
cluster_job_.AddMainTask(proxy_task);
} else if (task.IsUnCompletedClusterTask()) {
status.code = common::kExecutionPlanError;
status.msg =
"Fail to build main task, can't handler "
"uncompleted cluster task";
LOG(WARNING) << status;
return cluster_job_;
} else {
cluster_job_.AddMainTask(task);
}
return cluster_job_;
}
template <typename Op, typename... Args>
void CreateRunner(Op** result_runner, Args&&... args) {
Op* runner = new Op(std::forward<Args>(args)...);
*result_runner = nm_->RegisterNode(runner);
}
private:
node::NodeManager* nm_;
bool support_cluster_optimized_;
int32_t id_;
ClusterJob cluster_job_;
std::unordered_map<::hybridse::vm::PhysicalOpNode*,
::hybridse::vm::ClusterTask>
task_map_;
std::shared_ptr<ClusterTask> request_task_;
std::unordered_map<hybridse::vm::Runner*, ::hybridse::vm::Runner*>
proxy_runner_map_;
std::set<size_t> batch_common_node_set_;
ClusterTask BinaryInherit(const ClusterTask& left, const ClusterTask& right,
Runner* runner, const Key& index_key,
const TaskBiasType bias = kNoBias);
ClusterTask BuildLocalTaskForBinaryRunner(const ClusterTask& left,
const ClusterTask& right,
Runner* runner);
ClusterTask BuildClusterTaskForBinaryRunner(const ClusterTask& left,
const ClusterTask& right,
Runner* runner,
const Key& index_key,
const TaskBiasType bias);
ClusterTask BuildProxyRunnerForClusterTask(const ClusterTask& task);
ClusterTask InvalidTask() { return ClusterTask(); }
ClusterTask CommonTask(Runner* runner) { return ClusterTask(runner); }
ClusterTask UnCompletedClusterTask(
Runner* runner, const std::shared_ptr<TableHandler> table_handler,
std::string index);
ClusterTask BuildRequestTask(RequestRunner* runner);
ClusterTask UnaryInheritTask(const ClusterTask& input, Runner* runner);
};
class RunnerContext {
public:
explicit RunnerContext(hybridse::vm::ClusterJob* cluster_job,
const hybridse::codec::Row& parameter,
const bool is_debug = false)
: cluster_job_(cluster_job),
sp_name_(""),
request_(),
requests_(),
parameter_(parameter),
is_debug_(is_debug),
batch_cache_() {}
explicit RunnerContext(hybridse::vm::ClusterJob* cluster_job,
const hybridse::codec::Row& request,
const std::string& sp_name = "",
const bool is_debug = false)
: cluster_job_(cluster_job),
sp_name_(sp_name),
request_(request),
requests_(),
parameter_(),
is_debug_(is_debug),
batch_cache_() {}
explicit RunnerContext(hybridse::vm::ClusterJob* cluster_job,
const std::vector<Row>& request_batch,
const std::string& sp_name = "",
const bool is_debug = false)
: cluster_job_(cluster_job),
sp_name_(sp_name),
request_(),
requests_(request_batch),
parameter_(),
is_debug_(is_debug),
batch_cache_() {}
const size_t GetRequestSize() const { return requests_.size(); }
const hybridse::codec::Row& GetRequest() const { return request_; }
const hybridse::codec::Row& GetRequest(size_t idx) const {
return requests_[idx];
}
const hybridse::codec::Row& GetParameterRow() const { return parameter_; }
hybridse::vm::ClusterJob* cluster_job() { return cluster_job_; }
void SetRequest(const hybridse::codec::Row& request);
void SetRequests(const std::vector<hybridse::codec::Row>& requests);
bool is_debug() const { return is_debug_; }
const std::string& sp_name() { return sp_name_; }
std::shared_ptr<DataHandler> GetCache(int64_t id) const;
void SetCache(int64_t id, std::shared_ptr<DataHandler> data);
void ClearCache() { cache_.clear(); }
std::shared_ptr<DataHandlerList> GetBatchCache(int64_t id) const;
void SetBatchCache(int64_t id, std::shared_ptr<DataHandlerList> data);
private:
hybridse::vm::ClusterJob* cluster_job_;
const std::string sp_name_;
hybridse::codec::Row request_;
std::vector<hybridse::codec::Row> requests_;
hybridse::codec::Row parameter_;
size_t idx_;
const bool is_debug_;
// TODO(chenjing): optimize
std::map<int64_t, std::shared_ptr<DataHandler>> cache_;
std::map<int64_t, std::shared_ptr<DataHandlerList>> batch_cache_;
};
} // namespace vm
} // namespace hybridse
#endif // HYBRIDSE_SRC_VM_RUNNER_H_
| 37.887408 | 115 | 0.622132 |
302d118e4cf2cbbcefc75c8500306df17c12867a | 9,750 | h | C | components/sx127x/include/SX1278.h | curiousmuch/l-clip | f8f5027c1d105737fd016750472ee24b193cd850 | [
"Apache-2.0"
] | null | null | null | components/sx127x/include/SX1278.h | curiousmuch/l-clip | f8f5027c1d105737fd016750472ee24b193cd850 | [
"Apache-2.0"
] | null | null | null | components/sx127x/include/SX1278.h | curiousmuch/l-clip | f8f5027c1d105737fd016750472ee24b193cd850 | [
"Apache-2.0"
] | null | null | null |
/**
* Author Wojciech Domski <Wojciech.Domski@gmail.com>
* www: www.Domski.pl
*
* work based on DORJI.COM sample code and
* https://github.com/realspinner/SX1278_LoRa
*/
#ifndef __SX1278_H__
#define __SX1278_H__
#include <stdint.h>
#include <stdbool.h>
#define SX1278_MAX_PACKET 256
#define SX1278_DEFAULT_TIMEOUT 3000
//Error Coding rate (CR)setting
#define SX1278_CR_4_5
//#define SX1278_CR_4_6
//#define SX1278_CR_4_7
//#define SX1278_CR_4_8
#ifdef SX1278_CR_4_5
#define SX1278_CR 0x01
#else
#ifdef SX1278_CR_4_6
#define SX1278_CR 0x02
#else
#ifdef SX1278_CR_4_7
#define SX1278_CR 0x03
#else
#ifdef SX1278_CR_4_8
#define SX1278_CR 0x04
#endif
#endif
#endif
#endif
//CRC Enable
#define SX1278_CRC_EN
#ifdef SX1278_CRC_EN
#define SX1278_CRC 0x01
#else
#define SX1278_CRC 0x00
#endif
//RFM98 Internal registers Address
/********************LoRa mode***************************/
#define LR_RegFifo 0x00
// Common settings
#define LR_RegOpMode 0x01
#define LR_RegFrMsb 0x06
#define LR_RegFrMid 0x07
#define LR_RegFrLsb 0x08
// Tx settings
#define LR_RegPaConfig 0x09
#define LR_RegPaRamp 0x0A
#define LR_RegOcp 0x0B
// Rx settings
#define LR_RegLna 0x0C
// LoRa registers
#define LR_RegFifoAddrPtr 0x0D
#define LR_RegFifoTxBaseAddr 0x0E
#define LR_RegFifoRxBaseAddr 0x0F
#define LR_RegFifoRxCurrentaddr 0x10
#define LR_RegIrqFlagsMask 0x11
#define LR_RegIrqFlags 0x12
#define LR_RegRxNbBytes 0x13
#define LR_RegRxHeaderCntValueMsb 0x14
#define LR_RegRxHeaderCntValueLsb 0x15
#define LR_RegRxPacketCntValueMsb 0x16
#define LR_RegRxPacketCntValueLsb 0x17
#define LR_RegModemStat 0x18
#define LR_RegPktSnrValue 0x19
#define LR_RegPktRssiValue 0x1A
#define LR_RegRssiValue 0x1B
#define LR_RegHopChannel 0x1C
#define LR_RegModemConfig1 0x1D
#define LR_RegModemConfig2 0x1E
#define LR_RegSymbTimeoutLsb 0x1F
#define LR_RegPreambleMsb 0x20
#define LR_RegPreambleLsb 0x21
#define LR_RegPayloadLength 0x22
#define LR_RegMaxPayloadLength 0x23
#define LR_RegHopPeriod 0x24
#define LR_RegFifoRxByteAddr 0x25
// I/O settings
#define REG_LR_DIOMAPPING1 0x40
#define REG_LR_DIOMAPPING2 0x41
// Version
#define REG_LR_VERSION 0x42
// Additional settings
#define REG_LR_PLLHOP 0x44
#define REG_LR_TCXO 0x4B
#define REG_LR_PADAC 0x4D
#define REG_LR_FORMERTEMP 0x5B
#define REG_LR_AGCREF 0x61
#define REG_LR_AGCTHRESH1 0x62
#define REG_LR_AGCTHRESH2 0x63
#define REG_LR_AGCTHRESH3 0x64
/********************FSK/ook mode***************************/
#define RegFIFO 0x00
#define RegOpMode 0x01
#define RegBitRateMsb 0x02
#define RegBitRateLsb 0x03
#define RegFdevMsb 0x04
#define RegFdevLsb 0x05
#define RegFreqMsb 0x06
#define RegFreqMid 0x07
#define RegFreqLsb 0x08
#define RegPaConfig 0x09
#define RegPaRamp 0x0a
#define RegOcp 0x0b
#define RegLna 0x0c
#define RegRxConfig 0x0d
#define RegRssiConfig 0x0e
#define RegRssiCollision 0x0f
#define RegRssiThresh 0x10
#define RegRssiValue 0x11
#define RegRxBw 0x12
#define RegAfcBw 0x13
#define RegOokPeak 0x14
#define RegOokFix 0x15
#define RegOokAvg 0x16
#define RegAfcFei 0x1a
#define RegAfcMsb 0x1b
#define RegAfcLsb 0x1c
#define RegFeiMsb 0x1d
#define RegFeiLsb 0x1e
#define RegPreambleDetect 0x1f
#define RegRxTimeout1 0x20
#define RegRxTimeout2 0x21
#define RegRxTimeout3 0x22
#define RegRxDelay 0x23
#define RegOsc 0x24
#define RegPreambleMsb 0x25
#define RegPreambleLsb 0x26
#define RegSyncConfig 0x27
#define RegSyncValue1 0x28
#define RegSyncValue2 0x29
#define RegSyncValue3 0x2a
#define RegSyncValue4 0x2b
#define RegSyncValue5 0x2c
#define RegSyncValue6 0x2d
#define RegSyncValue7 0x2e
#define RegSyncValue8 0x2f
#define RegPacketConfig1 0x30
#define RegPacketConfig2 0x31
#define RegPayloadLength 0x32
#define RegNodeAdrs 0x33
#define RegBroadcastAdrs 0x34
#define RegFifoThresh 0x35
#define RegSeqConfig1 0x36
#define RegSeqConfig2 0x37
#define RegTimerResol 0x38
#define RegTimer1Coef 0x39
#define RegTimer2Coef 0x3a
#define RegImageCal 0x3b
#define RegTemp 0x3c
#define RegLowBat 0x3d
#define RegIrqFlags1 0x3e
#define RegIrqFlags2 0x3f
#define RegDioMapping1 0x40
#define RegDioMapping2 0x41
#define RegVersion 0x42
#define RegPllHop 0x44
#define RegPaDac 0x4d
#define RegBitRateFrac 0x5d
/**********************************************************
**Parameter table define
**********************************************************/
#define SX1278_433MHZ 0
static const uint8_t SX1278_Frequency[1][3] = { { 0x6C, 0x80, 0x00 }, //434MHz
};
#define SX1278_POWER_20DBM 0
#define SX1278_POWER_17DBM 1
#define SX1278_POWER_14DBM 2
#define SX1278_POWER_11DBM 3
static const uint8_t SX1278_Power[4] = { 0xFF, //20dbm
0xFC, //17dbm
0xF9, //14dbm
0xF6, //11dbm
};
#define SX1278_LORA_SF_6 0
#define SX1278_LORA_SF_7 1
#define SX1278_LORA_SF_8 2
#define SX1278_LORA_SF_9 3
#define SX1278_LORA_SF_10 4
#define SX1278_LORA_SF_11 5
#define SX1278_LORA_SF_12 6
static const uint8_t SX1278_SpreadFactor[7] = { 6, 7, 8, 9, 10, 11, 12 };
#define SX1278_LORA_BW_7_8KHZ 0
#define SX1278_LORA_BW_10_4KHZ 1
#define SX1278_LORA_BW_15_6KHZ 2
#define SX1278_LORA_BW_20_8KHZ 3
#define SX1278_LORA_BW_31_2KHZ 4
#define SX1278_LORA_BW_41_7KHZ 5
#define SX1278_LORA_BW_62_5KHZ 6
#define SX1278_LORA_BW_125KHZ 7
#define SX1278_LORA_BW_250KHZ 8
#define SX1278_LORA_BW_500KHZ 9
static const uint8_t SX1278_LoRaBandwidth[10] = { 0, // 7.8KHz,
1, // 10.4KHz,
2, // 15.6KHz,
3, // 20.8KHz,
4, // 31.2KHz,
5, // 41.7KHz,
6, // 62.5KHz,
7, // 125.0KHz,
8, // 250.0KHz,
9 // 500.0KHz
};
typedef enum _SX1278_STATUS {
SLEEP, STANDBY, TX, RX
} SX1278_Status_t;
typedef struct {
int pin;
void * port;
} SX1278_hw_dio_t;
typedef struct {
SX1278_hw_dio_t reset;
SX1278_hw_dio_t dio0;
SX1278_hw_dio_t nss;
SX1278_hw_dio_t miso;
SX1278_hw_dio_t mosi;
SX1278_hw_dio_t sclk;
void * spi;
} SX1278_hw_t;
typedef struct {
SX1278_hw_t * hw;
uint8_t frequency;
uint8_t power;
uint8_t LoRa_Rate;
uint8_t LoRa_BW;
uint8_t packetLength;
SX1278_Status_t status;
uint8_t rxBuffer[SX1278_MAX_PACKET];
uint8_t readBytes;
} SX1278_t;
//hardware
void SX1278_hw_init(SX1278_hw_t * hw);
void SX1278_hw_SetNSS(SX1278_hw_t * hw, int value);
void SX1278_hw_Reset(SX1278_hw_t * hw);
void SX1278_hw_SPICommand(SX1278_hw_t * hw, uint8_t cmd);
uint8_t SX1278_hw_SPIReadByte(SX1278_hw_t * hw);
void SX1278_hw_DelayMs(uint32_t msec);
int SX1278_hw_GetDIO0(SX1278_hw_t * hw);
//logic
uint8_t SX1278_SPIRead(SX1278_t * module, uint8_t addr);
void SX1278_SPIWrite(SX1278_t * module, uint8_t addr, uint8_t cmd);
void SX1278_SPIBurstRead(SX1278_t * module, uint8_t addr, uint8_t *rxBuf, uint8_t length);
void SX1278_SPIBurstWrite(SX1278_t * module, uint8_t addr, uint8_t *txBuf, uint8_t length);
void SX1278_DIO0_InterruptHandler(SX1278_t * module);
void SX1278_config(SX1278_t * module, uint8_t frequency, uint8_t power, uint8_t LoRa_Rate, uint8_t LoRa_BW);
void SX1278_defaultConfig(SX1278_t * module);
void SX1278_entryLoRa(SX1278_t * module);
void SX1278_clearLoRaIrq(SX1278_t * module);
int SX1278_LoRaEntryRx(SX1278_t * module, uint8_t length, uint32_t timeout);
uint8_t SX1278_LoRaRxPacket(SX1278_t * module);
int SX1278_LoRaEntryTx(SX1278_t * module, uint8_t length, uint32_t timeout);
int SX1278_LoRaTxPacket(SX1278_t * module, uint8_t *txBuf, uint8_t length, uint32_t timeout);
void SX1278_begin(SX1278_t * module, uint8_t frequency, uint8_t power, uint8_t LoRa_Rate, uint8_t LoRa_BW, uint8_t packetLength);
int SX1278_transmit(SX1278_t * module, uint8_t *txBuf, uint8_t length, uint32_t timeout);
int SX1278_(SX1278_t * module, uint8_t length, uint32_t timeoutT);
uint8_t SX1278_available(SX1278_t * module);
uint8_t SX1278_read(SX1278_t * module, uint8_t *rxBuf, uint8_t length);
uint8_t SX1278_RSSI_LoRa(SX1278_t * module);
uint8_t SX1278_RSSI(SX1278_t * module);
uint8_t SX1278_SNR(SX1278_t * module);
void SX1278_standby(SX1278_t * module);
void SX1278_sleep(SX1278_t * module);
#endif
| 33.050847 | 129 | 0.632718 |
5c9f10d31abf517fb02ab16ba4d30f4088b810df | 9,656 | h | C | examples/cpp/lib/effect.h | birgerjohansson/fadecandy | 242360f7fbb902ea16c7690d7e06c40bdcc066be | [
"MIT"
] | 959 | 2015-01-06T08:55:11.000Z | 2022-03-26T04:45:33.000Z | examples/cpp/lib/effect.h | birgerjohansson/fadecandy | 242360f7fbb902ea16c7690d7e06c40bdcc066be | [
"MIT"
] | 83 | 2015-03-12T15:32:53.000Z | 2022-03-21T05:25:36.000Z | examples/cpp/lib/effect.h | birgerjohansson/fadecandy | 242360f7fbb902ea16c7690d7e06c40bdcc066be | [
"MIT"
] | 352 | 2015-01-04T06:50:19.000Z | 2022-03-28T19:00:23.000Z | /*
* LED Effect Framework
*
* Copyright (c) 2014 Micah Elizabeth Scott <micah@scanlime.org>
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#pragma once
#include <cmath>
#include <unistd.h>
#include <vector>
#include <cstring>
#include <cstdlib>
#include "nanoflann.h" // Tiny KD-tree library
#include "svl/SVL.h"
#include "rapidjson/rapidjson.h"
#include "rapidjson/document.h"
class EffectRunner;
// Abstract base class for one LED effect
class Effect {
public:
class PixelInfo;
class FrameInfo;
class DebugInfo;
/*
* Calculate a pixel value, using floating point RGB in the nominal range [0, 1].
*
* The 'rgb' vector is initialized to (0, 0, 0). Caller is responsible for
* clamping the results if necessary. This supports effects that layer with
* other effects using full floating point precision and dynamic range.
*
* This function may be run in parallel, not run at all, or run multiple times
* per pixel. It therefore can't have side-effects other than producing an RGB
* value.
*/
virtual void shader(Vec3& rgb, const PixelInfo& p) const = 0;
/*
* Serialized post-processing on one pixel. This runs after shader(), once
* per mapped pixel, with the ability to modify Effect data. This shoudln't
* be used for anything CPU-intensive, but some effects require closed-loop
* feedback based on the calculated color.
*/
virtual void postProcess(const Vec3& rgb, const PixelInfo& p);
// Optional begin/end frame callbacks
virtual void beginFrame(const FrameInfo& f);
virtual bool endFrame(const FrameInfo& f);
// Optional callback, invoked once per second when verbose mode is enabled.
// This can print parameters out to the console.
virtual void debug(const DebugInfo& d);
// Information about one LED pixel
class PixelInfo {
public:
PixelInfo(unsigned index, const rapidjson::Value* layout);
// Point coordinates
Vec3 point;
// Index in the framebuffer
unsigned index;
// Parsed JSON for this pixel's layout
const rapidjson::Value* layout;
// Is this pixel being used, or is it a placeholder?
bool isMapped() const;
// Look up data from the JSON layout
const rapidjson::Value& get(const char *attribute) const;
double getNumber(const char *attribute) const;
double getArrayNumber(const char *attribute, int index) const;
Vec2 getVec2(const char *attribute) const;
Vec3 getVec3(const char *attribute) const;
};
typedef std::vector<PixelInfo> PixelInfoVec;
typedef std::vector<PixelInfo>::const_iterator PixelInfoIter;
// Information about one Effect frame
class FrameInfo {
public:
FrameInfo();
void init(const rapidjson::Value &layout);
// Seconds passed since the last frame
float timeDelta;
// Info for every pixel
PixelInfoVec pixels;
// Model axis-aligned bounding box
Vec3 modelMin, modelMax;
// Radius measured from center
Real modelRadius;
// Calculated model info
Vec3 modelCenter() const;
Vec3 modelSize() const;
Real distanceOutsideBoundingBox(Vec3 p) const;
// K-D Tree, for fast spatial lookups
typedef nanoflann::KDTreeSingleIndexAdaptor<
nanoflann::L2_Simple_Adaptor< Real, FrameInfo >,
FrameInfo, 3> IndexTree;
typedef std::vector<std::pair<size_t, Real> > ResultSet_t;
void radiusSearch(ResultSet_t& hits, Vec3 point, float radius) const;
IndexTree tree;
// Adapter functions for the K-D tree implementation
inline size_t kdtree_get_point_count() const {
return pixels.size();
}
inline Real kdtree_distance(const Real *p1, const size_t idx_p2, size_t size) const {
Real d0 = p1[0] - pixels[idx_p2].point[0];
Real d1 = p1[1] - pixels[idx_p2].point[1];
Real d2 = p1[2] - pixels[idx_p2].point[2];
return d0*d0 + d1*d1 + d2*d2;
}
Real kdtree_get_pt(const size_t idx, int dim) const {
return pixels[idx].point[dim];
}
template <class BBOX> bool kdtree_get_bbox(BBOX &bb) const {
bb[0].low = modelMin[0];
bb[1].low = modelMin[1];
bb[2].low = modelMin[2];
bb[0].high = modelMax[0];
bb[1].high = modelMax[1];
bb[2].high = modelMax[2];
return true;
}
};
// Information passed to debug() callbacks
class DebugInfo {
public:
DebugInfo(EffectRunner &runner);
EffectRunner &runner;
};
Effect(): number_frames(0), frame_count(0) {}
unsigned long number_frames;
unsigned long frame_count;
};
/*****************************************************************************************
* Implementation
*****************************************************************************************/
inline Effect::PixelInfo::PixelInfo(unsigned index, const rapidjson::Value* layout)
: index(index), layout(layout)
{
point = isMapped() ? getVec3("point") : Vec3(0, 0, 0);
}
inline bool Effect::PixelInfo::isMapped() const
{
return layout && layout->IsObject();
}
inline const rapidjson::Value& Effect::PixelInfo::get(const char *attribute) const
{
return (*layout)[attribute];
}
inline double Effect::PixelInfo::getNumber(const char *attribute) const
{
const rapidjson::Value& n = get(attribute);
return n.IsNumber() ? n.GetDouble() : 0.0;
}
inline double Effect::PixelInfo::getArrayNumber(const char *attribute, int index) const
{
const rapidjson::Value& a = get(attribute);
if (a.IsArray()) {
const rapidjson::Value& b = a[index];
if (b.IsNumber()) {
return b.GetDouble();
}
}
return 0.0;
}
inline Vec2 Effect::PixelInfo::getVec2(const char *attribute) const
{
return Vec2( getArrayNumber(attribute, 0),
getArrayNumber(attribute, 1) );
}
inline Vec3 Effect::PixelInfo::getVec3(const char *attribute) const
{
return Vec3( getArrayNumber(attribute, 0),
getArrayNumber(attribute, 1),
getArrayNumber(attribute, 2) );
}
inline Effect::FrameInfo::FrameInfo()
: timeDelta(0), tree(3, *this)
{}
inline void Effect::FrameInfo::init(const rapidjson::Value &layout)
{
timeDelta = 0;
pixels.clear();
// Create PixelInfo instances
for (unsigned i = 0; i < layout.Size(); i++) {
PixelInfo p(i, &layout[i]);
pixels.push_back(p);
}
// Calculate min/max
modelMin = modelMax = pixels[0].point;
for (unsigned i = 1; i < pixels.size(); i++) {
for (unsigned j = 0; j < 3; j++) {
modelMin[j] = std::min(modelMin[j], pixels[i].point[j]);
modelMax[j] = std::max(modelMax[j], pixels[i].point[j]);
}
}
// Calculate radius
modelRadius = 0;
for (unsigned i = 0; i < pixels.size(); i++) {
modelRadius = std::max(modelRadius, len(pixels[i].point - modelCenter()));
}
// Build K-D Tree index, for fast spatial lookups later
tree.buildIndex();
}
inline Vec3 Effect::FrameInfo::modelCenter() const
{
return (modelMin + modelMax) * 0.5;
}
inline Vec3 Effect::FrameInfo::modelSize() const
{
return modelMax - modelMin;
}
inline Real Effect::FrameInfo::distanceOutsideBoundingBox(Vec3 p) const
{
Real d = 0;
for (unsigned j = 0; j < 3; j++) {
d = std::max(d, modelMin[j] - p[j]);
d = std::max(d, p[j] - modelMax[j]);
}
return d;
}
inline void Effect::FrameInfo::radiusSearch(ResultSet_t& hits, Vec3 point, float radius) const
{
nanoflann::SearchParams params;
params.sorted = false;
tree.radiusSearch(&point[0], radius * radius, hits, params);
}
inline Effect::DebugInfo::DebugInfo(EffectRunner &runner)
: runner(runner) {}
inline void Effect::beginFrame( const FrameInfo & ) {}
inline bool Effect::endFrame( const FrameInfo & )
{
if( number_frames )
{
if( frame_count++ > number_frames )
{
frame_count = 0;
return true;
}
}
return false;
}
inline void Effect::debug( const DebugInfo & ) {}
inline void Effect::postProcess( const Vec3&, const PixelInfo& ) {}
static inline float sq(float a)
{
// Fast square
return a * a;
}
static inline Vec3 XZ(Vec2 v)
{
// Put a 2D vector on the XZ plane
return Vec3(v[0], 0, v[1]);
}
| 28.652819 | 94 | 0.628625 |
5ccc885559e60a0a04f63c4ad978ee32db19a394 | 324 | h | C | src/chatterbox_1.1.0/lib/Generator/Wavetable.h | danja/chatterbox | 59ebf9d65bac38854a6162bc0f6f4b9f6d43d330 | [
"MIT"
] | 2 | 2021-02-19T22:30:59.000Z | 2021-03-19T19:07:36.000Z | src/chatterbox_1.1.0/lib/Generator/Wavetable.h | danja/chatterbox | 59ebf9d65bac38854a6162bc0f6f4b9f6d43d330 | [
"MIT"
] | null | null | null | src/chatterbox_1.1.0/lib/Generator/Wavetable.h | danja/chatterbox | 59ebf9d65bac38854a6162bc0f6f4b9f6d43d330 | [
"MIT"
] | null | null | null | #ifndef _WAVETABLE_H
#define _WAVETABLE_H
#include <Node.h>
// #include <Patchbay.h>
const int TABLESIZE = 2048;
const float tablesize = 2048.0f;
class Wavetable : public Node
{
public:
void init();
const float get(const float hop);
float wavetable[TABLESIZE];
float pointer = 0.0f;
private:
};
#endif
| 14.086957 | 37 | 0.691358 |
6823374e6e59723070b854b7c35c25a3d43d7f44 | 998 | h | C | termsrv/license/licmgr/treenode.h | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | termsrv/license/licmgr/treenode.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | termsrv/license/licmgr/treenode.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //Copyright (c) 1998 - 1999 Microsoft Corporation
/*++
Module Name:
TreeNode.h
Abstract:
This Module contains the CTreeNode class
(Class used for representing every node in the tree view);
Author:
Arathi Kundapur (v-akunda) 11-Feb-1998
Revision History:
--*/
#include <afx.h>
class CTreeNode : public CObject
{
public:
// constructor
CTreeNode(NODETYPE NodeType, CObject* pObject) { m_NodeType = NodeType; m_pTreeObject = pObject; }
// Returns the node type
NODETYPE GetNodeType() { return m_NodeType; }
// Returns the object pointed to by this node
CObject *GetTreeObject() { return m_pTreeObject; }
// Returns the sort order stored in the object
ULONG GetSortOrder() { return m_SortOrder; }
// Sets the sort order stored with the object
void SetSortOrder(ULONG order) { m_SortOrder = order; }
private:
NODETYPE m_NodeType;
CObject* m_pTreeObject;
ULONG m_SortOrder;
}; | 22.681818 | 103 | 0.665331 |
fd9c8709e9746d9c3d3e95e4d5502117a6f0b881 | 1,249 | h | C | dlk/backends/include/cpp/utils.h | toohsk/blueoil | 596922caa939db9c5ecbac3286fbf6f703865ee6 | [
"Apache-2.0"
] | null | null | null | dlk/backends/include/cpp/utils.h | toohsk/blueoil | 596922caa939db9c5ecbac3286fbf6f703865ee6 | [
"Apache-2.0"
] | 1 | 2019-02-07T12:20:52.000Z | 2019-02-08T07:22:48.000Z | dlk/backends/include/cpp/utils.h | toohsk/blueoil | 596922caa939db9c5ecbac3286fbf6f703865ee6 | [
"Apache-2.0"
] | null | null | null | /* Copyright 2018 The Blueoil 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.
==============================================================================*/
#pragma once
#include "common/global.h"
namespace cpp {
inline T_out pop_count(T_in in_data) {
T_out sum = 0;
const unsigned nbits_per_word = sizeof(T_in) * 8;
for (unsigned i = 0; i < nbits_per_word; i++) {
sum += (in_data >> i) & 0x1;
}
return sum;
}
inline T_out PE(T_q k_buf, T_q in_buf0, T_q in_buf1) {
T_q xnor0 = ~(in_buf0 ^ k_buf);
T_q xnor1 = ~(in_buf1 ^ k_buf);
T_out in_pc0 = pop_count(xnor0);
T_out in_pc1 = pop_count(xnor1);
T_out k_pc = pop_count(~k_buf);
return in_pc0 + (2 * in_pc1) - (3 * k_pc);
}
}
| 29.046512 | 80 | 0.650921 |
fdcf4c3e29093e0e3f1d3b5cbebd50e5fdee9da4 | 1,047 | h | C | System/Library/PrivateFrameworks/UIKitCore.framework/UITableViewIndexOverlaySelectionViewCollectionViewFlowLayout.h | zhangkn/iOS14Header | 4323e9459ed6f6f5504ecbea2710bfd6c3d7c946 | [
"MIT"
] | 1 | 2020-11-04T15:43:01.000Z | 2020-11-04T15:43:01.000Z | System/Library/PrivateFrameworks/UIKitCore.framework/UITableViewIndexOverlaySelectionViewCollectionViewFlowLayout.h | zhangkn/iOS14Header | 4323e9459ed6f6f5504ecbea2710bfd6c3d7c946 | [
"MIT"
] | null | null | null | System/Library/PrivateFrameworks/UIKitCore.framework/UITableViewIndexOverlaySelectionViewCollectionViewFlowLayout.h | zhangkn/iOS14Header | 4323e9459ed6f6f5504ecbea2710bfd6c3d7c946 | [
"MIT"
] | null | null | null | /*
* This header is generated by classdump-dyld 1.0
* on Sunday, September 27, 2020 at 11:38:59 AM Mountain Standard Time
* Operating System: Version 14.0 (Build 18A373)
* Image Source: /System/Library/PrivateFrameworks/UIKitCore.framework/UIKitCore
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos.
*/
#import <UIKitCore/UIKitCore-Structs.h>
#import <UIKitCore/UICollectionViewFlowLayout.h>
@interface UITableViewIndexOverlaySelectionViewCollectionViewFlowLayout : UICollectionViewFlowLayout {
CGRect _frameForDoneButton;
double _rightMarginForDoneButton;
}
@property (assign,nonatomic) CGRect frameForDoneButton;
@property (assign,nonatomic) double rightMarginForDoneButton;
+(Class)layoutAttributesClass;
-(id)layoutAttributesForElementsInRect:(CGRect)arg1 ;
-(id)layoutAttributesForSupplementaryViewOfKind:(id)arg1 atIndexPath:(id)arg2 ;
-(CGRect)frameForDoneButton;
-(double)rightMarginForDoneButton;
-(void)setFrameForDoneButton:(CGRect)arg1 ;
-(void)setRightMarginForDoneButton:(double)arg1 ;
@end
| 34.9 | 102 | 0.816619 |
a94eb5085cb912b575bb30f5aa1b8cd5d85b7630 | 63 | h | C | include/architecture/mips32/stddef.h | nfd/ci20-os | abe23fbd758ccf823d4b43c24bd9cafff9046661 | [
"MIT"
] | 5 | 2015-05-30T07:12:33.000Z | 2021-03-03T06:32:53.000Z | include/architecture/mips32/stddef.h | nfd/ci20-os | abe23fbd758ccf823d4b43c24bd9cafff9046661 | [
"MIT"
] | null | null | null | include/architecture/mips32/stddef.h | nfd/ci20-os | abe23fbd758ccf823d4b43c24bd9cafff9046661 | [
"MIT"
] | 5 | 2015-04-18T10:55:26.000Z | 2019-06-06T19:44:02.000Z | /* TODO this is mips-specific */
typedef unsigned int size_t;
| 15.75 | 32 | 0.730159 |
a9739d0fa8cd37ae6b2806c4e3f7aefb882c4214 | 148 | h | C | src/proto.h | huyen-tt/Bingo_Programming | 0655df05540f46999edb5a6737f16bffdceae669 | [
"MIT"
] | null | null | null | src/proto.h | huyen-tt/Bingo_Programming | 0655df05540f46999edb5a6737f16bffdceae669 | [
"MIT"
] | 1 | 2019-12-23T07:33:50.000Z | 2019-12-23T07:33:50.000Z | src/proto.h | huyen-tt/Bingo_Programming | 0655df05540f46999edb5a6737f16bffdceae669 | [
"MIT"
] | 1 | 2019-12-16T12:54:04.000Z | 2019-12-16T12:54:04.000Z | #ifndef PROTO
#define PROTO
#define LENGTH_NAME 31
#define LENGTH_MSG 101
#define LENGTH_SEND 201
#define FILEHISTORY "history.txt"
#endif // PROTO | 18.5 | 33 | 0.790541 |
45633c9661f5220776640ccb5756bef8c6493e65 | 457 | h | C | MailHeaders/Lion/Mail/_MTMNotesMailbox.h | w-i-n-s/SimplePlugin | b834309d470de50b2eac29d5c4488a1942bab925 | [
"MIT"
] | 10 | 2015-02-19T21:47:05.000Z | 2021-04-23T10:40:12.000Z | MailHeaders/Lion/Mail/_MTMNotesMailbox.h | w-i-n-s/SimplePlugin | b834309d470de50b2eac29d5c4488a1942bab925 | [
"MIT"
] | null | null | null | MailHeaders/Lion/Mail/_MTMNotesMailbox.h | w-i-n-s/SimplePlugin | b834309d470de50b2eac29d5c4488a1942bab925 | [
"MIT"
] | 2 | 2018-03-04T02:29:41.000Z | 2021-02-09T20:42:21.000Z | /*
* Generated by class-dump 3.3.3 (64 bit).
*
* class-dump is Copyright (C) 1997-1998, 2000-2001, 2004-2010 by Steve Nygard.
*/
#import "_MTMStoredMetaMailbox.h"
@interface _MTMNotesMailbox : _MTMStoredMetaMailbox
{
}
- (id)displayName;
- (id)recoverDisplayName;
- (id)restoreMode;
- (id)messageColumnConfiguration;
- (id)defaultMessageColumnAttributesKey;
- (id)_oneMesageString;
- (id)_severalMessagesString;
- (id)messageListFont;
@end
| 19.041667 | 83 | 0.724289 |
ca5dfe6f16ba7cbc0de11042a40e47396bbd7a58 | 1,949 | h | C | toonz/sources/toonz/keyframeselection.h | jhonsu01/opentoonz | b8b0f90055ae6a54fc5926c46a063d460c9884d7 | [
"BSD-3-Clause"
] | 1 | 2021-08-07T00:16:54.000Z | 2021-08-07T00:16:54.000Z | toonz/sources/toonz/keyframeselection.h | LibrePhone/opentoonz | cb95a29db4c47ab1f36a6e85a039c4c9c901f88a | [
"BSD-3-Clause"
] | null | null | null | toonz/sources/toonz/keyframeselection.h | LibrePhone/opentoonz | cb95a29db4c47ab1f36a6e85a039c4c9c901f88a | [
"BSD-3-Clause"
] | 1 | 2021-08-07T00:16:58.000Z | 2021-08-07T00:16:58.000Z | #pragma once
#ifndef TKEYFRAMESELECTION_H
#define TKEYFRAMESELECTION_H
#include "toonzqt/selection.h"
#include <set>
//=============================================================================
// TKeyframeSelection
//-----------------------------------------------------------------------------
class TKeyframeSelection final : public TSelection {
public:
typedef std::pair<int, int> Position; // row, col
public:
std::set<Position> m_positions;
TKeyframeSelection(std::set<Position> positions) : m_positions(positions) {}
TKeyframeSelection() {}
void enableCommands() override;
/* FIXME: clang
* でテンポラリオブジェクトをアドレッシングしたとエラーになっていたので参照を返すようにしたが、元の意図が不明なので注意
*/
#if 0
std::set<Position> getSelection(){ return m_positions; }
#else
std::set<Position> &getSelection() { return m_positions; }
#endif
void select(std::set<Position> positions) {
clear();
std::set<Position>::iterator it;
for (it = positions.begin(); it != positions.end(); ++it)
select(it->first, it->second);
}
void clear() { m_positions.clear(); }
void selectNone() override { m_positions.clear(); }
void select(int row, int col) {
m_positions.insert(std::make_pair(row, col));
}
void unselect(int row, int col) {
m_positions.erase(std::make_pair(row, col));
}
bool isSelected(int row, int col) const {
return m_positions.find(std::make_pair(row, col)) != m_positions.end();
}
bool isEmpty() const override { return m_positions.empty(); }
TSelection *clone() const { return new TKeyframeSelection(m_positions); }
int getFirstRow() const;
void unselectLockedColumn();
bool select(const TSelection *s);
void setKeyframes();
void copyKeyframes();
void pasteKeyframes();
void deleteKeyframes();
void cutKeyframes();
void pasteKeyframesWithShift(int r0, int r1, int c0, int c1);
void deleteKeyframesWithShift(int r0, int r1, int c0, int c1);
};
#endif // TKEYFRAMESELECTION_H
| 25.311688 | 79 | 0.645459 |
3403bf0efcd10ba9ff55e852502ad1b8f03a3213 | 7,499 | h | C | src/language.h | jhertel/poed | 679057f8a9e051e482cbfa9caf2bfb37f8a4b0c2 | [
"MIT"
] | null | null | null | src/language.h | jhertel/poed | 679057f8a9e051e482cbfa9caf2bfb37f8a4b0c2 | [
"MIT"
] | null | null | null | src/language.h | jhertel/poed | 679057f8a9e051e482cbfa9caf2bfb37f8a4b0c2 | [
"MIT"
] | null | null | null | /*
* This file is part of Poedit (https://poedit.net)
*
* Copyright (C) 2013-2020 Vaclav Slavik
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
#ifndef Poedit_language_h
#define Poedit_language_h
#include <wx/string.h>
#include <memory>
#include <string>
#include <vector>
#include <unicode/locid.h>
class PluralFormsCalculator;
class PluralFormsExpr;
/// Language's text writing direction
enum class TextDirection
{
LTR,
RTL
};
/// Representation of translation's language.
class Language
{
public:
Language() : m_direction(TextDirection::LTR) {}
bool IsValid() const { return !m_code.empty(); }
const std::string& Code() const { return m_code; }
std::wstring WCode() const { return std::wstring(m_code.begin(), m_code.end()); }
/// Returns language part (cs)
std::string Lang() const;
/// Returns country part (CZ, may be empty)
std::string Country() const;
/// Returns language+country parts, without the variant
std::string LangAndCountry() const;
/// Returns optional variant (after @, e.g. 'latin', typically empty)
std::string Variant() const;
/// Return language tag for the language, per BCP 47, e.g. en-US or sr-Latn
std::string LanguageTag() const { return m_tag; }
/// Returns name of the locale suitable for ICU
std::string IcuLocaleName() const { return m_icuLocale; }
/// Returns ICU equivalent of the language info
icu::Locale ToIcu() const;
/// Returns name of this language suitable for display to the user in current UI language
wxString DisplayName() const;
/// Like DisplayName(), but shorted (no country/variant).
wxString LanguageDisplayName() const;
/// Returns name of this language in itself
wxString DisplayNameInItself() const;
/**
Human-readable (if possible) form usable for round-tripping, i.e.
understood by TryParse(). Typically "language (country)" in UI language.
@see AllFormattedNames()
*/
wxString FormatForRoundtrip() const;
/**
Return all formatted language names known, in sorted order.
@see FormatForRoundtrip()
*/
static const std::vector<std::wstring>& AllFormattedNames();
/**
Return appropriate plural form for this language.
@return Plural form expression suitable for directly using in the
gettext header or empty string if no record was found.
*/
PluralFormsExpr DefaultPluralFormsExpr() const;
/// Count of plural forms for this language
int nplurals() const;
/// Returns language's text writing direction
TextDirection Direction() const { return m_direction; }
/// Returns true if the language is written right-to-left.
bool IsRTL() const { return m_direction == TextDirection::RTL; }
/**
Tries to parse the string as language identification.
Accepts various forms:
- standard code (cs, cs_CZ, cs_CZ@latin, ...)
- ditto with nonstandard capitalization
- language name in English or current UI language
- ditto for "language (country)"
Returned language instance is either invalid if the value couldn't
be parsed or a language with normalized language code.
@note
This function does *not* validate language codes: if @a s has standard
form, the codes are assumed to be valid. Use TryParseWithValidation()
if you are not sure.
*/
static Language TryParse(const std::wstring& s);
static Language TryParse(const std::string& s)
{ return TryParse(std::wstring(s.begin(), s.end())); }
/**
Like TryParse(), but only accepts language codes if they are known
valid ISO 639/3166 codes.
*/
static Language TryParseWithValidation(const std::wstring& s);
/**
Returns language object corresponding to given BCP 47 tag.
Returned language instance is invalid if @a tag is invalid.
*/
static Language FromLanguageTag(const std::string& tag);
/**
Tries to create the language from Poedit's legacy X-Poedit-Language and
X-Poedit-Country headers.
*/
static Language FromLegacyNames(const std::string& lang, const std::string& country);
/**
Try to guess the language from filename, if the filename follows some
commonly used naming pattern.
*/
static Language TryGuessFromFilename(const wxString& filename);
/**
Try to detect the language from UTF-8 text.
Pass @a probableLanguage if the result is likely known, e.g. English
for source texts.
*/
static Language TryDetectFromText(const char *buffer, size_t len,
Language probableLanguage = Language());
/// Returns object for English language
static Language English() { return Language("en"); }
/**
Checks if @a s has the form of language code.
*/
static bool IsValidCode(const std::wstring& s);
bool operator==(const Language& other) const { return m_code == other.m_code; }
bool operator!=(const Language& other) const { return m_code != other.m_code; }
bool operator<(const Language& other) const { return m_code < other.m_code; }
private:
Language(const std::string& code) { Init(code); }
Language(const std::wstring& code) { Init(std::string(code.begin(), code.end())); }
void Init(const std::string& code);
private:
std::string m_code;
std::string m_tag;
std::string m_icuLocale;
TextDirection m_direction;
};
/// Language's plural forms expression
class PluralFormsExpr
{
public:
/// What numbers to test or show examples for (0..1001)
static const int MAX_EXAMPLES_COUNT = 1002;
PluralFormsExpr();
PluralFormsExpr(const std::string& expr, int nplurals = -1);
~PluralFormsExpr();
const std::string& str() const { return m_expr; }
bool operator==(const PluralFormsExpr& other) const;
bool operator!=(const PluralFormsExpr& other) const { return !(*this == other); }
explicit operator bool() const { return !m_expr.empty() && calc() != nullptr; }
int nplurals() const;
int evaluate_for_n(int n) const;
private:
std::shared_ptr<PluralFormsCalculator> calc() const;
std::string m_expr;
int m_nplurals;
bool m_calcCreated;
std::shared_ptr<PluralFormsCalculator> m_calc;
};
#endif // Poedit_language_h
| 33.328889 | 93 | 0.67689 |
340e40b369c61a5c1e0797272a1f532c4bed1679 | 4,488 | c | C | test/vtm/core/test_elem.c | ventanium/ventanium | 02b7e8516df32e49a79e47a8a59f78e3b44dc58f | [
"BSD-2-Clause"
] | 20 | 2019-03-14T15:08:20.000Z | 2020-11-11T13:11:01.000Z | test/vtm/core/test_elem.c | ventanium/ventanium | 02b7e8516df32e49a79e47a8a59f78e3b44dc58f | [
"BSD-2-Clause"
] | null | null | null | test/vtm/core/test_elem.c | ventanium/ventanium | 02b7e8516df32e49a79e47a8a59f78e3b44dc58f | [
"BSD-2-Clause"
] | 1 | 2019-03-15T11:57:44.000Z | 2019-03-15T11:57:44.000Z | /*
* Copyright (C) 2018-2019 Matthias Benkendorf
*/
#include <vtf.h>
#include <vtm/core/elem.h>
#include <vtm/core/math.h>
#define VTM_TEST_NUMERIC_CONVERSION(EL, TYPE, VAL) \
do { \
VTM_TEST_CHECK(vtm_elem_as_int8(TYPE, EL) == (int8_t) VAL, "elem value int8"); \
VTM_TEST_CHECK(vtm_elem_as_uint8(TYPE, EL) == (uint8_t) VAL, "elem value uint8"); \
VTM_TEST_CHECK(vtm_elem_as_int16(TYPE, EL) == (int16_t) VAL, "elem value int16"); \
VTM_TEST_CHECK(vtm_elem_as_uint16(TYPE, EL) == (uint16_t) VAL, "elem value uint16"); \
VTM_TEST_CHECK(vtm_elem_as_int32(TYPE, EL) == (int32_t) VAL, "elem value int32"); \
VTM_TEST_CHECK(vtm_elem_as_uint32(TYPE, EL) == (uint32_t) VAL, "elem value uint32"); \
VTM_TEST_CHECK(vtm_elem_as_int64(TYPE, EL) == (int64_t) VAL, "elem value int64"); \
VTM_TEST_CHECK(vtm_elem_as_uint64(TYPE, EL) == (uint64_t) VAL, "elem value uint64"); \
VTM_TEST_CHECK(vtm_elem_as_char(TYPE, EL) == (char) VAL, "elem value char"); \
VTM_TEST_CHECK(vtm_elem_as_schar(TYPE, EL) == (signed char) VAL, "elem value signed char"); \
VTM_TEST_CHECK(vtm_elem_as_uchar(TYPE, EL) == (unsigned char) VAL, "elem value unsigned char"); \
VTM_TEST_CHECK(vtm_elem_as_short(TYPE, EL) == (short) VAL, "elem value signed short"); \
VTM_TEST_CHECK(vtm_elem_as_ushort(TYPE, EL) == (unsigned short) VAL, "elem value unsigned short"); \
VTM_TEST_CHECK(vtm_elem_as_int(TYPE, EL) == (int) VAL, "elem value signed int"); \
VTM_TEST_CHECK(vtm_elem_as_uint(TYPE, EL) == (unsigned int) VAL, "elem value unsigned int"); \
VTM_TEST_CHECK(vtm_elem_as_long(TYPE, EL) == (long) VAL, "elem value signed long"); \
VTM_TEST_CHECK(vtm_elem_as_ulong(TYPE, EL) == (unsigned long) VAL, "elem value unsigned long"); \
} while (0)
#define VTM_TEST_FLOATING_POINT_CONVERSION(EL, TYPE, VAL) \
do { \
bool feq, deq; \
feq = vtm_math_float_cmp(vtm_elem_as_float(TYPE, EL), (float) VAL, 0.0001f); \
VTM_TEST_CHECK(feq == true, "elem value float"); \
deq = vtm_math_double_cmp(vtm_elem_as_double(TYPE, EL), (double) VAL, 0.0001); \
VTM_TEST_CHECK(deq == true, "elem value double"); \
} while (0)
#define VTM_TEST_ELEM(TYPE, ELEM, VAL) \
do { \
union vtm_elem el; \
el.elem_ ## ELEM = VAL; \
VTM_TEST_NUMERIC_CONVERSION(&el, TYPE, VAL); \
VTM_TEST_FLOATING_POINT_CONVERSION(&el, TYPE, VAL); \
} while (0)
static void test_elem(void)
{
VTM_TEST_ELEM(VTM_ELEM_INT8, int8, INT8_MIN);
VTM_TEST_ELEM(VTM_ELEM_UINT8, uint8, UINT8_MAX);
VTM_TEST_ELEM(VTM_ELEM_INT16, int16, INT16_MIN);
VTM_TEST_ELEM(VTM_ELEM_UINT16, uint16, UINT16_MAX);
VTM_TEST_ELEM(VTM_ELEM_INT32, int32, INT32_MIN);
VTM_TEST_ELEM(VTM_ELEM_UINT32, uint32, UINT32_MAX);
VTM_TEST_ELEM(VTM_ELEM_INT64, int64, INT64_MIN);
VTM_TEST_ELEM(VTM_ELEM_UINT64, uint64, UINT64_MAX);
VTM_TEST_ELEM(VTM_ELEM_CHAR, char, CHAR_MAX);
VTM_TEST_ELEM(VTM_ELEM_SCHAR, schar, SCHAR_MAX);
VTM_TEST_ELEM(VTM_ELEM_UCHAR, uchar, UCHAR_MAX);
VTM_TEST_ELEM(VTM_ELEM_SHORT, short, SHRT_MIN);
VTM_TEST_ELEM(VTM_ELEM_USHORT, ushort, USHRT_MAX);
VTM_TEST_ELEM(VTM_ELEM_INT, int, INT_MIN);
VTM_TEST_ELEM(VTM_ELEM_UINT, uint, UINT_MAX);
VTM_TEST_ELEM(VTM_ELEM_LONG, long, LONG_MIN);
VTM_TEST_ELEM(VTM_ELEM_ULONG, ulong, ULONG_MAX);
VTM_TEST_ELEM(VTM_ELEM_FLOAT, float, 1.23456f);
VTM_TEST_ELEM(VTM_ELEM_DOUBLE, double, 1.23456789);
}
extern void test_vtm_core_elem(void)
{
VTM_TEST_LABEL("elem");
test_elem();
}
| 59.052632 | 104 | 0.554144 |
3155fc47ed25d052eaa20502d4f27a98d1b7535b | 859 | h | C | src/Ethereum/ABI/ParamBase.h | Khaos-Labs/khaos-wallet-core | 2c06d49fddf978e0815b208dddef50ee2011c551 | [
"MIT"
] | 2 | 2020-11-16T08:06:30.000Z | 2021-06-18T03:21:44.000Z | src/Ethereum/ABI/ParamBase.h | Khaos-Labs/khaos-wallet-core | 2c06d49fddf978e0815b208dddef50ee2011c551 | [
"MIT"
] | null | null | null | src/Ethereum/ABI/ParamBase.h | Khaos-Labs/khaos-wallet-core | 2c06d49fddf978e0815b208dddef50ee2011c551 | [
"MIT"
] | null | null | null | // Copyright © 2017-2020 Khaos Wallet.
//
// This file is part of Trust. The full Trust copyright notice, including
// terms governing use, modification, and redistribution, is contained in the
// file LICENSE at the root of the source code distribution tree.
#pragma once
#include "Data.h"
#include <string>
namespace TW::Ethereum::ABI {
/// Abstract base class for parameters.
class ParamBase
{
public:
virtual ~ParamBase() = default;
virtual std::string getType() const = 0;
virtual size_t getSize() const = 0;
virtual bool isDynamic() const = 0;
virtual void encode(Data& data) const = 0;
virtual bool decode(const Data& encoded, size_t& offset_inout) = 0;
};
/// Collection parameters base class
class ParamCollection: public ParamBase
{
public:
virtual size_t getCount() const = 0;
};
} // namespace TW::Ethereum::ABI
| 24.542857 | 77 | 0.711292 |
bda43e83daf91f02be067c68210d56d6d1feb063 | 23,434 | h | C | Framework/Externals/OptiX/include/optix_prime/optix_primepp.h | tfoleyNV/Falcor-old | 2155109af2322f2aa1db2385cde44d1b7507976b | [
"BSD-3-Clause"
] | 1 | 2020-03-24T18:16:27.000Z | 2020-03-24T18:16:27.000Z | Framework/Externals/OptiX/include/optix_prime/optix_primepp.h | tfoleyNV/Falcor-old | 2155109af2322f2aa1db2385cde44d1b7507976b | [
"BSD-3-Clause"
] | null | null | null | Framework/Externals/OptiX/include/optix_prime/optix_primepp.h | tfoleyNV/Falcor-old | 2155109af2322f2aa1db2385cde44d1b7507976b | [
"BSD-3-Clause"
] | null | null | null |
/*
* Copyright (c) 2013 NVIDIA Corporation. All rights reserved.
*
* NVIDIA Corporation and its licensors retain all intellectual property and proprietary
* rights in and to this software, related documentation and any modifications thereto.
* Any use, reproduction, disclosure or distribution of this software and related
* documentation without an express license agreement from NVIDIA Corporation is strictly
* prohibited.
*
* TO THE MAXIMUM EXTENT PERMITTED BY APPLICABLE LAW, THIS SOFTWARE IS PROVIDED *AS IS*
* AND NVIDIA AND ITS SUPPLIERS DISCLAIM ALL WARRANTIES, EITHER EXPRESS OR IMPLIED,
* INCLUDING, BUT NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE. IN NO EVENT SHALL NVIDIA OR ITS SUPPLIERS BE LIABLE FOR ANY
* SPECIAL, INCIDENTAL, INDIRECT, OR CONSEQUENTIAL DAMAGES WHATSOEVER (INCLUDING, WITHOUT
* LIMITATION, DAMAGES FOR LOSS OF BUSINESS PROFITS, BUSINESS INTERRUPTION, LOSS OF
* BUSINESS INFORMATION, OR ANY OTHER PECUNIARY LOSS) ARISING OUT OF THE USE OF OR
* INABILITY TO USE THIS SOFTWARE, EVEN IF NVIDIA HAS BEEN ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGES
*/
///
/// \file optix_primepp.h
/// \brief A C++ wrapper around the OptiX Prime API.
///
#ifndef __optix_optix_primepp_h__
#define __optix_optix_primepp_h__
#include <string>
#include <vector>
#include "optix_prime.h"
#include "internal/Handle.h"
namespace optix {
namespace prime {
/****************************************
*
* FORWARD DECLARATIONS
*
****************************************/
class BufferDescObj;
class ContextObj;
class ModelObj;
class QueryObj;
/****************************************
*
* HANDLE - TYPEDEFS
*
****************************************/
/// \ingroup optixprimepp
/// @{
typedef Handle<BufferDescObj> BufferDesc; ///< Use this to manipulate RTPbufferdesc objects.
typedef Handle<ContextObj> Context; ///< Use this to manipulate RTPcontext objects.
typedef Handle<ModelObj> Model; ///< Use this to manipulate RTPmodel objects.
typedef Handle<QueryObj> Query; ///< Use this to manipulate RTPquery objects.
/// @}
/****************************************
*
* GLOBAL FUNCTIONS
*
****************************************/
/// Returns a string describing the version of the OptiX Prime being used. See @ref rtpGetVersionString
std::string getVersionString();
/****************************************
*
* REFERENCE COUNTED API - OBJECTS
*
****************************************/
/// \ingroup optixprimepp
///
/// \brief Wraps the OptiX Prime C API @ref RTPcontext opaque type and its associated function set representing an OptiX Prime context.
///
class ContextObj : public RefCountedObj {
public:
//
// OBJECT CREATION - FUNCTIONS
//
/// Creates a Context object. See @ref rtpContextCreate
static Context create( RTPcontexttype type );
/// Creates a BufferDesc object. See @ref rtpBufferDescCreate
BufferDesc createBufferDesc( RTPbufferformat format, RTPbuffertype type, void* buffer );
/// Creates a Model object. See @ref rtpModelCreate
Model createModel();
//
// API-FUNCTIONS
//
/// Sets the CUDA devices used by a context. See @ref rtpContextSetCudaDeviceNumbers
void setCudaDeviceNumbers( const std::vector<unsigned>& deviceNumbers );
/// Sets the CUDA devices used by a context. See @ref rtpContextSetCudaDeviceNumbers
void setCudaDeviceNumbers( unsigned deviceCount, const unsigned* deviceNumbers );
/// Sets the number of CPU threads used by a CPU context. See @ref rtpContextSetCpuThreads
void setCpuThreads( unsigned numThreads );
/// Returns a string describing last error encountered. See @ref rtpContextGetLastErrorString
std::string getLastErrorString();
/// Returns the @ref RTPcontext context stored within this object.
RTPcontext getRTPcontext();
private:
friend class QueryObj;
friend class ModelObj;
friend class BufferDescObj;
Context getContext();
ContextObj( RTPcontexttype type );
~ContextObj();
operator Context();
RTPcontext m_ctx;
};
/// \ingroup optixprimepp
///
/// \brief Encapsulates an OptiX Prime buffer descriptor. The purpose of a buffer descriptor is to provide information about a buffer's type, format,
/// and location. It also describes the region of the buffer to use.
class BufferDescObj : public RefCountedObj {
public:
//
// API-FUNCTIONS
//
/// Returns the context associated within this object.
Context getContext();
/// Sets the range of a buffer to be used. See @ref rtpBufferDescSetRange
void setRange( RTPsize begin, RTPsize end );
/// Sets the stride for elements in a buffer. See @ref rtpBufferDescSetStride
void setStride( unsigned strideBytes );
/// Sets the CUDA device number for a buffer. See @ref rtpBufferDescSetCudaDeviceNumber
void setCudaDeviceNumber( unsigned deviceNumber );
/// Returns the @ref RTPbufferdesc descriptor stored within this object.
RTPbufferdesc getRTPbufferdesc();
private:
friend class ContextObj;
friend class ModelObj;
friend class QueryObj;
BufferDescObj( const Context& ctx, RTPbufferformat format, RTPbuffertype type, void* buffer );
~BufferDescObj();
RTPbufferdesc m_desc;
Context m_ctx;
};
/// \ingroup optixprimepp
///
/// \brief Encapsulates an OptiX Prime model. The purpose of a model is to represent a set of triangles and an acceleration structure.
class ModelObj : public RefCountedObj {
public:
//
// OBJECT CREATION - FUNCTIONS
//
/// Creates a Query object. See @ref rtpQueryCreate
Query createQuery( RTPquerytype queryType );
//
// API-FUNCTIONS
//
/// Returns the context associated within this object.
Context getContext();
/// Blocks current thread until model update is finished. See @ref rtpModelFinish
void finish();
/// Polls the status of a model update. See @ref rtpModelGetFinished
int isFinished();
/// Creates the acceleration structure over the triangles. See @ref rtpModelUpdate
void update( unsigned hints );
/// Copies one model to another. See @ref rtpModelCopy
void copy( const Model& srcModel );
/// Sets the triangle data for a model. This function creates a buffer descriptor of the specified type, populates it with the supplied data and assigns it to the model.
/// The list of vertices is assumed to be a flat list of triangles and each three vertices form a single triangle. See @ref rtpModelSetTriangles for additional information
void setTriangles( RTPsize triCount, RTPbuffertype type, const void* vertPtr, unsigned stride=0 );
/// Sets the triangle data for a model. This function creates buffer descriptors of the specified types, populates them with the supplied data and assigns them to the model.
/// The list of vertices uses the indices list to determine the triangles. See @ref rtpModelSetTriangles for additional information
void setTriangles( RTPsize triCount, RTPbuffertype type, const void* indexPtr, RTPsize vertCount, RTPbuffertype vertType, const void* vertPtr, unsigned stride=0 );
/// Sets the triangle data for a model using the supplied buffer descriptor of vertices. The list of vertices is assumed to be a flat list of triangles and each three vertices shape a single triangle.
/// See @ref rtpModelSetTriangles for additional information
void setTriangles( const BufferDesc& vertices );
/// Sets the triangle data for a model using the supplied buffer descriptor of vertices. The list of vertices uses the indices list to determine the triangles.
/// See @ref rtpModelSetTriangles for additional information
void setTriangles( const BufferDesc& indices, const BufferDesc& vertices );
/// Sets the instance data for a model. This function creates buffer descriptors of the specified types and formats, populates them with the supplied data and assigns them to the model.
/// See @ref rtpModelSetInstances for additional information
void setInstances(RTPsize count, RTPbuffertype instanceType, const RTPmodel* instanceList, RTPbufferformat transformFormat, RTPbuffertype transformType, const void* transformList);
/// Sets the instance data for a model using the supplied buffer descriptors.
/// See @ref rtpModelSetInstances for additional information
void setInstances( const BufferDesc& instances, const BufferDesc& transforms );
/// Sets a model build parameter
/// See @ref rtpModelSetBuilderParameter for additional information
void setBuilderParameter( RTPbuilderparam param, RTPsize size, const void* p );
/// Sets a model build parameter
/// See @ref rtpModelSetBuilderParameter for additional information
template<typename T>
void setBuilderParameter( RTPbuilderparam param, const T& val );
/// Returns the @ref RTPmodel model stored within this object.
RTPmodel getRTPmodel() { return m_model; }
private:
friend class ContextObj;
friend class QueryObj;
ModelObj( const Context& ctx );
~ModelObj();
operator Model();
Context m_ctx;
RTPmodel m_model;
};
/// \ingroup optixprimepp
///
/// \brief Encapsulates an OptiX Prime query. The purpose of a query is to coordinate the intersection of rays with a model.
class QueryObj : public RefCountedObj {
public:
//
// API-FUNCTIONS
//
/// Returns the context associated within this object.
Context getContext();
/// Blocks current thread until query is finished. See @ref rtpQueryFinish
void finish();
/// Polls the status of a query. See @ref rtpQueryGetFinished
int isFinished();
/// Sets a stream for a query. See @ref rtpQuerySetCudaStream
void setCudaStream( cudaStream_t stream );
/// Creates a buffer descriptor and sets the rays of a query. See @ref rtpQuerySetRays
void setRays( RTPsize count, RTPbufferformat format, RTPbuffertype type, void* rays );
/// Sets the rays of a query from a buffer descriptor. See @ref rtpQuerySetRays
void setRays( const BufferDesc& rays );
/// Sets a hit buffer for the query. See @ref rtpQuerySetHits
void setHits( RTPsize count, RTPbufferformat format, RTPbuffertype type, void* hits );
/// Sets a hit buffer for the query from a buffer description. See @ref rtpQuerySetHits
void setHits( const BufferDesc& hits );
/// Executes a raytracing query. See @ref rtpQueryExecute
void execute( unsigned hint );
/// Returns the @ref RTPquery query stored within this object.
RTPquery getRTPquery() { return m_query; }
private:
friend class ContextObj;
friend class ModelObj;
QueryObj( const Model& model, RTPquerytype queryType );
~QueryObj();
Model m_model;
RTPquery m_query;
};
/****************************************
*
* EXCEPTION
*
****************************************/
/// \ingroup optixprimepp
///
/// \brief Encapsulates an OptiX Prime exception.
class Exception : public std::exception {
public:
/// Returns a string describing last error encountered. See @ref rtpGetErrorString
static Exception makeException( RTPresult code );
/// Returns a string describing last error encountered. See @ref rtpContextGetLastErrorString
static Exception makeException( RTPresult code, RTPcontext context );
virtual ~Exception() throw() {}
/// Stores the @ref RTPresult error code for this exception
RTPresult getErrorCode() const;
/// Stores the human-readable error string associated with this exception
const std::string& getErrorString() const;
virtual const char* what() const throw();
private:
Exception( const std::string& message, RTPresult error_code = RTP_ERROR_UNKNOWN );
std::string m_errorMessage;
RTPresult m_errorCode;
};
///////////////////////////////////////////////////////////////////////////////
// //
// IMPLEMENTATION //
// //
///////////////////////////////////////////////////////////////////////////////
//
// HELPER - FUNCTIONS AND MACROS
//
///
void checkError( RTPresult code );
void checkError( RTPresult code, RTPcontext context );
#define CHK( code ) checkError( code, getContext()->getRTPcontext() )
//
// GLOBALS
//
inline std::string getVersionString()
{
const char* versionString;
checkError( rtpGetVersionString( &versionString ) );
return versionString;
}
//
// CONTEXT
//
inline Context ContextObj::create( RTPcontexttype type )
{
Context h( new ContextObj(type) );
return h;
}
inline BufferDesc ContextObj::createBufferDesc( RTPbufferformat format, RTPbuffertype type, void* buffer )
{
BufferDesc h( new BufferDescObj(*this, format, type, buffer) );
return h;
}
inline Model ContextObj::createModel()
{
Model h( new ModelObj(*this) );
return h;
}
inline ContextObj::ContextObj( RTPcontexttype type ) : m_ctx(0) {
RTPresult r = rtpContextCreate( type, &m_ctx );
if( r!=RTP_SUCCESS )
m_ctx = 0;
checkError( r, m_ctx );
}
inline ContextObj::~ContextObj() {
if( m_ctx ) {
RTPresult r = rtpContextDestroy( m_ctx );
if( r!=RTP_SUCCESS )
m_ctx = 0;
}
}
inline void ContextObj::setCudaDeviceNumbers( const std::vector<unsigned>& deviceNumbers )
{
if( deviceNumbers.size()==0 ) {
CHK( rtpContextSetCudaDeviceNumbers(m_ctx, 0, NULL) );
} else {
CHK( rtpContextSetCudaDeviceNumbers(m_ctx, (unsigned int)deviceNumbers.size(), &deviceNumbers[0]) );
}
}
inline void ContextObj::setCudaDeviceNumbers( unsigned deviceCount, const unsigned* deviceNumbers )
{
CHK( rtpContextSetCudaDeviceNumbers(m_ctx, deviceCount, deviceNumbers) );
}
inline void ContextObj::setCpuThreads( unsigned numThreads )
{
CHK( rtpContextSetCpuThreads(m_ctx, numThreads) );
}
inline std::string ContextObj::getLastErrorString()
{
const char* str;
rtpContextGetLastErrorString( m_ctx, &str );
return str;
}
inline RTPcontext ContextObj::getRTPcontext()
{
return m_ctx;
}
inline ContextObj::operator Context()
{
Context context( this ); context->ref();
return context;
}
inline Context ContextObj::getContext()
{
return Context( *this );
}
//
// BUFFERDESC
//
inline BufferDescObj::BufferDescObj( const Context& ctx, RTPbufferformat format, RTPbuffertype type, void* buffer ) : m_desc(0) {
m_ctx = ctx;
CHK( rtpBufferDescCreate(m_ctx->getRTPcontext(), format, type, buffer, &m_desc) );
}
inline BufferDescObj::~BufferDescObj() {
if( m_desc ) {
rtpBufferDescDestroy(m_desc);
}
}
inline Context BufferDescObj::getContext()
{
return m_ctx;
}
inline void BufferDescObj::setRange( RTPsize begin, RTPsize end )
{
CHK( rtpBufferDescSetRange(m_desc, begin, end) );
}
inline void BufferDescObj::setStride( unsigned strideBytes )
{
CHK( rtpBufferDescSetStride(m_desc, strideBytes) );
}
inline void BufferDescObj::setCudaDeviceNumber( unsigned deviceNumber )
{
CHK( rtpBufferDescSetCudaDeviceNumber(m_desc, deviceNumber) );
}
inline RTPbufferdesc BufferDescObj::getRTPbufferdesc()
{
return m_desc;
}
//
// MODEL
//
inline ModelObj::ModelObj( const Context& ctx ) : m_model(0) {
m_ctx = ctx;
CHK( rtpModelCreate(m_ctx->getRTPcontext(), &m_model) );
}
inline ModelObj::~ModelObj() {
if( m_model ) {
rtpModelDestroy(m_model);
}
}
inline Context ModelObj::getContext()
{
return m_ctx;
}
inline void ModelObj::setTriangles( const BufferDesc& indices, const BufferDesc& vertices )
{
if( indices.isValid() ) {
CHK( rtpModelSetTriangles(m_model, indices->getRTPbufferdesc(), vertices->getRTPbufferdesc()) );
} else {
CHK( rtpModelSetTriangles(m_model, 0, vertices->getRTPbufferdesc()) );
}
}
inline void ModelObj::setTriangles( const BufferDesc& vertices )
{
CHK( rtpModelSetTriangles(m_model, 0, vertices->getRTPbufferdesc()) );
}
inline void ModelObj::setTriangles( RTPsize triCount, RTPbuffertype type, const void* vertPtr, unsigned stride/*=0 */ )
{
BufferDesc vtxBufDesc( m_ctx->createBufferDesc(RTP_BUFFER_FORMAT_VERTEX_FLOAT3, type, const_cast<void*>( vertPtr ) ) );
vtxBufDesc->setRange( 0, 3*triCount );
if( stride ) {
vtxBufDesc->setStride( stride );
}
BufferDesc idxBufDesc;
setTriangles( idxBufDesc, vtxBufDesc );
}
inline void ModelObj::setTriangles( RTPsize triCount, RTPbuffertype indexType, const void* indexPtr, RTPsize vertCount, RTPbuffertype vertType, const void* vertPtr, unsigned stride/*=0 */ )
{
BufferDesc idxBufDesc( m_ctx->createBufferDesc(RTP_BUFFER_FORMAT_INDICES_INT3, indexType, const_cast<void*>( indexPtr ) ) );
BufferDesc vtxBufDesc( m_ctx->createBufferDesc(RTP_BUFFER_FORMAT_VERTEX_FLOAT3, vertType, const_cast<void*>( vertPtr ) ) );
idxBufDesc->setRange( 0, triCount );
vtxBufDesc->setRange( 0, vertCount );
if( stride ) {
vtxBufDesc->setStride( stride );
}
setTriangles( idxBufDesc, vtxBufDesc );
}
inline void ModelObj::setInstances(RTPsize count, RTPbuffertype instanceType, const RTPmodel* instanceList, RTPbufferformat transformFormat, RTPbuffertype transformType, const void* transformList)
{
BufferDesc instances(m_ctx->createBufferDesc(RTP_BUFFER_FORMAT_INSTANCE_MODEL, instanceType, const_cast<RTPmodel*>(instanceList)));
instances->setRange(0, count);
BufferDesc transforms(m_ctx->createBufferDesc(transformFormat, transformType, const_cast<void*>(transformList)));
transforms->setRange(0, count);
CHK(rtpModelSetInstances(m_model, instances->getRTPbufferdesc(), transforms->getRTPbufferdesc()));
}
inline void ModelObj::setInstances( const BufferDesc& instances, const BufferDesc& transforms )
{
CHK( rtpModelSetInstances(m_model, instances->getRTPbufferdesc(), transforms->getRTPbufferdesc()) );
}
inline void ModelObj::update( unsigned hints )
{
CHK( rtpModelUpdate(m_model, hints) );
}
inline void ModelObj::finish()
{
CHK( rtpModelFinish(m_model) );
}
inline int ModelObj::isFinished()
{
int finished = 0;
CHK( rtpModelGetFinished(m_model, &finished) );
return finished;
}
inline void ModelObj::copy( const Model& srcModel )
{
CHK( rtpModelCopy(m_model, srcModel->getRTPmodel()) );
}
inline ModelObj::operator Model()
{
Model model( this ); model->ref();
return model;
}
inline Query ModelObj::createQuery( RTPquerytype queryType )
{
Query h( new QueryObj(*this, queryType) );
return h;
}
inline void ModelObj::setBuilderParameter( RTPbuilderparam param, RTPsize size, const void* p )
{
CHK( rtpModelSetBuilderParameter(m_model, param, size, p) );
}
template<typename T>
void optix::prime::ModelObj::setBuilderParameter( RTPbuilderparam param, const T& val )
{
setBuilderParameter( param, sizeof(T), &val );
}
//
// QUERY
//
inline QueryObj::QueryObj( const Model& model, RTPquerytype queryType ) : m_query(0) {
m_model = model;
CHK( rtpQueryCreate(model->getRTPmodel(), queryType, &m_query) );
}
inline QueryObj::~QueryObj() {
if( m_query ) {
rtpQueryDestroy(m_query);
}
}
inline Context QueryObj::getContext()
{
return m_model->getContext();
}
inline void QueryObj::setRays( const BufferDesc& rays )
{
CHK( rtpQuerySetRays(m_query, rays->getRTPbufferdesc()) );
}
inline void QueryObj::setRays( RTPsize count, RTPbufferformat format, RTPbuffertype type, void* rays )
{
BufferDesc desc(m_model->m_ctx->createBufferDesc(format, type, rays) );
desc->setRange( 0, count );
setRays( desc );
}
inline void QueryObj::setHits( const BufferDesc& hits )
{
CHK( rtpQuerySetHits(m_query, hits->getRTPbufferdesc()) );
}
inline void QueryObj::setHits( RTPsize count, RTPbufferformat format, RTPbuffertype type, void* hits )
{
BufferDesc desc(m_model->m_ctx->createBufferDesc(format, type, hits) );
desc->setRange( 0, count );
setHits( desc );
}
inline void QueryObj::execute( unsigned hint )
{
CHK( rtpQueryExecute(m_query, hint) );
}
inline void QueryObj::finish()
{
CHK( rtpQueryFinish(m_query) );
}
inline int QueryObj::isFinished()
{
int finished = 0;
CHK( rtpQueryGetFinished(m_query, &finished) );
return finished;
}
inline void QueryObj::setCudaStream( cudaStream_t stream )
{
CHK( rtpQuerySetCudaStream(m_query, stream) );
}
//
// EXCEPTION
//
inline Exception Exception::makeException( RTPresult code )
{
const char* str;
rtpGetErrorString( code, &str );
Exception h( std::string(str), code );
return h;
}
inline Exception Exception::makeException( RTPresult code, RTPcontext ctx )
{
const char* str;
rtpContextGetLastErrorString( ctx, &str );
Exception h( std::string(str), code );
return h;
}
inline Exception::Exception( const std::string& message, RTPresult error_code )
: m_errorMessage(message), m_errorCode( error_code )
{
}
inline RTPresult Exception::getErrorCode() const
{
return m_errorCode;
}
inline const std::string& Exception::getErrorString() const
{
return m_errorMessage;
}
inline const char* Exception::what() const throw()
{
return m_errorMessage.c_str();
}
//
// HELPER - FUNCTIONS
//
inline void checkError( RTPresult code )
{
if( code != RTP_SUCCESS ) {
throw Exception::makeException( code );
}
}
inline void checkError( RTPresult code, RTPcontext context )
{
if( code != RTP_SUCCESS ) {
throw Exception::makeException( code, context );
}
}
} // end namespace prime
} // end namespace optix
#endif // #ifndef __optix_optix_primepp_h__
| 31.412869 | 206 | 0.643381 |
bdb243aa7311a27ed9ecb65177262dc0aad2ecc1 | 10,441 | h | C | richtext/rich_textui.h | Lys0gen/Urho3D-RichText3D | df1e9d98321dfd329fb89c0b340fa2de20a76e00 | [
"MIT"
] | 1 | 2021-04-03T22:41:59.000Z | 2021-04-03T22:41:59.000Z | richtext/rich_textui.h | Lys0gen/Urho3D-RichText3D | df1e9d98321dfd329fb89c0b340fa2de20a76e00 | [
"MIT"
] | null | null | null | richtext/rich_textui.h | Lys0gen/Urho3D-RichText3D | df1e9d98321dfd329fb89c0b340fa2de20a76e00 | [
"MIT"
] | 1 | 2021-11-07T14:50:46.000Z | 2021-11-07T14:50:46.000Z | #ifndef __RICH_TEXT_UI_H__
#define __RICH_TEXT_UI_H__
#pragma once
#include "rich_widget.h"
#include "../UI/UIElement.h"
namespace Urho3D {
/// %RichText %UI element.
class URHO3D_API RichTextUI : public UIElement//, public RichWidget
{
URHO3D_OBJECT(RichTextUI, UIElement);
friend class Text3D;
public:
/// Construct.
explicit RichTextUI(Context* context);
/// Destruct.
~RichTextUI() override;
/// Register object factory.
static void RegisterObject(Context* context);
/// Apply attribute changes that can not be applied immediately.
void ApplyAttributes() override;
/// Return UI rendering batches.
void GetBatches(PODVector<UIBatch>& batches, PODVector<float>& vertexData, const IntRect& currentScissor) override;
/// React to resize.
void OnResize(const IntVector2& newSize, const IntVector2& delta) override;
/// React to indent change.
void OnIndentSet() override;
/// Set font by looking from resource cache by name and font size. Return true if successful.
bool SetFont(const String& fontName, float size = DEFAULT_FONT_SIZE);
/// Set font and font size. Return true if successful.
//bool SetFont(Font* font, float size = DEFAULT_FONT_SIZE);
/// Set font size only while retaining the existing font. Return true if successful.
bool SetFontSize(float size);
/// Set text. Text is assumed to be either ASCII or UTF8-encoded.
void SetText(const String& text);
/// Set row alignment.
void SetTextAlignment(HorizontalAlignment align);
/// Set row spacing, 1.0 for original font spacing.
void SetRowSpacing(float spacing);
/// Set wordwrap. In wordwrap mode the text element will respect its current width. Otherwise it resizes itself freely.
//void SetWordwrap(bool enable);
/// The text will be automatically translated. The text value used as string identifier.
void SetAutoLocalizable(bool enable);
/// Set selection. When length is not provided, select until the text ends.
void SetSelection(unsigned start, unsigned length = M_MAX_UNSIGNED);
/// Clear selection.
void ClearSelection();
/// Set text effect.
void SetTextEffect(TextEffect textEffect);
/// Set shadow offset.
void SetEffectShadowOffset(const IntVector2& offset);
/// Set stroke thickness.
void SetEffectStrokeThickness(int thickness);
/// Set stroke rounding. Corners of the font will be rounded off in the stroke so the stroke won't have corners.
void SetEffectRoundStroke(bool roundStroke);
/// Set effect color.
void SetEffectColor(const Color& effectColor);
/// Return font.
//Font* GetFont() const { return font_; }
String GetFontName() const { return default_format_.font.face; }
/// Return font size.
float GetFontSize() const { return default_format_.font.size; }
/// Return text.
const String& GetText() const { return text_; }
/// Return row alignment.
HorizontalAlignment GetTextAlignment() const { return default_format_.align; }
/// Return row spacing.
float GetRowSpacing() const { return rowSpacing_; }
/// Return wordwrap mode.
//bool GetWordwrap() const { return wordWrap_; }
/// Return auto localizable mode.
bool GetAutoLocalizable() const { return autoLocalizable_; }
/// Return selection start.
unsigned GetSelectionStart() const { return selectionStart_; }
/// Return selection length.
unsigned GetSelectionLength() const { return selectionLength_; }
/// Return text effect.
TextEffect GetTextEffect() const { return textEffect_; }
/// Return effect shadow offset.
const IntVector2& GetEffectShadowOffset() const { return shadowOffset_; }
/// Return effect stroke thickness.
int GetEffectStrokeThickness() const { return strokeThickness_; }
/// Return effect round stroke.
bool GetEffectRoundStroke() const { return roundStroke_; }
/// Return effect color.
const Color& GetEffectColor() const { return effectColor_; }
/// Return row height.
float GetRowHeight() const { return rowHeight_; }
/// Return number of rows.
unsigned GetNumRows() const { return rowWidths_.Size(); }
/// Return number of characters.
unsigned GetNumChars() const { return unicodeText_.Size(); }
/// Return width of row by index.
float GetRowWidth(unsigned index) const;
/// Return position of character by index relative to the text element origin.
Vector2 GetCharPosition(unsigned index);
/// Return size of character by index.
Vector2 GetCharSize(unsigned index);
/// Set text effect Z bias. Zero by default, adjusted only in 3D mode.
void SetEffectDepthBias(float bias);
/// Return effect Z bias.
float GetEffectDepthBias() const { return effectDepthBias_; }
/// Set font attribute.
void SetFontAttr(const ResourceRef& value);
/// Return font attribute.
ResourceRef GetFontAttr() const;
/// Set text attribute.
void SetTextAttr(const String& value);
/// Return text attribute.
String GetTextAttr() const;
//####RichText3D####//
/// Set text color.
void SetTextColor(const Color& color);
/// Get text color.
Color GetTextColor() const { return default_format_.color; }
/// Set text alignment.
//void SetAlignment(HorizontalAlignment align);
/// Get text alignment.
//HorizontalAlignment GetAlignment() const { return default_format_.align; }
/// Set additional line spacing (can be negative).
void SetLineSpacing(int line_spacing);
/// Get additional line spacing.
int GetLineSpacing() const { return line_spacing_; }
/// Set word wrapping.
void SetWrapping(bool wrapping);
/// Get wrapping.
bool GetWrapping() const { return wrapping_ == WRAP_WORD; }
/// Set auto sizing.
void SetAutoSize(bool autoSizing);
/// Get auto sizing.
bool GetAutoSize() const { return autoSize_; }
/// Set ticker type.
//void SetTickerType(TickerType type);
/// Get ticker type.
//TickerType GetTickerType() const;
/// Set ticker scroll direction.
//void SetTickerDirection(TickerDirection direction);
/// Get ticker scroll direction.
//TickerDirection GetTickerDirection() const;
/// Set ticker scroll speed.
//void SetTickerSpeed(float pixelspersecond);
/// Get ticker scroll speed.
//float GetTickerSpeed() const;
/// Set single line.
void SetSingleLine(bool single_line);
/// Get single line.
bool GetSingleLine() const { return single_line_; }
/// Reset the ticker to the beginning.
//void ResetTicker();
/// Set ticker position (0-1 range).
void SetTickerPosition(float tickerPosition);
/// Get ticker position (0-1 range).
float GetTickerPosition() const;
/// Get font size.
int GetFontSizeAttr() const;
//##################//
protected:
/// Filter implicit attributes in serialization process.
bool FilterImplicitAttributes(XMLElement& dest) const override;
/// Update text when text, font or spacing changed.
void UpdateText(bool onResize = false);
/// Update cached character locations after text update, or when text alignment or indent has changed.
void UpdateCharLocations();
/// Validate text selection to be within the text.
void ValidateSelection();
/// Return row start X position.
int GetRowStartPosition(unsigned rowIndex) const;
/// Construct batch.
//void ConstructBatch
// (UIBatch& pageBatch, const PODVector<GlyphLocation>& pageGlyphLocation, float dx = 0, float dy = 0, Color* color = nullptr,
// float depthBias = 0.0f);
/// Rich Widget
SharedPtr<RichWidget> widget_;
/// Font.
//SharedPtr<Font> font_;
/// Current face.
//WeakPtr<FontFace> fontFace_;
/// Font size.
//float fontSize_;
/// UTF-8 encoded text.
String text_;
/// Row alignment.
//HorizontalAlignment textAlignment_;
/// Row spacing.
float rowSpacing_;
/// Wordwrap mode.
//bool wordWrap_;
/// Char positions dirty flag.
bool charLocationsDirty_;
/// Automatic resizing attribute.
bool autoSize_;
/// Selection start.
unsigned selectionStart_;
/// Selection length.
unsigned selectionLength_;
/// Text effect.
TextEffect textEffect_;
/// Text effect shadow offset.
IntVector2 shadowOffset_;
/// Text effect stroke thickness.
int strokeThickness_;
/// Text effect stroke rounding flag.
bool roundStroke_;
/// Effect color.
Color effectColor_;
/// Text effect Z bias.
float effectDepthBias_;
/// Row height.
float rowHeight_;
/// Text as Unicode characters.
PODVector<unsigned> unicodeText_;
/// Text modified into printed form.
PODVector<unsigned> printText_;
/// Mapping of printed form back to original char indices.
PODVector<unsigned> printToText_;
/// Row widths.
PODVector<float> rowWidths_;
/// Glyph locations per each texture in the font.
Vector<PODVector<GlyphLocation> > pageGlyphLocations_;
/// Cached locations of each character in the text.
PODVector<CharLocation> charLocations_;
/// The text will be automatically translated.
bool autoLocalizable_;
/// Localization string id storage. Used when autoLocalizable flag is set.
String stringId_;
/// Handle change Language.
void HandleChangeLanguage(StringHash eventType, VariantMap& eventData);
/// UTF8 to Unicode.
void DecodeToUnicode();
//####RichText3D####//
/// Additional line spacing (can be negative).
int line_spacing_;
/// Ticker type.
//TickerType ticker_type_;
/// Ticker direction.
//TickerDirection ticker_direction_;
/// Ticker speed.
//float ticker_speed_;
/// Default font state for unformatted text.
BlockFormat default_format_;
/// The lines of text.
Vector<TextLine> lines_; // TODO: could be removed in the future.
/// The scroll origin of the text (in ticker mode).
Vector3 scroll_origin_;
/// Is the text single line.
bool single_line_;
/// Ticker position (0-1).
//float ticker_position_;
/// Wrapping
TextWrapping wrapping_;
/// Per-frame text animation.
//void UpdateTickerAnimation(Urho3D::StringHash eventType, Urho3D::VariantMap& eventData);
//##################//
};
} // namespace Urho3D
#endif
| 34.009772 | 133 | 0.685183 |
93a8969faf715b83bd73fdc0578dc97209d6b15c | 7,467 | h | C | src/base/SIMD_SSE2.h | zeux/suslix | 327b6c968752663fd104fed1824ba14f248cb197 | [
"MIT"
] | 95 | 2015-04-21T08:00:26.000Z | 2022-03-04T16:40:26.000Z | src/base/SIMD_SSE2.h | zeux/suslix | 327b6c968752663fd104fed1824ba14f248cb197 | [
"MIT"
] | 2 | 2018-06-02T03:34:03.000Z | 2020-05-24T07:44:42.000Z | src/base/SIMD_SSE2.h | zeux/suslix | 327b6c968752663fd104fed1824ba14f248cb197 | [
"MIT"
] | 9 | 2016-08-29T05:02:47.000Z | 2021-06-24T11:05:19.000Z | #pragma once
namespace simd
{
struct V4f
{
__m128 v;
SIMD_INLINE V4f()
{
}
SIMD_INLINE V4f(__m128 v): v(v)
{
}
SIMD_INLINE operator __m128() const
{
return v;
}
SIMD_INLINE static V4f zero()
{
return _mm_setzero_ps();
}
SIMD_INLINE static V4f one(float v)
{
return _mm_set1_ps(v);
}
SIMD_INLINE static V4f sign()
{
return _mm_castsi128_ps(_mm_set1_epi32(0x80000000));
}
SIMD_INLINE static V4f load(const float* ptr)
{
return _mm_load_ps(ptr);
}
};
struct V4i
{
__m128i v;
SIMD_INLINE V4i()
{
}
SIMD_INLINE V4i(__m128i v): v(v)
{
}
SIMD_INLINE operator __m128i() const
{
return v;
}
SIMD_INLINE static V4i zero()
{
return _mm_setzero_si128();
}
SIMD_INLINE static V4i one(int v)
{
return _mm_set1_epi32(v);
}
SIMD_INLINE static V4i load(const int* ptr)
{
return _mm_load_si128(reinterpret_cast<const __m128i*>(ptr));
}
};
struct V4b
{
__m128 v;
SIMD_INLINE V4b()
{
}
SIMD_INLINE V4b(__m128 v): v(v)
{
}
SIMD_INLINE V4b(__m128i v): v(_mm_castsi128_ps(v))
{
}
SIMD_INLINE operator __m128() const
{
return v;
}
SIMD_INLINE static V4b zero()
{
return _mm_setzero_ps();
}
};
SIMD_INLINE V4f bitcast(V4i v)
{
return _mm_castsi128_ps(v.v);
}
SIMD_INLINE V4i bitcast(V4f v)
{
return _mm_castps_si128(v.v);
}
SIMD_INLINE V4f operator+(V4f v)
{
return v;
}
SIMD_INLINE V4f operator-(V4f v)
{
return _mm_xor_ps(V4f::sign(), v.v);
}
SIMD_INLINE V4f operator+(V4f l, V4f r)
{
return _mm_add_ps(l.v, r.v);
}
SIMD_INLINE V4f operator-(V4f l, V4f r)
{
return _mm_sub_ps(l.v, r.v);
}
SIMD_INLINE V4f operator*(V4f l, V4f r)
{
return _mm_mul_ps(l.v, r.v);
}
SIMD_INLINE V4f operator/(V4f l, V4f r)
{
return _mm_div_ps(l.v, r.v);
}
SIMD_INLINE void operator+=(V4f& l, V4f r)
{
l.v = _mm_add_ps(l.v, r.v);
}
SIMD_INLINE void operator-=(V4f& l, V4f r)
{
l.v = _mm_sub_ps(l.v, r.v);
}
SIMD_INLINE void operator*=(V4f& l, V4f r)
{
l.v = _mm_mul_ps(l.v, r.v);
}
SIMD_INLINE void operator/=(V4f& l, V4f r)
{
l.v = _mm_div_ps(l.v, r.v);
}
SIMD_INLINE V4b operator==(V4f l, V4f r)
{
return _mm_cmpeq_ps(l.v, r.v);
}
SIMD_INLINE V4b operator==(V4i l, V4i r)
{
return _mm_cmpeq_epi32(l.v, r.v);
}
SIMD_INLINE V4b operator!=(V4f l, V4f r)
{
return _mm_cmpneq_ps(l.v, r.v);
}
SIMD_INLINE V4b operator!=(V4i l, V4i r)
{
return _mm_xor_si128(_mm_setzero_si128(), _mm_cmpeq_epi32(l.v, r.v));
}
SIMD_INLINE V4b operator<(V4f l, V4f r)
{
return _mm_cmplt_ps(l.v, r.v);
}
SIMD_INLINE V4b operator<(V4i l, V4i r)
{
return _mm_cmplt_epi32(l.v, r.v);
}
SIMD_INLINE V4b operator<=(V4f l, V4f r)
{
return _mm_cmple_ps(l.v, r.v);
}
SIMD_INLINE V4b operator<=(V4i l, V4i r)
{
return _mm_xor_si128(_mm_setzero_si128(), _mm_cmplt_epi32(r.v, l.v));
}
SIMD_INLINE V4b operator>(V4f l, V4f r)
{
return _mm_cmpgt_ps(l.v, r.v);
}
SIMD_INLINE V4b operator>(V4i l, V4i r)
{
return _mm_cmpgt_epi32(l.v, r.v);
}
SIMD_INLINE V4b operator>=(V4f l, V4f r)
{
return _mm_cmpge_ps(l.v, r.v);
}
SIMD_INLINE V4b operator>=(V4i l, V4i r)
{
return _mm_xor_si128(_mm_setzero_si128(), _mm_cmplt_epi32(l.v, r.v));
}
SIMD_INLINE V4b operator!(V4b v)
{
return _mm_xor_ps(_mm_setzero_ps(), v.v);
}
SIMD_INLINE V4b operator&(V4b l, V4b r)
{
return _mm_and_ps(l.v, r.v);
}
SIMD_INLINE V4b operator|(V4b l, V4b r)
{
return _mm_or_ps(l.v, r.v);
}
SIMD_INLINE V4b operator^(V4b l, V4b r)
{
return _mm_xor_ps(l.v, r.v);
}
SIMD_INLINE void operator&=(V4b& l, V4b r)
{
l.v = _mm_and_ps(l.v, r.v);
}
SIMD_INLINE void operator|=(V4b& l, V4b r)
{
l.v = _mm_or_ps(l.v, r.v);
}
SIMD_INLINE void operator^=(V4b l, V4b r)
{
l.v = _mm_xor_ps(l.v, r.v);
}
SIMD_INLINE V4f abs(V4f v)
{
return _mm_andnot_ps(V4f::sign(), v.v);
}
SIMD_INLINE V4f copysign(V4f x, V4f y)
{
V4f sign = V4f::sign();
return _mm_or_ps(_mm_andnot_ps(sign.v, x.v), _mm_and_ps(y.v, sign.v));
}
SIMD_INLINE V4f flipsign(V4f x, V4f y)
{
return _mm_xor_ps(x.v, _mm_and_ps(y.v, V4f::sign()));
}
SIMD_INLINE V4f min(V4f l, V4f r)
{
return _mm_min_ps(l.v, r.v);
}
SIMD_INLINE V4f max(V4f l, V4f r)
{
return _mm_max_ps(l.v, r.v);
}
SIMD_INLINE V4f select(V4f l, V4f r, V4b m)
{
return _mm_or_ps(_mm_andnot_ps(m.v, l.v), _mm_and_ps(r.v, m.v));
}
SIMD_INLINE V4i select(V4i l, V4i r, V4b m)
{
__m128i mi = _mm_castps_si128(m.v);
return _mm_or_si128(_mm_andnot_si128(mi, l.v), _mm_and_si128(r.v, mi));
}
SIMD_INLINE bool none(V4b v)
{
return _mm_movemask_ps(v.v) == 0;
}
SIMD_INLINE bool any(V4b v)
{
return _mm_movemask_ps(v.v) != 0;
}
SIMD_INLINE bool all(V4b v)
{
return _mm_movemask_ps(v.v) == 15;
}
SIMD_INLINE void store(V4f v, float* ptr)
{
_mm_store_ps(ptr, v.v);
}
SIMD_INLINE void store(V4i v, int* ptr)
{
_mm_store_si128(reinterpret_cast<__m128i*>(ptr), v.v);
}
SIMD_INLINE void loadindexed4(V4f& v0, V4f& v1, V4f& v2, V4f& v3, const void* base, const int indices[4], unsigned int stride)
{
const char* ptr = static_cast<const char*>(base);
__m128 r0 = _mm_load_ps(reinterpret_cast<const float*>(ptr + indices[0] * stride));
__m128 r1 = _mm_load_ps(reinterpret_cast<const float*>(ptr + indices[1] * stride));
__m128 r2 = _mm_load_ps(reinterpret_cast<const float*>(ptr + indices[2] * stride));
__m128 r3 = _mm_load_ps(reinterpret_cast<const float*>(ptr + indices[3] * stride));
_MM_TRANSPOSE4_PS(r0, r1, r2, r3);
v0.v = r0;
v1.v = r1;
v2.v = r2;
v3.v = r3;
}
SIMD_INLINE void storeindexed4(const V4f& v0, const V4f& v1, const V4f& v2, const V4f& v3, void* base, const int indices[4], unsigned int stride)
{
char* ptr = static_cast<char*>(base);
__m128 r0 = v0.v;
__m128 r1 = v1.v;
__m128 r2 = v2.v;
__m128 r3 = v3.v;
_MM_TRANSPOSE4_PS(r0, r1, r2, r3);
_mm_store_ps(reinterpret_cast<float*>(ptr + indices[0] * stride), r0);
_mm_store_ps(reinterpret_cast<float*>(ptr + indices[1] * stride), r1);
_mm_store_ps(reinterpret_cast<float*>(ptr + indices[2] * stride), r2);
_mm_store_ps(reinterpret_cast<float*>(ptr + indices[3] * stride), r3);
}
SIMD_INLINE void loadindexed8(V4f& v0, V4f& v1, V4f& v2, V4f& v3, V4f& v4, V4f& v5, V4f& v6, V4f& v7, const void* base, const int indices[4], unsigned int stride)
{
const char* ptr = static_cast<const char*>(base);
const float* ptr0 = reinterpret_cast<const float*>(ptr + indices[0] * stride);
const float* ptr1 = reinterpret_cast<const float*>(ptr + indices[1] * stride);
const float* ptr2 = reinterpret_cast<const float*>(ptr + indices[2] * stride);
const float* ptr3 = reinterpret_cast<const float*>(ptr + indices[3] * stride);
__m128 r0 = _mm_load_ps(ptr0 + 0);
__m128 r1 = _mm_load_ps(ptr1 + 0);
__m128 r2 = _mm_load_ps(ptr2 + 0);
__m128 r3 = _mm_load_ps(ptr3 + 0);
__m128 r4 = _mm_load_ps(ptr0 + 4);
__m128 r5 = _mm_load_ps(ptr1 + 4);
__m128 r6 = _mm_load_ps(ptr2 + 4);
__m128 r7 = _mm_load_ps(ptr3 + 4);
_MM_TRANSPOSE4_PS(r0, r1, r2, r3);
_MM_TRANSPOSE4_PS(r4, r5, r6, r7);
v0.v = r0;
v1.v = r1;
v2.v = r2;
v3.v = r3;
v4.v = r4;
v5.v = r5;
v6.v = r6;
v7.v = r7;
}
}
namespace simd
{
template <> struct VNf_<4> { typedef V4f type; };
template <> struct VNi_<4> { typedef V4i type; };
template <> struct VNb_<4> { typedef V4b type; };
}
using simd::V4f;
using simd::V4i;
using simd::V4b;
| 18.761307 | 163 | 0.64631 |
fabc2739b0f0ea75ccc133677ef753db14823fa7 | 185 | c | C | compiler/work/intermediate.c | jayaraj-poroor/verticalthings | 1e153ef61bcb4e3af45894c39961ae468e58706c | [
"MIT"
] | 2 | 2018-09-04T02:38:14.000Z | 2018-09-05T17:12:44.000Z | compiler/work/intermediate.c | jayaraj-poroor/verticalthings | 1e153ef61bcb4e3af45894c39961ae468e58706c | [
"MIT"
] | 1 | 2021-03-08T20:03:12.000Z | 2021-03-08T20:03:12.000Z | compiler/work/intermediate.c | jayarajporoor/verticalthings | 1e153ef61bcb4e3af45894c39961ae468e58706c | [
"MIT"
] | 1 | 2018-09-30T14:17:49.000Z | 2018-09-30T14:17:49.000Z | res_vector[i] = matrix[i,.] * vector;
for i in {
sum=0;
loop(j)
sum+= matrix[i][j] * vector[j]
res_vector[i] = sum;
}
loop(i) {
res += res_vector[i] * model_vec[i];
}
| 14.230769 | 38 | 0.540541 |
3687cae25867fd2355efbc79cea802ab26f316cd | 4,048 | h | C | src/primitives/pureheader.h | arseneum/arseneum | feb67a087cbb396b95c1c081ec61dc7a590b59ce | [
"MIT"
] | 1 | 2020-01-24T00:00:41.000Z | 2020-01-24T00:00:41.000Z | src/primitives/pureheader.h | arseneum/arseneum | feb67a087cbb396b95c1c081ec61dc7a590b59ce | [
"MIT"
] | null | null | null | src/primitives/pureheader.h | arseneum/arseneum | feb67a087cbb396b95c1c081ec61dc7a590b59ce | [
"MIT"
] | 3 | 2017-05-15T15:36:11.000Z | 2018-06-20T04:19:14.000Z | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2013 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#ifndef BITCOIN_PRIMITIVES_PUREHEADER_H
#define BITCOIN_PRIMITIVES_PUREHEADER_H
#include "serialize.h"
#include "uint256.h"
/**
* A block header without auxpow information. This "intermediate step"
* in constructing the full header is useful, because it breaks the cyclic
* dependency between auxpow (referencing a parent block header) and
* the block header (referencing an auxpow). The parent block header
* does not have auxpow itself, so it is a pure header.
*/
class CPureBlockHeader
{
private:
/* Modifiers to the version. */
static const int32_t VERSION_AUXPOW = (1 << 8);
/** Bits above are reserved for the auxpow chain ID. */
static const int32_t VERSION_CHAIN_START = (1 << 16);
public:
// header
int32_t nVersion;
uint256 hashPrevBlock;
uint256 hashMerkleRoot;
uint32_t nTime;
uint32_t nBits;
uint32_t nNonce;
CPureBlockHeader()
{
SetNull();
}
ADD_SERIALIZE_METHODS;
template <typename Stream, typename Operation>
inline void SerializationOp(Stream& s, Operation ser_action) {
READWRITE(this->nVersion);
READWRITE(hashPrevBlock);
READWRITE(hashMerkleRoot);
READWRITE(nTime);
READWRITE(nBits);
READWRITE(nNonce);
}
void SetNull()
{
nVersion = 0;
hashPrevBlock.SetNull();
hashMerkleRoot.SetNull();
nTime = 0;
nBits = 0;
nNonce = 0;
}
bool IsNull() const
{
return (nBits == 0);
}
uint256 GetHash() const;
int64_t GetBlockTime() const
{
return (int64_t)nTime;
}
/* Below are methods to interpret the version with respect to
auxpow data and chain ID. This used to be in the CBlockVersion
class, but was moved here when we switched back to nVersion being
a pure int member as preparation to undoing the "abuse" and
allowing BIP9 to work. */
/**
* Extract the base version (without modifiers and chain ID).
* @return The base version./
*/
inline int32_t GetBaseVersion() const
{
return GetBaseVersion(nVersion);
}
static inline int32_t GetBaseVersion(int32_t ver)
{
return ver % VERSION_AUXPOW;
}
/**
* Set the base version (apart from chain ID and auxpow flag) to
* the one given. This should only be called when auxpow is not yet
* set, to initialise a block!
* @param nBaseVersion The base version.
* @param nChainId The auxpow chain ID.
*/
void SetBaseVersion(int32_t nBaseVersion, int32_t nChainId);
/**
* Extract the chain ID.
* @return The chain ID encoded in the version.
*/
inline int32_t GetChainId() const
{
return nVersion / VERSION_CHAIN_START;
}
/**
* Set the chain ID. This is used for the test suite.
* @param ch The chain ID to set.
*/
inline void SetChainId(int32_t chainId)
{
nVersion %= VERSION_CHAIN_START;
nVersion |= chainId * VERSION_CHAIN_START;
}
/**
* Check if the auxpow flag is set in the version.
* @return True iff this block version is marked as auxpow.
*/
inline bool IsAuxpow() const
{
return nVersion & VERSION_AUXPOW;
}
/**
* Set the auxpow flag. This is used for testing.
* @param auxpow Whether to mark auxpow as true.
*/
inline void SetAuxpowVersion (bool auxpow)
{
if (auxpow)
nVersion |= VERSION_AUXPOW;
else
nVersion &= ~VERSION_AUXPOW;
}
/**
* Check whether this is a "legacy" block without chain ID.
* @return True iff it is.
*/
inline bool IsLegacy() const
{
return nVersion == 1;
}
};
#endif // BITCOIN_PRIMITIVES_PUREHEADER_H
| 25.948718 | 74 | 0.636117 |
36ff437481bc9281d528a7263f4e256893275e80 | 4,351 | h | C | ugene/src/plugins_3rdparty/ball/src/include/BALL/STRUCTURE/trianglePoint.h | iganna/lspec | c75cba3e4fa9a46abeecbf31b5d467827cf4fec0 | [
"MIT"
] | null | null | null | ugene/src/plugins_3rdparty/ball/src/include/BALL/STRUCTURE/trianglePoint.h | iganna/lspec | c75cba3e4fa9a46abeecbf31b5d467827cf4fec0 | [
"MIT"
] | null | null | null | ugene/src/plugins_3rdparty/ball/src/include/BALL/STRUCTURE/trianglePoint.h | iganna/lspec | c75cba3e4fa9a46abeecbf31b5d467827cf4fec0 | [
"MIT"
] | null | null | null | // -*- Mode: C++; tab-width: 2; -*-
// vi: set ts=2:
//
// $Id: trianglePoint.h,v 1.12.18.1 2007-03-25 21:25:33 oliver Exp $
//
#ifndef BALL_STRUCTURE_TRIANGLEPOINT_H
#define BALL_STRUCTURE_TRIANGLEPOINT_H
#ifndef BALL_MATHS_VECTOR3_H
# include <BALL/MATHS/vector3.h>
#endif
#ifndef BALL_STRUCTURE_GRAPHEDGE_H
# include <BALL/STRUCTURE/graphEdge.h>
#endif
#ifndef BALL_STRUCTURE_GRAPHFACE_H
# include <BALL/STRUCTURE/graphFace.h>
#endif
#ifndef BALL_STRUCTURE_GRAPHVERTEX_H
# include <BALL/STRUCTURE/graphVertex.h>
#endif
namespace BALL
{
class TriangleEdge;
class Triangle;
class TriangulatedSurface;
class TriangulatedSphere;
class TriangulatedSES;
class SESTriangulator;
class TriangulatedSAS;
class SASTriangulator;
/** Generic TriangleEdge Class.
\ingroup Surface
*/
class BALL_EXPORT TrianglePoint
: public GraphVertex< TrianglePoint,TriangleEdge,Triangle >
{
public:
/** @name Class friends
- class Triangle
- class TriangleEdge
- class TriangulatedSurface
- class TriangulatedSphere
- class TriangulatedSES
- class SESTriangulator
- class TriangulatedSAS
- class SASTriangulator
*/
friend class Triangle;
friend class TriangleEdge;
friend class TriangulatedSurface;
friend class TriangulatedSphere;
friend class TriangulatedSES;
friend class SESTriangulator;
friend class TriangulatedSAS;
friend class SASTriangulator;
BALL_CREATE(TrianglePoint)
/** @name Constructors and Destructors
*/
//@{
/** Default constructor.
This method creates a new TrianglePoint object.
*/
TrianglePoint()
throw();
/** Copy constructor.
Create a new TrianglePoint object from another.
@param point the TrianglePoint object to be copied
@param deep if deep = false, all pointers are set to NULL (default).
Otherwise the new TrianglePoint object is linked to the
neighbours of the old TrianglePoint object.
*/
TrianglePoint(const TrianglePoint& point, bool deep = false)
throw();
/** Destructor.
Destructs the TrianglePoint object.
*/
virtual ~TrianglePoint()
throw();
//@}
/** @name Assignments
*/
//@{
/** Assign from another TrianglePoint.
@param point the TrianglePoint object to assign from
@param deep if deep = false, all pointers are set to NULL
(default). Otherwise the new TrianglePoint object is
linked to the neighbours of the TrianglePoint object to
assign from.
*/
void set(const TrianglePoint& point, bool deep = false)
throw();
/** Assign from another TrianglePoint.
The new TrianglePoint object is linked to the neighbours of the
TrianglePoint object to assign from.
@param point the TrianglePoint object to assign from
*/
TrianglePoint& operator = (const TrianglePoint& point)
throw();
//@}
/** @name Accessors
*/
//@{
/** Get the point
*/
TVector3<double> getPoint() const
throw();
/** Set the point
*/
void setPoint(const TVector3<double>& point)
throw();
/** Get the normal of the TrianglePoint
*/
TVector3<double> getNormal() const
throw();
/** Set the normal of the TrianglePoint
*/
void setNormal(const TVector3<double>& normal)
throw(Exception::DivisionByZero);
//@}
/** @name Predicates
*/
//@{
/** Equality operator
@return bool <b>true</b> if the TrianglePoints lie on the same point,
<b>false</b> otherwise.
*/
virtual bool operator == (const TrianglePoint& point) const
throw();
/** Inequality operator
@return bool <b>false</b> if the TrianglePoints lie on the same point,
<b>true</b> otherwise.
*/
virtual bool operator != (const TrianglePoint& point) const
throw();
/** Similarity operator
@return bool <b>true</b> if the TrianglePoints lie on the same point,
<b>false</b> otherwise.
*/
virtual bool operator *= (const TrianglePoint& point) const
throw();
//@}
protected:
/*_ The point itselfe
*/
TVector3<double> point_;
/*_ The normal vector of the point
*/
TVector3<double> normal_;
};
/** @name Storers
*/
//@{
/** Output- Operator
*/
BALL_EXPORT std::ostream& operator << (std::ostream& s, const TrianglePoint& point);
//@}
} // namespace BALL
#endif // BALL_STRUCTURE_TRIANGLEPOINT_H
| 21.539604 | 85 | 0.680303 |
82824530e90be9fdd01296248488b437aeb35b27 | 1,234 | c | C | esercitazione/es_02_structlib/miastruct.c | EmanueleGiacomini/icaro-soccer-1819 | 05306ed7b8dc63ad5028b9c5cb96dacd076cfed6 | [
"Apache-2.0"
] | 1 | 2018-10-01T07:51:16.000Z | 2018-10-01T07:51:16.000Z | esercitazione/es_02_structlib/miastruct.c | EmanueleGiacomini/icaro-soccer-1819 | 05306ed7b8dc63ad5028b9c5cb96dacd076cfed6 | [
"Apache-2.0"
] | null | null | null | esercitazione/es_02_structlib/miastruct.c | EmanueleGiacomini/icaro-soccer-1819 | 05306ed7b8dc63ad5028b9c5cb96dacd076cfed6 | [
"Apache-2.0"
] | null | null | null | /**
miastruct.c
**/
#include "miastruct.h"
/**
Inizializza TempoStruct t impostando s secondi, m minuti e h ore
**/
void TempoStruct_init(TempoStruct* t, int h, int m, int s) {
t->secondi = s;
t->minuti = m;
t->ore = h;
}
/**
Calcola la differenza fra t2 e t1 e la salva in diff
Si supponga che t2 > t1 (quindi t2.ore > t1.ore)
consiglio:
se t2.sec < t1.sec è possibile fare
t2.minuti--
t2.secondi += 60
e poi eseguire la differenza fra secondi.
Iterare il ragionamento anche sui minuti
**/
void TempoStruct_calcolaDiff(TempoStruct* t2, TempoStruct* t1, TempoStruct* diff) {
if(t2->secondi < t1->secondi)
{
t2->minuti --;
t2->secondi +=60;
}
diff->secondi = t2->secondi - t1->secondi;
if(t2->minuti < t1->minuti)
{
t2->ore --;
t2->minuti += 60;
}
diff->minuti = t2->minuti - t1->minuti;
diff->ore = t2->ore - t1->ore;
}
/** Restituire il tempo contenuto in t sotto forma di secondi.
Si può calcolare il tempo in secondi con la formula:
secondiTotali=secondi + 60*minuti + 3600 * ore
**/
int TempoStruct_toSecondi(TempoStruct* t) {
int secondiTotali;
secondiTotali = t->secondi + 60*t->minuti + 3600* t->ore;
return secondiTotali;
}
| 23.283019 | 83 | 0.639384 |
d20d8cdd7cf955e5081537113efde7c38bb4f48e | 9,514 | c | C | plat/arm/common/arm_bl31_setup.c | zhuxlproject/arm-trusted-fireware | 95fba14bc483055114d40e72386daf9c021177b6 | [
"BSD-3-Clause"
] | 6 | 2018-02-06T23:41:22.000Z | 2021-04-04T04:53:28.000Z | plat/arm/common/arm_bl31_setup.c | zhuxlproject/arm-trusted-fireware | 95fba14bc483055114d40e72386daf9c021177b6 | [
"BSD-3-Clause"
] | null | null | null | plat/arm/common/arm_bl31_setup.c | zhuxlproject/arm-trusted-fireware | 95fba14bc483055114d40e72386daf9c021177b6 | [
"BSD-3-Clause"
] | 3 | 2017-06-15T07:36:36.000Z | 2018-12-05T16:54:31.000Z | /*
* Copyright (c) 2015-2016, ARM Limited and Contributors. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* Neither the name of ARM nor the names of its contributors may be used
* to endorse or promote products derived from this software without specific
* prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#include <arch.h>
#include <arch_helpers.h>
#include <arm_def.h>
#include <assert.h>
#include <bl_common.h>
#include <console.h>
#include <debug.h>
#include <mmio.h>
#include <plat_arm.h>
#include <platform.h>
#define BL31_END (uintptr_t)(&__BL31_END__)
/*
* Placeholder variables for copying the arguments that have been passed to
* BL31 from BL2.
*/
static entry_point_info_t bl32_image_ep_info;
static entry_point_info_t bl33_image_ep_info;
/* Weak definitions may be overridden in specific ARM standard platform */
#pragma weak bl31_early_platform_setup
#pragma weak bl31_platform_setup
#pragma weak bl31_plat_arch_setup
#pragma weak bl31_plat_get_next_image_ep_info
/*******************************************************************************
* Return a pointer to the 'entry_point_info' structure of the next image for the
* security state specified. BL33 corresponds to the non-secure image type
* while BL32 corresponds to the secure image type. A NULL pointer is returned
* if the image does not exist.
******************************************************************************/
entry_point_info_t *bl31_plat_get_next_image_ep_info(uint32_t type)
{
entry_point_info_t *next_image_info;
assert(sec_state_is_valid(type));
next_image_info = (type == NON_SECURE)
? &bl33_image_ep_info : &bl32_image_ep_info;
/*
* None of the images on the ARM development platforms can have 0x0
* as the entrypoint
*/
if (next_image_info->pc)
return next_image_info;
else
return NULL;
}
/*******************************************************************************
* Perform any BL31 early platform setup common to ARM standard platforms.
* Here is an opportunity to copy parameters passed by the calling EL (S-EL1
* in BL2 & S-EL3 in BL1) before they are lost (potentially). This needs to be
* done before the MMU is initialized so that the memory layout can be used
* while creating page tables. BL2 has flushed this information to memory, so
* we are guaranteed to pick up good data.
******************************************************************************/
#if LOAD_IMAGE_V2
void arm_bl31_early_platform_setup(void *from_bl2,
void *plat_params_from_bl2)
#else
void arm_bl31_early_platform_setup(bl31_params_t *from_bl2,
void *plat_params_from_bl2)
#endif
{
/* Initialize the console to provide early debug support */
console_init(PLAT_ARM_BOOT_UART_BASE, PLAT_ARM_BOOT_UART_CLK_IN_HZ,
ARM_CONSOLE_BAUDRATE);
#if RESET_TO_BL31
/* There are no parameters from BL2 if BL31 is a reset vector */
assert(from_bl2 == NULL);
assert(plat_params_from_bl2 == NULL);
#ifdef BL32_BASE
/* Populate entry point information for BL32 */
SET_PARAM_HEAD(&bl32_image_ep_info,
PARAM_EP,
VERSION_1,
0);
SET_SECURITY_STATE(bl32_image_ep_info.h.attr, SECURE);
bl32_image_ep_info.pc = BL32_BASE;
bl32_image_ep_info.spsr = arm_get_spsr_for_bl32_entry();
#endif /* BL32_BASE */
/* Populate entry point information for BL33 */
SET_PARAM_HEAD(&bl33_image_ep_info,
PARAM_EP,
VERSION_1,
0);
/*
* Tell BL31 where the non-trusted software image
* is located and the entry state information
*/
bl33_image_ep_info.pc = plat_get_ns_image_entrypoint();
bl33_image_ep_info.spsr = arm_get_spsr_for_bl33_entry();
SET_SECURITY_STATE(bl33_image_ep_info.h.attr, NON_SECURE);
#else /* RESET_TO_BL31 */
/*
* In debug builds, we pass a special value in 'plat_params_from_bl2'
* to verify platform parameters from BL2 to BL31.
* In release builds, it's not used.
*/
assert(((unsigned long long)plat_params_from_bl2) ==
ARM_BL31_PLAT_PARAM_VAL);
# if LOAD_IMAGE_V2
/*
* Check params passed from BL2 should not be NULL,
*/
bl_params_t *params_from_bl2 = (bl_params_t *)from_bl2;
assert(params_from_bl2 != NULL);
assert(params_from_bl2->h.type == PARAM_BL_PARAMS);
assert(params_from_bl2->h.version >= VERSION_2);
bl_params_node_t *bl_params = params_from_bl2->head;
/*
* Copy BL33 and BL32 (if present), entry point information.
* They are stored in Secure RAM, in BL2's address space.
*/
while (bl_params) {
if (bl_params->image_id == BL32_IMAGE_ID)
bl32_image_ep_info = *bl_params->ep_info;
if (bl_params->image_id == BL33_IMAGE_ID)
bl33_image_ep_info = *bl_params->ep_info;
bl_params = bl_params->next_params_info;
}
if (bl33_image_ep_info.pc == 0)
panic();
# else /* LOAD_IMAGE_V2 */
/*
* Check params passed from BL2 should not be NULL,
*/
assert(from_bl2 != NULL);
assert(from_bl2->h.type == PARAM_BL31);
assert(from_bl2->h.version >= VERSION_1);
/*
* Copy BL32 (if populated by BL2) and BL33 entry point information.
* They are stored in Secure RAM, in BL2's address space.
*/
if (from_bl2->bl32_ep_info)
bl32_image_ep_info = *from_bl2->bl32_ep_info;
bl33_image_ep_info = *from_bl2->bl33_ep_info;
# endif /* LOAD_IMAGE_V2 */
#endif /* RESET_TO_BL31 */
}
#if LOAD_IMAGE_V2
void bl31_early_platform_setup(void *from_bl2,
void *plat_params_from_bl2)
#else
void bl31_early_platform_setup(bl31_params_t *from_bl2,
void *plat_params_from_bl2)
#endif
{
arm_bl31_early_platform_setup(from_bl2, plat_params_from_bl2);
/*
* Initialize Interconnect for this cluster during cold boot.
* No need for locks as no other CPU is active.
*/
plat_arm_interconnect_init();
/*
* Enable Interconnect coherency for the primary CPU's cluster.
* Earlier bootloader stages might already do this (e.g. Trusted
* Firmware's BL1 does it) but we can't assume so. There is no harm in
* executing this code twice anyway.
* Platform specific PSCI code will enable coherency for other
* clusters.
*/
plat_arm_interconnect_enter_coherency();
}
/*******************************************************************************
* Perform any BL31 platform setup common to ARM standard platforms
******************************************************************************/
void arm_bl31_platform_setup(void)
{
/* Initialize the GIC driver, cpu and distributor interfaces */
plat_arm_gic_driver_init();
plat_arm_gic_init();
#if RESET_TO_BL31
/*
* Do initial security configuration to allow DRAM/device access
* (if earlier BL has not already done so).
*/
plat_arm_security_setup();
#endif /* RESET_TO_BL31 */
/* Enable and initialize the System level generic timer */
mmio_write_32(ARM_SYS_CNTCTL_BASE + CNTCR_OFF,
CNTCR_FCREQ(0) | CNTCR_EN);
/* Allow access to the System counter timer module */
arm_configure_sys_timer();
/* Initialize power controller before setting up topology */
plat_arm_pwrc_setup();
}
/*******************************************************************************
* Perform any BL31 platform runtime setup prior to BL31 exit common to ARM
* standard platforms
******************************************************************************/
void arm_bl31_plat_runtime_setup(void)
{
/* Initialize the runtime console */
console_init(PLAT_ARM_BL31_RUN_UART_BASE, PLAT_ARM_BL31_RUN_UART_CLK_IN_HZ,
ARM_CONSOLE_BAUDRATE);
}
void bl31_platform_setup(void)
{
arm_bl31_platform_setup();
}
void bl31_plat_runtime_setup(void)
{
arm_bl31_plat_runtime_setup();
}
/*******************************************************************************
* Perform the very early platform specific architectural setup shared between
* ARM standard platforms. This only does basic initialization. Later
* architectural setup (bl31_arch_setup()) does not do anything platform
* specific.
******************************************************************************/
void arm_bl31_plat_arch_setup(void)
{
arm_setup_page_tables(BL31_BASE,
BL31_END - BL31_BASE,
BL_CODE_BASE,
BL_CODE_END,
BL_RO_DATA_BASE,
BL_RO_DATA_END
#if USE_COHERENT_MEM
, BL_COHERENT_RAM_BASE,
BL_COHERENT_RAM_END
#endif
);
enable_mmu_el3(0);
}
void bl31_plat_arch_setup(void)
{
arm_bl31_plat_arch_setup();
}
| 32.360544 | 81 | 0.693294 |
d2e33f7fc7c05b19e6e0c6eaded6af3709512bdf | 6,263 | h | C | userspace/lib/window.h | chenyukang/osdev | 355d4b4dbe7f1ac913fd28bd2b37cdc7550d73c3 | [
"NCSA",
"Unlicense",
"MIT"
] | 3 | 2018-03-12T02:58:51.000Z | 2021-07-14T05:50:36.000Z | userspace/lib/window.h | chenyukang/osdev | 355d4b4dbe7f1ac913fd28bd2b37cdc7550d73c3 | [
"NCSA",
"Unlicense",
"MIT"
] | null | null | null | userspace/lib/window.h | chenyukang/osdev | 355d4b4dbe7f1ac913fd28bd2b37cdc7550d73c3 | [
"NCSA",
"Unlicense",
"MIT"
] | 2 | 2018-03-12T02:58:52.000Z | 2021-04-05T03:32:34.000Z | /* vim: tabstop=4 shiftwidth=4 noexpandtab
*
* Compositing and Window Management Library
*/
#ifndef COMPOSITING_H
#define COMPOSITING_H
#include <stdint.h>
#include "list.h"
#include "graphics.h"
#include "kbd.h"
/* Connection */
typedef struct {
/* Control flow structures */
volatile uint8_t lock; /* Spinlock byte */
/* LOCK REQUIRED REGION */
volatile uint8_t client_done; /* Client has finished work */
volatile uint8_t server_done; /* Server has finished work */
/* The actual data passed back and forth */
pid_t client_pid; /* Actively communicating client process */
uintptr_t event_pipe; /* Client event pipe (ie, mouse, keyboard) */
uintptr_t command_pipe; /* Client command pipe (ie, resize) */
/* END LOCK REQUIRED REGION */
/* Data about the system */
pid_t server_pid; /* The wins -- for signals */
uint16_t server_width; /* Screen resolution, width */
uint16_t server_height; /* Screen resolution, height */
uint8_t server_depth; /* Native screen depth (in bits) */
uint32_t magic;
} wins_server_global_t;
/* Commands and Events */
typedef struct {
uint32_t magic;
uint8_t command_type; /* Command or event specifier */
size_t packet_size; /* Size of the *remaining* packet data */
} wins_packet_t;
#define WINS_PACKET(p) ((char *)((uintptr_t)p + sizeof(wins_packet_t)))
#define WINS_SERVER_IDENTIFIER "sys.compositor"
#define WINS_MAGIC 0xDECADE99
/* Commands */
#define WC_NEWWINDOW 0x00 /* New Window */
#define WC_RESIZE 0x01 /* Resize and move an existing window */
#define WC_DESTROY 0x02 /* Destroy an existing window */
#define WC_DAMAGE 0x03 /* Damage window (redraw region) */
#define WC_REDRAW 0x04 /* Damage window (redraw region) */
#define WC_REORDER 0x05 /* Set the Z-index for a window (request) */
#define WC_SET_ALPHA 0x06 /* Enable RGBA for compositing */
/* Events */
#define WE_KEYDOWN 0x10 /* A key has been pressed down */
#define WE_KEYUP 0x11 /* RESERVED: Key up [UNUSED] */
#define WE_MOUSEMOVE 0x20 /* The mouse has moved (to the given coordinates) */
#define WE_MOUSEENTER 0x21 /* The mouse has entered your window (at the given coordinates) */
#define WE_MOUSELEAVE 0x22 /* The mouse has left your window (at the given coordinates) */
#define WE_MOUSECLICK 0x23 /* A mouse button has been pressed that was not previously pressed */
#define WE_MOUSEUP 0x24 /* A mouse button has been released */
#define WE_NEWWINDOW 0x30 /* A new window has been created */
#define WE_RESIZED 0x31 /* Your window has been resized or moved */
#define WE_DESTROYED 0x32 /* Window has been removed */
#define WE_REDRAWN 0x34
#define WE_FOCUSCHG 0x35
#define WE_GROUP_MASK 0xF0
#define WE_KEY_EVT 0x10 /* Some sort of keyboard event */
#define WE_MOUSE_EVT 0x20 /* Some sort of mouse event */
#define WE_WINDOW_EVT 0x30 /* Some sort of window event */
typedef uint16_t wid_t;
typedef struct {
wid_t wid; /* or none for new window */
int16_t left; /* X coordinate */
int16_t top; /* Y coordinate */
uint16_t width; /* Width of window or region */
uint16_t height; /* Height of window or region */
uint8_t command; /* The command (duplicated) */
} w_window_t;
typedef struct {
wid_t wid;
uint16_t key;
uint8_t ret;
key_event_t event;
uint8_t command;
} w_keyboard_t;
typedef struct {
wid_t wid;
int32_t old_x;
int32_t old_y;
int32_t new_x;
int32_t new_y;
uint8_t buttons;
uint8_t command;
} w_mouse_t;
#define MOUSE_BUTTON_LEFT 0x01
#define MOUSE_BUTTON_RIGHT 0x02
#define MOUSE_BUTTON_MIDDLE 0x04
#define SHMKEY(buf,sz,win) snprintf(buf, sz, "%s.%d.%d.%d", WINS_SERVER_IDENTIFIER, win->owner->pid, win->wid, win->bufid);
#define SHMKEY_(buf,sz,win) snprintf(buf, sz, "%s.%d.%d.%d", WINS_SERVER_IDENTIFIER, getpid(), win->wid, win->bufid);
/* Windows */
typedef struct process_windows process_windows_t;
typedef struct {
wid_t wid; /* Window identifier */
process_windows_t * owner; /* Owning process (back ptr) */
uint16_t width; /* Buffer width in pixels */
uint16_t height; /* Buffer height in pixels */
/* UNUSED IN CLIENT */
int32_t x; /* X coordinate of upper-left corner */
int32_t y; /* Y coordinate of upper-left corner */
uint16_t z; /* Stack order */
int16_t rotation;
uint8_t use_alpha;
/* END UNUSED IN CLIENT */
uint8_t focused;
uint8_t * buffer; /* Window buffer */
uint16_t bufid; /* We occasionally replace the buffer; each is uniquely-indexed */
} window_t;
struct process_windows {
uint32_t pid;
int event_pipe; /* Pipe to send events through */
FILE * event_pipe_file;
int command_pipe; /* Pipe on which we receive commands */
FILE * command_pipe_file;
list_t * windows;
};
extern volatile wins_server_global_t * wins_globals;
/* Client Windowing */
int setup_windowing ();
void teardown_windowing ();
window_t * window_create (int16_t left, int16_t top, uint16_t width, uint16_t height);
void window_resize (window_t * window, int16_t left, int16_t top, uint16_t width, uint16_t height);
void window_redraw (window_t * window, int16_t left, int16_t top, uint16_t width, uint16_t height);
void window_redraw_full (window_t * window);
void window_redraw_wait (window_t * window);
void window_destroy (window_t * window);
void window_reorder (window_t * window, uint16_t new_zed);
void window_enable_alpha (window_t * window);
void window_disable_alpha (window_t * window);
w_keyboard_t * poll_keyboard();
w_keyboard_t * poll_keyboard_async();
w_mouse_t * poll_mouse();
#define TO_WINDOW_OFFSET(x,y) (((x) - window->x) + ((y) - window->y) * window->width)
#define DIRECT_OFFSET(x,y) ((x) + (y) * window->width)
gfx_context_t * init_graphics_window(window_t * window);
gfx_context_t * init_graphics_window_double_buffer(window_t * window);
void reinit_graphics_window(gfx_context_t * out, window_t * window);
void win_use_threaded_handler();
extern void (*mouse_action_callback)(w_mouse_t *);
extern void (*resize_window_callback)(window_t *);
extern void (*focus_changed_callback)(window_t *);
window_t * wins_get_window (wid_t wid);
void win_sane_events();
wins_packet_t * get_window_events();
wins_packet_t * get_window_events_async();
void resize_window_buffer_client (window_t * window, int16_t left, int16_t top, uint16_t width, uint16_t height);
#endif
| 32.283505 | 123 | 0.731918 |
d04ac2299e5a1fcbe88c9aa28287f53161bd421c | 3,324 | h | C | System/Library/PrivateFrameworks/ATVLegacyContentKit.framework/TVLImageTextImageView.h | lechium/tvOS145Headers | 9940da19adb0017f8037853e9cfccbe01b290dd5 | [
"MIT"
] | 5 | 2021-04-29T04:31:43.000Z | 2021-08-19T18:59:58.000Z | System/Library/PrivateFrameworks/ATVLegacyContentKit.framework/TVLImageTextImageView.h | lechium/tvOS145Headers | 9940da19adb0017f8037853e9cfccbe01b290dd5 | [
"MIT"
] | null | null | null | System/Library/PrivateFrameworks/ATVLegacyContentKit.framework/TVLImageTextImageView.h | lechium/tvOS145Headers | 9940da19adb0017f8037853e9cfccbe01b290dd5 | [
"MIT"
] | 1 | 2022-03-19T11:16:23.000Z | 2022-03-19T11:16:23.000Z | /*
* This header is generated by classdump-dyld 1.5
* on Wednesday, April 28, 2021 at 9:10:25 PM Mountain Standard Time
* Operating System: Version 14.5 (Build 18L204)
* Image Source: /System/Library/PrivateFrameworks/ATVLegacyContentKit.framework/ATVLegacyContentKit
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley.
*/
#import <ATVLegacyContentKit/ATVLegacyContentKit-Structs.h>
#import <UIKitCore/UIView.h>
#import <libobjc.A.dylib/TVLMenuItemCell.h>
@class TVLImageTextImageMenuItemElement, TVImageView, UILabel, UIView, NSString;
@interface TVLImageTextImageView : UIView <TVLMenuItemCell> {
BOOL _dimmed;
TVLImageTextImageMenuItemElement* _menuItemElement;
TVImageView* _leftImageView;
TVImageView* _rightImageView;
UILabel* _separatorLabel;
UILabel* _titleLabel;
UILabel* _rightLabel;
UIView* _dimmedView;
}
@property (nonatomic,retain) TVLImageTextImageMenuItemElement * menuItemElement; //@synthesize menuItemElement=_menuItemElement - In the implementation block
@property (nonatomic,retain) TVImageView * leftImageView; //@synthesize leftImageView=_leftImageView - In the implementation block
@property (nonatomic,retain) TVImageView * rightImageView; //@synthesize rightImageView=_rightImageView - In the implementation block
@property (nonatomic,retain) UILabel * separatorLabel; //@synthesize separatorLabel=_separatorLabel - In the implementation block
@property (nonatomic,retain) UILabel * titleLabel; //@synthesize titleLabel=_titleLabel - In the implementation block
@property (nonatomic,retain) UILabel * rightLabel; //@synthesize rightLabel=_rightLabel - In the implementation block
@property (nonatomic,retain) UIView * dimmedView; //@synthesize dimmedView=_dimmedView - In the implementation block
@property (assign,nonatomic) BOOL dimmed; //@synthesize dimmed=_dimmed - In the implementation block
@property (nonatomic,copy) NSString * title;
@property (readonly) unsigned long long hash;
@property (readonly) Class superclass;
@property (copy,readonly) NSString * description;
@property (copy,readonly) NSString * debugDescription;
-(NSString *)title;
-(void)setTitle:(NSString *)arg1 ;
-(id)initWithFrame:(CGRect)arg1 ;
-(void)layoutSubviews;
-(UILabel *)titleLabel;
-(void)setTitleLabel:(UILabel *)arg1 ;
-(UILabel *)rightLabel;
-(BOOL)dimmed;
-(void)setDimmed:(BOOL)arg1 ;
-(void)configureWithMenuItemElement:(id)arg1 ;
-(TVImageView *)rightImageView;
-(void)setRightImageView:(TVImageView *)arg1 ;
-(void)setRightLabel:(UILabel *)arg1 ;
-(UIView *)dimmedView;
-(void)setDimmedView:(UIView *)arg1 ;
-(TVLImageTextImageMenuItemElement *)menuItemElement;
-(void)setMenuItemElement:(TVLImageTextImageMenuItemElement *)arg1 ;
-(TVImageView *)leftImageView;
-(void)setLeftImageView:(TVImageView *)arg1 ;
-(UILabel *)separatorLabel;
-(void)setSeparatorLabel:(UILabel *)arg1 ;
@end
| 51.9375 | 170 | 0.687124 |
d09c6617788cef27e074d9af5c6abd336da459b1 | 1,292 | h | C | Nuclear/vcclr.h | InsidersSoftware/NuclearSDK | a83ed476e6169b317adef0068e1697a34a0ca9d3 | [
"MIT"
] | 2 | 2021-01-27T10:19:30.000Z | 2021-02-09T06:24:30.000Z | Nuclear/vcclr.h | InsidersSoftware/NuclearSDK | a83ed476e6169b317adef0068e1697a34a0ca9d3 | [
"MIT"
] | null | null | null | Nuclear/vcclr.h | InsidersSoftware/NuclearSDK | a83ed476e6169b317adef0068e1697a34a0ca9d3 | [
"MIT"
] | 1 | 2021-01-27T10:19:36.000Z | 2021-01-27T10:19:36.000Z | //
// vcclr.h - helper code for using the managed extensions to C++
//
// Copyright (C) Microsoft Corporation
// All rights reserved.
//
#if _MSC_VER > 1000
#pragma once
#endif
#if !defined(_INC_VCCLR)
#define _INC_VCCLR
#ifndef RC_INVOKED
#include <gcroot.h>
#pragma warning(push)
#pragma warning(disable:4400)
#ifdef __cplusplus_cli
typedef cli::interior_ptr<const System::Char> __const_Char_ptr;
typedef cli::interior_ptr<const System::Byte> __const_Byte_ptr;
typedef cli::interior_ptr<System::Byte> _Byte_ptr;
typedef const System::String^ __const_String_handle;
#define _NULLPTR nullptr
#else
typedef const System::Char* __const_Char_ptr;
typedef const System::Byte* __const_Byte_ptr;
typedef System::Byte* _Byte_ptr;
typedef const System::String* __const_String_handle;
#define _NULLPTR 0
#endif
//
// get an interior gc pointer to the first character contained in a System::String object
//
inline __const_Char_ptr PtrToStringChars(__const_String_handle s) {
_Byte_ptr bp = const_cast<_Byte_ptr>(reinterpret_cast<__const_Byte_ptr>(s));
if( bp != _NULLPTR ) {
bp += System::Runtime::CompilerServices::RuntimeHelpers::OffsetToStringData;
}
return reinterpret_cast<__const_Char_ptr>(bp);
}
#pragma warning(pop)
#undef _NULLPTR
#endif /* RC_INVOKED */
#endif //_INC_VCCLR
| 23.925926 | 89 | 0.774768 |
fdecebff3ec04467a478d1f85859c1f3488e3531 | 9,487 | h | C | webrtc_headers/third_party/blink/renderer/core/html/html_frame_owner_element.h | ESWIN-DC/webrtc-jetson | 12ec9efbd7d47e4d888b276ef722f9e1b32087f3 | [
"Unlicense"
] | null | null | null | webrtc_headers/third_party/blink/renderer/core/html/html_frame_owner_element.h | ESWIN-DC/webrtc-jetson | 12ec9efbd7d47e4d888b276ef722f9e1b32087f3 | [
"Unlicense"
] | null | null | null | webrtc_headers/third_party/blink/renderer/core/html/html_frame_owner_element.h | ESWIN-DC/webrtc-jetson | 12ec9efbd7d47e4d888b276ef722f9e1b32087f3 | [
"Unlicense"
] | null | null | null | /*
* Copyright (C) 2006, 2007, 2009 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*
*/
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_HTML_HTML_FRAME_OWNER_ELEMENT_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_HTML_HTML_FRAME_OWNER_ELEMENT_H_
#include "services/network/public/mojom/trust_tokens.mojom-blink-forward.h"
#include "third_party/blink/public/mojom/frame/frame_owner_element_type.mojom-blink.h"
#include "third_party/blink/public/mojom/scroll/scrollbar_mode.mojom-blink.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/dom/document.h"
#include "third_party/blink/renderer/core/feature_policy/feature_policy_parser.h"
#include "third_party/blink/renderer/core/frame/dom_window.h"
#include "third_party/blink/renderer/core/frame/embedded_content_view.h"
#include "third_party/blink/renderer/core/frame/frame_owner.h"
#include "third_party/blink/renderer/core/html/html_element.h"
#include "third_party/blink/renderer/core/scroll/scroll_types.h"
#include "third_party/blink/renderer/platform/heap/handle.h"
#include "third_party/blink/renderer/platform/weborigin/security_policy.h"
#include "third_party/blink/renderer/platform/wtf/casting.h"
#include "third_party/blink/renderer/platform/wtf/hash_counted_set.h"
namespace blink {
class ExceptionState;
class Frame;
class LayoutEmbeddedContent;
class LazyLoadFrameObserver;
class WebPluginContainerImpl;
class CORE_EXPORT HTMLFrameOwnerElement : public HTMLElement,
public FrameOwner {
USING_GARBAGE_COLLECTED_MIXIN(HTMLFrameOwnerElement);
public:
~HTMLFrameOwnerElement() override;
DOMWindow* contentWindow() const;
Document* contentDocument() const;
virtual void DisconnectContentFrame();
// Most subclasses use LayoutEmbeddedContent (either LayoutEmbeddedObject or
// LayoutIFrame) except for HTMLObjectElement and HTMLEmbedElement which may
// return any LayoutObject when using fallback content.
LayoutEmbeddedContent* GetLayoutEmbeddedContent() const;
// Whether to collapse the frame owner element in the embedder document. That
// is, to remove it from the layout as if it did not exist.
virtual void SetCollapsed(bool) {}
virtual mojom::blink::FrameOwnerElementType OwnerType() const = 0;
Document* getSVGDocument(ExceptionState&) const;
void SetEmbeddedContentView(EmbeddedContentView*);
EmbeddedContentView* ReleaseEmbeddedContentView();
EmbeddedContentView* OwnedEmbeddedContentView() const {
return embedded_content_view_;
}
class PluginDisposeSuspendScope {
STACK_ALLOCATED();
public:
PluginDisposeSuspendScope() { suspend_count_ += 2; }
~PluginDisposeSuspendScope() {
suspend_count_ -= 2;
if (suspend_count_ == 1)
PerformDeferredPluginDispose();
}
private:
void PerformDeferredPluginDispose();
// Low bit indicates if there are plugins to dispose.
static int suspend_count_;
friend class HTMLFrameOwnerElement;
};
// FrameOwner overrides:
Frame* ContentFrame() const final { return content_frame_; }
void SetContentFrame(Frame&) final;
void ClearContentFrame() final;
void AddResourceTiming(const ResourceTimingInfo&) final;
void DispatchLoad() final;
const FramePolicy& GetFramePolicy() const final { return frame_policy_; }
bool CanRenderFallbackContent() const override { return false; }
void RenderFallbackContent(Frame*) override {}
void IntrinsicSizingInfoChanged() override {}
void SetNeedsOcclusionTracking(bool) override {}
AtomicString BrowsingContextContainerName() const override {
return FastGetAttribute(html_names::kNameAttr);
}
mojom::blink::ScrollbarMode ScrollbarMode() const override {
return mojom::blink::ScrollbarMode::kAuto;
}
int MarginWidth() const override { return -1; }
int MarginHeight() const override { return -1; }
bool AllowFullscreen() const override { return false; }
bool AllowPaymentRequest() const override { return false; }
bool IsDisplayNone() const override { return !embedded_content_view_; }
AtomicString RequiredCsp() const override { return g_null_atom; }
bool ShouldLazyLoadChildren() const final;
// For unit tests, manually trigger the UpdateContainerPolicy method.
void UpdateContainerPolicyForTests() { UpdateContainerPolicy(); }
void CancelPendingLazyLoad();
void ParseAttribute(const AttributeModificationParams&) override;
void SetEmbeddingToken(const base::UnguessableToken& token);
const base::Optional<base::UnguessableToken>& GetEmbeddingToken() const {
return embedding_token_;
}
bool IsAdRelated() const override;
void Trace(Visitor*) const override;
protected:
HTMLFrameOwnerElement(const QualifiedName& tag_name, Document&);
void SetSandboxFlags(network::mojom::blink::WebSandboxFlags);
void SetAllowedToDownload(bool allowed) {
frame_policy_.allowed_to_download = allowed;
}
void SetDisallowDocumentAccesss(bool disallowed);
bool LoadOrRedirectSubframe(const KURL&,
const AtomicString& frame_name,
bool replace_current_item);
bool IsKeyboardFocusable() const override;
void FrameOwnerPropertiesChanged() override;
void DisposePluginSoon(WebPluginContainerImpl*);
// Return the origin which is to be used for feature policy container
// policies, as "the origin of the URL in the frame's src attribute" (see
// https://wicg.github.io/feature-policy/#iframe-allow-attribute).
// This method is intended to be overridden by specific frame classes.
virtual scoped_refptr<const SecurityOrigin> GetOriginForFeaturePolicy()
const {
return SecurityOrigin::CreateUniqueOpaque();
}
// Return a feature policy container policy for this frame, based on the
// frame attributes and the effective origin specified in the frame
// attributes.
virtual ParsedFeaturePolicy ConstructContainerPolicy() const = 0;
// Update the container policy and notify the frame loader client of any
// changes.
void UpdateContainerPolicy();
// Return a document policy required policy for this frame, based on the
// frame attributes.
virtual DocumentPolicy::FeatureState ConstructRequiredPolicy() const {
return DocumentPolicy::FeatureState{};
}
// Update the required policy and notify the frame loader client of any
// changes.
void UpdateRequiredPolicy();
// Return a set of Trust Tokens parameters for requests for this frame,
// based on the frame attributes.
virtual network::mojom::blink::TrustTokenParamsPtr ConstructTrustTokenParams()
const;
private:
// Intentionally private to prevent redundant checks when the type is
// already HTMLFrameOwnerElement.
bool IsLocal() const final { return true; }
bool IsRemote() const final { return false; }
bool IsFrameOwnerElement() const final { return true; }
void SetIsSwappingFrames(bool is_swapping) override {
is_swapping_frames_ = is_swapping;
}
virtual network::mojom::ReferrerPolicy ReferrerPolicyAttribute() {
return network::mojom::ReferrerPolicy::kDefault;
}
Member<Frame> content_frame_;
Member<EmbeddedContentView> embedded_content_view_;
FramePolicy frame_policy_;
base::Optional<base::UnguessableToken> embedding_token_;
Member<LazyLoadFrameObserver> lazy_load_frame_observer_;
bool should_lazy_load_children_;
bool is_swapping_frames_;
};
class SubframeLoadingDisabler {
STACK_ALLOCATED();
public:
explicit SubframeLoadingDisabler(Node& root)
: SubframeLoadingDisabler(&root) {}
explicit SubframeLoadingDisabler(Node* root) : root_(root) {
if (root_)
DisabledSubtreeRoots().insert(root_);
}
~SubframeLoadingDisabler() {
if (root_)
DisabledSubtreeRoots().erase(root_);
}
static bool CanLoadFrame(HTMLFrameOwnerElement& owner) {
for (Node* node = &owner; node; node = node->ParentOrShadowHostNode()) {
if (DisabledSubtreeRoots().Contains(node))
return false;
}
return true;
}
private:
// The use of UntracedMember<Node> is safe as all SubtreeRootSet
// references are on the stack and reachable in case a conservative
// GC hits.
// TODO(sof): go back to HeapHashSet<> once crbug.com/684551 has been
// resolved.
using SubtreeRootSet = HashCountedSet<UntracedMember<Node>>;
CORE_EXPORT static SubtreeRootSet& DisabledSubtreeRoots();
Node* root_;
};
template <>
struct DowncastTraits<HTMLFrameOwnerElement> {
static bool AllowFrom(const FrameOwner& owner) { return owner.IsLocal(); }
static bool AllowFrom(const Node& node) { return node.IsFrameOwnerElement(); }
};
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_HTML_HTML_FRAME_OWNER_ELEMENT_H_
| 36.348659 | 86 | 0.760514 |
a94c8e588070c3daace3630a25172c1b784fafdc | 458 | h | C | myg/Third/Image/ImageManipulator.h | Miaocool/MYG-NewVersion | 37ff3baa9030d291584c42bd00572f650a6e2ac9 | [
"MIT"
] | null | null | null | myg/Third/Image/ImageManipulator.h | Miaocool/MYG-NewVersion | 37ff3baa9030d291584c42bd00572f650a6e2ac9 | [
"MIT"
] | null | null | null | myg/Third/Image/ImageManipulator.h | Miaocool/MYG-NewVersion | 37ff3baa9030d291584c42bd00572f650a6e2ac9 | [
"MIT"
] | null | null | null | //
// ImageManipulator.h
//
// Class for manipulating images.
//
// Created by Björn Sållarp on 2008-09-11.
// Copyright 2008 Björn Sållarp. All rights reserved.
//
// Read my blog @ http://blog.sallarp.com
//
// Updated on 2009-04-05
#import <UIKit/UIKit.h>
@interface ImageManipulator : NSObject {
}
+(UIImage *)makeRoundCornerImage:(UIImage*)img :(int) cornerWidth :(int) cornerHeight;
+(UIImage*)imageWithBorderFromImage:(UIImage*)source;
@end
| 19.913043 | 86 | 0.707424 |
802a9debb057429641344241a191fcee83a26050 | 99 | h | C | src/samples/CernyAutomaton.h | andgein/automata | a9cd3f3474b4665a8b941306375ec32ca0a80481 | [
"MIT"
] | null | null | null | src/samples/CernyAutomaton.h | andgein/automata | a9cd3f3474b4665a8b941306375ec32ca0a80481 | [
"MIT"
] | null | null | null | src/samples/CernyAutomaton.h | andgein/automata | a9cd3f3474b4665a8b941306375ec32ca0a80481 | [
"MIT"
] | null | null | null | #pragma once
#include "../algorithms/Automaton.h"
IAutomaton* CernyAutomaton(size_t states_count); | 24.75 | 48 | 0.79798 |
805a784e2b7eaa83c4e85246691ebb9561b0d41b | 1,863 | c | C | randomdraw.c | lolq123r/c-1 | b2cfef9ab43e107ade878a7e7e24c2f1356d977b | [
"Apache-2.0"
] | 1 | 2022-02-06T19:02:00.000Z | 2022-02-06T19:02:00.000Z | randomdraw.c | lolq123r/c-1 | b2cfef9ab43e107ade878a7e7e24c2f1356d977b | [
"Apache-2.0"
] | null | null | null | randomdraw.c | lolq123r/c-1 | b2cfef9ab43e107ade878a7e7e24c2f1356d977b | [
"Apache-2.0"
] | 2 | 2020-10-18T09:01:05.000Z | 2022-02-06T19:02:07.000Z | ///////////////////////////////////////////////////////////////////////////////
////
//// Raffle tickets: draw all numbers in a range in random order.
////
//// (c) E. Dronkert <e@dronkert.nl>
//// https://github.com/ednl
////
///////////////////////////////////////////////////////////////////////////////
#include <stdio.h> // printf
#include <stdlib.h> // srand, rand, RAND_MAX, NULL
#include <time.h> // to seed random number generator
#define FIRST (1u) // first number in the raffle ticket range
#define LAST (9u) // last number in the raffle ticket range
#define LEN (LAST - FIRST + 1u) // number of raffle tickets
///////////////////////////////////////////////////////////////////////////////
int main(void)
{
unsigned int i, n, raffles = 10, ticket[LEN];
// Seed random number generator.
#if defined(__APPLE__) && defined(__MACH__)
srandomdev();
#elif defined(__linux__)
srandom(time(NULL));
#else
srand(time(NULL));
#endif
// Do a certain number of complete raffles.
while (raffles--)
{
// Initialize the range.
for (n = 0; n < LEN; ++n)
ticket[n] = FIRST + n;
// n is now equal to LEN.
// Draw all tickets in random order.
// precondition: n == LEN
while (n)
{
// Random index from range [0..n> with decreasing length = n to 1.
// Unbiased, see https://en.cppreference.com/w/c/numeric/random/rand
i = rand() / ((RAND_MAX + 1u) / n--);
// Show the ticket number.
// Amend format when using larger numbers than single digits.
printf("%u", ticket[i]);
// Swap last element of currently used array to index we just used
// (not really *swap* because we decrease the array length anyway,
// so no need to save ticket[i]).
// No effect if indices i and n are equal, which is good.
ticket[i] = ticket[n];
}
// End of the raffle.
printf("\n");
}
return 0;
}
| 28.661538 | 79 | 0.553408 |
439237433da4c5290c638df845ff93c448e7e052 | 25,720 | c | C | mi8/drivers/input/touchscreen/synaptics_dsx_2.6/synaptics_dsx_rmi_dev.c | wqk317/mi8_kernel_source | e3482d1a7ea6021de2fc8f3178496b4b043bb727 | [
"MIT"
] | null | null | null | mi8/drivers/input/touchscreen/synaptics_dsx_2.6/synaptics_dsx_rmi_dev.c | wqk317/mi8_kernel_source | e3482d1a7ea6021de2fc8f3178496b4b043bb727 | [
"MIT"
] | null | null | null | mi8/drivers/input/touchscreen/synaptics_dsx_2.6/synaptics_dsx_rmi_dev.c | wqk317/mi8_kernel_source | e3482d1a7ea6021de2fc8f3178496b4b043bb727 | [
"MIT"
] | 1 | 2020-03-28T11:26:15.000Z | 2020-03-28T11:26:15.000Z | /*
* Synaptics DSX touchscreen driver
*
* Copyright (C) 2012-2015 Synaptics Incorporated. All rights reserved.
*
* Copyright (C) 2012 Alexandra Chin <alexandra.chin@tw.synaptics.com>
* Copyright (C) 2012 Scott Lin <scott.lin@tw.synaptics.com>
* Copyright (C) 2018 The Linux Foundation. All rights reserved.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* INFORMATION CONTAINED IN THIS DOCUMENT IS PROVIDED "AS-IS," AND SYNAPTICS
* EXPRESSLY DISCLAIMS ALL EXPRESS AND IMPLIED WARRANTIES, INCLUDING ANY
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE,
* AND ANY WARRANTIES OF NON-INFRINGEMENT OF ANY INTELLECTUAL PROPERTY RIGHTS.
* IN NO EVENT SHALL SYNAPTICS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, PUNITIVE, OR CONSEQUENTIAL DAMAGES ARISING OUT OF OR IN CONNECTION
* WITH THE USE OF THE INFORMATION CONTAINED IN THIS DOCUMENT, HOWEVER CAUSED
* AND BASED ON ANY THEORY OF LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* NEGLIGENCE OR OTHER TORTIOUS ACTION, AND EVEN IF SYNAPTICS WAS ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE. IF A TRIBUNAL OF COMPETENT JURISDICTION DOES
* NOT PERMIT THE DISCLAIMER OF DIRECT DAMAGES OR ANY OTHER DAMAGES, SYNAPTICS'
* TOTAL CUMULATIVE LIABILITY TO ANY PARTY SHALL NOT EXCEED ONE HUNDRED U.S.
* DOLLARS.
*/
#include <linux/kernel.h>
#include <linux/module.h>
#include <linux/slab.h>
#include <linux/interrupt.h>
#include <linux/delay.h>
#include <linux/input.h>
#include <linux/signal.h>
#include <linux/sched.h>
#include <linux/gpio.h>
#include <linux/uaccess.h>
#include <linux/cdev.h>
#include <linux/platform_device.h>
#include <linux/input/synaptics_dsx_v2_6.h>
#include "synaptics_dsx_core.h"
#define CHAR_DEVICE_NAME "rmi"
#define DEVICE_CLASS_NAME "rmidev"
#define SYSFS_FOLDER_NAME "rmidev"
#define DEV_NUMBER 1
#define REG_ADDR_LIMIT 0xFFFF
static ssize_t rmidev_sysfs_data_show(struct file *data_file,
struct kobject *kobj, struct bin_attribute *attributes,
char *buf, loff_t pos, size_t count);
static ssize_t rmidev_sysfs_data_store(struct file *data_file,
struct kobject *kobj, struct bin_attribute *attributes,
char *buf, loff_t pos, size_t count);
static ssize_t rmidev_sysfs_open_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count);
static ssize_t rmidev_sysfs_release_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count);
static ssize_t rmidev_sysfs_attn_state_show(struct device *dev,
struct device_attribute *attr, char *buf);
static ssize_t rmidev_sysfs_pid_show(struct device *dev,
struct device_attribute *attr, char *buf);
static ssize_t rmidev_sysfs_pid_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count);
static ssize_t rmidev_sysfs_term_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count);
static ssize_t rmidev_sysfs_intr_mask_show(struct device *dev,
struct device_attribute *attr, char *buf);
static ssize_t rmidev_sysfs_intr_mask_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count);
static ssize_t rmidev_sysfs_concurrent_show(struct device *dev,
struct device_attribute *attr, char *buf);
static ssize_t rmidev_sysfs_concurrent_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count);
struct rmidev_handle {
dev_t dev_no;
pid_t pid;
unsigned char intr_mask;
unsigned char *tmpbuf;
unsigned int tmpbuf_size;
struct device dev;
struct synaptics_rmi4_data *rmi4_data;
struct kobject *sysfs_dir;
struct siginfo interrupt_signal;
struct siginfo terminate_signal;
struct task_struct *task;
void *data;
bool irq_enabled;
bool concurrent;
};
struct rmidev_data {
int ref_count;
struct cdev main_dev;
struct class *device_class;
struct mutex file_mutex;
struct rmidev_handle *rmi_dev;
};
static struct bin_attribute attr_data = {
.attr = {
.name = "data",
.mode = 0664,
},
.size = 0,
.read = rmidev_sysfs_data_show,
.write = rmidev_sysfs_data_store,
};
static struct device_attribute attrs[] = {
__ATTR(open, 0220,
NULL,
rmidev_sysfs_open_store),
__ATTR(release, 0220,
NULL,
rmidev_sysfs_release_store),
__ATTR(attn_state, 0444,
rmidev_sysfs_attn_state_show,
NULL),
__ATTR(pid, 0664,
rmidev_sysfs_pid_show,
rmidev_sysfs_pid_store),
__ATTR(term, 0220,
NULL,
rmidev_sysfs_term_store),
__ATTR(intr_mask, 0444,
rmidev_sysfs_intr_mask_show,
rmidev_sysfs_intr_mask_store),
__ATTR(concurrent, 0444,
rmidev_sysfs_concurrent_show,
rmidev_sysfs_concurrent_store),
};
static int rmidev_major_num;
static struct class *rmidev_device_class;
static struct rmidev_handle *rmidev;
DECLARE_COMPLETION(rmidev_remove_complete_v26);
static irqreturn_t rmidev_sysfs_irq(int irq, void *data)
{
struct synaptics_rmi4_data *rmi4_data = data;
sysfs_notify(&rmi4_data->input_dev->dev.kobj,
SYSFS_FOLDER_NAME, "attn_state");
return IRQ_HANDLED;
}
static int rmidev_sysfs_irq_enable(struct synaptics_rmi4_data *rmi4_data,
bool enable)
{
int retval = 0;
unsigned char intr_status[MAX_INTR_REGISTERS];
unsigned long irq_flags = IRQF_TRIGGER_FALLING | IRQF_TRIGGER_RISING |
IRQF_ONESHOT;
if (enable) {
if (rmidev->irq_enabled)
return retval;
/* Clear interrupts first */
retval = synaptics_rmi4_reg_read(rmi4_data,
rmi4_data->f01_data_base_addr + 1,
intr_status,
rmi4_data->num_of_intr_regs);
if (retval < 0)
return retval;
retval = request_threaded_irq(rmi4_data->irq, NULL,
rmidev_sysfs_irq, irq_flags,
PLATFORM_DRIVER_NAME, rmi4_data);
if (retval < 0) {
dev_err(rmi4_data->pdev->dev.parent,
"%s: Failed to create irq thread\n",
__func__);
return retval;
}
rmidev->irq_enabled = true;
} else {
if (rmidev->irq_enabled) {
disable_irq(rmi4_data->irq);
free_irq(rmi4_data->irq, rmi4_data);
rmidev->irq_enabled = false;
}
}
return retval;
}
static ssize_t rmidev_sysfs_data_show(struct file *data_file,
struct kobject *kobj, struct bin_attribute *attributes,
char *buf, loff_t pos, size_t count)
{
int retval;
unsigned char intr_status = 0;
unsigned int length = (unsigned int)count;
unsigned short address = (unsigned short)pos;
struct synaptics_rmi4_fn *fhandler;
struct synaptics_rmi4_device_info *rmi;
struct synaptics_rmi4_data *rmi4_data = rmidev->rmi4_data;
rmi = &(rmi4_data->rmi4_mod_info);
if (length > (REG_ADDR_LIMIT - address)) {
dev_err(rmi4_data->pdev->dev.parent,
"%s: Out of register map limit\n",
__func__);
return -EINVAL;
}
if (length) {
retval = synaptics_rmi4_reg_read(rmi4_data,
address,
(unsigned char *)buf,
length);
if (retval < 0) {
dev_err(rmi4_data->pdev->dev.parent,
"%s: Failed to read data\n",
__func__);
return retval;
}
} else {
return -EINVAL;
}
if (!rmidev->concurrent)
goto exit;
if (address != rmi4_data->f01_data_base_addr)
goto exit;
if (length <= 1)
goto exit;
intr_status = buf[1];
if (!list_empty(&rmi->support_fn_list)) {
list_for_each_entry(fhandler, &rmi->support_fn_list, link) {
if (fhandler->num_of_data_sources) {
if (fhandler->intr_mask & intr_status) {
rmi4_data->report_touch(rmi4_data,
fhandler);
}
}
}
}
exit:
return length;
}
static ssize_t rmidev_sysfs_data_store(struct file *data_file,
struct kobject *kobj, struct bin_attribute *attributes,
char *buf, loff_t pos, size_t count)
{
int retval;
unsigned int length = (unsigned int)count;
unsigned short address = (unsigned short)pos;
struct synaptics_rmi4_data *rmi4_data = rmidev->rmi4_data;
if (length > (REG_ADDR_LIMIT - address)) {
dev_err(rmi4_data->pdev->dev.parent,
"%s: Out of register map limit\n",
__func__);
return -EINVAL;
}
if (length) {
retval = synaptics_rmi4_reg_write(rmi4_data,
address,
(unsigned char *)buf,
length);
if (retval < 0) {
dev_err(rmi4_data->pdev->dev.parent,
"%s: Failed to write data\n",
__func__);
return retval;
}
} else {
return -EINVAL;
}
return length;
}
static ssize_t rmidev_sysfs_open_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
unsigned int input;
struct synaptics_rmi4_data *rmi4_data = rmidev->rmi4_data;
if (sscanf(buf, "%u", &input) != 1)
return -EINVAL;
if (input != 1)
return -EINVAL;
if (rmi4_data->sensor_sleep) {
dev_err(rmi4_data->pdev->dev.parent,
"%s: Sensor sleeping\n",
__func__);
return -ENODEV;
}
rmi4_data->stay_awake = true;
rmi4_data->irq_enable(rmi4_data, false, false);
rmidev_sysfs_irq_enable(rmi4_data, true);
dev_dbg(rmi4_data->pdev->dev.parent,
"%s: Attention interrupt disabled\n",
__func__);
return count;
}
static ssize_t rmidev_sysfs_release_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
unsigned int input;
struct synaptics_rmi4_data *rmi4_data = rmidev->rmi4_data;
if (sscanf(buf, "%u", &input) != 1)
return -EINVAL;
if (input != 1)
return -EINVAL;
rmidev_sysfs_irq_enable(rmi4_data, false);
rmi4_data->irq_enable(rmi4_data, true, false);
dev_dbg(rmi4_data->pdev->dev.parent,
"%s: Attention interrupt enabled\n",
__func__);
rmi4_data->reset_device(rmi4_data, false);
rmi4_data->stay_awake = false;
return count;
}
static ssize_t rmidev_sysfs_attn_state_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
int attn_state;
struct synaptics_rmi4_data *rmi4_data = rmidev->rmi4_data;
const struct synaptics_dsx_board_data *bdata =
rmi4_data->hw_if->board_data;
attn_state = gpio_get_value(bdata->irq_gpio);
return snprintf(buf, PAGE_SIZE, "%u\n", attn_state);
}
static ssize_t rmidev_sysfs_pid_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%u\n", rmidev->pid);
}
static ssize_t rmidev_sysfs_pid_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
unsigned int input;
struct synaptics_rmi4_data *rmi4_data = rmidev->rmi4_data;
if (sscanf(buf, "%u", &input) != 1)
return -EINVAL;
rmidev->pid = input;
if (rmidev->pid) {
rmidev->task = pid_task(find_vpid(rmidev->pid), PIDTYPE_PID);
if (!rmidev->task) {
dev_err(rmi4_data->pdev->dev.parent,
"%s: Failed to locate PID of data logging tool\n",
__func__);
return -EINVAL;
}
}
return count;
}
static ssize_t rmidev_sysfs_term_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
unsigned int input;
if (sscanf(buf, "%u", &input) != 1)
return -EINVAL;
if (input != 1)
return -EINVAL;
if (rmidev->pid)
send_sig_info(SIGTERM, &rmidev->terminate_signal, rmidev->task);
return count;
}
static ssize_t rmidev_sysfs_intr_mask_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return snprintf(buf, PAGE_SIZE, "0x%02x\n", rmidev->intr_mask);
}
static ssize_t rmidev_sysfs_intr_mask_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
unsigned int input;
if (sscanf(buf, "%u", &input) != 1)
return -EINVAL;
rmidev->intr_mask = (unsigned char)input;
return count;
}
static ssize_t rmidev_sysfs_concurrent_show(struct device *dev,
struct device_attribute *attr, char *buf)
{
return snprintf(buf, PAGE_SIZE, "%d\n", rmidev->concurrent);
}
static ssize_t rmidev_sysfs_concurrent_store(struct device *dev,
struct device_attribute *attr, const char *buf, size_t count)
{
unsigned int input;
if (sscanf(buf, "%u", &input) != 1)
return -EINVAL;
rmidev->concurrent = input > 0 ? true : false;
return count;
}
static int rmidev_allocate_buffer(int count)
{
if (count + 1 > rmidev->tmpbuf_size) {
if (rmidev->tmpbuf_size)
kfree(rmidev->tmpbuf);
rmidev->tmpbuf = kzalloc(count + 1, GFP_KERNEL);
if (!rmidev->tmpbuf) {
dev_err(rmidev->rmi4_data->pdev->dev.parent,
"%s: Failed to alloc mem for buffer\n",
__func__);
rmidev->tmpbuf_size = 0;
return -ENOMEM;
}
rmidev->tmpbuf_size = count + 1;
}
return 0;
}
/*
* rmidev_llseek - set register address to access for RMI device
*
* @filp: pointer to file structure
* @off:
* if whence == SEEK_SET,
* off: 16-bit RMI register address
* if whence == SEEK_CUR,
* off: offset from current position
* if whence == SEEK_END,
* off: offset from end position (0xFFFF)
* @whence: SEEK_SET, SEEK_CUR, or SEEK_END
*/
static loff_t rmidev_llseek(struct file *filp, loff_t off, int whence)
{
loff_t newpos;
struct rmidev_data *dev_data = filp->private_data;
struct synaptics_rmi4_data *rmi4_data = rmidev->rmi4_data;
if (IS_ERR(dev_data)) {
pr_err("%s: Pointer of char device data is invalid", __func__);
return -EBADF;
}
mutex_lock(&(dev_data->file_mutex));
switch (whence) {
case SEEK_SET:
newpos = off;
break;
case SEEK_CUR:
newpos = filp->f_pos + off;
break;
case SEEK_END:
newpos = REG_ADDR_LIMIT + off;
break;
default:
newpos = -EINVAL;
goto clean_up;
}
if (newpos < 0 || newpos > REG_ADDR_LIMIT) {
dev_err(rmi4_data->pdev->dev.parent,
"%s: New position 0x%04x is invalid\n",
__func__, (unsigned int)newpos);
newpos = -EINVAL;
goto clean_up;
}
filp->f_pos = newpos;
clean_up:
mutex_unlock(&(dev_data->file_mutex));
return newpos;
}
/*
* rmidev_read: read register data from RMI device
*
* @filp: pointer to file structure
* @buf: pointer to user space buffer
* @count: number of bytes to read
* @f_pos: starting RMI register address
*/
static ssize_t rmidev_read(struct file *filp, char __user *buf,
size_t count, loff_t *f_pos)
{
ssize_t retval;
unsigned char intr_status = 0;
unsigned short address;
struct rmidev_data *dev_data = filp->private_data;
struct synaptics_rmi4_fn *fhandler;
struct synaptics_rmi4_device_info *rmi;
struct synaptics_rmi4_data *rmi4_data = rmidev->rmi4_data;
rmi = &(rmi4_data->rmi4_mod_info);
if (IS_ERR(dev_data)) {
pr_err("%s: Pointer of char device data is invalid", __func__);
return -EBADF;
}
mutex_lock(&(dev_data->file_mutex));
if (*f_pos > REG_ADDR_LIMIT) {
retval = -EFAULT;
goto clean_up;
}
if (count > (REG_ADDR_LIMIT - *f_pos))
count = REG_ADDR_LIMIT - *f_pos;
if (count == 0) {
retval = 0;
goto clean_up;
}
address = (unsigned short)(*f_pos);
rmidev_allocate_buffer(count);
retval = synaptics_rmi4_reg_read(rmidev->rmi4_data,
*f_pos,
rmidev->tmpbuf,
count);
if (retval < 0)
goto clean_up;
if (copy_to_user(buf, rmidev->tmpbuf, count))
retval = -EFAULT;
else
*f_pos += retval;
if (!rmidev->concurrent)
goto clean_up;
if (address != rmi4_data->f01_data_base_addr)
goto clean_up;
if (count <= 1)
goto clean_up;
intr_status = rmidev->tmpbuf[1];
if (!list_empty(&rmi->support_fn_list)) {
list_for_each_entry(fhandler, &rmi->support_fn_list, link) {
if (fhandler->num_of_data_sources) {
if (fhandler->intr_mask & intr_status) {
rmi4_data->report_touch(rmi4_data,
fhandler);
}
}
}
}
clean_up:
mutex_unlock(&(dev_data->file_mutex));
return retval;
}
/*
* rmidev_write: write register data to RMI device
*
* @filp: pointer to file structure
* @buf: pointer to user space buffer
* @count: number of bytes to write
* @f_pos: starting RMI register address
*/
static ssize_t rmidev_write(struct file *filp, const char __user *buf,
size_t count, loff_t *f_pos)
{
ssize_t retval;
struct rmidev_data *dev_data = filp->private_data;
if (IS_ERR(dev_data)) {
pr_err("%s: Pointer of char device data is invalid", __func__);
return -EBADF;
}
mutex_lock(&(dev_data->file_mutex));
if (*f_pos > REG_ADDR_LIMIT) {
retval = -EFAULT;
goto unlock;
}
if (count > (REG_ADDR_LIMIT - *f_pos))
count = REG_ADDR_LIMIT - *f_pos;
if (count == 0) {
retval = 0;
goto unlock;
}
rmidev_allocate_buffer(count);
if (copy_from_user(rmidev->tmpbuf, buf, count)) {
return -EFAULT;
goto unlock;
}
retval = synaptics_rmi4_reg_write(rmidev->rmi4_data,
*f_pos,
rmidev->tmpbuf,
count);
if (retval >= 0)
*f_pos += retval;
unlock:
mutex_unlock(&(dev_data->file_mutex));
return retval;
}
static int rmidev_open(struct inode *inp, struct file *filp)
{
int retval = 0;
struct synaptics_rmi4_data *rmi4_data = rmidev->rmi4_data;
struct rmidev_data *dev_data =
container_of(inp->i_cdev, struct rmidev_data, main_dev);
if (!dev_data)
return -EACCES;
if (rmi4_data->sensor_sleep) {
dev_err(rmi4_data->pdev->dev.parent,
"%s: Sensor sleeping\n",
__func__);
return -ENODEV;
}
rmi4_data->stay_awake = true;
filp->private_data = dev_data;
mutex_lock(&(dev_data->file_mutex));
rmi4_data->irq_enable(rmi4_data, false, false);
dev_dbg(rmi4_data->pdev->dev.parent,
"%s: Attention interrupt disabled\n",
__func__);
if (dev_data->ref_count < 1)
dev_data->ref_count++;
else
retval = -EACCES;
mutex_unlock(&(dev_data->file_mutex));
return retval;
}
static int rmidev_release(struct inode *inp, struct file *filp)
{
struct synaptics_rmi4_data *rmi4_data = rmidev->rmi4_data;
struct rmidev_data *dev_data =
container_of(inp->i_cdev, struct rmidev_data, main_dev);
if (!dev_data)
return -EACCES;
mutex_lock(&(dev_data->file_mutex));
dev_data->ref_count--;
if (dev_data->ref_count < 0)
dev_data->ref_count = 0;
rmi4_data->irq_enable(rmi4_data, true, false);
dev_dbg(rmi4_data->pdev->dev.parent,
"%s: Attention interrupt enabled\n",
__func__);
mutex_unlock(&(dev_data->file_mutex));
rmi4_data->reset_device(rmi4_data, false);
rmi4_data->stay_awake = false;
return 0;
}
static const struct file_operations rmidev_fops = {
.owner = THIS_MODULE,
.llseek = rmidev_llseek,
.read = rmidev_read,
.write = rmidev_write,
.open = rmidev_open,
.release = rmidev_release,
};
static void rmidev_device_cleanup(struct rmidev_data *dev_data)
{
dev_t devno;
struct synaptics_rmi4_data *rmi4_data = rmidev->rmi4_data;
if (dev_data) {
devno = dev_data->main_dev.dev;
if (dev_data->device_class)
device_destroy(dev_data->device_class, devno);
cdev_del(&dev_data->main_dev);
unregister_chrdev_region(devno, 1);
dev_dbg(rmi4_data->pdev->dev.parent,
"%s: rmidev device removed\n",
__func__);
}
return;
}
static char *rmi_char_devnode(struct device *dev, umode_t *mode)
{
if (!mode)
return NULL;
*mode = (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH);
return kasprintf(GFP_KERNEL, "rmi/%s", dev_name(dev));
}
static int rmidev_create_device_class(void)
{
if (rmidev_device_class != NULL)
return 0;
rmidev_device_class = class_create(THIS_MODULE, DEVICE_CLASS_NAME);
if (IS_ERR(rmidev_device_class)) {
pr_err("%s: Failed to create /dev/%s\n",
__func__, CHAR_DEVICE_NAME);
return -ENODEV;
}
rmidev_device_class->devnode = rmi_char_devnode;
return 0;
}
static void rmidev_attn(struct synaptics_rmi4_data *rmi4_data,
unsigned char intr_mask)
{
if (!rmidev)
return;
if (rmidev->pid && (rmidev->intr_mask & intr_mask))
send_sig_info(SIGIO, &rmidev->interrupt_signal, rmidev->task);
return;
}
static int rmidev_init_device(struct synaptics_rmi4_data *rmi4_data)
{
int retval;
dev_t dev_no;
unsigned char attr_count;
struct rmidev_data *dev_data;
struct device *device_ptr;
const struct synaptics_dsx_board_data *bdata =
rmi4_data->hw_if->board_data;
if (rmidev) {
dev_dbg(rmi4_data->pdev->dev.parent,
"%s: Handle already exists\n",
__func__);
return 0;
}
rmidev = kzalloc(sizeof(*rmidev), GFP_KERNEL);
if (!rmidev) {
dev_err(rmi4_data->pdev->dev.parent,
"%s: Failed to alloc mem for rmidev\n",
__func__);
retval = -ENOMEM;
goto err_rmidev;
}
rmidev->rmi4_data = rmi4_data;
memset(&rmidev->interrupt_signal, 0, sizeof(rmidev->interrupt_signal));
rmidev->interrupt_signal.si_signo = SIGIO;
rmidev->interrupt_signal.si_code = SI_USER;
memset(&rmidev->terminate_signal, 0, sizeof(rmidev->terminate_signal));
rmidev->terminate_signal.si_signo = SIGTERM;
rmidev->terminate_signal.si_code = SI_USER;
retval = rmidev_create_device_class();
if (retval < 0) {
dev_err(rmi4_data->pdev->dev.parent,
"%s: Failed to create device class\n",
__func__);
goto err_device_class;
}
if (rmidev_major_num) {
dev_no = MKDEV(rmidev_major_num, DEV_NUMBER);
retval = register_chrdev_region(dev_no, 1, CHAR_DEVICE_NAME);
} else {
retval = alloc_chrdev_region(&dev_no, 0, 1, CHAR_DEVICE_NAME);
if (retval < 0) {
dev_err(rmi4_data->pdev->dev.parent,
"%s: Failed to allocate char device region\n",
__func__);
goto err_device_region;
}
rmidev_major_num = MAJOR(dev_no);
dev_dbg(rmi4_data->pdev->dev.parent,
"%s: Major number of rmidev = %d\n",
__func__, rmidev_major_num);
}
dev_data = kzalloc(sizeof(*dev_data), GFP_KERNEL);
if (!dev_data) {
dev_err(rmi4_data->pdev->dev.parent,
"%s: Failed to alloc mem for dev_data\n",
__func__);
retval = -ENOMEM;
goto err_dev_data;
}
mutex_init(&dev_data->file_mutex);
dev_data->rmi_dev = rmidev;
rmidev->data = dev_data;
cdev_init(&dev_data->main_dev, &rmidev_fops);
retval = cdev_add(&dev_data->main_dev, dev_no, 1);
if (retval < 0) {
dev_err(rmi4_data->pdev->dev.parent,
"%s: Failed to add rmi char device\n",
__func__);
goto err_char_device;
}
dev_set_name(&rmidev->dev, "rmidev%d", MINOR(dev_no));
dev_data->device_class = rmidev_device_class;
device_ptr = device_create(dev_data->device_class, NULL, dev_no,
NULL, CHAR_DEVICE_NAME"%d", MINOR(dev_no));
if (IS_ERR(device_ptr)) {
dev_err(rmi4_data->pdev->dev.parent,
"%s: Failed to create rmi char device\n",
__func__);
retval = -ENODEV;
goto err_char_device;
}
retval = gpio_export(bdata->irq_gpio, false);
if (retval < 0) {
dev_err(rmi4_data->pdev->dev.parent,
"%s: Failed to export attention gpio\n",
__func__);
} else {
retval = gpio_export_link(&(rmi4_data->input_dev->dev),
"attn", bdata->irq_gpio);
if (retval < 0) {
dev_err(rmi4_data->pdev->dev.parent,
"%s Failed to create gpio symlink\n",
__func__);
} else {
dev_dbg(rmi4_data->pdev->dev.parent,
"%s: Exported attention gpio %d\n",
__func__, bdata->irq_gpio);
}
}
rmidev->sysfs_dir = kobject_create_and_add(SYSFS_FOLDER_NAME,
&rmi4_data->input_dev->dev.kobj);
if (!rmidev->sysfs_dir) {
dev_err(rmi4_data->pdev->dev.parent,
"%s: Failed to create sysfs directory\n",
__func__);
retval = -ENODEV;
goto err_sysfs_dir;
}
retval = sysfs_create_bin_file(rmidev->sysfs_dir,
&attr_data);
if (retval < 0) {
dev_err(rmi4_data->pdev->dev.parent,
"%s: Failed to create sysfs bin file\n",
__func__);
goto err_sysfs_bin;
}
for (attr_count = 0; attr_count < ARRAY_SIZE(attrs); attr_count++) {
retval = sysfs_create_file(rmidev->sysfs_dir,
&attrs[attr_count].attr);
if (retval < 0) {
dev_err(rmi4_data->pdev->dev.parent,
"%s: Failed to create sysfs attributes\n",
__func__);
retval = -ENODEV;
goto err_sysfs_attrs;
}
}
return 0;
err_sysfs_attrs:
for (attr_count--; attr_count >= 0; attr_count--)
sysfs_remove_file(rmidev->sysfs_dir, &attrs[attr_count].attr);
sysfs_remove_bin_file(rmidev->sysfs_dir, &attr_data);
err_sysfs_bin:
kobject_put(rmidev->sysfs_dir);
err_sysfs_dir:
err_char_device:
rmidev_device_cleanup(dev_data);
kfree(dev_data);
err_dev_data:
unregister_chrdev_region(dev_no, 1);
err_device_region:
if (rmidev_device_class != NULL) {
class_destroy(rmidev_device_class);
rmidev_device_class = NULL;
}
err_device_class:
kfree(rmidev);
rmidev = NULL;
err_rmidev:
return retval;
}
static void rmidev_remove_device(struct synaptics_rmi4_data *rmi4_data)
{
unsigned char attr_count;
struct rmidev_data *dev_data;
const struct synaptics_dsx_board_data *bdata =
rmi4_data->hw_if->board_data;
if (!rmidev)
goto exit;
for (attr_count = 0; attr_count < ARRAY_SIZE(attrs); attr_count++)
sysfs_remove_file(rmidev->sysfs_dir, &attrs[attr_count].attr);
sysfs_remove_bin_file(rmidev->sysfs_dir, &attr_data);
kobject_put(rmidev->sysfs_dir);
gpio_unexport(bdata->irq_gpio);
dev_data = rmidev->data;
if (dev_data) {
rmidev_device_cleanup(dev_data);
kfree(dev_data);
}
unregister_chrdev_region(rmidev->dev_no, 1);
if (rmidev_device_class != NULL) {
class_destroy(rmidev_device_class);
rmidev_device_class = NULL;
}
kfree(rmidev->tmpbuf);
kfree(rmidev);
rmidev = NULL;
exit:
complete(&rmidev_remove_complete_v26);
return;
}
static struct synaptics_rmi4_exp_fn rmidev_module = {
.fn_type = RMI_DEV,
.init = rmidev_init_device,
.remove = rmidev_remove_device,
.reset = NULL,
.reinit = NULL,
.early_suspend = NULL,
.suspend = NULL,
.resume = NULL,
.late_resume = NULL,
.attn = rmidev_attn,
};
static int __init rmidev_module_init(void)
{
synaptics_rmi4_new_function(&rmidev_module, true);
return 0;
}
static void __exit rmidev_module_exit(void)
{
synaptics_rmi4_new_function(&rmidev_module, false);
wait_for_completion(&rmidev_remove_complete_v26);
return;
}
module_init(rmidev_module_init);
module_exit(rmidev_module_exit);
MODULE_AUTHOR("Synaptics, Inc.");
MODULE_DESCRIPTION("Synaptics DSX RMI Dev Module");
MODULE_LICENSE("GPL v2");
| 23.925581 | 79 | 0.721501 |
318b42fde965af3ac296f98242c832140e6045e8 | 1,272 | h | C | memtools_memory_interface.h | jordan-bonecutter/memtools | f344847b3e6f948181ce3fdd33b80a62366b2012 | [
"BSD-3-Clause"
] | 13 | 2020-08-13T05:09:19.000Z | 2020-08-17T08:30:34.000Z | memtools_memory_interface.h | jordan-bonecutter/memtools | f344847b3e6f948181ce3fdd33b80a62366b2012 | [
"BSD-3-Clause"
] | 4 | 2020-08-15T19:06:08.000Z | 2020-08-15T21:39:14.000Z | memtools_memory_interface.h | jordan-bonecutter/memtools | f344847b3e6f948181ce3fdd33b80a62366b2012 | [
"BSD-3-Clause"
] | null | null | null | /* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* memtools_memory_interface.h * * * * * * * * * * * * * * * * * * * */
/* 6 august 2020 * * * * * * * * * * * * * * * * * * * * * * * * * * */
/* jordan bonecutter * * * * * * * * * * * * * * * * * * * * * * * * */
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
#ifndef memtools_memory_interface_INCLUDE_GUARD
#define memtools_memory_interface_INCLUDE_GUARD
typedef struct{
unsigned int line;
uint8_t* memstart;
size_t n;
char **comments, *file, *alloc_type;
unsigned int n_comments;
}memtools_allocation;
typedef struct{
bool is_valid_ptr, shifted_ptr;
size_t n_bytes;
void* memstart;
}memtools_free_info;
typedef void* memtools_memory_interface;
memtools_memory_interface* memtools_memory_interface_create();
memtools_allocation* memtools_memory_interface_add_allocation(memtools_memory_interface**, size_t n);
memtools_allocation* memtools_memory_interface_get_allocation_for_pointer(memtools_memory_interface*, void*);
memtools_free_info memtools_memory_interface_destroy_allocation_by_pointer(memtools_memory_interface**, void*);
void memtools_memory_interface_for_each(memtools_memory_interface*, void (*for_each)(memtools_allocation*));
#endif
| 37.411765 | 111 | 0.650157 |
c8df1d597dee4fab0c8fc07304ef95cdc84a9fa3 | 3,730 | h | C | octovis/include/octovis/ViewerWidget.h | fmder/octomap | a38647a0d03fc4aba90c2f8212a8d5a871ed63b7 | [
"BSD-3-Clause"
] | null | null | null | octovis/include/octovis/ViewerWidget.h | fmder/octomap | a38647a0d03fc4aba90c2f8212a8d5a871ed63b7 | [
"BSD-3-Clause"
] | null | null | null | octovis/include/octovis/ViewerWidget.h | fmder/octomap | a38647a0d03fc4aba90c2f8212a8d5a871ed63b7 | [
"BSD-3-Clause"
] | null | null | null | /*
* OctoMap - An Efficient Probabilistic 3D Mapping Framework Based on Octrees
* http://octomap.github.com/
*
* Copyright (c) 2009-2013, K.M. Wurm and A. Hornung, University of Freiburg
* All rights reserved.
* License (octovis): GNU GPL v2
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.txt
*
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
#ifndef VIEWERWIDGET_H_
#define VIEWERWIDGET_H_
#include "SceneObject.h"
#include "SelectionBox.h"
#include <octomap/octomap.h>
#include <qglviewer.h>
namespace octomap{
class ViewerWidget : public QGLViewer {
Q_OBJECT
public:
ViewerWidget(QWidget* parent = NULL);
void clearAll();
/**
* Adds an object to the scene that can be drawn
*
* @param obj SceneObject to be added
*/
void addSceneObject(SceneObject* obj);
/**
* Removes a SceneObject from the list of drawable objects if
* it has been added previously. Does nothing otherwise.
*
* @param obj SceneObject to be removed
*/
void removeSceneObject(SceneObject* obj);
public slots:
void enablePrintoutMode (bool enabled = true);
void enableHeightColorMode (bool enabled = true);
void enableSemanticColoring (bool enabled = true);
void enableSelectionBox (bool enabled = true);
void setCamPosition(double x, double y, double z, double lookX, double lookY, double lookZ);
void setCamPose(const octomath::Pose6D& pose);
virtual void setSceneBoundingBox(const qglviewer::Vec& min, const qglviewer::Vec& max);
void deleteCameraPath(int id);
void appendToCameraPath(int id, const octomath::Pose6D& pose);
void appendCurrentToCameraPath(int id);
void addCurrentToCameraPath(int id, int frame);
void removeFromCameraPath(int id, int frame);
void updateCameraPath(int id, int frame);
void jumpToCamFrame(int id, int frame);
void playCameraPath(int id, int start_frame);
void stopCameraPath(int id);
const SelectionBox& selectionBox() const { return m_selectionBox;}
/**
* Resets the 3D viewpoint to the initial value
*/
void resetView();
private slots:
void cameraPathFinished();
void cameraPathInterpolated();
signals:
void cameraPathStopped(int id);
void cameraPathFrameChanged(int id, int current_camera_frame);
protected:
virtual void draw();
virtual void drawWithNames();
virtual void init();
/**
* Overloaded from QGLViewer. Draws own axis and grid in scale, then calls QGLViewer::postDraw().
*/
virtual void postDraw();
virtual void postSelection(const QPoint&);
virtual QString helpString() const;
qglviewer::Quaternion poseToQGLQuaternion(const octomath::Pose6D& pose);
std::vector<SceneObject*> m_sceneObjects;
SelectionBox m_selectionBox;
bool m_printoutMode;
bool m_heightColorMode;
bool m_semantic_coloring;
bool m_drawAxis; // actual state of axis (original overwritten)
bool m_drawGrid; // actual state of grid (original overwritten)
bool m_drawSelectionBox;
double m_zMin;
double m_zMax;
int m_current_camera_path;
int m_current_camera_frame;
};
}
#endif /* VIEWERWIDGET_H_ */
| 29.603175 | 99 | 0.738874 |
c8e6c00007bb6eb586b684398a19f6ffaa783f45 | 504 | h | C | server/parser.h | zhyzhyzhy/tinyhttp | 17377110fd6abe32a1d376e5ef95b24651475a80 | [
"MIT"
] | 1 | 2017-07-20T17:47:45.000Z | 2017-07-20T17:47:45.000Z | server/parser.h | zhyzhyzhy/tinyhttp | 17377110fd6abe32a1d376e5ef95b24651475a80 | [
"MIT"
] | null | null | null | server/parser.h | zhyzhyzhy/tinyhttp | 17377110fd6abe32a1d376e5ef95b24651475a80 | [
"MIT"
] | null | null | null | //
// Created by 朱逸尘 on 2017/11/6.
//
#ifndef TINYHTTP_PARSER_H
#define TINYHTTP_PARSER_H
typedef struct {
int status_code;
const char *status_message;
}http_status_pair;
typedef struct {
const char* type;
const char* value;
}http_mime_type;
const char* parse_http_code(int httpcode);
int parse_http_request_line(int conn_fd, char* method, char* path, char* version);
int check_read_done(char* request_head);
const char* parse_mime_type(const char* path);
#endif //TINYHTTP_PARSER_H
| 21 | 82 | 0.753968 |
da0145205b5c5594f7d89c110b1296a15db6f70f | 1,159 | h | C | src/core/inc/IGraphFactory.h | SebaMaio/complexnets | 0f6e0278293ee8a2d2a1574a61507d3bfffecb06 | [
"AFL-3.0"
] | null | null | null | src/core/inc/IGraphFactory.h | SebaMaio/complexnets | 0f6e0278293ee8a2d2a1574a61507d3bfffecb06 | [
"AFL-3.0"
] | null | null | null | src/core/inc/IGraphFactory.h | SebaMaio/complexnets | 0f6e0278293ee8a2d2a1574a61507d3bfffecb06 | [
"AFL-3.0"
] | null | null | null | #pragma once
#include "IBetweenness.h"
#include "IClusteringCoefficient.h"
#include "IDegreeDistribution.h"
#include "IGraphReader.h"
#include "INearestNeighborsDegree.h"
#include "IShellIndex.h"
#include "MaxClique.h"
#include "StrengthDistribution.h"
#include "typedefs.h"
namespace graphpp
{
template <class Graph, class Vertex>
class IGraphFactory
{
public:
virtual IBetweenness<Graph, Vertex>* createBetweenness(Graph& g) = 0;
virtual IClusteringCoefficient<Graph, Vertex>* createClusteringCoefficient() = 0;
virtual INearestNeighborsDegree<Graph, Vertex>* createNearestNeighborsDegree() = 0;
virtual IShellIndex<Graph, Vertex>* createShellIndex(Graph& g) = 0;
virtual IGraphReader<Graph, Vertex>* createGraphReader() = 0;
virtual IDegreeDistribution<Graph, Vertex>* createDegreeDistribution(Graph& g) = 0;
virtual StrengthDistribution<Graph, Vertex>* createStrengthDistribution(Graph& g) = 0;
virtual MaxClique<Graph, Vertex>* createMaxClique(Graph& g) = 0;
virtual MaxCliqueExact<Graph, Vertex>* createExactMaxClique(Graph& g, int max_time) = 0;
virtual ~IGraphFactory() {}
};
} // namespace graphpp
| 28.975 | 92 | 0.753236 |
ecab76a3207c08e2fd9ad58772bbde3104018154 | 1,097 | h | C | kernel/linux-4.13/drivers/rtc/rtc-core.h | ShawnZhong/SplitFS | 7e21a6fc505ff70802e5666d097326ecb97a4ae3 | [
"Apache-2.0"
] | 31 | 2018-01-16T17:11:44.000Z | 2022-03-16T13:51:24.000Z | kernel/linux-4.13/drivers/rtc/rtc-core.h | braymill/SplitFS | 00a42bb1b51718048e4c15dde31e9d358932575e | [
"Apache-2.0"
] | 5 | 2020-04-04T09:24:09.000Z | 2020-04-19T12:33:55.000Z | kernel/linux-4.13/drivers/rtc/rtc-core.h | braymill/SplitFS | 00a42bb1b51718048e4c15dde31e9d358932575e | [
"Apache-2.0"
] | 30 | 2018-05-02T08:43:27.000Z | 2022-01-23T03:25:54.000Z | #ifdef CONFIG_RTC_INTF_DEV
extern void __init rtc_dev_init(void);
extern void __exit rtc_dev_exit(void);
extern void rtc_dev_prepare(struct rtc_device *rtc);
#else
static inline void rtc_dev_init(void)
{
}
static inline void rtc_dev_exit(void)
{
}
static inline void rtc_dev_prepare(struct rtc_device *rtc)
{
}
#endif
#ifdef CONFIG_RTC_INTF_PROC
extern void rtc_proc_add_device(struct rtc_device *rtc);
extern void rtc_proc_del_device(struct rtc_device *rtc);
#else
static inline void rtc_proc_add_device(struct rtc_device *rtc)
{
}
static inline void rtc_proc_del_device(struct rtc_device *rtc)
{
}
#endif
#ifdef CONFIG_RTC_INTF_SYSFS
const struct attribute_group **rtc_get_dev_attribute_groups(void);
#else
static inline const struct attribute_group **rtc_get_dev_attribute_groups(void)
{
return NULL;
}
#endif
#ifdef CONFIG_RTC_NVMEM
void rtc_nvmem_register(struct rtc_device *rtc);
void rtc_nvmem_unregister(struct rtc_device *rtc);
#else
static inline void rtc_nvmem_register(struct rtc_device *rtc) {}
static inline void rtc_nvmem_unregister(struct rtc_device *rtc) {}
#endif
| 19.589286 | 79 | 0.80948 |
aeb048c12ae91d4a800cfa019212712b759b145d | 244 | c | C | C/pg62_joao.c | SigmaRS/Algoritmos | e9e88ca844a45c4f7a1197493ae7934e7ac78789 | [
"Unlicense"
] | null | null | null | C/pg62_joao.c | SigmaRS/Algoritmos | e9e88ca844a45c4f7a1197493ae7934e7ac78789 | [
"Unlicense"
] | null | null | null | C/pg62_joao.c | SigmaRS/Algoritmos | e9e88ca844a45c4f7a1197493ae7934e7ac78789 | [
"Unlicense"
] | null | null | null | #include <stdio.h>
#include <conio.h>
int main()
{
char str[5] = "Joao";
printf("String: %s", str);
printf("\nSegunda letra: %c", str[1]);
str[1] = 'U';
printf("\nString: %s", str);
printf("\nSegunda letra: %c", str[1]);
getch();
}
| 15.25 | 39 | 0.557377 |
aed41f7ac8d11941d06d6bcc0ad385766cd426ac | 4,630 | h | C | examples/pxScene2d/external/libnode-v10.15.3/deps/icu-small/source/i18n/collationsets.h | madanagopaltcomcast/pxCore | c4a3a40a190521c8b6383d126c87612eca5b3c42 | [
"Apache-2.0"
] | 12,278 | 2015-01-29T17:11:33.000Z | 2022-03-31T21:12:00.000Z | examples/pxScene2d/external/libnode-v10.15.3/deps/icu-small/source/i18n/collationsets.h | madanagopaltcomcast/pxCore | c4a3a40a190521c8b6383d126c87612eca5b3c42 | [
"Apache-2.0"
] | 9,469 | 2015-01-30T05:33:07.000Z | 2022-03-31T16:17:21.000Z | examples/pxScene2d/external/libnode-v10.15.3/deps/icu-small/source/i18n/collationsets.h | madanagopaltcomcast/pxCore | c4a3a40a190521c8b6383d126c87612eca5b3c42 | [
"Apache-2.0"
] | 892 | 2015-01-29T16:26:19.000Z | 2022-03-20T07:44:30.000Z | // © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
* Copyright (C) 2013-2014, International Business Machines
* Corporation and others. All Rights Reserved.
*******************************************************************************
* collationsets.h
*
* created on: 2013feb09
* created by: Markus W. Scherer
*/
#ifndef __COLLATIONSETS_H__
#define __COLLATIONSETS_H__
#include "unicode/utypes.h"
#if !UCONFIG_NO_COLLATION
#include "unicode/uniset.h"
#include "collation.h"
U_NAMESPACE_BEGIN
struct CollationData;
/**
* Finds the set of characters and strings that sort differently in the tailoring
* from the base data.
*
* Every mapping in the tailoring needs to be compared to the base,
* because some mappings are copied for optimization, and
* all contractions for a character are copied if any contractions for that character
* are added, modified or removed.
*
* It might be simpler to re-parse the rule string, but:
* - That would require duplicating some of the from-rules builder code.
* - That would make the runtime code depend on the builder.
* - That would only work if we have the rule string, and we allow users to
* omit the rule string from data files.
*/
class TailoredSet : public UMemory {
public:
TailoredSet(UnicodeSet *t)
: data(NULL), baseData(NULL),
tailored(t),
suffix(NULL),
errorCode(U_ZERO_ERROR) {}
void forData(const CollationData *d, UErrorCode &errorCode);
/**
* @return U_SUCCESS(errorCode) in C++, void in Java
* @internal only public for access by callback
*/
UBool handleCE32(UChar32 start, UChar32 end, uint32_t ce32);
private:
void compare(UChar32 c, uint32_t ce32, uint32_t baseCE32);
void comparePrefixes(UChar32 c, const UChar *p, const UChar *q);
void compareContractions(UChar32 c, const UChar *p, const UChar *q);
void addPrefixes(const CollationData *d, UChar32 c, const UChar *p);
void addPrefix(const CollationData *d, const UnicodeString &pfx, UChar32 c, uint32_t ce32);
void addContractions(UChar32 c, const UChar *p);
void addSuffix(UChar32 c, const UnicodeString &sfx);
void add(UChar32 c);
/** Prefixes are reversed in the data structure. */
void setPrefix(const UnicodeString &pfx) {
unreversedPrefix = pfx;
unreversedPrefix.reverse();
}
void resetPrefix() {
unreversedPrefix.remove();
}
const CollationData *data;
const CollationData *baseData;
UnicodeSet *tailored;
UnicodeString unreversedPrefix;
const UnicodeString *suffix;
UErrorCode errorCode;
};
class ContractionsAndExpansions : public UMemory {
public:
class CESink : public UMemory {
public:
virtual ~CESink();
virtual void handleCE(int64_t ce) = 0;
virtual void handleExpansion(const int64_t ces[], int32_t length) = 0;
};
ContractionsAndExpansions(UnicodeSet *con, UnicodeSet *exp, CESink *s, UBool prefixes)
: data(NULL),
contractions(con), expansions(exp),
sink(s),
addPrefixes(prefixes),
checkTailored(0),
suffix(NULL),
errorCode(U_ZERO_ERROR) {}
void forData(const CollationData *d, UErrorCode &errorCode);
void forCodePoint(const CollationData *d, UChar32 c, UErrorCode &ec);
// all following: @internal, only public for access by callback
void handleCE32(UChar32 start, UChar32 end, uint32_t ce32);
void handlePrefixes(UChar32 start, UChar32 end, uint32_t ce32);
void handleContractions(UChar32 start, UChar32 end, uint32_t ce32);
void addExpansions(UChar32 start, UChar32 end);
void addStrings(UChar32 start, UChar32 end, UnicodeSet *set);
/** Prefixes are reversed in the data structure. */
void setPrefix(const UnicodeString &pfx) {
unreversedPrefix = pfx;
unreversedPrefix.reverse();
}
void resetPrefix() {
unreversedPrefix.remove();
}
const CollationData *data;
UnicodeSet *contractions;
UnicodeSet *expansions;
CESink *sink;
UBool addPrefixes;
int8_t checkTailored; // -1: collected tailored +1: exclude tailored
UnicodeSet tailored;
UnicodeSet ranges;
UnicodeString unreversedPrefix;
const UnicodeString *suffix;
int64_t ces[Collation::MAX_EXPANSION_LENGTH];
UErrorCode errorCode;
};
U_NAMESPACE_END
#endif // !UCONFIG_NO_COLLATION
#endif // __COLLATIONSETS_H__
| 31.931034 | 95 | 0.667387 |
8388bc0c31dea36791f3f5a1b6a81961f20b1976 | 1,109 | h | C | macOS/10.13/AppKit.framework/NSDocumentControllerOpening.h | onmyway133/Runtime-Headers | e9b80e7ab9103f37ad421ad6b8b58ee06369d21f | [
"MIT"
] | 30 | 2016-10-09T20:13:00.000Z | 2022-01-24T04:14:57.000Z | macOS/10.12/AppKit.framework/NSDocumentControllerOpening.h | onmyway133/Runtime-Headers | e9b80e7ab9103f37ad421ad6b8b58ee06369d21f | [
"MIT"
] | null | null | null | macOS/10.12/AppKit.framework/NSDocumentControllerOpening.h | onmyway133/Runtime-Headers | e9b80e7ab9103f37ad421ad6b8b58ee06369d21f | [
"MIT"
] | 7 | 2017-08-29T14:41:25.000Z | 2022-01-19T17:14:54.000Z | /* Generated by RuntimeBrowser
Image: /System/Library/Frameworks/AppKit.framework/Versions/C/AppKit
*/
@interface NSDocumentControllerOpening : NSObject {
NSDocument * _document;
BOOL _documentWasAlreadyOpen;
NSError * _error;
NSString * _recentDocumentRecordsKey;
QLSeamlessDocumentOpener * _seamlessOpener;
NSURL * _url;
}
@property (atomic, readwrite, retain) NSDocument *document;
@property (atomic, readwrite) BOOL documentWasAlreadyOpen;
@property (atomic, readwrite, retain) NSError *error;
@property (atomic, readwrite, retain) NSString *recentDocumentRecordsKey;
@property (atomic, readwrite, retain) QLSeamlessDocumentOpener *seamlessOpener;
@property (setter=setURL:, atomic, readwrite, retain) NSURL *url;
- (void)dealloc;
- (id)document;
- (BOOL)documentWasAlreadyOpen;
- (id)error;
- (id)recentDocumentRecordsKey;
- (id)seamlessOpener;
- (void)setDocument:(id)arg1;
- (void)setDocumentWasAlreadyOpen:(BOOL)arg1;
- (void)setError:(id)arg1;
- (void)setRecentDocumentRecordsKey:(id)arg1;
- (void)setSeamlessOpener:(id)arg1;
- (void)setURL:(id)arg1;
- (id)url;
@end
| 30.805556 | 79 | 0.758341 |
8ae0b9ef379b5f18903030ba983a173128e6261c | 1,640 | h | C | include/Process.h | caiomcg/OS-SchedulingSimulation | e4dcac4db5013492b05741e0aabf9c9a87602418 | [
"MIT"
] | null | null | null | include/Process.h | caiomcg/OS-SchedulingSimulation | e4dcac4db5013492b05741e0aabf9c9a87602418 | [
"MIT"
] | null | null | null | include/Process.h | caiomcg/OS-SchedulingSimulation | e4dcac4db5013492b05741e0aabf9c9a87602418 | [
"MIT"
] | null | null | null | /**
* @class Process
*
* @brief Process simulation class
*
* This Class is responsible for simulating a process. The
* process concists of an arrival time, the process time span
* and the program counter for the process.
*
* @author Caio Marcelo Campoy Guedes <caiomcg@gmail.com>
*/
#ifndef PROCESS_H_
#define PROCESS_H_
class Process {
private:
unsigned int _arrival; /// Process arrival time.
unsigned int _span; /// Process time span.
unsigned int _programCounter; /// Process counter.
bool _run;
public:
/**
* @brief Class constructor.
* @details Initialize the class attributes.
*
* @param int Process arrival time.
* @param int Process time span.
* @param int Process counter(ID).
*/
Process(unsigned int arrival, unsigned int span, unsigned int programCounter);
/**
* @brief Class destructor.
* @details Does base C++ cleanup.
*/
~Process();
/**
* @brief Returns the process arrival time.
*
* @return The arrival time.
*/
unsigned int getArrivalTime() const;
/**
* @brief Returns the process time span.
*
* @return The time span.
*/
unsigned int getProcessSpan() const;
/**
* @brief Set the process time span.
*
* @param int The time span.
*/
void setProcessSpan(const unsigned int span);
/**
* @brief Returns the process counter.
*
* @return The process counter.
*/
unsigned int getProgramCounter() const;
/**
* @brief Get if the process ran.
*
* @return True if ran.
*/
bool getRun() const;
/**
* @brief Set if process ran.
*
* @param run The state of the process.
*/
void setRun(const bool run);
};
#endif // PROCESS_H_ | 21.298701 | 79 | 0.666463 |
1e05834ed12c0907077a89b14db77ffafe807dc9 | 1,511 | h | C | fboss/platform/weutil/WeutilDarwin.h | nathanawmk/fboss | 9f36dbaaae47202f9131598560c65715334a9a83 | [
"BSD-3-Clause"
] | null | null | null | fboss/platform/weutil/WeutilDarwin.h | nathanawmk/fboss | 9f36dbaaae47202f9131598560c65715334a9a83 | [
"BSD-3-Clause"
] | null | null | null | fboss/platform/weutil/WeutilDarwin.h | nathanawmk/fboss | 9f36dbaaae47202f9131598560c65715334a9a83 | [
"BSD-3-Clause"
] | null | null | null | // (c) Facebook, Inc. and its affiliates. Confidential and proprietary.
#pragma once
#include <sstream>
#include <unordered_map>
#include <utility>
#include <vector>
#include "fboss/platform/weutil/WeutilInterface.h"
#include "fboss/platform/weutil/prefdl/prefdl.h"
namespace facebook::fboss::platform {
class WeutilDarwin : public WeutilInterface {
public:
WeutilDarwin();
virtual void printInfo() override;
virtual ~WeutilDarwin() override = default;
protected:
const std::string kPathPrefix_ = "/tmp/WeutilDarwin/";
const std::string kPredfl_ = kPathPrefix_ + "system-prefdl-bin";
const std::string kCreateLayout_ =
"echo \"00001000:0001efff prefdl\" > " + kPathPrefix_ + "layout";
const std::string kFlashRom_ = "flashrom -p internal -l " + kPathPrefix_ +
"layout -i prefdl -r " + kPathPrefix_ + "/bios > /dev/null 2>&1";
const std::string kddComands_ = "dd if=" + kPathPrefix_ +
"/bios of=" + kPredfl_ + " bs=1 skip=8192 count=61440 > /dev/null 2>&1";
// Map weutil fields to prefld fields
const std::unordered_map<std::string, std::string> kMapping_{
{"Product Name", "SID"},
{"Product Part Number", "SKU"},
{"System Assembly Part Number", "ASY"},
{"ODM PCBA Part Number", "PCA"},
{"Product Version", "HwVer"},
{"Product Sub-Version", "HwSubVer"},
{"System Manufacturing Date", "MfgTime2"},
{"Local MAC", "MAC"},
{"Product Serial Number", "SerialNumber"},
};
};
} // namespace facebook::fboss::platform
| 34.340909 | 78 | 0.667108 |
b322f9460426e5ef4ac7059ed7b03b3ceb44980b | 6,366 | c | C | src/modules/periodic/src/periodic.c | mirgor-gnu/ciclador | 0953eb7525d2a0d5935165adb386bc09972d56e7 | [
"MIT-0",
"MIT"
] | 1 | 2020-08-12T17:04:46.000Z | 2020-08-12T17:04:46.000Z | src/modules/periodic/src/periodic.c | mirgor-gnu/ciclador | 0953eb7525d2a0d5935165adb386bc09972d56e7 | [
"MIT-0",
"MIT"
] | null | null | null | src/modules/periodic/src/periodic.c | mirgor-gnu/ciclador | 0953eb7525d2a0d5935165adb386bc09972d56e7 | [
"MIT-0",
"MIT"
] | null | null | null | /*
*
* MIT License
*
* Copyright (c) 2020 Mirgor
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
//********************************************************************
//
//! \file periodic.c
//!
//! \brief This is the periodic module implementation file
//!
//! \author Esteban Pupillo
//!
//! \date 21 Apr 2020
//
//********************************************************************
//********************************************************************
// Include header files
//********************************************************************
#include "standard.h"
#include "logger_api.h"
//********************************************************************
//! @addtogroup periodic_imp
//! @{
//********************************************************************
//********************************************************************
// File level pragmas
//********************************************************************
#include "periodic_conf.h"
#include "periodic_api.h"
#include "periodic_callouts.h"
//********************************************************************
// Constant and Macro Definitions using #define
//********************************************************************
//********************************************************************
// Enumerations and Structures and Typedefs
//********************************************************************
//********************************************************************
// Function Prototypes for Private Functions with File Level Scope
//********************************************************************
static void periodic_task(void);
//********************************************************************
// ROM Const Variables With File Level Scope
//********************************************************************
//********************************************************************
// Static Variables and Const Variables With File Level Scope
//********************************************************************
static void periodic_init(void);
static void periodic_1x(void);
static void periodic_2x(void);
static void periodic_4x(void);
static void periodic_8x(void);
static void periodic_16x(void);
static void periodic_32x(void);
static void periodic_64x(void);
static void periodic_128x(void);
//********************************************************************
// Function Definitions
//********************************************************************
//********************************************************************
//
//! Periodic module initialization
//!
//! \param None.
//!
//! This initialization should be performed prior to starting the
//! RTOS scheduling i.e. called from main() initialization.
//!
//! \return None.
//
//********************************************************************
void Periodic_Init(void)
{
}
void Periodic_Start(void)
{
//start periodic_task
periodic_task();
}
//********************************************************************
//
//! Periodic module task
//!
//! \param None.
//!
//! This is the RTOS task for periodic call handling.
//!
//! \return None.
//
//********************************************************************
static void periodic_task(void)
{
uint8_t slice = 0;
uint32_t lastTicks = 0;
// Initialize required data
periodic_init();
// Task loop
for (;;)
{
// Delay task
if ((HAL_GetTick() - lastTicks) >= PERIODIC_MIN_TIMESLOT)
{
lastTicks = HAL_GetTick();
slice++;
Periodic_OnProcessingStart();
periodic_1x();
if ((0x01 & slice) == 0x01)
periodic_2x();
if ((0x03 & slice) == 0x03)
periodic_4x();
if ((0x07 & slice) == 0x07)
periodic_8x();
if ((0x0F & slice) == 0x0F)
periodic_16x();
if ((0x1F & slice) == 0x1F)
periodic_32x();
if ((0x3F & slice) == 0x3F)
periodic_64x();
if ((0x7F & slice) == 0x7F)
periodic_128x();
Periodic_OnProcessingStop();
}
}
//we should never get here!
}
// Periodic call init
static void periodic_init(void)
{
}
// 1X periodic task (16ms)
static void periodic_1x(void)
{
// call application specific handler
Periodic_handler_1x();
}
// 2X periodic task
static void periodic_2x(void)
{
// call application specific handler
Periodic_handler_2x();
}
// 4X periodic task
static void periodic_4x(void)
{
// call application specific handler
Periodic_handler_4x();
}
// 8X periodic task
static void periodic_8x(void)
{
// call application specific handler
Periodic_handler_8x();
}
// 16X periodic task
static void periodic_16x(void)
{
// call application specific handler
Periodic_handler_16x();
}
// 32X periodic task
static void periodic_32x(void)
{
// call application specific handler
Periodic_handler_32x();
}
// 64X periodic task
static void periodic_64x(void)
{
// call application specific handler
Periodic_handler_64x();
}
// 128X periodic task
static void periodic_128x(void)
{
// call application specific handler
Periodic_handler_128x();
}
//********************************************************************
//
// Close the Doxygen group.
//! @}
//
//********************************************************************
| 26.197531 | 81 | 0.491203 |
1ec1adadd9dc307a4d9a7d8884c9a57ecd552b22 | 34,963 | h | C | nufxlib/NufxLib.h | salfter/ciderpress | 4d85f31f0f0b55c1c9bf3ec85fb8f4c8916978fe | [
"BSD-3-Clause"
] | null | null | null | nufxlib/NufxLib.h | salfter/ciderpress | 4d85f31f0f0b55c1c9bf3ec85fb8f4c8916978fe | [
"BSD-3-Clause"
] | null | null | null | nufxlib/NufxLib.h | salfter/ciderpress | 4d85f31f0f0b55c1c9bf3ec85fb8f4c8916978fe | [
"BSD-3-Clause"
] | null | null | null | /*
* NuFX archive manipulation library
* Copyright (C) 2000-2007 by Andy McFadden, All Rights Reserved.
* This is free software; you can redistribute it and/or modify it under the
* terms of the BSD License, see the file COPYING-LIB.
*
* External interface (types, defines, and function prototypes).
*/
#ifndef NUFXLIB_NUFXLIB_H
#define NUFXLIB_NUFXLIB_H
#include <stdio.h>
#include <stdint.h>
#ifdef __cplusplus
extern "C" {
#endif
/*
* NufxLib version number. Compare these values (which represent the
* version against which your application was compiled) to the values
* returned by NuGetVersion (representing the version against which
* your application is statically or dynamically linked). If the major
* number doesn't match exactly, an existing interface has changed and you
* should halt immediately. If the minor number from NuGetVersion is
* less, there may be new interfaces, new features, or bug fixes missing
* upon which your application depends, so you should halt immediately.
* (If the minor number is greater, there are new features, but your
* application will not be affected by them.)
*
* The "bug" version can usually be ignored, since it represents minor
* fixes. Unless, of course, your code depends upon that fix.
*/
#define kNuVersionMajor 3
#define kNuVersionMinor 0
#define kNuVersionBug 0
/*
* ===========================================================================
* Types
* ===========================================================================
*/
/*
* Unicode character type. For Linux and Mac OS X, filenames use "narrow"
* characters and UTF-8 encoding, which allows them to use standard file I/O
* functions like fopen(). Windows uses UTF-16, which requires a different
* character type and an alternative set of I/O functions like _wfopen().
*
* The idea is that NufxLib API functions will operate on filenames with
* the OS dominant method, so on Windows the API accepts UTF-16. This
* definition is a bit like Windows TCHAR, but it's dependent on the OS, not
* on whether _MBCS or _UNICODE is defined.
*
* The app can include "Unichar.h" to get definitions for functions that
* switch between narrow and wide functions (e.g. "unistrlen()" becomes
* strlen() or wcslen() as appropriate).
*
* We switch based on _WIN32, because we're not really switching on
* filename-character size; the key issue is all the pesky wide I/O calls.
*/
#if defined(_WIN32)
// TODO: complete this
//# include <wchar.h>
//# define UNICHAR wchar_t
# define UNICHAR char
#else
# define UNICHAR char
#endif
/*
* Error values returned from functions.
*
* These are negative so that they don't conflict with system-defined
* errors (like ENOENT). A NuError can hold either.
*/
typedef enum NuError {
kNuErrNone = 0,
kNuErrGeneric = -1,
kNuErrInternal = -2,
kNuErrUsage = -3,
kNuErrSyntax = -4,
kNuErrMalloc = -5,
kNuErrInvalidArg = -6,
kNuErrBadStruct = -7,
kNuErrUnexpectedNil = -8,
kNuErrBusy = -9,
kNuErrSkipped = -10, /* processing skipped by request */
kNuErrAborted = -11, /* processing aborted by request */
kNuErrRename = -12, /* user wants to rename before extracting */
kNuErrFile = -20,
kNuErrFileOpen = -21,
kNuErrFileClose = -22,
kNuErrFileRead = -23,
kNuErrFileWrite = -24,
kNuErrFileSeek = -25,
kNuErrFileExists = -26, /* existed when it shouldn't */
kNuErrFileNotFound = -27, /* didn't exist when it should have */
kNuErrFileStat = -28, /* some sort of GetFileInfo failure */
kNuErrFileNotReadable = -29, /* bad access permissions */
kNuErrDirExists = -30, /* dir exists, don't need to create it */
kNuErrNotDir = -31, /* expected a dir, got a regular file */
kNuErrNotRegularFile = -32, /* expected regular file, got weirdness */
kNuErrDirCreate = -33, /* unable to create a directory */
kNuErrOpenDir = -34, /* error opening directory */
kNuErrReadDir = -35, /* error reading directory */
kNuErrFileSetDate = -36, /* unable to set file date */
kNuErrFileSetAccess = -37, /* unable to set file access permissions */
kNuErrFileAccessDenied = -38, /* equivalent to EACCES */
kNuErrNotNuFX = -40, /* 'NuFile' missing; not a NuFX archive? */
kNuErrBadMHVersion = -41, /* bad master header version */
kNuErrRecHdrNotFound = -42, /* 'NuFX' missing; corrupted archive? */
kNuErrNoRecords = -43, /* archive doesn't have any records */
kNuErrBadRecord = -44, /* something about the record looked bad */
kNuErrBadMHCRC = -45, /* bad master header CRC */
kNuErrBadRHCRC = -46, /* bad record header CRC */
kNuErrBadThreadCRC = -47, /* bad thread header CRC */
kNuErrBadDataCRC = -48, /* bad CRC detected in the data */
kNuErrBadFormat = -50, /* compression type not supported */
kNuErrBadData = -51, /* expansion func didn't like input */
kNuErrBufferOverrun = -52, /* overflowed a user buffer */
kNuErrBufferUnderrun = -53, /* underflowed a user buffer */
kNuErrOutMax = -54, /* output limit exceeded */
kNuErrNotFound = -60, /* (generic) search unsuccessful */
kNuErrRecordNotFound = -61, /* search for specific record failed */
kNuErrRecIdxNotFound = -62, /* search by NuRecordIdx failed */
kNuErrThreadIdxNotFound = -63, /* search by NuThreadIdx failed */
kNuErrThreadIDNotFound = -64, /* search by NuThreadID failed */
kNuErrRecNameNotFound = -65, /* search by storageName failed */
kNuErrRecordExists = -66, /* found existing record with same name */
kNuErrAllDeleted = -70, /* attempt to delete everything */
kNuErrArchiveRO = -71, /* archive is open in read-only mode */
kNuErrModRecChange = -72, /* tried to change modified record */
kNuErrModThreadChange = -73, /* tried to change modified thread */
kNuErrThreadAdd = -74, /* adding that thread creates a conflict */
kNuErrNotPreSized = -75, /* tried to update a non-pre-sized thread */
kNuErrPreSizeOverflow = -76, /* too much data */
kNuErrInvalidFilename = -77, /* invalid filename */
kNuErrLeadingFssep = -80, /* names in archives must not start w/sep */
kNuErrNotNewer = -81, /* item same age or older than existing */
kNuErrDuplicateNotFound = -82, /* "must overwrite" was set, but item DNE */
kNuErrDamaged = -83, /* original archive may have been damaged */
kNuErrIsBinary2 = -90, /* this looks like a Binary II archive */
kNuErrUnknownFeature =-100, /* attempt to test unknown feature */
kNuErrUnsupFeature = -101, /* feature not supported */
} NuError;
/*
* Return values from callback functions.
*/
typedef enum NuResult {
kNuOK = 0,
kNuSkip = 1,
kNuAbort = 2,
/*kNuAbortAll = 3,*/
kNuRetry = 4,
kNuIgnore = 5,
kNuRename = 6,
kNuOverwrite = 7
} NuResult;
/*
* NuRecordIdxs are assigned to records in an archive. You may assume that
* the values are unique, but that is all.
*/
typedef uint32_t NuRecordIdx;
/*
* NuThreadIdxs are assigned to threads within a record. Again, you may
* assume that the values are unique within a record, but that is all.
*/
typedef uint32_t NuThreadIdx;
/*
* Thread ID, a combination of thread_class and thread_kind. Standard
* values have explicit identifiers.
*/
typedef uint32_t NuThreadID;
#define NuMakeThreadID(class, kind) /* construct a NuThreadID */ \
((uint32_t)(class) << 16 | (uint32_t)(kind))
#define NuGetThreadID(pThread) /* pull NuThreadID out of NuThread */ \
(NuMakeThreadID((pThread)->thThreadClass, (pThread)->thThreadKind))
#define NuThreadIDGetClass(threadID) /* get threadClass from NuThreadID */ \
((uint16_t) ((uint32_t)(threadID) >> 16))
#define NuThreadIDGetKind(threadID) /* get threadKind from NuThreadID */ \
((uint16_t) ((threadID) & 0xffff))
#define kNuThreadClassMessage 0x0000
#define kNuThreadClassControl 0x0001
#define kNuThreadClassData 0x0002
#define kNuThreadClassFilename 0x0003
#define kNuThreadIDOldComment NuMakeThreadID(kNuThreadClassMessage, 0x0000)
#define kNuThreadIDComment NuMakeThreadID(kNuThreadClassMessage, 0x0001)
#define kNuThreadIDIcon NuMakeThreadID(kNuThreadClassMessage, 0x0002)
#define kNuThreadIDMkdir NuMakeThreadID(kNuThreadClassControl, 0x0000)
#define kNuThreadIDDataFork NuMakeThreadID(kNuThreadClassData, 0x0000)
#define kNuThreadIDDiskImage NuMakeThreadID(kNuThreadClassData, 0x0001)
#define kNuThreadIDRsrcFork NuMakeThreadID(kNuThreadClassData, 0x0002)
#define kNuThreadIDFilename NuMakeThreadID(kNuThreadClassFilename, 0x0000)
#define kNuThreadIDWildcard NuMakeThreadID(0xffff, 0xffff)
/* enumerate the possible values for thThreadFormat */
typedef enum NuThreadFormat {
kNuThreadFormatUncompressed = 0x0000,
kNuThreadFormatHuffmanSQ = 0x0001,
kNuThreadFormatLZW1 = 0x0002,
kNuThreadFormatLZW2 = 0x0003,
kNuThreadFormatLZC12 = 0x0004,
kNuThreadFormatLZC16 = 0x0005,
kNuThreadFormatDeflate = 0x0006, /* NOTE: not in NuFX standard */
kNuThreadFormatBzip2 = 0x0007, /* NOTE: not in NuFX standard */
} NuThreadFormat;
/* extract the filesystem separator char from the "file_sys_info" field */
#define NuGetSepFromSysInfo(sysInfo) \
((UNICHAR) ((sysInfo) & 0xff))
/* return a file_sys_info with a replaced filesystem separator */
#define NuSetSepInSysInfo(sysInfo, newSep) \
((uint16_t) (((sysInfo) & 0xff00) | ((newSep) & 0xff)) )
/* GS/OS-defined file system identifiers; sadly, UNIX is not among them */
typedef enum NuFileSysID {
kNuFileSysUnknown = 0, /* NuFX spec says use this */
kNuFileSysProDOS = 1,
kNuFileSysDOS33 = 2,
kNuFileSysDOS32 = 3,
kNuFileSysPascal = 4,
kNuFileSysMacHFS = 5,
kNuFileSysMacMFS = 6,
kNuFileSysLisa = 7,
kNuFileSysCPM = 8,
kNuFileSysCharFST = 9,
kNuFileSysMSDOS = 10,
kNuFileSysHighSierra = 11,
kNuFileSysISO9660 = 12,
kNuFileSysAppleShare = 13
} NuFileSysID;
/* simplified definition of storage types */
typedef enum NuStorageType {
kNuStorageUnknown = 0, /* (used by ProDOS for deleted files) */
kNuStorageSeedling = 1, /* <= 512 bytes */
kNuStorageSapling = 2, /* < 128KB */
kNuStorageTree = 3, /* < 16MB */
kNuStoragePascalVol = 4, /* (embedded pascal volume; rare) */
kNuStorageExtended = 5, /* forked (any size) */
kNuStorageDirectory = 13, /* directory */
kNuStorageSubdirHeader = 14, /* (only used in subdir headers) */
kNuStorageVolumeHeader = 15, /* (only used in volume dir header) */
} NuStorageType;
/* bit flags for NuOpenRW */
enum {
kNuOpenCreat = 0x0001,
kNuOpenExcl = 0x0002
};
/*
* The actual NuArchive structure is opaque, and should only be visible
* to the library. We define it here as an ambiguous struct.
*/
typedef struct NuArchive NuArchive;
/*
* Generic callback prototype.
*/
typedef NuResult (*NuCallback)(NuArchive* pArchive, void* args);
/*
* Parameters that affect archive operations.
*/
typedef enum NuValueID {
kNuValueInvalid = 0,
kNuValueIgnoreCRC = 1,
kNuValueDataCompression = 2,
kNuValueDiscardWrapper = 3,
kNuValueEOL = 4,
kNuValueConvertExtractedEOL = 5,
kNuValueOnlyUpdateOlder = 6,
kNuValueAllowDuplicates = 7,
kNuValueHandleExisting = 8,
kNuValueModifyOrig = 9,
kNuValueMimicSHK = 10,
kNuValueMaskDataless = 11,
kNuValueStripHighASCII = 12,
kNuValueJunkSkipMax = 13,
kNuValueIgnoreLZW2Len = 14,
kNuValueHandleBadMac = 15
} NuValueID;
typedef uint32_t NuValue;
/*
* Enumerated values for things you pass in a NuValue.
*/
enum NuValueValue {
/* for the truly retentive */
kNuValueFalse = 0,
kNuValueTrue = 1,
/* for kNuValueDataCompression */
kNuCompressNone = 10,
kNuCompressSQ = 11,
kNuCompressLZW1 = 12,
kNuCompressLZW2 = 13,
kNuCompressLZC12 = 14,
kNuCompressLZC16 = 15,
kNuCompressDeflate = 16,
kNuCompressBzip2 = 17,
/* for kNuValueEOL */
kNuEOLUnknown = 50,
kNuEOLCR = 51,
kNuEOLLF = 52,
kNuEOLCRLF = 53,
/* for kNuValueConvertExtractedEOL */
kNuConvertOff = 60,
kNuConvertOn = 61,
kNuConvertAuto = 62,
/* for kNuValueHandleExisting */
kNuMaybeOverwrite = 90,
kNuNeverOverwrite = 91,
kNuAlwaysOverwrite = 93,
kNuMustOverwrite = 94
};
/*
* Pull out archive attributes.
*/
typedef enum NuAttrID {
kNuAttrInvalid = 0,
kNuAttrArchiveType = 1,
kNuAttrNumRecords = 2,
kNuAttrHeaderOffset = 3,
kNuAttrJunkOffset = 4,
} NuAttrID;
typedef uint32_t NuAttr;
/*
* Archive types.
*/
typedef enum NuArchiveType {
kNuArchiveUnknown, /* .??? */
kNuArchiveNuFX, /* .SHK (sometimes .SDK) */
kNuArchiveNuFXInBNY, /* .BXY */
kNuArchiveNuFXSelfEx, /* .SEA */
kNuArchiveNuFXSelfExInBNY, /* .BSE */
kNuArchiveBNY /* .BNY, .BQY - not supported */
} NuArchiveType;
/*
* Some common values for "locked" and "unlocked". Under ProDOS each bit
* can be set independently, so don't use these defines to *interpret*
* what you see. They're reasonable things to *set* the access field to.
*
* The defined bits are:
* 0x80 'D' destroy enabled
* 0x40 'N' rename enabled
* 0x20 'B' file needs to be backed up
* 0x10 (reserved, must be zero)
* 0x08 (reserved, must be zero)
* 0x04 'I' file is invisible
* 0x02 'W' write enabled
* 0x01 'R' read enabled
*/
#define kNuAccessLocked 0x21
#define kNuAccessUnlocked 0xe3
/*
* NuFlush result flags.
*/
#define kNuFlushSucceeded (1L)
#define kNuFlushAborted (1L << 1)
#define kNuFlushCorrupted (1L << 2)
#define kNuFlushReadOnly (1L << 3)
#define kNuFlushInaccessible (1L << 4)
/*
* ===========================================================================
* NuFX archive defintions
* ===========================================================================
*/
typedef struct NuThreadMod NuThreadMod; /* dummy def for internal struct */
typedef union NuDataSource NuDataSource; /* dummy def for internal struct */
typedef union NuDataSink NuDataSink; /* dummy def for internal struct */
/*
* NuFX Date/Time structure; same as TimeRec from IIgs "misctool.h".
*/
typedef struct NuDateTime {
uint8_t second; /* 0-59 */
uint8_t minute; /* 0-59 */
uint8_t hour; /* 0-23 */
uint8_t year; /* year - 1900 */
uint8_t day; /* 0-30 */
uint8_t month; /* 0-11 */
uint8_t extra; /* (must be zero) */
uint8_t weekDay; /* 1-7 (1=sunday) */
} NuDateTime;
/*
* NuFX "thread" definition.
*
* Guaranteed not to have pointers in it. Can be copied with memcpy or
* assignment.
*/
typedef struct NuThread {
/* from the archive */
uint16_t thThreadClass;
NuThreadFormat thThreadFormat;
uint16_t thThreadKind;
uint16_t thThreadCRC; /* comp or uncomp data; see rec vers */
uint32_t thThreadEOF;
uint32_t thCompThreadEOF;
/* extra goodies */
NuThreadIdx threadIdx;
uint32_t actualThreadEOF; /* disk images might be off */
long fileOffset; /* fseek offset to data in shk */
/* internal use only */
uint16_t used; /* mark as uninteresting */
} NuThread;
/*
* NuFX "record" definition.
*
* (Note to developers: update Nu_AddRecord if this changes.)
*
* The filenames are in Mac OS Roman format. It's arguable whether MOR
* strings should be part of the interface at all. However, the API
* pre-dates the inclusion of Unicode support, and I'm leaving it alone.
*/
#define kNufxIDLen 4 /* len of 'NuFX' with funky MSBs */
#define kNuReasonableAttribCount 256
#define kNuReasonableFilenameLen 1024
#define kNuReasonableTotalThreads 16
#define kNuMaxRecordVersion 3 /* max we can handle */
#define kNuOurRecordVersion 3 /* what we write */
typedef struct NuRecord {
/* version 0+ */
uint8_t recNufxID[kNufxIDLen];
uint16_t recHeaderCRC;
uint16_t recAttribCount;
uint16_t recVersionNumber;
uint32_t recTotalThreads;
NuFileSysID recFileSysID;
uint16_t recFileSysInfo;
uint32_t recAccess;
uint32_t recFileType;
uint32_t recExtraType;
uint16_t recStorageType; /* NuStorage*,file_sys_block_size */
NuDateTime recCreateWhen;
NuDateTime recModWhen;
NuDateTime recArchiveWhen;
/* option lists only in version 1+ */
uint16_t recOptionSize;
uint8_t* recOptionList; /* NULL if v0 or recOptionSize==0 */
/* data specified by recAttribCount, not accounted for by option list */
int32_t extraCount;
uint8_t* extraBytes;
uint16_t recFilenameLength; /* usually zero */
char* recFilenameMOR; /* doubles as disk volume_name */
/* extra goodies; "dirtyHeader" does not apply to anything below */
NuRecordIdx recordIdx; /* session-unique record index */
char* threadFilenameMOR; /* extracted from filename thread */
char* newFilenameMOR; /* memorized during "add file" call */
const char* filenameMOR; /* points at recFilen or threadFilen */
uint32_t recHeaderLength; /* size of rec hdr, incl thread hdrs */
uint32_t totalCompLength; /* total len of data in archive file */
uint32_t fakeThreads; /* used by "MaskDataless" */
int isBadMac; /* malformed "bad mac" header */
long fileOffset; /* file offset of record header */
/* use provided interface to access this */
struct NuThread* pThreads; /* ptr to thread array */
/* private -- things the application shouldn't look at */
struct NuRecord* pNext; /* used internally */
NuThreadMod* pThreadMods; /* used internally */
short dirtyHeader; /* set in "copy" when hdr fields uptd */
short dropRecFilename; /* if set, we're dropping this name */
} NuRecord;
/*
* NuFX "master header" definition.
*
* The "mhReserved2" entry doesn't appear in my copy of the $e0/8002 File
* Type Note, but as best as I can recall the MH block must be 48 bytes.
*/
#define kNufileIDLen 6 /* length of 'NuFile' with funky MSBs */
#define kNufileMasterReserved1Len 8
#define kNufileMasterReserved2Len 6
#define kNuMaxMHVersion 2 /* max we can handle */
#define kNuOurMHVersion 2 /* what we write */
typedef struct NuMasterHeader {
uint8_t mhNufileID[kNufileIDLen];
uint16_t mhMasterCRC;
uint32_t mhTotalRecords;
NuDateTime mhArchiveCreateWhen;
NuDateTime mhArchiveModWhen;
uint16_t mhMasterVersion;
uint8_t mhReserved1[kNufileMasterReserved1Len];
uint32_t mhMasterEOF;
uint8_t mhReserved2[kNufileMasterReserved2Len];
/* private -- internal use only */
short isValid;
} NuMasterHeader;
/*
* ===========================================================================
* Misc declarations
* ===========================================================================
*/
/*
* Record attributes that can be changed with NuSetRecordAttr. This is
* a small subset of the full record.
*/
typedef struct NuRecordAttr {
NuFileSysID fileSysID;
/*uint16_t fileSysInfo;*/
uint32_t access;
uint32_t fileType;
uint32_t extraType;
NuDateTime createWhen;
NuDateTime modWhen;
NuDateTime archiveWhen;
} NuRecordAttr;
/*
* Some additional details about a file.
*
* Ideally (from an API cleanliness perspective) the storage name would
* be passed around as UTF-8 and converted internally. Passing it as
* MOR required fewer changes to the library, and allows us to avoid
* having to deal with illegal characters.
*/
typedef struct NuFileDetails {
/* used during AddFile call */
NuThreadID threadID; /* data, rsrc, disk img? */
const void* origName; /* arbitrary pointer, usually a string */
/* these go straight into the NuRecord */
const char* storageNameMOR;
NuFileSysID fileSysID;
uint16_t fileSysInfo;
uint32_t access;
uint32_t fileType;
uint32_t extraType;
uint16_t storageType; /* use Unknown, or disk block size */
NuDateTime createWhen;
NuDateTime modWhen;
NuDateTime archiveWhen;
} NuFileDetails;
/*
* Passed into the SelectionFilter callback.
*/
typedef struct NuSelectionProposal {
const NuRecord* pRecord;
const NuThread* pThread;
} NuSelectionProposal;
/*
* Passed into the OutputPathnameFilter callback.
*/
typedef struct NuPathnameProposal {
const UNICHAR* pathnameUNI;
UNICHAR filenameSeparator;
const NuRecord* pRecord;
const NuThread* pThread;
const UNICHAR* newPathnameUNI;
UNICHAR newFilenameSeparator;
/*NuThreadID newStorage;*/
NuDataSink* newDataSink;
} NuPathnameProposal;
/* used by error handler and progress updater to indicate what we're doing */
typedef enum NuOperation {
kNuOpUnknown = 0,
kNuOpAdd,
kNuOpExtract,
kNuOpTest,
kNuOpDelete, /* not used for progress updates */
kNuOpContents /* not used for progress updates */
} NuOperation;
/* state of progress when adding or extracting */
typedef enum NuProgressState {
kNuProgressPreparing, /* not started yet */
kNuProgressOpening, /* opening files */
kNuProgressAnalyzing, /* analyzing data */
kNuProgressCompressing, /* compressing data */
kNuProgressStoring, /* storing (no compression) data */
kNuProgressExpanding, /* expanding data */
kNuProgressCopying, /* copying data (in or out) */
kNuProgressDone, /* all done, success */
kNuProgressSkipped, /* all done, we skipped this one */
kNuProgressAborted, /* all done, user cancelled the operation */
kNuProgressFailed /* all done, failure */
} NuProgressState;
/*
* Passed into the ProgressUpdater callback. All pointers become
* invalid when the callback returns.
*
* [ Thought for the day: add an optional flag that causes us to only
* call the progressFunc when the "percentComplete" changes by more
* than a specified amount. ]
*/
typedef struct NuProgressData {
/* what are we doing */
NuOperation operation;
/* what specifically are we doing */
NuProgressState state;
/* how far along are we */
short percentComplete; /* 0-100 */
/* original pathname (in archive for expand, on disk for compress) */
const UNICHAR* origPathnameUNI;
/* processed pathname (PathnameFilter for expand, in-record for compress) */
const UNICHAR* pathnameUNI;
/* basename of "pathname" (for convenience) */
const UNICHAR* filenameUNI;
/* pointer to the record we're expanding from */
const NuRecord* pRecord;
uint32_t uncompressedLength; /* size of uncompressed data */
uint32_t uncompressedProgress; /* #of bytes in/out */
struct {
NuThreadFormat threadFormat; /* compression being applied */
} compress;
struct {
uint32_t totalCompressedLength; /* all "data" threads */
uint32_t totalUncompressedLength;
/*uint32_t compressedLength; * size of compressed data */
/*uint32_t compressedProgress; * #of compressed bytes in/out*/
const NuThread* pThread; /* thread we're working on */
NuValue convertEOL; /* set if LF/CR conv is on */
} expand;
/* pay no attention */
NuCallback progressFunc;
} NuProgressData;
/*
* Passed into the ErrorHandler callback.
*/
typedef struct NuErrorStatus {
NuOperation operation; /* were we adding, extracting, ?? */
NuError err; /* library error code */
int sysErr; /* system error code, if applicable */
const UNICHAR* message; /* (optional) message to user */
const NuRecord* pRecord; /* relevant record, if any */
const UNICHAR* pathnameUNI; /* problematic pathname, if any */
const void* origPathname; /* original pathname ref, if any */
UNICHAR filenameSeparator; /* fssep for pathname, if any */
/*char origArchiveTouched;*/
char canAbort; /* give option to abort */
/*char canAbortAll;*/ /* abort + discard all recent changes */
char canRetry; /* give option to retry same op */
char canIgnore; /* give option to ignore error */
char canSkip; /* give option to skip this file/rec */
char canRename; /* give option to rename file */
char canOverwrite; /* give option to overwrite file */
} NuErrorStatus;
/*
* Error message callback gets one of these.
*/
typedef struct NuErrorMessage {
const char* message; /* the message itself (UTF-8) */
NuError err; /* relevant error code (may be none) */
short isDebug; /* set for debug-only messages */
/* these identify where the message originated if lib built w/debug set */
const char* file; /* source file (UTF-8) */
int line; /* line number */
const char* function; /* function name (might be NULL) */
} NuErrorMessage;
/*
* Options for the NuTestFeature function.
*/
typedef enum NuFeature {
kNuFeatureUnknown = 0,
kNuFeatureCompressSQ = 1, /* kNuThreadFormatHuffmanSQ */
kNuFeatureCompressLZW = 2, /* kNuThreadFormatLZW1 and LZW2 */
kNuFeatureCompressLZC = 3, /* kNuThreadFormatLZC12 and LZC16 */
kNuFeatureCompressDeflate = 4, /* kNuThreadFormatDeflate */
kNuFeatureCompressBzip2 = 5, /* kNuThreadFormatBzip2 */
} NuFeature;
/*
* ===========================================================================
* Function prototypes
* ===========================================================================
*/
/*
* Win32 dll magic.
*/
#if defined(_WIN32)
# include <windows.h>
# if defined(NUFXLIB_EXPORTS)
/* building the NufxLib DLL */
# define NUFXLIB_API __declspec(dllexport)
# elif defined (NUFXLIB_DLL)
/* building to link against the NufxLib DLL */
# define NUFXLIB_API __declspec(dllimport)
# else
/* using static libs */
# define NUFXLIB_API
# endif
#else
/* not using Win32... hooray! */
# define NUFXLIB_API
#endif
/* streaming and non-streaming read-only interfaces */
NUFXLIB_API NuError NuStreamOpenRO(FILE* infp, NuArchive** ppArchive);
NUFXLIB_API NuError NuContents(NuArchive* pArchive, NuCallback contentFunc);
NUFXLIB_API NuError NuExtract(NuArchive* pArchive);
NUFXLIB_API NuError NuTest(NuArchive* pArchive);
/* strictly non-streaming read-only interfaces */
NUFXLIB_API NuError NuOpenRO(const UNICHAR* archivePathnameUNI,
NuArchive** ppArchive);
NUFXLIB_API NuError NuExtractRecord(NuArchive* pArchive, NuRecordIdx recordIdx);
NUFXLIB_API NuError NuExtractThread(NuArchive* pArchive, NuThreadIdx threadIdx,
NuDataSink* pDataSink);
NUFXLIB_API NuError NuTestRecord(NuArchive* pArchive, NuRecordIdx recordIdx);
NUFXLIB_API NuError NuGetRecord(NuArchive* pArchive, NuRecordIdx recordIdx,
const NuRecord** ppRecord);
NUFXLIB_API NuError NuGetRecordIdxByName(NuArchive* pArchive,
const char* nameMOR, NuRecordIdx* pRecordIdx);
NUFXLIB_API NuError NuGetRecordIdxByPosition(NuArchive* pArchive,
uint32_t position, NuRecordIdx* pRecordIdx);
/* read/write interfaces */
NUFXLIB_API NuError NuOpenRW(const UNICHAR* archivePathnameUNI,
const UNICHAR* tempPathnameUNI, uint32_t flags,
NuArchive** ppArchive);
NUFXLIB_API NuError NuFlush(NuArchive* pArchive, uint32_t* pStatusFlags);
NUFXLIB_API NuError NuAddRecord(NuArchive* pArchive,
const NuFileDetails* pFileDetails, NuRecordIdx* pRecordIdx);
NUFXLIB_API NuError NuAddThread(NuArchive* pArchive, NuRecordIdx recordIdx,
NuThreadID threadID, NuDataSource* pDataSource,
NuThreadIdx* pThreadIdx);
NUFXLIB_API NuError NuAddFile(NuArchive* pArchive, const UNICHAR* pathnameUNI,
const NuFileDetails* pFileDetails, short fromRsrcFork,
NuRecordIdx* pRecordIdx);
NUFXLIB_API NuError NuRename(NuArchive* pArchive, NuRecordIdx recordIdx,
const char* pathnameMOR, char fssep);
NUFXLIB_API NuError NuSetRecordAttr(NuArchive* pArchive, NuRecordIdx recordIdx,
const NuRecordAttr* pRecordAttr);
NUFXLIB_API NuError NuUpdatePresizedThread(NuArchive* pArchive,
NuThreadIdx threadIdx, NuDataSource* pDataSource, int32_t* pMaxLen);
NUFXLIB_API NuError NuDelete(NuArchive* pArchive);
NUFXLIB_API NuError NuDeleteRecord(NuArchive* pArchive, NuRecordIdx recordIdx);
NUFXLIB_API NuError NuDeleteThread(NuArchive* pArchive, NuThreadIdx threadIdx);
/* general interfaces */
NUFXLIB_API NuError NuClose(NuArchive* pArchive);
NUFXLIB_API NuError NuAbort(NuArchive* pArchive);
NUFXLIB_API NuError NuGetMasterHeader(NuArchive* pArchive,
const NuMasterHeader** ppMasterHeader);
NUFXLIB_API NuError NuGetExtraData(NuArchive* pArchive, void** ppData);
NUFXLIB_API NuError NuSetExtraData(NuArchive* pArchive, void* pData);
NUFXLIB_API NuError NuGetValue(NuArchive* pArchive, NuValueID ident,
NuValue* pValue);
NUFXLIB_API NuError NuSetValue(NuArchive* pArchive, NuValueID ident,
NuValue value);
NUFXLIB_API NuError NuGetAttr(NuArchive* pArchive, NuAttrID ident,
NuAttr* pAttr);
NUFXLIB_API NuError NuDebugDumpArchive(NuArchive* pArchive);
/* sources and sinks */
NUFXLIB_API NuError NuCreateDataSourceForFile(NuThreadFormat threadFormat,
uint32_t otherLen, const UNICHAR* pathnameUNI,
short isFromRsrcFork, NuDataSource** ppDataSource);
NUFXLIB_API NuError NuCreateDataSourceForFP(NuThreadFormat threadFormat,
uint32_t otherLen, FILE* fp, long offset, long length,
NuCallback closeFunc, NuDataSource** ppDataSource);
NUFXLIB_API NuError NuCreateDataSourceForBuffer(NuThreadFormat threadFormat,
uint32_t otherLen, const uint8_t* buffer, long offset,
long length, NuCallback freeFunc, NuDataSource** ppDataSource);
NUFXLIB_API NuError NuFreeDataSource(NuDataSource* pDataSource);
NUFXLIB_API NuError NuDataSourceSetRawCrc(NuDataSource* pDataSource,
uint16_t crc);
NUFXLIB_API NuError NuCreateDataSinkForFile(short doExpand, NuValue convertEOL,
const UNICHAR* pathnameUNI, UNICHAR fssep, NuDataSink** ppDataSink);
NUFXLIB_API NuError NuCreateDataSinkForFP(short doExpand, NuValue convertEOL,
FILE* fp, NuDataSink** ppDataSink);
NUFXLIB_API NuError NuCreateDataSinkForBuffer(short doExpand,
NuValue convertEOL, uint8_t* buffer, uint32_t bufLen,
NuDataSink** ppDataSink);
NUFXLIB_API NuError NuFreeDataSink(NuDataSink* pDataSink);
NUFXLIB_API NuError NuDataSinkGetOutCount(NuDataSink* pDataSink,
uint32_t* pOutCount);
/* miscellaneous non-archive operations */
NUFXLIB_API NuError NuGetVersion(int32_t* pMajorVersion, int32_t* pMinorVersion,
int32_t* pBugVersion, const char** ppBuildDate,
const char** ppBuildFlags);
NUFXLIB_API const char* NuStrError(NuError err);
NUFXLIB_API NuError NuTestFeature(NuFeature feature);
NUFXLIB_API void NuRecordCopyAttr(NuRecordAttr* pRecordAttr,
const NuRecord* pRecord);
NUFXLIB_API NuError NuRecordCopyThreads(const NuRecord* pRecord,
NuThread** ppThreads);
NUFXLIB_API uint32_t NuRecordGetNumThreads(const NuRecord* pRecord);
NUFXLIB_API const NuThread* NuThreadGetByIdx(const NuThread* pThread,
int32_t idx);
NUFXLIB_API short NuIsPresizedThreadID(NuThreadID threadID);
NUFXLIB_API size_t NuConvertMORToUNI(const char* stringMOR,
UNICHAR* bufUNI, size_t bufSize);
NUFXLIB_API size_t NuConvertUNIToMOR(const UNICHAR* stringUNI,
char* bufMOR, size_t bufSize);
#define NuGetThread(pRecord, idx) ( (const NuThread*) \
((uint32_t) (idx) < (pRecord)->recTotalThreads ? \
&(pRecord)->pThreads[(idx)] : NULL) \
)
/* callback setters */
#define kNuInvalidCallback ((NuCallback) 1)
NUFXLIB_API NuCallback NuSetSelectionFilter(NuArchive* pArchive,
NuCallback filterFunc);
NUFXLIB_API NuCallback NuSetOutputPathnameFilter(NuArchive* pArchive,
NuCallback filterFunc);
NUFXLIB_API NuCallback NuSetProgressUpdater(NuArchive* pArchive,
NuCallback updateFunc);
NUFXLIB_API NuCallback NuSetErrorHandler(NuArchive* pArchive,
NuCallback errorFunc);
NUFXLIB_API NuCallback NuSetErrorMessageHandler(NuArchive* pArchive,
NuCallback messageHandlerFunc);
NUFXLIB_API NuCallback NuSetGlobalErrorMessageHandler(NuCallback messageHandlerFunc);
#ifdef __cplusplus
}
#endif
#endif /*NUFXLIB_NUFXLIB_H*/
| 39.372748 | 85 | 0.639133 |
f04db9b56b1e237b1d7778435acb8d59c2f53ab3 | 719 | h | C | Medusa/Medusa/Resource/Map/Tiled/TiledMapFactory.h | JamesLinus/Medusa | 243e1f67e76dba10a0b69d4154b47e884c3f191f | [
"MIT"
] | 1 | 2019-04-22T09:09:50.000Z | 2019-04-22T09:09:50.000Z | Medusa/Medusa/Resource/Map/Tiled/TiledMapFactory.h | JamesLinus/Medusa | 243e1f67e76dba10a0b69d4154b47e884c3f191f | [
"MIT"
] | null | null | null | Medusa/Medusa/Resource/Map/Tiled/TiledMapFactory.h | JamesLinus/Medusa | 243e1f67e76dba10a0b69d4154b47e884c3f191f | [
"MIT"
] | 1 | 2021-06-30T14:08:03.000Z | 2021-06-30T14:08:03.000Z | // Copyright (c) 2015 fjz13. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file.
#pragma once
#include "Core/Pattern/Singleton.h"
#include "Resource/BaseResourceFactory.h"
#include "Resource/Map/Tiled/ITiledMap.h"
MEDUSA_BEGIN;
class TiledMapFactory :public Singleton<TiledMapFactory>, public BaseResourceFactory < ITiledMap >
{
friend class Singleton < TiledMapFactory > ;
public:
TiledMapFactory();
~TiledMapFactory();
public:
virtual bool Initialize()override;
virtual bool Uninitialize()override;
public:
TmxTiledMap* Create(const FileIdRef& fileId, ResourceShareType shareType = ResourceShareType::Share);
private:
};
MEDUSA_END; | 25.678571 | 102 | 0.77886 |
9b885dcf23eb2e6832870c559e68dfe8e7f4406a | 4,074 | c | C | ledger-app-fio/src/io.c | vacuumlabs/experimental-ledger-app | 42ae60a3628e11d493e1bd4517f1a25bd9dc2973 | [
"Apache-2.0"
] | null | null | null | ledger-app-fio/src/io.c | vacuumlabs/experimental-ledger-app | 42ae60a3628e11d493e1bd4517f1a25bd9dc2973 | [
"Apache-2.0"
] | 1 | 2021-09-06T15:12:54.000Z | 2021-09-06T15:12:54.000Z | ledger-app-fio/src/io.c | vacuumlabs/experimental-ledger-app | 42ae60a3628e11d493e1bd4517f1a25bd9dc2973 | [
"Apache-2.0"
] | 2 | 2021-09-06T14:46:59.000Z | 2021-12-03T16:48:15.000Z | #include "io.h"
#include "common.h"
io_state_t io_state;
#if defined(TARGET_NANOS)
static timeout_callback_fn_t* timeout_cb;
void nanos_clear_timer()
{
timeout_cb = NULL;
}
void nanos_set_timer(int ms, timeout_callback_fn_t* cb)
{
// if TRACE() is enabled, set_timer must be called
// before ui_ methods, because it causes Ledger Nano S
// to freeze in debug mode
// TRACE();
ASSERT(timeout_cb == NULL);
ASSERT(ms >= 0);
timeout_cb = cb;
UX_CALLBACK_SET_INTERVAL((unsigned) ms);
}
#define HANDLE_UX_TICKER_EVENT(ux_allowed) \
do {\
if (timeout_cb) \
{ \
timeout_callback_fn_t* callback = timeout_cb; \
timeout_cb = NULL; /* clear first if cb() throws */ \
callback(ux_allowed); \
} \
} while(0)
#elif defined(TARGET_NANOX)
#define HANDLE_UX_TICKER_EVENT(ux_allowed) do {} while(0)
#endif
void CHECK_RESPONSE_SIZE(unsigned int tx)
{
// Note(ppershing): we do both checks due to potential overflows
ASSERT(tx < sizeof(G_io_apdu_buffer));
ASSERT(tx + 2u < sizeof(G_io_apdu_buffer));
}
// io_exchange_with_code is a helper function for sending response APDUs from
// button handlers. Note that the IO_RETURN_AFTER_TX flag is set. 'tx' is the
// conventional name for the size of the response APDU, i.e. the write-offset
// within G_io_apdu_buffer.
void _io_send_G_io_apdu_buffer(uint16_t code, uint16_t tx)
{
CHECK_RESPONSE_SIZE(tx);
G_io_apdu_buffer[tx++] = code >> 8;
G_io_apdu_buffer[tx++] = code & 0xFF;
io_exchange(CHANNEL_APDU | IO_RETURN_AFTER_TX, tx);
// From now on we can receive new APDU
io_state = IO_EXPECT_IO;
}
void io_send_buf(uint16_t code, uint8_t* buffer, size_t bufferSize)
{
CHECK_RESPONSE_SIZE(bufferSize);
memmove(G_io_apdu_buffer, buffer, bufferSize);
_io_send_G_io_apdu_buffer(code, bufferSize);
}
// Everything below this point is Ledger magic.
// override point, but nothing more to do
void io_seproxyhal_display(const bagl_element_t *element)
{
io_seproxyhal_display_default((bagl_element_t *)element);
}
unsigned char G_io_seproxyhal_spi_buffer[IO_SEPROXYHAL_BUFFER_SIZE_B];
unsigned char io_event(unsigned char channel MARK_UNUSED)
{
// can't have more than one tag in the reply, not supported yet.
switch (G_io_seproxyhal_spi_buffer[0]) {
case SEPROXYHAL_TAG_FINGER_EVENT:
// This app is not supposed to work with Blue
ASSERT(false);
UX_FINGER_EVENT(G_io_seproxyhal_spi_buffer);
break;
case SEPROXYHAL_TAG_BUTTON_PUSH_EVENT:
UX_BUTTON_PUSH_EVENT(G_io_seproxyhal_spi_buffer);
break;
case SEPROXYHAL_TAG_STATUS_EVENT:
if (G_io_apdu_media == IO_APDU_MEDIA_USB_HID &&
!(U4BE(G_io_seproxyhal_spi_buffer, 3) &
SEPROXYHAL_TAG_STATUS_EVENT_FLAG_USB_POWERED)) {
THROW(EXCEPTION_IO_RESET);
}
UX_DEFAULT_EVENT();
break;
case SEPROXYHAL_TAG_DISPLAY_PROCESSED_EVENT:
UX_DISPLAYED_EVENT({});
break;
case SEPROXYHAL_TAG_TICKER_EVENT:
UX_TICKER_EVENT(G_io_seproxyhal_spi_buffer, {
TRACE("timer");
HANDLE_UX_TICKER_EVENT(UX_ALLOWED);
});
break;
default:
UX_DEFAULT_EVENT();
break;
}
// close the event if not done previously (by a display or whatever)
if (!io_seproxyhal_spi_is_status_sent()) {
io_seproxyhal_general_status();
}
// command has been processed, DO NOT reset the current APDU transport
return 1;
}
unsigned short io_exchange_al(unsigned char channel, unsigned short tx_len)
{
switch (channel & ~(IO_FLAGS)) {
case CHANNEL_KEYBOARD:
break;
// multiplexed io exchange over a SPI channel and TLV encapsulated protocol
case CHANNEL_SPI:
if (tx_len) {
io_seproxyhal_spi_send(G_io_apdu_buffer, tx_len);
if (channel & IO_RESET_AFTER_REPLIED) {
reset();
}
return 0; // nothing received from the master so far (it's a tx transaction)
} else {
return io_seproxyhal_spi_recv(G_io_apdu_buffer, sizeof(G_io_apdu_buffer), 0);
}
default:
THROW(INVALID_PARAMETER);
}
return 0;
}
STATIC_ASSERT(CX_APILEVEL >= 9, "bad api level");
static const unsigned PIN_VERIFIED = BOLOS_UX_OK; // Seems to work for api 9/10
bool device_is_unlocked()
{
return os_global_pin_is_validated() == PIN_VERIFIED;
}
| 25.949045 | 80 | 0.752332 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.