hexsha stringlengths 40 40 | size int64 22 2.4M | ext stringclasses 5
values | lang stringclasses 1
value | max_stars_repo_path stringlengths 3 260 | max_stars_repo_name stringlengths 5 109 | max_stars_repo_head_hexsha stringlengths 40 78 | max_stars_repo_licenses listlengths 1 9 | max_stars_count float64 1 191k ⌀ | max_stars_repo_stars_event_min_datetime stringlengths 24 24 ⌀ | max_stars_repo_stars_event_max_datetime stringlengths 24 24 ⌀ | max_issues_repo_path stringlengths 3 260 | max_issues_repo_name stringlengths 5 109 | max_issues_repo_head_hexsha stringlengths 40 78 | max_issues_repo_licenses listlengths 1 9 | max_issues_count float64 1 67k ⌀ | 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 260 | max_forks_repo_name stringlengths 5 109 | max_forks_repo_head_hexsha stringlengths 40 78 | max_forks_repo_licenses listlengths 1 9 | max_forks_count float64 1 105k ⌀ | max_forks_repo_forks_event_min_datetime stringlengths 24 24 ⌀ | max_forks_repo_forks_event_max_datetime stringlengths 24 24 ⌀ | content stringlengths 22 2.4M | avg_line_length float64 5 169k | max_line_length int64 5 786k | alphanum_fraction float64 0.06 0.95 | matches listlengths 1 11 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
6519fa15fc87379464c554ea0ce367fa03cc8011 | 526 | h | C | QuestEngine/Using/Model.h | paulburgess1357/Quest | 16c9513a28478cd56e25420aac1f0d4cd2c38734 | [
"MIT"
] | 1 | 2021-11-02T15:38:47.000Z | 2021-11-02T15:38:47.000Z | QuestEngine/Using/Model.h | paulburgess1357/Quest | 16c9513a28478cd56e25420aac1f0d4cd2c38734 | [
"MIT"
] | null | null | null | QuestEngine/Using/Model.h | paulburgess1357/Quest | 16c9513a28478cd56e25420aac1f0d4cd2c38734 | [
"MIT"
] | null | null | null | #pragma once
#include "QuestGLCore/Model/ExternalTypedefs.h"
namespace QuestEngine::Model {
using StandardModel = QuestGLCore::Model::StandardModel;
using StandardMesh = QuestGLCore::Model::StandardMesh;
using IndexedModel = QuestGLCore::Model::IndexedModel;
using IndexedMesh = QuestGLCore::Model::IndexedMesh;
using IndexedMeshQuad = QuestGLCore::Model::IndexedMeshQuad;
using ModelCreator = QuestGLCore::Model::ModelCreator;
using ModelDrawMode = QuestGLCore::Model::ModelDrawMode;
} // namespace QuestEngine::Model | 43.833333 | 61 | 0.804183 | [
"model"
] |
651d962237a621ff6364b6e5113797f7e5d034b4 | 6,728 | h | C | libs/hikyuu/Stock.h | CodingNowNow/jiaoyi | 57513f8cf0d282fa70ac9e8e76ff785d7a2a019c | [
"MIT"
] | 1 | 2019-03-22T06:36:56.000Z | 2019-03-22T06:36:56.000Z | libs/hikyuu/Stock.h | nvsnvyu/hikyuu | 57513f8cf0d282fa70ac9e8e76ff785d7a2a019c | [
"MIT"
] | null | null | null | libs/hikyuu/Stock.h | nvsnvyu/hikyuu | 57513f8cf0d282fa70ac9e8e76ff785d7a2a019c | [
"MIT"
] | 1 | 2020-03-31T16:45:23.000Z | 2020-03-31T16:45:23.000Z | /*
* Stock.h
*
* Created on: 2011-11-9
* Author: fasiondog
*/
#ifndef STOCK_H_
#define STOCK_H_
#include "StockWeight.h"
#include "KQuery.h"
namespace hku {
class HKU_API StockManager;
class KDataDriver;
typedef shared_ptr<KDataDriver> KDataDriverPtr;
class HKU_API KData;
/**
* Stock基类,Application中一般使用StockPtr进行操作
* @ingroup StockManage
*/
class HKU_API Stock {
friend class StockManager;
private:
static const string default_market;
static const string default_code;
static const string default_market_code;
static const string default_name;
static const hku_uint32 default_type;
static const bool default_valid;
static const Datetime default_startDate;
static const Datetime default_lastDate;
static const price_t default_tick;
static const price_t default_tickValue;
static const price_t default_unit;
static const int default_precision;
static const size_t default_minTradeNumber;
static const size_t default_maxTradeNumber;
public:
Stock();
Stock(const Stock&);
Stock(const string& market, const string& code, const string& name);
Stock(const string& market, const string& code,
const string& name, hku_uint32 type, bool valid,
const Datetime& startDate, const Datetime& lastDate);
Stock(const string& market, const string& code,
const string& name, hku_uint32 type, bool valid,
const Datetime& startDate, const Datetime& lastDate,
price_t tick, price_t tickValue, int precision,
size_t minTradeNumber, size_t maxTradeNumber);
virtual ~Stock();
Stock& operator=(const Stock&);
bool operator==(const Stock&) const;
bool operator!=(const Stock&) const;
/** 获取内部id,一般用于作为map的键值使用,该id实质为m_data的内存地址 */
hku_uint64 id() const;
/** 获取所属市场简称,市场简称是市场的唯一标识 */
const string& market() const;
/** 获取证券代码 */
const string& code() const;
/** 市场简称+证券代码,如: sh000001 */
const string& market_code() const;
/** 获取证券名称 */
const string& name() const;
/** 获取证券类型 */
hku_uint32 type() const;
/** 该证券当前是否有效 */
bool valid() const;
/** 获取证券起始日期 */
Datetime startDatetime() const;
/** 获取证券最后日期 */
Datetime lastDatetime() const;
/** 获取最小跳动量 */
price_t tick() const;
/** 最小跳动量价值 */
price_t tickValue() const;
/** 每单位价值 = tickValue / tick */
price_t unit() const;
/** 获取价格精度 */
int precision() const;
/** 获取最小交易数量,同minTradeNumber */
size_t atom() const;
/** 获取最小交易数量 */
size_t minTradeNumber() const;
/** 获取最大交易量 */
size_t maxTradeNumber() const;
/** 获取所有权息信息 */
StockWeightList getWeight() const;
/**
* 获取指定时间段[start,end)内的权息信息
* @param start 起始日期
* @param end 结束日期
* @return 满足要求的权息信息列表指针
*/
StockWeightList getWeight(const Datetime& start,
const Datetime& end = Null<Datetime>()) const;
/** 获取不同类型K线数据量 */
size_t getCount(KQuery::KType dataType = KQuery::DAY) const;
/** 获取指定日期时刻的市值,即小于等于指定日期的最后一条记录的收盘价 */
price_t getMarketValue(const Datetime&, KQuery::KType) const;
/**
* 根据KQuery指定的条件,获取对应的K线位置范围
* @param query [in] 指定的查询条件
* @param out_start [out] 对应的K线起始范围
* @param out_end [out] 对应的K线结束范围,不包含自身
* @return true 成功 | false 失败
*/
bool getIndexRange(const KQuery&, size_t& out_start, size_t& out_end) const;
/** 获取指定索引的K线数据记录,未作越界检查 */
KRecord getKRecord(size_t pos,
KQuery::KType dataType = KQuery::DAY) const;
/** 根据数据类型(日线/周线等),获取指定日期的KRecord */
KRecord getKRecordByDate(const Datetime&, KQuery::KType ktype = KQuery::DAY) const;
/** 获取K线数据 */
KData getKData(const KQuery&) const;
/** 获取K线记录,一般不直接使用,用getKData替代 */
KRecordList getKRecordList(size_t start, size_t end, KQuery::KType) const;
/** 获取日期列表 */
DatetimeList getDatetimeList(size_t start, size_t end, KQuery::KType) const;
/** 获取日期列表 */
DatetimeList getDatetimeList(const KQuery& query) const;
/** 设置权息信息 */
void setWeightList(const StockWeightList&);
/** 设置K线数据获取驱动 */
void setKDataDriver(const KDataDriverPtr& kdataDriver);
/** 获取K线数据获取驱动 */
KDataDriverPtr getKDataDriver() const;
/**
* 将K线数据做自身缓存
* @note 一般不主动调用,谨慎
*/
void loadKDataToBuffer(KQuery::KType);
/** 释放对应的K线缓存 */
void releaseKDataBuffer(KQuery::KType);
/** 指定类型的K线数据是否被缓存 */
bool isBuffer(KQuery::KType) const;
/** 是否为Null */
bool isNull() const;
/** (临时函数)只用于更新缓存中的日线数据 **/
void realtimeUpdate(const KRecord&);
/** 仅用于python的__str__ */
string toString() const;
private:
bool _getIndexRangeByIndex(const KQuery&, size_t& out_start, size_t& out_end) const;
bool _getIndexRangeByDateFromBuffer(const KQuery&, size_t&, size_t&) const;
private:
struct HKU_API Data;
shared_ptr<Data> m_data;
KDataDriverPtr m_kdataDriver;
};
struct HKU_API Stock::Data {
string m_market; //所属的市场简称
string m_code; //证券代码
string m_market_code;//市场简称证券代码
string m_name; //证券名称
hku_uint32 m_type; //证券类型
bool m_valid; //当前证券是否有效
Datetime m_startDate; //证券起始日期
Datetime m_lastDate; //证券最后日期
StockWeightList m_weightList; //权息信息列表
price_t m_tick;
price_t m_tickValue;
price_t m_unit;
int m_precision;
size_t m_minTradeNumber;
size_t m_maxTradeNumber;
KRecordListPtr pKData[KQuery::INVALID_KTYPE];
Data();
Data(const string& market, const string& code,
const string& name, hku_uint32 type, bool valid,
const Datetime& startDate, const Datetime& lastDate,
price_t tick, price_t tickValue, int precision,
size_t minTradeNumber, size_t maxTradeNumber);
virtual ~Data();
};
/**
* 输出Stock信息,如:Stock(market, code, name, type, valid, startDatetime, lastDatetime)
* @ingroup StockManage
*/
HKU_API std::ostream& operator <<(std::ostream &os, const Stock& stock);
/** @ingroup StockManage */
typedef vector<Stock> StockList;
/* 用于将Stock实例作为map的key,一般建议使用stock.id做键值,
* 否则map还要利用拷贝构造函数,创建新对象,效率低 */
bool operator < (const Stock& s1, const Stock& s2);
inline bool operator < (const Stock& s1, const Stock& s2) {
return s1.id() < s2.id();
}
inline hku_uint64 Stock::id() const {
return isNull() ? 0 : (hku_int64)m_data.get();
}
inline StockWeightList Stock::getWeight() const {
return m_data ? m_data->m_weightList : StockWeightList();
}
inline bool Stock::operator==(const Stock& stock) const {
return (*this != stock) ? false : true;
}
} /* namespace */
#endif /* STOCK_H_ */
| 25.876923 | 88 | 0.65547 | [
"vector"
] |
652008cd01f2f38190952f372f5653f7a9c2109b | 8,826 | c | C | dlls/quartz/systemclock.c | 2600box/wine | 2b5b690fa14ea89092bb079ae90cb61b1fd70add | [
"MIT"
] | null | null | null | dlls/quartz/systemclock.c | 2600box/wine | 2b5b690fa14ea89092bb079ae90cb61b1fd70add | [
"MIT"
] | null | null | null | dlls/quartz/systemclock.c | 2600box/wine | 2b5b690fa14ea89092bb079ae90cb61b1fd70add | [
"MIT"
] | null | null | null | /*
* Implementation of IReferenceClock
*
* Copyright 2004 Raphael Junqueira
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
*/
#include "quartz_private.h"
#include "wine/debug.h"
#include <assert.h>
WINE_DEFAULT_DEBUG_CHANNEL(quartz);
static int cookie_counter;
struct advise_sink
{
struct list entry;
HANDLE handle;
REFERENCE_TIME due_time, period;
int cookie;
};
struct system_clock
{
IReferenceClock IReferenceClock_iface;
LONG ref;
BOOL thread_created;
HANDLE thread, notify_event, stop_event;
REFERENCE_TIME last_time;
CRITICAL_SECTION cs;
struct list sinks;
};
static inline struct system_clock *impl_from_IReferenceClock(IReferenceClock *iface)
{
return CONTAINING_RECORD(iface, struct system_clock, IReferenceClock_iface);
}
static DWORD WINAPI SystemClockAdviseThread(void *param)
{
struct system_clock *clock = param;
struct advise_sink *sink, *cursor;
REFERENCE_TIME current_time;
DWORD timeout = INFINITE;
HANDLE handles[2] = {clock->stop_event, clock->notify_event};
TRACE("Starting advise thread for clock %p.\n", clock);
for (;;)
{
EnterCriticalSection(&clock->cs);
current_time = GetTickCount64() * 10000;
LIST_FOR_EACH_ENTRY_SAFE(sink, cursor, &clock->sinks, struct advise_sink, entry)
{
if (sink->due_time <= current_time)
{
if (sink->period)
{
DWORD periods = ((current_time - sink->due_time) / sink->period) + 1;
ReleaseSemaphore(sink->handle, periods, NULL);
sink->due_time += periods * sink->period;
}
else
{
SetEvent(sink->handle);
list_remove(&sink->entry);
heap_free(sink);
continue;
}
}
timeout = min(timeout, (sink->due_time - current_time) / 10000);
}
LeaveCriticalSection(&clock->cs);
if (WaitForMultipleObjects(2, handles, FALSE, timeout) == 0)
return 0;
}
}
static void notify_thread(struct system_clock *clock)
{
if (!InterlockedCompareExchange(&clock->thread_created, TRUE, FALSE))
{
clock->notify_event = CreateEventW(NULL, FALSE, FALSE, NULL);
clock->stop_event = CreateEventW(NULL, TRUE, FALSE, NULL);
clock->thread = CreateThread(NULL, 0, SystemClockAdviseThread, clock, 0, NULL);
}
SetEvent(clock->notify_event);
}
static HRESULT WINAPI SystemClockImpl_QueryInterface(IReferenceClock *iface, REFIID iid, void **out)
{
struct system_clock *clock = impl_from_IReferenceClock(iface);
TRACE("clock %p, iid %s, out %p.\n", clock, debugstr_guid(iid), out);
if (IsEqualGUID(iid, &IID_IUnknown) || IsEqualGUID(iid, &IID_IReferenceClock))
{
IReferenceClock_AddRef(iface);
*out = iface;
return S_OK;
}
WARN("%s not implemented, returning E_NOINTERFACE.\n", debugstr_guid(iid));
*out = NULL;
return E_NOINTERFACE;
}
static ULONG WINAPI SystemClockImpl_AddRef(IReferenceClock *iface)
{
struct system_clock *clock = impl_from_IReferenceClock(iface);
ULONG refcount = InterlockedIncrement(&clock->ref);
TRACE("%p increasing refcount to %u.\n", clock, refcount);
return refcount;
}
static ULONG WINAPI SystemClockImpl_Release(IReferenceClock *iface)
{
struct system_clock *clock = impl_from_IReferenceClock(iface);
ULONG refcount = InterlockedDecrement(&clock->ref);
TRACE("%p decreasing refcount to %u.\n", clock, refcount);
if (!refcount)
{
if (clock->thread)
{
SetEvent(clock->stop_event);
WaitForSingleObject(clock->thread, INFINITE);
CloseHandle(clock->thread);
CloseHandle(clock->notify_event);
CloseHandle(clock->stop_event);
}
clock->cs.DebugInfo->Spare[0] = 0;
DeleteCriticalSection(&clock->cs);
heap_free(clock);
}
return refcount;
}
static HRESULT WINAPI SystemClockImpl_GetTime(IReferenceClock *iface, REFERENCE_TIME *time)
{
struct system_clock *clock = impl_from_IReferenceClock(iface);
REFERENCE_TIME ret;
HRESULT hr;
TRACE("clock %p, time %p.\n", clock, time);
if (!time) {
return E_POINTER;
}
ret = GetTickCount64() * 10000;
EnterCriticalSection(&clock->cs);
hr = (ret == clock->last_time) ? S_FALSE : S_OK;
*time = clock->last_time = ret;
LeaveCriticalSection(&clock->cs);
return hr;
}
static HRESULT WINAPI SystemClockImpl_AdviseTime(IReferenceClock *iface,
REFERENCE_TIME base, REFERENCE_TIME offset, HEVENT event, DWORD_PTR *cookie)
{
struct system_clock *clock = impl_from_IReferenceClock(iface);
struct advise_sink *sink;
TRACE("clock %p, base %s, offset %s, event %#lx, cookie %p.\n",
clock, wine_dbgstr_longlong(base), wine_dbgstr_longlong(offset), event, cookie);
if (!event)
return E_INVALIDARG;
if (base + offset <= 0)
return E_INVALIDARG;
if (!cookie)
return E_POINTER;
if (!(sink = heap_alloc_zero(sizeof(*sink))))
return E_OUTOFMEMORY;
sink->handle = (HANDLE)event;
sink->due_time = base + offset;
sink->period = 0;
sink->cookie = InterlockedIncrement(&cookie_counter);
EnterCriticalSection(&clock->cs);
list_add_tail(&clock->sinks, &sink->entry);
LeaveCriticalSection(&clock->cs);
notify_thread(clock);
*cookie = sink->cookie;
return S_OK;
}
static HRESULT WINAPI SystemClockImpl_AdvisePeriodic(IReferenceClock* iface,
REFERENCE_TIME start, REFERENCE_TIME period, HSEMAPHORE semaphore, DWORD_PTR *cookie)
{
struct system_clock *clock = impl_from_IReferenceClock(iface);
struct advise_sink *sink;
TRACE("clock %p, start %s, period %s, semaphore %#lx, cookie %p.\n",
clock, wine_dbgstr_longlong(start), wine_dbgstr_longlong(period), semaphore, cookie);
if (!semaphore)
return E_INVALIDARG;
if (start <= 0 || period <= 0)
return E_INVALIDARG;
if (!cookie)
return E_POINTER;
if (!(sink = heap_alloc_zero(sizeof(*sink))))
return E_OUTOFMEMORY;
sink->handle = (HANDLE)semaphore;
sink->due_time = start;
sink->period = period;
sink->cookie = InterlockedIncrement(&cookie_counter);
EnterCriticalSection(&clock->cs);
list_add_tail(&clock->sinks, &sink->entry);
LeaveCriticalSection(&clock->cs);
notify_thread(clock);
*cookie = sink->cookie;
return S_OK;
}
static HRESULT WINAPI SystemClockImpl_Unadvise(IReferenceClock *iface, DWORD_PTR cookie)
{
struct system_clock *clock = impl_from_IReferenceClock(iface);
struct advise_sink *sink;
TRACE("clock %p, cookie %#lx.\n", clock, cookie);
EnterCriticalSection(&clock->cs);
LIST_FOR_EACH_ENTRY(sink, &clock->sinks, struct advise_sink, entry)
{
if (sink->cookie == cookie)
{
list_remove(&sink->entry);
heap_free(sink);
LeaveCriticalSection(&clock->cs);
return S_OK;
}
}
LeaveCriticalSection(&clock->cs);
return S_FALSE;
}
static const IReferenceClockVtbl SystemClock_Vtbl =
{
SystemClockImpl_QueryInterface,
SystemClockImpl_AddRef,
SystemClockImpl_Release,
SystemClockImpl_GetTime,
SystemClockImpl_AdviseTime,
SystemClockImpl_AdvisePeriodic,
SystemClockImpl_Unadvise
};
HRESULT QUARTZ_CreateSystemClock(IUnknown *outer, void **out)
{
struct system_clock *object;
TRACE("outer %p, out %p.\n", outer, out);
if (!(object = heap_alloc_zero(sizeof(*object))))
{
*out = NULL;
return E_OUTOFMEMORY;
}
object->IReferenceClock_iface.lpVtbl = &SystemClock_Vtbl;
list_init(&object->sinks);
InitializeCriticalSection(&object->cs);
object->cs.DebugInfo->Spare[0] = (DWORD_PTR)(__FILE__ ": SystemClockImpl.cs");
return SystemClockImpl_QueryInterface(&object->IReferenceClock_iface, &IID_IReferenceClock, out);
}
| 28.10828 | 101 | 0.661228 | [
"object"
] |
652102762d9ff3e9945631d2e4d4edb5ff30e86b | 4,956 | h | C | components/policy/core/common/async_policy_loader.h | iplo/Chain | 8bc8943d66285d5258fffc41bed7c840516c4422 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 231 | 2015-01-08T09:04:44.000Z | 2021-12-30T03:03:10.000Z | components/policy/core/common/async_policy_loader.h | j4ckfrost/android_external_chromium_org | a1a3dad8b08d1fcf6b6b36c267158ed63217c780 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2017-02-14T21:55:58.000Z | 2017-02-14T21:55:58.000Z | components/policy/core/common/async_policy_loader.h | j4ckfrost/android_external_chromium_org | a1a3dad8b08d1fcf6b6b36c267158ed63217c780 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 268 | 2015-01-21T05:53:28.000Z | 2022-03-25T22:09:01.000Z | // Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_POLICY_CORE_COMMON_ASYNC_POLICY_LOADER_H_
#define COMPONENTS_POLICY_CORE_COMMON_ASYNC_POLICY_LOADER_H_
#include "base/callback.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h"
#include "base/time/time.h"
#include "components/policy/core/common/schema_map.h"
#include "components/policy/policy_export.h"
namespace base {
class SequencedTaskRunner;
}
namespace policy {
class PolicyBundle;
// Base implementation for platform-specific policy loaders. Together with the
// AsyncPolicyProvider, this base implementation takes care of the initial load,
// periodic reloads, watching file changes, refreshing policies and object
// lifetime.
//
// All methods are invoked on the background |task_runner_|, including the
// destructor. The only exceptions are the constructor (which may be called on
// any thread), and the initial Load() which is called on the thread that owns
// the provider.
// LastModificationTime() is also invoked once on that thread at startup.
class POLICY_EXPORT AsyncPolicyLoader {
public:
explicit AsyncPolicyLoader(
scoped_refptr<base::SequencedTaskRunner> task_runner);
virtual ~AsyncPolicyLoader();
// Gets a SequencedTaskRunner backed by the background thread.
base::SequencedTaskRunner* task_runner() const { return task_runner_.get(); }
// Returns the currently configured policies. Load() is always invoked on
// the background thread, except for the initial Load() at startup which is
// invoked from the thread that owns the provider.
virtual scoped_ptr<PolicyBundle> Load() = 0;
// Allows implementations to finalize their initialization on the background
// thread (e.g. setup file watchers).
virtual void InitOnBackgroundThread() = 0;
// Implementations should return the time of the last modification detected,
// or base::Time() if it doesn't apply, which is the default.
virtual base::Time LastModificationTime();
// Used by the AsyncPolicyProvider to do the initial Load(). The first load
// is also used to initialize |last_modification_time_| and
// |schema_map_|.
scoped_ptr<PolicyBundle> InitialLoad(const scoped_refptr<SchemaMap>& schemas);
// Implementations should invoke Reload() when a change is detected. This
// must be invoked from the background thread and will trigger a Load(),
// and pass the returned bundle to the provider.
// The load is immediate when |force| is true. Otherwise, the loader
// reschedules the reload until the LastModificationTime() is a couple of
// seconds in the past. This mitigates the problem of reading files that are
// currently being written to, and whose contents are incomplete.
// A reload is posted periodically, if it hasn't been triggered recently. This
// makes sure the policies are reloaded if the update events aren't triggered.
void Reload(bool force);
const scoped_refptr<SchemaMap>& schema_map() const { return schema_map_; }
private:
// Allow AsyncPolicyProvider to call Init().
friend class AsyncPolicyProvider;
typedef base::Callback<void(scoped_ptr<PolicyBundle>)> UpdateCallback;
// Used by the AsyncPolicyProvider to install the |update_callback_|.
// Invoked on the background thread.
void Init(const UpdateCallback& update_callback);
// Used by the AsyncPolicyProvider to reload with an updated SchemaMap.
void RefreshPolicies(scoped_refptr<SchemaMap> schema_map);
// Cancels any pending periodic reload and posts one |delay| time units from
// now.
void ScheduleNextReload(base::TimeDelta delay);
// Checks if the underlying files haven't changed recently, by checking the
// LastModificationTime(). |delay| is updated with a suggested time to wait
// before retrying when this returns false.
bool IsSafeToReload(const base::Time& now, base::TimeDelta* delay);
// Task runner to run background threads.
scoped_refptr<base::SequencedTaskRunner> task_runner_;
// Callback for updates, passed in Init().
UpdateCallback update_callback_;
// Used to get WeakPtrs for the periodic reload task.
base::WeakPtrFactory<AsyncPolicyLoader> weak_factory_;
// Records last known modification timestamp.
base::Time last_modification_time_;
// The wall clock time at which the last modification timestamp was
// recorded. It's better to not assume the file notification time and the
// wall clock times come from the same source, just in case there is some
// non-local filesystem involved.
base::Time last_modification_clock_;
// The current policy schemas that this provider should load.
scoped_refptr<SchemaMap> schema_map_;
DISALLOW_COPY_AND_ASSIGN(AsyncPolicyLoader);
};
} // namespace policy
#endif // COMPONENTS_POLICY_CORE_COMMON_ASYNC_POLICY_LOADER_H_
| 40.292683 | 80 | 0.768563 | [
"object"
] |
65226670ef9c047da116a6bfb20580858fd97eb2 | 5,696 | h | C | vtkm/cont/internal/ArrayTransfer.h | yisyuanliou/VTK-m | cc483c8c2319a78b58b3ab849da8ca448e896220 | [
"BSD-3-Clause"
] | 2 | 2021-07-07T22:53:19.000Z | 2021-07-31T19:29:35.000Z | vtkm/cont/internal/ArrayTransfer.h | yisyuanliou/VTK-m | cc483c8c2319a78b58b3ab849da8ca448e896220 | [
"BSD-3-Clause"
] | 2 | 2020-11-18T16:50:34.000Z | 2022-01-21T13:31:47.000Z | vtkm/cont/internal/ArrayTransfer.h | yisyuanliou/VTK-m | cc483c8c2319a78b58b3ab849da8ca448e896220 | [
"BSD-3-Clause"
] | 5 | 2020-10-02T10:14:35.000Z | 2022-03-10T07:50:22.000Z | //============================================================================
// Copyright (c) Kitware, Inc.
// All rights reserved.
// See LICENSE.txt for details.
//
// This software is distributed WITHOUT ANY WARRANTY; without even
// the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE. See the above copyright notice for more information.
//============================================================================
#ifndef vtk_m_cont_internal_ArrayTransfer_h
#define vtk_m_cont_internal_ArrayTransfer_h
#include <vtkm/cont/Storage.h>
#include <vtkm/cont/Token.h>
#include <vtkm/cont/internal/ArrayManagerExecution.h>
namespace vtkm
{
namespace cont
{
namespace internal
{
/// \brief Class that manages the transfer of data between control and execution.
///
/// This templated class provides a mechanism (used by the ArrayHandle) to
/// transfer data from the control environment to the execution environment and
/// back. The interface for ArrayTransfer is nearly identical to that of
/// ArrayManagerExecution and the default implementation simply delegates all
/// calls to that class.
///
/// The primary motivation for having a separate class is that the
/// ArrayManagerExecution is meant to be specialized for each device adapter
/// whereas the ArrayTransfer is meant to be specialized for each storage type
/// (or specific combination of storage and device adapter). Thus, transfers
/// for most storage tyeps will be delegated through the ArrayManagerExecution,
/// but some storage types, like implicit storage, will be specialized to
/// transfer through a different path.
///
template <typename T, class StorageTag, class DeviceAdapterTag>
class ArrayTransfer
{
private:
using StorageType = vtkm::cont::internal::Storage<T, StorageTag>;
using ArrayManagerType =
vtkm::cont::internal::ArrayManagerExecution<T, StorageTag, DeviceAdapterTag>;
public:
/// The type of value held in the array (vtkm::FloatDefault, vtkm::Vec, etc.)
///
using ValueType = T;
/// An array portal that can be used in the control environment.
///
using PortalControl = typename StorageType::PortalType;
using PortalConstControl = typename StorageType::PortalConstType;
/// An array portal that can be used in the execution environment.
///
using PortalExecution = typename ArrayManagerType::PortalType;
using PortalConstExecution = typename ArrayManagerType::PortalConstType;
VTKM_CONT
ArrayTransfer(StorageType* storage)
: ArrayManager(storage)
{
}
/// Returns the number of values stored in the array. Results are undefined
/// if data has not been loaded or allocated.
///
VTKM_CONT
vtkm::Id GetNumberOfValues() const { return this->ArrayManager.GetNumberOfValues(); }
/// Prepares the data for use as input in the execution environment. If the
/// flag \c updateData is true, then data is transferred to the execution
/// environment. Otherwise, this transfer is (or may be) skipped.
///
/// Returns a constant array portal valid in the execution environment.
///
VTKM_CONT
PortalConstExecution PrepareForInput(bool updateData, vtkm::cont::Token& token)
{
return this->ArrayManager.PrepareForInput(updateData, token);
}
/// Prepares the data for use as both input and output in the execution
/// environment. If the flag \c updateData is true, then data is transferred
/// to the execution environment. Otherwise, this transfer is (or may be)
/// skipped.
///
/// Returns a read-write array portal valid in the execution environment.
///
VTKM_CONT
PortalExecution PrepareForInPlace(bool updateData, vtkm::cont::Token& token)
{
return this->ArrayManager.PrepareForInPlace(updateData, token);
}
/// Allocates an array in the execution environment of the specified size. If
/// control and execution share arrays, then this class can allocate data
/// using the given Storage it can be used directly in the execution
/// environment.
///
/// Returns a writable array portal valid in the execution environment.
///
VTKM_CONT
PortalExecution PrepareForOutput(vtkm::Id numberOfValues, vtkm::cont::Token& token)
{
return this->ArrayManager.PrepareForOutput(numberOfValues, token);
}
/// Allocates data in the given Storage and copies data held in the execution
/// environment (managed by this class) into the storage object. The
/// reference to the storage given is the same as that passed to the
/// constructor. If control and execution share arrays, this can be no
/// operation. This method should only be called after PrepareForOutput is
/// called.
///
VTKM_CONT
void RetrieveOutputData(StorageType* storage) const
{
this->ArrayManager.RetrieveOutputData(storage);
}
/// \brief Reduces the size of the array without changing its values.
///
/// This method allows you to resize the array without reallocating it. The
/// number of entries in the array is changed to \c numberOfValues. The data
/// in the array (from indices 0 to \c numberOfValues - 1) are the same, but
/// \c numberOfValues must be equal or less than the preexisting size
/// (returned from GetNumberOfValues). That is, this method can only be used
/// to shorten the array, not lengthen.
///
VTKM_CONT
void Shrink(vtkm::Id numberOfValues) { this->ArrayManager.Shrink(numberOfValues); }
/// Frees any resources (i.e. memory) allocated for the exeuction
/// environment, if any.
///
VTKM_CONT
void ReleaseResources() { this->ArrayManager.ReleaseResources(); }
private:
ArrayManagerType ArrayManager;
};
}
}
} // namespace vtkm::cont::internal
#endif //vtk_m_cont_internal_ArrayTransfer_h
| 37.473684 | 87 | 0.722261 | [
"object"
] |
6525901121ca453142625ee624d644145c9f88a4 | 90,254 | c | C | kernel/common/drivers/input/touchscreen/tst200_download_luisa.c | foxsake/infuzion-sgp | 2b7e22ea2069e0d74a8721c9f5389378c29e709c | [
"Apache-2.0"
] | null | null | null | kernel/common/drivers/input/touchscreen/tst200_download_luisa.c | foxsake/infuzion-sgp | 2b7e22ea2069e0d74a8721c9f5389378c29e709c | [
"Apache-2.0"
] | null | null | null | kernel/common/drivers/input/touchscreen/tst200_download_luisa.c | foxsake/infuzion-sgp | 2b7e22ea2069e0d74a8721c9f5389378c29e709c | [
"Apache-2.0"
] | 1 | 2020-11-04T06:53:55.000Z | 2020-11-04T06:53:55.000Z | /*******************************************************************************
* Copyright 2011 Cypress Corporation. All rights reserved.
*
* Unless you and Cypress execute a separate written software license agreement
* governing use of this software, this software is licensed to you under the
* terms of the GNU General Public License version 2, available at
* http://www.gnu.org/copyleft/gpl.html (the "GPL").
*
* Notwithstanding the above, under no circumstances may you combine this
* software in any way with any other Cypress software provided under a license
* other than the GPL, without Cypress' express prior written consent.
*******************************************************************************/
#include <linux/module.h>
#include <linux/delay.h>
#include <linux/earlysuspend.h>
#include <linux/hrtimer.h>
#include <linux/i2c.h>
#include <linux/input.h>
#include <linux/interrupt.h>
#include <linux/io.h>
#include <linux/platform_device.h>
#include <mach/gpio.h>
#include <linux/synaptics_i2c_rmi.h>
#include <linux/device.h>
#include <mach/reg_syscfg.h>
#include <linux/uaccess.h>
#include <linux/slab.h>
#include <linux/syscalls.h>
#include "tst200_download_luisa.h"
#include "./TST200_FIRMWARE_LUISA/Luisa_H02S03.h"
#include "./TST200_FIRMWARE_LUISA/Luisa_H03S0B.h"
#include "./TST200_FIRMWARE_LUISA/Luisa_H04S09.h"
#include "./TST200_FIRMWARE_LUISA/Luisa_H05S04.h"
#define TSP_SDA 27
#define TSP_SCL 26
/***********************
*
* Touchpad Tuning APIs
*
************************/
extern void touch_ctrl_regulator(int on_off);
void TchDrv_DownloadVddSetHigh(void)
{
touch_ctrl_regulator(1); /* always on */
}
void TchDrv_DownloadVddSetLow(void)
{
touch_ctrl_regulator(0); /* always off */
}
#if 0
void TchDrv_DownloadIntSetHigh(void)
{
HAL_GPIO_SetState_st_t HAL_GPIO_Set_st;
HAL_GPIO_Set_st.gpio_pin = TOUCH_INT_GPIO;
HAL_GPIO_Ctrl(ACTION_GPIO_SetHigh_64pin, &HAL_GPIO_Set_st, NULL);
}
void TchDrv_DownloadIntSetLow(void)
{
HAL_GPIO_SetState_st_t HAL_GPIO_Set_st;
HAL_GPIO_Set_st.gpio_pin = TOUCH_INT_GPIO;
HAL_GPIO_Ctrl(ACTION_GPIO_SetLow_64pin, &HAL_GPIO_Set_st, NULL);
}
void TchDrv_DownloadIntSetOutput(void)
{
HAL_GPIO_ConfigOutput_st_t HAL_GPIO_ConfigOutput_st;
HAL_GPIO_ConfigOutput_st.mask = GET_GPIO_PIN_MASK(TOUCH_INT_GPIO);/* Interrupt is input */
HAL_GPIO_Ctrl(ACTION_GPIO_ConfigOutput, &HAL_GPIO_ConfigOutput_st, NULL);
}
void TchDrv_DownloadIntSetInput(void)
{
HAL_GPIO_ConfigInput_st_t HAL_GPIO_ConfigInput_st;
HAL_GPIO_ConfigInput_st.input_mask = GET_GPIO_PIN_MASK(TOUCH_INT_GPIO);/* Interrupt is input */
HAL_GPIO_Ctrl(ACTION_GPIO_ConfigInput, &HAL_GPIO_ConfigInput_st, NULL);
}
IRQMask_t sv_tch_savedirqmask;
void TchDrv_DownloadDisableIRQ(void)
{
extern void IRQ_DisableAll( IRQMask_t *mask );
IRQ_DisableAll(&sv_tch_savedirqmask);
}
void TchDrv_DownloadEnableIRQ(void)
{
extern void IRQ_Restore( IRQMask_t saved_mask_val );
IRQ_Restore(sv_tch_savedirqmask);
}
void TchDrv_DownloadDisableWD(void)
{
extern void WDT_Disable( void );
WDT_Disable();
}
void TchDrv_DownloadEnableWD(void)
{
extern void WDT_Enable(void);
WDT_Enable();
}
void uart_printf(const char *szFormat, ...)
{
}
#endif
#if 0
#define TCH_I2C_SCL_GPIO GPIO_I2C_SCL
#define TCH_I2C_SDA_GPIO GPIO_I2C_SDA
#define I2C_SW_EMU_SCL_GPIO TCH_I2C_SCL_GPIO
#define I2C_SW_EMU_SDA_GPIO TCH_I2C_SDA_GPIO
////The following macro definitions may need to be changed case by case/////////
#define I2C_SW_EMU_SCL_GPIO_CTRL_REG (*(volatile UInt32 *)GPOR0_REG)
#define I2C_SW_EMU_SCL_GPIO_CTRL_MASK (0x1<<I2C_SW_EMU_SCL_GPIO)
#define I2C_SW_EMU_SCL_GPIO_TYPE_REG (*(volatile UInt32 *)IOTR0_REG)
#define I2C_SW_EMU_SCL_GPIO_READ_REG (*(volatile UInt32 *)GPIPS0_REG)
#define I2C_SW_EMU_SCL_GPIO_OUTPUT_MASK (0x2<<(I2C_SW_EMU_SCL_GPIO*2))
#define I2C_SW_EMU_SCL_GPIO_INPUT_MASK (0x0<<(I2C_SW_EMU_SCL_GPIO*2))
#define I2C_SW_EMU_SCL_GPIO_NOTUSED_MASK (0x3<<(I2C_SW_EMU_SCL_GPIO*2))
#define I2C_SW_EMU_SCL_GPIO_READ_MASK (0x1<<I2C_SW_EMU_SCL_GPIO)
#define I2C_SET_SCL_GPIO() I2C_SW_EMU_SCL_GPIO_TYPE_REG &= ~I2C_SW_EMU_SCL_GPIO_NOTUSED_MASK //gpio input
#define I2C_CLR_SCL_GPIO() I2C_SW_EMU_SCL_GPIO_TYPE_REG |= I2C_SW_EMU_SCL_GPIO_OUTPUT_MASK //gpio output
#define I2C_SET_SCL_GPIO_LOW() I2C_SW_EMU_SCL_GPIO_CTRL_REG &= ~I2C_SW_EMU_SCL_GPIO_CTRL_MASK //gpio output low
#define I2C_SET_SCL_GPIO_HIGH() I2C_SW_EMU_SCL_GPIO_CTRL_REG |= I2C_SW_EMU_SCL_GPIO_CTRL_MASK //gpio output high
#define I2C_SW_EMU_SDA_GPIO_CTRL_REG (*(volatile UInt32 *)GPOR0_REG)
#define I2C_SW_EMU_SDA_GPIO_TYPE_REG (*(volatile UInt32 *)IOTR0_REG)
#define I2C_SW_EMU_SDA_GPIO_READ_REG (*(volatile UInt32 *)GPIPS0_REG)
#define I2C_SW_EMU_SDA_GPIO_CTRL_MASK (0x1<<I2C_SW_EMU_SDA_GPIO)
#define I2C_SW_EMU_SDA_GPIO_OUTPUT_MASK (0x2<<(I2C_SW_EMU_SDA_GPIO*2))
#define I2C_SW_EMU_SDA_GPIO_INPUT_MASK (0x0<<(I2C_SW_EMU_SDA_GPIO*2))
#define I2C_SW_EMU_SDA_GPIO_NOTUSED_MASK (0x3<<(I2C_SW_EMU_SDA_GPIO*2))
#define I2C_SW_EMU_SDA_GPIO_READ_MASK (0x1<<I2C_SW_EMU_SDA_GPIO)
#define I2C_SET_SDA_GPIO() I2C_SW_EMU_SDA_GPIO_TYPE_REG &= ~I2C_SW_EMU_SDA_GPIO_NOTUSED_MASK //gpio input
#define I2C_CLR_SDA_GPIO() I2C_SW_EMU_SDA_GPIO_TYPE_REG |= I2C_SW_EMU_SDA_GPIO_OUTPUT_MASK //gpio output
#define I2C_SET_SDA_GPIO_LOW() I2C_SW_EMU_SDA_GPIO_CTRL_REG &= ~I2C_SW_EMU_SDA_GPIO_CTRL_MASK //gpio output low
#define I2C_SET_SDA_GPIO_HIGH() I2C_SW_EMU_SDA_GPIO_CTRL_REG |= I2C_SW_EMU_SDA_GPIO_CTRL_MASK //gpio output high
#define I2C_READ_SDA_GPIO() (I2C_SW_EMU_SDA_GPIO_READ_REG&I2C_SW_EMU_SDA_GPIO_READ_MASK) //input is being driven high/low
#define I2C_READ_SCL_GPIO() (I2C_SW_EMU_SCL_GPIO_READ_REG&I2C_SW_EMU_SCL_GPIO_READ_MASK) //input is being driven high/low
#endif
/*++ DELAY TEST ++*/
// provides delays in us
#define ONE_MICROSSEC_CNT 100 // 312MHz
static void delay_1us(void)
{
volatile unsigned int i;
for(i=0; i<ONE_MICROSSEC_CNT; i++)
{
}
}
static void delay_us(unsigned int us)
{
volatile unsigned int i;
for(i=0; i<us; i++)
{
delay_1us();
}
}
/*-- DELAY TEST --*/
//-----------------------------------------
//
// Converting ASCII and VALUE
//
//-----------------------------------------
static unsigned char mcsdl_hex_htoi( unsigned char *pAscii )
{
unsigned char ucTemp = 0;
switch (*pAscii) {
case '0' : ucTemp = 0x00; break;
case '1' : ucTemp = 0x01; break;
case '2' : ucTemp = 0x02; break;
case '3' : ucTemp = 0x03; break;
case '4' : ucTemp = 0x04; break;
case '5' : ucTemp = 0x05; break;
case '6' : ucTemp = 0x06; break;
case '7' : ucTemp = 0x07; break;
case '8' : ucTemp = 0x08; break;
case '9' : ucTemp = 0x09; break;
case 'a' :
case 'A' : ucTemp = 0x0A; break;
case 'b' :
case 'B' : ucTemp = 0x0B; break;
case 'c' :
case 'C' : ucTemp = 0x0C; break;
case 'd' :
case 'D' : ucTemp = 0x0D; break;
case 'e' :
case 'E' : ucTemp = 0x0E; break;
case 'f' :
case 'F' : ucTemp = 0x0F; break;
default : break;
}
return ucTemp;
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
/////
///// Issp_driver_routines.c
/////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
unsigned int wBinaryAddress;
unsigned char bTargetDataPtr;
unsigned char abTargetDataOUT[TARGET_DATABUFF_LEN];
unsigned char abTargetDataOUT_secure[TARGET_DATABUFF_LEN] ={0x00,};
//unsigned char abSecurityData[TARGET_DATABUFF_LEN];
///unsigned char firmData[514][64];
unsigned char firmData[512][64];
// for test - kjhw
extern unsigned char BinaryData[128] =
{
0x7d, 0x00, 0x68, 0x30, 0x30, 0x30, 0x30, 0x30, 0x7e, 0x30, 0x30, 0x30, 0x7d, 0x05, 0x27, 0x7e, 0x7d, 0x05, 0xcf, 0x7e, // 20
0x7e, 0x30, 0x30, 0x30, 0x7e, 0x30, 0x30, 0x30, 0x7d, 0x10, 0xe7, 0x7e, 0x7e, 0x30, 0x30, 0x30, 0x7e, 0x30, 0x30, 0x30, // 40
0x7e, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x7e, 0x30, 0x30, 0x30, 0x7e, 0x30, 0x30, 0x30, 0x7e, 0x30, 0x30, 0x30, // 60
0x7e, 0x30, 0x30, 0x30, 0x7e, 0x30, 0x30, 0x30, 0x7e, 0x30, 0x30, 0x30, 0x7e, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, // 80
0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x30, 0x4f, 0x5a, 0xf9, 0x06, // 100
0xf9, 0x03, 0x00, 0x7f, 0x40, 0x43, 0xe6, 0x02, 0x70, 0xcf, 0x71, 0x10, 0x62, 0xe3, 0x00, 0x70, 0xcf, 0x50, 0x80, 0x4e, // 120
0x5d, 0xd5, 0x08, 0x62, 0xd5, 0x00, 0x55, 0xfa // 128
};
// ****************************** PORT BIT MASKS ******************************
// ****************************************************************************
// **** PROCESSOR SPECIFIC ****
// ****************************************************************************
// **** USER ATTENTION REQUIRED ****
// ****************************************************************************
#define SDATA_PIN 0x80 // P1.7
#define SCLK_PIN 0x40 // P1.6
#define XRES_PIN 0x40 // P2.6
#define TARGET_VDD 0x08 // P2.3
// ********************* LOW-LEVEL ISSP SUBROUTINE SECTION ********************
// ****************************************************************************
// **** PROCESSOR SPECIFIC ****
// ****************************************************************************
// **** USER ATTENTION REQUIRED ****
// ****************************************************************************
// Delay()
// This delay uses a simple "nop" loop. With the CPU running at 24MHz, each
// pass of the loop is about 1 usec plus an overhead of about 3 usec.
// total delay = (n + 3) * 1 usec
// To adjust delays and to adapt delays when porting this application, see the
// ISSP_Delays.h file.
// ****************************************************************************
void Delay(unsigned char n) // by KIMC
{
while(n)
{
//asm("nop");
n -= 1;
}
}
// ********************* LOW-LEVEL ISSP SUBROUTINE SECTION ********************
// ****************************************************************************
// **** PROCESSOR SPECIFIC ****
// ****************************************************************************
// **** USER ATTENTION REQUIRED ****
// ****************************************************************************
// LoadProgramData()
// The final application should load program data from HEX file generated by
// PSoC Designer into a 64 byte host ram buffer.
// 1. Read data from next line in hex file into ram buffer. One record
// (line) is 64 bytes of data.
// 2. Check host ram buffer + record data (Address, # of bytes) against hex
// record checksum at end of record line
// 3. If error reread data from file or abort
// 4. Exit this Function and Program block or verify the block.
// This demo program will, instead, load predetermined data into each block.
// The demo does it this way because there is no comm link to get data.
// ****************************************************************************
void LoadProgramData(unsigned char bBankNum, unsigned char bBlockNum)
{
// >>> The following call is for demo use only. <<<
// Function InitTargetTestData fills buffer for demo
for (bTargetDataPtr = 0; bTargetDataPtr < TARGET_DATABUFF_LEN; bTargetDataPtr++)
{
// Binarydata is f/w binary.
abTargetDataOUT[bTargetDataPtr] = BinaryData[wBinaryAddress];
wBinaryAddress++;
if (wBinaryAddress == 128)
{
wBinaryAddress = 0;
}
}
// Note:
// Error checking should be added for the final version as noted above.
// For demo use this function just returns VOID.
}
// ********************* LOW-LEVEL ISSP SUBROUTINE SECTION ********************
// ****************************************************************************
// **** PROCESSOR SPECIFIC ****
// ****************************************************************************
// **** USER ATTENTION REQUIRED ****
// ****************************************************************************
// fLoadSecurityData()
// Load security data from hex file into 64 byte host ram buffer. In a fully
// functional program (not a demo) this routine should do the following:
// 1. Read data from security record in hex file into ram buffer.
// 2. Check host ram buffer + record data (Address, # of bytes) against hex
// record checksum at end of record line
// 3. If error reread security data from file or abort
// 4. Exit this Function and Program block
// In this demo routine, all of the security data is set to unprotected (0x00)
// and it returns.
// This function always returns PASS. The flag return is reserving
// functionality for non-demo versions.
// ****************************************************************************
signed char fLoadSecurityData(unsigned char bBankNum)
{
// >>> The following call is for demo use only. <<<
// Function LoadArrayWithSecurityData fills buffer for demo
// abSecurityData is security data which is included in the f/w file.
for (bTargetDataPtr = 0; bTargetDataPtr < SECURITY_BYTES_PER_BANK; bTargetDataPtr++)
{
//abTargetDataOUT[bTargetDataPtr] = abSecurityData[bTargetDataPtr];
abTargetDataOUT_secure[bTargetDataPtr] = 0xff;
}
// Note:
// Error checking should be added for the final version as noted above.
// For demo use this function just returns PASS.
return(PASS);
}
// ********************* LOW-LEVEL ISSP SUBROUTINE SECTION ********************
// ****************************************************************************
// **** PROCESSOR SPECIFIC ****
// ****************************************************************************
// **** USER ATTENTION REQUIRED ****
// ****************************************************************************
// fSDATACheck()
// Check SDATA pin for high or low logic level and return value to calling
// routine.
// Returns:
// 0 if the pin was low.
// 1 if the pin was high.
// ****************************************************************************
unsigned char fSDATACheck(void)
{
if ( gpio_get_value ( TSP_SDA ) )
return(1);
else
return(0);
}
// ********************* LOW-LEVEL ISSP SUBROUTINE SECTION ********************
// ****************************************************************************
// **** PROCESSOR SPECIFIC ****
// ****************************************************************************
// **** USER ATTENTION REQUIRED ****
// ****************************************************************************
// SCLKHigh()
// Set the SCLK pin High
// ****************************************************************************
void SCLKHigh(void)
{
gpio_direction_output(TSP_SCL, 1);//gpio output high
delay_us(1);
//udelay(1);
}
// ********************* LOW-LEVEL ISSP SUBROUTINE SECTION ********************
// ****************************************************************************
// **** PROCESSOR SPECIFIC ****
// ****************************************************************************
// **** USER ATTENTION REQUIRED ****
// ****************************************************************************
// SCLKLow()
// Make Clock pin Low
// ****************************************************************************
void SCLKLow(void)
{
gpio_direction_output(TSP_SCL, 0);//gpio output low
delay_us(1);
//udelay(1);
}
#ifndef RESET_MODE // Only needed for power cycle mode
// ********************* LOW-LEVEL ISSP SUBROUTINE SECTION ********************
// ****************************************************************************
// **** PROCESSOR SPECIFIC ****
// ****************************************************************************
// **** USER ATTENTION REQUIRED ****
// ****************************************************************************
// SetSCLKHiZ()
// Set SCLK pin to HighZ drive mode.
// ****************************************************************************
void SetSCLKHiZ(void)
{
gpio_direction_input(TSP_SCL);//gpio input
}
#endif
// ********************* LOW-LEVEL ISSP SUBROUTINE SECTION ********************
// ****************************************************************************
// **** PROCESSOR SPECIFIC ****
// ****************************************************************************
// **** USER ATTENTION REQUIRED ****
// ****************************************************************************
// SetSCLKStrong()
// Set SCLK to an output (Strong drive mode)
// ****************************************************************************
void SetSCLKStrong(void)
{
gpio_direction_output(TSP_SCL ,0);//gpio output (low)
}
// ********************* LOW-LEVEL ISSP SUBROUTINE SECTION ********************
// ****************************************************************************
// **** PROCESSOR SPECIFIC ****
// ****************************************************************************
// **** USER ATTENTION REQUIRED ****
// ****************************************************************************
// SetSDATAHigh()
// Make SDATA pin High
// ****************************************************************************
void SetSDATAHigh(void)
{
#if 0
PRT1DR |= SDATA_PIN;
#endif
gpio_direction_output(TSP_SDA ,1);//gpio output high
delay_us(2);
//udelay(2);
}
// ********************* LOW-LEVEL ISSP SUBROUTINE SECTION ********************
// ****************************************************************************
// **** PROCESSOR SPECIFIC ****
// ****************************************************************************
// **** USER ATTENTION REQUIRED ****
// ****************************************************************************
// SetSDATALow()
// Make SDATA pin Low
// ****************************************************************************
void SetSDATALow(void)
{
gpio_direction_output(TSP_SDA, 0);//gpio output low
delay_us(2);
//udelay(2);
}
// ********************* LOW-LEVEL ISSP SUBROUTINE SECTION ********************
// ****************************************************************************
// **** PROCESSOR SPECIFIC ****
// ****************************************************************************
// **** USER ATTENTION REQUIRED ****
// ****************************************************************************
// SetSDATAHiZ()
// Set SDATA pin to an input (HighZ drive mode).
// ****************************************************************************
void SetSDATAHiZ(void)
{
gpio_direction_input(TSP_SDA);//gpio input
}
// ********************* LOW-LEVEL ISSP SUBROUTINE SECTION ********************
// ****************************************************************************
// **** PROCESSOR SPECIFIC ****
// ****************************************************************************
// **** USER ATTENTION REQUIRED ****
// ****************************************************************************
// SetSDATAStrong()
// Set SDATA for transmission (Strong drive mode) -- as opposed to being set to
// High Z for receiving data.
// ****************************************************************************
void SetSDATAStrong(void)
{
gpio_direction_output(TSP_SDA, 1);//gpio output (high)
}
#ifdef RESET_MODE
// ********************* LOW-LEVEL ISSP SUBROUTINE SECTION ********************
// ****************************************************************************
// **** PROCESSOR SPECIFIC ****
// ****************************************************************************
// **** USER ATTENTION REQUIRED ****
// ****************************************************************************
// SetXRESStrong()
// Set external reset (XRES) to an output (Strong drive mode).
// ****************************************************************************
void SetXRESStrong(void)
{
PRT2DM0 |= XRES_PIN;
PRT2DM1 &= ~XRES_PIN;
PRT2DM2 &= ~XRES_PIN;
}
// ********************* LOW-LEVEL ISSP SUBROUTINE SECTION ********************
// ****************************************************************************
// **** PROCESSOR SPECIFIC ****
// ****************************************************************************
// **** USER ATTENTION REQUIRED ****
// ****************************************************************************
// AssertXRES()
// Set XRES pin High
// ****************************************************************************
void AssertXRES(void)
{
PRT2DR |= XRES_PIN;
}
// ********************* LOW-LEVEL ISSP SUBROUTINE SECTION ********************
// ****************************************************************************
// **** PROCESSOR SPECIFIC ****
// ****************************************************************************
// **** USER ATTENTION REQUIRED ****
// ****************************************************************************
// DeassertXRES()
// Set XRES pin low.
// ****************************************************************************
void DeassertXRES(void)
{
PRT2DR &= ~XRES_PIN;
}
#else
// ********************* LOW-LEVEL ISSP SUBROUTINE SECTION ********************
// ****************************************************************************
// **** PROCESSOR SPECIFIC ****
// ****************************************************************************
// **** USER ATTENTION REQUIRED ****
// ****************************************************************************
// SetTargetVDDStrong()
// Set VDD pin (PWR) to an output (Strong drive mode).
// ****************************************************************************
void SetTargetVDDStrong(void)
{
TchDrv_DownloadVddSetLow();
}
// ********************* LOW-LEVEL ISSP SUBROUTINE SECTION ********************
// ****************************************************************************
// **** PROCESSOR SPECIFIC ****
// ****************************************************************************
// **** USER ATTENTION REQUIRED ****
// ****************************************************************************
// ApplyTargetVDD()
// Provide power to the target PSoC's Vdd pin through a GPIO.
// ****************************************************************************
void ApplyTargetVDD(void)
{
TchDrv_DownloadVddSetHigh();
}
// ********************* LOW-LEVEL ISSP SUBROUTINE SECTION ********************
// ****************************************************************************
// **** PROCESSOR SPECIFIC ****
// ****************************************************************************
// **** USER ATTENTION REQUIRED ****
// ****************************************************************************
// RemoveTargetVDD()
// Remove power from the target PSoC's Vdd pin.
// ****************************************************************************
void RemoveTargetVDD(void)
{
TchDrv_DownloadVddSetLow();
}
#endif
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
/////
///// Issp_routines.c
/////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
unsigned char bTargetDataIN;
//unsigned char abTargetDataOUT_secure[TARGET_DATABUFF_LEN] ={0x00,};
//unsigned char abTargetDataOUT[TARGET_DATABUFF_LEN];
//unsigned char abSecurityData[TARGET_DATABUFF_LEN];
extern unsigned int wBinaryAddress;
unsigned char bTargetAddress;
unsigned char bTargetDataPtr = 0;
unsigned char bTargetID[10];
unsigned char bTargetStatus[10]; //PTJ: created to support READ-STATUS in fReadStatus()
unsigned char fIsError;
/* ((((((((((((((((((((( LOW-LEVEL ISSP SUBROUTINE SECTION ))))))))))))))))))))
(( The subroutines in this section use functions from the C file ))
(( ISSP_Drive_Routines.c. The functions in that file interface to the ))
(( processor specific hardware. So, these functions should work as is, if ))
(( the routines in ISSP_Drive_Routines.c are correctly converted. ))
(((((((((((((((((((((((((((((((((((())))))))))))))))))))))))))))))))))))))))*/
// ============================================================================
// RunClock()
// Description:
// Run Clock without sending/receiving bits. Use this when transitioning from
// write to read and read to write "num_cycles" is number of SCLK cycles, not
// number of counter cycles.
//
// SCLK cannot run faster than the specified maximum frequency of 8MHz. Some
// processors may need to have delays added after setting SCLK low and setting
// SCLK high in order to not exceed this specification. The maximum frequency
// of SCLK should be measured as part of validation of the final program
//
// ============================================================================
void RunClock(unsigned int iNumCycles)
{
int i;
for(i=0; i < iNumCycles; i++) {
SCLKLow();
SCLKHigh();
}
// function exits with CLK high.
}
// ============================================================================
// bReceiveBit()
// Clocks the SCLK pin (high-low-high) and reads the status of the SDATA pin
// after the rising edge.
//
// SCLK cannot run faster than the specified maximum frequency of 8MHz. Some
// processors may need to have delays added after setting SCLK low and setting
// SCLK high in order to not exceed this specification. The maximum frequency
// of SCLK should be measured as part of validation of the final program
//
// Returns:
// 0 if SDATA was low
// 1 if SDATA was high
// ============================================================================
unsigned char bReceiveBit(void)
{
SCLKLow();
SCLKHigh();
if (fSDATACheck()) {
return(1);
}
else {
return(0);
}
}
// ============================================================================
// bReceiveByte()
// Calls ReceiveBit 8 times to receive one byte.
// Returns:
// The 8-bit values recieved.
// ============================================================================
unsigned char bReceiveByte(void)
{
unsigned char b;
unsigned char bCurrByte = 0x00;
for (b=0; b<8; b++) {
bCurrByte = (bCurrByte<<1) + bReceiveBit();
}
return(bCurrByte);
}
// ============================================================================
// SendByte()
// This routine sends up to one byte of a vector, one bit at a time.
// bCurrByte the byte that contains the bits to be sent.
// bSize the number of bits to be sent. Valid values are 1 to 8.
//
// SCLK cannot run faster than the specified maximum frequency of 8MHz. Some
// processors may need to have delays added after setting SCLK low and setting
// SCLK high in order to not exceed this specification. The maximum frequency
// of SCLK should be measured as part of validation of the final program
//
// There is no returned value.
// ============================================================================
void SendByte(unsigned char bCurrByte, unsigned char bSize)
{
unsigned char b = 0;
for(b=0; b<bSize; b++) {
if (bCurrByte & 0x80) {
// Send a '1'
SetSDATAHigh();
SCLKHigh();
SCLKLow();
}
else {
// Send a '0'
SetSDATALow();
SCLKHigh();
SCLKLow();
}
bCurrByte = bCurrByte << 1;
}
}
// ============================================================================
// SendVector()
// This routine sends the vector specifed. All vectors constant strings found
// in ISSP_Vectors.h. The data line is returned to HiZ after the vector is
// sent.
// bVect a pointer to the vector to be sent.
// nNumBits the number of bits to be sent.
// bCurrByte scratch var to keep the byte to be sent.
//
// There is no returned value.
// ============================================================================
void SendVector(const unsigned char* bVect, unsigned int iNumBits)
{
SetSDATAStrong();
while(iNumBits > 0)
{
if (iNumBits >= 8) {
SendByte(*(bVect), 8);
iNumBits -= 8;
bVect++;
}
else {
SendByte(*(bVect), iNumBits);
iNumBits = 0;
}
}
SetSDATAHiZ();
}
// ============================================================================
// fDetectHiLoTransition()
// Waits for transition from SDATA = 1 to SDATA = 0. Has a 100 msec timeout.
// TRANSITION_TIMEOUT is a loop counter for a 100msec timeout when waiting for
// a high-to-low transition. This is used in the polling loop of
// fDetectHiLoTransition(). The timing of the while(1) loops can be calculated
// and the number of loops is counted, using iTimer, to determine when 100
// msec has passed.
//
//// SCLK cannot run faster than the specified maximum frequency of 8MHz. Some
// processors may need to have delays added after setting SCLK low and setting
// SCLK high in order to not exceed this specification. The maximum frequency
// of SCLK should be measured as part of validation of the final program
//
// Returns:
// 0 if successful
// -1 if timed out.
// ============================================================================
signed char fDetectHiLoTransition(void)
{
// nTimer breaks out of the while loops if the wait in the two loops totals
// more than 100 msec. Making this static makes the loop run a faster.
// This is really a processor/compiler dependency and it not needed.
static unsigned int iTimer;
/// printk("[TSP] %s, %d\n", __func__, __LINE__);
// NOTE:
// These loops look unconventional, but it is necessary to check SDATA_PIN
// as shown because the transition can be missed otherwise, due to the
// length of the SDATA Low-High-Low after certain commands.
// Generate clocks for the target to pull SDATA High
iTimer = TRANSITION_TIMEOUT;//200ms
while(1) {
SCLKLow();
if (fSDATACheck()) // exit once SDATA goes HI
break;
SCLKHigh();
// If the wait is too long then timeout
if (iTimer-- == 0) {
printk( "[TSP] %s, %d : Error\n", __func__, __LINE__);
return (ERROR);
}
}
// Generate Clocks and wait for Target to pull SDATA Low again
iTimer = TRANSITION_TIMEOUT; // reset the timeout counter
while(1) {
SCLKLow();
if (!fSDATACheck()) { // exit once SDATA returns LOW
break;
}
//SCLKHigh();
// If the wait is too long then timeout
if (iTimer-- == 0) {
printk( "[TSP] %s, %d : Error\n", __func__, __LINE__);
return (ERROR);
}
}
return (PASS);
}
/* ((((((((((((((((((((( HIGH-LEVEL ISSP ROUTINE SECTION ))))))))))))))))))))))
(( These functions are mostly made of calls to the low level routines ))
(( above. This should isolate the processor-specific changes so that ))
(( these routines do not need to be modified. ))
(((((((((((((((((((((((((((((((((((())))))))))))))))))))))))))))))))))))))))*/
#ifdef RESET_MODE
// ============================================================================
// fXRESInitializeTargetForISSP()
// Implements the intialization vectors for the device.
// Returns:
// 0 if successful
// INIT_ERROR if timed out on handshake to the device.
// ============================================================================
signed char fXRESInitializeTargetForISSP(void)
{
// Configure the pins for initialization
SetSDATAHiZ();
SetSCLKStrong();
SCLKLow();
SetXRESStrong();
// Cycle reset and put the device in programming mode when it exits reset
AssertXRES();
Delay(XRES_CLK_DELAY);
DeassertXRES();
// !!! NOTE:
// The timing spec that requires that the first Init-Vector happen within
// 1 msec after the reset/power up. For this reason, it is not advisable
// to separate the above RESET_MODE or POWER_CYCLE_MODE code from the
// Init-Vector instructions below. Doing so could introduce excess delay
// and cause the target device to exit ISSP Mode.
//PTJ: Send id_setup_1 instead of init1_v
//PTJ: both send CA Test Key and do a Calibrate1 SROM function
SendVector(id_setup_1, num_bits_id_setup_1);
if (fIsError = fDetectHiLoTransition()) {
#ifdef TX_ON
TX8SW_CPutString("\r\n fDetectHiLoTransition Error");
#endif
return(INIT_ERROR);
}
SendVector(wait_and_poll_end, num_bits_wait_and_poll_end);
return(PASS);
}
#else //else = the part is power cycle programmed
// ============================================================================
// fPowerCycleInitializeTargetForISSP()
// Implements the intialization vectors for the device.
// The first time fDetectHiLoTransition is called the Clk pin is highZ because
// the clock is not needed during acquire.
// Returns:
// 0 if successful
// INIT_ERROR if timed out on handshake to the device.
// ============================================================================
signed char fPowerCycleInitializeTargetForISSP(void)
{
unsigned char n;
/// printk("[TSP] %s, %d\n", __func__, __LINE__);
// Set all pins to highZ to avoid back powering the PSoC through the GPIO
// protection diodes.
SetSCLKHiZ();
SetSDATAHiZ();
// Turn on power to the target device before other signals
SetTargetVDDStrong();
mdelay(200);//200ms
ApplyTargetVDD();
// wait 1msec for the power to stabilize
// for (n=0; n<10; n++) {
// Delay(DELAY100us);
// }
//mdelay(1);//1ms
// Set SCLK to high Z so there is no clock and wait for a high to low
// transition on SDAT. SCLK is not needed this time.
//SetSCLKHiZ();
SetSCLKStrong();
if (fIsError = fDetectHiLoTransition()) {
printk( "[TSP] %s, %d : Error\n", __func__, __LINE__);
return(INIT_ERROR);
}
// Configure the pins for initialization
SetSDATAHiZ();
SetSCLKStrong();
SCLKLow(); //PTJ: DO NOT SET A BREAKPOINT HERE AND EXPECT SILICON ID TO PASS!
// !!! NOTE:
// The timing spec that requires that the first Init-Vector happen within
// 1 msec after the reset/power up. For this reason, it is not advisable
// to separate the above RESET_MODE or POWER_CYCLE_MODE code from the
// Init-Vector instructions below. Doing so could introduce excess delay
// and cause the target device to exit ISSP Mode.
SendVector(id_setup_1, num_bits_id_setup_1);
if (fIsError = fDetectHiLoTransition()) {
printk( "[TSP] %s, %d : Error\n", __func__, __LINE__);
return(INIT_ERROR);
}
SendVector(wait_and_poll_end, num_bits_wait_and_poll_end);
return(PASS);
}
#endif
// ============================================================================
// fVerifySiliconID()
// Returns:
// 0 if successful
// Si_ID_ERROR if timed out on handshake to the device.
// ============================================================================
signed char fVerifySiliconID(void)
{
/// printk( "[TSP] %s, %d\n", __func__, __LINE__);
SendVector(id_setup_1, num_bits_id_setup_1);
if (fIsError = fDetectHiLoTransition()) {
#ifdef TX_ON
TX8SW_CPutString("\r\n fDetectHiLoTransition Error");
#endif
printk( "[TSP] %s, %d : Error\n", __func__, __LINE__);
return(SiID_ERROR);
}
SendVector(wait_and_poll_end, num_bits_wait_and_poll_end);
SendVector(id_setup_2, num_bits_id_setup_2);
if (fIsError = fDetectHiLoTransition()) {
#ifdef TX_ON
TX8SW_CPutString("\r\n fDetectHiLoTransition Error");
#endif
printk( "[TSP] %s, %d : Error\n", __func__, __LINE__);
return(SiID_ERROR);
}
SendVector(wait_and_poll_end, num_bits_wait_and_poll_end);
SendVector(tsync_enable, num_bits_tsync_enable);
//Send Read ID vector and get Target ID
SendVector(read_id_v, 11); // Read-MSB Vector is the first 11-Bits
RunClock(2); // Two SCLK cycles between write & read
bTargetID[0] = bReceiveByte();
RunClock(1);
SendVector(read_id_v+2, 12); // 1+11 bits starting from the 3rd byte
RunClock(2); // Read-LSB Command
bTargetID[1] = bReceiveByte();
RunClock(1);
SendVector(read_id_v+4, 1); // 1 bit starting from the 5th byte
//read Revision ID from Accumulator A and Accumulator X
SendVector(read_id_v+5, 11); //11 bits starting from the 6th byte
RunClock(2);
bTargetID[2] = bReceiveByte(); //Read from Acc.X
RunClock(1);
SendVector(read_id_v+7, 12); //1+11 bits starting from the 8th byte
RunClock(2);
bTargetID[3] = bReceiveByte(); //Read from Acc.A
RunClock(1);
SendVector(read_id_v+4, 1); //1bit starting from the 5th byte,
#ifdef TSYNC
SendVector(tsync_disable, num_bits_tsync_disable);
#endif /* TSYNC */
#ifdef TX_ON
// Print READ-ID
TX8SW_CPutString("\r\n Silicon-ID : ");
TX8SW_PutChar(' ');
TX8SW_PutSHexByte(bTargetID[0]);
TX8SW_PutChar(' ');
TX8SW_PutSHexByte(bTargetID[1]);
TX8SW_PutChar(' ');
TX8SW_PutSHexByte(bTargetID[2]);
TX8SW_PutChar(' ');
TX8SW_PutSHexByte(bTargetID[3]);
TX8SW_PutChar(' ');
#endif
if ( (bTargetID[0] != target_id_v[0]) || (bTargetID[1] != target_id_v[1]) )
{
printk( "[TSP] %s, %d : Error\n", __func__, __LINE__);
return(SiID_ERROR);
}
else
{
return(PASS);
}
}
// PTJ: =======================================================================
// fReadStatus()
// Returns:
// 0 if successful
// _____ if timed out on handshake to the device.
// ============================================================================
signed char fReadStatus(void)
{
/// printk( "[TSP] %s, %d\n", __func__, __LINE__);
#ifdef TSYNC
SendVector(tsync_enable, num_bits_tsync_enable);
#endif /* TSYNC */
//Send Read ID vector and get Target ID
SendVector(read_id_v, 11); // Read-MSB Vector is the first 11-Bits
RunClock(2); // Two SCLK cycles between write & read
bTargetStatus[0] = bReceiveByte();
RunClock(1);
SendVector(read_id_v+2, 12); // 12 bits starting from the 3rd character
RunClock(2); // Read-LSB Command
bTargetStatus[1] = bReceiveByte();
RunClock(1);
SendVector(read_id_v+4, 1); // 1 bit starting from the 5th character
#ifdef TSYNC
SendVector(tsync_disable, num_bits_tsync_disable);
#endif /* TSYNC */
if (bTargetStatus[0] == target_status00_v) {
return(PASS); //PTJ: Status = 00 means Success, the SROM function did what it was supposed to
}
if (bTargetStatus[0] == target_status01_v) {
printk( "[TSP] %s, %d : Error\n", __func__, __LINE__);
return(STATUS_ERROR); //PTJ: Status = 01 means that function is not allowed because of block level protection, for test with verify_setup (VERIFY-SETUP)
}
if (bTargetStatus[0] == target_status03_v) {
printk( "[TSP] %s, %d : Error\n", __func__, __LINE__);
return(STATUS_ERROR); //PTJ: Status = 03 is fatal error, SROM halted
}
if (bTargetStatus[0] == target_status04_v) {
printk( "[TSP] %s, %d : Error\n", __func__, __LINE__);
return(STATUS_ERROR); //PTJ: Status = 04 means there was a checksum faliure with either the smart write code checksum, or the smart write paramters checksum, for test with PROGRAM-AND-VERIFY
}
if (bTargetStatus[0] == target_status06_v) {
printk( "[TSP] %s, %d : Error\n", __func__, __LINE__);
return(STATUS_ERROR); //PTJ: Status = 06 means that Calibrate1 failed, for test with id_setup_1 (ID-SETUP-1)
}
else {
printk( "[TSP] %s, %d : Error\n", __func__, __LINE__);
return(STATUS_ERROR);
}
}
// PTJ: =======================================================================
// fReadCalRegisters()
// PTJ: use this to read some cal registers that should be loaded by Calibrate1 in id_setup_1
// Returns:
// 0 if successful
// _____ if timed out on handshake to the device.
// ============================================================================
signed char fReadCalRegisters(void)
{
/// printk( "[TSP] %s, %d\n", __func__, __LINE__);
#ifdef TSYNC
SendVector(tsync_enable, num_bits_tsync_enable);
#endif /* TSYNC */
SendVector(Switch_Bank1, 22);
SendVector(read_IMOtrim, 11); // Read-MSB Vector is the first 11-Bits
RunClock(2); // Two SCLK cycles between write & read
bTargetStatus[0] = bReceiveByte();
RunClock(1);
// Set SDATA to Strong Drive here because SendByte() does not
SetSDATAStrong();
SendByte(read_reg_end, 1);
SendVector(read_SPCtrim, 11); // Read-MSB Vector is the first 11-Bits
RunClock(2); // Two SCLK cycles between write & read
bTargetStatus[1] = bReceiveByte();
RunClock(1);
// Set SDATA to Strong Drive here because SendByte() does not
SetSDATAStrong();
SendByte(read_reg_end, 1);
SendVector(read_VBGfinetrim, 11); // Read-MSB Vector is the first 11-Bits
RunClock(2); // Two SCLK cycles between write & read
bTargetStatus[2] = bReceiveByte();
RunClock(1);
// Set SDATA to Strong Drive here because SendByte() does not
SetSDATAStrong();
SendByte(read_reg_end, 1);
SendVector(Switch_Bank0, 22);
#ifdef TSYNC
SendVector(tsync_disable, num_bits_tsync_disable);
#endif /* TSYNC */
if (bTargetStatus[0] == target_status00_v) {
return(PASS); //PTJ: Status = 00 means Success, the SROM function did what it was supposed to
}
return PASS;
}
// PTJ: =======================================================================
// fReadWriteSetup()
// PTJ: The READ-WRITE-SETUP vector will enable TSYNC and switches the device
// to SRAM bank1 for PROGRAM-AND-VERIFY, SECURE and VERIFY-SETUP.
// Returns:
// 0 if successful
// _____ if timed out on handshake to the device.
// ============================================================================
signed char fReadWriteSetup(void)
{
/// printk( "[TSP] %s, %d\n", __func__, __LINE__);
SendVector(read_write_setup, num_bits_read_write_setup);
return(PASS); //PTJ: is there anything else that should be done?
}
// ============================================================================
// fEraseTarget()
// Perform a bulk erase of the target device.
// Returns:
// 0 if successful
// ERASE_ERROR if timed out on handshake to the device.
// ============================================================================
signed char fEraseTarget(void)
{
/// printk( "[TSP] %s, %d\n", __func__, __LINE__);
SendVector(erase, num_bits_erase);
if (fIsError = fDetectHiLoTransition()) {
#ifdef TX_ON
TX8SW_CPutString("\r\n fDetectHiLoTransition");
#endif
printk( "[TSP] %s, %d : Error\n", __func__, __LINE__);
return(ERASE_ERROR);
}
SendVector(wait_and_poll_end, num_bits_wait_and_poll_end);
return(PASS);
}
extern unsigned int iBlockCounter;
// ============================================================================
// LoadTarget()
// Transfers data from array in Host to RAM buffer in the target.
// Returns the checksum of the data.
// ============================================================================
unsigned int iLoadTarget(void)
{
unsigned char bTemp;
unsigned int iChecksumData = 0;
/// printk( "[TSP] %s, %d\n", __func__, __LINE__);
// Set SDATA to Strong Drive here because SendByte() does not
SetSDATAStrong();
// Transfer the temporary RAM array into the target.
// In this section, a 128-Byte array was specified by #define, so the entire
// 128-Bytes are written in this loop.
bTargetAddress = 0x00;
bTargetDataPtr = 0x00;
while(bTargetDataPtr < TARGET_DATABUFF_LEN) {
bTemp = abTargetDataOUT[bTargetDataPtr];
iChecksumData += bTemp;
SendByte(write_byte_start,4); //PTJ: we need to be able to write 128 bytes from address 0x80 to 0xFF
SendByte(bTargetAddress, 7); //PTJ: we need to be able to write 128 bytes from address 0x80 to 0xFF
SendByte(bTemp, 8);
SendByte(write_byte_end, 3);
// !!!NOTE:
// SendByte() uses MSbits, so inc by '2' to put the 0..128 address into
// the seven MSBit locations.
//
// This can be confusing, but check the logic:
// The address is only 7-Bits long. The SendByte() subroutine will
// send however-many bits, BUT...always reads them bits from left-to-
// right. So in order to pass a value of 0..128 as the address using
// SendByte(), we have to left justify the address by 1-Bit.
// This can be done easily by incrementing the address each time by
// '2' rather than by '1'.
bTargetAddress += 2; //PTJ: inc by 2 in order to support a 128 byte address space, MSB~1 for address
bTargetDataPtr++;
}
return(iChecksumData);
}
// ============================================================================
// fProgramTargetBlock()
// Program one block with data that has been loaded into a RAM buffer in the
// target device.
// Returns:
// 0 if successful
// BLOCK_ERROR if timed out on handshake to the device.
// ============================================================================
signed char fProgramTargetBlock(unsigned char bBankNumber, unsigned char bBlockNumber)
{
/// printk( "[TSP] %s, %d\n", __func__, __LINE__);
#ifdef TSYNC
SendVector(tsync_enable, num_bits_tsync_enable);
#endif /* TSYNC */
#ifdef SET_BLOCK_NUM
SendVector(set_block_num, num_bits_set_block_num);
#endif
// Set the drive here because SendByte() does not.
SetSDATAStrong();
SendByte(bBlockNumber,8);
#ifdef SET_BLOCK_NUM
SendByte(set_block_num_end, 3);
#endif
#ifdef TSYNC
SendVector(tsync_disable, num_bits_tsync_disable);
#endif /* TSYNC */
// Send the program-block vector.
#ifdef PROGRAM_AND_VERIFY
SendVector(program_and_verify, num_bits_program_and_verify); //PTJ: PROGRAM-AND-VERIFY
#endif
// wait for acknowledge from target.
if (fIsError = fDetectHiLoTransition()) {
printk( "[TSP] %s, %d : Error\n", __func__, __LINE__);
return(BLOCK_ERROR);
}
// Send the Wait-For-Poll-End vector
SendVector(wait_and_poll_end, num_bits_wait_and_poll_end);
return(PASS);
}
// ============================================================================
// fAddTargetBankChecksum()
// Reads and adds the target bank checksum to the referenced accumulator.
// Returns:
// 0 if successful
// VERIFY_ERROR if timed out on handshake to the device.
// ============================================================================
signed char fAccTargetBankChecksum(unsigned int* pAcc)
{
/// printk( "[TSP] %s, %d\n", __func__, __LINE__);
unsigned int wCheckSumData = 0;
SendVector(checksum_setup, num_bits_checksum_setup); //PTJ:CHECKSUM-SETUP, it is taking 100ms > time > 200ms to complete the checksum
mdelay(200); // 200ms delay
/*
if (fIsError = fDetectHiLoTransition())
{ //100ms is default
//TX8SW_CPutString("This Hi-LOW");
printk( "[TSP] %s, %d : Error\n", __func__, __LINE__);
return(SECURITY_ERROR);
}
*/
SendVector(wait_and_poll_end, num_bits_wait_and_poll_end);
#ifdef TSYNC
SendVector(tsync_enable, num_bits_tsync_enable);
#endif /* TSYNC */
//Send Read Checksum vector and get Target Checksum
SendVector(read_checksum_v, 11); // first 11-bits is ReadCKSum-MSB
RunClock(2); // Two SCLKs between write & read
bTargetDataIN = bReceiveByte();
wCheckSumData = (bTargetDataIN & 0xFF)<<8;
RunClock(1); // See Fig. 6
SendVector(read_checksum_v + 2, 12); // 12 bits starting from 3rd character
RunClock(2); // Read-LSB Command
bTargetDataIN = bReceiveByte();
wCheckSumData |= (bTargetDataIN & 0xFF);
RunClock(1);
SendVector(read_checksum_v + 4, 1); // Send the final bit of the command
#ifdef TSYNC
SendVector(tsync_disable, num_bits_tsync_disable);
#endif /* TSYNC */
*pAcc = wCheckSumData;
return(PASS);
}
// ============================================================================
// ReStartTarget()
// After programming, the target PSoC must be reset to take it out of
// programming mode. This routine performs a reset.
// ============================================================================
void ReStartTarget(void)
{
printk( "[TSP] %s, %d\n", __func__, __LINE__);
#ifdef RESET_MODE
// Assert XRES, then release, then disable XRES-Enable
AssertXRES();
Delay(XRES_CLK_DELAY);
DeassertXRES();
#else
// Set all pins to highZ to avoid back powering the PSoC through the GPIO
// protection diodes.
SetSCLKHiZ();
SetSDATAHiZ();
// Cycle power on the target to cause a reset
RemoveTargetVDD();
mdelay(200);
ApplyTargetVDD();
mdelay(200);
#endif
}
// ============================================================================
// fVerifySetup()
// Verify the block just written to. This can be done byte-by-byte before the
// protection bits are set.
// Returns:
// 0 if successful
// BLOCK_ERROR if timed out on handshake to the device.
// ============================================================================
signed char fVerifySetup(unsigned char bBankNumber, unsigned char bBlockNumber)
{
/// printk( "[TSP] %s, %d\n", __func__, __LINE__);
#ifdef TSYNC
SendVector(tsync_enable, num_bits_tsync_enable);
#endif /* TSYNC */
#ifdef SET_BLOCK_NUM
SendVector(set_block_num, num_bits_set_block_num);
#endif
//Set the drive here because SendByte() does not
SetSDATAStrong();
SendByte(bBlockNumber,8);
#ifdef SET_BLOCK_NUM
SendByte(set_block_num_end, 3); //PTJ:
#endif
#ifdef TSYNC
SendVector(tsync_disable, num_bits_tsync_disable); //PTJ:
#endif /* TSYNC */
#ifdef VERIFY_SETUP
SendVector(verify_setup, num_bits_my_verify_setup); //PTJ:
#endif
if (fIsError = fDetectHiLoTransition()) {
printk( "[TSP] %s, %d : Error\n", __func__, __LINE__);
return(BLOCK_ERROR);
}
SendVector(wait_and_poll_end, num_bits_wait_and_poll_end);
return(PASS);
}
// ============================================================================
// fReadByteLoop()
// Reads the data back from Target SRAM and compares it to expected data in
// Host SRAM
// Returns:
// 0 if successful
// BLOCK_ERROR if timed out on handshake to the device.
// ============================================================================
signed char fReadByteLoop(void)
{
bTargetAddress = 0;
bTargetDataPtr = 0;
/// printk( "[TSP] %s, %d\n", __func__, __LINE__);
while(bTargetDataPtr < TARGET_DATABUFF_LEN)
{
//Send Read Byte vector and then get a byte from Target
SendVector(read_byte_v, 4);
// Set the drive here because SendByte() does not
SetSDATAStrong();
SendByte(bTargetAddress,7);
RunClock(2); // Run two SCLK cycles between writing and reading
SetSDATAHiZ(); // Set to HiZ so Target can drive SDATA
bTargetDataIN = bReceiveByte();
RunClock(1);
SendVector(read_byte_v + 1, 1); // Send the ReadByte Vector End
// Test the Byte that was read from the Target against the original
// value (already in the 128-Byte array "abTargetDataOUT[]"). If it
// matches, then bump the address & pointer,loop-back and continue.
// If it does NOT match abort the loop and return and error.
if (bTargetDataIN != abTargetDataOUT[bTargetDataPtr])
{
printk( "[TSP] %s, %d : Error\n", __func__, __LINE__);
return(BLOCK_ERROR);
}
bTargetDataPtr++;
// Increment the address by 2 to accomodate 7-Bit addressing
// (puts the 7-bit address into MSBit locations for "SendByte()").
bTargetAddress += 2;
}
return(PASS);
}
// ============================================================================
// fVerifyTargetBlock()
// Verify the block just written to. This can be done byte-by-byte before the
// protection bits are set.
// Returns:
// 0 if successful
// BLOCK_ERROR if timed out on handshake to the device.
// ============================================================================
signed char fVerifyTargetBlock(unsigned char bBankNumber, unsigned char bBlockNumber)
{
/// printk( "[TSP] %s, %d\n", __func__, __LINE__);
SendVector(set_block_number, 11);
//Set the drive here because SendByte() does not
SetSDATAStrong();
SendByte(bBlockNumber,8);
SendByte(set_block_number_end, 3);
SendVector(verify_setup, num_bits_my_verify_setup);
if (fIsError = fDetectHiLoTransition())
{
printk( "[TSP] %s, %d : Error\n", __func__, __LINE__);
return(BLOCK_ERROR);
}
SendVector(wait_and_poll_end, num_bits_wait_and_poll_end);
bTargetAddress = 0;
bTargetDataPtr = 0;
while(bTargetDataPtr < TARGET_DATABUFF_LEN) {
//Send Read Byte vector and then get a byte from Target
SendVector(read_byte_v, 4);
// Set the drive here because SendByte() does not
SetSDATAStrong();
SendByte(bTargetAddress,7);
RunClock(2); // Run two SCLK cycles between writing and reading
SetSDATAHiZ(); // Set to HiZ so Target can drive SDATA
bTargetDataIN = bReceiveByte();
RunClock(1);
SendVector(read_byte_v + 1, 1); // Send the ReadByte Vector End
// Test the Byte that was read from the Target against the original
// value (already in the 128-Byte array "abTargetDataOUT[]"). If it
// matches, then bump the address & pointer,loop-back and continue.
// If it does NOT match abort the loop and return an error.
if (bTargetDataIN != abTargetDataOUT[bTargetDataPtr])
{
#ifdef TX_ON
TX8SW_PutSHexByte(bTargetDataIN);
TX8SW_PutSHexByte(abTargetDataOUT[bTargetDataPtr]);
#endif
printk( "[TSP] %s, %d : Error\n", __func__, __LINE__);
return(BLOCK_ERROR);
}
bTargetDataPtr++;
// Increment the address by four to accomodate 6-Bit addressing
// (puts the 6-bit address into MSBit locations for "SendByte()").
bTargetAddress += 2;
}
return(PASS);
}
// ============================================================================
// fSecureTargetFlash()
// Before calling, load the array, abTargetDataOUT, with the desired security
// settings using LoadArrayWithSecurityData(StartAddress,Length,SecurityType).
// The can be called multiple times with different SecurityTypes as needed for
// particular Flash Blocks. Or set them all the same using the call below:
// Returns:
// 0 if successful
// SECURITY_ERROR if timed out on handshake to the device.
// ============================================================================
signed char fSecureTargetFlash(void)
{
unsigned char bTemp;
/// printk( "[TSP] %s, %d\n", __func__, __LINE__);
// Transfer the temporary RAM array into the target
bTargetAddress = 0x00;
bTargetDataPtr = 0x00;
SetSDATAStrong();
while(bTargetDataPtr < SECURITY_BYTES_PER_BANK)
{
//bTemp = abTargetDataOUT[bTargetDataPtr];
bTemp = abTargetDataOUT_secure[bTargetDataPtr];
SendByte(write_byte_start,4);
SendByte(bTargetAddress, 7);
SendByte(bTemp, 8);
SendByte(write_byte_end, 3);
// SendBytes() uses MSBits, so increment the address by '2' to put
// the 0..n address into the seven MSBit locations
bTargetAddress += 2; //PTJ: inc by 2 in order to support a 128 byte address space
bTargetDataPtr++;
}
SendVector(secure, num_bits_secure); //PTJ:
if (fIsError = fDetectHiLoTransition()) {
printk( "[TSP] %s, %d : Error\n", __func__, __LINE__);
return(SECURITY_ERROR);
}
SendVector(wait_and_poll_end, num_bits_wait_and_poll_end);
return(PASS);
}
// ============================================================================
// PTJ: fReadSecurity()
// This reads from SM0 with Read Supervisory SPC command.
// Need to have SPC Test Mode enabled before using these commands?
// Returns:
// 0 if successful
// __________ if timed out on handshake to the device.
// ============================================================================
signed char fReadSecurity(void)
{
/// printk( "[TSP] %s, %d\n", __func__, __LINE__);
SendVector(SPCTestMode_enable, num_bits_SPCTestMode_enable);
bTargetAddress = 0x00;
while(bTargetAddress < (SECURITY_BYTES_PER_BANK * 2)) { //PTJ: we do SECURITY_BYTES_PER_BANK * 2 because we bTargetAddress += 2
//PTJ: TSYNC Enable
SendVector(tsync_enable, num_bits_tsync_enable);
SendVector(read_security_pt1, num_bits_read_security_pt1); //PTJ:
// Set the drive here because SendByte() does not.
SetSDATAStrong();
SendByte(bTargetAddress,7); //PTJ: hardcode MSb of address as 0 in bit stream
SendVector(read_security_pt1_end, num_bits_read_security_pt1_end);
//PTJ: TSYNC Disable
SendVector(tsync_disable, num_bits_tsync_disable);
SendVector(read_security_pt2, num_bits_read_security_pt2);
SendVector(wait_and_poll_end, num_bits_wait_and_poll_end);
SendVector(read_security_pt3, num_bits_read_security_pt3);
SetSDATAStrong();
SendByte(bTargetAddress,7);
SendVector(read_security_pt3_end, num_bits_read_security_pt3_end);
SendVector(wait_and_poll_end, num_bits_wait_and_poll_end);
bTargetAddress +=2;
}
bTargetAddress = 0x00;
bTargetDataPtr = 0x00;
while(bTargetAddress < (SECURITY_BYTES_PER_BANK * 2)) { //PTJ: we do SECURITY_BYTES_PER_BANK * 2 because we bTargetAddress += 2
//Send Read Byte vector and then get a byte from Target
SendVector(read_byte_v, 4);
// Set the drive here because SendByte() does not
SetSDATAStrong();
SendByte(bTargetAddress,7);
RunClock(2); // Run two SCLK cycles between writing and reading
SetSDATAHiZ(); // Set to HiZ so Target can drive SDATA
bTargetDataIN = bReceiveByte();
RunClock(1);
SendVector(read_byte_v + 1, 1); // Send the ReadByte Vector End
// Test the Byte that was read from the Target against the original
// value (already in the 128-Byte array "abTargetDataOUT[]"). If it
// matches, then bump the address & pointer,loop-back and continue.
// If it does NOT match abort the loop and return and error.
//if (bTargetDataIN != abTargetDataOUT[bTargetDataPtr])
if (bTargetDataIN != abTargetDataOUT_secure[bTargetDataPtr])
{
printk( "[TSP] bTargetDataIN = %x\n", bTargetDataIN);
printk( "[TSP] abTargetDataOUT_secure[%d] = %x\n", bTargetDataPtr, abTargetDataOUT_secure[bTargetDataPtr]);
printk( "[TSP] %s, %d : Error\n", __func__, __LINE__);
return(BLOCK_ERROR);
}
// Increment the address by two to accomodate 7-Bit addressing
// (puts the 7-bit address into MSBit locations for "SendByte()").
bTargetDataPtr++;
bTargetAddress += 2;
}
return(PASS);
}
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
/////
///// Main.c
/////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
/* ############################################################################
################### CRITICAL PROJECT CONSTRAINTS ########################
############################################################################
ISSP programming can only occur within a temperature range of 5C to 50C.
- This project is written without temperature compensation and using
programming pulse-widths that match those used by programmers such as the
Mini-Prog and the ISSP Programmer.
This means that the die temperature of the PSoC device cannot be outside
of the above temperature range.
If a wider temperature range is required, contact your Cypress Semi-
conductor FAE or sales person for assistance.
The project can be configured to program devices at 5V or at 3.3V.
- Initialization of the device is different for different voltages. The
initialization is hardcoded and can only be set for one voltage range.
The supported voltages ranges are 3.3V (3.0V to 3.6V) and 5V (4.75V to
5.25V). See the device datasheet for more details. If varying voltage
ranges must be supported, contact your Cypress Semiconductor FAE or sales
person for assistance.
- ISSP programming for the 2.7V range (2.7V to 3.0V) is not supported.
This program does not support programming all PSoC Devices
- It does not support obsoleted PSoC devices. A list of devices that are
not supported is shown here:
CY8C22x13 - not supported
CY8C24x23 - not supported (CY8C24x23A is supported)
CY8C25x43 - not supported
CY8C26x43 - not supported
- It does not suport devices that have not been released for sale at the
time this version was created. If you need to ISSP program a newly released
device, please contact Cypress Semiconductor Applications, your FAE or
sales person for assistance.
The CY8C20x23 devices are not supported at the time of this release.
############################################################################
##########################################################################*/
/* (((((((((((((((((((((((((((((((((((((())))))))))))))))))))))))))))))))))))))
PSoC In-System Serial Programming (ISSP) Template
This PSoC Project is designed to be used as a template for designs that
require PSoC ISSP Functions.
This project is based on the AN2026 series of Application Notes. That app
note should be referenced before any modifications to this project are made.
The subroutines and files were created in such a way as to allow easy cut &
paste as needed. There are no customer-specific functions in this project.
This demo of the code utilizes a PSoC as the Host.
Some of the subroutines could be merged, or otherwise reduced, but they have
been written as independently as possible so that the specific steps involved
within each function can easily be seen. By merging things, some code-space
savings could be realized.
As is, and with all features enabled, the project consumes approximately 3500
bytes of code space, and 19-Bytes of RAM (not including stack usage). The
Block-Verify requires a 64-Byte buffer for read-back verification. This same
buffer could be used to hold the (actual) incoming program data.
Please refer to the compiler-directives file "directives.h" to see the various
features.
The pin used in this project are assigned as shown below. The HOST pins are
arbitrary and any 3 pins could be used (the masks used to control the pins
must be changed). The TARGET pins cannot be changed, these are fixed function
pins on the PSoC.
The PWR pin is used to provide power to the target device if power cycle
programming mode is used. The compiler directive RESET_MODE in ISSP_directives.h
is used to select the programming mode. This pin could control the enable on
a voltage regulator, or could control the gate of a FET that is used to turn
the power to the PSoC on.
The TP pin is a Test Point pin that can be used signal from the host processor
that the program has completed certain tasks. Predefined test points are
included that can be used to observe the timing for bulk erasing, block
programming and security programming.
SIGNAL HOST TARGET
---------------------
SDATA P1.0 P1.0
SCLK P1.1 P1.1
XRES P2.0 XRES
PWR P2.1 Vdd
TP P0.7 n/a
For test & demonstration, this project generates the program data internally.
It does not take-in the data from an external source such as I2C, UART, SPI,
etc. However, the program was written in such a way to be portable into such
designs. The spirit of this project was to keep it stripped to the minimum
functions required to do the ISSP functions only, thereby making a portable
framework for integration with other projects.
The high-level functions have been written in C in order to be portable to
other processors. The low-level functions that are processor dependent, such
as toggling pins and implementing specific delays, are all found in the file
ISSP_Drive_Routines.c. These functions must be converted to equivalent
functions for the HOST processor. Care must be taken to meet the timing
requirements when converting to a new processor. ISSP timing information can
be found in Application Note AN2026. All of the sections of this program
that need to be modified for the host processor have "PROCESSOR_SPECIFIC" in
the comments. By performing a "Find in files" using "PROCESSOR_SPECIFIC" these
sections can easily be identified.
The variables in this project use Hungarian notation. Hungarian prepends a
lower case letter to each variable that identifies the variable type. The
prefixes used in this program are defined below:
b = byte length variable, signed char and unsigned char
i = 2-byte length variable, signed int and unsigned int
f = byte length variable used as a flag (TRUE = 0, FALSE != 0)
ab = an array of byte length variables
After this program has been ported to the desired host processor the timing
of the signals must be confirmed. The maximum SCLK frequency must be checked
as well as the timing of the bulk erase, block write and security write
pulses.
The maximum SCLK frequency for the target device can be found in the device
datasheet under AC Programming Specifications with a Symbol of "Fsclk".
An oscilloscope should be used to make sure that no half-cycles (the high
time or the low time) are shorter than the half-period of the maximum
freqency. In other words, if the maximum SCLK frequency is 8MHz, there can be
no high or low pulses shorter than 1/(2*8MHz), or 62.5 nsec.
The test point (TP) functions, enabled by the define USE_TP, provide an output
from the host processor that brackets the timing of the internal bulk erase,
block write and security write programming pulses. An oscilloscope, along with
break points in the PSoC ICE Debugger should be used to verify the timing of
the programming. The Application Note, "Host-Sourced Serial Programming"
explains how to do these measurements and should be consulted for the expected
timing of the erase and program pulses.
/* ############################################################################
############################################################################
(((((((((((((((((((((((((((((((((((((()))))))))))))))))))))))))))))))))))))) */
/*----------------------------------------------------------------------------
// C main line
//----------------------------------------------------------------------------
*/
//#include <m8c.h> // part specific constants and macros
//#include "PSoCAPI.h" // PSoC API definitions for all User Modules
// ------ Declarations Associated with ISSP Files & Routines -------
// Add these to your project as needed.
//#include "ISSP_extern.h"
//#include "ISSP_directives.h"
//#include "ISSP_defs.h"
//#include "ISSP_errors.h"
//#include "Device.h"
/* ------------------------------------------------------------------------- */
unsigned char bBankCounter;
unsigned int iBlockCounter;
unsigned int iChecksumData;
unsigned int iChecksumTarget;
unsigned int wBinaryAddress;
/* ========================================================================= */
// ErrorTrap()
// Return is not valid from main for PSOC, so this ErrorTrap routine is used.
// For some systems returning an error code will work best. For those, the
// calls to ErrorTrap() should be replaced with a return(bErrorNumber). For
// other systems another method of reporting an error could be added to this
// function -- such as reporting over a communcations port.
/* ========================================================================= */
void ErrorTrap(unsigned char bErrorNumber)
{
printk( "[TSP] %s, %d : ErrorNumber = %d\n", __func__, __LINE__, bErrorNumber);
#ifndef RESET_MODE
// Set all pins to highZ to avoid back powering the PSoC through the GPIO
// protection diodes.
SetSCLKHiZ();
SetSDATAHiZ();
// If Power Cycle programming, turn off the target
RemoveTargetVDD();
#endif
#ifdef TX_ON
TX8SW_CPutString("\r\nErrorTrap");
TX8SW_PutSHexByte(bErrorNumber);
#endif
//while (1);
// return(bErrorNumbers);
}
void Delay_int(unsigned int n) // by KIMC
{
while(n)
{
//asm("nop");
n -= 1;
}
}
/* ========================================================================= */
/* MAIN LOOP */
/* Based on the diagram in the AN2026 */
/* ========================================================================= */
unsigned char make2ChTo1(unsigned char hi, unsigned char lo)
{
unsigned char ch;
if(hi == 'A' || hi == 'a')
hi = 0xa;
else if(hi == 'B' || hi == 'b')
hi = 0xb;
else if(hi == 'C' || hi == 'c')
hi = 0xc;
else if(hi == 'D' || hi == 'd')
hi = 0xd;
else if(hi == 'E' || hi == 'e')
hi = 0xe;
else if(hi == 'F' || hi == 'f')
hi = 0xf;
else
hi = hi;
if(lo == 'A' || lo == 'a')
lo = 0xa;
else if(lo == 'B' || lo == 'b')
lo = 0xb;
else if(lo == 'C' || lo == 'c')
lo = 0xc;
else if(lo == 'D' || lo == 'd')
lo = 0xd;
else if(lo == 'E' || lo == 'e')
lo = 0xe;
else if(lo == 'F' || lo == 'f')
lo = 0xf;
else
lo = lo;
ch = ((hi&0x0f) << 4) | (lo & 0x0f);
return ch;
}
unsigned int load_tst200_frimware_data(int HW_ver)
{
int i,j;
extern unsigned char tsp_special_update;
mm_segment_t oldfs;
// struct file *filp;
int fd;
uint8_t* buffer;
int result = -1;
unsigned int nBinary_length = 0;
unsigned int firmwareline, onelinelength;
unsigned char temp_onelinedata[128];
if(tsp_special_update == 0)//normal firmware update from phone-binary
{
if(HW_ver == 2)
{
for(i=0; i<512; i++)
for(j=0; j<64; j++)
firmData[i][j] = BinaryData_HW02[i*64 + j];
return PASS;
}
else if(HW_ver == 3)
{
for(i=0; i<512; i++)
for(j=0; j<64; j++)
firmData[i][j] = BinaryData_HW03[i*64 + j];
return PASS;
}
else if(HW_ver == 4)
{
for(i=0; i<512; i++)
for(j=0; j<64; j++)
firmData[i][j] = BinaryData_HW04[i*64 + j];
return PASS;
}
else if(HW_ver == 5)
{
for(i=0; i<512; i++)
for(j=0; j<64; j++)
firmData[i][j] = BinaryData_HW05[i*64 + j];
return PASS;
}
else
{
return NO_FIRMWARE_ERROR;
}
}
else if(tsp_special_update == 1)//special firmware update from t-flash
{
printk("[TSP] %s, %d\n", __func__, __LINE__ );
oldfs = get_fs();
set_fs (KERNEL_DS); /* set KERNEL address space */
/* - Get file Size */
buffer = kmalloc(72192, GFP_KERNEL);/*141*512*/
if(buffer == NULL)
{
printk("[TSP] firmware_down_using_sdcard : alllocate mem fail\n");
result = FILE_ACCESS_ERROR;
goto error;
}
if((fd = sys_open("/mnt/sdcard/luisa_tsp.hex", O_RDONLY | O_LARGEFILE, 0)) > 0)
{
if(sys_read(fd, buffer, 72192) > 0)
{
sys_close(fd);
printk("[TSP] firmware_down_using_sdcard : read file success\n");
}
else
{
sys_close(fd);
result = FILE_ACCESS_ERROR;
printk("[TSP] firmware_down_using_sdcard : file read fail\n");
goto error;
}
}
else
{
result = FILE_ACCESS_ERROR;
printk("[TSP] firmware_down_using_sdcard : file open fail\n");
goto error;
}
printk("\n[TSP] firmware_down_using_sdcard : firmware_data : START \n");
for(firmwareline=0; firmwareline<512; firmwareline++)
{
i = 0;
strncpy(temp_onelinedata, buffer + 141*firmwareline + 9, 128);
for(onelinelength=0; onelinelength<64; onelinelength++)
{
firmData[firmwareline][onelinelength] = make2ChTo1(temp_onelinedata[i], temp_onelinedata[i+1]);
i += 2;
}
}
printk("\n[TSP] firmware_down_using_sdcard : firmware_data : END \n");
/*
for(i=0; i<512; i++)
{
for(j=0; j<64; j++)
printk("%x ", firmData[i][j]);
printk("\n");
}
printk("\n[TSP] firmware_data : END \n");
*/
result = PASS;
error:
if(buffer)
kfree(buffer);
set_fs(oldfs);
return result;
}
else
{
return NO_FIRMWARE_ERROR;
}
#if 0
//unsigned char *pData = NULL;
//unsigned char *temp;
unsigned int nBinary_length = 0;
unsigned int i, j, firmwareline, onelinelength;
unsigned int TSP_FILE_SIZE = 256;
unsigned int TSP_blk = 0;
FSFILE* fp;
int nRead;
char pathName[256];
extern unsigned char sv_tch_special_update;
extern unsigned char tch_ven_id;
extern unsigned char tch_mod_rev;
extern unsigned char tch_fw_ver;
OSTASK_Sleep(100);
//Delay10us(1000*100);//100ms
if(sv_tch_special_update == 1)
strcpy(pathName, "/Mount/Mmc/collins_test.hex");
else if(tch_mod_rev == 0x01)
strcpy(pathName, "/SystemFS/Driver/TouchFirmware/TST200/ModRev_01/collins_01_lastest.hex");
else
return NO_FIRMWARE_ERROR;
OSTASK_Sleep(100);
//Delay10us(1000*100);//100ms
//------------------------------
// Open a file
//------------------------------
fp = FS_Open(pathName, "rb");
if (fp == NULL)
{
// FS_Close(fp);
//return MCSDL_RET_FILE_ACCESS_FAILED;
return FILE_ACCESS_ERROR;
}
//------------------------------
// Read binary file
//------------------------------
FS_Read(pData, 1, 141*515, fp); // Read binary file
//------------------------------
// Close file
//------------------------------
FS_Close(fp);
for(firmwareline=0; firmwareline<515; firmwareline++)
{
i = 0;
if(firmwareline < 512)
{
strncpy(temp_onelinedata, pData + 141*firmwareline + 9, 128);
for(onelinelength=0; onelinelength<64; onelinelength++)
{
firmData[firmwareline][onelinelength] = make2ChTo1(temp_onelinedata[i], temp_onelinedata[i+1]);
i += 2;
}
}
else if(firmwareline == 512)
{
}
else
{
strncpy(temp_onelinedata, pData + 141*(firmwareline-1) + 17 + 9, 128);
for(onelinelength=0; onelinelength<64; onelinelength++)
{
firmData[firmwareline-1][onelinelength] = make2ChTo1(temp_onelinedata[i], temp_onelinedata[i+1]);
i += 2;
}
}
}
for(j=0; j<128; j++)
{
if(j<64)
abTargetDataOUT_secure[j] = firmData[512][j];
else
abTargetDataOUT_secure[j] = firmData[513][j-64];
}
#endif
return PASS;
}
int cypress_update(HW_ver)
{
unsigned int i;
unsigned int aIndex;
unsigned int bTry=0;
// -- This example section of commands show the high-level calls to -------
// -- perform Target Initialization, SilcionID Test, Bulk-Erase, Target ---
// -- RAM Load, FLASH-Block Program, and Target Checksum Verification. ----
if (fIsError = load_tst200_frimware_data(HW_ver))
{
ErrorTrap(fIsError);
return fIsError;
}
// >>>> ISSP Programming Starts Here <<<<
#ifdef TX_ON
TX8SW_Start();
TX8SW_PutCRLF();
TX8SW_PutCRLF();
TX8SW_PutCRLF();
TX8SW_PutCRLF();
TX8SW_CPutString("\r\nStart");
#endif
// Acquire the device through reset or power cycle
#ifdef RESET_MODE
for (bTry=0 ; bTry < 5 ; bTry++) // when failure, retrying the initialization.
{
fIsError = fXRESInitializeTargetForISSP();
if(!fIsError)
{
break;
}
else
{
ReStartTarget();
}
}
if (fIsError)
{
ErrorTrap(fIsError);
}
#else
// Initialize the Host & Target for ISSP operations
for (bTry=0 ; bTry < 5 ; bTry++) // when failure, retrying the initialization.
{
fIsError = fPowerCycleInitializeTargetForISSP();
if(!fIsError)
{
break;
}
else
{
ReStartTarget();
}
}
if (fIsError)
{
ErrorTrap(fIsError);
return fIsError;
}
#endif // initialization mode
#ifdef TX_ON
TX8SW_CPutString("\r\n InitializeTargetForISSP");
#endif
// Run the SiliconID Verification, and proceed according to result.
if (fIsError = fVerifySiliconID())
{
ErrorTrap(fIsError);
return fIsError;
}
#ifdef TX_ON
TX8SW_CPutString("\r\n fVerifySiliconID");
#endif
/* Disable watchdog and interrupt */
//TchDrv_DownloadDisableIRQ(); // Disable Baseband touch interrupt ISR.
//TchDrv_DownloadDisableWD(); // Disable Baseband watchdog timer
// Bulk-Erase the Device.
if (fIsError = fEraseTarget())
{
ErrorTrap(fIsError);
goto MCSDL_DOWNLOAD_FINISH;
}
#ifdef TX_ON
TX8SW_CPutString("\r\n fEraseTarget");
TX8SW_CPutString("\r\n Program Flash Blocks Start");
#endif
//==============================================================//
// Program Flash blocks with predetermined data. In the final application
// this data should come from the HEX output of PSoC Designer.
iChecksumData = 0; // Calculte the device checksum as you go
wBinaryAddress = 0 ;
for (bBankCounter=0; bBankCounter<NUM_BANKS; bBankCounter++) //PTJ: NUM_BANKS should be 1 for Krypton
{
for (iBlockCounter=0; iBlockCounter<BLOCKS_PER_BANK; iBlockCounter++)
{
//PTJ: READ-WRITE-SETUP used here to select SRAM Bank 1, and TSYNC Enable
if (fIsError = fReadWriteSetup())
{
ErrorTrap(fIsError);
goto MCSDL_DOWNLOAD_FINISH;
}
#ifdef TX_ON
TX8SW_PutChar('#');
#endif
//----------------------------------------------------------------------------//
// need to modify - user code
#if 1//please check
aIndex = iBlockCounter*2;
for(i=0;i<TARGET_DATABUFF_LEN;i++)
{
if(i<64)
{
abTargetDataOUT[i] = firmData[aIndex][i];
}
else
{
abTargetDataOUT[i] = firmData[aIndex+1][i-64];
}
}
#endif
//LoadProgramData(bBankCounter, (unsigned char)iBlockCounter);
iChecksumData += iLoadTarget();
//----------------------------------------------------------------------------//
if (fIsError = fProgramTargetBlock(bBankCounter,(unsigned char)iBlockCounter))
{
ErrorTrap(fIsError);
goto MCSDL_DOWNLOAD_FINISH;
}
// READ-STATUS after PROGRAM-AND-VERIFY
if (fIsError = fReadStatus())
{
ErrorTrap(fIsError);
goto MCSDL_DOWNLOAD_FINISH;
}
}
}
#ifdef TX_ON
TX8SW_CPutString("\r\n Program Flash Blocks End");
#endif
#if 1 // Verify
#ifdef TX_ON
TX8SW_CPutString("\r\n Verify Start");
#endif
//=======================================================//
//PTJ: Doing Verify
//PTJ: this code isnt needed in the program flow because we use PROGRAM-AND-VERIFY (ProgramAndVerify SROM Func)
//PTJ: which has Verify built into it.
// Verify included for completeness in case host desires to do a stand-alone verify at a later date.
wBinaryAddress = 0;
for (bBankCounter=0; bBankCounter<NUM_BANKS; bBankCounter++)
{
for (iBlockCounter=0; iBlockCounter<BLOCKS_PER_BANK; iBlockCounter++)
{
//LoadProgramData(bBankCounter, (unsigned char)iBlockCounter);
#if 1//please check
aIndex = iBlockCounter*2;
for(i=0;i<TARGET_DATABUFF_LEN;i++)
{
if(i<64)
{
abTargetDataOUT[i] = firmData[aIndex][i];
}
else
{
abTargetDataOUT[i] = firmData[aIndex+1][i-64];
}
}
#endif
//PTJ: READ-WRITE-SETUP used here to select SRAM Bank 1, and TSYNC Enable
if (fIsError = fReadWriteSetup())
{
ErrorTrap(fIsError);
goto MCSDL_DOWNLOAD_FINISH;
}
if (fIsError = fVerifySetup(bBankCounter, (unsigned char)iBlockCounter))
{
ErrorTrap(fIsError);
goto MCSDL_DOWNLOAD_FINISH;
}
#ifdef TX_ON
TX8SW_PutChar('.');
#endif
if (fIsError = fReadStatus())
{
ErrorTrap(fIsError);
goto MCSDL_DOWNLOAD_FINISH;
}
//PTJ: READ-WRITE-SETUP used here to select SRAM Bank 1, and TSYNC Enable
if (fIsError = fReadWriteSetup())
{
ErrorTrap(fIsError);
goto MCSDL_DOWNLOAD_FINISH;
}
if (fIsError = fReadByteLoop())
{
ErrorTrap(fIsError);
goto MCSDL_DOWNLOAD_FINISH;
}
}
}
#ifdef TX_ON
TX8SW_CPutString("\r\n Verify End");
#endif
#endif // end Verify
#if 1 // program security
#ifdef TX_ON
TX8SW_CPutString("\r\n Security Start");
#endif
//=======================================================//
// Program security data into target PSoC. In the final application this
// data should come from the HEX output of PSoC Designer.
for (bBankCounter=0; bBankCounter<NUM_BANKS; bBankCounter++)
{
//PTJ: READ-WRITE-SETUP used here to select SRAM Bank 1
if (fIsError = fReadWriteSetup()) {
ErrorTrap(fIsError);
goto MCSDL_DOWNLOAD_FINISH;
}
//----------------------------------------------------------------------------//
// need to modify - user code
#if 1//please check
// Load one bank of security data from hex file into buffer
if (fIsError = fLoadSecurityData(bBankCounter))
{
ErrorTrap(fIsError);
goto MCSDL_DOWNLOAD_FINISH;
}
#endif
//----------------------------------------------------------------------------//
// Secure one bank of the target flash
if (fIsError = fSecureTargetFlash())
{
ErrorTrap(fIsError);
goto MCSDL_DOWNLOAD_FINISH;
}
}
/*
if (fIsError = fReadSecurity())
{
ErrorTrap(fIsError);
goto MCSDL_DOWNLOAD_FINISH;
}
*/
#ifdef TX_ON
TX8SW_CPutString("\r\n End Security data");
#endif
#endif // program security
#ifdef TX_ON
TX8SW_CPutString("\r\n CheckSum Start");
#endif
//=======================================================//
//PTJ: Doing Checksum
iChecksumTarget = 0;
for (bBankCounter=0; bBankCounter<NUM_BANKS; bBankCounter++)
{
if (fIsError = fAccTargetBankChecksum(&iChecksumTarget))
{
printk( "[TSP] %s, %d : Error\n", __func__, __LINE__);
ErrorTrap(fIsError);
goto MCSDL_DOWNLOAD_FINISH;
}
}
#ifdef TX_ON
TX8SW_CPutString("\r\n Checksum : iChecksumTarget (0x");
TX8SW_PutSHexInt(iChecksumTarget);
TX8SW_CPutString("), iChecksumData (0x");
TX8SW_PutSHexInt(iChecksumData);
TX8SW_CPutString(")");
#endif
if ((iChecksumTarget & 0xFFFF) != (iChecksumData & 0xFFFF))
{
printk( "[TSP] %s, %d : Error\n", __func__, __LINE__);
fIsError = CHECKSUM_ERROR;
ErrorTrap(fIsError);
goto MCSDL_DOWNLOAD_FINISH;
}
#ifdef TX_ON
TX8SW_CPutString("\r\n Doing Checksum");
#endif
// *** SUCCESS ***
// At this point, the Target has been successfully Initialize, ID-Checked,
// Bulk-Erased, Block-Loaded, Block-Programmed, Block-Verified, and Device-
// Checksum Verified.
// You may want to restart Your Target PSoC Here.
ReStartTarget();
#ifdef TX_ON
TX8SW_CPutString("\r\n ReStartTarget");
#endif
#if 0
while(1) {
// Continue with other functions or return to the calling routine
}
#endif
MCSDL_DOWNLOAD_FINISH :
// Delay10us(50*1000);
// Delay10us(50*1000);
/* Enable watchdog and interrupt */
// TchDrv_DownloadEnableWD();
// TchDrv_DownloadEnableIRQ();
// Delay10us(50*1000);
// Delay10us(50*1000);
// Delay10us(50*1000);
// Delay10us(50*1000);
ReStartTarget();
return fIsError;
}
| 35.283034 | 199 | 0.527267 | [
"vector"
] |
65298050037d94b7dbbdd48a2402400c9768b100 | 4,503 | h | C | copasi/layout/CLColorDefinition.h | SzVarga/COPASI | 00451b1a67eeec8272c73791ca861da754a7c4c4 | [
"Artistic-2.0"
] | 64 | 2015-03-14T14:06:18.000Z | 2022-02-04T23:19:08.000Z | copasi/layout/CLColorDefinition.h | SzVarga/COPASI | 00451b1a67eeec8272c73791ca861da754a7c4c4 | [
"Artistic-2.0"
] | 4 | 2017-08-16T10:26:46.000Z | 2020-01-08T12:05:54.000Z | copasi/layout/CLColorDefinition.h | SzVarga/COPASI | 00451b1a67eeec8272c73791ca861da754a7c4c4 | [
"Artistic-2.0"
] | 28 | 2015-04-16T14:14:59.000Z | 2022-03-28T12:04:14.000Z | // Copyright (C) 2019 by Pedro Mendes, Rector and Visitors of the
// University of Virginia, University of Heidelberg, and University
// of Connecticut School of Medicine.
// All rights reserved.
// Copyright (C) 2017 - 2018 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and University of
// of Connecticut School of Medicine.
// All rights reserved.
// Copyright (C) 2010 - 2016 by Pedro Mendes, Virginia Tech Intellectual
// Properties, Inc., University of Heidelberg, and The University
// of Manchester.
// All rights reserved.
#ifndef CLColorDefinition_H__
#define CLColorDefinition_H__
#include <string>
#include "copasi/layout/CLBase.h"
#include "copasi/core/CDataObject.h"
LIBSBML_CPP_NAMESPACE_BEGIN
class ColorDefinition;
LIBSBML_CPP_NAMESPACE_END
class CDataContainer;
class CLColorDefinition : public CLBase, public CDataObject
{
private:
// preent the compiler from generating the assignment operator
CLColorDefinition& operator=(const CLColorDefinition& source);
protected:
// id is inherited from SBase
unsigned char mRed;
unsigned char mGreen;
unsigned char mBlue;
unsigned char mAlpha;
/**
* The color definition needs a key.
*/
std::string mKey;
/**
* The color definition needs an id in addition to the key.
* The id corresponds to the id in the SBML render extension and it does not have to
* be globally unique. As a matter of fact, it is sometimes needed that color definitions of
* different render information have the same id.
*/
std::string mId;
public:
/**
* Static method to create a CDataObject based on the provided data
* @param const CData & data
* @return CLColorDefinition * pDataObject
*/
static CLColorDefinition * fromData(const CData & data, CUndoObjectInterface * pParent);
/**
* Retrieve the data describing the object
* @return CData data
*/
virtual CData toData() const;
/**
* Apply the provided data to the object
* @param const CData & data
* @return bool success
*/
virtual bool applyData(const CData & data, CUndoData::CChangeSet & changes);
/**
* Contructor which sets the ColorDefinition to completely opaque
* black.
*/
CLColorDefinition(CDataContainer* pParent = NULL);
/**
* Constructor which sets the ColorDefinition to the given RGBA values.
*/
CLColorDefinition(unsigned char r, unsigned char g, unsigned char b, unsigned char a = 255, CDataContainer* pParent = NULL);
/**
* Copy Contructor
*/
CLColorDefinition(const CLColorDefinition& source, CDataContainer* pParent = NULL);
/**
* Constructor to generate object from the corresponding SBML object.
*/
CLColorDefinition(const ColorDefinition& source, CDataContainer* pParent = NULL);
virtual ~CLColorDefinition();
/**
* Returns the red color component.
*/
unsigned char getRed() const;
/**
* Returns the green color component.
*/
unsigned char getGreen() const;
/**
* Returns the blue color component.
*/
unsigned char getBlue() const;
/**
* Returns the alpha color component.
*/
unsigned char getAlpha() const;
/**
* Sets the red color component.
*/
void setRed(unsigned char c);
/**
* Sets the green color component.
*/
void setGreen(unsigned char c);
/**
* Sets the blue color component.
*/
void setBlue(unsigned char c);
/**
* Sets alpha red color component.
*/
void setAlpha(unsigned char c);
/**
* Sets the red green, blue and alpha color component.
* The alpha value is optional and defaults to 255 if not given.
*/
void setRGBA(unsigned char r, unsigned char g, unsigned char b, unsigned char a = 255);
/**
* Sets the color value from a given string.
* If the string is not a valid value string, the color value is set to
* black and false is returned.
*/
bool setColorValue(const std::string& valueString);
/**
* Creates a string the represents the current color value.
*/
std::string createValueString() const;
/**
* Returns the key of the color definition.
*/
const std::string& getKey() const;
/**
* Converts this object to the corresponding SBML object.
*/
ColorDefinition* toSBML(unsigned int level, unsigned int version) const;
/**
* Returns the id of the object.
*/
const std::string& getId() const;
/**
* Sets the id of the object.
*/
void setId(const std::string& id);
};
#endif /* CLColorDefinition_H__ */
| 25.016667 | 126 | 0.69598 | [
"render",
"object"
] |
652b9ebe28fdd542a837c329ed13d4cfdc9972d7 | 3,503 | c | C | src/level.c | HHP267/Game2D | d9ac052d91c35c0371a3baa8ef48865b7d3faaa5 | [
"MIT"
] | null | null | null | src/level.c | HHP267/Game2D | d9ac052d91c35c0371a3baa8ef48865b7d3faaa5 | [
"MIT"
] | null | null | null | src/level.c | HHP267/Game2D | d9ac052d91c35c0371a3baa8ef48865b7d3faaa5 | [
"MIT"
] | null | null | null | #include "level.h"
#include "camera.h"
#include "simple_logger.h"
#include "simple_json.h"
#include "entity.h"
#include "floor.h"
#include "camera.h"
#include <stdlib.h>
Level *levelNew()
{
Level *level;
level = (Level *)malloc(sizeof(Level));
if (!level)
{
slog("Failed to allocate memory for the game level");
return NULL;
}
memset(level, 0, sizeof(Level));
return level;
}
Level *levelLoad(const char *filename)
{
const char *string;
Level *level;
SJson *json, *leveljs, *levelMap, *row;
int rows, cols, i, j, count, tileIndex;
entity_manager_init(100);
if (!filename)
{
slog("filename is NULL, cannot load level");
return NULL;
}
json = sj_load(filename);
if (!json) return NULL;
level = levelNew();
if (!level)
{
return NULL;
}
leveljs = sj_object_get_value(json, "level");
if (!leveljs)
{
slog("Missing Level JSON object");
levelFree(level);
sj_free(json);
return NULL;
}
string = sj_get_string_value(sj_object_get_value(leveljs, "bgimage"));
if (string)
{
level->bgimage = gf2d_sprite_load_image((char *)string);
}
string = sj_get_string_value(sj_object_get_value(leveljs, "tileset"));
if (string)
{
sj_get_integer_value(sj_object_get_value(leveljs, "tileWidth"), &level->tileWidth);
sj_get_integer_value(sj_object_get_value(leveljs, "tileHeight"), &level->tileHeight);
sj_get_integer_value(sj_object_get_value(leveljs, "tileFramesPerLine"), &level->tileFramesPerLine);
level->tilesetA = gf2d_sprite_load_all(
(char *)string,
level->tileWidth,
level->tileHeight,
level->tileFramesPerLine);
}
levelMap = sj_object_get_value(leveljs, "tileMap");
if (!levelMap)
{
slog("missing tileMap data");
levelFree(level);
sj_free(json);
return NULL;
}
rows = sj_array_get_count(levelMap);
row = sj_array_get_nth(levelMap, 0);
cols = sj_array_get_count(row);
count = rows*cols;
level->levelWidth = cols;
level->levelHeight = rows;
level->tileMap = (TileTypes *)gfc_allocate_array(sizeof(TileTypes), count);
if (!level->tileMap)
{
levelFree(level);
sj_free(json);
return NULL;
}
tileIndex = 0;
for (j = 0; j < rows; j++)
{
row = sj_array_get_nth(levelMap, j);
if (!row)continue;
if (cols != sj_array_get_count(row))
{
slog("row %i, cols count mismatch");
continue;
}
for (i = 0; i < cols; i++)
{
sj_get_integer_value(sj_array_get_nth(row, i), &level->tileMap[tileIndex++]);
}
}
sj_free(json);
return level;
}
void levelFree(Level *level)
{
if (!level)
{
return;
}
if (level->tileMap != NULL)
{
free(level->tileMap);
level->tileMap = NULL;
}
gf2d_sprite_free(level->bgimage);
gf2d_sprite_free(level->tilesetA);
free(level);
}
void levelDraw(Level *level)
{
int i;
if (!level)
{
slog("Cannot Draw Level - Null pointer provided");
return;
}
//draw BG
gf2d_sprite_draw_image(level->bgimage, vector2d(0, 0));
if (!level->tileMap)
{
slog("no tiles loaded for level");
return;
}
//draw tiles
for (i = 0; i < level->levelWidth * level->levelHeight; i++)
{
if (level->tileMap[i] == 0) continue;
gf2d_sprite_draw(
level->tilesetA,
vector2d((i%level->levelWidth) * level->tilesetA->frame_w, (i/level->levelHeight) * level->tilesetA->frame_h),
NULL,
NULL,
NULL,
NULL,
NULL,
level->tileMap[i] - 1);
}
}
/*footer*/ | 19.247253 | 114 | 0.635741 | [
"object"
] |
65314942a46c90de90bbea3738e1083e7cfbc807 | 3,912 | h | C | ARK2D/src/ARK2D/GJ/GameJolt.h | ashleygwinnell/ark2d | bbfbee742ace9c52841dad4fab74d0d120ffe662 | [
"Unlicense"
] | 6 | 2015-08-25T19:16:20.000Z | 2021-04-19T16:47:58.000Z | ARK2D/src/ARK2D/GJ/GameJolt.h | ashleygwinnell/ark2d | bbfbee742ace9c52841dad4fab74d0d120ffe662 | [
"Unlicense"
] | 1 | 2015-09-17T14:03:12.000Z | 2015-09-17T14:03:12.000Z | ARK2D/src/ARK2D/GJ/GameJolt.h | ashleygwinnell/ark2d | bbfbee742ace9c52841dad4fab74d0d120ffe662 | [
"Unlicense"
] | 1 | 2018-10-02T19:59:47.000Z | 2018-10-02T19:59:47.000Z | /*
* GameJolt.h
*
* Created on: Jun 26, 2012
* Author: ashleygwinnell
*/
#ifndef ARK_GJ_GAMEJOLT_H_
#define ARK_GJ_GAMEJOLT_H_
//#include "../Includes.h"
#include "../Namespaces.h"
#include "DataStore.h"
#include "Highscore.h"
#include "Trophy.h"
#include "User.h"
#include "MD5.h"
#include <string>
#include <vector>
using namespace std;
namespace ARK {
namespace GJ {
class ARK2D_API GameJolt {
private: // protected properties
unsigned int m_gameId;
string m_privateKey;
string m_username;
string m_userToken;
bool m_verbose;
bool m_verified;
string m_errorMessage;
unsigned int m_usingFormat;
public:
static const unsigned int FORMAT_PLAINTEXT = 0;
static const unsigned int FORMAT_JSON = 1;
static const unsigned int FORMAT_XML = 2;
protected: // protected functions
string md5(string input);
string open(string url);
string url(string method, map<string, string> params);
string url(string method, map<string, string> params, bool addUserToken);
string url(string method, map<string, string> params, bool addUserToken, bool addKey);
string request(string method, map<string, string> params);
string request(string method, map<string, string> params, bool requiresVerified);
void logError(string message);
void logWarning(string message);
void logInformation(string message);
string getFormatString() {
if (m_usingFormat == FORMAT_PLAINTEXT) {
return "keypair";
} else if (m_usingFormat == FORMAT_JSON) {
return "json";
} else if (m_usingFormat == FORMAT_XML) {
return "xml";
}
return "keypair";
}
public: // public functions
GameJolt(unsigned int gameId, string privateKey);
GameJolt(unsigned int gameId, string privateKey, string username, string userToken);
void setVerbose(bool verbose);
bool isVerbose();
bool isVerified();
bool hasQuickplay();
User* getQuickplayUser();
User* getVerifiedUser();
bool verifyUser(string username, string token);
string getErrorMessage();
vector<Highscore> getHighscoresInTable(unsigned int tableId, unsigned int page, unsigned int limit);
vector<Highscore*> getHighscores();
vector<Highscore*> getHighscores(bool all);
vector<Highscore*> getHighscores(bool all, unsigned int limit);
bool addHighscore(string score, int sort);
bool addHighscore(string score, int sort, string extra);
bool addGuestHighscore(string username, string score, int sort);
bool addGuestHighscore(string username, string score, int sort, string extra);
bool addGuestHighscore(string username, string score, int sort, string extra, unsigned int tableId);
DataStore* setDataStore(unsigned int type, string key, string value);
bool removeDataStore(unsigned int type, string key);
vector<DataStore*> getDataStores(unsigned int type);
vector<string> getDataStoreKeys(unsigned int type);
DataStore* getDataStore(unsigned int type, string key);
bool sessionOpen();
bool sessionUpdate();
bool sessionUpdate(bool active);
bool sessionClose();
inline void setFormat(unsigned int format) { m_usingFormat = format; }
bool m_isBatching;
int m_numBatchItems;
string m_batchUrl;
void startBatch();
string endBatch();
bool isBatching();
// get rank
//unsigned int getRank(signed int score);
unsigned int getRank(signed int score, unsigned int tableId);
string achieveTrophy(Trophy* trophy);
string achieveTrophy(unsigned int trophyId);
vector<Trophy*> getTrophies();
vector<Trophy*> getTrophies(unsigned int achieved);
Trophy* getTrophy(int trophyId);
string request(string method, string params);
string request(string method, string params, bool requiresVerified);
virtual ~GameJolt();
};
}
}
#endif /* ARK_GJ_GAMEJOLT_H_ */
| 28.764706 | 104 | 0.705521 | [
"vector"
] |
653dbe68537d1dfbbc10f9181f987eb5f73666af | 893 | h | C | EHenTaiViewer/QJMangaImageDownloader.h | lvjunru/exhTest | 016181021846b3de94610611c61f7042a84a1053 | [
"MIT"
] | 1,141 | 2017-01-07T06:46:19.000Z | 2022-03-28T07:58:33.000Z | EHenTaiViewer/QJMangaImageDownloader.h | iphone4855662/E-HentaiViewer | f5702a9a587cd4537e077657b2fdb3a7a00de7f0 | [
"MIT"
] | 90 | 2017-01-26T00:36:12.000Z | 2022-01-11T13:07:07.000Z | EHenTaiViewer/QJMangaImageDownloader.h | iphone4855662/E-HentaiViewer | f5702a9a587cd4537e077657b2fdb3a7a00de7f0 | [
"MIT"
] | 147 | 2017-04-23T15:10:14.000Z | 2022-03-08T20:13:12.000Z | //
// QJMangaImageDownloader.h
// EHenTaiViewer
//
// Created by kayanouriko on 2018/6/12.
// Copyright © 2018年 kayanouriko. All rights reserved.
//
#import <Foundation/Foundation.h>
@class QJMangaImageModel, QJMangaImageDownloader;
@protocol QJMangaImageDownloaderDelegate <NSObject>
@optional
- (void)imageDownloadFinishWithLoader:(QJMangaImageDownloader *)loader;
@end
@interface QJMangaImageDownloader : NSOperation
@property (nonatomic, strong) id<QJMangaImageDownloaderDelegate> delegate;
// 持有的对象
@property (nonatomic, strong) QJMangaImageModel *model;
// indexPath
@property (nonatomic, strong, readonly) NSIndexPath *indexPathInTableView;
// 初始化
- (instancetype)initWithModel:(QJMangaImageModel *)model atIndexPath:(NSIndexPath *)indexPath showKey:(NSString *)showkey gid:(NSString *)gid thdelegate:(id<QJMangaImageDownloaderDelegate>)delegate;
- (void)cancelTask;
@end
| 26.264706 | 198 | 0.790594 | [
"model"
] |
654bfb00382c9a0fc728a566b4f05d15d77c0793 | 1,693 | h | C | src/Board.h | kluge/jatkanshakki | 3dc0aca39832369d4efedaccb7ab4f8f989ee3a7 | [
"Zlib"
] | null | null | null | src/Board.h | kluge/jatkanshakki | 3dc0aca39832369d4efedaccb7ab4f8f989ee3a7 | [
"Zlib"
] | null | null | null | src/Board.h | kluge/jatkanshakki | 3dc0aca39832369d4efedaccb7ab4f8f989ee3a7 | [
"Zlib"
] | null | null | null | #ifndef BOARD_H
#define BOARD_H
#include <vector>
#include <QString>
/// The different states a tic tac toe square can be in.
enum Square
{
Blank = 0,
X,
O
};
/// Convert Square to the traditional ASCII representation.
inline
QString toQString(Square square) {
switch (square) {
case X:
return "X";
case O:
return "O";
default:
return " ";
}
}
/// Coordinates to a specific square on the board.
struct Point
{
int row;
int column;
};
/// A variable-sized square board for 5-in-a-row tic tac toe.
class Board
{
public:
Board(int rows = 5);
static int const TARGET = 5; ///< amount of connected symbols needed to win
Square& operator()(int r, int c);
Square const& operator()(int r, int c) const;
/// Amount of rows (and columns) in the square grid
int rows() const;
typedef std::vector<Square>::const_iterator const_iterator;
typedef std::vector<Square>::iterator iterator;
const_iterator begin() const;
iterator begin();
const_iterator end() const;
iterator end();
/// Total amount of squares on the board.
size_t size() const;
/// Whether all the squares on the board are already full.
bool full() const;
private:
int m_rows;
std::vector<Square> m_squares;
};
struct RunLength
{
Square square;
int length;
};
typedef std::vector<RunLength> RunLengths;
std::vector<RunLengths> rowRunLengths(Board const& board);
std::vector<RunLengths> colRunLengths(Board const& board);
std::vector<RunLengths> downwardDiagonalRunLengths(Board const& board);
std::vector<RunLengths> upwardDiagonalRunLengths(Board const& board);
#endif // BOARD_H
| 20.39759 | 79 | 0.669817 | [
"vector"
] |
654ee1e6707ebb7e675d58c45d6bf94d4f87feba | 22,233 | c | C | tools/BladeRF/fx3_firmware/src/cyfxbladeRFusbdscr.c | Charmve/BLE-Security-Att-Def | 3652d84bf4ac0c694bb3c4c0f611098da9122af0 | [
"BSD-2-Clause"
] | 149 | 2020-10-23T23:31:51.000Z | 2022-03-15T00:25:35.000Z | tools/BladeRF/fx3_firmware/src/cyfxbladeRFusbdscr.c | Charmve/BLE-Security-Att-Def | 3652d84bf4ac0c694bb3c4c0f611098da9122af0 | [
"BSD-2-Clause"
] | 1 | 2021-04-12T19:24:00.000Z | 2021-04-27T03:11:07.000Z | tools/BladeRF/fx3_firmware/src/cyfxbladeRFusbdscr.c | Charmve/BLE-Security-Att-Def | 3652d84bf4ac0c694bb3c4c0f611098da9122af0 | [
"BSD-2-Clause"
] | 22 | 2020-11-17T02:52:40.000Z | 2022-03-15T00:26:38.000Z | /*
* Copyright (c) 2013-2017 Nuand LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include "bladeRF.h"
#include "cyfxbladeRF.h"
/* Device descriptors for USB 3.0 and 2.0 (CyFxUSB30DeviceDscr[] and
* CyFxUSB20DeviceDscr[]), along with the product string descriptor
* (CyFxUSBProductDscr[]), are now located in the product-specific files
* (bladeRF1.c and bladeRF2.c) */
/* Binary device object store descriptor */
const uint8_t CyFxUSBBOSDscr[] __attribute__ ((aligned (32))) __attribute__ ((section(".usbdscr"))) =
{
0x05, /* Descriptor size */
CY_U3P_BOS_DESCR, /* Device descriptor type */
0x16,0x00, /* Length of this descriptor and all sub descriptors */
0x02, /* Number of device capability descriptors */
/* USB 2.0 extension */
0x07, /* Descriptor size */
CY_U3P_DEVICE_CAPB_DESCR, /* Device capability type descriptor */
CY_U3P_USB2_EXTN_CAPB_TYPE, /* USB 2.0 extension capability type */
0x02,0x00,0x00,0x00, /* Supported device level features: LPM support */
/* SuperSpeed device capability */
0x0A, /* Descriptor size */
CY_U3P_DEVICE_CAPB_DESCR, /* Device capability type descriptor */
CY_U3P_SS_USB_CAPB_TYPE, /* SuperSpeed device capability type */
0x00, /* Supported device level features */
0x0E,0x00, /* Speeds supported by the device : SS, HS and FS */
0x03, /* Functionality support */
0x00, /* U1 Device Exit latency */
0x00,0x00 /* U2 Device Exit latency */
};
/* Standard device qualifier descriptor */
const uint8_t CyFxUSBDeviceQualDscr[] __attribute__ ((aligned (32))) __attribute__ ((section(".usbdscr"))) =
{
0x0A, /* Descriptor size */
CY_U3P_USB_DEVQUAL_DESCR, /* Device qualifier descriptor type */
0x00,0x02, /* USB 2.0 */
0x00, /* Device class */
0x00, /* Device sub-class */
0x00, /* Device protocol */
0x40, /* Maxpacket size for EP0 : 64 bytes */
0x01, /* Number of configurations */
0x00 /* Reserved */
};
/* Standard super speed configuration descriptor */
const uint8_t CyFxUSBSSConfigDscr[] __attribute__ ((aligned (32))) __attribute__ ((section(".usbdscr"))) =
{
/* Configuration descriptor */
0x09, /* Descriptor size */
CY_U3P_USB_CONFIG_DESCR, /* Configuration descriptor type */
0x7B,0x00, /* Length of this descriptor and all sub descriptors */
0x01, /* Number of interfaces */
0x01, /* Configuration number */
0x00, /* COnfiguration string index */
0x80, /* Config characteristics - Bus powered */
0x64, /* Max power consumption of device (in 8mA unit) : 200mA */
/* Interface descriptor #0, alt interface #0, Nothing */
0x09, /* Descriptor size */
CY_U3P_USB_INTRFC_DESCR, /* Interface Descriptor type */
0x00, /* Interface number */
0x00, /* Alternate setting number */
0x00, /* Number of end points */
0xFF, /* Interface class */
0x00, /* Interface sub class */
0x00, /* Interface protocol code */
0x00, /* Interface descriptor string index */
/* Interface descriptor #0, alt interface #1, RF */
0x09, /* Descriptor size */
CY_U3P_USB_INTRFC_DESCR, /* Interface Descriptor type */
0x00, /* Interface number */
0x01, /* Alternate setting number */
0x04, /* Number of end points */
0xFF, /* Interface class */
0x00, /* Interface sub class */
0x00, /* Interface protocol code */
0x00, /* Interface descriptor string index */
/* Endpoint descriptor for consumer EP */
0x07, /* Descriptor size */
CY_U3P_USB_ENDPNT_DESCR, /* Endpoint descriptor type */
CY_FX_EP_CONSUMER, /* Endpoint address and description */
CY_U3P_USB_EP_BULK, /* Bulk endpoint type */
0x00,0x04, /* Max packet size = 1024 bytes */
0x00, /* Servicing interval for data transfers : 0 for Bulk */
/* Super speed endpoint companion descriptor for consumer EP */
0x06, /* Descriptor size */
CY_U3P_SS_EP_COMPN_DESCR, /* SS endpoint companion descriptor type */
0x0f, /* Max no. of packets in a burst : 0: burst 1 packet at a time */
0x00, /* Max streams for bulk EP = 0 (No streams) */
0x00,0x00, /* Service interval for the EP : 0 for bulk */
/* Endpoint descriptor for producer EP */
0x07, /* Descriptor size */
CY_U3P_USB_ENDPNT_DESCR, /* Endpoint descriptor type */
CY_FX_EP_PRODUCER, /* Endpoint address and description */
CY_U3P_USB_EP_BULK, /* Bulk endpoint type */
0x00,0x04, /* Max packet size = 1024 bytes */
0x00, /* Servicing interval for data transfers : 0 for bulk */
/* Super speed endpoint companion descriptor for producer EP */
0x06, /* Descriptor size */
CY_U3P_SS_EP_COMPN_DESCR, /* SS endpoint companion descriptor type */
0x0f, /* Max no. of packets in a burst : 0: burst 1 packet at a time */
0x00, /* Max streams for bulk EP = 0 (No streams) */
0x00,0x00, /* Service interval for the EP : 0 for bulk */
/* Endpoint descriptor for consumer EP */
0x07, /* Descriptor size */
CY_U3P_USB_ENDPNT_DESCR, /* Endpoint descriptor type */
0x82, /* Endpoint address and description */
CY_U3P_USB_EP_BULK, /* Bulk endpoint type */
0x00,0x04, /* Max packet size = 1024 bytes */
0x00, /* Servicing interval for data transfers : 0 for Bulk */
/* Super speed endpoint companion descriptor for consumer EP */
0x06, /* Descriptor size */
CY_U3P_SS_EP_COMPN_DESCR, /* SS endpoint companion descriptor type */
0x01, /* Max no. of packets in a burst : 0: burst 1 packet at a time */
0x00, /* Max streams for bulk EP = 0 (No streams) */
0x00,0x00, /* Service interval for the EP : 0 for bulk */
/* Endpoint descriptor for producer EP */
0x07, /* Descriptor size */
CY_U3P_USB_ENDPNT_DESCR, /* Endpoint descriptor type */
BLADE_FPGA_EP_PRODUCER, /* Endpoint address and description */
CY_U3P_USB_EP_BULK, /* Bulk endpoint type */
0x00,0x04, /* Max packet size = 1024 bytes */
0x00, /* Servicing interval for data transfers : 0 for bulk */
/* Super speed endpoint companion descriptor for producer EP */
0x06, /* Descriptor size */
CY_U3P_SS_EP_COMPN_DESCR, /* SS endpoint companion descriptor type */
0x0f, /* Max no. of packets in a burst : 0: burst 1 packet at a time */
0x00, /* Max streams for bulk EP = 0 (No streams) */
0x00,0x00, /* Service interval for the EP : 0 for bulk */
/* Interface descriptor #0, alt interface #2, FX3 firmware */
0x09, /* Descriptor size */
CY_U3P_USB_INTRFC_DESCR, /* Interface Descriptor type */
0x00, /* Interface number */
0x02, /* Alternate setting number */
0x01, /* Number of end points */
0xFF, /* Interface class */
0x00, /* Interface sub class */
0x00, /* Interface protocol code */
0x00, /* Interface descriptor string index */
/* Endpoint descriptor for producer EP */
0x07, /* Descriptor size */
CY_U3P_USB_ENDPNT_DESCR, /* Endpoint descriptor type */
BLADE_FPGA_EP_PRODUCER, /* Endpoint address and description */
CY_U3P_USB_EP_BULK, /* Bulk endpoint type */
0x00,0x04, /* Max packet size = 1024 bytes */
0x00, /* Servicing interval for data transfers : 0 for bulk */
/* Super speed endpoint companion descriptor for producer EP */
0x06, /* Descriptor size */
CY_U3P_SS_EP_COMPN_DESCR, /* SS endpoint companion descriptor type */
0x01, /* Max no. of packets in a burst : 0: burst 1 packet at a time */
0x00, /* Max streams for bulk EP = 0 (No streams) */
0x00,0x00, /* Service interval for the EP : 0 for bulk */
/* Interface descriptor #0, alt interface #3, FPGA load */
0x09, /* Descriptor size */
CY_U3P_USB_INTRFC_DESCR, /* Interface Descriptor type */
0x00, /* Interface number */
0x03, /* Alternate setting number */
0x01, /* Number of end points */
0xFF, /* Interface class */
0x00, /* Interface sub class */
0x00, /* Interface protocol code */
0x00, /* Interface descriptor string index */
/* Endpoint descriptor for producer EP */
0x07, /* Descriptor size */
CY_U3P_USB_ENDPNT_DESCR, /* Endpoint descriptor type */
BLADE_FPGA_EP_PRODUCER, /* Endpoint address and description */
CY_U3P_USB_EP_BULK, /* Bulk endpoint type */
0x00,0x04, /* Max packet size = 1024 bytes */
0x00, /* Servicing interval for data transfers : 0 for bulk */
/* Super speed endpoint companion descriptor for producer EP */
0x06, /* Descriptor size */
CY_U3P_SS_EP_COMPN_DESCR, /* SS endpoint companion descriptor type */
0x01, /* Max no. of packets in a burst : 0: burst 1 packet at a time */
0x00, /* Max streams for bulk EP = 0 (No streams) */
0x00,0x00, /* Service interval for the EP : 0 for bulk */
};
/* Standard high speed configuration descriptor */
const uint8_t CyFxUSBHSConfigDscr[] __attribute__ ((aligned (32))) __attribute__ ((section(".usbdscr"))) =
{
/* Configuration descriptor */
0x09, /* Descriptor size */
CY_U3P_USB_CONFIG_DESCR, /* Configuration descriptor type */
0x57,0x00, /* Length of this descriptor and all sub descriptors */
0x01, /* Number of interfaces */
0x01, /* Configuration number */
0x00, /* COnfiguration string index */
0x80, /* Config characteristics - bus powered */
0x64, /* Max power consumption of device (in 2mA unit) : 200mA */
/* Interface descriptor #0, alt interface #0, Nothing */
0x09, /* Descriptor size */
CY_U3P_USB_INTRFC_DESCR, /* Interface Descriptor type */
0x00, /* Interface number */
0x00, /* Alternate setting number */
0x00, /* Number of endpoints */
0xFF, /* Interface class */
0x00, /* Interface sub class */
0x00, /* Interface protocol code */
0x00, /* Interface descriptor string index */
/* Interface descriptor #0, alt interface #1, RF */
0x09, /* Descriptor size */
CY_U3P_USB_INTRFC_DESCR, /* Interface Descriptor type */
0x00, /* Interface number */
0x01, /* Alternate setting number */
0x04, /* Number of endpoints */
0xFF, /* Interface class */
0x00, /* Interface sub class */
0x00, /* Interface protocol code */
0x00, /* Interface descriptor string index */
/* Endpoint descriptor for producer EP */
0x07, /* Descriptor size */
CY_U3P_USB_ENDPNT_DESCR, /* Endpoint descriptor type */
0x01, /* Endpoint address and description */
CY_U3P_USB_EP_BULK, /* Bulk endpoint type */
0x00,0x02, /* Max packet size = 512 bytes */
0x00, /* Servicing interval for data transfers : 0 for bulk */
/* Endpoint descriptor for producer EP */
0x07, /* Descriptor size */
CY_U3P_USB_ENDPNT_DESCR, /* Endpoint descriptor type */
0x81, /* Endpoint address and description */
CY_U3P_USB_EP_BULK, /* Bulk endpoint type */
0x00,0x02, /* Max packet size = 512 bytes */
0x00, /* Servicing interval for data transfers : 0 for bulk */
/* Endpoint descriptor for producer EP */
0x07, /* Descriptor size */
CY_U3P_USB_ENDPNT_DESCR, /* Endpoint descriptor type */
0x02, /* Endpoint address and description */
CY_U3P_USB_EP_BULK, /* Bulk endpoint type */
0x00,0x02, /* Max packet size = 512 bytes */
0x00, /* Servicing interval for data transfers : 0 for bulk */
/* Endpoint descriptor for producer EP */
0x07, /* Descriptor size */
CY_U3P_USB_ENDPNT_DESCR, /* Endpoint descriptor type */
0x82, /* Endpoint address and description */
CY_U3P_USB_EP_BULK, /* Bulk endpoint type */
0x00,0x02, /* Max packet size = 512 bytes */
0x00, /* Servicing interval for data transfers : 0 for bulk */
/* Interface descriptor #0, alt interface #2, FX3 firmware */
0x09, /* Descriptor size */
CY_U3P_USB_INTRFC_DESCR, /* Interface Descriptor type */
0x00, /* Interface number */
0x02, /* Alternate setting number */
0x01, /* Number of endpoints */
0xFF, /* Interface class */
0x00, /* Interface sub class */
0x00, /* Interface protocol code */
0x00, /* Interface descriptor string index */
/* Endpoint descriptor for producer EP */
0x07, /* Descriptor size */
CY_U3P_USB_ENDPNT_DESCR, /* Endpoint descriptor type */
0x01, /* Endpoint address and description */
CY_U3P_USB_EP_BULK, /* Bulk endpoint type */
0x00,0x02, /* Max packet size = 512 bytes */
0x00, /* Servicing interval for data transfers : 0 for bulk */
/* Interface descriptor #0, alt interface #3, FPGA load */
0x09, /* Descriptor size */
CY_U3P_USB_INTRFC_DESCR, /* Interface Descriptor type */
0x00, /* Interface number */
0x03, /* Alternate setting number */
0x01, /* Number of endpoints */
0xFF, /* Interface class */
0x00, /* Interface sub class */
0x00, /* Interface protocol code */
0x00, /* Interface descriptor string index */
/* Endpoint descriptor for producer EP */
0x07, /* Descriptor size */
CY_U3P_USB_ENDPNT_DESCR, /* Endpoint descriptor type */
BLADE_FPGA_EP_PRODUCER, /* Endpoint address and description */
CY_U3P_USB_EP_BULK, /* Bulk endpoint type */
0x00,0x02, /* Max packet size = 512 bytes */
0x00, /* Servicing interval for data transfers : 0 for bulk */
};
/* Standard full speed configuration descriptor */
const uint8_t CyFxUSBFSConfigDscr[] __attribute__ ((aligned (32))) __attribute__ ((section(".usbdscr"))) =
{
/* Configuration descriptor */
0x09, /* Descriptor size */
CY_U3P_USB_CONFIG_DESCR, /* Configuration descriptor type */
0x27,0x00, /* Length of this descriptor and all sub descriptors */
0x01, /* Number of interfaces */
0x01, /* Configuration number */
0x00, /* COnfiguration string index */
0x80, /* Config characteristics - bus powered */
0x32, /* Max power consumption of device (in 2mA unit) : 100mA */
/* Interface descriptor */
0x09, /* Descriptor size */
CY_U3P_USB_INTRFC_DESCR, /* Interface descriptor type */
0x00, /* Interface number */
0x00, /* Alternate setting number */
0x03, /* Number of endpoints */
0xFF, /* Interface class */
0x00, /* Interface sub class */
0x00, /* Interface protocol code */
0x00, /* Interface descriptor string index */
/* Endpoint descriptor for producer EP */
0x07, /* Descriptor size */
CY_U3P_USB_ENDPNT_DESCR, /* Endpoint descriptor type */
CY_FX_EP_PRODUCER, /* Endpoint address and description */
CY_U3P_USB_EP_BULK, /* Bulk endpoint type */
0x40,0x00, /* Max packet size = 64 bytes */
0x00, /* Servicing interval for data transfers : 0 for bulk */
/* Endpoint descriptor for producer EP */
0x07, /* Descriptor size */
CY_U3P_USB_ENDPNT_DESCR, /* Endpoint descriptor type */
BLADE_FPGA_EP_PRODUCER, /* Endpoint address and description */
CY_U3P_USB_EP_BULK, /* Bulk endpoint type */
0x40,0x00, /* Max packet size = 64 bytes */
0x00, /* Servicing interval for data transfers : 0 for bulk */
/* Endpoint descriptor for consumer EP */
0x07, /* Descriptor size */
CY_U3P_USB_ENDPNT_DESCR, /* Endpoint descriptor type */
CY_FX_EP_CONSUMER, /* Endpoint address and description */
CY_U3P_USB_EP_BULK, /* Bulk endpoint type */
0x40,0x00, /* Max packet size = 64 bytes */
0x00 /* Servicing interval for data transfers : 0 for bulk */
};
/* Standard language ID string descriptor */
const uint8_t CyFxUSBStringLangIDDscr[] __attribute__ ((aligned (32))) __attribute__ ((section(".usbdscr"))) =
{
0x04, /* Descriptor size */
CY_U3P_USB_STRING_DESCR, /* Device descriptor type */
0x09,0x04 /* Language ID supported */
};
/* Standard manufacturer string descriptor */
const uint8_t CyFxUSBManufactureDscr[] __attribute__ ((aligned (32))) __attribute__ ((section(".usbdscr"))) =
{
0x0C, /* Descriptor size */
CY_U3P_USB_STRING_DESCR, /* Device descriptor type */
'N',0x00,
'u',0x00,
'a',0x00,
'n',0x00,
'd',0x00,
};
/* [ ] */
| 55.861809 | 110 | 0.508478 | [
"object"
] |
6554a75273218dfb38b558c2f50774e98aee5586 | 366 | h | C | src/commlib/zcelib/zce_os_adapt_backtrace.h | sailzeng/zcelib | 88e14ab436f1b40e8071e15ef6d9fae396efc3b4 | [
"Apache-2.0"
] | 72 | 2015-01-08T05:01:48.000Z | 2021-12-28T06:13:03.000Z | src/commlib/zcelib/zce_os_adapt_backtrace.h | sailzeng/zcelib | 88e14ab436f1b40e8071e15ef6d9fae396efc3b4 | [
"Apache-2.0"
] | 4 | 2016-01-18T12:24:59.000Z | 2019-10-12T07:19:15.000Z | src/commlib/zcelib/zce_os_adapt_backtrace.h | sailzeng/zcelib | 88e14ab436f1b40e8071e15ef6d9fae396efc3b4 | [
"Apache-2.0"
] | 40 | 2015-01-26T06:49:18.000Z | 2021-07-20T08:11:48.000Z | #ifndef ZCE_LIB_OS_ADAPT_BACKTRACE_H_
#define ZCE_LIB_OS_ADAPT_BACKTRACE_H_
namespace zce
{
/*!
* @brief
* @return int ==0 表示执行成功
* @param str_ary
* @note
*/
int backtrace_stack(std::vector<std::string> &str_ary);
int backtrace_stack(FILE *stream);
int backtrace_stack(ZCE_LOG_PRIORITY dbg_lvl,
const char *dbg_info);
};
#endif // | 16.636364 | 55 | 0.691257 | [
"vector"
] |
6559a3ed0976ff30d201ad565337781d10937832 | 1,904 | c | C | trunk/freertos/app/mesh/model/generics/generic_default_transition_time/generic_default_transition_time.c | HESUPING/JmeshBLE-StaticLib | cf0900f004026c7e2e3448ffde07e21d4af8e387 | [
"Apache-2.0"
] | null | null | null | trunk/freertos/app/mesh/model/generics/generic_default_transition_time/generic_default_transition_time.c | HESUPING/JmeshBLE-StaticLib | cf0900f004026c7e2e3448ffde07e21d4af8e387 | [
"Apache-2.0"
] | null | null | null | trunk/freertos/app/mesh/model/generics/generic_default_transition_time/generic_default_transition_time.c | HESUPING/JmeshBLE-StaticLib | cf0900f004026c7e2e3448ffde07e21d4af8e387 | [
"Apache-2.0"
] | 3 | 2019-08-27T17:11:42.000Z | 2021-02-04T06:38:35.000Z | #include "osapp_config.h"
#ifdef OSAPP_MESH
#include "generic_default_transition_time.h"
#include "access.h"
#include "sig_msg.h"
void generic_default_transition_time_status_tx(ger_default_trans_time_server_t *server,access_message_tx_t *p_tx,uint16_t dst_addr)
{
access_model_reply(server->model.base.elmt,&server->model.base,p_tx,dst_addr);
}
void generic_default_transition_time_get_rx(mesh_elmt_t *elmt,model_base_t *model,access_pdu_rx_t *pdu)
{
access_message_tx_t access_message_tx;
ger_default_trans_time_server_t *server = GET_SERVER_MODEL_PTR(ger_default_trans_time_server_t,model);
access_message_tx.p_buffer = (uint8_t *)&(server->trans_time);
access_message_tx.opcode = TWO_OCTETS_OPCODE_GEN(Generic_Default_Transition_Time_Status,GENERIC_DEFAULT_TRANSITION_TIME_OPCODE_OFFSET);
generic_default_transition_time_status_tx(server,&access_message_tx,pdu->base.dst_addr);
}
void generic_default_transition_time_set_rx(mesh_elmt_t *elmt,model_base_t *model,access_pdu_rx_t *pdu)
{
access_message_tx_t access_message_tx;
ger_default_trans_time_server_t *server = GET_SERVER_MODEL_PTR(ger_default_trans_time_server_t,model);
server->trans_time = *(uint16_t *)pdu->access;
access_message_tx.p_buffer = (uint8_t *)&server->trans_time;
access_message_tx.opcode = TWO_OCTETS_OPCODE_GEN(Generic_Default_Transition_Time_Status,GENERIC_DEFAULT_TRANSITION_TIME_OPCODE_OFFSET);
generic_default_transition_time_status_tx(server,&access_message_tx,pdu->base.dst_addr);
}
void generic_default_transition_time_unacknowledge_set_rx(mesh_elmt_t *elmt,model_base_t *model,access_pdu_rx_t *pdu)
{
ger_default_trans_time_server_t *server = GET_SERVER_MODEL_PTR(ger_default_trans_time_server_t,model);
server->trans_time = *(uint8_t *)pdu->access;
}
uint8_t user_generic_default_transition_time_get(ger_default_trans_time_server_t *server)
{
return server->trans_time;
}
#endif
| 34 | 137 | 0.847164 | [
"model"
] |
6559fe634d97f6fef2c106fce0dc77606fa245cf | 7,652 | h | C | src/frontend/Partitioner2/FunctionCallGraph.h | mschordan/rose-develop | b4a6d1b7f8762d94d9ee49777e2f0bf146475a10 | [
"BSD-3-Clause"
] | 1 | 2021-02-05T21:59:32.000Z | 2021-02-05T21:59:32.000Z | src/frontend/Partitioner2/FunctionCallGraph.h | mschordan/rose-develop | b4a6d1b7f8762d94d9ee49777e2f0bf146475a10 | [
"BSD-3-Clause"
] | null | null | null | src/frontend/Partitioner2/FunctionCallGraph.h | mschordan/rose-develop | b4a6d1b7f8762d94d9ee49777e2f0bf146475a10 | [
"BSD-3-Clause"
] | null | null | null | #ifndef ROSE_Partitioner2_FunctionCallGraph_H
#define ROSE_Partitioner2_FunctionCallGraph_H
#include <Partitioner2/BasicTypes.h>
#include <Sawyer/Graph.h>
namespace Rose {
namespace BinaryAnalysis {
namespace Partitioner2 {
/** Function call information.
*
* This class provides methods that operate on a function call graph, such as constructing a function call graph from a
* control flow graph. The graph vertices are function pointers (Function::Ptr) and the edges contain information about the
* type of inter-function edge (function call, function transfer, etc) and the number of such edges. Function call graphs can
* be built so that inter-function control transfer is represented by its own edge, or so that multiple transfers share an
* edge. */
class FunctionCallGraph {
public:
/** Information about each edge in the call graph. */
class Edge {
friend class FunctionCallGraph;
EdgeType type_;
size_t count_;
public:
explicit Edge(EdgeType type): type_(type), count_(1) {}
/** Type of edge. Edge types @ref E_FUNCTION_CALL and @ref E_FUNCTION_XFER are supported. */
EdgeType type() const { return type_; }
/** Number of inter-function control flow edges represented by this edge. */
size_t count() const { return count_; }
};
/** Function call graph. */
typedef Sawyer::Container::Graph<FunctionPtr, Edge> Graph;
/** Maps function address to function call graph vertex. */
typedef Sawyer::Container::Map<rose_addr_t, Graph::VertexIterator> Index;
private:
Graph graph_;
Index index_;
public:
/** Underlying function call graph.
*
* This returns the Sawyer::Container::Graph representing inter-function edges. It is read-only since modifying the graph
* must be done in conjunction with updating the function-to-vertex index. */
const Graph& graph() const { return graph_; }
/** Function-to-vertex index.
*
* Returns the index mapping function addresses to function call graph vertices. The index is read-only since updating the
* index must be done in conjunction with updating the graph. */
const Index& index() const { return index_; }
/** Constructs an empty function call graph. */
FunctionCallGraph();
/** Copy constructor. */
FunctionCallGraph(const FunctionCallGraph &other);
/** Assignment operator. */
FunctionCallGraph& operator=(const FunctionCallGraph &other);
~FunctionCallGraph();
/** Return all functions in the call graph. */
boost::iterator_range<Graph::ConstVertexValueIterator> functions() {
return graph_.vertexValues();
}
/** Find function in call graph.
*
* Returns the call graph vertex (as an iterator) for the specified function, or the end vertex iterator if the function
* does not exist in the call graph. The function can be specified by its pointer or entry address.
*
* @{ */
Graph::ConstVertexIterator findFunction(const FunctionPtr &function) const;
Graph::ConstVertexIterator findFunction(rose_addr_t entryVa) const;
/** @} */
/** Determine if a function exists in the call graph.
*
* Returns true if the function is a member of the call graph and false otherwise. A function can be a member of a call
* graph even if it has no incident edges.
*
* @{ */
bool exists(const FunctionPtr &function) const;
bool exists(rose_addr_t entryVa) const;
/** @} */
/** Insert a function vertex.
*
* Inserts the specified function into the call graph if it is not a member of the call graph, otherwise does nothing. In
* any case, it returns the vertex for the function. */
Graph::VertexIterator insertFunction(const FunctionPtr &function);
/** Insert a call edge.
*
* Inserts an edge representing a call from source (caller) to target (callee). The @p type can be @ref E_FUNCTION_CALL or
* @ref E_FUNCTION_XFER.
*
* If @p edgeCount is non-zero an an edge of the correct type already exists between the @p source and @p target, then the
* count on that edge is incremented instead. Otherwise, when @p edgeCount is zero, a new edge with unit count is inserted
* even if it means creating an edge parallel to an existing edge.
*
* Returns the edge that was inserted or incremented.
*
* @{ */
Graph::EdgeIterator insertCall(const FunctionPtr &source, const FunctionPtr &target,
EdgeType type = E_FUNCTION_CALL, size_t edgeCount = 0);
Graph::EdgeIterator insertCall(const Graph::VertexIterator &source, const Graph::VertexIterator &target,
EdgeType type = E_FUNCTION_CALL, size_t edgeCount = 0);
/** @} */
/** List of all functions that call the specified function.
*
* Returns a sorted list of distinct functions that call the specified function.
*
* @{ */
std::vector<FunctionPtr> callers(const FunctionPtr &target) const;
std::vector<FunctionPtr> callers(const Graph::ConstVertexIterator &target) const;
/** @} */
/** Number of functions that call the specified function.
*
* This is the number of distinct functions that call the specified @p target function.
*
* @{ */
size_t nCallers(const FunctionPtr &target) const;
size_t nCallers(const Graph::ConstVertexIterator &target) const;
/** @} */
/** List of all functions called by the specified function.
*
* Returns a sorted list of distinct functions that call the function specified by entry address or call graph vertex. If
* the specified function does not exist in the call graph then an empty list is returned.
*
* @{ */
std::vector<FunctionPtr> callees(const FunctionPtr &source) const;
std::vector<FunctionPtr> callees(const Graph::ConstVertexIterator &source) const;
/** @} */
/** Number of functions that the specified function calls.
*
* This is the number of distinct functions called from the specified @p source function.
*
* @{ */
size_t nCallees(const FunctionPtr &source) const;
size_t nCallees(const Graph::ConstVertexIterator &source) const;
/** @} */
/** Total number of calls to a function.
*
* Returns the total number of calls to the specified function, counting each call when a single function calls more than
* once. I.e., it is the sum of the @c count fields of all the incoming edges for @p target.
*
* @{ */
size_t nCallsIn(const FunctionPtr &target) const;
size_t nCallsIn(const Graph::ConstVertexIterator &target) const;
/** @} */
/** Total number of calls from a function.
*
* Returns the total number of calls from the specified function, counting each call when a single function is called more
* than once. I.e., it is the sum of the @c count fields of all the outgoing edges for @p source.
*
* @{ */
size_t nCallsOut(const FunctionPtr &source) const;
size_t nCallsOut(const Graph::ConstVertexIterator &source) const;
/** @} */
/** Number of calls between two specific functions.
*
* This is the sum of the @c count fields for all edges between @p source and @p target.
*
* @{ */
size_t nCalls(const FunctionPtr &source, const FunctionPtr &target) const;
size_t nCalls(const Graph::ConstVertexIterator &source, const Graph::ConstVertexIterator &target) const;
/** @} */
};
} // namespace
} // namespace
} // namespace
#endif
| 40.486772 | 127 | 0.675379 | [
"vector"
] |
655dbc17bc36c05ca8426faa20288f60769907ab | 1,619 | h | C | src/PieMenu.h | markusfisch/PieDock | 070ec545659bca9ddf1e46b0c218ea8d933174ff | [
"MIT"
] | 10 | 2015-01-16T02:29:08.000Z | 2022-02-01T20:34:59.000Z | src/PieMenu.h | markusfisch/PieDock | 070ec545659bca9ddf1e46b0c218ea8d933174ff | [
"MIT"
] | 10 | 2015-01-10T12:58:51.000Z | 2021-11-12T00:02:11.000Z | src/PieMenu.h | markusfisch/PieDock | 070ec545659bca9ddf1e46b0c218ea8d933174ff | [
"MIT"
] | 7 | 2016-02-16T23:12:46.000Z | 2020-09-21T21:33:52.000Z | #ifndef _PieDock_PieMenu_
#define _PieDock_PieMenu_
#include "Application.h"
#include "Surface.h"
#include "Blender.h"
#include "Icon.h"
#include "Menu.h"
#include <vector>
#include <math.h>
namespace PieDock {
class PieMenu : public Menu {
public:
PieMenu(Application *, Surface &);
virtual ~PieMenu() {}
inline const bool cursorInCenter() const {
return (getSelected() == 0);
}
inline const int &getRadius() const {
return maxRadius;
}
inline Blender *getBlender() {
return &blender;
}
inline void invalidate() {
lastX = lastY = -1;
}
virtual bool update(std::string = "", Window = 0);
virtual bool isObsolete(int, int);
virtual void draw(int, int);
virtual void turn(double);
virtual void turn(int);
virtual void setTwistForSelection();
protected:
/**
* Return the smallest difference of two angles in radians; implemented
* here to ensure the method will be compiled inline
*
* @param a - angle in radians
* @param b - angle in radians
*/
inline virtual double getAngleDifference(double a, double b) {
double d = fmod((a - b) + tau, tau);
if (d > M_PI) {
d -= tau;
}
return d;
}
/**
* Make sure angle is between 0 and TAU; implemented here to ensure
* the method will be compiled inline
*
* @param a - angle in radians
*/
inline virtual double getValidAngle(double a) {
return fmod(a + tau, tau);
}
private:
static const double tau;
static const double turnSteps[];
Blender blender;
int size;
int maxRadius;
int radius;
double twist;
int centerX;
int centerY;
int lastX;
int lastY;
double *turnStack;
double *turnBy;
};
}
#endif
| 19.743902 | 72 | 0.683755 | [
"vector"
] |
655e17f91240809ae5e734367ff87f406375373f | 886 | h | C | src/shared/Matrix.h | RainerBlessing/TheRayTracerChallenge-C- | 22c990201507f46d5bb1604bc1f6ee88e59cef95 | [
"MIT"
] | null | null | null | src/shared/Matrix.h | RainerBlessing/TheRayTracerChallenge-C- | 22c990201507f46d5bb1604bc1f6ee88e59cef95 | [
"MIT"
] | null | null | null | src/shared/Matrix.h | RainerBlessing/TheRayTracerChallenge-C- | 22c990201507f46d5bb1604bc1f6ee88e59cef95 | [
"MIT"
] | null | null | null | //
// Created by rainer on 24.11.19.
//
#ifndef RAY_TRACER_CHALLENGE_MATRIX_H
#define RAY_TRACER_CHALLENGE_MATRIX_H
#include <vector>
#include "Tuple.h"
#include "Point.h"
#include <iostream>
class Matrix {
public:
Matrix();
Matrix(int n, int i);
Tuple& operator [] (int i){return m[i];}
Tuple operator [] (int i) const {return m[i];}
bool operator == (Matrix n) const;
std::vector<Tuple> m;
bool equals(Matrix n) const;
int size() const;
Matrix multiply(Matrix matrix);
Tuple multiply(Tuple tuple);
Point multiply(Point point);
Matrix transpose();
static Matrix getIdentity();
double determinant();
Matrix submatrix(int row, int column);
double minor_(int row, int column);
double cofactor(int row, int column);
bool invertible();
Matrix inverse();
};
#endif //RAY_TRACER_CHALLENGE_MATRIX_H
| 17.372549 | 50 | 0.6614 | [
"vector"
] |
6561715069e43c6f442d57b17b8feaa4684d21cb | 999 | h | C | src/proxy.h | lgeiger/zeromq-ng | b9f60496e155be6ad738e7a42e66973a21ea02f5 | [
"MIT"
] | null | null | null | src/proxy.h | lgeiger/zeromq-ng | b9f60496e155be6ad738e7a42e66973a21ea02f5 | [
"MIT"
] | null | null | null | src/proxy.h | lgeiger/zeromq-ng | b9f60496e155be6ad738e7a42e66973a21ea02f5 | [
"MIT"
] | null | null | null | /* Copyright (c) 2017-2018 Rolf Timmermans */
#pragma once
#include "binding.h"
#ifdef ZMQ_HAS_STEERABLE_PROXY
namespace zmq {
class Proxy : public Napi::ObjectWrap<Proxy> {
public:
static Napi::FunctionReference Constructor;
static void Initialize(Napi::Env& env, Napi::Object& exports);
explicit Proxy(const Napi::CallbackInfo& info);
~Proxy();
protected:
inline Napi::Value Run(const Napi::CallbackInfo& info);
inline void Pause(const Napi::CallbackInfo& info);
inline void Resume(const Napi::CallbackInfo& info);
inline void Terminate(const Napi::CallbackInfo& info);
inline Napi::Value GetFrontEnd(const Napi::CallbackInfo& info);
inline Napi::Value GetBackEnd(const Napi::CallbackInfo& info);
private:
inline void SendCommand(const char* command);
Napi::ObjectReference front_ref;
Napi::ObjectReference back_ref;
Napi::ObjectReference capture_ref;
void* control_sub = nullptr;
void* control_pub = nullptr;
};
}
#endif
| 24.975 | 67 | 0.722723 | [
"object"
] |
6563b14629206edea1c36008c08c85f922579fa0 | 29,065 | c | C | src/trigger.c | qiuping/sqlcipher | 91ab560aec719a1b2295257b017c4749035629d8 | [
"FSFAP"
] | 1 | 2016-05-09T09:36:12.000Z | 2016-05-09T09:36:12.000Z | src/trigger.c | qiuping/sqlcipher | 91ab560aec719a1b2295257b017c4749035629d8 | [
"FSFAP"
] | null | null | null | src/trigger.c | qiuping/sqlcipher | 91ab560aec719a1b2295257b017c4749035629d8 | [
"FSFAP"
] | null | null | null | /*
**
** The author disclaims copyright to this source code. In place of
** a legal notice, here is a blessing:
**
** May you do good and not evil.
** May you find forgiveness for yourself and forgive others.
** May you share freely, never taking more than you give.
**
*************************************************************************
**
**
** $Id: trigger.c,v 1.133 2008/12/26 07:56:39 danielk1977 Exp $
*/
#include "sqliteInt.h"
#ifndef SQLITE_OMIT_TRIGGER
/*
** Delete a linked list of TriggerStep structures.
*/
void sqlite3DeleteTriggerStep(sqlite3 *db, TriggerStep *pTriggerStep){
while( pTriggerStep ){
TriggerStep * pTmp = pTriggerStep;
pTriggerStep = pTriggerStep->pNext;
if( pTmp->target.dyn ) sqlite3DbFree(db, (char*)pTmp->target.z);
sqlite3ExprDelete(db, pTmp->pWhere);
sqlite3ExprListDelete(db, pTmp->pExprList);
sqlite3SelectDelete(db, pTmp->pSelect);
sqlite3IdListDelete(db, pTmp->pIdList);
sqlite3DbFree(db, pTmp);
}
}
/*
** This is called by the parser when it sees a CREATE TRIGGER statement
** up to the point of the BEGIN before the trigger actions. A Trigger
** structure is generated based on the information available and stored
** in pParse->pNewTrigger. After the trigger actions have been parsed, the
** sqlite3FinishTrigger() function is called to complete the trigger
** construction process.
*/
void sqlite3BeginTrigger(
Parse *pParse, /* The parse context of the CREATE TRIGGER statement */
Token *pName1, /* The name of the trigger */
Token *pName2, /* The name of the trigger */
int tr_tm, /* One of TK_BEFORE, TK_AFTER, TK_INSTEAD */
int op, /* One of TK_INSERT, TK_UPDATE, TK_DELETE */
IdList *pColumns, /* column list if this is an UPDATE OF trigger */
SrcList *pTableName,/* The name of the table/view the trigger applies to */
Expr *pWhen, /* WHEN clause */
int isTemp, /* True if the TEMPORARY keyword is present */
int noErr /* Suppress errors if the trigger already exists */
){
Trigger *pTrigger = 0;
Table *pTab;
char *zName = 0; /* Name of the trigger */
sqlite3 *db = pParse->db;
int iDb; /* The database to store the trigger in */
Token *pName; /* The unqualified db name */
DbFixer sFix;
int iTabDb;
assert( pName1!=0 ); /* pName1->z might be NULL, but not pName1 itself */
assert( pName2!=0 );
assert( op==TK_INSERT || op==TK_UPDATE || op==TK_DELETE );
assert( op>0 && op<0xff );
if( isTemp ){
/* If TEMP was specified, then the trigger name may not be qualified. */
if( pName2->n>0 ){
sqlite3ErrorMsg(pParse, "temporary trigger may not have qualified name");
goto trigger_cleanup;
}
iDb = 1;
pName = pName1;
}else{
/* Figure out the db that the the trigger will be created in */
iDb = sqlite3TwoPartName(pParse, pName1, pName2, &pName);
if( iDb<0 ){
goto trigger_cleanup;
}
}
/* If the trigger name was unqualified, and the table is a temp table,
** then set iDb to 1 to create the trigger in the temporary database.
** If sqlite3SrcListLookup() returns 0, indicating the table does not
** exist, the error is caught by the block below.
*/
if( !pTableName || db->mallocFailed ){
goto trigger_cleanup;
}
pTab = sqlite3SrcListLookup(pParse, pTableName);
if( pName2->n==0 && pTab && pTab->pSchema==db->aDb[1].pSchema ){
iDb = 1;
}
/* Ensure the table name matches database name and that the table exists */
if( db->mallocFailed ) goto trigger_cleanup;
assert( pTableName->nSrc==1 );
if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", pName) &&
sqlite3FixSrcList(&sFix, pTableName) ){
goto trigger_cleanup;
}
pTab = sqlite3SrcListLookup(pParse, pTableName);
if( !pTab ){
/* The table does not exist. */
goto trigger_cleanup;
}
if( IsVirtual(pTab) ){
sqlite3ErrorMsg(pParse, "cannot create triggers on virtual tables");
goto trigger_cleanup;
}
/* Check that the trigger name is not reserved and that no trigger of the
** specified name exists */
zName = sqlite3NameFromToken(db, pName);
if( !zName || SQLITE_OK!=sqlite3CheckObjectName(pParse, zName) ){
goto trigger_cleanup;
}
if( sqlite3HashFind(&(db->aDb[iDb].pSchema->trigHash),
zName, sqlite3Strlen30(zName)) ){
if( !noErr ){
sqlite3ErrorMsg(pParse, "trigger %T already exists", pName);
}
goto trigger_cleanup;
}
/* Do not create a trigger on a system table */
if( sqlite3StrNICmp(pTab->zName, "sqlite_", 7)==0 ){
sqlite3ErrorMsg(pParse, "cannot create trigger on system table");
pParse->nErr++;
goto trigger_cleanup;
}
/* INSTEAD of triggers are only for views and views only support INSTEAD
** of triggers.
*/
if( pTab->pSelect && tr_tm!=TK_INSTEAD ){
sqlite3ErrorMsg(pParse, "cannot create %s trigger on view: %S",
(tr_tm == TK_BEFORE)?"BEFORE":"AFTER", pTableName, 0);
goto trigger_cleanup;
}
if( !pTab->pSelect && tr_tm==TK_INSTEAD ){
sqlite3ErrorMsg(pParse, "cannot create INSTEAD OF"
" trigger on table: %S", pTableName, 0);
goto trigger_cleanup;
}
iTabDb = sqlite3SchemaToIndex(db, pTab->pSchema);
#ifndef SQLITE_OMIT_AUTHORIZATION
{
int code = SQLITE_CREATE_TRIGGER;
const char *zDb = db->aDb[iTabDb].zName;
const char *zDbTrig = isTemp ? db->aDb[1].zName : zDb;
if( iTabDb==1 || isTemp ) code = SQLITE_CREATE_TEMP_TRIGGER;
if( sqlite3AuthCheck(pParse, code, zName, pTab->zName, zDbTrig) ){
goto trigger_cleanup;
}
if( sqlite3AuthCheck(pParse, SQLITE_INSERT, SCHEMA_TABLE(iTabDb),0,zDb)){
goto trigger_cleanup;
}
}
#endif
/* INSTEAD OF triggers can only appear on views and BEFORE triggers
** cannot appear on views. So we might as well translate every
** INSTEAD OF trigger into a BEFORE trigger. It simplifies code
** elsewhere.
*/
if (tr_tm == TK_INSTEAD){
tr_tm = TK_BEFORE;
}
/* Build the Trigger object */
pTrigger = (Trigger*)sqlite3DbMallocZero(db, sizeof(Trigger));
if( pTrigger==0 ) goto trigger_cleanup;
pTrigger->name = zName;
zName = 0;
pTrigger->table = sqlite3DbStrDup(db, pTableName->a[0].zName);
pTrigger->pSchema = db->aDb[iDb].pSchema;
pTrigger->pTabSchema = pTab->pSchema;
pTrigger->op = (u8)op;
pTrigger->tr_tm = tr_tm==TK_BEFORE ? TRIGGER_BEFORE : TRIGGER_AFTER;
pTrigger->pWhen = sqlite3ExprDup(db, pWhen);
pTrigger->pColumns = sqlite3IdListDup(db, pColumns);
sqlite3TokenCopy(db, &pTrigger->nameToken,pName);
assert( pParse->pNewTrigger==0 );
pParse->pNewTrigger = pTrigger;
trigger_cleanup:
sqlite3DbFree(db, zName);
sqlite3SrcListDelete(db, pTableName);
sqlite3IdListDelete(db, pColumns);
sqlite3ExprDelete(db, pWhen);
if( !pParse->pNewTrigger ){
sqlite3DeleteTrigger(db, pTrigger);
}else{
assert( pParse->pNewTrigger==pTrigger );
}
}
/*
** This routine is called after all of the trigger actions have been parsed
** in order to complete the process of building the trigger.
*/
void sqlite3FinishTrigger(
Parse *pParse, /* Parser context */
TriggerStep *pStepList, /* The triggered program */
Token *pAll /* Token that describes the complete CREATE TRIGGER */
){
Trigger *pTrig = 0; /* The trigger whose construction is finishing up */
sqlite3 *db = pParse->db; /* The database */
DbFixer sFix;
int iDb; /* Database containing the trigger */
pTrig = pParse->pNewTrigger;
pParse->pNewTrigger = 0;
if( pParse->nErr || !pTrig ) goto triggerfinish_cleanup;
iDb = sqlite3SchemaToIndex(pParse->db, pTrig->pSchema);
pTrig->step_list = pStepList;
while( pStepList ){
pStepList->pTrig = pTrig;
pStepList = pStepList->pNext;
}
if( sqlite3FixInit(&sFix, pParse, iDb, "trigger", &pTrig->nameToken)
&& sqlite3FixTriggerStep(&sFix, pTrig->step_list) ){
goto triggerfinish_cleanup;
}
/* if we are not initializing, and this trigger is not on a TEMP table,
** build the sqlite_master entry
*/
if( !db->init.busy ){
Vdbe *v;
char *z;
/* Make an entry in the sqlite_master table */
v = sqlite3GetVdbe(pParse);
if( v==0 ) goto triggerfinish_cleanup;
sqlite3BeginWriteOperation(pParse, 0, iDb);
z = sqlite3DbStrNDup(db, (char*)pAll->z, pAll->n);
sqlite3NestedParse(pParse,
"INSERT INTO %Q.%s VALUES('trigger',%Q,%Q,0,'CREATE TRIGGER %q')",
db->aDb[iDb].zName, SCHEMA_TABLE(iDb), pTrig->name,
pTrig->table, z);
sqlite3DbFree(db, z);
sqlite3ChangeCookie(pParse, iDb);
sqlite3VdbeAddOp4(v, OP_ParseSchema, iDb, 0, 0, sqlite3MPrintf(
db, "type='trigger' AND name='%q'", pTrig->name), P4_DYNAMIC
);
}
if( db->init.busy ){
int n;
Table *pTab;
Trigger *pDel;
pDel = sqlite3HashInsert(&db->aDb[iDb].pSchema->trigHash,
pTrig->name, sqlite3Strlen30(pTrig->name), pTrig);
if( pDel ){
assert( pDel==pTrig );
db->mallocFailed = 1;
goto triggerfinish_cleanup;
}
n = sqlite3Strlen30(pTrig->table) + 1;
pTab = sqlite3HashFind(&pTrig->pTabSchema->tblHash, pTrig->table, n);
assert( pTab!=0 );
pTrig->pNext = pTab->pTrigger;
pTab->pTrigger = pTrig;
pTrig = 0;
}
triggerfinish_cleanup:
sqlite3DeleteTrigger(db, pTrig);
assert( !pParse->pNewTrigger );
sqlite3DeleteTriggerStep(db, pStepList);
}
/*
** Make a copy of all components of the given trigger step. This has
** the effect of copying all Expr.token.z values into memory obtained
** from sqlite3_malloc(). As initially created, the Expr.token.z values
** all point to the input string that was fed to the parser. But that
** string is ephemeral - it will go away as soon as the sqlite3_exec()
** call that started the parser exits. This routine makes a persistent
** copy of all the Expr.token.z strings so that the TriggerStep structure
** will be valid even after the sqlite3_exec() call returns.
*/
static void sqlitePersistTriggerStep(sqlite3 *db, TriggerStep *p){
if( p->target.z ){
p->target.z = (u8*)sqlite3DbStrNDup(db, (char*)p->target.z, p->target.n);
p->target.dyn = 1;
}
if( p->pSelect ){
Select *pNew = sqlite3SelectDup(db, p->pSelect);
sqlite3SelectDelete(db, p->pSelect);
p->pSelect = pNew;
}
if( p->pWhere ){
Expr *pNew = sqlite3ExprDup(db, p->pWhere);
sqlite3ExprDelete(db, p->pWhere);
p->pWhere = pNew;
}
if( p->pExprList ){
ExprList *pNew = sqlite3ExprListDup(db, p->pExprList);
sqlite3ExprListDelete(db, p->pExprList);
p->pExprList = pNew;
}
if( p->pIdList ){
IdList *pNew = sqlite3IdListDup(db, p->pIdList);
sqlite3IdListDelete(db, p->pIdList);
p->pIdList = pNew;
}
}
/*
** Turn a SELECT statement (that the pSelect parameter points to) into
** a trigger step. Return a pointer to a TriggerStep structure.
**
** The parser calls this routine when it finds a SELECT statement in
** body of a TRIGGER.
*/
TriggerStep *sqlite3TriggerSelectStep(sqlite3 *db, Select *pSelect){
TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
if( pTriggerStep==0 ) {
sqlite3SelectDelete(db, pSelect);
return 0;
}
pTriggerStep->op = TK_SELECT;
pTriggerStep->pSelect = pSelect;
pTriggerStep->orconf = OE_Default;
sqlitePersistTriggerStep(db, pTriggerStep);
return pTriggerStep;
}
/*
** Build a trigger step out of an INSERT statement. Return a pointer
** to the new trigger step.
**
** The parser calls this routine when it sees an INSERT inside the
** body of a trigger.
*/
TriggerStep *sqlite3TriggerInsertStep(
sqlite3 *db, /* The database connection */
Token *pTableName, /* Name of the table into which we insert */
IdList *pColumn, /* List of columns in pTableName to insert into */
ExprList *pEList, /* The VALUE clause: a list of values to be inserted */
Select *pSelect, /* A SELECT statement that supplies values */
int orconf /* The conflict algorithm (OE_Abort, OE_Replace, etc.) */
){
TriggerStep *pTriggerStep;
assert(pEList == 0 || pSelect == 0);
assert(pEList != 0 || pSelect != 0 || db->mallocFailed);
pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
if( pTriggerStep ){
pTriggerStep->op = TK_INSERT;
pTriggerStep->pSelect = pSelect;
pTriggerStep->target = *pTableName;
pTriggerStep->pIdList = pColumn;
pTriggerStep->pExprList = pEList;
pTriggerStep->orconf = orconf;
sqlitePersistTriggerStep(db, pTriggerStep);
}else{
sqlite3IdListDelete(db, pColumn);
sqlite3ExprListDelete(db, pEList);
sqlite3SelectDelete(db, pSelect);
}
return pTriggerStep;
}
/*
** Construct a trigger step that implements an UPDATE statement and return
** a pointer to that trigger step. The parser calls this routine when it
** sees an UPDATE statement inside the body of a CREATE TRIGGER.
*/
TriggerStep *sqlite3TriggerUpdateStep(
sqlite3 *db, /* The database connection */
Token *pTableName, /* Name of the table to be updated */
ExprList *pEList, /* The SET clause: list of column and new values */
Expr *pWhere, /* The WHERE clause */
int orconf /* The conflict algorithm. (OE_Abort, OE_Ignore, etc) */
){
TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
if( pTriggerStep==0 ){
sqlite3ExprListDelete(db, pEList);
sqlite3ExprDelete(db, pWhere);
return 0;
}
pTriggerStep->op = TK_UPDATE;
pTriggerStep->target = *pTableName;
pTriggerStep->pExprList = pEList;
pTriggerStep->pWhere = pWhere;
pTriggerStep->orconf = orconf;
sqlitePersistTriggerStep(db, pTriggerStep);
return pTriggerStep;
}
/*
** Construct a trigger step that implements a DELETE statement and return
** a pointer to that trigger step. The parser calls this routine when it
** sees a DELETE statement inside the body of a CREATE TRIGGER.
*/
TriggerStep *sqlite3TriggerDeleteStep(
sqlite3 *db, /* Database connection */
Token *pTableName, /* The table from which rows are deleted */
Expr *pWhere /* The WHERE clause */
){
TriggerStep *pTriggerStep = sqlite3DbMallocZero(db, sizeof(TriggerStep));
if( pTriggerStep==0 ){
sqlite3ExprDelete(db, pWhere);
return 0;
}
pTriggerStep->op = TK_DELETE;
pTriggerStep->target = *pTableName;
pTriggerStep->pWhere = pWhere;
pTriggerStep->orconf = OE_Default;
sqlitePersistTriggerStep(db, pTriggerStep);
return pTriggerStep;
}
/*
** Recursively delete a Trigger structure
*/
void sqlite3DeleteTrigger(sqlite3 *db, Trigger *pTrigger){
if( pTrigger==0 ) return;
sqlite3DeleteTriggerStep(db, pTrigger->step_list);
sqlite3DbFree(db, pTrigger->name);
sqlite3DbFree(db, pTrigger->table);
sqlite3ExprDelete(db, pTrigger->pWhen);
sqlite3IdListDelete(db, pTrigger->pColumns);
if( pTrigger->nameToken.dyn ) sqlite3DbFree(db, (char*)pTrigger->nameToken.z);
sqlite3DbFree(db, pTrigger);
}
/*
** This function is called to drop a trigger from the database schema.
**
** This may be called directly from the parser and therefore identifies
** the trigger by name. The sqlite3DropTriggerPtr() routine does the
** same job as this routine except it takes a pointer to the trigger
** instead of the trigger name.
**/
void sqlite3DropTrigger(Parse *pParse, SrcList *pName, int noErr){
Trigger *pTrigger = 0;
int i;
const char *zDb;
const char *zName;
int nName;
sqlite3 *db = pParse->db;
if( db->mallocFailed ) goto drop_trigger_cleanup;
if( SQLITE_OK!=sqlite3ReadSchema(pParse) ){
goto drop_trigger_cleanup;
}
assert( pName->nSrc==1 );
zDb = pName->a[0].zDatabase;
zName = pName->a[0].zName;
nName = sqlite3Strlen30(zName);
for(i=OMIT_TEMPDB; i<db->nDb; i++){
int j = (i<2) ? i^1 : i; /* Search TEMP before MAIN */
if( zDb && sqlite3StrICmp(db->aDb[j].zName, zDb) ) continue;
pTrigger = sqlite3HashFind(&(db->aDb[j].pSchema->trigHash), zName, nName);
if( pTrigger ) break;
}
if( !pTrigger ){
if( !noErr ){
sqlite3ErrorMsg(pParse, "no such trigger: %S", pName, 0);
}
goto drop_trigger_cleanup;
}
sqlite3DropTriggerPtr(pParse, pTrigger);
drop_trigger_cleanup:
sqlite3SrcListDelete(db, pName);
}
/*
** Return a pointer to the Table structure for the table that a trigger
** is set on.
*/
static Table *tableOfTrigger(Trigger *pTrigger){
int n = sqlite3Strlen30(pTrigger->table) + 1;
return sqlite3HashFind(&pTrigger->pTabSchema->tblHash, pTrigger->table, n);
}
/*
** Drop a trigger given a pointer to that trigger.
*/
void sqlite3DropTriggerPtr(Parse *pParse, Trigger *pTrigger){
Table *pTable;
Vdbe *v;
sqlite3 *db = pParse->db;
int iDb;
iDb = sqlite3SchemaToIndex(pParse->db, pTrigger->pSchema);
assert( iDb>=0 && iDb<db->nDb );
pTable = tableOfTrigger(pTrigger);
assert( pTable );
assert( pTable->pSchema==pTrigger->pSchema || iDb==1 );
#ifndef SQLITE_OMIT_AUTHORIZATION
{
int code = SQLITE_DROP_TRIGGER;
const char *zDb = db->aDb[iDb].zName;
const char *zTab = SCHEMA_TABLE(iDb);
if( iDb==1 ) code = SQLITE_DROP_TEMP_TRIGGER;
if( sqlite3AuthCheck(pParse, code, pTrigger->name, pTable->zName, zDb) ||
sqlite3AuthCheck(pParse, SQLITE_DELETE, zTab, 0, zDb) ){
return;
}
}
#endif
/* Generate code to destroy the database record of the trigger.
*/
assert( pTable!=0 );
if( (v = sqlite3GetVdbe(pParse))!=0 ){
int base;
static const VdbeOpList dropTrigger[] = {
{ OP_Rewind, 0, ADDR(9), 0},
{ OP_String8, 0, 1, 0}, /* 1 */
{ OP_Column, 0, 1, 2},
{ OP_Ne, 2, ADDR(8), 1},
{ OP_String8, 0, 1, 0}, /* 4: "trigger" */
{ OP_Column, 0, 0, 2},
{ OP_Ne, 2, ADDR(8), 1},
{ OP_Delete, 0, 0, 0},
{ OP_Next, 0, ADDR(1), 0}, /* 8 */
};
sqlite3BeginWriteOperation(pParse, 0, iDb);
sqlite3OpenMasterTable(pParse, iDb);
base = sqlite3VdbeAddOpList(v, ArraySize(dropTrigger), dropTrigger);
sqlite3VdbeChangeP4(v, base+1, pTrigger->name, 0);
sqlite3VdbeChangeP4(v, base+4, "trigger", P4_STATIC);
sqlite3ChangeCookie(pParse, iDb);
sqlite3VdbeAddOp2(v, OP_Close, 0, 0);
sqlite3VdbeAddOp4(v, OP_DropTrigger, iDb, 0, 0, pTrigger->name, 0);
}
}
/*
** Remove a trigger from the hash tables of the sqlite* pointer.
*/
void sqlite3UnlinkAndDeleteTrigger(sqlite3 *db, int iDb, const char *zName){
Trigger *pTrigger;
int nName = sqlite3Strlen30(zName);
pTrigger = sqlite3HashInsert(&(db->aDb[iDb].pSchema->trigHash),
zName, nName, 0);
if( pTrigger ){
Table *pTable = tableOfTrigger(pTrigger);
assert( pTable!=0 );
if( pTable->pTrigger == pTrigger ){
pTable->pTrigger = pTrigger->pNext;
}else{
Trigger *cc = pTable->pTrigger;
while( cc ){
if( cc->pNext == pTrigger ){
cc->pNext = cc->pNext->pNext;
break;
}
cc = cc->pNext;
}
assert(cc);
}
sqlite3DeleteTrigger(db, pTrigger);
db->flags |= SQLITE_InternChanges;
}
}
/*
** pEList is the SET clause of an UPDATE statement. Each entry
** in pEList is of the format <id>=<expr>. If any of the entries
** in pEList have an <id> which matches an identifier in pIdList,
** then return TRUE. If pIdList==NULL, then it is considered a
** wildcard that matches anything. Likewise if pEList==NULL then
** it matches anything so always return true. Return false only
** if there is no match.
*/
static int checkColumnOverLap(IdList *pIdList, ExprList *pEList){
int e;
if( !pIdList || !pEList ) return 1;
for(e=0; e<pEList->nExpr; e++){
if( sqlite3IdListIndex(pIdList, pEList->a[e].zName)>=0 ) return 1;
}
return 0;
}
/*
** Return a bit vector to indicate what kind of triggers exist for operation
** "op" on table pTab. If pChanges is not NULL then it is a list of columns
** that are being updated. Triggers only match if the ON clause of the
** trigger definition overlaps the set of columns being updated.
**
** The returned bit vector is some combination of TRIGGER_BEFORE and
** TRIGGER_AFTER.
*/
int sqlite3TriggersExist(
Table *pTab, /* The table the contains the triggers */
int op, /* one of TK_DELETE, TK_INSERT, TK_UPDATE */
ExprList *pChanges /* Columns that change in an UPDATE statement */
){
Trigger *pTrigger;
int mask = 0;
pTrigger = IsVirtual(pTab) ? 0 : pTab->pTrigger;
while( pTrigger ){
if( pTrigger->op==op && checkColumnOverLap(pTrigger->pColumns, pChanges) ){
mask |= pTrigger->tr_tm;
}
pTrigger = pTrigger->pNext;
}
return mask;
}
/*
** Convert the pStep->target token into a SrcList and return a pointer
** to that SrcList.
**
** This routine adds a specific database name, if needed, to the target when
** forming the SrcList. This prevents a trigger in one database from
** referring to a target in another database. An exception is when the
** trigger is in TEMP in which case it can refer to any other database it
** wants.
*/
static SrcList *targetSrcList(
Parse *pParse, /* The parsing context */
TriggerStep *pStep /* The trigger containing the target token */
){
Token sDb; /* Dummy database name token */
int iDb; /* Index of the database to use */
SrcList *pSrc; /* SrcList to be returned */
iDb = sqlite3SchemaToIndex(pParse->db, pStep->pTrig->pSchema);
if( iDb==0 || iDb>=2 ){
assert( iDb<pParse->db->nDb );
sDb.z = (u8*)pParse->db->aDb[iDb].zName;
sDb.n = sqlite3Strlen30((char*)sDb.z);
pSrc = sqlite3SrcListAppend(pParse->db, 0, &sDb, &pStep->target);
} else {
pSrc = sqlite3SrcListAppend(pParse->db, 0, &pStep->target, 0);
}
return pSrc;
}
/*
** Generate VDBE code for zero or more statements inside the body of a
** trigger.
*/
static int codeTriggerProgram(
Parse *pParse, /* The parser context */
TriggerStep *pStepList, /* List of statements inside the trigger body */
int orconfin /* Conflict algorithm. (OE_Abort, etc) */
){
TriggerStep * pTriggerStep = pStepList;
int orconf;
Vdbe *v = pParse->pVdbe;
sqlite3 *db = pParse->db;
assert( pTriggerStep!=0 );
assert( v!=0 );
sqlite3VdbeAddOp2(v, OP_ContextPush, 0, 0);
VdbeComment((v, "begin trigger %s", pStepList->pTrig->name));
while( pTriggerStep ){
sqlite3ExprClearColumnCache(pParse, -1);
orconf = (orconfin == OE_Default)?pTriggerStep->orconf:orconfin;
pParse->trigStack->orconf = orconf;
switch( pTriggerStep->op ){
case TK_SELECT: {
Select *ss = sqlite3SelectDup(db, pTriggerStep->pSelect);
if( ss ){
SelectDest dest;
sqlite3SelectDestInit(&dest, SRT_Discard, 0);
sqlite3Select(pParse, ss, &dest);
sqlite3SelectDelete(db, ss);
}
break;
}
case TK_UPDATE: {
SrcList *pSrc;
pSrc = targetSrcList(pParse, pTriggerStep);
sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0);
sqlite3Update(pParse, pSrc,
sqlite3ExprListDup(db, pTriggerStep->pExprList),
sqlite3ExprDup(db, pTriggerStep->pWhere), orconf);
sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0);
break;
}
case TK_INSERT: {
SrcList *pSrc;
pSrc = targetSrcList(pParse, pTriggerStep);
sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0);
sqlite3Insert(pParse, pSrc,
sqlite3ExprListDup(db, pTriggerStep->pExprList),
sqlite3SelectDup(db, pTriggerStep->pSelect),
sqlite3IdListDup(db, pTriggerStep->pIdList), orconf);
sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0);
break;
}
case TK_DELETE: {
SrcList *pSrc;
sqlite3VdbeAddOp2(v, OP_ResetCount, 0, 0);
pSrc = targetSrcList(pParse, pTriggerStep);
sqlite3DeleteFrom(pParse, pSrc,
sqlite3ExprDup(db, pTriggerStep->pWhere));
sqlite3VdbeAddOp2(v, OP_ResetCount, 1, 0);
break;
}
default:
assert(0);
}
pTriggerStep = pTriggerStep->pNext;
}
sqlite3VdbeAddOp2(v, OP_ContextPop, 0, 0);
VdbeComment((v, "end trigger %s", pStepList->pTrig->name));
return 0;
}
/*
** This is called to code FOR EACH ROW triggers.
**
** When the code that this function generates is executed, the following
** must be true:
**
** 1. No cursors may be open in the main database. (But newIdx and oldIdx
** can be indices of cursors in temporary tables. See below.)
**
** 2. If the triggers being coded are ON INSERT or ON UPDATE triggers, then
** a temporary vdbe cursor (index newIdx) must be open and pointing at
** a row containing values to be substituted for new.* expressions in the
** trigger program(s).
**
** 3. If the triggers being coded are ON DELETE or ON UPDATE triggers, then
** a temporary vdbe cursor (index oldIdx) must be open and pointing at
** a row containing values to be substituted for old.* expressions in the
** trigger program(s).
**
** If they are not NULL, the piOldColMask and piNewColMask output variables
** are set to values that describe the columns used by the trigger program
** in the OLD.* and NEW.* tables respectively. If column N of the
** pseudo-table is read at least once, the corresponding bit of the output
** mask is set. If a column with an index greater than 32 is read, the
** output mask is set to the special value 0xffffffff.
**
*/
int sqlite3CodeRowTrigger(
Parse *pParse, /* Parse context */
int op, /* One of TK_UPDATE, TK_INSERT, TK_DELETE */
ExprList *pChanges, /* Changes list for any UPDATE OF triggers */
int tr_tm, /* One of TRIGGER_BEFORE, TRIGGER_AFTER */
Table *pTab, /* The table to code triggers from */
int newIdx, /* The indice of the "new" row to access */
int oldIdx, /* The indice of the "old" row to access */
int orconf, /* ON CONFLICT policy */
int ignoreJump, /* Instruction to jump to for RAISE(IGNORE) */
u32 *piOldColMask, /* OUT: Mask of columns used from the OLD.* table */
u32 *piNewColMask /* OUT: Mask of columns used from the NEW.* table */
){
Trigger *p;
sqlite3 *db = pParse->db;
TriggerStack trigStackEntry;
trigStackEntry.oldColMask = 0;
trigStackEntry.newColMask = 0;
assert(op == TK_UPDATE || op == TK_INSERT || op == TK_DELETE);
assert(tr_tm == TRIGGER_BEFORE || tr_tm == TRIGGER_AFTER );
assert(newIdx != -1 || oldIdx != -1);
for(p=pTab->pTrigger; p; p=p->pNext){
int fire_this = 0;
/* Determine whether we should code this trigger */
if(
p->op==op &&
p->tr_tm==tr_tm &&
(p->pSchema==p->pTabSchema || p->pSchema==db->aDb[1].pSchema) &&
(op!=TK_UPDATE||!p->pColumns||checkColumnOverLap(p->pColumns,pChanges))
){
TriggerStack *pS; /* Pointer to trigger-stack entry */
for(pS=pParse->trigStack; pS && p!=pS->pTrigger; pS=pS->pNext){}
if( !pS ){
fire_this = 1;
}
#if 0 /* Give no warning for recursive triggers. Just do not do them */
else{
sqlite3ErrorMsg(pParse, "recursive triggers not supported (%s)",
p->name);
return SQLITE_ERROR;
}
#endif
}
if( fire_this ){
int endTrigger;
Expr * whenExpr;
AuthContext sContext;
NameContext sNC;
#ifndef SQLITE_OMIT_TRACE
sqlite3VdbeAddOp4(pParse->pVdbe, OP_Trace, 0, 0, 0,
sqlite3MPrintf(db, "-- TRIGGER %s", p->name),
P4_DYNAMIC);
#endif
memset(&sNC, 0, sizeof(sNC));
sNC.pParse = pParse;
/* Push an entry on to the trigger stack */
trigStackEntry.pTrigger = p;
trigStackEntry.newIdx = newIdx;
trigStackEntry.oldIdx = oldIdx;
trigStackEntry.pTab = pTab;
trigStackEntry.pNext = pParse->trigStack;
trigStackEntry.ignoreJump = ignoreJump;
pParse->trigStack = &trigStackEntry;
sqlite3AuthContextPush(pParse, &sContext, p->name);
/* code the WHEN clause */
endTrigger = sqlite3VdbeMakeLabel(pParse->pVdbe);
whenExpr = sqlite3ExprDup(db, p->pWhen);
if( db->mallocFailed || sqlite3ResolveExprNames(&sNC, whenExpr) ){
pParse->trigStack = trigStackEntry.pNext;
sqlite3ExprDelete(db, whenExpr);
return 1;
}
sqlite3ExprIfFalse(pParse, whenExpr, endTrigger, SQLITE_JUMPIFNULL);
sqlite3ExprDelete(db, whenExpr);
codeTriggerProgram(pParse, p->step_list, orconf);
/* Pop the entry off the trigger stack */
pParse->trigStack = trigStackEntry.pNext;
sqlite3AuthContextPop(&sContext);
sqlite3VdbeResolveLabel(pParse->pVdbe, endTrigger);
}
}
if( piOldColMask ) *piOldColMask |= trigStackEntry.oldColMask;
if( piNewColMask ) *piNewColMask |= trigStackEntry.newColMask;
return 0;
}
#endif /* !defined(SQLITE_OMIT_TRIGGER) */
| 33.954439 | 80 | 0.657423 | [
"object",
"vector"
] |
65647d0aae3a635d74067a2d6abaf7e3c109a2b3 | 2,348 | h | C | src/utils.h | TL-4319/ua_navigation | f5579ad6a5e83da7764bdd3406ccbbe72e890685 | [
"MIT"
] | 1 | 2022-03-08T20:43:57.000Z | 2022-03-08T20:43:57.000Z | src/utils.h | TL-4319/ua_navigation | f5579ad6a5e83da7764bdd3406ccbbe72e890685 | [
"MIT"
] | null | null | null | src/utils.h | TL-4319/ua_navigation | f5579ad6a5e83da7764bdd3406ccbbe72e890685 | [
"MIT"
] | null | null | null | /*
* Brian R Taylor
* brian.taylor@bolderflight.com
*
* Copyright (c) 2021 Bolder Flight Systems Inc
*
* 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 NAVIGATION_SRC_UTILS_H_ // NOLINT
#define NAVIGATION_SRC_UTILS_H_
#include "eigen.h" // NOLINT
#include "Eigen/Dense"
namespace bfs {
/* Converts a +/- 180 value to a 0 - 360 value */
template<typename T>
T WrapTo2Pi(T ang) {
static_assert(std::is_floating_point<T>::value,
"Only floating point types supported");
ang = std::fmod(ang, BFS_2PI<T>);
if (ang < static_cast<T>(0)) {
ang += BFS_2PI<T>;
}
return ang;
}
/* Converts a 0 - 360 value to a +/- 180 value */
template<typename T>
T WrapToPi(T ang) {
static_assert(std::is_floating_point<T>::value,
"Only floating point types supported");
if (ang > BFS_PI<T>) {
ang -= BFS_2PI<T>;
}
if (ang < -BFS_PI<T>) {
ang += BFS_2PI<T>;
}
return ang;
}
/* Skew symmetric matrix from a given vector w */
template<typename T>
Eigen::Matrix<T, 3, 3> Skew(const Eigen::Matrix<T, 3, 1> &w) {
Eigen::Matrix<T, 3, 3> c;
c(0, 0) = 0.0;
c(0, 1) = -w(2);
c(0, 2) = w(1);
c(1, 0) = w(2);
c(1, 1) = 0.0;
c(1, 2) = -w(0);
c(2, 0) = -w(1);
c(2, 1) = w(0);
c(2, 2) = 0.0;
return c;
}
} // namespace bfs
#endif // NAVIGATION_SRC_UTILS_H_ NOLINT
| 29.721519 | 78 | 0.676746 | [
"vector"
] |
656ad8915be89d93b38da4c4cdcf86a0aa6780e1 | 4,349 | h | C | third_party/gecko-16/win32/include/nsIScriptLoaderObserver.h | bwp/SeleniumWebDriver | 58221fbe59fcbbde9d9a033a95d45d576b422747 | [
"Apache-2.0"
] | 1 | 2018-02-05T04:23:18.000Z | 2018-02-05T04:23:18.000Z | third_party/gecko-16/win32/include/nsIScriptLoaderObserver.h | bwp/SeleniumWebDriver | 58221fbe59fcbbde9d9a033a95d45d576b422747 | [
"Apache-2.0"
] | null | null | null | third_party/gecko-16/win32/include/nsIScriptLoaderObserver.h | bwp/SeleniumWebDriver | 58221fbe59fcbbde9d9a033a95d45d576b422747 | [
"Apache-2.0"
] | null | null | null | /*
* DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-m-rel-xr-w32-bld/build/content/base/public/nsIScriptLoaderObserver.idl
*/
#ifndef __gen_nsIScriptLoaderObserver_h__
#define __gen_nsIScriptLoaderObserver_h__
#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
class nsIScriptElement; /* forward declaration */
class nsIURI; /* forward declaration */
/* starting interface: nsIScriptLoaderObserver */
#define NS_ISCRIPTLOADEROBSERVER_IID_STR "7b787204-76fb-4764-96f1-fb7a666db4f4"
#define NS_ISCRIPTLOADEROBSERVER_IID \
{0x7b787204, 0x76fb, 0x4764, \
{ 0x96, 0xf1, 0xfb, 0x7a, 0x66, 0x6d, 0xb4, 0xf4 }}
class NS_NO_VTABLE NS_SCRIPTABLE nsIScriptLoaderObserver : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_ISCRIPTLOADEROBSERVER_IID)
/* void scriptAvailable (in nsresult aResult, in nsIScriptElement aElement, in boolean aIsInline, in nsIURI aURI, in PRInt32 aLineNo); */
NS_SCRIPTABLE NS_IMETHOD ScriptAvailable(nsresult aResult, nsIScriptElement *aElement, bool aIsInline, nsIURI *aURI, PRInt32 aLineNo) = 0;
/* void scriptEvaluated (in nsresult aResult, in nsIScriptElement aElement, in boolean aIsInline); */
NS_SCRIPTABLE NS_IMETHOD ScriptEvaluated(nsresult aResult, nsIScriptElement *aElement, bool aIsInline) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIScriptLoaderObserver, NS_ISCRIPTLOADEROBSERVER_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSISCRIPTLOADEROBSERVER \
NS_SCRIPTABLE NS_IMETHOD ScriptAvailable(nsresult aResult, nsIScriptElement *aElement, bool aIsInline, nsIURI *aURI, PRInt32 aLineNo); \
NS_SCRIPTABLE NS_IMETHOD ScriptEvaluated(nsresult aResult, nsIScriptElement *aElement, bool aIsInline);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSISCRIPTLOADEROBSERVER(_to) \
NS_SCRIPTABLE NS_IMETHOD ScriptAvailable(nsresult aResult, nsIScriptElement *aElement, bool aIsInline, nsIURI *aURI, PRInt32 aLineNo) { return _to ScriptAvailable(aResult, aElement, aIsInline, aURI, aLineNo); } \
NS_SCRIPTABLE NS_IMETHOD ScriptEvaluated(nsresult aResult, nsIScriptElement *aElement, bool aIsInline) { return _to ScriptEvaluated(aResult, aElement, aIsInline); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSISCRIPTLOADEROBSERVER(_to) \
NS_SCRIPTABLE NS_IMETHOD ScriptAvailable(nsresult aResult, nsIScriptElement *aElement, bool aIsInline, nsIURI *aURI, PRInt32 aLineNo) { return !_to ? NS_ERROR_NULL_POINTER : _to->ScriptAvailable(aResult, aElement, aIsInline, aURI, aLineNo); } \
NS_SCRIPTABLE NS_IMETHOD ScriptEvaluated(nsresult aResult, nsIScriptElement *aElement, bool aIsInline) { return !_to ? NS_ERROR_NULL_POINTER : _to->ScriptEvaluated(aResult, aElement, aIsInline); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsScriptLoaderObserver : public nsIScriptLoaderObserver
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSISCRIPTLOADEROBSERVER
nsScriptLoaderObserver();
private:
~nsScriptLoaderObserver();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsScriptLoaderObserver, nsIScriptLoaderObserver)
nsScriptLoaderObserver::nsScriptLoaderObserver()
{
/* member initializers and constructor code */
}
nsScriptLoaderObserver::~nsScriptLoaderObserver()
{
/* destructor code */
}
/* void scriptAvailable (in nsresult aResult, in nsIScriptElement aElement, in boolean aIsInline, in nsIURI aURI, in PRInt32 aLineNo); */
NS_IMETHODIMP nsScriptLoaderObserver::ScriptAvailable(nsresult aResult, nsIScriptElement *aElement, bool aIsInline, nsIURI *aURI, PRInt32 aLineNo)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* void scriptEvaluated (in nsresult aResult, in nsIScriptElement aElement, in boolean aIsInline); */
NS_IMETHODIMP nsScriptLoaderObserver::ScriptEvaluated(nsresult aResult, nsIScriptElement *aElement, bool aIsInline)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsIScriptLoaderObserver_h__ */
| 40.268519 | 246 | 0.798115 | [
"object"
] |
65712cb7c06e44817340efd34d94fe5761906af7 | 1,744 | h | C | gcc-build/i686-pc-linux-gnu/libjava/java/security/KeyFactory.h | giraffe/jrate | 764bbf973d1de4e38f93ba9b9c7be566f1541e16 | [
"Xnet",
"Linux-OpenIB",
"X11"
] | 1 | 2021-06-15T05:43:22.000Z | 2021-06-15T05:43:22.000Z | gcc-build/i686-pc-linux-gnu/libjava/java/security/KeyFactory.h | giraffe/jrate | 764bbf973d1de4e38f93ba9b9c7be566f1541e16 | [
"Xnet",
"Linux-OpenIB",
"X11"
] | null | null | null | gcc-build/i686-pc-linux-gnu/libjava/java/security/KeyFactory.h | giraffe/jrate | 764bbf973d1de4e38f93ba9b9c7be566f1541e16 | [
"Xnet",
"Linux-OpenIB",
"X11"
] | null | null | null | // DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*-
#ifndef __java_security_KeyFactory__
#define __java_security_KeyFactory__
#pragma interface
#include <java/lang/Object.h>
extern "Java"
{
namespace java
{
namespace security
{
class Key;
class PrivateKey;
class PublicKey;
namespace spec
{
class KeySpec;
}
class KeyFactory;
class Provider;
class KeyFactorySpi;
}
}
};
class ::java::security::KeyFactory : public ::java::lang::Object
{
public: // actually protected
KeyFactory (::java::security::KeyFactorySpi *, ::java::security::Provider *, ::java::lang::String *);
public:
static ::java::security::KeyFactory *getInstance (::java::lang::String *);
static ::java::security::KeyFactory *getInstance (::java::lang::String *, ::java::lang::String *);
private:
static ::java::security::KeyFactory *getInstance (::java::lang::String *, ::java::lang::String *, ::java::security::Provider *);
public:
::java::security::Provider *getProvider () { return provider; }
::java::lang::String *getAlgorithm () { return algorithm; }
::java::security::PublicKey *generatePublic (::java::security::spec::KeySpec *);
::java::security::PrivateKey *generatePrivate (::java::security::spec::KeySpec *);
::java::security::spec::KeySpec *getKeySpec (::java::security::Key *, ::java::lang::Class *);
::java::security::Key *translateKey (::java::security::Key *);
private:
::java::security::KeyFactorySpi * __attribute__((aligned(__alignof__( ::java::lang::Object )))) keyFacSpi;
::java::security::Provider *provider;
::java::lang::String *algorithm;
public:
static ::java::lang::Class class$;
};
#endif /* __java_security_KeyFactory__ */
| 31.142857 | 130 | 0.666858 | [
"object"
] |
657589eb494dbf8a27bc84d81066c47a2765b5a2 | 3,771 | h | C | python/ideep4py/py/primitives/concat_py.h | yinghai/ideep | 1146816a58e108a9c2c15948422d0d3236eb69cd | [
"MIT"
] | null | null | null | python/ideep4py/py/primitives/concat_py.h | yinghai/ideep | 1146816a58e108a9c2c15948422d0d3236eb69cd | [
"MIT"
] | null | null | null | python/ideep4py/py/primitives/concat_py.h | yinghai/ideep | 1146816a58e108a9c2c15948422d0d3236eb69cd | [
"MIT"
] | null | null | null | /*
*Copyright (c) 2018 Intel Corporation.
*
*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 _CONCAT_PY_H_
#define _CONCAT_PY_H_
#include <vector>
#include <memory>
#include "mdarray.h"
#include "ideep.hpp"
class Concat
{
public:
using scratch_allocator = ideep::utils::scratch_allocator;
using tensor = ideep::tensor;
using concat = ideep::concat;
using spliter = ideep::reorder;
static mdarray Forward(std::vector<mdarray> inputs, int axis) {
std::vector<tensor> inputs_;
for (mdarray elems : inputs) {
inputs_.push_back(*elems.get());
}
tensor dst;
concat::compute<scratch_allocator>(inputs_, axis, dst);
auto out = mdarray(dst);
return out;
}
static std::vector<mdarray> Backward(mdarray *grady,
std::vector<int> offsets,
int axis) {
std::vector<mdarray> gxs;
std::vector<int> axis_len;
tensor::dims offset_dims(grady->get()->ndims(), 0);
tensor::dims grady_dims = grady->get()->get_dims();
tensor::dims gradx_dims(grady_dims);
// FIXME
// For split function usage. if not support, fallback to numpy
bool ret = is_valid_offsets(grady_dims, offsets, axis_len, axis);
if (!ret)
return gxs;
for (unsigned i = 0; i < axis_len.size(); i++) {
gradx_dims[axis] = axis_len[i];
auto gradx = spliter::compute<scratch_allocator>(*grady->get(),
gradx_dims, offset_dims);
gxs.push_back(mdarray(gradx));
offset_dims[axis] += axis_len[i];
}
return gxs;
}
private:
static bool is_valid_offsets(tensor::dims grady_dims, std::vector<int> &offsets,
std::vector<int> &axis_len, int axis) {
int min_value = -1;
std::vector<int> valid_offsets;
for (unsigned i = 0; i < offsets.size(); i++) {
if (offsets[i] < 0)
offsets[i] += grady_dims[axis];
if (offsets[i] == 0) // mkldnn can't handle zero dim
return false;
else if (offsets[i] > min_value) {
min_value = offsets[i];
// larger than max value in corresponding dims
if (offsets[i] >= grady_dims[axis])
return false;
else
valid_offsets.push_back(offsets[i]);
} else { // out of order
return false;
}
}
if (valid_offsets.empty())
return false;
// push dim len along axis
for (unsigned i = 0; i < valid_offsets.size(); i++) {
if (i == 0)
axis_len.push_back(valid_offsets[i]);
else
axis_len.push_back(valid_offsets[i] - valid_offsets[i - 1]);
}
// push last dim len
axis_len.push_back(grady_dims[axis] - valid_offsets.back());
return true;
}
};
#endif // _CONCAT_PY_H_
| 29.692913 | 82 | 0.64996 | [
"vector"
] |
6582530f1666176dd0c3c3a818185f745eb52355 | 19,812 | c | C | applications/MultiScalePedestrianDetector/HoGEstimGenerator.c | knmcguire/gap_sdk | 7b0a09a353ab6f0550793d40bd46e98051f4a3d7 | [
"Apache-2.0"
] | 1 | 2020-01-29T15:39:31.000Z | 2020-01-29T15:39:31.000Z | applications/MultiScalePedestrianDetector/HoGEstimGenerator.c | knmcguire/gap_sdk | 7b0a09a353ab6f0550793d40bd46e98051f4a3d7 | [
"Apache-2.0"
] | null | null | null | applications/MultiScalePedestrianDetector/HoGEstimGenerator.c | knmcguire/gap_sdk | 7b0a09a353ab6f0550793d40bd46e98051f4a3d7 | [
"Apache-2.0"
] | 1 | 2021-11-11T02:12:25.000Z | 2021-11-11T02:12:25.000Z | /*
* Copyright 2019 GreenWaves Technologies, SAS
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdint.h>
#include <stdio.h>
#include "AutoTilerLib.h"
void LoadHOGLibrary()
{
LibKernel("KerProcessCellLine", CALL_PARALLEL,
CArgs(5,
TCArg("uint8_t * __restrict__", "In"),
TCArg("uint32_t", "W"),
TCArg("uint16_t ** __restrict__", "CellLines"),
TCArg("uint32_t", "CellLineIndex"),
TCArg("uint32_t", "CellLineCount")
),
"KerProcessCellLine_ArgT"
);
LibKernel("KerProcessBlockLine", CALL_PARALLEL,
CArgs(3,
TCArg("uint16_t ** __restrict__", "CellLines"),
TCArg("uint32_t", "W"),
TCArg("uint16_t * __restrict__", "HOGFeatures")
),
"KerProcessBlockLine_ArgT"
);
LibKernel("KerReadHoGFeatCol", CALL_PARALLEL,
CArgs(6,
TCArg("uint16_t * __restrict__", "In"),
TCArg("uint32_t", "H"),
TCArg("uint32_t", "FeatureSize"),
TCArg("uint32_t", "EstimWidth"),
TCArg("uint16_t ** __restrict__", "HoGFeatCols"),
TCArg("uint32_t", "HoGFeatColIndex")
),
"KerReadHoGFeatCol_ArgT"
);
LibKernel("KerEstimate", CALL_PARALLEL,
CArgs(6,
TCArg("uint16_t ** __restrict__", "HoGFeatCols"),
TCArg("uint32_t", "FeatureSize"),
TCArg("uint32_t", "WEstimator"),
TCArg("uint32_t", "HEstimator"),
TCArg("uint32_t", "HFeatCols"),
TCArg("uint32_t * __restrict__", "Out")
),
"KerEstimate_ArgT"
);
LibKernel("KerEstimateWin", CALL_SEQUENTIAL,
CArgs(7,
TCArg("uint16_t ** __restrict__", "HoGFeatCols"),
TCArg("uint32_t", "FeatureSize"),
TCArg("uint32_t", "WEstimator"),
TCArg("uint32_t", "HEstimator"),
TCArg("uint32_t", "HFeatCols"),
TCArg("uint32_t * __restrict__", "Out"),
TCArg("uint16_t * __restrict__", "Buffer")
),
""
);
LibKernel("KerWeakEstimateWin", CALL_SEQUENTIAL,
CArgs(9,
TCArg("uint16_t ** __restrict__", "HoGFeatCols"),
TCArg("uint32_t", "FeatureSize"),
TCArg("uint32_t", "WEstimator"),
TCArg("uint32_t", "HEstimator"),
TCArg("uint32_t", "HFeatCols"),
TCArg("uint8_t * __restrict__", "Out"),
TCArg("uint16_t * __restrict__", "Buffer"),
TCArg("HoGWeakPredictor_T * __restrict__","Model"),
TCArg("uint32_t", "ModelSize")
),
""
);
LibKernel("KerWeakEstimateAllWindows", CALL_PARALLEL,
CArgs(7,
TCArg("uint16_t ** __restrict__", "HoGFeatCols"),
TCArg("uint32_t", "ColumnIndexM1"),
TCArg("uint32_t", "HEstimator"),
TCArg("uint32_t", "HFeatCols"),
TCArg("uint32_t", "FeatureSize"),
TCArg("HoGWeakPredictorBis_T * __restrict__", "Model"),
TCArg("uint32_t", "ModelSize")
),
"KerWeakEstimate_ArgT"
);
}
void GenerateHOG(char *Name,
unsigned int W, /* Image width */
unsigned int H, /* Image Height */
unsigned int CellSize, /* Cell is [CellSize x CellSize] pixels */
unsigned int BlockSize, /* Block is [BlockSize x BlockSize] Cells */
unsigned int BlockOverlap, /* Number Cells in common between 2 adjacent blocks */
unsigned int BinsPerCell) /* Number of bins for a cell */
{
/*
(H-2)/CellSize = BlockSize + Kh*(BlockSize-BlockOverlap)
=> Kh = ((H-2)/CellSize - BlockSize)/(BlockSize - BlockOverlap)
=> Ha = (Kh*(BlockSize - BlockOverlap) + BlockSize) * CellSize + 2
Kh + 1 is the number of HOG feature blocks in the vertical direction
Ha is the adjusted height of the image in order to have an a number of lines in the image that exactly gives Kh+1
HOG features in the vertical direction.
(W-2)/CellSize = BlockSize + Kw*(BlockSize-BlockOverlap)
=> Kw = ((W-2)/CellSize - BlockSize)/(BlockSize - BlockOverlap)
=> Wa = (Kw*(BlockSize - BlockOverlap) + BlockSize) * CellSize + 2
Kw + 1 is the number of HOG feature blocks in the horizontal direction
Wa is the adjusted width of the image in order to have an a number of lines in the image that exactly gives Kw+1
HOG features in the horizontal direction.
*/
unsigned int Kh = ((H-2)/CellSize - BlockSize)/(BlockSize - BlockOverlap);
unsigned int Ha = (Kh*(BlockSize - BlockOverlap) + BlockSize) * CellSize + 2;
unsigned int Kw = ((W-2)/CellSize - BlockSize)/(BlockSize - BlockOverlap);
unsigned int Wa = (Kw*(BlockSize - BlockOverlap) + BlockSize) * CellSize + 2;
// if ((W & 0x3) != 0) GenTilingError("Image width must be a multiple of 4, Actual: %d\n", W);
printf("Generating HOG Feature Extraction:\n");
printf("\tInput Image [%3d x %3d], Adjusted to [%3d x %3d]\n", W, H, Wa, Ha);
printf("\tHOG Cell Size [%3d ], Bins per Cells: %d\n", CellSize, BinsPerCell);
printf("\tHOG Block Size [%3d ], Overlap: %d,\n", BlockSize, BlockOverlap);
printf("\tHOG Features output:[%3d x %3d]\n", Kw+1, Kh+1);
OpenKernelGroup(Name);
UserKernel(AppendNames("Prime", Name),
KernelDimensions(0, W, CellSize*BlockSize+2, 0),
KernelIterationOrder(KER_DIM2, KER_TILE),
TILE_HOR,
CArgs(3,
TCArg("uint8_t * __restrict__", "ImageIn"),
TCArg("uint16_t ** __restrict__", "CellLines"),
TCArg("uint16_t * __restrict__", "HOGFeatures")
),
Calls(2,
Call("KerProcessCellLine", LOC_INNER_LOOP,
Bindings(5,
K_Arg("KerIn", KER_ARG_TILE),
K_Arg("KerIn", KER_ARG_TILE_W),
C_Arg("CellLines"),
K_Arg("KerIn", KER_ARG_TILEINDEX),
Imm(1)
)
),
Call("KerProcessBlockLine", LOC_INNER_LOOP_EPILOG,
Bindings(3,
C_Arg("CellLines"),
K_Arg("KerIn", KER_ARG_W),
K_Arg("KerFeatOut", KER_ARG_TILE)
)
)
),
KerArgs(2,
KerArg("KerIn", OBJ_IN_DB, W, BlockSize*CellSize+2, sizeof(char),
2, OBJ_CONSTRAINTS_ONEPREFTILE, CellSize, "ImageIn", 0),
KerArg("KerFeatOut", OBJ_BUFFER_OUT_NTILED, 1+Kw, 1, BlockSize*BlockSize*BinsPerCell*sizeof(short),
0, 0, 0, "HOGFeatures", 0)
)
);
UserKernel(AppendNames("Body", Name),
KernelDimensions(0, W, H-CellSize*BlockSize, 0),
KernelIterationOrder(KER_DIM2, KER_TILE),
TILE_HOR,
CArgs(3,
TCArg("uint8_t * __restrict__", "ImageIn"),
TCArg("uint16_t ** __restrict__", "CellLines"),
TCArg("uint16_t * __restrict__", "HOGFeatures")
),
Calls(2,
Call("KerProcessCellLine", LOC_INNER_LOOP,
Bindings(5,
K_Arg("KerIn", KER_ARG_TILE),
K_Arg("KerIn", KER_ARG_TILE_W),
C_Arg("CellLines"),
Imm(BlockSize),
Imm(BlockSize-BlockOverlap)
)
),
Call("KerProcessBlockLine", LOC_INNER_LOOP,
Bindings(3,
C_Arg("CellLines"),
K_Arg("KerIn", KER_ARG_W),
K_Arg("KerFeatOut", KER_ARG_TILE)
)
)
),
KerArgs(2,
KerArg("KerIn", OBJ_IN_DB, W, Ha - BlockSize*CellSize, sizeof(char),
2, OBJ_CONSTRAINTS_ONEPREFTILE, (BlockSize-BlockOverlap)*CellSize, "ImageIn", 0),
KerArg("KerFeatOut", OBJ_OUT_DB, 1+Kw, Kh, BlockSize*BlockSize*BinsPerCell*sizeof(short),
0, 0, 0, "HOGFeatures", 0)
)
);
CloseKernelGroup();
UserKernelGroup(Name,
CArgs(5,
TCArg("uint8_t * __restrict__", "ImageIn"),
TCArg("uint16_t ** __restrict__", "CellLines"),
TCArg("uint16_t * __restrict__", "HOGFeatures"),
TCArg("uint32_t", "OneFullBlockLineOffset"),
TCArg("uint32_t", "OneFullHoGFeatureLineOffset")
),
Calls(2,
UserKernelCall(AppendNames("Prime", Name), LOC_GROUP,
Bindings(3, C_Arg("ImageIn"), C_Arg("CellLines"), C_Arg("HOGFeatures"))
),
UserKernelCall(AppendNames("Body", Name), LOC_GROUP,
Bindings(3,
C_ArgPlusCvarOffset("ImageIn", "OneFullBlockLineOffset"),
C_Arg("CellLines"),
C_ArgPlusCvarOffset("HOGFeatures", "OneFullHoGFeatureLineOffset")
)
)
)
);
}
void GenerateWeakHOGEstimator(
char *Name,
unsigned int W, /* Image width */
unsigned int H, /* Image Height */
unsigned int CellSize, /* Cell is [CellSize x CellSize] pixels */
unsigned int BlockSize, /* Block is [BlockSize x BlockSize] Cells */
unsigned int BlockOverlap, /* Number Cells in common between 2 adjacent blocks */
unsigned int BinsPerCell, /* Number of bins for a cell */
unsigned int WEstimPix, /* Width of the estimation window, in pixels */
unsigned int HEstimPix, /* Height of the estimation window, in pixels */
unsigned int EstimSize, /* Size of estimation result per estimation window, in bytes */
unsigned int NWeakEstim /* Number of weak estimators in the model */
)
{
unsigned int Kh = ((H-2)/CellSize - BlockSize)/(BlockSize - BlockOverlap);
unsigned int Ha = (Kh*(BlockSize - BlockOverlap) + BlockSize) * CellSize + 2;
unsigned int Kw = ((W-2)/CellSize - BlockSize)/(BlockSize - BlockOverlap);
unsigned int Wa = (Kw*(BlockSize - BlockOverlap) + BlockSize) * CellSize + 2;
unsigned int HoGFeatSize = BlockSize*BlockSize*BinsPerCell*sizeof(unsigned short int);
unsigned int Whf = 1 + Kw; /* Width in HoG features */
unsigned int Hhf = 1 + Kh; /* Height in HoG features */
unsigned int KhE = ((HEstimPix)/CellSize - BlockSize)/(BlockSize - BlockOverlap);
unsigned int KwE = ((WEstimPix)/CellSize - BlockSize)/(BlockSize - BlockOverlap);
unsigned int WEstim = 1 + KwE; /* Width of Estim window in HoG Features */
unsigned int HEstim = 1 + KhE; /* Height of Estim window in HoG Features */
if (W<WEstimPix || H<HEstimPix) GenTilingError("Image size [%d x %d] must be larger than estimation window [%d x %d]\n", W, H, WEstimPix, HEstimPix);
printf("Generating HOG Based Estimator, Weak Estimator Version:\n");
printf("\tHOG Features [%3d x %3d] from Image [%3d x %3d]\n", Whf, Hhf, W, H);
printf("\tEstimation Window: [%3d x %3d] pixels or [%3d x %3d] HOG features\n", WEstimPix, HEstimPix, WEstim, HEstim);
printf("\tEstimation output: [%3d x %3d]\n", (Whf-WEstim)+1, (Hhf-HEstim)+1);
printf("\tWeak estimators: [%4d ]\n", NWeakEstim);
OpenKernelGroup(Name);
UserKernel(AppendNames("Prime", Name),
KernelDimensions(0, WEstim, Hhf, 0),
KernelIterationOrder(KER_DIM2, KER_TILE),
TILE_VER,
CArgs(6,
TCArg("uint16_t * __restrict__", "HoGFeatIn"),
TCArg("uint16_t ** __restrict__", "HoGFeatCols"),
TCArg("uint32_t", "HFeat"),
TCArg("uint8_t * __restrict__", "Out"),
TCArg("HoGWeakPredictor_T * __restrict__", "Model"),
TCArg("uint32_t", "ModelSize")
),
Calls(2,
Call("KerReadHoGFeatCol", LOC_INNER_LOOP,
Bindings(6,
K_Arg("KerIn", KER_ARG_TILE),
K_Arg("KerIn", KER_ARG_TILE_H),
Imm(BlockSize*BlockSize*BinsPerCell),
Imm(WEstim),
C_Arg("HoGFeatCols"),
K_Arg("KerIn", KER_ARG_TILEINDEX)
)
),
Call("KerWeakEstimateWin", LOC_EPILOG,
Bindings(9,
C_Arg("HoGFeatCols"),
Imm(BlockSize*BlockSize*BinsPerCell),
Imm(WEstim),
Imm(HEstim),
C_Arg("HFeat"), // Imm(Hhf),
K_Arg("KerOut", KER_ARG_TILE), // C_Arg("Out")
K_Arg("Buffer", KER_ARG),
C_Arg("Model"),
C_Arg("ModelSize")
)
)
),
KerArgs(3,
KerArgPart("KerIn", OBJ_IN_DB, Whf, WEstim, Hhf, Hhf, HoGFeatSize, 0, OBJ_CONSTRAINTS_ONEPREFTILE, 1, "HoGFeatIn", 0),
KerArgPart("KerOut", OBJ_BUFFER_OUT_NTILED, Whf-WEstim+1, 1, Hhf-HEstim+1, Hhf-HEstim+1, EstimSize, 0, 0, 0, "Out", 0),
KerArg("Buffer", OBJ_BUFFER_NTILED, WEstim, HEstim, HoGFeatSize, 0, 0, 0, "", 0)
)
);
UserKernel(AppendNames("Body", Name),
KernelDimensions(0, Whf-WEstim, Hhf, 0),
KernelIterationOrder(KER_DIM2, KER_TILE),
TILE_VER,
CArgs(6,
TCArg("uint16_t * __restrict__", "HoGFeatIn"),
TCArg("uint16_t ** __restrict__", "HoGFeatCols"),
TCArg("uint32_t", "HFeat"),
TCArg("uint8_t * __restrict__", "Out"),
TCArg("HoGWeakPredictor_T * __restrict__", "Model"),
TCArg("uint32_t", "ModelSize")
),
Calls(2,
Call("KerReadHoGFeatCol", LOC_INNER_LOOP,
Bindings(6,
K_Arg("KerIn", KER_ARG_TILE),
K_Arg("KerIn", KER_ARG_TILE_H),
Imm(BlockSize*BlockSize*BinsPerCell),
Imm(WEstim),
C_Arg("HoGFeatCols"),
Imm(WEstim)
)
),
Call("KerWeakEstimateWin", LOC_INNER_LOOP,
Bindings(9,
C_Arg("HoGFeatCols"),
Imm(BlockSize*BlockSize*BinsPerCell),
Imm(WEstim),
Imm(HEstim),
C_Arg("HFeat"), // Imm(Hhf),
K_Arg("KerOut", KER_ARG_TILE),
K_Arg("Buffer", KER_ARG),
C_Arg("Model"),
C_Arg("ModelSize")
)
)
),
KerArgs(3,
KerArgPart("KerIn", OBJ_IN_DB, Whf, Whf-WEstim, Hhf, Hhf, HoGFeatSize, 0, OBJ_CONSTRAINTS_ONEPREFTILE, 1, "HoGFeatIn", 0),
KerArgPart("KerOut", OBJ_OUT_DB, Whf-WEstim+1, Whf-WEstim, Hhf-HEstim+1, Hhf-HEstim+1, EstimSize, 0, 0, 0, "Out", 0),
KerArg ("Buffer", OBJ_BUFFER_NTILED, WEstim, HEstim, HoGFeatSize, 0, 0, 0, "", 0)
)
);
CloseKernelGroup();
UserKernelGroup(Name,
CArgs(6,
TCArg("uint16_t * __restrict__", "HoGFeatIn"),
TCArg("uint16_t ** __restrict__", "HoGFeatCols"),
TCArg("uint32_t", "HFeat"),
TCArg("uint8_t * __restrict__", "Out"),
TCArg("HoGWeakPredictor_T * __restrict__", "Model"),
TCArg("uint32_t", "ModelSize")
),
Calls(2,
UserKernelCall(AppendNames("Prime", Name), LOC_GROUP,
Bindings(6, C_Arg("HoGFeatIn"), C_Arg("HoGFeatCols"), C_Arg("HFeat"), C_Arg("Out"), C_Arg("Model"), C_Arg("ModelSize"))
),
UserKernelCall(AppendNames("Body", Name), LOC_GROUP,
Bindings(6, C_ArgPlusImmOffset("HoGFeatIn", WEstim*BlockSize*BlockSize*BinsPerCell),
C_Arg("HoGFeatCols"), C_Arg("HFeat"), C_ArgPlusImmOffset("Out", 1), C_Arg("Model"), C_Arg("ModelSize"))
)
)
);
}
void GenerateWeakHOGEstimatorBis(
char *Name,
unsigned int W, /* Image width */
unsigned int H, /* Image Height */
unsigned int CellSize, /* Cell is [CellSize x CellSize] pixels */
unsigned int BlockSize, /* Block is [BlockSize x BlockSize] Cells */
unsigned int BlockOverlap, /* Number Cells in common between 2 adjacent blocks */
unsigned int BinsPerCell, /* Number of bins for a cell */
unsigned int WEstimPix, /* Width of the estimation window, in pixels */
unsigned int HEstimPix, /* Height of the estimation window, in pixels */
unsigned int EstimSize, /* Size of estimation result per estimation window, in bytes */
unsigned int NWeakEstim /* Number of weak estimators in the model */
)
{
unsigned int Kh = ((H-2)/CellSize - BlockSize)/(BlockSize - BlockOverlap);
unsigned int Ha = (Kh*(BlockSize - BlockOverlap) + BlockSize) * CellSize + 2;
unsigned int Kw = ((W-2)/CellSize - BlockSize)/(BlockSize - BlockOverlap);
unsigned int Wa = (Kw*(BlockSize - BlockOverlap) + BlockSize) * CellSize + 2;
unsigned int HoGFeatSize = BlockSize*BlockSize*BinsPerCell*sizeof(unsigned short int);
unsigned int Whf = 1 + Kw; /* Width in HoG features */
unsigned int Hhf = 1 + Kh; /* Height in HoG features */
unsigned int KhE = ((HEstimPix)/CellSize - BlockSize)/(BlockSize - BlockOverlap);
unsigned int KwE = ((WEstimPix)/CellSize - BlockSize)/(BlockSize - BlockOverlap);
unsigned int WEstim = 1 + KwE; /* Width of Estim window in HoG Features */
unsigned int HEstim = 1 + KhE; /* Height of Estim window in HoG Features */
if (W<WEstimPix || H<HEstimPix) GenTilingError("Image size [%d x %d] must be larger than estimation window [%d x %d]\n", W, H, WEstimPix, HEstimPix);
printf("Generating HOG Based Estimator, Weak Estimator Version:\n");
printf("\tHOG Features [%3d x %3d] from Image [%3d x %3d]\n", Whf, Hhf, W, H);
printf("\tEstimation Window: [%3d x %3d] pixels or [%3d x %3d] HOG features\n", WEstimPix, HEstimPix, WEstim, HEstim);
printf("\tEstimation output: [%3d x %3d]\n", (Whf-WEstim)+1, (Hhf-HEstim)+1);
printf("\tWeak estimators: [%4d ]\n", NWeakEstim);
OpenKernelGroup(Name);
UserKernel(AppendNames("Prime", Name),
KernelDimensions(0, WEstim, Hhf, 0),
KernelIterationOrder(KER_DIM2, KER_TILE),
TILE_VER,
CArgs(5,
TCArg("uint16_t * __restrict__", "HoGFeatIn"),
TCArg("uint16_t ** __restrict__", "HoGFeatCols"),
TCArg("uint32_t", "HFeat"),
TCArg("HoGWeakPredictorBis_T * __restrict__", "Model"),
TCArg("uint32_t", "ModelSize")
),
Calls(2,
Call("KerReadHoGFeatCol", LOC_INNER_LOOP,
Bindings(6,
K_Arg("KerIn", KER_ARG_TILE),
K_Arg("KerIn", KER_ARG_TILE_H),
Imm(BlockSize*BlockSize*BinsPerCell),
Imm(WEstim),
C_Arg("HoGFeatCols"),
K_Arg("KerIn", KER_ARG_TILEINDEX)
)
),
Call("KerWeakEstimateAllWindows", LOC_EPILOG,
Bindings(7,
C_Arg("HoGFeatCols"),
Imm(-1),
Imm(HEstim),
C_Arg("HFeat"), // Imm(Hhf),
Imm(BlockSize*BlockSize*BinsPerCell),
C_Arg("Model"),
C_Arg("ModelSize")
)
)
),
KerArgs(1, KerArgPart("KerIn", OBJ_IN_DB, Whf, WEstim, Hhf, Hhf, HoGFeatSize, 0, OBJ_CONSTRAINTS_ONEPREFTILE, 1, "HoGFeatIn", 0))
);
UserKernel(AppendNames("Body", Name),
KernelDimensions(0, Whf-WEstim, Hhf, 0),
KernelIterationOrder(KER_DIM2, KER_TILE),
TILE_VER,
CArgs(5,
TCArg("uint16_t * __restrict__", "HoGFeatIn"),
TCArg("uint16_t ** __restrict__", "HoGFeatCols"),
TCArg("uint32_t", "HFeat"),
TCArg("HoGWeakPredictorBis_T * __restrict__", "Model"),
TCArg("uint32_t", "ModelSize")
),
Calls(2,
Call("KerReadHoGFeatCol", LOC_INNER_LOOP,
Bindings(6,
K_Arg("KerIn", KER_ARG_TILE),
K_Arg("KerIn", KER_ARG_TILE_H),
Imm(BlockSize*BlockSize*BinsPerCell),
Imm(WEstim),
C_Arg("HoGFeatCols"),
Imm(WEstim)
)
),
Call("KerWeakEstimateAllWindows", LOC_INNER_LOOP,
Bindings(7,
C_Arg("HoGFeatCols"),
K_Arg("KerIn", KER_ARG_TILEINDEX),
Imm(HEstim),
C_Arg("HFeat"), // Imm(Hhf),
Imm(BlockSize*BlockSize*BinsPerCell),
C_Arg("Model"),
C_Arg("ModelSize")
)
)
),
KerArgs(1, KerArgPart("KerIn", OBJ_IN_DB, Whf, Whf-WEstim, Hhf, Hhf, HoGFeatSize, 0, OBJ_CONSTRAINTS_ONEPREFTILE, 1, "HoGFeatIn", 0))
);
CloseKernelGroup();
UserKernelGroup(Name,
CArgs(5,
TCArg("uint16_t * __restrict__", "HoGFeatIn"),
TCArg("uint16_t ** __restrict__", "HoGFeatCols"),
TCArg("uint32_t", "HFeat"),
TCArg("HoGWeakPredictorBis_T * __restrict__", "Model"),
TCArg("uint32_t", "ModelSize")
),
Calls(2,
UserKernelCall(AppendNames("Prime", Name), LOC_GROUP,
Bindings(5, C_Arg("HoGFeatIn"), C_Arg("HoGFeatCols"), C_Arg("HFeat"), C_Arg("Model"), C_Arg("ModelSize"))
),
UserKernelCall(AppendNames("Body", Name), LOC_GROUP,
Bindings(5, C_ArgPlusImmOffset("HoGFeatIn", WEstim*BlockSize*BlockSize*BinsPerCell),
C_Arg("HoGFeatCols"), C_Arg("HFeat"), C_Arg("Model"), C_Arg("ModelSize"))
)
)
);
}
void HOGEstimDependencies()
{
SetUsedFilesNames(0, 2, "HoGBasicKernels.h", "HoGEstimBasicKernels.h");
}
void HOGEstimConfiguration(unsigned int L1Memory)
{
SetInlineMode(ALWAYS_INLINE);
//SetInlineMode(NEVER_INLINE);
SetSymbolNames("HOG_L1_Memory", "HOG_L2_Memory", "HOG_KernelDescr", "HOG_KernelArgs");
SetSymbolDynamics();
SetKernelOpts(KER_OPT_NONE, KER_OPT_BUFFER_PROMOTE);
HOGEstimDependencies();
SetGeneratedFilesNames("HoGEstimKernelsInit.c", "HoGEstimKernelsInit.h", "HoGEstimKernels.c", "HoGEstimKernels.h");
SetL1MemorySize(L1Memory);
}
| 35.891304 | 175 | 0.652382 | [
"model",
"3d"
] |
65868294403c02532cf79d0e3a3612a446eb13da | 20,712 | h | C | llvm/include/llvm/Bitcode/BitstreamReader.h | clairechingching/ScaffCC | 737ae90f85d9fe79819d66219747d27efa4fa5b9 | [
"BSD-2-Clause"
] | 3 | 2019-02-12T04:14:39.000Z | 2020-11-05T08:46:20.000Z | llvm/include/llvm/Bitcode/BitstreamReader.h | clairechingching/ScaffCC | 737ae90f85d9fe79819d66219747d27efa4fa5b9 | [
"BSD-2-Clause"
] | null | null | null | llvm/include/llvm/Bitcode/BitstreamReader.h | clairechingching/ScaffCC | 737ae90f85d9fe79819d66219747d27efa4fa5b9 | [
"BSD-2-Clause"
] | 1 | 2020-11-04T06:38:51.000Z | 2020-11-04T06:38:51.000Z | //===- BitstreamReader.h - Low-level bitstream reader interface -*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This header defines the BitstreamReader class. This class can be used to
// read an arbitrary bitstream, regardless of its contents.
//
//===----------------------------------------------------------------------===//
#ifndef BITSTREAM_READER_H
#define BITSTREAM_READER_H
#include "llvm/ADT/OwningPtr.h"
#include "llvm/Bitcode/BitCodes.h"
#include "llvm/Support/Endian.h"
#include "llvm/Support/StreamableMemoryObject.h"
#include <climits>
#include <string>
#include <vector>
namespace llvm {
class Deserializer;
class BitstreamReader {
public:
/// BlockInfo - This contains information emitted to BLOCKINFO_BLOCK blocks.
/// These describe abbreviations that all blocks of the specified ID inherit.
struct BlockInfo {
unsigned BlockID;
std::vector<BitCodeAbbrev*> Abbrevs;
std::string Name;
std::vector<std::pair<unsigned, std::string> > RecordNames;
};
private:
OwningPtr<StreamableMemoryObject> BitcodeBytes;
std::vector<BlockInfo> BlockInfoRecords;
/// IgnoreBlockInfoNames - This is set to true if we don't care about the
/// block/record name information in the BlockInfo block. Only llvm-bcanalyzer
/// uses this.
bool IgnoreBlockInfoNames;
BitstreamReader(const BitstreamReader&); // DO NOT IMPLEMENT
void operator=(const BitstreamReader&); // DO NOT IMPLEMENT
public:
BitstreamReader() : IgnoreBlockInfoNames(true) {
}
BitstreamReader(const unsigned char *Start, const unsigned char *End) {
IgnoreBlockInfoNames = true;
init(Start, End);
}
BitstreamReader(StreamableMemoryObject *bytes) {
BitcodeBytes.reset(bytes);
}
void init(const unsigned char *Start, const unsigned char *End) {
assert(((End-Start) & 3) == 0 &&"Bitcode stream not a multiple of 4 bytes");
BitcodeBytes.reset(getNonStreamedMemoryObject(Start, End));
}
StreamableMemoryObject &getBitcodeBytes() { return *BitcodeBytes; }
~BitstreamReader() {
// Free the BlockInfoRecords.
while (!BlockInfoRecords.empty()) {
BlockInfo &Info = BlockInfoRecords.back();
// Free blockinfo abbrev info.
for (unsigned i = 0, e = static_cast<unsigned>(Info.Abbrevs.size());
i != e; ++i)
Info.Abbrevs[i]->dropRef();
BlockInfoRecords.pop_back();
}
}
/// CollectBlockInfoNames - This is called by clients that want block/record
/// name information.
void CollectBlockInfoNames() { IgnoreBlockInfoNames = false; }
bool isIgnoringBlockInfoNames() { return IgnoreBlockInfoNames; }
//===--------------------------------------------------------------------===//
// Block Manipulation
//===--------------------------------------------------------------------===//
/// hasBlockInfoRecords - Return true if we've already read and processed the
/// block info block for this Bitstream. We only process it for the first
/// cursor that walks over it.
bool hasBlockInfoRecords() const { return !BlockInfoRecords.empty(); }
/// getBlockInfo - If there is block info for the specified ID, return it,
/// otherwise return null.
const BlockInfo *getBlockInfo(unsigned BlockID) const {
// Common case, the most recent entry matches BlockID.
if (!BlockInfoRecords.empty() && BlockInfoRecords.back().BlockID == BlockID)
return &BlockInfoRecords.back();
for (unsigned i = 0, e = static_cast<unsigned>(BlockInfoRecords.size());
i != e; ++i)
if (BlockInfoRecords[i].BlockID == BlockID)
return &BlockInfoRecords[i];
return 0;
}
BlockInfo &getOrCreateBlockInfo(unsigned BlockID) {
if (const BlockInfo *BI = getBlockInfo(BlockID))
return *const_cast<BlockInfo*>(BI);
// Otherwise, add a new record.
BlockInfoRecords.push_back(BlockInfo());
BlockInfoRecords.back().BlockID = BlockID;
return BlockInfoRecords.back();
}
};
class BitstreamCursor {
friend class Deserializer;
BitstreamReader *BitStream;
size_t NextChar;
/// CurWord - This is the current data we have pulled from the stream but have
/// not returned to the client.
uint32_t CurWord;
/// BitsInCurWord - This is the number of bits in CurWord that are valid. This
/// is always from [0...31] inclusive.
unsigned BitsInCurWord;
// CurCodeSize - This is the declared size of code values used for the current
// block, in bits.
unsigned CurCodeSize;
/// CurAbbrevs - Abbrevs installed at in this block.
std::vector<BitCodeAbbrev*> CurAbbrevs;
struct Block {
unsigned PrevCodeSize;
std::vector<BitCodeAbbrev*> PrevAbbrevs;
explicit Block(unsigned PCS) : PrevCodeSize(PCS) {}
};
/// BlockScope - This tracks the codesize of parent blocks.
SmallVector<Block, 8> BlockScope;
public:
BitstreamCursor() : BitStream(0), NextChar(0) {
}
BitstreamCursor(const BitstreamCursor &RHS) : BitStream(0), NextChar(0) {
operator=(RHS);
}
explicit BitstreamCursor(BitstreamReader &R) : BitStream(&R) {
NextChar = 0;
CurWord = 0;
BitsInCurWord = 0;
CurCodeSize = 2;
}
void init(BitstreamReader &R) {
freeState();
BitStream = &R;
NextChar = 0;
CurWord = 0;
BitsInCurWord = 0;
CurCodeSize = 2;
}
~BitstreamCursor() {
freeState();
}
void operator=(const BitstreamCursor &RHS) {
freeState();
BitStream = RHS.BitStream;
NextChar = RHS.NextChar;
CurWord = RHS.CurWord;
BitsInCurWord = RHS.BitsInCurWord;
CurCodeSize = RHS.CurCodeSize;
// Copy abbreviations, and bump ref counts.
CurAbbrevs = RHS.CurAbbrevs;
for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
i != e; ++i)
CurAbbrevs[i]->addRef();
// Copy block scope and bump ref counts.
BlockScope = RHS.BlockScope;
for (unsigned S = 0, e = static_cast<unsigned>(BlockScope.size());
S != e; ++S) {
std::vector<BitCodeAbbrev*> &Abbrevs = BlockScope[S].PrevAbbrevs;
for (unsigned i = 0, e = static_cast<unsigned>(Abbrevs.size());
i != e; ++i)
Abbrevs[i]->addRef();
}
}
void freeState() {
// Free all the Abbrevs.
for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
i != e; ++i)
CurAbbrevs[i]->dropRef();
CurAbbrevs.clear();
// Free all the Abbrevs in the block scope.
for (unsigned S = 0, e = static_cast<unsigned>(BlockScope.size());
S != e; ++S) {
std::vector<BitCodeAbbrev*> &Abbrevs = BlockScope[S].PrevAbbrevs;
for (unsigned i = 0, e = static_cast<unsigned>(Abbrevs.size());
i != e; ++i)
Abbrevs[i]->dropRef();
}
BlockScope.clear();
}
/// GetAbbrevIDWidth - Return the number of bits used to encode an abbrev #.
unsigned GetAbbrevIDWidth() const { return CurCodeSize; }
bool isEndPos(size_t pos) {
return BitStream->getBitcodeBytes().isObjectEnd(static_cast<uint64_t>(pos));
}
bool canSkipToPos(size_t pos) const {
// pos can be skipped to if it is a valid address or one byte past the end.
return pos == 0 || BitStream->getBitcodeBytes().isValidAddress(
static_cast<uint64_t>(pos - 1));
}
unsigned char getByte(size_t pos) {
uint8_t byte = -1;
BitStream->getBitcodeBytes().readByte(pos, &byte);
return byte;
}
uint32_t getWord(size_t pos) {
uint8_t buf[sizeof(uint32_t)];
memset(buf, 0xFF, sizeof(buf));
BitStream->getBitcodeBytes().readBytes(pos,
sizeof(buf),
buf,
NULL);
return *reinterpret_cast<support::ulittle32_t *>(buf);
}
bool AtEndOfStream() {
return isEndPos(NextChar) && BitsInCurWord == 0;
}
/// GetCurrentBitNo - Return the bit # of the bit we are reading.
uint64_t GetCurrentBitNo() const {
return NextChar*CHAR_BIT - BitsInCurWord;
}
BitstreamReader *getBitStreamReader() {
return BitStream;
}
const BitstreamReader *getBitStreamReader() const {
return BitStream;
}
/// JumpToBit - Reset the stream to the specified bit number.
void JumpToBit(uint64_t BitNo) {
uintptr_t ByteNo = uintptr_t(BitNo/8) & ~3;
uintptr_t WordBitNo = uintptr_t(BitNo) & 31;
assert(canSkipToPos(ByteNo) && "Invalid location");
// Move the cursor to the right word.
NextChar = ByteNo;
BitsInCurWord = 0;
CurWord = 0;
// Skip over any bits that are already consumed.
if (WordBitNo)
Read(static_cast<unsigned>(WordBitNo));
}
uint32_t Read(unsigned NumBits) {
assert(NumBits <= 32 && "Cannot return more than 32 bits!");
// If the field is fully contained by CurWord, return it quickly.
if (BitsInCurWord >= NumBits) {
uint32_t R = CurWord & ((1U << NumBits)-1);
CurWord >>= NumBits;
BitsInCurWord -= NumBits;
return R;
}
// If we run out of data, stop at the end of the stream.
if (isEndPos(NextChar)) {
CurWord = 0;
BitsInCurWord = 0;
return 0;
}
unsigned R = CurWord;
// Read the next word from the stream.
CurWord = getWord(NextChar);
NextChar += 4;
// Extract NumBits-BitsInCurWord from what we just read.
unsigned BitsLeft = NumBits-BitsInCurWord;
// Be careful here, BitsLeft is in the range [1..32] inclusive.
R |= (CurWord & (~0U >> (32-BitsLeft))) << BitsInCurWord;
// BitsLeft bits have just been used up from CurWord.
if (BitsLeft != 32)
CurWord >>= BitsLeft;
else
CurWord = 0;
BitsInCurWord = 32-BitsLeft;
return R;
}
uint64_t Read64(unsigned NumBits) {
if (NumBits <= 32) return Read(NumBits);
uint64_t V = Read(32);
return V | (uint64_t)Read(NumBits-32) << 32;
}
uint32_t ReadVBR(unsigned NumBits) {
uint32_t Piece = Read(NumBits);
if ((Piece & (1U << (NumBits-1))) == 0)
return Piece;
uint32_t Result = 0;
unsigned NextBit = 0;
while (1) {
Result |= (Piece & ((1U << (NumBits-1))-1)) << NextBit;
if ((Piece & (1U << (NumBits-1))) == 0)
return Result;
NextBit += NumBits-1;
Piece = Read(NumBits);
}
}
// ReadVBR64 - Read a VBR that may have a value up to 64-bits in size. The
// chunk size of the VBR must still be <= 32 bits though.
uint64_t ReadVBR64(unsigned NumBits) {
uint32_t Piece = Read(NumBits);
if ((Piece & (1U << (NumBits-1))) == 0)
return uint64_t(Piece);
uint64_t Result = 0;
unsigned NextBit = 0;
while (1) {
Result |= uint64_t(Piece & ((1U << (NumBits-1))-1)) << NextBit;
if ((Piece & (1U << (NumBits-1))) == 0)
return Result;
NextBit += NumBits-1;
Piece = Read(NumBits);
}
}
void SkipToWord() {
BitsInCurWord = 0;
CurWord = 0;
}
unsigned ReadCode() {
return Read(CurCodeSize);
}
// Block header:
// [ENTER_SUBBLOCK, blockid, newcodelen, <align4bytes>, blocklen]
/// ReadSubBlockID - Having read the ENTER_SUBBLOCK code, read the BlockID for
/// the block.
unsigned ReadSubBlockID() {
return ReadVBR(bitc::BlockIDWidth);
}
/// SkipBlock - Having read the ENTER_SUBBLOCK abbrevid and a BlockID, skip
/// over the body of this block. If the block record is malformed, return
/// true.
bool SkipBlock() {
// Read and ignore the codelen value. Since we are skipping this block, we
// don't care what code widths are used inside of it.
ReadVBR(bitc::CodeLenWidth);
SkipToWord();
unsigned NumWords = Read(bitc::BlockSizeWidth);
// Check that the block wasn't partially defined, and that the offset isn't
// bogus.
size_t SkipTo = NextChar + NumWords*4;
if (AtEndOfStream() || !canSkipToPos(SkipTo))
return true;
NextChar = SkipTo;
return false;
}
/// EnterSubBlock - Having read the ENTER_SUBBLOCK abbrevid, enter
/// the block, and return true if the block is valid.
bool EnterSubBlock(unsigned BlockID, unsigned *NumWordsP = 0) {
// Save the current block's state on BlockScope.
BlockScope.push_back(Block(CurCodeSize));
BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
// Add the abbrevs specific to this block to the CurAbbrevs list.
if (const BitstreamReader::BlockInfo *Info =
BitStream->getBlockInfo(BlockID)) {
for (unsigned i = 0, e = static_cast<unsigned>(Info->Abbrevs.size());
i != e; ++i) {
CurAbbrevs.push_back(Info->Abbrevs[i]);
CurAbbrevs.back()->addRef();
}
}
// Get the codesize of this block.
CurCodeSize = ReadVBR(bitc::CodeLenWidth);
SkipToWord();
unsigned NumWords = Read(bitc::BlockSizeWidth);
if (NumWordsP) *NumWordsP = NumWords;
// Validate that this block is sane.
if (CurCodeSize == 0 || AtEndOfStream())
return true;
return false;
}
bool ReadBlockEnd() {
if (BlockScope.empty()) return true;
// Block tail:
// [END_BLOCK, <align4bytes>]
SkipToWord();
PopBlockScope();
return false;
}
private:
void PopBlockScope() {
CurCodeSize = BlockScope.back().PrevCodeSize;
// Delete abbrevs from popped scope.
for (unsigned i = 0, e = static_cast<unsigned>(CurAbbrevs.size());
i != e; ++i)
CurAbbrevs[i]->dropRef();
BlockScope.back().PrevAbbrevs.swap(CurAbbrevs);
BlockScope.pop_back();
}
//===--------------------------------------------------------------------===//
// Record Processing
//===--------------------------------------------------------------------===//
private:
void ReadAbbreviatedLiteral(const BitCodeAbbrevOp &Op,
SmallVectorImpl<uint64_t> &Vals) {
assert(Op.isLiteral() && "Not a literal");
// If the abbrev specifies the literal value to use, use it.
Vals.push_back(Op.getLiteralValue());
}
void ReadAbbreviatedField(const BitCodeAbbrevOp &Op,
SmallVectorImpl<uint64_t> &Vals) {
assert(!Op.isLiteral() && "Use ReadAbbreviatedLiteral for literals!");
// Decode the value as we are commanded.
switch (Op.getEncoding()) {
default: llvm_unreachable("Unknown encoding!");
case BitCodeAbbrevOp::Fixed:
Vals.push_back(Read((unsigned)Op.getEncodingData()));
break;
case BitCodeAbbrevOp::VBR:
Vals.push_back(ReadVBR64((unsigned)Op.getEncodingData()));
break;
case BitCodeAbbrevOp::Char6:
Vals.push_back(BitCodeAbbrevOp::DecodeChar6(Read(6)));
break;
}
}
public:
/// getAbbrev - Return the abbreviation for the specified AbbrevId.
const BitCodeAbbrev *getAbbrev(unsigned AbbrevID) {
unsigned AbbrevNo = AbbrevID-bitc::FIRST_APPLICATION_ABBREV;
assert(AbbrevNo < CurAbbrevs.size() && "Invalid abbrev #!");
return CurAbbrevs[AbbrevNo];
}
unsigned ReadRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals,
const char **BlobStart = 0, unsigned *BlobLen = 0) {
if (AbbrevID == bitc::UNABBREV_RECORD) {
unsigned Code = ReadVBR(6);
unsigned NumElts = ReadVBR(6);
for (unsigned i = 0; i != NumElts; ++i)
Vals.push_back(ReadVBR64(6));
return Code;
}
const BitCodeAbbrev *Abbv = getAbbrev(AbbrevID);
for (unsigned i = 0, e = Abbv->getNumOperandInfos(); i != e; ++i) {
const BitCodeAbbrevOp &Op = Abbv->getOperandInfo(i);
if (Op.isLiteral()) {
ReadAbbreviatedLiteral(Op, Vals);
} else if (Op.getEncoding() == BitCodeAbbrevOp::Array) {
// Array case. Read the number of elements as a vbr6.
unsigned NumElts = ReadVBR(6);
// Get the element encoding.
assert(i+2 == e && "array op not second to last?");
const BitCodeAbbrevOp &EltEnc = Abbv->getOperandInfo(++i);
// Read all the elements.
for (; NumElts; --NumElts)
ReadAbbreviatedField(EltEnc, Vals);
} else if (Op.getEncoding() == BitCodeAbbrevOp::Blob) {
// Blob case. Read the number of bytes as a vbr6.
unsigned NumElts = ReadVBR(6);
SkipToWord(); // 32-bit alignment
// Figure out where the end of this blob will be including tail padding.
size_t NewEnd = NextChar+((NumElts+3)&~3);
// If this would read off the end of the bitcode file, just set the
// record to empty and return.
if (!canSkipToPos(NewEnd)) {
Vals.append(NumElts, 0);
NextChar = BitStream->getBitcodeBytes().getExtent();
break;
}
// Otherwise, read the number of bytes. If we can return a reference to
// the data, do so to avoid copying it.
if (BlobStart) {
*BlobStart = (const char*)BitStream->getBitcodeBytes().getPointer(
NextChar, NumElts);
*BlobLen = NumElts;
} else {
for (; NumElts; ++NextChar, --NumElts)
Vals.push_back(getByte(NextChar));
}
// Skip over tail padding.
NextChar = NewEnd;
} else {
ReadAbbreviatedField(Op, Vals);
}
}
unsigned Code = (unsigned)Vals[0];
Vals.erase(Vals.begin());
return Code;
}
unsigned ReadRecord(unsigned AbbrevID, SmallVectorImpl<uint64_t> &Vals,
const char *&BlobStart, unsigned &BlobLen) {
return ReadRecord(AbbrevID, Vals, &BlobStart, &BlobLen);
}
//===--------------------------------------------------------------------===//
// Abbrev Processing
//===--------------------------------------------------------------------===//
void ReadAbbrevRecord() {
BitCodeAbbrev *Abbv = new BitCodeAbbrev();
unsigned NumOpInfo = ReadVBR(5);
for (unsigned i = 0; i != NumOpInfo; ++i) {
bool IsLiteral = Read(1) ? true : false;
if (IsLiteral) {
Abbv->Add(BitCodeAbbrevOp(ReadVBR64(8)));
continue;
}
BitCodeAbbrevOp::Encoding E = (BitCodeAbbrevOp::Encoding)Read(3);
if (BitCodeAbbrevOp::hasEncodingData(E))
Abbv->Add(BitCodeAbbrevOp(E, ReadVBR64(5)));
else
Abbv->Add(BitCodeAbbrevOp(E));
}
CurAbbrevs.push_back(Abbv);
}
public:
bool ReadBlockInfoBlock() {
// If this is the second stream to get to the block info block, skip it.
if (BitStream->hasBlockInfoRecords())
return SkipBlock();
if (EnterSubBlock(bitc::BLOCKINFO_BLOCK_ID)) return true;
SmallVector<uint64_t, 64> Record;
BitstreamReader::BlockInfo *CurBlockInfo = 0;
// Read all the records for this module.
while (1) {
unsigned Code = ReadCode();
if (Code == bitc::END_BLOCK)
return ReadBlockEnd();
if (Code == bitc::ENTER_SUBBLOCK) {
ReadSubBlockID();
if (SkipBlock()) return true;
continue;
}
// Read abbrev records, associate them with CurBID.
if (Code == bitc::DEFINE_ABBREV) {
if (!CurBlockInfo) return true;
ReadAbbrevRecord();
// ReadAbbrevRecord installs the abbrev in CurAbbrevs. Move it to the
// appropriate BlockInfo.
BitCodeAbbrev *Abbv = CurAbbrevs.back();
CurAbbrevs.pop_back();
CurBlockInfo->Abbrevs.push_back(Abbv);
continue;
}
// Read a record.
Record.clear();
switch (ReadRecord(Code, Record)) {
default: break; // Default behavior, ignore unknown content.
case bitc::BLOCKINFO_CODE_SETBID:
if (Record.size() < 1) return true;
CurBlockInfo = &BitStream->getOrCreateBlockInfo((unsigned)Record[0]);
break;
case bitc::BLOCKINFO_CODE_BLOCKNAME: {
if (!CurBlockInfo) return true;
if (BitStream->isIgnoringBlockInfoNames()) break; // Ignore name.
std::string Name;
for (unsigned i = 0, e = Record.size(); i != e; ++i)
Name += (char)Record[i];
CurBlockInfo->Name = Name;
break;
}
case bitc::BLOCKINFO_CODE_SETRECORDNAME: {
if (!CurBlockInfo) return true;
if (BitStream->isIgnoringBlockInfoNames()) break; // Ignore name.
std::string Name;
for (unsigned i = 1, e = Record.size(); i != e; ++i)
Name += (char)Record[i];
CurBlockInfo->RecordNames.push_back(std::make_pair((unsigned)Record[0],
Name));
break;
}
}
}
}
};
} // End llvm namespace
#endif
| 30.959641 | 80 | 0.609888 | [
"vector"
] |
6587a8a455bab61112f17168416730e88aef8cb0 | 17,685 | h | C | src/plugins/map/map.h | mahdi1001/vpp | 2f54c27f7fd0d2c24e7d6b1d48809e8b58ec1abf | [
"Apache-2.0"
] | null | null | null | src/plugins/map/map.h | mahdi1001/vpp | 2f54c27f7fd0d2c24e7d6b1d48809e8b58ec1abf | [
"Apache-2.0"
] | null | null | null | src/plugins/map/map.h | mahdi1001/vpp | 2f54c27f7fd0d2c24e7d6b1d48809e8b58ec1abf | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2015 Cisco and/or its affiliates.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdbool.h>
#include <vppinfra/error.h>
#include <vnet/vnet.h>
#include <vnet/ip/ip.h>
#include <vlib/vlib.h>
#include <vnet/fib/fib_types.h>
#include <vnet/fib/ip4_fib.h>
#include <vnet/adj/adj.h>
#include <map/map_dpo.h>
#include <vnet/dpo/load_balance.h>
#define MAP_SKIP_IP6_LOOKUP 1
int map_create_domain (ip4_address_t * ip4_prefix, u8 ip4_prefix_len,
ip6_address_t * ip6_prefix, u8 ip6_prefix_len,
ip6_address_t * ip6_src, u8 ip6_src_len,
u8 ea_bits_len, u8 psid_offset, u8 psid_length,
u32 * map_domain_index, u16 mtu, u8 flags);
int map_delete_domain (u32 map_domain_index);
int map_add_del_psid (u32 map_domain_index, u16 psid, ip6_address_t * tep,
u8 is_add);
u8 *format_map_trace (u8 * s, va_list * args);
typedef enum
{
MAP_DOMAIN_PREFIX = 1 << 0,
MAP_DOMAIN_TRANSLATION = 1 << 1, // The domain uses MAP-T
MAP_DOMAIN_RFC6052 = 1 << 2,
} __attribute__ ((__packed__)) map_domain_flags_e;
/**
* IP4 reassembly logic:
* One virtually reassembled flow requires a map_ip4_reass_t structure in order
* to keep the first-fragment port number and, optionally, cache out of sequence
* packets.
* There are up to MAP_IP4_REASS_MAX_REASSEMBLY such structures.
* When in use, those structures are stored in a hash table of MAP_IP4_REASS_BUCKETS buckets.
* When a new structure needs to be used, it is allocated from available ones.
* If there is no structure available, the oldest in use is selected and used if and
* only if it was first allocated more than MAP_IP4_REASS_LIFETIME seconds ago.
* In case no structure can be allocated, the fragment is dropped.
*/
#define MAP_IP4_REASS_LIFETIME_DEFAULT (100) /* ms */
#define MAP_IP4_REASS_HT_RATIO_DEFAULT (1.0)
#define MAP_IP4_REASS_POOL_SIZE_DEFAULT 1024 // Number of reassembly structures
#define MAP_IP4_REASS_BUFFERS_DEFAULT 2048
#define MAP_IP4_REASS_MAX_FRAGMENTS_PER_REASSEMBLY 5 // Number of fragment per reassembly
#define MAP_IP6_REASS_LIFETIME_DEFAULT (100) /* ms */
#define MAP_IP6_REASS_HT_RATIO_DEFAULT (1.0)
#define MAP_IP6_REASS_POOL_SIZE_DEFAULT 1024 // Number of reassembly structures
#define MAP_IP6_REASS_BUFFERS_DEFAULT 2048
#define MAP_IP6_REASS_MAX_FRAGMENTS_PER_REASSEMBLY 5
#define MAP_IP6_REASS_COUNT_BYTES
#define MAP_IP4_REASS_COUNT_BYTES
//#define IP6_MAP_T_OVERRIDE_TOS 0
/*
* This structure _MUST_ be no larger than a single cache line (64 bytes).
* If more space is needed make a union of ip6_prefix and *rules, those are mutually exclusive.
*/
typedef struct
{
/* Required for pool_get_aligned */
CLIB_CACHE_LINE_ALIGN_MARK (cacheline0);
ip6_address_t ip6_src;
ip6_address_t ip6_prefix;
ip6_address_t *rules;
u32 suffix_mask;
ip4_address_t ip4_prefix;
u16 psid_mask;
u16 mtu;
map_domain_flags_e flags;
u8 ip6_prefix_len;
u8 ip6_src_len;
u8 ea_bits_len;
u8 psid_offset;
u8 psid_length;
/* helpers */
u8 psid_shift;
u8 suffix_shift;
u8 ea_shift;
/* not used by forwarding */
u8 ip4_prefix_len;
} map_domain_t;
STATIC_ASSERT ((sizeof (map_domain_t) <= CLIB_CACHE_LINE_BYTES),
"MAP domain fits in one cacheline");
#define MAP_REASS_INDEX_NONE ((u16)0xffff)
/*
* Hash key, padded out to 16 bytes for fast compare
*/
/* *INDENT-OFF* */
typedef union {
CLIB_PACKED (struct {
ip4_address_t src;
ip4_address_t dst;
u16 fragment_id;
u8 protocol;
});
u64 as_u64[2];
u32 as_u32[4];
} map_ip4_reass_key_t;
/* *INDENT-ON* */
typedef struct
{
map_ip4_reass_key_t key;
f64 ts;
#ifdef MAP_IP4_REASS_COUNT_BYTES
u16 expected_total;
u16 forwarded;
#endif
i32 port;
u16 bucket;
u16 bucket_next;
u16 fifo_prev;
u16 fifo_next;
u32 fragments[MAP_IP4_REASS_MAX_FRAGMENTS_PER_REASSEMBLY];
} map_ip4_reass_t;
/*
* MAP domain counters
*/
typedef enum
{
/* Simple counters */
MAP_DOMAIN_IPV4_FRAGMENT = 0,
/* Combined counters */
MAP_DOMAIN_COUNTER_RX = 0,
MAP_DOMAIN_COUNTER_TX,
MAP_N_DOMAIN_COUNTER
} map_domain_counter_t;
/*
* main_main_t
*/
/* *INDENT-OFF* */
typedef union {
CLIB_PACKED (struct {
ip6_address_t src;
ip6_address_t dst;
u32 fragment_id;
u8 protocol;
});
u64 as_u64[5];
u32 as_u32[10];
} map_ip6_reass_key_t;
/* *INDENT-OFF* */
typedef struct {
u32 pi; //Cached packet or ~0
u16 next_data_offset; //The data offset of the additional 20 bytes or ~0
u8 next_data_len; //Number of bytes ready to be copied (20 if not last fragment)
u8 next_data[20]; //The 20 additional bytes
} map_ip6_fragment_t;
typedef struct {
map_ip6_reass_key_t key;
f64 ts;
#ifdef MAP_IP6_REASS_COUNT_BYTES
u16 expected_total;
u16 forwarded;
#endif
u16 bucket; //What hash bucket this element is linked in
u16 bucket_next;
u16 fifo_prev;
u16 fifo_next;
ip4_header_t ip4_header;
map_ip6_fragment_t fragments[MAP_IP6_REASS_MAX_FRAGMENTS_PER_REASSEMBLY];
} map_ip6_reass_t;
#ifdef MAP_SKIP_IP6_LOOKUP
/**
* A pre-resolved next-hop
*/
typedef struct map_main_pre_resolved_t_
{
/**
* Linkage into the FIB graph
*/
fib_node_t node;
/**
* The FIB entry index of the next-hop
*/
fib_node_index_t fei;
/**
* This object sibling index on the FIB entry's child dependency list
*/
u32 sibling;
/**
* The Load-balance object index to use to forward
*/
dpo_id_t dpo;
} map_main_pre_resolved_t;
/**
* Pre-resolved next hops for v4 and v6. Why these are global and not
* per-domain is beyond me.
*/
extern map_main_pre_resolved_t pre_resolved[FIB_PROTOCOL_MAX];
#endif
typedef struct {
/* pool of MAP domains */
map_domain_t *domains;
/* MAP Domain packet/byte counters indexed by map domain index */
vlib_simple_counter_main_t *simple_domain_counters;
vlib_combined_counter_main_t *domain_counters;
volatile u32 *counter_lock;
/* API message id base */
u16 msg_id_base;
/* Traffic class: zero, copy (~0) or fixed value */
u8 tc;
bool tc_copy;
bool sec_check; /* Inbound security check */
bool sec_check_frag; /* Inbound security check for (subsequent) fragments */
bool icmp6_enabled; /* Send destination unreachable for security check failure */
bool is_ce; /* If this MAP node is a Customer Edge router*/
/* ICMPv6 -> ICMPv4 relay parameters */
ip4_address_t icmp4_src_address;
vlib_simple_counter_main_t icmp_relayed;
/* convenience */
vlib_main_t *vlib_main;
vnet_main_t *vnet_main;
/*
* IPv4 encap and decap reassembly
*/
/* Configuration */
f32 ip4_reass_conf_ht_ratio; //Size of ht is 2^ceil(log2(ratio*pool_size))
u16 ip4_reass_conf_pool_size; //Max number of allocated reass structures
u16 ip4_reass_conf_lifetime_ms; //Time a reassembly struct is considered valid in ms
u32 ip4_reass_conf_buffers; //Maximum number of buffers used by ip4 reassembly
/* Runtime */
map_ip4_reass_t *ip4_reass_pool;
u8 ip4_reass_ht_log2len; //Hash table size is 2^log2len
u16 ip4_reass_allocated;
u16 *ip4_reass_hash_table;
u16 ip4_reass_fifo_last;
volatile u32 *ip4_reass_lock;
/* Counters */
u32 ip4_reass_buffered_counter;
bool frag_inner; /* Inner or outer fragmentation */
bool frag_ignore_df; /* Fragment (outer) packet even if DF is set */
/*
* IPv6 decap reassembly
*/
/* Configuration */
f32 ip6_reass_conf_ht_ratio; //Size of ht is 2^ceil(log2(ratio*pool_size))
u16 ip6_reass_conf_pool_size; //Max number of allocated reass structures
u16 ip6_reass_conf_lifetime_ms; //Time a reassembly struct is considered valid in ms
u32 ip6_reass_conf_buffers; //Maximum number of buffers used by ip6 reassembly
/* Runtime */
map_ip6_reass_t *ip6_reass_pool;
u8 ip6_reass_ht_log2len; //Hash table size is 2^log2len
u16 ip6_reass_allocated;
u16 *ip6_reass_hash_table;
u16 ip6_reass_fifo_last;
volatile u32 *ip6_reass_lock;
/* Counters */
u32 ip6_reass_buffered_counter;
} map_main_t;
/*
* MAP Error counters/messages
*/
#define foreach_map_error \
/* Must be first. */ \
_(NONE, "valid MAP packets") \
_(BAD_PROTOCOL, "bad protocol") \
_(SEC_CHECK, "security check failed") \
_(ENCAP_SEC_CHECK, "encap security check failed") \
_(DECAP_SEC_CHECK, "decap security check failed") \
_(ICMP, "unable to translate ICMP") \
_(ICMP_RELAY, "unable to relay ICMP") \
_(UNKNOWN, "unknown") \
_(NO_BINDING, "no binding") \
_(NO_DOMAIN, "no domain") \
_(FRAGMENTED, "packet is a fragment") \
_(FRAGMENT_MEMORY, "could not cache fragment") \
_(FRAGMENT_MALFORMED, "fragment has unexpected format")\
_(FRAGMENT_DROPPED, "dropped cached fragment") \
_(MALFORMED, "malformed packet") \
_(DF_SET, "can't fragment, DF set")
typedef enum {
#define _(sym,str) MAP_ERROR_##sym,
foreach_map_error
#undef _
MAP_N_ERROR,
} map_error_t;
u64 map_error_counter_get(u32 node_index, map_error_t map_error);
typedef struct {
u32 map_domain_index;
u16 port;
} map_trace_t;
extern map_main_t map_main;
extern vlib_node_registration_t ip4_map_node;
extern vlib_node_registration_t ip6_map_node;
extern vlib_node_registration_t ip4_map_t_node;
extern vlib_node_registration_t ip4_map_t_fragmented_node;
extern vlib_node_registration_t ip4_map_t_tcp_udp_node;
extern vlib_node_registration_t ip4_map_t_icmp_node;
extern vlib_node_registration_t ip6_map_t_node;
extern vlib_node_registration_t ip6_map_t_fragmented_node;
extern vlib_node_registration_t ip6_map_t_tcp_udp_node;
extern vlib_node_registration_t ip6_map_t_icmp_node;
/*
* map_get_pfx
*/
static_always_inline u64
map_get_pfx (map_domain_t *d, u32 addr, u16 port)
{
u16 psid = (port >> d->psid_shift) & d->psid_mask;
if (d->ea_bits_len == 0 && d->rules)
return clib_net_to_host_u64(d->rules[psid].as_u64[0]);
u32 suffix = (addr >> d->suffix_shift) & d->suffix_mask;
u64 ea = d->ea_bits_len == 0 ? 0 : (((u64) suffix << d->psid_length)) | psid;
return clib_net_to_host_u64(d->ip6_prefix.as_u64[0]) | ea << d->ea_shift;
}
static_always_inline u64
map_get_pfx_net (map_domain_t *d, u32 addr, u16 port)
{
return clib_host_to_net_u64(map_get_pfx(d, clib_net_to_host_u32(addr),
clib_net_to_host_u16(port)));
}
/*
* map_get_sfx
*/
static_always_inline u64
map_get_sfx (map_domain_t *d, u32 addr, u16 port)
{
u16 psid = (port >> d->psid_shift) & d->psid_mask;
/* Shared 1:1 mode. */
if (d->ea_bits_len == 0 && d->rules)
return clib_net_to_host_u64(d->rules[psid].as_u64[1]);
if (d->ip6_prefix_len == 128)
return clib_net_to_host_u64(d->ip6_prefix.as_u64[1]);
if (d->flags & MAP_DOMAIN_RFC6052)
return (clib_net_to_host_u64(d->ip6_prefix.as_u64[1]) | addr);
/* IPv4 prefix */
if (d->flags & MAP_DOMAIN_PREFIX)
return (u64) (addr & (0xFFFFFFFF << d->suffix_shift)) << 16;
/* Shared or full IPv4 address */
return ((u64) addr << 16) | psid;
}
static_always_inline u64
map_get_sfx_net (map_domain_t *d, u32 addr, u16 port)
{
return clib_host_to_net_u64(map_get_sfx(d, clib_net_to_host_u32(addr),
clib_net_to_host_u16(port)));
}
static_always_inline u32
map_get_ip4 (ip6_address_t *addr, map_domain_flags_e flags)
{
if (flags & MAP_DOMAIN_RFC6052)
return clib_host_to_net_u32(clib_net_to_host_u64(addr->as_u64[1]));
else
return clib_host_to_net_u32(clib_net_to_host_u64(addr->as_u64[1]) >> 16);
}
/*
* Get the MAP domain from an IPv4 lookup adjacency.
*/
static_always_inline map_domain_t *
ip4_map_get_domain (u32 mdi)
{
map_main_t *mm = &map_main;
return pool_elt_at_index(mm->domains, mdi);
}
/*
* Get the MAP domain from an IPv6 lookup adjacency.
* If the IPv6 address or prefix is not shared, no lookup is required.
* The IPv4 address is used otherwise.
*/
static_always_inline map_domain_t *
ip6_map_get_domain (u32 mdi,
ip4_address_t *addr,
u32 *map_domain_index,
u8 *error)
{
map_main_t *mm = &map_main;
#ifdef TODO
/*
* Disable direct MAP domain lookup on decap, until the security check is updated to verify IPv4 SA.
* (That's done implicitly when MAP domain is looked up in the IPv4 FIB)
*/
//#ifdef MAP_NONSHARED_DOMAIN_ENABLED
//#error "How can you be sure this domain is not shared?"
#endif
*map_domain_index = mdi;
return pool_elt_at_index(mm->domains, mdi);
#ifdef TODO
u32 lbi = ip4_fib_forwarding_lookup(0, addr);
const dpo_id_t *dpo = load_balance_get_bucket(lbi, 0);
if (PREDICT_TRUE(dpo->dpoi_type == map_dpo_type ||
dpo->dpoi_type == map_t_dpo_type))
{
*map_domain_index = dpo->dpoi_index;
return pool_elt_at_index(mm->domains, *map_domain_index);
}
*error = MAP_ERROR_NO_DOMAIN;
return NULL;
#endif
}
map_ip4_reass_t *
map_ip4_reass_get(u32 src, u32 dst, u16 fragment_id,
u8 protocol, u32 **pi_to_drop);
void
map_ip4_reass_free(map_ip4_reass_t *r, u32 **pi_to_drop);
#define map_ip4_reass_lock() while (__sync_lock_test_and_set(map_main.ip4_reass_lock, 1)) {}
#define map_ip4_reass_unlock() do {CLIB_MEMORY_BARRIER(); *map_main.ip4_reass_lock = 0;} while(0)
static_always_inline void
map_ip4_reass_get_fragments(map_ip4_reass_t *r, u32 **pi)
{
int i;
for (i=0; i<MAP_IP4_REASS_MAX_FRAGMENTS_PER_REASSEMBLY; i++)
if(r->fragments[i] != ~0) {
vec_add1(*pi, r->fragments[i]);
r->fragments[i] = ~0;
map_main.ip4_reass_buffered_counter--;
}
}
clib_error_t * map_plugin_api_hookup (vlib_main_t * vm);
int map_ip4_reass_add_fragment(map_ip4_reass_t *r, u32 pi);
map_ip6_reass_t *
map_ip6_reass_get(ip6_address_t *src, ip6_address_t *dst, u32 fragment_id,
u8 protocol, u32 **pi_to_drop);
void
map_ip6_reass_free(map_ip6_reass_t *r, u32 **pi_to_drop);
#define map_ip6_reass_lock() while (__sync_lock_test_and_set(map_main.ip6_reass_lock, 1)) {}
#define map_ip6_reass_unlock() do {CLIB_MEMORY_BARRIER(); *map_main.ip6_reass_lock = 0;} while(0)
int
map_ip6_reass_add_fragment(map_ip6_reass_t *r, u32 pi,
u16 data_offset, u16 next_data_offset,
u8 *data_start, u16 data_len);
void map_ip4_drop_pi(u32 pi);
int map_ip4_reass_conf_ht_ratio(f32 ht_ratio, u32 *trashed_reass, u32 *dropped_packets);
#define MAP_IP4_REASS_CONF_HT_RATIO_MAX 100
int map_ip4_reass_conf_pool_size(u16 pool_size, u32 *trashed_reass, u32 *dropped_packets);
#define MAP_IP4_REASS_CONF_POOL_SIZE_MAX (0xfeff)
int map_ip4_reass_conf_lifetime(u16 lifetime_ms);
#define MAP_IP4_REASS_CONF_LIFETIME_MAX 0xffff
int map_ip4_reass_conf_buffers(u32 buffers);
#define MAP_IP4_REASS_CONF_BUFFERS_MAX (0xffffffff)
void map_ip6_drop_pi(u32 pi);
int map_ip6_reass_conf_ht_ratio(f32 ht_ratio, u32 *trashed_reass, u32 *dropped_packets);
#define MAP_IP6_REASS_CONF_HT_RATIO_MAX 100
int map_ip6_reass_conf_pool_size(u16 pool_size, u32 *trashed_reass, u32 *dropped_packets);
#define MAP_IP6_REASS_CONF_POOL_SIZE_MAX (0xfeff)
int map_ip6_reass_conf_lifetime(u16 lifetime_ms);
#define MAP_IP6_REASS_CONF_LIFETIME_MAX 0xffff
int map_ip6_reass_conf_buffers(u32 buffers);
#define MAP_IP6_REASS_CONF_BUFFERS_MAX (0xffffffff)
static_always_inline void
ip4_map_t_embedded_address (map_domain_t *d,
ip6_address_t *ip6, const ip4_address_t *ip4)
{
ASSERT(d->ip6_src_len == 96 || d->ip6_src_len == 64); //No support for other lengths for now
u8 offset = d->ip6_src_len == 64 ? 9 : 12;
ip6->as_u64[0] = d->ip6_src.as_u64[0];
ip6->as_u64[1] = d->ip6_src.as_u64[1];
clib_memcpy(&ip6->as_u8[offset], ip4, 4);
}
static_always_inline u32
ip6_map_t_embedded_address (map_domain_t *d, ip6_address_t *addr)
{
ASSERT(d->ip6_src_len == 64 || d->ip6_src_len == 96);
u32 x;
u8 offset = d->ip6_src_len == 64 ? 9 : 12;
clib_memcpy(&x, &addr->as_u8[offset], 4);
return x;
}
static inline void
map_domain_counter_lock (map_main_t *mm)
{
if (mm->counter_lock)
while (__sync_lock_test_and_set(mm->counter_lock, 1))
/* zzzz */ ;
}
static inline void
map_domain_counter_unlock (map_main_t *mm)
{
if (mm->counter_lock)
*mm->counter_lock = 0;
}
static_always_inline void
map_send_all_to_node(vlib_main_t *vm, u32 *pi_vector,
vlib_node_runtime_t *node, vlib_error_t *error,
u32 next)
{
u32 n_left_from, *from, next_index, *to_next, n_left_to_next;
//Deal with fragments that are ready
from = pi_vector;
n_left_from = vec_len(pi_vector);
next_index = node->cached_next_index;
while (n_left_from > 0) {
vlib_get_next_frame(vm, node, next_index, to_next, n_left_to_next);
while (n_left_from > 0 && n_left_to_next > 0) {
u32 pi0 = to_next[0] = from[0];
from += 1;
n_left_from -= 1;
to_next += 1;
n_left_to_next -= 1;
vlib_buffer_t *p0 = vlib_get_buffer(vm, pi0);
p0->error = *error;
vlib_validate_buffer_enqueue_x1(vm, node, next_index, to_next, n_left_to_next, pi0, next);
}
vlib_put_next_frame(vm, node, next_index, n_left_to_next);
}
}
/*
* fd.io coding-style-patch-verification: ON
*
* Local Variables:
* eval: (c-set-style "gnu")
* End:
*/
| 29.377076 | 102 | 0.727113 | [
"object"
] |
6589cf0147e8eaf623bf33819d57ed74bd76cb0f | 9,312 | h | C | lib/drivers/include/clint.h | shuichitakano/kendryte-standalone-sdk | 495fca51c55f53a95240e7d6d126c256de02bed6 | [
"Apache-2.0"
] | 344 | 2018-09-13T19:26:55.000Z | 2022-03-28T05:20:49.000Z | lib/drivers/include/clint.h | shuichitakano/kendryte-standalone-sdk | 495fca51c55f53a95240e7d6d126c256de02bed6 | [
"Apache-2.0"
] | 91 | 2018-10-12T07:55:03.000Z | 2022-03-31T07:58:17.000Z | lib/drivers/include/clint.h | shuichitakano/kendryte-standalone-sdk | 495fca51c55f53a95240e7d6d126c256de02bed6 | [
"Apache-2.0"
] | 138 | 2018-10-11T00:38:43.000Z | 2022-02-19T20:53:00.000Z | /* Copyright 2018 Canaan Inc.
*
* 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.
*/
/**
* @file
* @brief The CLINT block holds memory-mapped control and status registers
* associated with local interrupts for a Coreplex.
*
* @note CLINT RAM Layout
*
* | Address -| Description |
* |------------|---------------------------------|
* | 0x02000000 | msip for core 0 |
* | 0x02000004 | msip for core 1 |
* | ... | ... |
* | 0x02003FF8 | msip for core 4094 |
* | | |
* | 0x02004000 | mtimecmp for core 0 |
* | 0x02004008 | mtimecmp for core 1 |
* | ... | ... |
* | 0x0200BFF0 | mtimecmp For core 4094 |
* | 0x0200BFF8 | mtime |
* | | |
* | 0x0200C000 | Reserved |
* | ... | ... |
* | 0x0200EFFC | Reserved |
*/
#ifndef _DRIVER_CLINT_H
#define _DRIVER_CLINT_H
#include <stddef.h>
#include <stdint.h>
#include "platform.h"
#ifdef __cplusplus
extern "C" {
#endif
/* clang-format off */
/* Register address offsets */
#define CLINT_MSIP (0x0000)
#define CLINT_MSIP_SIZE (0x4)
#define CLINT_MTIMECMP (0x4000)
#define CLINT_MTIMECMP_SIZE (0x8)
#define CLINT_MTIME (0xBFF8)
#define CLINT_MTIME_SIZE (0x8)
/* Max number of cores */
#define CLINT_MAX_CORES (4095)
/* Real number of cores */
#define CLINT_NUM_CORES (2)
/* Clock frequency division factor */
#define CLINT_CLOCK_DIV (50)
/* clang-format on */
/**
* @brief MSIP Registers
*
* Machine-mode software interrupts are generated by writing to a
* per-core memory-mapped control register. The msip registers are
* 32-bit wide WARL registers, where the LSB is reflected in the
* msip bit of the associated core’s mip register. Other bits in
* the msip registers are hardwired to zero. The mapping supports
* up to 4095 machine-mode cores.
*/
typedef struct _clint_msip
{
uint32_t msip : 1; /*!< Bit 0 is msip */
uint32_t zero : 31; /*!< Bits [32:1] is 0 */
} __attribute__((packed, aligned(4))) clint_msip_t;
/**
* @brief Timer compare Registers Machine-mode timer interrupts are
* generated by a real-time counter and a per-core comparator. The
* mtime register is a 64-bit read-only register that contains the
* current value of the real-time counter. Each mtimecmp register
* holds its core’s time comparator. A timer interrupt is pending
* whenever mtime is greater than or equal to the value in a
* core’s mtimecmp register. The timer interrupt is reflected in
* the mtip bit of the associated core’s mip register.
*/
typedef uint64_t clint_mtimecmp_t;
/**
* @brief Timer Registers
*
* The mtime register has a 64-bit precision on all RV32, RV64,
* and RV128 systems. Platforms provide a 64-bit memory-mapped
* machine-mode timer compare register (mtimecmp), which causes a
* timer interrupt to be posted when the mtime register contains a
* value greater than or equal to the value in the mtimecmp
* register. The interrupt remains posted until it is cleared by
* writing the mtimecmp register. The interrupt will only be taken
* if interrupts are enabled and the MTIE bit is set in the mie
* register.
*/
typedef uint64_t clint_mtime_t;
/**
* @brief CLINT object
*
* Coreplex-Local INTerrupts, which includes software interrupts,
* local timer interrupts, and other interrupts routed directly to
* a core.
*/
typedef struct _clint
{
/* 0x0000 to 0x3FF8, MSIP Registers */
clint_msip_t msip[CLINT_MAX_CORES];
/* Resverd space, do not use */
uint32_t resv0;
/* 0x4000 to 0xBFF0, Timer Compare Registers */
clint_mtimecmp_t mtimecmp[CLINT_MAX_CORES];
/* 0xBFF8, Time Register */
clint_mtime_t mtime;
} __attribute__((packed, aligned(4))) clint_t;
/**
* @brief Clint object instanse
*/
extern volatile clint_t *const clint;
/**
* @brief Definitions for the timer callbacks
*/
typedef int (*clint_timer_callback_t)(void *ctx);
/**
* @brief Definitions for local interprocessor interrupt callbacks
*/
typedef int (*clint_ipi_callback_t)(void *ctx);
typedef struct _clint_timer_instance
{
uint64_t interval;
uint64_t cycles;
uint64_t single_shot;
clint_timer_callback_t callback;
void *ctx;
} clint_timer_instance_t;
typedef struct _clint_ipi_instance
{
clint_ipi_callback_t callback;
void *ctx;
} clint_ipi_instance_t;
/**
* @brief Get the time form CLINT timer register
*
* @note The CLINT must init to get right time
*
* @return 64bit Time
*/
uint64_t clint_get_time(void);
/**
* @brief Init the CLINT timer
*
* @note MIP_MTIP will be clear after init. The MSTATUS_MIE must set by
* user.
*
* @return result
* - 0 Success
* - Other Fail
*/
int clint_timer_init(void);
/**
* @brief Stop the CLINT timer
*
* @note MIP_MTIP will be clear after stop
*
* @return result
* - 0 Success
* - Other Fail
*/
int clint_timer_stop(void);
/**
* @brief Start the CLINT timer
*
* @param[in] interval The interval with Millisecond(ms)
* @param[in] single_shot Single shot or repeat
*
* @return result
* - 0 Success
* - Other Fail
*/
int clint_timer_start(uint64_t interval, int single_shot);
/**
* @brief Get the interval of timer
*
* @return The interval with Millisecond(ms)
*/
uint64_t clint_timer_get_interval(void);
/**
* @brief Set the interval with Millisecond(ms)
*
* @param[in] interval The interval with Millisecond(ms)
*
* @return result
* - 0 Success
* - Other Fail
*/
int clint_timer_set_interval(uint64_t interval);
/**
* @brief Get whether the timer is a single shot timer
*
* @return result
* - 0 It is a repeat timer
* - 1 It is a single shot timer
*/
int clint_timer_get_single_shot(void);
/**
* @brief Set the timer working as a single shot timer or repeat timer
*
* @param[in] single_shot Single shot or repeat
*
* @return result
* - 0 Success
* - Other Fail
*/
int clint_timer_set_single_shot(int single_shot);
/**
* @brief Set user callback function when timer is timeout
*
* @param[in] callback The callback function
* @param[in] ctx The context
*
* @return result
* - 0 Success
* - Other Fail
*/
int clint_timer_register(clint_timer_callback_t callback, void *ctx);
/**
* @brief Deregister user callback function
*
* @return result
* - 0 Success
* - Other Fail
*/
int clint_timer_unregister(void);
/**
* @brief Initialize local interprocessor interrupt
*
* @return result
* - 0 Success
* - Other Fail
*/
int clint_ipi_init(void);
/**
* @brief Enable local interprocessor interrupt
*
* @return result
* - 0 Success
* - Other Fail
*/
int clint_ipi_enable(void);
/**
* @brief Disable local interprocessor interrupt
*
* @return result
* - 0 Success
* - Other Fail
*/
int clint_ipi_disable(void);
/**
* @brief Send local interprocessor interrupt to core by core id
*
* @param[in] core_id The core identifier
*
* @return result
* - 0 Success
* - Other Fail
*/
int clint_ipi_send(size_t core_id);
/**
* @brief Clear local interprocessor interrupt
*
* @param[in] core_id The core identifier
*
* @return result
* - 1 An IPI was pending
* - 0 Non IPI was pending
* - -1 Fail
*/
int clint_ipi_clear(size_t core_id);
/**
* @brief Set user callback function when interprocessor interrupt
*
* @param[in] callback The callback function
* @param[in] ctx The context
*
* @return result
* - 0 Success
* - Other Fail
*/
int clint_ipi_register(clint_ipi_callback_t callback, void *ctx);
/**
* @brief Deregister user callback function
*
* @return result
* - 0 Success
* - Other Fail
*/
int clint_ipi_unregister(void);
#ifdef __cplusplus
}
#endif
#endif /* _DRIVER_CLINT_H */
| 27.550296 | 79 | 0.600408 | [
"object"
] |
658b77ba98a7da3f5a6607fabbb2ca26966eba48 | 524 | h | C | Win32xx/samples/MDIFrame/src/MDIFrameApp.h | mufunyo/VisionRGBApp | c09092770032150083eda171a22b1a3ef0914dab | [
"Unlicense"
] | 2 | 2021-03-25T04:19:22.000Z | 2021-05-03T03:23:30.000Z | Win32xx/samples/MDIFrame/src/MDIFrameApp.h | mufunyo/VisionRGBApp | c09092770032150083eda171a22b1a3ef0914dab | [
"Unlicense"
] | null | null | null | Win32xx/samples/MDIFrame/src/MDIFrameApp.h | mufunyo/VisionRGBApp | c09092770032150083eda171a22b1a3ef0914dab | [
"Unlicense"
] | 1 | 2020-12-28T08:53:42.000Z | 2020-12-28T08:53:42.000Z | //////////////////////////////////////
// MDIFrameApp.h
#ifndef MDIFRAMEAPP_H
#define MDIFRAMEAPP_H
#include "MainMDIFrm.h"
class CMDIFrameApp : public CWinApp
{
public:
CMDIFrameApp();
virtual ~CMDIFrameApp() {}
virtual BOOL InitInstance();
CMainMDIFrame& GetMDIFrame() { return m_mainMDIFrame; }
private:
CMainMDIFrame m_mainMDIFrame;
};
// returns a pointer to the CMDIFrameApp object
inline CMDIFrameApp* GetMDIApp() { return static_cast<CMDIFrameApp*>(GetApp()); }
#endif // MDIFRAMEAPP_H
| 18.068966 | 81 | 0.675573 | [
"object"
] |
658edb61da1e244e2b6957ce5bff88ee848675c7 | 508 | h | C | main/include/jumpnrun/ai/AI_Supervised.h | wonderhorn/mkfj | 18d2dd290811662d87abefe2fe2e338ba9caf8a5 | [
"MIT"
] | null | null | null | main/include/jumpnrun/ai/AI_Supervised.h | wonderhorn/mkfj | 18d2dd290811662d87abefe2fe2e338ba9caf8a5 | [
"MIT"
] | null | null | null | main/include/jumpnrun/ai/AI_Supervised.h | wonderhorn/mkfj | 18d2dd290811662d87abefe2fe2e338ba9caf8a5 | [
"MIT"
] | null | null | null | #pragma once
#include"jumpnrun/ai/AI.h"
#include<vector>
#include<string>
#include<map>
#include"jumpnrun/ai/TemplateHistogram.h"
namespace jnr
{
namespace ai
{
class AI_Supervised: public AI
{
public:
AI_Supervised();
~AI_Supervised();
void initialize();
Feature processMyStatus(CharacterStatus cs);
void think(const CharacterStatus& cs);
void decodeButtons(int i);
private:
std::map<Feature, myutil::Histogram<int, int>> f2act;
Feature f_prev;
int command;
};
};
}; | 18.814815 | 56 | 0.700787 | [
"vector"
] |
659527496e547d3258a8aab2118c98cf46f1405e | 1,059 | c | C | lib/wizards/neophyte/healer/healer.c | vlehtola/questmud | 8bc3099b5ad00a9e0261faeb6637c76b521b6dbe | [
"MIT"
] | null | null | null | lib/wizards/neophyte/healer/healer.c | vlehtola/questmud | 8bc3099b5ad00a9e0261faeb6637c76b521b6dbe | [
"MIT"
] | null | null | null | lib/wizards/neophyte/healer/healer.c | vlehtola/questmud | 8bc3099b5ad00a9e0261faeb6637c76b521b6dbe | [
"MIT"
] | null | null | null | inherit "obj/monster";
int seconds,i;
object *user;
object x;
string spells;
reset(arg) {
::reset(arg);
if(arg) return;
set_level(80);
set_name("healer");
set_alias("verot");
set_race("human");
set_short("Travelling healer giving a free healings");
set_long("She is wearing a white cape and small oaken staff.\n"+
"She is constantly mumbling something about healing.\n");
set_gender(2);
set_al(0);
set_heart_beat(1);
set_skill("chanting", 100);
set_skill("channel", 100);
set_skill("cast divine", 100);
set_skill("cast wide", 100);
set_skill("cast major", 100);
set_skill("mastery of medicine", 100);
set_wis(query_wis()*10);
set_max_hp(query_hp()*10);
set_hp(query_max_hp());
}
void heart_beat() {
::heart_beat();
user = users();
spells = "chl kfq mar";
if (!this_object()->query_spell() && !this_object()->query_stunned() && random(100) > 90) {
x = clone_object("/guilds/obj/spell");
move_object(x,this_object());
x->start_spell(spells);
}
}
| 25.214286 | 93 | 0.631728 | [
"object"
] |
659d2436c01243a34506088d3f19c957e9e83b28 | 6,438 | h | C | include/yaramod/types/symbols.h | mehrdad-shokri/yaramod | 20b6f28099f4b146e4e481604646256485193b98 | [
"BSD-3-Clause",
"MIT"
] | null | null | null | include/yaramod/types/symbols.h | mehrdad-shokri/yaramod | 20b6f28099f4b146e4e481604646256485193b98 | [
"BSD-3-Clause",
"MIT"
] | null | null | null | include/yaramod/types/symbols.h | mehrdad-shokri/yaramod | 20b6f28099f4b146e4e481604646256485193b98 | [
"BSD-3-Clause",
"MIT"
] | null | null | null | /**
* @file src/types/symbols.h
* @brief Declaration of all Symbol subclasses.
* @copyright (c) 2017 Avast Software, licensed under the MIT license
*/
#pragma once
#include <optional>
#include <vector>
#include "yaramod/types/symbol.h"
namespace yaramod {
/**
* Class representing value symbol. Value symbol carries only name
* of the symbol and some data type.
*/
class ValueSymbol : public Symbol
{
public:
ValueSymbol(const std::string& name, ExpressionType dataType) : Symbol(Symbol::Type::Value, name, dataType) {}
};
/**
* Abstract class representing iterable symbol. Iterable symbol may be
* array or dictionary symbol. Iterable symbols store data type of the elements
* they are iterating over. If the element type is @c ExpressionType::Object then
* iterable symbol also carries the symbol representing structured type of the element.
*/
class IterableSymbol : public Symbol
{
public:
ExpressionType getElementType() const { return _elementType; }
const std::shared_ptr<Symbol>& getStructuredElementType() const { return _structuredType; }
bool isStructured() const { return _elementType == ExpressionType::Object && _structuredType; }
protected:
IterableSymbol(Symbol::Type type, const std::string& name, ExpressionType elementType)
: Symbol(type, name, ExpressionType::Object), _elementType(elementType), _structuredType() {}
IterableSymbol(Symbol::Type type, const std::string& name, const std::shared_ptr<Symbol>& structuredType)
: Symbol(type, name, ExpressionType::Object), _elementType(ExpressionType::Object), _structuredType(structuredType) {}
ExpressionType _elementType; ///< Element of the iterated data
std::shared_ptr<Symbol> _structuredType; ///< Structured type of the object elements
};
/**
* Class representing array symbol. Array symbol carries name of the array and type of the element of the array.
* Data type of the whole array symbol is always @c Symbol::Type::Array.
*/
class ArraySymbol : public IterableSymbol
{
public:
ArraySymbol(const std::string& name, ExpressionType elementType) : IterableSymbol(Symbol::Type::Array, name, elementType) {}
ArraySymbol(const std::string& name, const std::shared_ptr<Symbol>& structuredType) : IterableSymbol(Symbol::Type::Array, name, structuredType) {}
};
/**
* Class representing dictionary symbol. Dictionary symbol carries name of the dictionary and type of the element of the dictionary.
* Data type of the whole dictionary symbol is always @c Symbol::Type::Dictionary.
*/
class DictionarySymbol : public IterableSymbol
{
public:
DictionarySymbol(const std::string& name, ExpressionType elementType) : IterableSymbol(Symbol::Type::Dictionary, name, elementType) {}
DictionarySymbol(const std::string& name, const std::shared_ptr<Symbol>& structuredType) : IterableSymbol(Symbol::Type::Array, name, structuredType) {}
};
/**
* Class representing function symbol. Function symbol carries name of the function, return type of the function
* and argument types of all possible overloads of that function.
*/
class FunctionSymbol : public Symbol
{
public:
template <typename... Args>
FunctionSymbol(const std::string& name, ExpressionType returnType, const Args&... args)
: Symbol(Symbol::Type::Function, name, ExpressionType::Object), _returnType(returnType), _argTypesOverloads(1)
{
_initArgs(args...);
}
ExpressionType getReturnType() const { return _returnType; }
const std::vector<std::vector<ExpressionType>>& getAllOverloads() const { return _argTypesOverloads; }
std::size_t getArgumentCount(std::size_t overloadIndex = 0) const
{
assert(overloadIndex < _argTypesOverloads.size());
return _argTypesOverloads[overloadIndex].size();
}
std::vector<ExpressionType> getArgumentTypes(std::size_t overloadIndex = 0) const
{
assert(overloadIndex < _argTypesOverloads.size());
return _argTypesOverloads[overloadIndex];
}
bool addOverload(const std::vector<ExpressionType>& argTypes)
{
if (overloadExists(argTypes))
return false;
_argTypesOverloads.push_back(argTypes);
return true;
}
bool overloadExists(const std::vector<ExpressionType>& args) const
{
for (const auto& overload : _argTypesOverloads)
{
if (overload.size() != args.size())
continue;
// No mismatch in two vectors, so they are completely the same.
auto mismatch = std::mismatch(overload.begin(), overload.end(), args.begin());
if (mismatch.first == overload.end())
return true;
}
return false;
}
private:
void _initArgs() {}
template <typename... Args>
void _initArgs(ExpressionType argType, const Args&... args)
{
_argTypesOverloads.front().push_back(argType);
_initArgs(args...);
}
ExpressionType _returnType; ///< Return type of the function
std::vector<std::vector<ExpressionType>> _argTypesOverloads; ///< All possible overloads of the function
};
/**
* Class representing structure symbol. Structure symbol carries name of the structure and its attributes.
*/
class StructureSymbol : public Symbol
{
public:
StructureSymbol(const std::string& name) : Symbol(Symbol::Type::Structure, name, ExpressionType::Object) {}
std::optional<std::shared_ptr<Symbol>> getAttribute(const std::string& name) const
{
auto itr = _attributes.find(name);
if (itr == _attributes.end())
return std::nullopt;
return { itr->second };
}
bool addAttribute(const std::shared_ptr<Symbol>& attribute)
{
// Insertion result is pair of iterator and boolean indicator whether insertion was successful
auto insertionResult = _attributes.emplace(attribute->getName(), attribute);
if (insertionResult.second)
return true;
// Insertion did not succeed and we must handle that
auto itr = insertionResult.first;
// If we are trying to add a function and function with that name already exists,
// it may be function overload, so check that.
if (itr->second->isFunction() && attribute->isFunction())
{
auto oldFunction = std::static_pointer_cast<FunctionSymbol>(itr->second);
auto newFunction = std::static_pointer_cast<const FunctionSymbol>(attribute);
// Overload return types must be the same, only argument count and types may differ.
if (oldFunction->getReturnType() != newFunction->getReturnType())
return false;
return oldFunction->addOverload(newFunction->getArgumentTypes());
}
return false;
}
private:
std::unordered_map<std::string, std::shared_ptr<Symbol>> _attributes; ///< Attributes of the structure
};
}
| 34.063492 | 152 | 0.746816 | [
"object",
"vector"
] |
45550865cc2875fc3e271db17e95dc8cdcbef9c5 | 8,659 | h | C | sources/configuration/configuration_handler.h | PFGimenez/Kraken-cpp | 4b0d300a6ed188f75523ab6bf79dc4a1ac592ab9 | [
"MIT"
] | 9 | 2018-05-14T10:36:50.000Z | 2018-11-06T21:39:01.000Z | sources/configuration/configuration_handler.h | kraken-robotics/Kraken-cpp | 4b0d300a6ed188f75523ab6bf79dc4a1ac592ab9 | [
"MIT"
] | 10 | 2018-05-15T11:56:35.000Z | 2018-07-09T07:17:07.000Z | sources/configuration/configuration_handler.h | kraken-robotics/Kraken-cpp | 4b0d300a6ed188f75523ab6bf79dc4a1ac592ab9 | [
"MIT"
] | 5 | 2018-05-15T17:27:43.000Z | 2018-08-28T00:26:38.000Z | #ifndef CONFIGURATION_HANDLER_H
#define CONFIGURATION_HANDLER_H
#include <string>
#include <functional>
#include "configuration_module.h"
#include "iniReader/INIReader.h"
#include <iostream>
namespace kraken {
/*
* Before modifying this enum, consider that:
* - The enumeration values are used as keys in a vector, they need to be a contiguous range of integers.
* - NbPoints is used to initialize the size of said vector.
* - The enumerations are ordered by module (see ConfigModule). If you have to modify this enum, keep the groups in the
* same order and let the first key of each group at the first place. If you don't do this, update the array
* modules_limits according to your changes.
* - The default_values_ initializer list directly depends on the order of the enumerations values.
*/
namespace ConfigKeys {
enum class ConfigKeys {
//Navmesh parameters
NavmeshObstaclesDilatation = 0,
LargestTriangleAreaInNavmesh,
LongestEdgeInNavmesh,
NavmeshFilename,
//Auto replanning
NecessaryMargin,
PreferedMargin,
MarginBeforeCollision,
InitialMargin,
//Research and mechanical parameters
MaxCurvatureDerivative,
MaxLateralAcceleration,
MaxLinearAcceleration,
DefaultMaxSpeed,
MinimalSpeed,
MaxCurvature,
StopDuration,
SearchTimeout,
ThreadNumber,
EnableDebug,
FastAndDirty,
CheckNewObstacles,
AllowBackwardMotion,
//Memory management parameters
NodeMemoryPoolSize,
ObstaclesMemoryPoolSize,
//Tentacle parameters
PrecisionTrace,
NbPoints
};
}
using ConfigKey = ConfigKeys::ConfigKeys;
/*
* Before modifying this enum, consider that:
* - The enumeration values are used as keys in a vector, they need to be a contiguous range of integers.
* - Tentacle is used to initialize the size of said vector.
*/
namespace ConfigModules {
enum class ConfigModules {
Navmesh = 0, //Require to regenerate the navmesh
Autoreplanning, //Can be modified on-the-fly
ResearchMechanical, //Can be modified on-the-fly
Memory, //Require to recreate the pools
Tentacle
};
}
using ConfigModule = ConfigModules::ConfigModules;
class ConfigurationHandler {
private:
//Structure holding all possible types of parameter value.
//It should be an union, but it will require a bit more work because of the std::string
struct ConfigurationParameter {
float numeric_value = 0;
bool boolean_value = false;
std::string string_value = {};
ConfigurationParameter() = default;
explicit ConfigurationParameter(float value) { numeric_value = value; }
explicit ConfigurationParameter(int value) { numeric_value = value; }
explicit ConfigurationParameter(bool value) { boolean_value = value; }
explicit ConfigurationParameter(const std::string& value) { string_value = value; }
};
public:
ConfigurationHandler();
#if USE_FILESYSTEM
void loadFromFile(const std::string& filename);
#endif
void loadFromString(const std::string& fileContent);
void registerCallback(ConfigModule module_enum, ConfigurationCallback callback);
void changeModuleSection(ConfigModule module_enum, std::string new_section);
void changeModuleSection(std::vector<ConfigModule> &&modules, std::string new_section);
template<typename T>
T get(ConfigKey key, ConfigModule module_enum)
{
auto defaultValue = getDefaultValue<T>(key);
auto sectionName = getSectionName(module_enum);
return ini_reader_.get<T>(sectionName, getKeyName(key), defaultValue);
}
template<typename T>
T get(ConfigKey key)
{
return get<T>(key, getModuleEnumFromKeyEnum(key));
}
private:
ConfigModule getModuleEnumFromKeyEnum(ConfigKey key) const noexcept;
std::string getSectionName(ConfigModule module_key);
std::string getKeyName(ConfigKey key);
ConfigurationModule* getModule(ConfigModule module_enum);
void callCallbacks();
template<class T>
T getDefaultValue(ConfigKey key);
INIReader ini_reader_;
std::vector<ConfigurationModule> modules_;
static constexpr unsigned long configuration_key_count = (unsigned long) ConfigKey::NbPoints + 1;
static constexpr unsigned long module_count = (unsigned long) ConfigModule::Tentacle + 1;
//This array need to be initialized in the same order as the ConfigKey enum
const ConfigurationParameter default_values_[configuration_key_count] = {
ConfigurationParameter{100}, //NavmeshObstaclesDilatation
ConfigurationParameter{20000}, //LargestTriangleAreaInNavmesh
ConfigurationParameter{200}, //LongestEdgeInNavmesh
ConfigurationParameter{(std::string)"navmesh.krk"}, //NavmeshFilename
ConfigurationParameter{40}, //NecessaryMargin
ConfigurationParameter{60}, //PreferedMargin
ConfigurationParameter{100}, //MarginBeforeCollision
ConfigurationParameter{100}, //InitialMargin
ConfigurationParameter{5}, //MaxCurvatureDerivative
ConfigurationParameter{3}, //MaxLateralAcceleration
ConfigurationParameter{2}, //MaxLinearAcceleration
ConfigurationParameter{1}, //DefaultMaxSpeed
ConfigurationParameter{0}, //MinimalSpeed
ConfigurationParameter{5}, //MaxCurvature
ConfigurationParameter{800}, //StopDuration
ConfigurationParameter{10000}, //SearchTimeout
ConfigurationParameter{1}, //ThreadNumber
ConfigurationParameter{true}, //EnableDebug
ConfigurationParameter{false}, //FastAndDirty
ConfigurationParameter{false}, //CheckNewObstacles
ConfigurationParameter{20000}, //NodeMemoryPoolSize
ConfigurationParameter{50000}, //ObstaclesMemoryPoolSize
ConfigurationParameter{true}, //AllowBackwardMotion
ConfigurationParameter{0.02f}, //PrecisionTrace
ConfigurationParameter{5} //NbPoints
};
//The array that keeps the string values of the ConfigKeys
const std::string configuration_key_string_values[configuration_key_count] = {
"NavmeshObstaclesDilatation", "LargestTriangleAreaInNavmesh", "LongestEdgeInNavmesh", "NavmeshFilename",
"NecessaryMargin", "PreferedMargin", "MarginBeforeCollision", "InitialMargin", "MaxCurvatureDerivative",
"MaxLateralAcceleration", "MaxLinearAcceleration", "DefaultMaxSpeed", "MinimalSpeed", "MaxCurvature",
"StopDuration", "SearchTimeout", "ThreadNumber", "EnableDebug", "FastAndDirty", "CheckNewObstacles",
"AllowBackwardMotion", "NodeMemoryPoolSize", "ObstaclesMemoryPoolSize", "PrecisionTrace", "NbPoints"
};
const std::pair<ConfigKey, ConfigModule> modules_limits[4] = {
{ ConfigKey::NecessaryMargin, ConfigModule::Navmesh },
{ ConfigKey::MaxCurvatureDerivative, ConfigModule::Autoreplanning },
{ ConfigKey::NodeMemoryPoolSize, ConfigModule::ResearchMechanical },
{ ConfigKey::PrecisionTrace, ConfigModule::Memory }
};
};
}
#endif //CONFIGURATION_HANDLER_H
| 45.098958 | 124 | 0.59545 | [
"vector"
] |
45578208544e2583ceaff7bef0584e0a1a99a7ee | 1,945 | h | C | controller/warehouse_controller.h | hyunmindev/CLI_Warehouse | 8fa632329e07b49bd18b11ac2dea2df28a0eafbe | [
"MIT"
] | null | null | null | controller/warehouse_controller.h | hyunmindev/CLI_Warehouse | 8fa632329e07b49bd18b11ac2dea2df28a0eafbe | [
"MIT"
] | null | null | null | controller/warehouse_controller.h | hyunmindev/CLI_Warehouse | 8fa632329e07b49bd18b11ac2dea2df28a0eafbe | [
"MIT"
] | 2 | 2021-04-07T01:44:07.000Z | 2021-06-19T05:16:55.000Z | //
// Created by 정현민 on 2021/03/25.
//
#ifndef PROJECT_CONTROLLER_WAREHOUSE_CONTROLLER_H_
#define PROJECT_CONTROLLER_WAREHOUSE_CONTROLLER_H_
#include <iostream>
#include <fstream>
#include <vector>
#include <algorithm>
#include "../handler/output_handler.h"
#include "../handler/string_handler.h"
#include "../model/item_model.h"
#include "../model/warehouse_model.h"
struct WarehouseState {
WarehouseModel warehouse;
// int a
std::vector<std::pair<std::string, int>> items_state;
};
class WarehouseController {
public:
explicit WarehouseController();
~WarehouseController();
void ReadWarehouse();
void ReadStoreState();
void ReadItem();
void ReadFiles();
void WriteStoreState() const;
void WriteItem() const;
void WriteWarehouse() const;
int FindItem(const std::string &identifier) const;
int FindWarehouse(std::string &identifier);
int Receive(std::string &identifier, int item_count);
bool Release(std::string &identifier, int item_count);
bool ReceiveSubPromptWeight(int weight);
bool ReceiveSubPromptVolume(int volume);
bool ReceiveSubPromptIdentifier(std::string &identifier);
bool ReleaseSubPrompt(std::vector<std::string> &identifiers);
int GetStateAcceptableVolume(const std::string &warehouse_identifier) const;
int FindWarehouseState(const std::string &warehouse_identifier) const;
int FindWarehouseItemIndex(std::string &item_identifier);
void FindItemIndexClear();
std::vector<WarehouseModel> GetAllWarehouses() const;
static bool CheckWarehouseIdentifier(std::string &warehouse_identifier);
bool GetItemInfo(std::string &item_id) const;
ItemModel *GetReceiveItem() const;
private:
std::vector<WarehouseState> warehouse_state_;
std::vector<ItemModel> all_items_;
std::vector<WarehouseModel> all_warehouses_;
std::vector<std::pair<int, int>> find_item_index_;
ItemModel *receive_item_;
int item_count_;
};
#endif //PROJECT_CONTROLLER_WAREHOUSE_CONTROLLER_H_
| 31.885246 | 78 | 0.771722 | [
"vector",
"model"
] |
4559e93928273f72d425e1e29705443986fdc8cf | 1,105 | h | C | include/n2/utils.h | gony0/n2 | 824981473b3c499323a1f677c78fdc246a065a2a | [
"Apache-2.0"
] | 528 | 2017-11-30T08:43:42.000Z | 2022-03-12T11:21:04.000Z | include/n2/utils.h | gony0/n2 | 824981473b3c499323a1f677c78fdc246a065a2a | [
"Apache-2.0"
] | 38 | 2017-12-01T11:54:00.000Z | 2022-03-17T04:43:29.000Z | include/n2/utils.h | gony0/n2 | 824981473b3c499323a1f677c78fdc246a065a2a | [
"Apache-2.0"
] | 78 | 2017-11-30T16:53:36.000Z | 2022-03-29T09:58:06.000Z | // Copyright 2017 Kakao Corp. <http://www.kakaocorp.com>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <algorithm>
#include <numeric>
#include <vector>
namespace n2 {
class Utils {
public:
static void NormalizeVector(const std::vector<float>& in, std::vector<float>& out) {
float sum = std::inner_product(in.begin(), in.end(), in.begin(), 0.0);
if (sum != 0.0) {
sum = 1 / std::sqrt(sum);
std::transform(in.begin(), in.end(), out.begin(), std::bind1st(std::multiplies<float>(), sum));
}
}
};
} // namespace n2
| 31.571429 | 107 | 0.669683 | [
"vector",
"transform"
] |
456c63389b72816fd6a0f4838f80c22f626df728 | 6,359 | h | C | Vendor/OpenFramework/libs/cairo/include/cairo/cairo-recording-surface-private.h | TygoB-B5/OSCSpaceShooter | 9a94fbbe4392c9283e47696d06a2866a7a8f1213 | [
"Apache-2.0"
] | 142 | 2015-01-15T04:05:34.000Z | 2022-02-15T00:34:42.000Z | Vendor/OpenFramework/libs/cairo/include/cairo/cairo-recording-surface-private.h | TygoB-B5/OSCSpaceShooter | 9a94fbbe4392c9283e47696d06a2866a7a8f1213 | [
"Apache-2.0"
] | 32 | 2015-01-22T09:02:11.000Z | 2021-04-18T08:20:45.000Z | Vendor/OpenFramework/libs/cairo/include/cairo/cairo-recording-surface-private.h | TygoB-B5/OSCSpaceShooter | 9a94fbbe4392c9283e47696d06a2866a7a8f1213 | [
"Apache-2.0"
] | 63 | 2015-03-18T00:16:31.000Z | 2022-02-13T22:45:12.000Z | /* cairo - a vector graphics library with display and print output
*
* Copyright © 2005 Red Hat, Inc
*
* This library is free software; you can redistribute it and/or
* modify it either under the terms of the GNU Lesser General Public
* License version 2.1 as published by the Free Software Foundation
* (the "LGPL") or, at your option, under the terms of the Mozilla
* Public License Version 1.1 (the "MPL"). If you do not alter this
* notice, a recipient may use your version of this file under either
* the MPL or the LGPL.
*
* You should have received a copy of the LGPL along with this library
* in the file COPYING-LGPL-2.1; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Suite 500, Boston, MA 02110-1335, USA
* You should have received a copy of the MPL along with this library
* in the file COPYING-MPL-1.1
*
* The contents of this file are subject to the Mozilla Public License
* Version 1.1 (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.mozilla.org/MPL/
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY
* OF ANY KIND, either express or implied. See the LGPL or the MPL for
* the specific language governing rights and limitations.
*
* The Original Code is the cairo graphics library.
*
* The Initial Developer of the Original Code is Red Hat, Inc.
*
* Contributor(s):
* Kristian Høgsberg <krh@redhat.com>
* Adrian Johnson <ajohnson@redneon.com>
*/
#ifndef CAIRO_RECORDING_SURFACE_H
#define CAIRO_RECORDING_SURFACE_H
#include "cairoint.h"
#include "cairo-path-fixed-private.h"
#include "cairo-pattern-private.h"
#include "cairo-surface-backend-private.h"
typedef enum {
/* The 5 basic drawing operations. */
CAIRO_COMMAND_PAINT,
CAIRO_COMMAND_MASK,
CAIRO_COMMAND_STROKE,
CAIRO_COMMAND_FILL,
CAIRO_COMMAND_SHOW_TEXT_GLYPHS,
} cairo_command_type_t;
typedef enum {
CAIRO_RECORDING_REGION_ALL,
CAIRO_RECORDING_REGION_NATIVE,
CAIRO_RECORDING_REGION_IMAGE_FALLBACK
} cairo_recording_region_type_t;
typedef struct _cairo_command_header {
cairo_command_type_t type;
cairo_recording_region_type_t region;
cairo_operator_t op;
cairo_rectangle_int_t extents;
cairo_clip_t *clip;
int index;
struct _cairo_command_header *chain;
} cairo_command_header_t;
typedef struct _cairo_command_paint {
cairo_command_header_t header;
cairo_pattern_union_t source;
} cairo_command_paint_t;
typedef struct _cairo_command_mask {
cairo_command_header_t header;
cairo_pattern_union_t source;
cairo_pattern_union_t mask;
} cairo_command_mask_t;
typedef struct _cairo_command_stroke {
cairo_command_header_t header;
cairo_pattern_union_t source;
cairo_path_fixed_t path;
cairo_stroke_style_t style;
cairo_matrix_t ctm;
cairo_matrix_t ctm_inverse;
double tolerance;
cairo_antialias_t antialias;
} cairo_command_stroke_t;
typedef struct _cairo_command_fill {
cairo_command_header_t header;
cairo_pattern_union_t source;
cairo_path_fixed_t path;
cairo_fill_rule_t fill_rule;
double tolerance;
cairo_antialias_t antialias;
} cairo_command_fill_t;
typedef struct _cairo_command_show_text_glyphs {
cairo_command_header_t header;
cairo_pattern_union_t source;
char *utf8;
int utf8_len;
cairo_glyph_t *glyphs;
unsigned int num_glyphs;
cairo_text_cluster_t *clusters;
int num_clusters;
cairo_text_cluster_flags_t cluster_flags;
cairo_scaled_font_t *scaled_font;
} cairo_command_show_text_glyphs_t;
typedef union _cairo_command {
cairo_command_header_t header;
cairo_command_paint_t paint;
cairo_command_mask_t mask;
cairo_command_stroke_t stroke;
cairo_command_fill_t fill;
cairo_command_show_text_glyphs_t show_text_glyphs;
} cairo_command_t;
typedef struct _cairo_recording_surface {
cairo_surface_t base;
/* A recording-surface is logically unbounded, but when used as a
* source we need to render it to an image, so we need a size at
* which to create that image. */
cairo_rectangle_t extents_pixels;
cairo_rectangle_int_t extents;
cairo_bool_t unbounded;
cairo_array_t commands;
unsigned int *indices;
unsigned int num_indices;
cairo_bool_t optimize_clears;
cairo_bool_t has_bilevel_alpha;
cairo_bool_t has_only_op_over;
struct bbtree {
cairo_box_t extents;
struct bbtree *left, *right;
cairo_command_header_t *chain;
} bbtree;
} cairo_recording_surface_t;
slim_hidden_proto (cairo_recording_surface_create);
cairo_private cairo_int_status_t
_cairo_recording_surface_get_path (cairo_surface_t *surface,
cairo_path_fixed_t *path);
cairo_private cairo_status_t
_cairo_recording_surface_replay_one (cairo_recording_surface_t *surface,
long unsigned index,
cairo_surface_t *target);
cairo_private cairo_status_t
_cairo_recording_surface_replay (cairo_surface_t *surface,
cairo_surface_t *target);
cairo_private cairo_status_t
_cairo_recording_surface_replay_with_clip (cairo_surface_t *surface,
const cairo_matrix_t *surface_transform,
cairo_surface_t *target,
const cairo_clip_t *target_clip);
cairo_private cairo_status_t
_cairo_recording_surface_replay_and_create_regions (cairo_surface_t *surface,
cairo_surface_t *target);
cairo_private cairo_status_t
_cairo_recording_surface_replay_region (cairo_surface_t *surface,
const cairo_rectangle_int_t *surface_extents,
cairo_surface_t *target,
cairo_recording_region_type_t region);
cairo_private cairo_status_t
_cairo_recording_surface_get_bbox (cairo_recording_surface_t *recording,
cairo_box_t *bbox,
const cairo_matrix_t *transform);
cairo_private cairo_status_t
_cairo_recording_surface_get_ink_bbox (cairo_recording_surface_t *surface,
cairo_box_t *bbox,
const cairo_matrix_t *transform);
cairo_private cairo_bool_t
_cairo_recording_surface_has_only_bilevel_alpha (cairo_recording_surface_t *surface);
cairo_private cairo_bool_t
_cairo_recording_surface_has_only_op_over (cairo_recording_surface_t *surface);
#endif /* CAIRO_RECORDING_SURFACE_H */
| 32.443878 | 85 | 0.767574 | [
"render",
"vector",
"transform"
] |
456e3030817500eefa08ddaef2c79f573ab125b7 | 498 | h | C | Clustering.h | MMKaragoz/kmeanspp | c8652cbe05d59af99260c959c684e2f9ee31229e | [
"MIT"
] | 2 | 2022-01-07T18:10:46.000Z | 2022-01-12T10:13:58.000Z | Clustering.h | MMKaragoz/kmeanspp | c8652cbe05d59af99260c959c684e2f9ee31229e | [
"MIT"
] | 1 | 2022-01-07T18:11:37.000Z | 2022-01-07T18:14:45.000Z | Clustering.h | MMKaragoz/kmeanspp | c8652cbe05d59af99260c959c684e2f9ee31229e | [
"MIT"
] | null | null | null | #ifndef CLUSTERING_H
#define CLUSTERING_H
#include "Node.h"
#include <string>
#include <vector>
class Clustering
{
public:
Clustering();
~Clustering();
void readFile(std::string fileName);
void chooseK();
void setK(int K);
int getK() const;
std::vector<Node> &getNodes();
void print() const;
void printNodes() ;
private:
int k; /// number of clusters
std::vector<Node> nodes;
};
#endif | 17.172414 | 44 | 0.558233 | [
"vector"
] |
45745fdb0dcf1995d4f29abb175c140eb2b323b2 | 105,891 | c | C | runtime/flang/miscsup_com.c | pawosm-arm/flang | dc6ca7de36567704d8117536eed60344683d0845 | [
"Apache-2.0"
] | null | null | null | runtime/flang/miscsup_com.c | pawosm-arm/flang | dc6ca7de36567704d8117536eed60344683d0845 | [
"Apache-2.0"
] | null | null | null | runtime/flang/miscsup_com.c | pawosm-arm/flang | dc6ca7de36567704d8117536eed60344683d0845 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 1995-2018, NVIDIA CORPORATION. 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.
*
*/
/* clang-format off */
/** \file
* \brief
* Collection of misc Fortran intrinsics (present, min, max, ajustl, adjustl, ...).
*
*/
#include <time.h>
#include <string.h>
#include <sys/time.h>
#include <unistd.h>
#include "stdioInterf.h"
#include "fioMacros.h"
#include "llcrit.h"
#include "global.h"
#include "memops.h"
MP_SEMAPHORE(static, sem);
#include "type.h"
extern double __fort_second();
extern long __fort_getoptn(char *, long);
#define time(x) __fort_time(x)
typedef __INT8_T MXINT_T;
static void store_mxint_t(void *, F90_Desc *, MXINT_T);
static MXINT_T mxint(F90_Desc *);
__INT_T
ENTFTN(ILEN, ilen)(void *ib, __INT_T *size)
{
/*
* if i is nonnegative,
* ilen(i) = ceiling(log2(i+1))
* if i is negative,
* ilen(i) = ceiling(log2(-i))
*/
unsigned ui;
int i, k, ln;
i = I8(__fort_varying_int)(ib, size);
if (i < 0)
i = -i;
else
++i;
/* find bit position (relative to 0) of the leftmost 1 bit */
ui = i;
ln = -1;
k = (*size * 8) >> 1;
while (k) {
if (ui >> k) {
ui >>= k;
ln += k;
}
k >>= 1;
}
if (ui)
++ln;
/* if i is larger than 2**(bit pos), increase by one */
if (i ^ (1 << ln))
++ln;
return ln;
}
__LOG_T
ENTF90(PRESENT, present)(void *p)
{
if (p == NULL) {
return 0;
}
#if defined(DESC_I8)
if (!((__INT4_T *)(p) >= ENTCOMN(0, 0) &&
(__INT4_T *)(p) <= (ENTCOMN(0, 0) + 3)))
#else
if (!((__INT_T *)(p) >= ENTCOMN(0, 0) &&
(__INT_T *)(p) <= (ENTCOMN(0, 0) + 3)))
#endif
return GET_DIST_TRUE_LOG;
else
return 0;
}
__LOG_T
ENTF90(PRESENT_PTR, present_ptr)(void *p)
{
if (p == NULL) {
return 0;
}
#if defined(DESC_I8)
if (!((__INT4_T *)(p) >= ENTCOMN(0, 0) &&
(__INT4_T *)(p) <= (ENTCOMN(0, 0) + 3)) &&
!(*(__INT4_T **)(p) >= ENTCOMN(0, 0) &&
*(__INT4_T **)(p) <= (ENTCOMN(0, 0) + 3)))
#else
if (!((__INT_T *)(p) >= ENTCOMN(0, 0) &&
(__INT_T *)(p) <= (ENTCOMN(0, 0) + 3)) &&
!(*(__INT_T **)(p) >= ENTCOMN(0, 0) &&
*(__INT_T **)(p) <= (ENTCOMN(0, 0) + 3)))
#endif
return GET_DIST_TRUE_LOG;
else
return 0;
}
__LOG_T
ENTF90(PRESENTCA, presentca)(DCHAR(p) DCLEN64(p))
{
if (CADR(p) == NULL) {
return 0;
}
if (CADR(p) != ABSENTC)
return GET_DIST_TRUE_LOG;
else
return 0;
}
/* 32 bit CLEN version */
__LOG_T
ENTF90(PRESENTC, presentc)(DCHAR(p) DCLEN(p))
{
ENTF90(PRESENTCA, presentca)(CADR(p), (__CLEN_T)CLEN(p));
}
/** \brief
* -i8 variant of present
*/
__LOG8_T
ENTF90(KPRESENT, kpresent)(void *p)
{
return (__INT8_T)ISPRESENT(p) ? GET_DIST_TRUE_LOG : 0;
}
__LOG8_T
ENTF90(KPRESENT_PTR, kpresent_ptr)(void *p)
{
/*
* -i8 variant of present
*/
if (p == NULL) {
return 0;
}
#if defined(DESC_I8)
if (!((__INT4_T *)(p) >= ENTCOMN(0, 0) &&
(__INT4_T *)(p) <= (ENTCOMN(0, 0) + 3)) &&
!(*(__INT4_T **)(p) >= ENTCOMN(0, 0) &&
*(__INT4_T **)(p) <= (ENTCOMN(0, 0) + 3)))
#else
if (!((__INT_T *)(p) >= ENTCOMN(0, 0) &&
(__INT_T *)(p) <= (ENTCOMN(0, 0) + 3)) &&
!(*(__INT_T **)(p) >= ENTCOMN(0, 0) &&
*(__INT_T **)(p) <= (ENTCOMN(0, 0) + 3)))
#endif
return GET_DIST_TRUE_LOG;
else
return 0;
}
__LOG8_T
ENTF90(KPRESENTCA, kpresentca)(DCHAR(p) DCLEN64(p))
{
/*
* -i8 variant of PRESENTC
*/
return (__INT8_T)ISPRESENTC(p) ? GET_DIST_TRUE_LOG : 0;
}
/* 32 bit CLEN version */
__LOG8_T
ENTF90(KPRESENTC, kpresentc)(DCHAR(p) DCLEN(p))
{
return ENTF90(KPRESENTCA, kpresentca)(CADR(p), (__CLEN_T)CLEN(p));
}
__LOG_T
ENTF90(IS_IOSTAT_END, is_iostat_end)(__INT4_T i)
{
return (i == -1) ? GET_DIST_TRUE_LOG : 0;
}
__LOG8_T
ENTF90(KIS_IOSTAT_END, kis_iostat_end)(__INT4_T i)
{
return (i == -1) ? GET_DIST_TRUE_LOG : 0;
}
__LOG_T
ENTF90(IS_IOSTAT_EOR, is_iostat_eor)(__INT4_T i)
{
return (i == -2) ? GET_DIST_TRUE_LOG : 0;
}
__LOG8_T
ENTF90(KIS_IOSTAT_EOR, kis_iostat_eor)(__INT4_T i)
{
return (i == -2) ? GET_DIST_TRUE_LOG : 0;
}
void
*ENTF90(LOC, loc)(void *p)
{
return p;
}
__INT_T
ENTF90(IMAX, imax)(__INT_T i, __INT_T j)
{
return (i > j) ? i : j;
}
#if !defined(DESC_I8)
void
ENTF90(MIN, min)(int *nargs, ...)
{
char *nextstr;
char *minstr;
char *result;
int i, j;
__CLEN_T clen;
va_list argp;
va_start(argp, nargs);
j = *nargs;
/* First loop through the argument list to get character len */
result = va_arg(argp, char *);
minstr = va_arg(argp, char *);
if (result == NULL)
return;
/* argument list */
for (i = 0; i < j; ++i) {
nextstr = va_arg(argp, char *);
}
clen = va_arg(argp, __CLEN_T);
va_end(argp);
/* start real comparison */
va_start(argp, nargs);
result = va_arg(argp, char *);
minstr = va_arg(argp, char *);
if (minstr == NULL)
return;
for (i = 0; i < j - 1; ++i) {
nextstr = va_arg(argp, char *);
if (nextstr) {
if (strncmp(nextstr, minstr, clen) < 0)
minstr = nextstr;
}
}
strncpy(result, minstr, clen);
va_end(argp);
}
void
ENTF90(MAX, max)(int *nargs, ...)
{
char *nextstr;
char *maxstr;
char *result;
int i, j;
__CLEN_T clen;
va_list argp;
va_start(argp, nargs);
j = *nargs;
/* First loop through the argument list to get character len */
result = va_arg(argp, char *);
maxstr = va_arg(argp, char *);
if (result == NULL)
return;
/* argument list */
for (i = 0; i < j; ++i) {
nextstr = va_arg(argp, char *);
}
clen = va_arg(argp, __CLEN_T);
va_end(argp);
/* start real comparison */
va_start(argp, nargs);
result = va_arg(argp, char *);
maxstr = va_arg(argp, char *);
if (maxstr == NULL)
return;
for (i = 0; i < j - 1; ++i) {
nextstr = va_arg(argp, char *);
if (nextstr) {
if (strncmp(nextstr, maxstr, clen) > 0)
maxstr = nextstr;
}
}
strncpy(result, maxstr, clen);
va_end(argp);
}
#endif
__INT8_T
ENTF90(KICHARA, kichara)
(DCHAR(c) DCLEN64(c))
{
return (__INT8_T)(CADR(c)[0] & 0xff);
}
/* 32 bit CLEN version */
__INT8_T
ENTF90(KICHAR, kichar)
(DCHAR(c) DCLEN(c))
{
return ENTF90(KICHARA, kichara)(CADR(c), (__CLEN_T)CLEN(c));
}
__INT_T
ENTF90(LENA, lena)(DCHAR(s) DCLEN64(s))
{
return (__INT_T)CLEN(s);
}
/* 32 bit CLEN version */
__INT_T
ENTF90(LEN, len)(DCHAR(s) DCLEN(s))
{
return (__INT_T) ENTF90(LENA, lena)(CADR(s), (__CLEN_T)CLEN(s));
}
__INT8_T
ENTF90(KLENA, klena)(DCHAR(s) DCLEN64(s))
{
return (__INT8_T)CLEN(s);
}
/* 32 bit CLEN version */
__INT8_T
ENTF90(KLEN, klen)(DCHAR(s) DCLEN(s))
{
return ENTF90(KLENA, klena)(CADR(s), (__CLEN_T)CLEN(s));
}
__INT_T
ENTF90(NLENA, nlena)(DCHAR(s) DCLEN64(s))
{
return (__INT_T)CLEN(s);
}
/* 32 bit CLEN version */
__INT_T
ENTF90(NLEN, nlen)(DCHAR(s) DCLEN(s))
{
return ENTF90(NLENA, nlena)(CADR(s), (__CLEN_T)CLEN(s));
}
__CLEN_T
ENTF90(ADJUSTLA, adjustla)
(DCHAR(res), DCHAR(expr) DCLEN64(res) DCLEN64(expr))
{
__CLEN_T i, j, elen, rlen;
elen = CLEN(expr);
rlen = CLEN(res);
for (i = 0; i < elen && CADR(expr)[i] == ' '; ++i)
;
for (j = 0; i < elen; ++i, ++j)
CADR(res)[j] = CADR(expr)[i];
for (; j < rlen; ++j)
CADR(res)[j] = ' ';
return elen;
}
/* 32 bit CLEN version */
__INT_T
ENTF90(ADJUSTL, adjustl)
(DCHAR(res), DCHAR(expr) DCLEN(res) DCLEN(expr))
{
return (__INT_T)ENTF90(ADJUSTLA, adjustla)(CADR(res), CADR(expr),
(__CLEN_T)CLEN(res), (__CLEN_T)CLEN(expr));
}
__CLEN_T
ENTF90(ADJUSTRA, adjustra)
(DCHAR(res), DCHAR(expr) DCLEN64(res) DCLEN64(expr))
{
__CLEN_T i, j, len;
len = CLEN(expr);
for (i = len; i-- > 0 && CADR(expr)[i] == ' ';)
;
for (++i, j = len-1; i-- > 0; --j)
CADR(res)[j] = CADR(expr)[i];
for (++j; j-- > 0; )
CADR(res)[j] = ' ';
return len;
}
/* 32 bit CLEN version */
__INT_T
ENTF90(ADJUSTR, adjustr)
(DCHAR(res), DCHAR(expr) DCLEN(res) DCLEN(expr))
{
return (__INT_T)ENTF90(ADJUSTRA, adjustra)(CADR(res), CADR(expr),
(__CLEN_T)CLEN(res), (__CLEN_T)CLEN(expr));
}
static void
fstrcpy(char *s1, char *s2, __CLEN_T len1, __CLEN_T len2)
{
__CLEN_T i;
if (len2 < len1) {
for (i = 0; i < len2; ++i)
s1[i] = s2[i];
for (; i < len1; ++i)
s1[i] = ' ';
} else {
for (i = 0; i < len1; ++i)
s1[i] = s2[i];
}
}
static char *month[12] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
static int
yr2(int yr)
{
int y = yr;
if (y > 99)
y = y % 100;
return y;
}
void
ENTFTN(DATEA, datea)(DCHAR(date), F90_Desc *dated DCLEN64(date))
{
char loc_buf[16];
time_t ltime;
struct tm *lt;
ltime = time();
MP_P(sem);
;
lt = localtime(<ime);
sprintf(loc_buf, "%2d-%3s-%02d", lt->tm_mday, month[lt->tm_mon],
yr2(lt->tm_year));
MP_V(sem);
fstrcpy(CADR(date), loc_buf, CLEN(date), 9);
}
/* 32 bit CLEN version */
void
ENTFTN(DATE, date)(DCHAR(date), F90_Desc *dated DCLEN(date))
{
ENTFTN(DATEA, datea)(CADR(date), dated, (__CLEN_T)CLEN(date));
}
void
ENTFTN(DATEW, datew)(void *date, F90_Desc *dated)
{
char loc_buf[16];
time_t ltime;
struct tm *lt;
ltime = time();
MP_P(sem);
;
lt = localtime(<ime);
sprintf(loc_buf, "%2d-%3s-%02d", lt->tm_mday, month[lt->tm_mon],
yr2(lt->tm_year));
MP_V(sem);
fstrcpy(date, loc_buf, 9, 9);
}
void
ENTFTN(JDATE, jdate)(__INT4_T *i, __INT4_T *j, __INT4_T *k, F90_Desc *id,
F90_Desc *jd, F90_Desc *kd)
{
time_t ltime;
struct tm *ltimvar;
ltime = time();
MP_P(sem);
;
ltimvar = localtime(<ime);
*i = ltimvar->tm_mon + 1;
*j = ltimvar->tm_mday;
*k = yr2(ltimvar->tm_year);
MP_V(sem);
}
void
ENTFTN(IDATE, idate)(__INT2_T *i, __INT2_T *j, __INT2_T *k, F90_Desc *id,
F90_Desc *jd, F90_Desc *kd)
{
time_t ltime;
struct tm *ltimvar;
ltime = time();
MP_P(sem);
;
ltimvar = localtime(<ime);
*i = ltimvar->tm_mon + 1;
*j = ltimvar->tm_mday;
*k = yr2(ltimvar->tm_year);
MP_V(sem);
}
/* trying to deal with loss of significant digits in
real*4 version.
*/
#define TIME_THRESHOLD2 1.033944E+09
#define TIME_THRESHOLD1 1.003944E+09
void
ENTFTN(CPU_TIME, cpu_time)(__REAL4_T *x)
{
extern double __fort_second();
double secs;
__REAL4_T res;
secs = __fort_second();
if (secs > TIME_THRESHOLD2)
res = secs - TIME_THRESHOLD2;
else if (secs > TIME_THRESHOLD1)
res = secs - TIME_THRESHOLD1;
else
res = secs;
*x = res;
}
void
ENTFTN(CPU_TIMED, cpu_timed)(__REAL8_T *x)
{
extern double __fort_second();
double secs;
__REAL8_T res;
secs = __fort_second();
/* probably not necessary for this version, except that
user could mix real*4 and real*8 versions.
*/
if (secs > TIME_THRESHOLD2)
res = secs - TIME_THRESHOLD2;
else if (secs > TIME_THRESHOLD1)
res = secs - TIME_THRESHOLD1;
else
res = secs;
*x = res;
}
__REAL4_T
ENTFTN(SECNDS, secnds)(__REAL4_T *x, F90_Desc *xd)
{
static int called = 0;
static int diffs;
int i;
time_t ltime;
struct tm *lt;
__REAL4_T f;
ltime = time();
if (called == 0) {
called = 1; /* first time called */
/*
* compute value to subtract from time(0) to give seconds since
* midnight
*/
MP_P(sem);
;
lt = localtime(<ime);
i = lt->tm_sec + (60 * lt->tm_min) + (3600 * lt->tm_hour);
MP_V(sem);
diffs = ltime - i;
}
f = (__REAL4_T)(ltime - diffs);
return (f - *x);
}
__REAL8_T
ENTFTN(SECNDSD, secndsd)(__REAL8_T *x, F90_Desc *xd)
{
static int called = 0;
static int diffs;
int i;
time_t ltime;
struct tm *lt;
__REAL8_T f;
ltime = time();
if (called == 0) {
called = 1; /* first time called */
/*
* compute value to subtract from time() to give seconds since
* midnight
*/
MP_P(sem);
;
lt = localtime(<ime);
i = lt->tm_sec + (60 * lt->tm_min) + (3600 * lt->tm_hour);
MP_V(sem);
diffs = ltime - i;
}
f = (__REAL8_T)(ltime - diffs);
return (f - *x);
}
void
ENTFTN(FTIMEA, ftimea)(DCHAR(tbuf), F90_Desc *tbufd DCLEN64(tbuf))
{
char loc_buf[16];
time_t ltime;
struct tm *ltimvar;
ltime = time();
MP_P(sem);
;
ltimvar = localtime(<ime);
sprintf(loc_buf, "%2.2d:%2.2d:%2.2d", ltimvar->tm_hour, ltimvar->tm_min,
ltimvar->tm_sec);
MP_V(sem);
fstrcpy(CADR(tbuf), loc_buf, CLEN(tbuf), 8);
}
/* 32 bit CLEN version */
void
ENTFTN(FTIME, ftime)(DCHAR(tbuf), F90_Desc *tbufd DCLEN(tbuf))
{
ENTFTN(FTIMEA, ftimea)(CADR(tbuf), tbufd, (__CLEN_T)CLEN(tbuf));
}
void
ENTFTN(FTIMEW, ftimew)(void *tbuf, F90_Desc *tbufd)
{
char loc_buf[16];
time_t ltime;
struct tm *ltimvar;
ltime = time();
MP_P(sem);
;
ltimvar = localtime(<ime);
sprintf(loc_buf, "%2.2d:%2.2d:%2.2d", ltimvar->tm_hour, ltimvar->tm_min,
ltimvar->tm_sec);
MP_V(sem);
fstrcpy(tbuf, loc_buf, 8, 8);
}
static int
I8(next_index)(__INT_T *index, F90_Desc *s)
{
__INT_T i;
for (i = 0; i < F90_RANK_G(s); i++) {
index[i]++;
if (index[i] <= DIM_UBOUND_G(s, i)) {
return 1; /* keep going */
}
index[i] = F90_DIM_LBOUND_G(s, i);
}
return 0; /* finished */
}
void
ENTFTN(DANDTA, dandta)(DCHAR(date), DCHAR(tbuf), DCHAR(zone),
__STAT_T *values, F90_Desc *dated, F90_Desc *tbufd,
F90_Desc *zoned,
F90_Desc *valuesd DCLEN64(date) DCLEN64(tbuf) DCLEN64(zone))
{
int tvalues[8];
int i;
char c;
time_t ltime;
struct tm *tm, tmx;
char loc_buf[16];
int ms;
#if defined(TARGET_OSX)
struct timeval t;
struct timezone tz0;
#else
struct timeval t;
#endif
#if defined(TARGET_OSX)
gettimeofday(&t, &tz0);
ltime = t.tv_sec;
ms = t.tv_usec / 1000;
#else
gettimeofday(&t, (void *)0);
ltime = t.tv_sec;
ms = t.tv_usec / 1000;
#endif
MP_P(sem);
;
tm = localtime(<ime);
if (tm == NULL) {
fprintf(__io_stderr(), "BAD return value from localtime(0x%lx)\n",
(long)ltime);
perror("localtime: ");
exit(1);
}
memcpy(&tmx, tm, sizeof(struct tm));
tm = &tmx;
MP_V(sem);
if (ISPRESENTC(date) && CLEN(date) > 0) {
sprintf(loc_buf, "%04d%02d%02d", tm->tm_year + 1900, tm->tm_mon + 1,
tm->tm_mday);
fstrcpy(CADR(date), loc_buf, CLEN(date), 8);
}
if (ISPRESENTC(tbuf) && CLEN(tbuf) > 0) {
sprintf(loc_buf, "%02d%02d%02d.%03d", tm->tm_hour, tm->tm_min, tm->tm_sec,
ms);
fstrcpy(CADR(tbuf), loc_buf, CLEN(tbuf), 10);
}
if (ISPRESENTC(zone) && CLEN(zone) > 0) {
i = __io_timezone(tm);
c = '+';
if (i < 0) {
i = -i;
c = '-';
}
i /= 60;
sprintf(loc_buf, "%c%02d%02d", c, i / 60, i % 60);
fstrcpy(CADR(zone), loc_buf, CLEN(zone), 5);
}
if (ISPRESENT(values)) {
tvalues[0] = tm->tm_year + 1900;
tvalues[1] = tm->tm_mon + 1;
tvalues[2] = tm->tm_mday;
i = __io_timezone(tm);
c = '+';
if (i < 0) {
i = -i;
c = '-';
}
i /= 60;
if (c == '-')
i = -i;
tvalues[3] = i;
tvalues[4] = tm->tm_hour;
tvalues[5] = tm->tm_min;
tvalues[6] = tm->tm_sec;
tvalues[7] = ms;
if (valuesd && F90_TAG_G(valuesd) == __DESC) {
char *la;
__INT_T index[7];
for (i = 0; i < F90_RANK_G(valuesd); ++i) {
if (DIM_UBOUND_G(valuesd, i) < F90_DIM_LBOUND_G(valuesd, i))
return;
index[i] = F90_DIM_LBOUND_G(valuesd, i);
}
for (i = 0; i < 8; ++i) {
la = I8(__fort_local_address)(values, valuesd, index);
if (la) {
/* *((int *)la) = tvalues[i]; */
store_mxint_t(la, valuesd, tvalues[i]);
}
if (I8(next_index)(index, valuesd) == 0)
break;
}
} else {
for (i = 0; i < 8; ++i)
values[i] = tvalues[i];
}
}
}
/* 32 bit CLEN version */
void
ENTFTN(DANDT, dandt)(DCHAR(date), DCHAR(tbuf), DCHAR(zone),
__STAT_T *values, F90_Desc *dated, F90_Desc *tbufd,
F90_Desc *zoned,
F90_Desc *valuesd DCLEN(date) DCLEN(tbuf) DCLEN(zone))
{
ENTFTN(DANDTA, dandta)(CADR(date), CADR(tbuf), CADR(zone), values, dated,
tbufd, zoned, valuesd, (__CLEN_T)CLEN(date),
(__CLEN_T)CLEN(tbuf), (__CLEN_T)CLEN(zone));
}
void
ENTFTN(SYSCLK, sysclk)(__STAT_T *count, __STAT_T *count_rate,
__STAT_T *count_max, F90_Desc *countd,
F90_Desc *count_rated, F90_Desc *count_maxd)
{
static MXINT_T resol; /* resolution, tics per second */
int sz;
if (resol == 0) {
int def;
def = 1000000;
resol = __fort_getoptn("-system_clock_rate", def);
if (resol <= 0)
__fort_abort("invalid value given for system_clock rate");
}
if (ISPRESENT(count_rate)) {
if (ISPRESENT(count)) {
sz = GET_DIST_SIZE_OF(TYPEKIND(countd));
} else {
sz = GET_DIST_SIZE_OF(TYPEKIND(count_rated));
}
switch (sz) {
case 1:
resol = 10;
break;
case 2:
resol = 1000;
break;
case 4:
resol = 1000000;
break;
default: /* big*/
resol = 10000000;
break;
}
}
if (ISPRESENT(count)) {
double t = __fort_second();
MXINT_T mxt;
mxt = mxint(countd);
if (t * resol > mxt) {
t = 0;
__fort_set_second(t);
}
store_mxint_t(count, countd, (t)*resol);
}
if (ISPRESENT(count_rate)) {
store_mxint_t(count_rate, count_rated, resol);
}
if (ISPRESENT(count_max)) {
if (ISPRESENT(count)) {
store_mxint_t(count_max, count_maxd, mxint(countd));
} else {
store_mxint_t(count_max, count_maxd, mxint(count_maxd));
}
}
}
void
ENTF90(MVBITS, mvbits)(void *from, void *frompos, void *len, void *to,
void *topos, __INT_T *szfrom, __INT_T *szfrompos,
__INT_T *szlen, __INT_T *sztopos)
{
__INT1_T f1, t1, m1;
__INT2_T f2, t2, m2;
__INT4_T f4, t4, m4;
__INT8_T f8, t8, m8;
int fp = I8(__fort_varying_int)(frompos, szfrompos);
int ln = I8(__fort_varying_int)(len, szlen);
int tp = I8(__fort_varying_int)(topos, sztopos);
#undef MVBIT_OVFL
#define MVBIT_OVFL(w) ((fp + ln) > (w) || (tp + ln) > (w))
if (fp < 0 || tp < 0 || ln <= 0)
return;
switch (*szfrom) {
case 1:
if (MVBIT_OVFL(8))
break;
if (ln == 8) {
*(__INT1_T *)to = *(__INT1_T *)from;
break;
}
f1 = *(__INT1_T *)from;
t1 = *(__INT1_T *)to;
m1 = (~(-1 << ln)) << tp;
*(__INT1_T *)to = (t1 & ~m1) | (((f1 >> fp) << tp) & m1);
break;
case 2:
if (MVBIT_OVFL(16))
break;
if (ln == 16) {
*(__INT2_T *)to = *(__INT2_T *)from;
break;
}
f2 = *(__INT2_T *)from;
t2 = *(__INT2_T *)to;
m2 = (~(-1 << ln)) << tp;
*(__INT2_T *)to = (t2 & ~m2) | (((f2 >> fp) << tp) & m2);
break;
case 4:
if (MVBIT_OVFL(32))
break;
if (ln == 32) {
*(__INT4_T *)to = *(__INT4_T *)from;
break;
}
f4 = *(__INT4_T *)from;
t4 = *(__INT4_T *)to;
m4 = (~(-1 << ln)) << tp;
*(__INT4_T *)to = (t4 & ~m4) | (((f4 >> fp) << tp) & m4);
break;
case 8:
if (MVBIT_OVFL(64))
break;
if (ln == 64) {
*(__INT8_T *)to = *(__INT8_T *)from;
break;
}
f8 = *(__INT8_T *)from;
t8 = *(__INT8_T *)to;
m8 = (~((__INT8_T)-1 << ln)) << tp;
*(__INT8_T *)to = (t8 & ~m8) | (((f8 >> fp) << tp) & m8);
break;
default:
__fort_abort("MVBITS: unsupported from/to integer size");
}
}
/** \brief
*Varargs: __INT_T *lb1, __INT_T *ub1, ... __INT_T *lb<rank>, __INT_T *ub<rank>
*/
__INT_T
ENTF90(LB, lb)(__INT4_T *rank, __INT4_T *dim, ...)
{
va_list va;
__INT_T *lb;
__INT_T *ub;
__INT_T d;
d = *dim;
if (d < 1 || d > *rank)
__fort_abort("LBOUND: invalid dim");
va_start(va, dim);
while (d-- > 0) {
lb = va_arg(va, __INT_T *);
ub = va_arg(va, __INT_T *);
}
va_end(va);
if (!ISPRESENT(lb))
__fort_abort("LBOUND: lower bound not present for specified dim");
if (!ISPRESENT(ub))
/* presumably, it's the last dimension of an assumed array */
return *lb;
return (*lb <= *ub) ? *lb : 1;
}
/* Varargs:
* __INT_T *lb1, __INT_T *ub1, ... __INT_T *lb<rank>, __INT_T *ub<rank>
*/
__INT1_T
ENTF90(LB1, lb1)(__INT4_T *rank, __INT4_T *dim, ...)
{
va_list va;
__INT_T *lb;
__INT_T *ub;
__INT_T d;
d = *dim;
if (d < 1 || d > *rank)
__fort_abort("LBOUND: invalid dim");
va_start(va, dim);
while (d-- > 0) {
lb = va_arg(va, __INT_T *);
ub = va_arg(va, __INT_T *);
}
va_end(va);
if (!ISPRESENT(lb))
__fort_abort("LBOUND: lower bound not present for specified dim");
if (!ISPRESENT(ub))
/* presumably, it's the last dimension of an assumed array */
return (__INT1_T)*lb;
return (__INT1_T)(*lb <= *ub) ? *lb : 1;
}
/* Varargs:
* __INT_T *lb1, __INT_T *ub1, ... __INT_T *lb<rank>, __INT_T *ub<rank>
*/
__INT2_T
ENTF90(LB2, lb2)(__INT4_T *rank, __INT4_T *dim, ...)
{
va_list va;
__INT_T *lb;
__INT_T *ub;
__INT_T d;
d = *dim;
if (d < 1 || d > *rank)
__fort_abort("LBOUND: invalid dim");
va_start(va, dim);
while (d-- > 0) {
lb = va_arg(va, __INT_T *);
ub = va_arg(va, __INT_T *);
}
va_end(va);
if (!ISPRESENT(lb))
__fort_abort("LBOUND: lower bound not present for specified dim");
if (!ISPRESENT(ub))
/* presumably, it's the last dimension of an assumed array */
return (__INT2_T)*lb;
return (__INT2_T)(*lb <= *ub) ? *lb : 1;
}
/* Varargs: __INT_T *lb1, __INT_T *ub1, ... __INT_T *lb<rank>, __INT_T *ub<rank> */
__INT4_T
ENTF90(LB4, lb4)(__INT4_T *rank, __INT4_T *dim, ...)
{
va_list va;
__INT_T *lb;
__INT_T *ub;
__INT_T d;
d = *dim;
if (d < 1 || d > *rank)
__fort_abort("LBOUND: invalid dim");
va_start(va, dim);
while (d-- > 0) {
lb = va_arg(va, __INT_T *);
ub = va_arg(va, __INT_T *);
}
va_end(va);
if (!ISPRESENT(lb))
__fort_abort("LBOUND: lower bound not present for specified dim");
if (!ISPRESENT(ub))
/* presumably, it's the last dimension of an assumed array */
return (__INT4_T)*lb;
return (__INT4_T)(*lb <= *ub) ? *lb : 1;
}
/* Varargs: __INT_T *lb1, __INT_T *ub1, ... __INT_T *lb<rank>, __INT_T *ub<rank> */
__INT8_T
ENTF90(LB8, lb8)(__INT4_T *rank, __INT4_T *dim, ...)
{
va_list va;
__INT_T *lb;
__INT_T *ub;
__INT_T d;
d = *dim;
if (d < 1 || d > *rank)
__fort_abort("LBOUND: invalid dim");
va_start(va, dim);
while (d-- > 0) {
lb = va_arg(va, __INT_T *);
ub = va_arg(va, __INT_T *);
}
va_end(va);
if (!ISPRESENT(lb))
__fort_abort("LBOUND: lower bound not present for specified dim");
if (!ISPRESENT(ub))
/* presumably, it's the last dimension of an assumed array */
return (__INT8_T)*lb;
return (__INT8_T)(*lb <= *ub) ? *lb : 1;
}
/* Varargs: __INT_T *lb1, __INT_T *ub1, ... __INT_T *lb<rank>, __INT_T *ub<rank> */
__INT8_T
ENTF90(KLB, klb)(__INT4_T *rank, __INT4_T *dim, ...)
{
/*
* -i8 variant of LB
*/
va_list va;
__INT_T *lb;
__INT_T *ub;
__INT_T d;
d = *dim;
if (d < 1 || d > *rank)
__fort_abort("LBOUND: invalid dim");
va_start(va, dim);
while (d-- > 0) {
lb = va_arg(va, __INT_T *);
ub = va_arg(va, __INT_T *);
}
va_end(va);
if (!ISPRESENT(lb))
__fort_abort("LBOUND: lower bound not present for specified dim");
if (!ISPRESENT(ub))
/* presumably, it's the last dimension of an assumed array */
return *lb;
return (__INT8_T)(*lb <= *ub) ? *lb : 1;
}
/* Varargs: __INT_T *lb1, __INT_T *ub1, ... __INT_T *lb<rank>, __INT_T *ub<rank> */
__INT_T
ENTF90(UB, ub)(__INT4_T *rank, __INT4_T *dim, ...)
{
va_list va;
__INT_T *lb;
__INT_T *ub;
__INT_T d;
d = *dim;
if (d < 1 || d > *rank)
__fort_abort("UBOUND: invalid dim");
va_start(va, dim);
while (d-- > 0) {
lb = va_arg(va, __INT_T *);
ub = va_arg(va, __INT_T *);
}
va_end(va);
if (!ISPRESENT(ub))
__fort_abort("UBOUND: upper bound not present for specified dim");
return (*lb <= *ub) ? *ub : 0;
}
/* Varargs: __INT_T *lb1, __INT_T *ub1, ... __INT_T *lb<rank>, __INT_T *ub<rank> */
__INT1_T
ENTF90(UB1, ub1)(__INT4_T *rank, __INT4_T *dim, ...)
{
va_list va;
__INT_T *lb;
__INT_T *ub;
__INT_T d;
d = *dim;
if (d < 1 || d > *rank)
__fort_abort("UBOUND: invalid dim");
va_start(va, dim);
while (d-- > 0) {
lb = va_arg(va, __INT_T *);
ub = va_arg(va, __INT_T *);
}
va_end(va);
if (!ISPRESENT(ub))
__fort_abort("UBOUND: upper bound not present for specified dim");
return (__INT1_T)(*lb <= *ub) ? *ub : 0;
}
/* Varargs: __INT_T *lb1, __INT_T *ub1, ... __INT_T *lb<rank>, __INT_T *ub<rank> */
__INT2_T
ENTF90(UB2, ub2)(__INT4_T *rank, __INT4_T *dim, ...)
{
va_list va;
__INT_T *lb;
__INT_T *ub;
__INT_T d;
d = *dim;
if (d < 1 || d > *rank)
__fort_abort("UBOUND: invalid dim");
va_start(va, dim);
while (d-- > 0) {
lb = va_arg(va, __INT_T *);
ub = va_arg(va, __INT_T *);
}
va_end(va);
if (!ISPRESENT(ub))
__fort_abort("UBOUND: upper bound not present for specified dim");
return (__INT2_T)(*lb <= *ub) ? *ub : 0;
}
/* Varargs: __INT_T *lb1, __INT_T *ub1, ... __INT_T *lb<rank>, __INT_T *ub<rank> */
__INT4_T
ENTF90(UB4, ub4)(__INT4_T *rank, __INT4_T *dim, ...)
{
va_list va;
__INT_T *lb;
__INT_T *ub;
__INT_T d;
d = *dim;
if (d < 1 || d > *rank)
__fort_abort("UBOUND: invalid dim");
va_start(va, dim);
while (d-- > 0) {
lb = va_arg(va, __INT_T *);
ub = va_arg(va, __INT_T *);
}
va_end(va);
if (!ISPRESENT(ub))
__fort_abort("UBOUND: upper bound not present for specified dim");
return (__INT4_T)(*lb <= *ub) ? *ub : 0;
}
/* Varargs: __INT_T *lb1, __INT_T *ub1, ... __INT_T *lb<rank>, __INT_T *ub<rank> */
__INT8_T
ENTF90(UB8, ub8)(__INT4_T *rank, __INT4_T *dim, ...)
{
va_list va;
__INT_T *lb;
__INT_T *ub;
__INT_T d;
d = *dim;
if (d < 1 || d > *rank)
__fort_abort("UBOUND: invalid dim");
va_start(va, dim);
while (d-- > 0) {
lb = va_arg(va, __INT_T *);
ub = va_arg(va, __INT_T *);
}
va_end(va);
if (!ISPRESENT(ub))
__fort_abort("UBOUND: upper bound not present for specified dim");
return (__INT8_T)(*lb <= *ub) ? *ub : 0;
}
/* Varargs: __INT_T *lb1, __INT_T *ub1, ... __INT_T *lb<rank>, __INT_T *ub<rank> */
__INT8_T
ENTF90(KUB, kub)(__INT4_T *rank, __INT4_T *dim, ...)
{
/*
* -i8 variant of UB
*/
va_list va;
__INT_T *lb;
__INT_T *ub;
__INT_T d;
d = *dim;
if (d < 1 || d > *rank)
__fort_abort("UBOUND: invalid dim");
va_start(va, dim);
while (d-- > 0) {
lb = va_arg(va, __INT_T *);
ub = va_arg(va, __INT_T *);
}
va_end(va);
if (!ISPRESENT(ub))
__fort_abort("UBOUND: upper bound not present for specified dim");
return (__INT8_T)(*lb <= *ub) ? *ub : 0;
}
/* Varargs: __INT_T *lb1, __INT_T *ub1, ... __INT_T *lb<size>, __INT_T *ub<size> */
void
ENTF90(LBA, lba)(__INT_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *lb;
__INT_T *ub;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
lb = va_arg(va, __INT_T *);
if (!ISPRESENT(lb))
__fort_abort("LBOUND: lower bound not present");
ub = va_arg(va, __INT_T *);
if (!ISPRESENT(ub))
/* presumably, it's the last dimension of an assumed array */
*arr++ = *lb;
else
*arr++ = (*lb <= *ub) ? *lb : 1;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, __INT_T *ub1, ... __INT_T *lb<size>, __INT_T *ub<size> */
void
ENTF90(LBA1, lba1)(__INT1_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *lb;
__INT_T *ub;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
lb = va_arg(va, __INT_T *);
if (!ISPRESENT(lb))
__fort_abort("LBOUND: lower bound not present");
ub = va_arg(va, __INT_T *);
if (!ISPRESENT(ub))
/* presumably, it's the last dimension of an assumed array */
*arr++ = *lb;
else
*arr++ = (*lb <= *ub) ? *lb : 1;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, __INT_T *ub1, ... __INT_T *lb<size>, __INT_T *ub<size> */
void
ENTF90(LBA2, lba2)(__INT2_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *lb;
__INT_T *ub;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
lb = va_arg(va, __INT_T *);
if (!ISPRESENT(lb))
__fort_abort("LBOUND: lower bound not present");
ub = va_arg(va, __INT_T *);
if (!ISPRESENT(ub))
/* presumably, it's the last dimension of an assumed array */
*arr++ = *lb;
else
*arr++ = (*lb <= *ub) ? *lb : 1;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, __INT_T *ub1, ... __INT_T *lb<size>, __INT_T *ub<size> */
void
ENTF90(LBA4, lba4)(__INT4_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *lb;
__INT_T *ub;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
lb = va_arg(va, __INT_T *);
if (!ISPRESENT(lb))
__fort_abort("LBOUND: lower bound not present");
ub = va_arg(va, __INT_T *);
if (!ISPRESENT(ub))
/* presumably, it's the last dimension of an assumed array */
*arr++ = *lb;
else
*arr++ = (*lb <= *ub) ? *lb : 1;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, __INT_T *ub1, ... __INT_T *lb<size>, __INT_T *ub<size> */
void
ENTF90(LBA8, lba8)(__INT8_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *lb;
__INT_T *ub;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
lb = va_arg(va, __INT_T *);
if (!ISPRESENT(lb))
__fort_abort("LBOUND: lower bound not present");
ub = va_arg(va, __INT_T *);
if (!ISPRESENT(ub))
/* presumably, it's the last dimension of an assumed array */
*arr++ = *lb;
else
*arr++ = (*lb <= *ub) ? *lb : 1;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, __INT_T *ub1, ... __INT_T *lb<size>, __INT_T *ub<size> */
void
ENTF90(KLBA, klba)(__INT8_T *arr, __INT4_T *size, ...)
{
/*
* -i8 variant of LBA
*/
va_list va;
__INT_T *lb;
__INT_T *ub;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
lb = va_arg(va, __INT_T *);
if (!ISPRESENT(lb))
__fort_abort("LBOUND: lower bound not present");
ub = va_arg(va, __INT_T *);
if (!ISPRESENT(ub))
/* presumably, it's the last dimension of an assumed array */
*arr++ = *lb;
else
*arr++ = (*lb <= *ub) ? *lb : 1;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, __INT_T *ub1, ... __INT_T *lb<size>, __INT_T *ub<size> */
void
ENTF90(UBA, uba)(__INT_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *lb;
__INT_T *ub;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
lb = va_arg(va, __INT_T *);
ub = va_arg(va, __INT_T *);
if (!ISPRESENT(ub))
__fort_abort("UBOUND: upper bound not present");
*arr++ = (*lb <= *ub) ? *ub : 0;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, __INT_T *ub1, ... __INT_T *lb<size>, __INT_T *ub<size> */
void
ENTF90(UBA1, uba1)(__INT1_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *lb;
__INT_T *ub;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
lb = va_arg(va, __INT_T *);
ub = va_arg(va, __INT_T *);
if (!ISPRESENT(ub))
__fort_abort("UBOUND: upper bound not present");
*arr++ = (*lb <= *ub) ? *ub : 0;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, __INT_T *ub1, ... __INT_T *lb<size>, __INT_T *ub<size> */
void
ENTF90(UBA2, uba2)(__INT2_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *lb;
__INT_T *ub;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
lb = va_arg(va, __INT_T *);
ub = va_arg(va, __INT_T *);
if (!ISPRESENT(ub))
__fort_abort("UBOUND: upper bound not present");
*arr++ = (*lb <= *ub) ? *ub : 0;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, __INT_T *ub1, ... __INT_T *lb<size>, __INT_T *ub<size> */
void
ENTF90(UBA4, uba4)(__INT4_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *lb;
__INT_T *ub;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
lb = va_arg(va, __INT_T *);
ub = va_arg(va, __INT_T *);
if (!ISPRESENT(ub))
__fort_abort("UBOUND: upper bound not present");
*arr++ = (*lb <= *ub) ? *ub : 0;
}
va_end(va);
}
/* Varargs; __INT_T *lb1, __INT_T *ub1, ... __INT_T *lb<size>, __INT_T *ub<size> */
void
ENTF90(UBA8, uba8)(__INT8_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *lb;
__INT_T *ub;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
lb = va_arg(va, __INT_T *);
ub = va_arg(va, __INT_T *);
if (!ISPRESENT(ub))
__fort_abort("UBOUND: upper bound not present");
*arr++ = (*lb <= *ub) ? *ub : 0;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, __INT_T *ub1, ... __INT_T *lb<size>, __INT_T *ub<size> */
void
ENTF90(KUBA, kuba)(__INT8_T *arr, __INT4_T *size, ...)
{
/*
* -i8 variant of UBA
*/
va_list va;
__INT_T *lb;
__INT_T *ub;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
lb = va_arg(va, __INT_T *);
ub = va_arg(va, __INT_T *);
if (!ISPRESENT(ub))
__fort_abort("UBOUND: upper bound not present");
*arr++ = (*lb <= *ub) ? *ub : 0;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, __INT_T *ub1, ... __INT_T *lb<size>, __INT_T *ub<size> */
void
ENTF90(LBAZ, lbaz)(__INT4_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *lb;
__INT_T *ub;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
lb = va_arg(va, __INT_T *);
if (!ISPRESENT(lb))
__fort_abort("LBOUND: lower bound not present");
ub = va_arg(va, __INT_T *);
if (!ISPRESENT(ub))
/* presumably, it's the last dimension of an assumed array */
*arr++ = *lb;
else
*arr++ = (*lb <= *ub) ? *lb : 1;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, __INT_T *ub1, ... __INT_T *lb<size>, __INT_T *ub<size> */
void
ENTF90(LBAZ1, lbaz1)(__INT1_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *lb;
__INT_T *ub;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
lb = va_arg(va, __INT_T *);
if (!ISPRESENT(lb))
__fort_abort("LBOUND: lower bound not present");
ub = va_arg(va, __INT_T *);
if (!ISPRESENT(ub))
/* presumably, it's the last dimension of an assumed array */
*arr++ = *lb;
else
*arr++ = (*lb <= *ub) ? *lb : 1;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, __INT_T *ub1, ... __INT_T *lb<size>, __INT_T *ub<size> */
void
ENTF90(LBAZ2, lbaz2)(__INT2_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *lb;
__INT_T *ub;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
lb = va_arg(va, __INT_T *);
if (!ISPRESENT(lb))
__fort_abort("LBOUND: lower bound not present");
ub = va_arg(va, __INT_T *);
if (!ISPRESENT(ub))
/* presumably, it's the last dimension of an assumed array */
*arr++ = *lb;
else
*arr++ = (*lb <= *ub) ? *lb : 1;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, __INT_T *ub1, ... __INT_T *lb<size>, __INT_T *ub<size> */
void
ENTF90(LBAZ4, lbaz4)(__INT4_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *lb;
__INT_T *ub;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
lb = va_arg(va, __INT_T *);
if (!ISPRESENT(lb))
__fort_abort("LBOUND: lower bound not present");
ub = va_arg(va, __INT_T *);
if (!ISPRESENT(ub))
/* presumably, it's the last dimension of an assumed array */
*arr++ = *lb;
else
*arr++ = (*lb <= *ub) ? *lb : 1;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, __INT_T *ub1, ... __INT_T *lb<size>, __INT_T *ub<size> */
void
ENTF90(LBAZ8, lbaz8)(__INT8_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *lb;
__INT_T *ub;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
lb = va_arg(va, __INT_T *);
if (!ISPRESENT(lb))
__fort_abort("LBOUND: lower bound not present");
ub = va_arg(va, __INT_T *);
if (!ISPRESENT(ub))
/* presumably, it's the last dimension of an assumed array */
*arr++ = *lb;
else
*arr++ = (*lb <= *ub) ? *lb : 1;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, __INT_T *ub1, ... __INT_T *lb<size>, __INT_T *ub<size> */
void
ENTF90(KLBAZ, klbaz)(__INT8_T *arr, __INT4_T *size, ...)
{
/*
* -i8 variant of LBAZ
*/
va_list va;
__INT_T *lb;
__INT_T *ub;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
lb = va_arg(va, __INT_T *);
if (!ISPRESENT(lb))
__fort_abort("LBOUND: lower bound not present");
ub = va_arg(va, __INT_T *);
if (!ISPRESENT(ub))
/* presumably, it's the last dimension of an assumed array */
*arr++ = *lb;
else
*arr++ = (*lb <= *ub) ? *lb : 1;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, __INT_T *ub1, ... __INT_T *lb<size>, __INT_T *ub<size> */
void
ENTF90(UBAZ, ubaz)(__INT4_T *arr, __INT_T *size, ...)
{
va_list va;
__INT_T *lb;
__INT_T *ub;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
lb = va_arg(va, __INT_T *);
ub = va_arg(va, __INT_T *);
if (!ISPRESENT(ub))
__fort_abort("UBOUND: upper bound not present");
*arr++ = (*lb <= *ub) ? *ub : 0;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, __INT_T *ub1, ... __INT_T *lb<size>, __INT_T *ub<size> */
void
ENTF90(UBAZ1, ubaz1)(__INT1_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *lb;
__INT_T *ub;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
lb = va_arg(va, __INT_T *);
ub = va_arg(va, __INT_T *);
if (!ISPRESENT(ub))
__fort_abort("UBOUND: upper bound not present");
*arr++ = (*lb <= *ub) ? *ub : 0;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, __INT_T *ub1, ... __INT_T *lb<size>, __INT_T *ub<size> */
void
ENTF90(UBAZ2, ubaz2)(__INT2_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *lb;
__INT_T *ub;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
lb = va_arg(va, __INT_T *);
ub = va_arg(va, __INT_T *);
if (!ISPRESENT(ub))
__fort_abort("UBOUND: upper bound not present");
*arr++ = (*lb <= *ub) ? *ub : 0;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, __INT_T *ub1, ... __INT_T *lb<size>, __INT_T *ub<size> */
void
ENTF90(UBAZ4, ubaz4)(__INT4_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *lb;
__INT_T *ub;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
lb = va_arg(va, __INT_T *);
ub = va_arg(va, __INT_T *);
if (!ISPRESENT(ub))
__fort_abort("UBOUND: upper bound not present");
*arr++ = (*lb <= *ub) ? *ub : 0;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, __INT_T *ub1, ... __INT_T *lb<size>, __INT_T *ub<size> */
void
ENTF90(UBAZ8, ubaz8)(__INT8_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *lb;
__INT_T *ub;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
lb = va_arg(va, __INT_T *);
ub = va_arg(va, __INT_T *);
if (!ISPRESENT(ub))
__fort_abort("UBOUND: upper bound not present");
*arr++ = (*lb <= *ub) ? *ub : 0;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, __INT_T *ub1, ... __INT_T *lb<size>, __INT_T *ub<size> */
void
ENTF90(KUBAZ, kubaz)(__INT8_T *arr, __INT4_T *size, ...)
{
/*
* -i8 variant of UBAZ
*/
va_list va;
__INT_T *lb;
__INT_T *ub;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
lb = va_arg(va, __INT_T *);
ub = va_arg(va, __INT_T *);
if (!ISPRESENT(ub))
__fort_abort("UBOUND: upper bound not present");
*arr++ = (*lb <= *ub) ? *ub : 0;
}
va_end(va);
}
/* Varargs: __INT_T *ub1, ... __INT_T *ub<rank> */
__INT_T
ENTF90(LBOUND, lbound)(__INT4_T *rank, __INT4_T *dim, ...)
{
va_list va;
__INT_T *bnd;
__INT_T d;
d = *dim;
if (d < 1 || d > *rank)
__fort_abort("LBOUND: invalid dim");
va_start(va, dim);
while (d-- > 0)
bnd = va_arg(va, __INT_T *);
va_end(va);
if (!ISPRESENT(bnd))
__fort_abort("LBOUND: lower bound not present for specified dim");
return *bnd;
}
/* Varargs: __INT_T *ub1, ... __INT_T *ub<rank> */
__INT1_T
ENTF90(LBOUND1, lbound1)(__INT4_T *rank, __INT4_T *dim, ...)
{
va_list va;
__INT_T *bnd;
__INT_T d;
d = *dim;
if (d < 1 || d > *rank)
__fort_abort("LBOUND: invalid dim");
va_start(va, dim);
while (d-- > 0)
bnd = va_arg(va, __INT_T *);
va_end(va);
if (!ISPRESENT(bnd))
__fort_abort("LBOUND: lower bound not present for specified dim");
return (__INT1_T)*bnd;
}
/* Varargs: __INT_T *ub1, ... __INT_T *ub<rank> */
__INT2_T
ENTF90(LBOUND2, lbound2)(__INT4_T *rank, __INT4_T *dim, ...)
{
va_list va;
__INT_T *bnd;
__INT_T d;
d = *dim;
if (d < 1 || d > *rank)
__fort_abort("LBOUND: invalid dim");
va_start(va, dim);
while (d-- > 0)
bnd = va_arg(va, __INT_T *);
va_end(va);
if (!ISPRESENT(bnd))
__fort_abort("LBOUND: lower bound not present for specified dim");
return (__INT2_T)*bnd;
}
/* Varargs: __INT_T *ub1, ... __INT_T *ub<rank> */
__INT4_T
ENTF90(LBOUND4, lbound4)(__INT4_T *rank, __INT4_T *dim, ...)
{
va_list va;
__INT_T *bnd;
__INT_T d;
d = *dim;
if (d < 1 || d > *rank)
__fort_abort("LBOUND: invalid dim");
va_start(va, dim);
while (d-- > 0)
bnd = va_arg(va, __INT_T *);
va_end(va);
if (!ISPRESENT(bnd))
__fort_abort("LBOUND: lower bound not present for specified dim");
return (__INT4_T)*bnd;
}
/* Varargs: __INT_T *ub1, ... __INT_T *ub<rank> */
__INT8_T
ENTF90(LBOUND8, lbound8)(__INT4_T *rank, __INT4_T *dim, ...)
{
va_list va;
__INT_T *bnd;
__INT_T d;
d = *dim;
if (d < 1 || d > *rank)
__fort_abort("LBOUND: invalid dim");
va_start(va, dim);
while (d-- > 0)
bnd = va_arg(va, __INT_T *);
va_end(va);
if (!ISPRESENT(bnd))
__fort_abort("LBOUND: lower bound not present for specified dim");
return (__INT8_T)*bnd;
}
/* Varargs: __INT_T *ub1, ... __INT_T *ub<rank> */
__INT8_T
ENTF90(KLBOUND, klbound)(__INT4_T *rank, __INT4_T *dim, ...)
{
/*
* -i8 variant of lbound
*/
va_list va;
__INT_T *bnd;
__INT_T d;
d = *dim;
if (d < 1 || d > *rank)
__fort_abort("LBOUND: invalid dim");
va_start(va, dim);
while (d-- > 0)
bnd = va_arg(va, __INT_T *);
va_end(va);
if (!ISPRESENT(bnd))
__fort_abort("LBOUND: lower bound not present for specified dim");
return (__INT8_T)*bnd;
}
/* Varargs: __INT_T *ub1, ... __INT_T *ub<rank> */
__INT_T
ENTF90(UBOUND, ubound)(__INT4_T *rank, __INT4_T *dim, ...)
{
va_list va;
__INT_T *bnd;
__INT_T d;
d = *dim;
if (d < 1 || d > *rank)
__fort_abort("UBOUND: invalid dim");
va_start(va, dim);
while (d-- > 0)
bnd = va_arg(va, __INT_T *);
va_end(va);
if (!ISPRESENT(bnd))
__fort_abort("UBOUND: upper bound not present for specified dim");
return *bnd;
}
/* Varargs: __INT_T *ub1, ... __INT_T *ub<rank> */
__INT1_T
ENTF90(UBOUND1, ubound1)(__INT4_T *rank, __INT4_T *dim, ...)
{
va_list va;
__INT_T *bnd;
__INT_T d;
d = *dim;
if (d < 1 || d > *rank)
__fort_abort("UBOUND: invalid dim");
va_start(va, dim);
while (d-- > 0)
bnd = va_arg(va, __INT_T *);
va_end(va);
if (!ISPRESENT(bnd))
__fort_abort("UBOUND: upper bound not present for specified dim");
return (__INT1_T)*bnd;
}
/* Varargs: __INT_T *ub1, ... __INT_T *ub<rank> */
__INT2_T
ENTF90(UBOUND2, ubound2)(__INT4_T *rank, __INT4_T *dim, ...)
{
va_list va;
__INT_T *bnd;
__INT_T d;
d = *dim;
if (d < 1 || d > *rank)
__fort_abort("UBOUND: invalid dim");
va_start(va, dim);
while (d-- > 0)
bnd = va_arg(va, __INT_T *);
va_end(va);
if (!ISPRESENT(bnd))
__fort_abort("UBOUND: upper bound not present for specified dim");
return (__INT2_T)*bnd;
}
/* Varargs: __INT_T *ub1, ... __INT_T *ub<rank> */
__INT4_T
ENTF90(UBOUND4, ubound4)(__INT4_T *rank, __INT4_T *dim, ...)
{
va_list va;
__INT_T *bnd;
__INT_T d;
d = *dim;
if (d < 1 || d > *rank)
__fort_abort("UBOUND: invalid dim");
va_start(va, dim);
while (d-- > 0)
bnd = va_arg(va, __INT_T *);
va_end(va);
if (!ISPRESENT(bnd))
__fort_abort("UBOUND: upper bound not present for specified dim");
return (__INT4_T)*bnd;
}
/* Varargs: __INT_T *ub1, ... __INT_T *ub<rank> */
__INT8_T
ENTF90(UBOUND8, ubound8)(__INT4_T *rank, __INT4_T *dim, ...)
{
va_list va;
__INT_T *bnd;
__INT_T d;
d = *dim;
if (d < 1 || d > *rank)
__fort_abort("UBOUND: invalid dim");
va_start(va, dim);
while (d-- > 0)
bnd = va_arg(va, __INT_T *);
va_end(va);
if (!ISPRESENT(bnd))
__fort_abort("UBOUND: upper bound not present for specified dim");
return (__INT8_T)*bnd;
}
/* Varargs: __INT_T *ub1, ... __INT_T *ub<rank> */
__INT8_T
ENTF90(KUBOUND, kubound)(__INT4_T *rank, __INT4_T *dim, ...)
{
/*
* -i8 variant of ubound
*/
va_list va;
__INT_T *bnd;
__INT_T d;
d = *dim;
if (d < 1 || d > *rank)
__fort_abort("UBOUND: invalid dim");
va_start(va, dim);
while (d-- > 0)
bnd = va_arg(va, __INT_T *);
va_end(va);
if (!ISPRESENT(bnd))
__fort_abort("UBOUND: upper bound not present for specified dim");
return (__INT8_T)*bnd;
}
/* Varargs: __INT_T *lb1, ... __INT_T *lb<size> */
void
ENTF90(LBOUNDA, lbounda)(__INT_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *bnd;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
bnd = va_arg(va, __INT_T *);
if (!ISPRESENT(bnd))
__fort_abort("LBOUND: lower bound not present");
*arr++ = *bnd;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, ... __INT_T *lb<size> */
void
ENTF90(LBOUNDA1, lbounda1)(__INT1_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *bnd;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
bnd = va_arg(va, __INT_T *);
if (!ISPRESENT(bnd))
__fort_abort("LBOUND: lower bound not present");
*arr++ = *bnd;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, ... __INT_T *lb<size> */
void
ENTF90(LBOUNDA2, lbounda2)(__INT2_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *bnd;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
bnd = va_arg(va, __INT_T *);
if (!ISPRESENT(bnd))
__fort_abort("LBOUND: lower bound not present");
*arr++ = *bnd;
}
va_end(va);
}
/*Varargs: __INT_T *lb1, ... __INT_T *lb<size> */
void
ENTF90(LBOUNDA4, lbounda4)(__INT4_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *bnd;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
bnd = va_arg(va, __INT_T *);
if (!ISPRESENT(bnd))
__fort_abort("LBOUND: lower bound not present");
*arr++ = *bnd;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, ... __INT_T *lb<size> */
void
ENTF90(LBOUNDA8, lbounda8)(__INT8_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *bnd;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
bnd = va_arg(va, __INT_T *);
if (!ISPRESENT(bnd))
__fort_abort("LBOUND: lower bound not present");
*arr++ = *bnd;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, ... __INT_T *lb<size> */
void
ENTF90(KLBOUNDA, klbounda)(__INT8_T *arr, __INT4_T *size, ...)
{
/*
* -i8 variant of LBOUNDA
*/
va_list va;
__INT_T *bnd;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
bnd = va_arg(va, __INT_T *);
if (!ISPRESENT(bnd))
__fort_abort("LBOUND: lower bound not present");
*arr++ = *bnd;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, ... __INT_T *lb<size> */
void
ENTF90(UBOUNDA, ubounda)(__INT_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *bnd;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
bnd = va_arg(va, __INT_T *);
if (!ISPRESENT(bnd))
__fort_abort("UBOUND: upper bound not present");
*arr++ = *bnd;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, ... __INT_T *lb<size> */
void
ENTF90(UBOUNDA1, ubounda1)(__INT1_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *bnd;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
bnd = va_arg(va, __INT_T *);
if (!ISPRESENT(bnd))
__fort_abort("UBOUND: upper bound not present");
*arr++ = *bnd;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, ... __INT_T *lb<size> */
void
ENTF90(UBOUNDA2, ubounda2)(__INT2_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *bnd;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
bnd = va_arg(va, __INT_T *);
if (!ISPRESENT(bnd))
__fort_abort("UBOUND: upper bound not present");
*arr++ = *bnd;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, ... __INT_T *lb<size> */
void
ENTF90(UBOUNDA4, ubounda4)(__INT4_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *bnd;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
bnd = va_arg(va, __INT_T *);
if (!ISPRESENT(bnd))
__fort_abort("UBOUND: upper bound not present");
*arr++ = *bnd;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, ... __INT_T *lb<size> */
void
ENTF90(UBOUNDA8, ubounda8)(__INT8_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *bnd;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
bnd = va_arg(va, __INT_T *);
if (!ISPRESENT(bnd))
__fort_abort("UBOUND: upper bound not present");
*arr++ = *bnd;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, ... __INT_T *lb<size> */
void
ENTF90(KUBOUNDA, kubounda)(__INT8_T *arr, __INT4_T *size, ...)
{
/*
* -i8 variant of ubounda
*/
va_list va;
__INT_T *bnd;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
bnd = va_arg(va, __INT_T *);
if (!ISPRESENT(bnd))
__fort_abort("UBOUND: upper bound not present");
*arr++ = *bnd;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, ... __INT_T *lb<size> */
void
ENTF90(LBOUNDAZ, lboundaz)(__INT4_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *bnd;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
bnd = va_arg(va, __INT_T *);
if (!ISPRESENT(bnd))
__fort_abort("LBOUND: lower bound not present");
*arr++ = *bnd;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, ... __INT_T *lb<size> */
void
ENTF90(LBOUNDAZ1, lboundaz1)(__INT1_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *bnd;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
bnd = va_arg(va, __INT_T *);
if (!ISPRESENT(bnd))
__fort_abort("LBOUND: lower bound not present");
*arr++ = *bnd;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, ... __INT_T *lb<size> */
void
ENTF90(LBOUNDAZ2, lboundaz2)(__INT2_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *bnd;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
bnd = va_arg(va, __INT_T *);
if (!ISPRESENT(bnd))
__fort_abort("LBOUND: lower bound not present");
*arr++ = *bnd;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, ... __INT_T *lb<size> */
void
ENTF90(LBOUNDAZ4, lboundaz4)(__INT4_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *bnd;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
bnd = va_arg(va, __INT_T *);
if (!ISPRESENT(bnd))
__fort_abort("LBOUND: lower bound not present");
*arr++ = *bnd;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, ... __INT_T *lb<size> */
void
ENTF90(LBOUNDAZ8, lboundaz8)(__INT8_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *bnd;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
bnd = va_arg(va, __INT_T *);
if (!ISPRESENT(bnd))
__fort_abort("LBOUND: lower bound not present");
*arr++ = *bnd;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, ... __INT_T *lb<size> */
void
ENTF90(KLBOUNDAZ, klboundaz)(__INT8_T *arr, __INT4_T *size, ...)
{
/*
* -i8 variant of LBOUNDAZ
*/
va_list va;
__INT_T *bnd;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
bnd = va_arg(va, __INT_T *);
if (!ISPRESENT(bnd))
__fort_abort("LBOUND: lower bound not present");
*arr++ = *bnd;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, ... __INT_T *lb<size> */
void
ENTF90(UBOUNDAZ, uboundaz)(__INT4_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *bnd;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
bnd = va_arg(va, __INT_T *);
if (!ISPRESENT(bnd))
__fort_abort("UBOUND: upper bound not present");
*arr++ = *bnd;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, ... __INT_T *lb<size> */
void
ENTF90(UBOUNDAZ1, uboundaz1)(__INT1_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *bnd;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
bnd = va_arg(va, __INT_T *);
if (!ISPRESENT(bnd))
__fort_abort("UBOUND: upper bound not present");
*arr++ = *bnd;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, ... __INT_T *lb<size> */
void
ENTF90(UBOUNDAZ2, uboundaz2)(__INT2_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *bnd;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
bnd = va_arg(va, __INT_T *);
if (!ISPRESENT(bnd))
__fort_abort("UBOUND: upper bound not present");
*arr++ = *bnd;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, ... __INT_T *lb<size> */
void
ENTF90(UBOUNDAZ4, uboundaz4)(__INT4_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *bnd;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
bnd = va_arg(va, __INT_T *);
if (!ISPRESENT(bnd))
__fort_abort("UBOUND: upper bound not present");
*arr++ = *bnd;
}
va_end(va);
}
/* Varargs: __INT_T *lb1, ... __INT_T *lb<size> */
void
ENTF90(UBOUNDAZ8, uboundaz8)(__INT8_T *arr, __INT4_T *size, ...)
{
va_list va;
__INT_T *bnd;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
bnd = va_arg(va, __INT_T *);
if (!ISPRESENT(bnd))
__fort_abort("UBOUND: upper bound not present");
*arr++ = *bnd;
}
va_end(va);
}
/* Vargs: __INT_T *lb1, ... __INT_T *lb<size> */
void
ENTF90(KUBOUNDAZ, kuboundaz)(__INT8_T *arr, __INT4_T *size, ...)
{
/*
* -i8 variant of uboundaz
*/
va_list va;
__INT_T *bnd;
__INT_T s;
s = *size;
va_start(va, size);
while (s-- > 0) {
bnd = va_arg(va, __INT_T *);
if (!ISPRESENT(bnd))
__fort_abort("UBOUND: upper bound not present");
*arr++ = *bnd;
}
va_end(va);
}
/* Vargs: { *lwb, *upb, *stride }* */
__INT_T
ENTF90(SIZE, size)(__INT4_T *rank, __INT4_T *dim, ...)
{
va_list va;
__INT_T *lwb, *upb, *stride;
int d;
__INT_T extent;
va_start(va, dim);
if (!ISPRESENT(dim)) {
/* size = product of all extents */
extent = 1;
d = *rank;
while (d-- > 0) {
lwb = va_arg(va, __INT_T *);
upb = va_arg(va, __INT_T *);
stride = va_arg(va, __INT_T *);
if (!ISPRESENT(lwb) || !ISPRESENT(upb) || !ISPRESENT(stride))
__fort_abort("SIZE: bounds not present");
extent *= (*upb - *lwb + *stride) / *stride;
if (extent < 0)
extent = 0;
}
} else {
/* size = extent in dimension 'dim' */
d = *dim;
if (d < 1 || d > *rank)
__fort_abort("SIZE: invalid dim");
while (d-- > 0) {
lwb = va_arg(va, __INT_T *);
upb = va_arg(va, __INT_T *);
stride = va_arg(va, __INT_T *);
}
if (!ISPRESENT(lwb) || !ISPRESENT(upb) || !ISPRESENT(stride))
__fort_abort("SIZE: bounds not present for specified dim");
extent = (*upb - *lwb + *stride) / *stride;
if (extent < 0)
extent = 0;
}
va_end(va);
return extent;
}
/* Vargs: { *lwb, *upb, *stride }* */
__INT8_T
ENTF90(KSIZE, ksize)(__INT4_T *rank, __INT4_T *dim, ...)
{
/*
* -i8 variant of SIZE
*/
va_list va;
__INT_T *lwb, *upb, *stride;
int d;
__INT_T extent;
va_start(va, dim);
if (!ISPRESENT(dim)) {
/* size = product of all extents */
extent = 1;
d = *rank;
while (d-- > 0) {
lwb = va_arg(va, __INT_T *);
upb = va_arg(va, __INT_T *);
stride = va_arg(va, __INT_T *);
if (!ISPRESENT(lwb) || !ISPRESENT(upb) || !ISPRESENT(stride))
__fort_abort("SIZE: bounds not present");
extent *= (*upb - *lwb + *stride) / *stride;
if (extent < 0)
extent = 0;
}
} else {
/* size = extent in dimension 'dim' */
d = *dim;
if (d < 1 || d > *rank)
__fort_abort("SIZE: invalid dim");
while (d-- > 0) {
lwb = va_arg(va, __INT_T *);
upb = va_arg(va, __INT_T *);
stride = va_arg(va, __INT_T *);
}
if (!ISPRESENT(lwb) || !ISPRESENT(upb) || !ISPRESENT(stride))
__fort_abort("SIZE: bounds not present for specified dim");
extent = (*upb - *lwb + *stride) / *stride;
if (extent < 0)
extent = 0;
}
va_end(va);
return (__INT8_T)extent;
}
#define BITS_PER_BYTE 8
__INT8_T
ENTF90(CLASS_OBJ_SIZE, class_obj_size)(F90_Desc *d)
{
__INT8_T storage_sz;
if (!d->tag)
return 0;
storage_sz = ENTF90(KGET_OBJECT_SIZE, kget_object_size)(d);
return storage_sz;
}
/* Vargs: { *lwb, *upb, *stride }* */
void
ENTF90(SHAPE, shape)(__INT4_T *arr, __INT_T *rank, ...)
{
va_list va;
__INT_T *lwb, *upb, *stride;
int d;
__INT_T extent;
d = *rank;
va_start(va, rank);
while (d-- > 0) {
lwb = va_arg(va, __INT_T *);
upb = va_arg(va, __INT_T *);
stride = va_arg(va, __INT_T *);
if (!ISPRESENT(lwb) || !ISPRESENT(upb) || !ISPRESENT(stride))
__fort_abort("SHAPE: bounds not present");
extent = (*upb - *lwb + *stride) / *stride;
if (extent < 0)
extent = 0;
*arr++ = extent;
}
va_end(va);
}
/* Vargs: { *lwb, *upb, *stride }* */
void
ENTF90(SHAPE1, shape1)(__INT1_T *arr, __INT_T *rank, ...)
{
va_list va;
__INT_T *lwb, *upb, *stride;
int d;
__INT_T extent;
d = *rank;
va_start(va, rank);
while (d-- > 0) {
lwb = va_arg(va, __INT_T *);
upb = va_arg(va, __INT_T *);
stride = va_arg(va, __INT_T *);
if (!ISPRESENT(lwb) || !ISPRESENT(upb) || !ISPRESENT(stride))
__fort_abort("SHAPE: bounds not present");
extent = (*upb - *lwb + *stride) / *stride;
if (extent < 0)
extent = 0;
*arr++ = extent;
}
va_end(va);
}
/* Vargs: { *lwb, *upb, *stride }* */
void
ENTF90(SHAPE2, shape2)(__INT2_T *arr, __INT_T *rank, ...)
{
va_list va;
__INT_T *lwb, *upb, *stride;
int d;
__INT_T extent;
d = *rank;
va_start(va, rank);
while (d-- > 0) {
lwb = va_arg(va, __INT_T *);
upb = va_arg(va, __INT_T *);
stride = va_arg(va, __INT_T *);
if (!ISPRESENT(lwb) || !ISPRESENT(upb) || !ISPRESENT(stride))
__fort_abort("SHAPE: bounds not present");
extent = (*upb - *lwb + *stride) / *stride;
if (extent < 0)
extent = 0;
*arr++ = extent;
}
va_end(va);
}
/* Vargs: { *lwb, *upb, *stride }* */
void
ENTF90(SHAPE4, shape4)(__INT4_T *arr, __INT_T *rank, ...)
{
va_list va;
__INT_T *lwb, *upb, *stride;
int d;
__INT_T extent;
d = *rank;
va_start(va, rank);
while (d-- > 0) {
lwb = va_arg(va, __INT_T *);
upb = va_arg(va, __INT_T *);
stride = va_arg(va, __INT_T *);
if (!ISPRESENT(lwb) || !ISPRESENT(upb) || !ISPRESENT(stride))
__fort_abort("SHAPE: bounds not present");
extent = (*upb - *lwb + *stride) / *stride;
if (extent < 0)
extent = 0;
*arr++ = extent;
}
va_end(va);
}
/* Vargs: { *lwb, *upb, *stride }* */
void
ENTF90(SHAPE8, shape8)(__INT8_T *arr, __INT_T *rank, ...)
{
va_list va;
__INT_T *lwb, *upb, *stride;
int d;
__INT_T extent;
d = *rank;
va_start(va, rank);
while (d-- > 0) {
lwb = va_arg(va, __INT_T *);
upb = va_arg(va, __INT_T *);
stride = va_arg(va, __INT_T *);
if (!ISPRESENT(lwb) || !ISPRESENT(upb) || !ISPRESENT(stride))
__fort_abort("SHAPE: bounds not present");
extent = (*upb - *lwb + *stride) / *stride;
if (extent < 0)
extent = 0;
*arr++ = extent;
}
va_end(va);
}
/** \brief Vargs: { *lwb, *upb, *stride }* */
void
ENTF90(KSHAPE, kshape)(__INT8_T *arr, __INT_T *rank, ...)
{
va_list va;
__INT_T *lwb, *upb, *stride;
int d;
__INT_T extent;
d = *rank;
va_start(va, rank);
while (d-- > 0) {
lwb = va_arg(va, __INT_T *);
upb = va_arg(va, __INT_T *);
stride = va_arg(va, __INT_T *);
if (!ISPRESENT(lwb) || !ISPRESENT(upb) || !ISPRESENT(stride))
__fort_abort("SHAPE: bounds not present");
extent = (*upb - *lwb + *stride) / *stride;
if (extent < 0)
extent = 0;
*arr++ = extent;
}
va_end(va);
}
/** \brief ACHAR function returns LEN;
*
* avoid confusion on returning character result
*/
__INT_T
ENTF90(ACHARA, achara)
(DCHAR(res), void *i, __INT_T *size DCLEN64(res))
{
*CADR(res) = I8(__fort_varying_int)(i, size);
return 1;
}
/* 32 bit CLEN version */
__INT_T
ENTF90(ACHAR, achar)
(DCHAR(res), void *i, __INT_T *size DCLEN(res))
{
return ENTF90(ACHARA, achara) (CADR(res), i, size, (__CLEN_T)CLEN(res));
}
__CLEN_T
ENTF90(REPEATA, repeata)
(DCHAR(res), DCHAR(expr), void *ncopies, __INT_T *size DCLEN64(res) DCLEN64(expr))
{
__CLEN_T i, len;
int _ncopies;
len = CLEN(expr);
_ncopies = I8(__fort_varying_int)(ncopies, size);
for (i = 0; i < _ncopies; ++i) {
strncpy(CADR(res) + i * len, CADR(expr), len);
}
return _ncopies * len;
}
/* 32 bit CLEN version */
__INT_T
ENTF90(REPEAT, repeat)
(DCHAR(res), DCHAR(expr), void *ncopies, __INT_T *size DCLEN(res) DCLEN(expr))
{
return (__INT_T)ENTF90(REPEATA, repeata) (CADR(res), CADR(expr), ncopies,
size, (__CLEN_T)CLEN(res), (__CLEN_T)CLEN(expr));
}
__INT_T
ENTF90(TRIMA, trima)
(DCHAR(res), DCHAR(expr) DCLEN64(res) DCLEN64(expr))
{
int i, j;
char *rcptr;
char *ecptr;
/*
* The for loop below results in a call to _c_mcopy1.
* Not the most efficient thing to do when len is around 4 or so.
* If the target generates illegal alignment errors, need to not do
* int copies. So, enable fast code for x8664 only for now.
*
i = CLEN(expr)-1;
while (i >= 0 && CADR(expr)[i] == ' ')
--i;
if (i < 0)
return 0;
for (j = 0; j <= i; ++j)
CADR(res)[j] = CADR(expr)[j];
return i+1;
*/
i = CLEN(expr);
while (i > 0) {
if (CADR(expr)[i - 1] != ' ') {
if (i <= 11) {
int *rptr = ((int *)CADR(res));
int *eptr = ((int *)CADR(expr));
if (i & 0xc) {
*rptr = *eptr;
if (i == 4)
return i;
rptr++;
eptr++;
if (i & 8) {
*rptr = *eptr;
if (i == 8)
return i;
rptr++;
eptr++;
}
}
rcptr = (char *)rptr;
ecptr = (char *)eptr;
j = i & 3;
if (j > 2)
*rcptr++ = *ecptr++;
if (j > 1)
*rcptr++ = *ecptr++;
if (j > 0)
*rcptr = *ecptr;
} else {
for (j = 0; j < i; ++j)
CADR(res)[j] = CADR(expr)[j];
}
return i;
} else {
--i;
}
}
return 0;
}
/* 32 bit CLEN version */
__INT_T
ENTF90(TRIM, trim)
(DCHAR(res), DCHAR(expr) DCLEN(res) DCLEN(expr))
{
return ENTF90(TRIMA, trima) (CADR(res), CADR(expr), (__CLEN_T)CLEN(res), (__CLEN_T)CLEN(expr));
}
__INT_T
ENTF90(IACHARA, iachara)(DCHAR(c) DCLEN64(c)) { return *CADR(c); }
/* 32 bit CLEN version */
__INT_T
ENTF90(IACHAR, iachar)(DCHAR(c) DCLEN(c))
{
return ENTF90(IACHARA, iachara)(CADR(c), (__CLEN_T)CLEN(c));
}
/** \brief
* -i8 variant of iachar
*/
__INT8_T
ENTF90(KIACHARA, kiachara)(DCHAR(c) DCLEN64(c))
{
return (__INT8_T)*CADR(c);
}
/* 32 bit CLEN version */
__INT8_T
ENTF90(KIACHAR, kiachar)(DCHAR(c) DCLEN(c))
{
return ENTF90(KIACHARA, kiachara)(CADR(c), (__CLEN_T)CLEN(c));
}
void
ENTF90(MERGECHA, mergecha)(DCHAR(result), DCHAR(tsource), DCHAR(fsource),
void *mask, __INT_T *szmask DCLEN64(result)
DCLEN64(tsource) DCLEN64(fsource))
{
if (I8(__fort_varying_log)(mask, szmask))
fstrcpy(CADR(result), CADR(tsource), CLEN(result), CLEN(tsource));
else
fstrcpy(CADR(result), CADR(fsource), CLEN(result), CLEN(fsource));
}
/* 32 bit CLEN version */
void
ENTF90(MERGECH, mergech)(DCHAR(result), DCHAR(tsource), DCHAR(fsource),
void *mask, __INT_T *szmask DCLEN(result)
DCLEN(tsource) DCLEN(fsource))
{
ENTF90(MERGECHA, mergecha)(CADR(result), CADR(tsource), CADR(fsource), mask,
szmask, (__CLEN_T)CLEN(result),
(__CLEN_T)CLEN(tsource), (__CLEN_T)CLEN(fsource));
}
void
ENTF90(MERGEDT, mergedt)(void *result, void *tsource, void *fsource,
__INT_T *size, void *mask, __INT_T *szmask)
{
__fort_bcopy(result, I8(__fort_varying_log)(mask, szmask) ? tsource : fsource,
*size);
}
__INT1_T
ENTF90(MERGEI1, mergei1)
(__INT1_T *tsource, __INT1_T *fsource, void *mask, __INT_T *size)
{
return I8(__fort_varying_log)(mask, size) ? *tsource : *fsource;
}
__INT2_T
ENTF90(MERGEI2, mergei2)
(__INT2_T *tsource, __INT2_T *fsource, void *mask, __INT_T *size)
{
return I8(__fort_varying_log)(mask, size) ? *tsource : *fsource;
}
__INT4_T
ENTF90(MERGEI, mergei)
(__INT4_T *tsource, __INT4_T *fsource, void *mask, __INT_T *size)
{
return I8(__fort_varying_log)(mask, size) ? *tsource : *fsource;
}
__INT8_T
ENTF90(MERGEI8, mergei8)
(__INT8_T *tsource, __INT8_T *fsource, void *mask, __INT_T *size)
{
return I8(__fort_varying_log)(mask, size) ? *tsource : *fsource;
}
__LOG1_T
ENTF90(MERGEL1, mergel1)
(__LOG1_T *tsource, __LOG1_T *fsource, void *mask, __INT_T *size)
{
return I8(__fort_varying_log)(mask, size) ? *tsource : *fsource;
}
__LOG2_T
ENTF90(MERGEL2, mergel2)
(__LOG2_T *tsource, __LOG2_T *fsource, void *mask, __INT_T *size)
{
return I8(__fort_varying_log)(mask, size) ? *tsource : *fsource;
}
__LOG4_T
ENTF90(MERGEL, mergel)
(__LOG4_T *tsource, __LOG4_T *fsource, void *mask, __INT_T *size)
{
return I8(__fort_varying_log)(mask, size) ? *tsource : *fsource;
}
__LOG8_T
ENTF90(MERGEL8, mergel8)
(__LOG8_T *tsource, __LOG8_T *fsource, void *mask, __INT_T *size)
{
return I8(__fort_varying_log)(mask, size) ? *tsource : *fsource;
}
__REAL4_T
ENTF90(MERGER, merger)
(__REAL4_T *tsource, __REAL4_T *fsource, void *mask, __INT_T *size)
{
return I8(__fort_varying_log)(mask, size) ? *tsource : *fsource;
}
__REAL8_T
ENTF90(MERGED, merged)
(__REAL8_T *tsource, __REAL8_T *fsource, void *mask, __INT_T *size)
{
return I8(__fort_varying_log)(mask, size) ? *tsource : *fsource;
}
__REAL16_T
ENTF90(MERGEQ, mergeq)
(__REAL16_T *tsource, __REAL16_T *fsource, void *mask, __INT_T *size)
{
return I8(__fort_varying_log)(mask, size) ? *tsource : *fsource;
}
__INT_T
ENTF90(LENTRIMA, lentrima)(DCHAR(str) DCLEN64(str))
{
__INT_T i;
for (i = (__INT_T)CLEN(str); i-- > 0;)
if (CADR(str)[i] != ' ')
break;
return i + 1;
}
/* 32 bit CLEN version */
__INT_T
ENTF90(LENTRIM, lentrim)(DCHAR(str) DCLEN(str))
{
return ENTF90(LENTRIMA, lentrima)(CADR(str), (__CLEN_T)CLEN(str));
}
__INT8_T
ENTF90(KLENTRIMA, klentrima)(DCHAR(str) DCLEN64(str))
{
/*
* -i8 variant of lentrim
*/
__INT8_T i;
for (i = (__INT8_T)CLEN(str); i-- > 0;)
if (CADR(str)[i] != ' ')
break;
return i + 1;
}
/* 32 bit CLEN version */
__INT8_T
ENTF90(KLENTRIM, klentrim)(DCHAR(str) DCLEN(str))
{
return (__INT8_T) ENTF90(KLENTRIMA, klentrima)(CADR(str), (__CLEN_T)CLEN(str));
}
__INT_T
ENTF90(SCANA, scana)
(DCHAR(str), DCHAR(set), void *back, __INT_T *size DCLEN64(str) DCLEN64(set))
{
__INT_T i, j;
if (ISPRESENT(back) && I8(__fort_varying_log)(back, size)) {
for (i = (__INT_T)CLEN(str); i-- > 0;)
for (j = 0; j < (__INT_T)CLEN(set); ++j)
if (CADR(set)[j] == CADR(str)[i])
return i + 1;
return 0;
} else {
for (i = 0; i < (__INT_T)CLEN(str); ++i)
for (j = 0; j < (__INT_T)CLEN(set); ++j)
if (CADR(set)[j] == CADR(str)[i])
return i + 1;
return 0;
}
}
/* 32 bit CLEN version */
__INT_T
ENTF90(SCAN, scan)
(DCHAR(str), DCHAR(set), void *back, __INT_T *size DCLEN(str) DCLEN(set))
{
return ENTF90(SCANA, scana) (CADR(str), CADR(set), back, size,
(__CLEN_T)CLEN(str), (__CLEN_T)CLEN(set));
}
/** \brief
* -i8 variant of SCAN
*/
__INT8_T
ENTF90(KSCANA, kscana)
(DCHAR(str), DCHAR(set), void *back, __INT_T *size DCLEN64(str) DCLEN64(set))
{
__INT8_T i, j;
if (ISPRESENT(back) && I8(__fort_varying_log)(back, size)) {
for (i = (__INT8_T)CLEN(str); i-- > 0;)
for (j = 0; j < (__INT8_T)CLEN(set); ++j)
if (CADR(set)[j] == CADR(str)[i])
return i + 1;
return 0;
} else {
for (i = 0; i < (__INT8_T)CLEN(str); ++i)
for (j = 0; j < (__INT8_T)CLEN(set); ++j)
if (CADR(set)[j] == CADR(str)[i])
return i + 1;
return 0;
}
}
/* 32 bit CLEN version */
__INT8_T
ENTF90(KSCAN, kscan)
(DCHAR(str), DCHAR(set), void *back, __INT_T *size DCLEN(str) DCLEN(set))
{
return ENTF90(KSCANA, kscana) (CADR(str), CADR(set), back, size,
(__CLEN_T)CLEN(str), (__CLEN_T)CLEN(set));
}
__INT_T
ENTF90(VERIFYA, verifya)
(DCHAR(str), DCHAR(set), void *back, __INT_T *size DCLEN64(str) DCLEN64(set))
{
__INT_T i, j;
if (ISPRESENT(back) && I8(__fort_varying_log)(back, size)) {
for (i = (__INT_T)CLEN(str); i-- > 0;) {
for (j = 0; j < (__INT_T)CLEN(set); ++j)
if (CADR(set)[j] == CADR(str)[i])
goto contb;
return i + 1;
contb:;
}
return 0;
} else {
for (i = 0; i < (__INT_T)CLEN(str); ++i) {
for (j = 0; j < (__INT_T)CLEN(set); ++j)
if (CADR(set)[j] == CADR(str)[i])
goto contf;
return i + 1;
contf:;
}
return 0;
}
}
/* 32 bit CLEN version */
__INT_T
ENTF90(VERIFY, verify)
(DCHAR(str), DCHAR(set), void *back, __INT_T *size DCLEN(str) DCLEN(set))
{
return ENTF90(VERIFYA, verifya) (CADR(str), CADR(set), back, size,
(__CLEN_T)CLEN(str), (__CLEN_T)CLEN(set));
}
/** \brief
* -i8 variant of VERIFY
*/
__INT8_T
ENTF90(KVERIFYA, kverifya)
(DCHAR(str), DCHAR(set), void *back, __INT_T *size DCLEN64(str) DCLEN64(set))
{
__INT8_T i, j;
if (ISPRESENT(back) && I8(__fort_varying_log)(back, size)) {
for (i = (__INT8_T)CLEN(str); i-- > 0;) {
for (j = 0; j < (__INT8_T)CLEN(set); ++j)
if (CADR(set)[j] == CADR(str)[i])
goto contb;
return i + 1;
contb:;
}
return 0;
} else {
for (i = 0; i < (__INT8_T)CLEN(str); ++i) {
for (j = 0; j < (__INT8_T)CLEN(set); ++j)
if (CADR(set)[j] == CADR(str)[i])
goto contf;
return i + 1;
contf:;
}
return 0;
}
}
/* 32 bit CLEN version */
__INT8_T
ENTF90(KVERIFY, kverify)
(DCHAR(str), DCHAR(set), void *back, __INT_T *size DCLEN(str) DCLEN(set))
{
return ENTF90(KVERIFYA, kverifya) (CADR(str), CADR(set), back,
size, (__CLEN_T)CLEN(str), (__CLEN_T)CLEN(set));
}
/** \brief
* -i8 variant of INDEX
*/
__INT8_T
ENTF90(KINDEXA, kindexa)
(DCHAR(string), DCHAR(substring), void *back,
__INT_T *size DCLEN64(string) DCLEN64(substring))
{
__INT8_T i, n;
n = (__INT8_T)CLEN(string) - (__INT8_T)CLEN(substring);
if (n < 0)
return 0;
if (ISPRESENT(back) && I8(__fort_varying_log)(back, size)) {
if (CLEN(substring) == 0)
return (__INT8_T)CLEN(string) + 1;
for (i = n; i >= 0; --i) {
if (CADR(string)[i] == CADR(substring)[0] &&
strncmp(CADR(string) + i, CADR(substring), CLEN(substring)) == 0)
return i + 1;
}
} else {
if (CLEN(substring) == 0)
return 1;
for (i = 0; i <= n; ++i) {
if (CADR(string)[i] == CADR(substring)[0] &&
strncmp(CADR(string) + i, CADR(substring), CLEN(substring)) == 0)
return i + 1;
}
}
return 0;
}
/* 32 bit CLEN version */
__INT8_T
ENTF90(KINDEX, kindex)
(DCHAR(string), DCHAR(substring), void *back,
__INT_T *size DCLEN(string) DCLEN(substring))
{
return ENTF90(KINDEXA, kindexa) (CADR(string), CADR(substring),
back, size, (__CLEN_T)CLEN(string), (__CLEN_T)CLEN(substring));
}
__INT_T
ENTF90(INDEXA, indexa)
(DCHAR(string), DCHAR(substring), void *back,
__INT_T *size DCLEN64(string) DCLEN64(substring))
{
__INT_T i, n;
n = (__INT_T)CLEN(string) - (__INT_T)CLEN(substring);
if (n < 0)
return 0;
if (ISPRESENT(back) && I8(__fort_varying_log)(back, size)) {
if (CLEN(substring) == 0)
return (__INT_T)CLEN(string) + 1;
for (i = n; i >= 0; --i) {
if (CADR(string)[i] == CADR(substring)[0] &&
strncmp(CADR(string) + i, CADR(substring), CLEN(substring)) == 0)
return i + 1;
}
} else {
if (CLEN(substring) == 0)
return 1;
for (i = 0; i <= n; ++i) {
if (CADR(string)[i] == CADR(substring)[0] &&
strncmp(CADR(string) + i, CADR(substring), CLEN(substring)) == 0)
return i + 1;
}
}
return 0;
}
/* 32 bit CLEN version */
__INT_T
ENTF90(INDEX, index)
(DCHAR(string), DCHAR(substring), void *back,
__INT_T *size DCLEN(string) DCLEN(substring))
{
return ENTF90(INDEXA, indexa) (CADR(string), CADR(substring), back,
size, (__CLEN_T)CLEN(string), (__CLEN_T)CLEN(substring));
}
__INT_T
ENTFTN(LEADZ, leadz)(void *i, __INT_T *size)
{
unsigned ui; /* unsigned representation of 'i' */
int nz; /* number of leading zero bits in 'i' */
int k;
ui = (unsigned)I8(__fort_varying_int)(i, size);
nz = *size * 8;
k = nz >> 1;
while (k) {
if (ui >> k) {
ui >>= k;
nz -= k;
}
k >>= 1;
}
if (ui)
--nz;
return nz;
}
__INT_T
ENTFTN(POPCNT, popcnt)(void *i, __INT_T *size)
{
unsigned ui, uj; /* unsigned representation of 'i' */
__INT8_T ll;
switch (*size) {
case 8:
ll = *(__INT8_T *)i;
ui = (unsigned)(ll & 0xFFFFFFFF);
uj = (unsigned)((ll >> 32) & 0xFFFFFFFF);
ui = (ui & 0x55555555) + (ui >> 1 & 0x55555555);
uj = (uj & 0x55555555) + (uj >> 1 & 0x55555555);
ui = (ui & 0x33333333) + (ui >> 2 & 0x33333333);
uj = (uj & 0x33333333) + (uj >> 2 & 0x33333333);
ui = (ui & 0x07070707) + (ui >> 4 & 0x07070707);
ui += (uj & 0x07070707) + (uj >> 4 & 0x07070707);
ui += ui >> 8;
ui += ui >> 16;
ui &= 0x7f;
break;
case 4:
ui = (unsigned)(*(__INT4_T *)i);
ui = (ui & 0x55555555) + (ui >> 1 & 0x55555555);
ui = (ui & 0x33333333) + (ui >> 2 & 0x33333333);
ui = (ui & 0x07070707) + (ui >> 4 & 0x07070707);
ui += ui >> 8;
ui += ui >> 16;
ui &= 0x3f;
break;
case 2:
ui = (unsigned)(*(__INT2_T *)i);
ui = (ui & 0x5555) + (ui >> 1 & 0x5555);
ui = (ui & 0x3333) + (ui >> 2 & 0x3333);
ui = (ui & 0x0707) + (ui >> 4 & 0x0707);
ui += ui >> 8;
ui &= 0x1f;
break;
case 1:
ui = (unsigned)(*(__INT1_T *)i);
ui = (ui & 0x55) + (ui >> 1 & 0x55);
ui = (ui & 0x33) + (ui >> 2 & 0x33);
ui += ui >> 4;
ui &= 0xf;
break;
default:
__fort_abort("POPCNT: invalid size");
}
return ui;
}
__INT_T
ENTFTN(POPPAR, poppar)(void *i, __INT_T *size)
{
int ii;
__INT8_T ll;
switch (*size) {
case 8:
ll = *(__INT8_T *)i;
ii = ll ^ ll >> 32;
ii ^= ii >> 16;
ii ^= ii >> 8;
break;
case 4:
ii = *(__INT4_T *)i;
ii ^= ii >> 16;
ii ^= ii >> 8;
break;
case 2:
ii = *(__INT2_T *)i;
ii ^= ii >> 8;
break;
case 1:
ii = *(__INT1_T *)i;
break;
default:
__fort_abort("POPPAR: invalid size");
}
ii ^= ii >> 4;
ii ^= ii >> 2;
ii ^= ii >> 1;
return ii & 1;
}
/*
* The following functions are called when the compiler needs to invoke an
* intrinsic which has lost its intrinsic property (i.e, the intrinsic is
* a user-defined object).
*/
__INT4_T
ENTF90(JMAX0, jmax0)(__INT4_T *a, __INT4_T *b) { return (*a > *b) ? *a : *b; }
__INT4_T
ENTF90(MAX0, max0)(__INT4_T *a, __INT4_T *b) { return (*a > *b) ? *a : *b; }
__INT8_T
ENTF90(KMAX, kmax)(__INT8_T *a, __INT8_T *b) { return (*a > *b) ? *a : *b; }
__INT4_T
ENTF90(MIN0, min0)(__INT4_T *a, __INT4_T *b) { return (*a < *b) ? *a : *b; }
__INT4_T
ENTF90(MOD, mod)(__INT4_T *a, __INT4_T *b) { return *a % *b; }
__INT_T
ENTF90(INT, int)(void *a, __INT_T *ty)
{
switch (*ty) {
case __INT1:
return *(__INT1_T *)a;
case __LOG1:
return *(__LOG1_T *)a;
case __INT2:
return *(__INT2_T *)a;
case __LOG2:
return *(__LOG2_T *)a;
case __INT4:
return *(__INT4_T *)a;
case __LOG4:
return *(__LOG4_T *)a;
case __INT8:
return *(__INT8_T *)a;
case __LOG8:
return *(__LOG8_T *)a;
case __REAL4:
return *(__REAL4_T *)a;
case __REAL8:
return *(__REAL8_T *)a;
case __REAL16:
return *(__REAL16_T *)a;
case __CPLX8:
return ((__CPLX8_T *)a)->r;
case __CPLX16:
return ((__CPLX16_T *)a)->r;
case __CPLX32:
return ((__CPLX32_T *)a)->r;
default:
__fort_abort("INT: invalid argument type");
}
return 0; /* sgi warning: gotta have a return! */
}
__INT1_T
ENTF90(INT1, int1)(void *a, __INT_T *ty)
{
switch (*ty) {
case __INT1:
return *(__INT1_T *)a;
case __LOG1:
return *(__LOG1_T *)a;
case __INT2:
return *(__INT2_T *)a;
case __LOG2:
return *(__LOG2_T *)a;
case __INT4:
return *(__INT4_T *)a;
case __LOG4:
return *(__LOG4_T *)a;
case __INT8:
return *(__INT8_T *)a;
case __LOG8:
return *(__LOG8_T *)a;
case __REAL4:
return *(__REAL4_T *)a;
case __REAL8:
return *(__REAL8_T *)a;
case __REAL16:
return *(__REAL16_T *)a;
case __CPLX8:
return ((__CPLX8_T *)a)->r;
case __CPLX16:
return ((__CPLX16_T *)a)->r;
case __CPLX32:
return ((__CPLX32_T *)a)->r;
default:
__fort_abort("INT1: invalid argument type");
}
return 0; /* sgi warning: gotta have a return! */
}
__INT2_T
ENTF90(INT2, int2)(void *a, __INT_T *ty)
{
switch (*ty) {
case __INT1:
return *(__INT1_T *)a;
case __LOG1:
return *(__LOG1_T *)a;
case __INT2:
return *(__INT2_T *)a;
case __LOG2:
return *(__LOG2_T *)a;
case __INT4:
return *(__INT4_T *)a;
case __LOG4:
return *(__LOG4_T *)a;
case __INT8:
return *(__INT8_T *)a;
case __LOG8:
return *(__LOG8_T *)a;
case __REAL4:
return *(__REAL4_T *)a;
case __REAL8:
return *(__REAL8_T *)a;
case __REAL16:
return *(__REAL16_T *)a;
case __CPLX8:
return ((__CPLX8_T *)a)->r;
case __CPLX16:
return ((__CPLX16_T *)a)->r;
case __CPLX32:
return ((__CPLX32_T *)a)->r;
default:
__fort_abort("INT2: invalid argument type");
}
return 0; /* sgi warning: gotta have a return! */
}
__INT4_T
ENTF90(INT4, int4)(void *a, __INT_T *ty)
{
switch (*ty) {
case __INT1:
return *(__INT1_T *)a;
case __LOG1:
return *(__LOG1_T *)a;
case __INT2:
return *(__INT2_T *)a;
case __LOG2:
return *(__LOG2_T *)a;
case __INT4:
return *(__INT4_T *)a;
case __LOG4:
return *(__LOG4_T *)a;
case __INT8:
return *(__INT8_T *)a;
case __LOG8:
return *(__LOG8_T *)a;
case __REAL4:
return *(__REAL4_T *)a;
case __REAL8:
return *(__REAL8_T *)a;
case __REAL16:
return *(__REAL16_T *)a;
case __CPLX8:
return ((__CPLX8_T *)a)->r;
case __CPLX16:
return ((__CPLX16_T *)a)->r;
case __CPLX32:
return ((__CPLX32_T *)a)->r;
default:
__fort_abort("INT4: invalid argument type");
}
return 0; /* sgi warning: gotta have a return! */
}
__INT8_T
ENTF90(INT8, int8)(void *a, __INT_T *ty)
{
switch (*ty) {
case __INT1:
return *(__INT1_T *)a;
case __LOG1:
return *(__LOG1_T *)a;
case __INT2:
return *(__INT2_T *)a;
case __LOG2:
return *(__LOG2_T *)a;
case __INT4:
return *(__INT4_T *)a;
case __LOG4:
return *(__LOG4_T *)a;
case __INT8:
return *(__INT8_T *)a;
case __LOG8:
return *(__LOG8_T *)a;
case __REAL4:
return *(__REAL4_T *)a;
case __REAL8:
return *(__REAL8_T *)a;
case __REAL16:
return *(__REAL16_T *)a;
case __CPLX8:
return ((__CPLX8_T *)a)->r;
case __CPLX16:
return ((__CPLX16_T *)a)->r;
case __CPLX32:
return ((__CPLX32_T *)a)->r;
default:
__fort_abort("INT8: invalid argument type");
}
return 0; /* sgi warning: gotta have a return! */
}
__LOG1_T
ENTF90(LOG1, log1)(void *a, __INT_T *ty)
{
switch (*ty) {
case __INT1:
return *(__INT1_T *)a & GET_DIST_MASK_LOG1 ? GET_DIST_TRUE_LOG1 : 0;
case __LOG1:
return *(__LOG1_T *)a & GET_DIST_MASK_LOG1 ? GET_DIST_TRUE_LOG1 : 0;
case __INT2:
return *(__INT2_T *)a & GET_DIST_MASK_LOG2 ? GET_DIST_TRUE_LOG1 : 0;
case __LOG2:
return *(__LOG2_T *)a & GET_DIST_MASK_LOG2 ? GET_DIST_TRUE_LOG1 : 0;
case __INT4:
return *(__INT4_T *)a & GET_DIST_MASK_LOG4 ? GET_DIST_TRUE_LOG1 : 0;
case __LOG4:
return *(__LOG4_T *)a & GET_DIST_MASK_LOG4 ? GET_DIST_TRUE_LOG1 : 0;
case __INT8:
return *(__INT8_T *)a & GET_DIST_MASK_LOG8 ? GET_DIST_TRUE_LOG1 : 0;
case __LOG8:
return *(__LOG8_T *)a & GET_DIST_MASK_LOG8 ? GET_DIST_TRUE_LOG1 : 0;
default:
__fort_abort("LOG1: invalid argument type");
}
return 0; /* sgi warning: gotta have a return! */
}
__LOG2_T
ENTF90(LOG2, log2)(void *a, __INT_T *ty)
{
switch (*ty) {
case __INT1:
return *(__INT1_T *)a & GET_DIST_MASK_LOG1 ? GET_DIST_TRUE_LOG2 : 0;
case __LOG1:
return *(__LOG1_T *)a & GET_DIST_MASK_LOG1 ? GET_DIST_TRUE_LOG2 : 0;
case __INT2:
return *(__INT2_T *)a & GET_DIST_MASK_LOG2 ? GET_DIST_TRUE_LOG2 : 0;
case __LOG2:
return *(__LOG2_T *)a & GET_DIST_MASK_LOG2 ? GET_DIST_TRUE_LOG2 : 0;
case __INT4:
return *(__INT4_T *)a & GET_DIST_MASK_LOG4 ? GET_DIST_TRUE_LOG2 : 0;
case __LOG4:
return *(__LOG4_T *)a & GET_DIST_MASK_LOG4 ? GET_DIST_TRUE_LOG2 : 0;
case __INT8:
return *(__INT8_T *)a & GET_DIST_MASK_LOG8 ? GET_DIST_TRUE_LOG2 : 0;
case __LOG8:
return *(__LOG8_T *)a & GET_DIST_MASK_LOG8 ? GET_DIST_TRUE_LOG2 : 0;
default:
__fort_abort("LOG2: invalid argument type");
}
return 0; /* sgi warning: gotta have a return! */
}
__LOG4_T
ENTF90(LOG4, log4)(void *a, __INT_T *ty)
{
switch (*ty) {
case __INT1:
return *(__INT1_T *)a & GET_DIST_MASK_LOG1 ? GET_DIST_TRUE_LOG4 : 0;
case __LOG1:
return *(__LOG1_T *)a & GET_DIST_MASK_LOG1 ? GET_DIST_TRUE_LOG4 : 0;
case __INT2:
return *(__INT2_T *)a & GET_DIST_MASK_LOG2 ? GET_DIST_TRUE_LOG4 : 0;
case __LOG2:
return *(__LOG2_T *)a & GET_DIST_MASK_LOG2 ? GET_DIST_TRUE_LOG4 : 0;
case __INT4:
return *(__INT4_T *)a & GET_DIST_MASK_LOG4 ? GET_DIST_TRUE_LOG4 : 0;
case __LOG4:
return *(__LOG4_T *)a & GET_DIST_MASK_LOG4 ? GET_DIST_TRUE_LOG4 : 0;
case __INT8:
return *(__INT8_T *)a & GET_DIST_MASK_LOG8 ? GET_DIST_TRUE_LOG4 : 0;
case __LOG8:
return *(__LOG8_T *)a & GET_DIST_MASK_LOG8 ? GET_DIST_TRUE_LOG4 : 0;
default:
__fort_abort("LOG4: invalid argument type");
}
return 0; /* sgi warning: gotta have a return! */
}
__LOG8_T
ENTF90(LOG8, log8)(void *a, __INT_T *ty)
{
switch (*ty) {
case __INT1:
return *(__INT1_T *)a & GET_DIST_MASK_LOG1 ? GET_DIST_TRUE_LOG8 : 0;
case __LOG1:
return *(__LOG1_T *)a & GET_DIST_MASK_LOG1 ? GET_DIST_TRUE_LOG8 : 0;
case __INT2:
return *(__INT2_T *)a & GET_DIST_MASK_LOG2 ? GET_DIST_TRUE_LOG8 : 0;
case __LOG2:
return *(__LOG2_T *)a & GET_DIST_MASK_LOG2 ? GET_DIST_TRUE_LOG8 : 0;
case __INT4:
return *(__INT4_T *)a & GET_DIST_MASK_LOG4 ? GET_DIST_TRUE_LOG8 : 0;
case __LOG4:
return *(__LOG4_T *)a & GET_DIST_MASK_LOG4 ? GET_DIST_TRUE_LOG8 : 0;
case __INT8:
return *(__INT8_T *)a & GET_DIST_MASK_LOG8 ? GET_DIST_TRUE_LOG8 : 0;
case __LOG8:
return *(__LOG8_T *)a & GET_DIST_MASK_LOG8 ? GET_DIST_TRUE_LOG8 : 0;
default:
__fort_abort("LOG8: invalid argument type");
}
return 0; /* sgi warning: gotta have a return! */
}
__REAL_T
ENTF90(REAL, real)(void *a, __INT_T *ty)
{
switch (*ty) {
case __INT1:
return *(__INT1_T *)a;
case __LOG1:
return *(__LOG1_T *)a;
case __INT2:
return *(__INT2_T *)a;
case __LOG2:
return *(__LOG2_T *)a;
case __INT4:
return *(__INT4_T *)a;
case __LOG4:
return *(__LOG4_T *)a;
case __INT8:
return *(__INT8_T *)a;
case __LOG8:
return *(__LOG8_T *)a;
case __REAL4:
return *(__REAL4_T *)a;
case __CPLX8:
return ((__CPLX8_T *)a)->r;
case __REAL8:
return *(__REAL8_T *)a;
case __CPLX16:
return ((__CPLX16_T *)a)->r;
default:
__fort_abort("REAL: invalid argument type");
}
return 0.0; /* sgi warning: gotta have a return! */
}
__DBLE_T
ENTF90(DBLE, dble)(void *a, __INT_T *ty)
{
switch (*ty) {
case __INT1:
return *(__INT1_T *)a;
case __LOG1:
return *(__LOG1_T *)a;
case __INT2:
return *(__INT2_T *)a;
case __LOG2:
return *(__LOG2_T *)a;
case __INT4:
return *(__INT4_T *)a;
case __LOG4:
return *(__LOG4_T *)a;
case __INT8:
return *(__INT8_T *)a;
case __LOG8:
return *(__LOG8_T *)a;
case __REAL4:
return *(__REAL4_T *)a;
case __CPLX8:
return ((__CPLX8_T *)a)->r;
case __REAL8:
return *(__REAL8_T *)a;
case __CPLX16:
return ((__CPLX16_T *)a)->r;
default:
__fort_abort("DBLE: invalid argument type");
}
return 0.0; /* sgi warning: gotta have a return! */
}
__REAL4_T
ENTF90(REAL4, real4)(void *a, __INT_T *ty)
{
switch (*ty) {
case __INT1:
return *(__INT1_T *)a;
case __LOG1:
return *(__LOG1_T *)a;
case __INT2:
return *(__INT2_T *)a;
case __LOG2:
return *(__LOG2_T *)a;
case __INT4:
return *(__INT4_T *)a;
case __LOG4:
return *(__LOG4_T *)a;
case __INT8:
return *(__INT8_T *)a;
case __LOG8:
return *(__LOG8_T *)a;
case __REAL4:
return *(__REAL4_T *)a;
case __CPLX8:
return ((__CPLX8_T *)a)->r;
case __REAL8:
return *(__REAL8_T *)a;
case __CPLX16:
return ((__CPLX16_T *)a)->r;
default:
__fort_abort("REAL4: invalid argument type");
}
return 0.0; /* sgi warning: gotta have a return! */
}
__REAL8_T
ENTF90(REAL8, real8)(void *a, __INT_T *ty)
{
switch (*ty) {
case __INT1:
return *(__INT1_T *)a;
case __LOG1:
return *(__LOG1_T *)a;
case __INT2:
return *(__INT2_T *)a;
case __LOG2:
return *(__LOG2_T *)a;
case __INT4:
return *(__INT4_T *)a;
case __LOG4:
return *(__LOG4_T *)a;
case __INT8:
return *(__INT8_T *)a;
case __LOG8:
return *(__LOG8_T *)a;
case __REAL4:
return *(__REAL4_T *)a;
case __CPLX8:
return ((__CPLX8_T *)a)->r;
case __REAL8:
return *(__REAL8_T *)a;
case __CPLX16:
return ((__CPLX16_T *)a)->r;
default:
__fort_abort("REAL8: invalid argument type");
}
return 0.0; /* sgi warning: gotta have a return! */
}
__REAL_T
ENTF90(AMAX1, amax1)(__REAL_T *a, __REAL_T *b) { return (*a > *b) ? *a : *b; }
__DBLE_T
ENTF90(DMAX1, dmax1)(__DBLE_T *a, __DBLE_T *b) { return (*a > *b) ? *a : *b; }
__REAL_T
ENTF90(AMIN1, amin1)(__REAL_T *a, __REAL_T *b) { return (*a < *b) ? *a : *b; }
__DBLE_T
ENTF90(DMIN1, dmin1)(__DBLE_T *a, __DBLE_T *b) { return (*a < *b) ? *a : *b; }
double fmod();
__REAL_T
ENTF90(AMOD, amod)(__REAL_T *a, __REAL_T *b) { return fmod(*a, *b); }
__DBLE_T
ENTF90(DMOD, dmod)(__DBLE_T *a, __DBLE_T *b)
{
return fmod(*a, *b);
}
__INT4_T
ENTF90(MODULO, modulo)(__INT4_T *a, __INT4_T *p)
{
__INT4_T q, r;
q = (*a) / (*p);
r = (*a) - q * (*p);
if (r != 0 && ((*a) ^ (*p)) < 0) { /* signs differ */
r += (*p);
}
return r;
}
__INT8_T
ENTF90(I8MODULO, i8modulo)(__INT8_T *a, __INT8_T *p)
{
__INT8_T q, r;
q = (*a) / (*p);
r = (*a) - q * (*p);
if (r != 0 && ((*a) ^ (*p)) < 0) { /* signs differ */
r += (*p);
}
return r;
}
__INT2_T
ENTF90(IMODULO, imodulo)(__INT2_T *a, __INT2_T *p)
{
__INT_T q, r;
q = (*a) / (*p);
r = (*a) - q * (*p);
if (r != 0 && ((*a) ^ (*p)) < 0) { /* signs differ */
r += (*p);
}
return r;
}
__REAL_T
ENTF90(AMODULO, amodulo)(__REAL_T *x, __REAL_T *y)
{
double d;
d = fmod(*x, *y);
if (d != 0 && ((*x < 0 && *y > 0) || (*x > 0 && *y < 0)))
d += *y;
return d;
}
__DBLE_T
ENTF90(DMODULO, dmodulo)(__DBLE_T *x, __DBLE_T *y)
{
double d;
d = fmod(*x, *y);
if (d != 0 && ((*x < 0 && *y > 0) || (*x > 0 && *y < 0)))
d += *y;
return d;
}
__INT4_T
ENTF90(MODULOv, modulov)(__INT4_T a, __INT4_T p)
{
__INT4_T q, r;
q = (a) / (p);
r = (a)-q * (p);
if (r != 0 && ((a) ^ (p)) < 0) { /* signs differ */
r += (p);
}
return r;
}
__INT8_T
ENTF90(I8MODULOv, i8modulov)(__INT8_T a, __INT8_T p)
{
__INT8_T q, r;
q = (a) / (p);
r = (a)-q * (p);
if (r != 0 && ((a) ^ (p)) < 0) { /* signs differ */
r += (p);
}
return r;
}
__INT2_T
ENTF90(IMODULOv, imodulov)(__INT2_T a, __INT2_T p)
{
__INT_T q, r;
q = (a) / (p);
r = (a)-q * (p);
if (r != 0 && ((a) ^ (p)) < 0) { /* signs differ */
r += (p);
}
return r;
}
__REAL_T
ENTF90(AMODULOv, amodulov)(__REAL_T x, __REAL_T y)
{
double d;
d = fmod(x, y);
if (d != 0 && ((x < 0 && y > 0) || (x > 0 && y < 0)))
d += y;
return d;
}
__DBLE_T
ENTF90(DMODULOv, dmodulov)(__DBLE_T x, __DBLE_T y)
{
double d;
d = fmod(x, y);
if (d != 0 && ((x < 0 && y > 0) || (x > 0 && y < 0)))
d += y;
return d;
}
__INT_T
ENTF90(CEILING, ceiling)(__REAL_T *r)
{
__DBLE_T x;
int a;
x = *r;
a = x; /* integer part */
if (a == x)
return x;
if (x > 0)
return a + 1;
return a;
}
__INT8_T
ENTF90(KCEILING, kceiling)(__REAL_T *r)
{
__DBLE_T x;
__INT8_T a;
x = *r;
a = x; /* integer part */
if (a == x)
return x;
if (x > 0)
return a + 1;
return a;
}
__INT_T
ENTF90(DCEILING, dceiling)(__DBLE_T *r)
{
__DBLE_T x;
int a;
x = *r;
a = x; /* integer part */
if (a == x)
return x;
if (x > 0)
return a + 1;
return a;
}
__INT8_T
ENTF90(KDCEILING, kdceiling)(__DBLE_T *r)
{
__DBLE_T x;
__INT8_T a;
x = *r;
a = x; /* integer part */
if (a == x)
return x;
if (x > 0)
return a + 1;
return a;
}
__INT_T
ENTF90(CEILINGv, ceilingv)(__REAL_T r)
{
__DBLE_T x;
int a;
x = r;
a = x; /* integer part */
if (a == x)
return x;
if (x > 0)
return a + 1;
return a;
}
__INT8_T
ENTF90(KCEILINGv, kceilingv)(__REAL_T r)
{
__DBLE_T x;
__INT8_T a;
x = r;
a = x; /* integer part */
if (a == x)
return x;
if (x > 0)
return a + 1;
return a;
}
__INT_T
ENTF90(DCEILINGv, dceilingv)(__DBLE_T r)
{
__DBLE_T x;
int a;
x = r;
a = x; /* integer part */
if (a == x)
return x;
if (x > 0)
return a + 1;
return a;
}
__INT8_T
ENTF90(KDCEILINGv, kdceilingv)(__DBLE_T r)
{
__DBLE_T x;
__INT8_T a;
x = r;
a = x; /* integer part */
if (a == x)
return x;
if (x > 0)
return a + 1;
return a;
}
__INT_T
ENTF90(FLOOR, floor)(__REAL_T *r)
{
__DBLE_T x;
int a;
x = *r;
a = x; /* integer part */
if (a == x)
return x;
if (x < 0)
return a - 1;
return a;
}
__INT_T
ENTF90(KFLOOR, kfloor)(__REAL_T *r)
{
__DBLE_T x;
__INT8_T a;
x = *r;
a = x; /* integer part */
if (a == x)
return x;
if (x < 0)
return a - 1;
return a;
}
__INT_T
ENTF90(DFLOOR, dfloor)(__DBLE_T *r)
{
__DBLE_T x;
int a;
x = *r;
a = x; /* integer part */
if (a == x)
return x;
if (x < 0)
return a - 1;
return a;
}
__INT8_T
ENTF90(KDFLOOR, kdfloor)(__DBLE_T *r)
{
__DBLE_T x;
__INT8_T a;
x = *r;
a = x; /* integer part */
if (a == x)
return x;
if (x < 0)
return a - 1;
return a;
}
__INT_T
ENTF90(FLOORv, floorv)(__REAL_T r)
{
__DBLE_T x;
int a;
x = r;
a = x; /* integer part */
if (a == x)
return x;
if (x < 0)
return a - 1;
return a;
}
__INT_T
ENTF90(KFLOORv, kfloorv)(__REAL_T r)
{
__DBLE_T x;
__INT8_T a;
x = r;
a = x; /* integer part */
if (a == x)
return x;
if (x < 0)
return a - 1;
return a;
}
__INT_T
ENTF90(DFLOORv, dfloorv)(__DBLE_T r)
{
__DBLE_T x;
int a;
x = r;
a = x; /* integer part */
if (a == x)
return x;
if (x < 0)
return a - 1;
return a;
}
__INT8_T
ENTF90(KDFLOORv, kdfloorv)(__DBLE_T r)
{
__DBLE_T x;
__INT8_T a;
x = r;
a = x; /* integer part */
if (a == x)
return x;
if (x < 0)
return a - 1;
return a;
}
/** \brief selected_int_kind(r) */
__INT_T
ENTF90(SEL_INT_KIND, sel_int_kind)
(char *rb, F90_Desc *rd)
{
int r;
r = I8(__fort_fetch_int)(rb, rd);
if (r <= 2)
return 1;
if (r <= 4)
return 2;
if (r <= 9)
return 4;
if (r <= 18)
return 8;
return -1;
}
/** \brief
* -i8 variant of SEL_INT_KIND
*/
__INT8_T
ENTF90(KSEL_INT_KIND, ksel_int_kind)
(char *rb, F90_Desc *rd)
{
int r;
r = I8(__fort_fetch_int)(rb, rd);
if (r <= 2)
return 1;
if (r <= 4)
return 2;
if (r <= 9)
return 4;
if (r <= 18)
return 8;
return -1;
}
/* selected_char_kind(r) */
/** \brief Check charset
*
* Make sure this routine is consistent with
* - fe90: semfunc.c:_selected_char_kind()
* - f90: dinit.c:_selected_char_kind()
*/
static int
_selected_char_kind(char *p, __CLEN_T len)
{
if (__fortio_eq_str(p, len, "ASCII"))
return 1;
else if (__fortio_eq_str(p, len, "DEFAULT"))
return 1;
return -1;
}
__INT_T
ENTF90(SEL_CHAR_KINDA, sel_char_kinda)
(DCHAR(p), F90_Desc *rd DCLEN64(p))
{
int r;
r = _selected_char_kind(CADR(p), CLEN(p));
return r;
}
/* 32 bit CLEN version */
__INT_T
ENTF90(SEL_CHAR_KIND, sel_char_kind)
(DCHAR(p), F90_Desc *rd DCLEN(p))
{
return ENTF90(SEL_CHAR_KINDA, sel_char_kinda) (CADR(p), rd, (__CLEN_T)CLEN(p));
}
__INT8_T
ENTF90(KSEL_CHAR_KINDA, ksel_char_kinda)
(DCHAR(p), F90_Desc *rd DCLEN(p))
{
int r;
r = _selected_char_kind(CADR(p), CLEN(p));
return r;
}
/* 32 bit CLEN version */
__INT8_T
ENTF90(KSEL_CHAR_KIND, ksel_char_kind)
(DCHAR(p), F90_Desc *rd DCLEN(p))
{
return ENTF90(KSEL_CHAR_KINDA, ksel_char_kinda) (CADR(p), rd, (__CLEN_T)CLEN(p));
}
/* Real model support functions */
/* IEEE floating point - 4 byte reals, 8 byte double precision */
/** \brief selected_real_kind(p,r) */
__INT8_T
ENTF90(KSEL_REAL_KIND, ksel_real_kind)
(char *pb, char *rb, F90_Desc *pd, F90_Desc *rd)
{
/*
* -i8 variant of SEL_REAL_KIND
*/
int p, r, e, k;
e = 0;
k = 0;
if (ISPRESENT(pb)) {
p = I8(__fort_fetch_int)(pb, pd);
if (p <= 6)
k = 4;
else if (p <= 15)
k = 8;
else
e -= 1;
}
if (ISPRESENT(rb)) {
r = I8(__fort_fetch_int)(rb, rd);
if (r <= 37) {
if (k < 4)
k = 4;
}
else if (r <= 307) {
if (k < 8)
k = 8;
}
else
e -= 2;
}
return (__INT8_T)e ? e : k;
}
__INT_T
ENTF90(SEL_REAL_KIND, sel_real_kind)
(char *pb, char *rb, F90_Desc *pd, F90_Desc *rd)
{
int p, r, e, k;
e = 0;
k = 0;
if (ISPRESENT(pb)) {
p = I8(__fort_fetch_int)(pb, pd);
if (p <= 6)
k = 4;
else if (p <= 15)
k = 8;
else
e -= 1;
}
if (ISPRESENT(rb)) {
r = I8(__fort_fetch_int)(rb, rd);
if (r <= 37) {
if (k < 4)
k = 4;
}
else if (r <= 307) {
if (k < 8)
k = 8;
}
else
e -= 2;
}
return e ? e : k;
}
__INT_T
ENTF90(EXPONX, exponx)(__REAL4_T f)
{
union {
__INT4_T i;
__REAL4_T r;
} g;
g.r = f;
if ((g.i & ~0x80000000) == 0)
return 0;
else
return ((g.i >> 23) & 0xFF) - 126;
}
__INT_T
ENTF90(EXPON, expon)(__REAL4_T *f)
{
return ENTF90(EXPONX, exponx)(*f);
}
__INT_T
ENTF90(EXPONDX, expondx)(__REAL8_T d)
{
union {
__INT8_T i;
__REAL8_T r;
} g;
g.r = d;
if ((((g.i >> 32) & ~0x80000000) | (g.i & 0xffffffff)) == 0)
return 0;
else
return ((g.i >> 52) & 0x7FF) - 1022;
}
__INT_T
ENTF90(EXPOND, expond)(__REAL8_T *d)
{
return ENTF90(EXPONDX, expondx)(*d);
}
__INT8_T
ENTF90(KEXPONX, kexponx)(__REAL4_T f)
{
return ENTF90(EXPONX, exponx)(f);
}
__INT8_T
ENTF90(KEXPON, kexpon)(__REAL4_T *f)
{
return ENTF90(KEXPONX, kexponx)(*f);
}
__INT8_T
ENTF90(KEXPONDX, kexpondx)(__REAL8_T d)
{
return ENTF90(EXPONDX, expondx)(d);
}
__INT8_T
ENTF90(KEXPOND, kexpond)(__REAL8_T *d) {
return ENTF90(KEXPONDX, kexpondx)(*d);
}
__REAL4_T
ENTF90(FRACX, fracx)(__REAL4_T f)
{
union {
__REAL4_T f;
__INT4_T i;
} x;
x.f = f;
if (x.f != 0.0) {
x.i &= ~0x7F800000;
x.i |= 0x3F000000;
}
return x.f;
}
__REAL4_T
ENTF90(FRAC, frac)(__REAL4_T *f) { return ENTF90(FRACX, fracx)(*f); }
__REAL8_T
ENTF90(FRACDX, fracdx)(__REAL8_T d)
{
__REAL8_SPLIT x;
x.d = d;
if (x.d != 0.0) {
x.i.h &= ~0x7FF00000;
x.i.h |= 0x3FE00000;
}
return x.d;
}
__REAL8_T
ENTF90(FRACD, fracd)(__REAL8_T *d) { return ENTF90(FRACDX, fracdx)(*d); }
/** \brief NEAREST(X,S) has a value equal to the machine representable number
* distinct from X and nearest to it in the direction of the infinity
* with the same sign as S.
*
* The 'sign' argument is equal to the
* fortran logical expression (S .ge. 0.0). */
__REAL4_T
ENTF90(NEARESTX, nearestx)(__REAL4_T f, __LOG_T sign)
{
union {
__REAL4_T f;
__INT4_T i;
} x;
x.f = f;
if (x.f == 0.0) {
x.i = (sign & GET_DIST_MASK_LOG) ? 0x00800000 : 0x80800000;
} else if ((x.i & 0x7F800000) != 0x7F800000) { /* not nan or inf */
if ((x.f < 0.0) ^ (sign & GET_DIST_MASK_LOG))
++x.i;
else
--x.i;
}
return x.f;
}
__REAL4_T
ENTF90(NEAREST, nearest)(__REAL4_T *f, __LOG_T *sign)
{
return ENTF90(NEARESTX, nearestx)(*f, *sign);
}
__REAL8_T
ENTF90(NEARESTDX, nearestdx)(__REAL8_T d, __LOG_T sign)
{
__REAL8_SPLIT x;
x.d = d;
if (x.d == 0.0) {
x.i.h = (sign & 1) ? 0x00100000 : 0x80100000;
x.i.l = 0;
} else {
if ((x.ll >> 52 & 0x7FF) != 0x7FF) { /* not nan or inf */
if ((x.d < 0) ^ (sign & GET_DIST_MASK_LOG))
++x.ll;
else
--x.ll;
}
}
return x.d;
}
__REAL8_T
ENTF90(NEARESTD, nearestd)(__REAL8_T *d, __LOG_T *sign)
{
return ENTF90(NEARESTDX, nearestdx)(*d, *sign);
}
__REAL4_T
ENTF90(RRSPACINGX, rrspacingx)(__REAL4_T f)
{
union {
__REAL4_T f;
__INT4_T i;
} x, y;
x.f = f;
if (x.f == 0)
return 0;
y.i = (x.i & 0xFF << 23) ^ 0xFF << 23;
x.f *= y.f;
if (x.f < 0)
x.f = -x.f;
y.i = (22 + 127) << 23;
x.f *= y.f;
return x.f;
}
__REAL4_T
ENTF90(RRSPACING, rrspacing)(__REAL4_T *f)
{
return ENTF90(RRSPACINGX, rrspacingx)(*f);
}
__REAL8_T
ENTF90(RRSPACINGDX, rrspacingdx)(__REAL8_T d)
{
__REAL8_SPLIT x, y;
x.d = d;
if (x.d == 0)
return 0;
y.i.h = (x.i.h & 0x7FF << 20) ^ 0x7FF << 20;
y.i.l = 0;
x.d *= y.d;
if (x.d < 0)
x.d = -x.d;
y.i.h = (51 + 1023) << 20;
y.i.l = 0;
x.d *= y.d;
return x.d;
}
__REAL8_T
ENTF90(RRSPACINGD, rrspacingd)(__REAL8_T *d)
{
return ENTF90(RRSPACINGDX, rrspacingdx)(*d);
}
__REAL4_T
ENTF90(SCALEX, scalex)(__REAL4_T f, __INT_T i)
{
int e;
union {
__REAL4_T f;
__INT4_T i;
} x;
e = 127 + i;
if (e < 0)
e = 0;
else if (e > 255)
e = 255;
x.i = e << 23;
return f * x.f;
}
__REAL4_T
ENTF90(SCALE, scale)(__REAL4_T *f, void *i, __INT_T *size)
{
int e;
union {
__REAL4_T f;
__INT4_T i;
} x;
e = 127 + I8(__fort_varying_int)(i, size);
if (e < 0)
e = 0;
else if (e > 255)
e = 255;
x.i = e << 23;
return *f * x.f;
}
__REAL8_T
ENTF90(SCALEDX, scaledx)(__REAL8_T d, __INT_T i)
{
int e;
__REAL8_SPLIT x;
e = 1023 + i;
if (e < 0)
e = 0;
else if (e > 2047)
e = 2047;
x.i.h = e << 20;
x.i.l = 0;
return d * x.d;
}
__REAL8_T
ENTF90(SCALED, scaled)(__REAL8_T *d, void *i, __INT_T *size)
{
int e;
__REAL8_SPLIT x;
e = 1023 + I8(__fort_varying_int)(i, size);
if (e < 0)
e = 0;
else if (e > 2047)
e = 2047;
x.i.h = e << 20;
x.i.l = 0;
return *d * x.d;
}
__REAL4_T
ENTF90(SETEXPX, setexpx)(__REAL4_T f, __INT_T i)
{
int e;
union {
__REAL4_T f;
__INT4_T i;
} x, y;
y.f = f;
if (y.f == 0.0)
return y.f;
y.i &= ~0x7F800000;
y.i |= 0x3F800000;
e = 126 + i;
if (e < 0)
e = 0;
else if (e > 255)
e = 255;
x.i = e << 23;
return x.f * y.f;
}
__REAL4_T
ENTF90(SETEXP, setexp)(__REAL4_T *f, void *i, __INT_T *size)
{
int e;
union {
__REAL4_T f;
__INT4_T i;
} x, y;
y.f = *f;
if (y.f == 0.0)
return y.f;
y.i &= ~0x7F800000;
y.i |= 0x3F800000;
e = 126 + I8(__fort_varying_int)(i, size);
if (e < 0)
e = 0;
else if (e > 255)
e = 255;
x.i = e << 23;
return x.f * y.f;
}
__REAL8_T
ENTF90(SETEXPDX, setexpdx)(__REAL8_T d, __INT_T i)
{
int e;
__REAL8_SPLIT x, y;
y.d = d;
if (y.d == 0.0)
return y.d;
y.i.h &= ~0x7FF00000;
y.i.h |= 0x3FF00000;
e = 1022 + i;
if (e < 0)
e = 0;
else if (e > 2047)
e = 2047;
x.i.h = e << 20;
x.i.l = 0;
return x.d * y.d;
}
__REAL8_T
ENTF90(SETEXPD, setexpd)(__REAL8_T *d, void *i, __INT_T *size)
{
int e;
__REAL8_SPLIT x, y;
y.d = *d;
if (y.d == 0.0)
return y.d;
y.i.h &= ~0x7FF00000;
y.i.h |= 0x3FF00000;
e = 1022 + I8(__fort_varying_int)(i, size);
if (e < 0)
e = 0;
else if (e > 2047)
e = 2047;
x.i.h = e << 20;
x.i.l = 0;
return x.d * y.d;
}
__REAL4_T
ENTF90(SPACINGX, spacingx)(__REAL4_T f)
{
int e;
union {
__REAL4_T f;
__INT4_T i;
} x;
x.f = f;
e = ((x.i >> 23) & 0xFF) - 23;
if (e < 1)
e = 1;
x.i = e << 23;
return x.f;
}
__REAL4_T
ENTF90(SPACING, spacing)(__REAL4_T *f)
{
return ENTF90(SPACINGX, spacingx)(*f);
}
__REAL8_T
ENTF90(SPACINGDX, spacingdx)(__REAL8_T d)
{
int e;
__REAL8_SPLIT x;
x.d = d;
e = ((x.i.h >> 20) & 0x7FF) - 52;
if (e < 1)
e = 1;
x.i.h = e << 20;
x.i.l = 0;
return x.d;
}
__REAL8_T
ENTF90(SPACINGD, spacingd)(__REAL8_T *d)
{
return ENTF90(SPACINGDX, spacingdx)(*d);
}
#ifndef DESC_I8
typedef __INT8_T SZ_T;
#undef _MZERO
#define _MZERO(n, t) \
void \
ENTF90(MZEROERO##n, mzero##n)(void *d, SZ_T size) \
{ \
if (d && size > 0) \
__c_mzero##n(d, size); \
}
_MZERO(1, char)
_MZERO(2, short)
_MZERO(4, int)
_MZERO(8, long long)
void
ENTF90(MZEROZ8, mzeroz8)(void *d, SZ_T size)
{
if (d && size > 0) {
__c_mzero4(d, size * 2);
}
}
void
ENTF90(MZEROZ16, mzeroz16)(void *d, SZ_T size)
{
if (d && size > 0) {
__c_mzero8(d, size * 2);
}
}
#undef _MSET
#define _MSET(n, t) \
void ENTF90(MSET##n, mset##n)(void *d, void *v, SZ_T size) \
{ \
if (d && size > 0) \
__c_mset##n(d, *((t *)v), size); \
}
_MSET(1, char)
_MSET(2, short)
_MSET(4, int)
_MSET(8, long long)
void
ENTF90(MSETZ8, msetz8)(void *d, void *v, SZ_T size)
{
if (d) {
SZ_T i;
int *pd;
int v0, v1;
pd = (int *)d;
v0 = ((int *)v)[0];
v1 = ((int *)v)[1];
for (i = 0; i < size; i++) {
pd[0] = v0;
pd[1] = v1;
pd += 2;
}
}
}
void
ENTF90(MSETZ16, msetz16)(void *d, void *v, SZ_T size)
{
if (d) {
SZ_T i;
long long *pd;
long long v0, v1;
pd = (long long *)d;
v0 = ((long long *)v)[0];
v1 = ((long long *)v)[1];
for (i = 0; i < size; i++) {
pd[0] = v0;
pd[1] = v1;
pd += 2;
}
}
}
#undef _MCOPY
#define _MCOPY(n, t) \
void ENTF90(MCOPY##n, mcopy##n)(void *d, void *v, SZ_T size) \
{ \
if (d && v && size > 0) \
__c_mcopy##n(d, v, size); \
}
_MCOPY(1, char)
_MCOPY(2, short)
_MCOPY(4, int)
_MCOPY(8, long long)
void
ENTF90(MCOPYZ8, mcopyz8)(void *d, void *v, SZ_T size)
{
if (d && v && size) {
__c_mcopy4(d, v, size * 2);
}
}
void
ENTF90(MCOPYZ16, mcopyz16)(void *d, void *v, SZ_T size)
{
if (d && v && size) {
__c_mcopy8(d, v, size * 2);
}
}
#endif /* #if !defined(DESC_I8) */
/** \brief
* helper function to store the MXINT_T value into a simple numerical type
*/
static void
store_mxint_t(void *b, F90_Desc *bd, MXINT_T v)
{
switch (TYPEKIND(bd)) {
case __INT1:
case __LOG1:
*(__INT1_T *)b = (__INT1_T)v;
break;
case __INT2:
case __LOG2:
*(__INT2_T *)b = (__INT2_T)v;
break;
case __INT4:
case __LOG4:
*(__INT4_T *)b = (__INT4_T)v;
break;
case __INT8:
case __LOG8:
*(__INT8_T *)b = (__INT8_T)v;
break;
case __REAL4:
*(__REAL4_T *)b = (__REAL4_T)v;
break;
case __REAL8:
*(__REAL8_T *)b = (__REAL8_T)v;
break;
case __REAL16:
*(__REAL16_T *)b = (__REAL16_T)v;
break;
default:
*(__STAT_T *)b = (__STAT_T)v;
}
}
/** \brief
* helper function to store the STAT_T value into a varying int
*/
static MXINT_T
mxint(F90_Desc *bd)
{
MXINT_T v;
switch (TYPEKIND(bd)) {
case __INT1:
case __LOG1:
v = ~((__INT1_T)1 << (8 * sizeof(__INT1_T) - 1));
break;
case __INT2:
case __LOG2:
v = ~((__INT2_T)1 << (8 * sizeof(__INT2_T) - 1));
break;
case __INT8:
case __LOG8:
v = ~((__INT8_T)1 << (8 * sizeof(__INT8_T) - 1));
break;
case __INT4:
case __LOG4:
default:
v = ~((__INT4_T)1 << (8 * sizeof(__INT4_T) - 1));
break;
}
return v;
}
| 21.123279 | 97 | 0.568509 | [
"object",
"shape",
"model"
] |
457d7295e7179ecf8a591571ceb28ff108d9f05d | 1,261 | h | C | include/Camera&Image/Image.h | lsfcin/air-guitar-framework | eb3e00a9496e52f9df95364b11e6c9dd6501bb01 | [
"MIT"
] | null | null | null | include/Camera&Image/Image.h | lsfcin/air-guitar-framework | eb3e00a9496e52f9df95364b11e6c9dd6501bb01 | [
"MIT"
] | null | null | null | include/Camera&Image/Image.h | lsfcin/air-guitar-framework | eb3e00a9496e52f9df95364b11e6c9dd6501bb01 | [
"MIT"
] | null | null | null | #ifndef __IMAGE_H__
#define __IMAGE_H__
#include <stdlib.h>
#include <GL/glut.h>
#include <vector>
#include <queue>
#include "Resolution.h"
#include "Point2D.h"
#include "HandsPoints.h"
using namespace std;
#define DISTANCE_TOL 2
typedef struct ColorGroup
{
vector<Point2D> pixelsPositions;
int color;
} ColourGroup;
class Image
{
public:
Image();
Image(Resolution resolution, int nChannels, char *data);
~Image(){
if(markedPointsMap) {
delete [] markedPointsMap;
}
}
HandsPoints findHandsPoints(int colorLeft, int colorRight);
void markPoint(float x, float y, int mark);
void markPoint(Point2D point, int mark);
bool isPointMarked(float x, float y);
bool isPointMarked(Point2D point);
Color getPointColor(Point2D point);
Color getPointColor(int x, int y);
Resolution getResolution();
int getNChannels();
char* getData();
int* getMarkedPointsMap();
vector<ColorGroup> getHandsGroups();
void makeColorGroup(ColorGroup &colorGroup);
void makeColorGroups(int color);
Point2D findColorGroupBottom(ColorGroup &colorGroup);
Point2D findColorGroupCenter(ColorGroup &colorGroup);
private:
Resolution resolution;
int nChannels;
char *data;
int *markedPointsMap;
vector<ColorGroup> colorGroups;
};
#endif // __IMAGE_H__ | 19.106061 | 60 | 0.75337 | [
"vector"
] |
457f4338d60ea02882ea1c07f419810ae4c3ccc8 | 18,454 | h | C | ManagedScripts/MSoldierGameObj.h | mpforums/RenSharp | 5b3fb8bff2a1772a82a4148bcf3e1265a11aa097 | [
"Apache-2.0"
] | 1 | 2021-10-04T02:34:33.000Z | 2021-10-04T02:34:33.000Z | ManagedScripts/MSoldierGameObj.h | TheUnstoppable/RenSharp | 2a123c6018c18f3fc73501737d600e291ac3afa7 | [
"Apache-2.0"
] | 9 | 2019-07-03T19:19:59.000Z | 2020-03-02T22:00:21.000Z | ManagedScripts/MSoldierGameObj.h | TheUnstoppable/RenSharp | 2a123c6018c18f3fc73501737d600e291ac3afa7 | [
"Apache-2.0"
] | 2 | 2019-08-14T08:37:36.000Z | 2020-09-29T06:44:26.000Z | /*
Copyright 2020 Neijwiert
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 "IUnmanagedObject.h"
#include "AbstractUnmanagedObject.h"
#include "IUnmanagedContainer.h"
#include "MSmartGameObj.h"
#include "MTransitionGameObjDef.h"
#include "Mscripts.h"
#include "MHumanStateClass.h"
#include "MArmorWarheadManager.h"
#pragma managed(push, off)
class SoldierGameObj;
class TransitionCompletionDataStruct;
#pragma managed(pop)
namespace RenSharp
{
interface class IReferencerClass;
interface class ISoldierGameObjDef;
interface class IRenderObjClass;
interface class IcPlayer;
interface class IDAPlayerClass;
interface class IAnimControlClass;
interface class IDialogueClass;
interface class IAudibleSoundClass;
public interface class ITransitionCompletionDataStruct : public IUnmanagedObject
{
property IntPtr TransitionCompletionDataStructPointer
{
IntPtr get();
}
property ITransitionDataClass::StyleType Type
{
ITransitionDataClass::StyleType get();
void set(ITransitionDataClass::StyleType value);
}
property IReferencerClass ^Vehicle
{
IReferencerClass ^get();
void set(IReferencerClass ^value);
}
};
public ref class TransitionCompletionDataStruct : public AbstractUnmanagedObject, public ITransitionCompletionDataStruct
{
private:
TransitionCompletionDataStruct();
public:
TransitionCompletionDataStruct(IntPtr pointer);
static IUnmanagedContainer<ITransitionCompletionDataStruct ^> ^CreateTransitionCompletionDataStruct();
bool Equals(Object ^other) override;
property IntPtr TransitionCompletionDataStructPointer
{
virtual IntPtr get() sealed;
}
property ITransitionDataClass::StyleType Type
{
virtual ITransitionDataClass::StyleType get() sealed;
virtual void set(ITransitionDataClass::StyleType value) sealed;
}
property IReferencerClass ^Vehicle
{
virtual IReferencerClass ^get() sealed;
virtual void set(IReferencerClass ^value) sealed;
}
protected:
bool InternalDestroyPointer() override;
property ::TransitionCompletionDataStruct *InternalTransitionCompletionDataStructPointer
{
virtual ::TransitionCompletionDataStruct *get();
}
};
public interface class ISoldierGameObj : public ISmartGameObj
{
void ReInit(ISoldierGameObjDef ^definition);
void ApplyDamageIgnoreVehicleCheck(IOffenseObjectClass ^damager, float scale, int alternateSkin);
void ApplyDamageIgnoreVehicleCheck(IOffenseObjectClass ^damager, float scale);
void ApplyDamageIgnoreVehicleCheck(IOffenseObjectClass ^damager);
void SetWeaponModel(String ^modelName);
void SetWeaponAnimation(String ^animName);
void StartTransitionAnimation(String ^animName, ITransitionCompletionDataStruct ^completionData);
void SetBlendedAnimation(String ^animationName, bool looping, float frameOffset, bool playBackwards);
void SetBlendedAnimation(String ^animationName, bool looping, float frameOffset);
void SetBlendedAnimation(String ^animationName, bool looping);
void SetBlendedAnimation(String ^animationName);
void ToggleFlyMode();
void LookAt(Vector3 pos, float time);
void UpdateLookAt(Vector3 pos);
void CancelLookAt();
void InnateEnable(int bits);
void InnateEnable();
void InnateDisable(int bits);
void InnateDisable();
bool IsInnateEnabled(int bits);
bool IsInnateEnabled();
void ClearInnateObserver();
void GiveKey(int keyNumber);
void RemoveKey(int keyNumber);
bool HasKey(int keyNumber);
void SetHumanAnimOverride(bool enableHumanAnimOverride);
int GetHumanAnimOverride();
void SetIsSniping();
property IntPtr SoldierGameObjPointer
{
IntPtr get();
}
property ISoldierGameObjDef ^Definition
{
ISoldierGameObjDef ^get();
}
property bool IsTurreted
{
bool get();
}
property bool DetonateC4
{
bool get();
}
property bool IsInElevator
{
bool get();
}
property bool IsDead
{
bool get();
}
property bool IsDestroyed
{
bool get();
}
property bool IsUpright
{
bool get();
}
property bool IsWounded
{
bool get();
}
property bool InTransition
{
bool get();
}
property bool IsAirborne
{
bool get();
}
property bool IsCrouched
{
bool get();
}
property bool IsSniping
{
bool get();
}
property bool IsSlow
{
bool get();
}
property bool IsOnLadder
{
bool get();
}
property bool IsInVehicle
{
bool get();
}
property float MaxSpeed
{
float get();
void set(float value);
}
property IVehicleGameObj ^Vehicle
{
IVehicleGameObj ^get();
}
property String ^AnimationName
{
String ^get();
}
property IHumanStateClass ^HumanState
{
IHumanStateClass ^get();
}
property bool IsLooking
{
bool get();
}
property IntPtr FacialAnim
{
IntPtr get();
}
property SoldierAIState AIState
{
SoldierAIState get();
}
property IntPtr InnateObserver
{
IntPtr get();
void set(IntPtr value);
}
property int KeyRing
{
int get();
}
property bool WantsPowerups
{
bool get();
}
property bool AllowSpecialDamageStateLock
{
bool get();
}
property bool IsVisible
{
bool get();
void set(bool value);
}
property bool IsTargetable
{
bool get();
}
property bool FlyMode
{
bool get();
}
property IHumanStateClass::HumanStateType State
{
IHumanStateClass::HumanStateType get();
}
property IRenderObjClass ^WeaponRenderModel
{
IRenderObjClass ^get();
}
property bool CanStealVehicles
{
bool get();
void set(bool value);
}
property bool CanDriveVehicles
{
bool get();
void set(bool value);
}
property bool BlockActionKey
{
bool get();
void set(bool value);
}
property bool Freeze
{
bool get();
void set(bool value);
}
property bool CanPlayDamageAnimations
{
bool get();
void set(bool value);
}
property float NetworkRescale
{
float get();
void set(float value);
}
property bool MovementLoitersAllowed
{
bool get();
void set(bool value);
}
property bool UseStockGhostBehavior
{
bool get();
}
property bool OverrideMuzzleDirection
{
bool get();
void set(bool value);
}
property int ContactSurfaceType
{
int get();
}
property float SkeletonHeight
{
float get();
void set(float value);
}
property float SkeletonWidth
{
float get();
void set(float value);
}
property int OverrideWeaponHoldStyle
{
int get();
void set(int value);
}
property IcPlayer ^Player
{
IcPlayer ^get();
}
property IDAPlayerClass ^DAPlayer
{
IDAPlayerClass ^get();
}
};
public ref class SoldierGameObj : public SmartGameObj, public ISoldierGameObj
{
public:
SoldierGameObj(IntPtr pointer);
virtual void ReInit(ISoldierGameObjDef ^definition) sealed;
virtual void ApplyDamageIgnoreVehicleCheck(IOffenseObjectClass ^damager, float scale, int alternateSkin) sealed;
virtual void ApplyDamageIgnoreVehicleCheck(IOffenseObjectClass ^damager, float scale) sealed;
virtual void ApplyDamageIgnoreVehicleCheck(IOffenseObjectClass ^damager) sealed;
virtual void SetWeaponModel(String ^modelName) sealed;
virtual void SetWeaponAnimation(String ^animName) sealed;
virtual void StartTransitionAnimation(String ^animName, ITransitionCompletionDataStruct ^completionData) sealed;
virtual void SetBlendedAnimation(String ^animationName, bool looping, float frameOffset, bool playBackwards) sealed;
virtual void SetBlendedAnimation(String ^animationName, bool looping, float frameOffset) sealed;
virtual void SetBlendedAnimation(String ^animationName, bool looping) sealed;
virtual void SetBlendedAnimation(String ^animationName) sealed;
virtual void ToggleFlyMode() sealed;
virtual void LookAt(Vector3 pos, float time) sealed;
virtual void UpdateLookAt(Vector3 pos) sealed;
virtual void CancelLookAt() sealed;
virtual void InnateEnable(int bits) sealed;
virtual void InnateEnable() sealed;
virtual void InnateDisable(int bits) sealed;
virtual void InnateDisable() sealed;
virtual bool IsInnateEnabled(int bits) sealed;
virtual bool IsInnateEnabled() sealed;
virtual void ClearInnateObserver() sealed;
virtual void GiveKey(int keyNumber) sealed;
virtual void RemoveKey(int keyNumber) sealed;
virtual bool HasKey(int keyNumber) sealed;
virtual void SetHumanAnimOverride(bool enableHumanAnimOverride) sealed;
virtual int GetHumanAnimOverride() sealed;
virtual void SetIsSniping() sealed;
property IntPtr SoldierGameObjPointer
{
virtual IntPtr get() sealed;
}
property ISoldierGameObjDef ^Definition
{
#pragma push_macro("new")
#undef new
virtual ISoldierGameObjDef ^get() new sealed;
#pragma pop_macro("new")
}
property bool IsTurreted
{
virtual bool get() sealed;
}
property bool DetonateC4
{
virtual bool get() sealed;
protected:
void set(bool value);
}
property bool IsInElevator
{
virtual bool get() sealed;
}
property bool IsDead
{
virtual bool get() sealed;
}
property bool IsDestroyed
{
virtual bool get() sealed;
}
property bool IsUpright
{
virtual bool get() sealed;
}
property bool IsWounded
{
virtual bool get() sealed;
}
property bool InTransition
{
virtual bool get() sealed;
}
property bool IsAirborne
{
virtual bool get() sealed;
}
property bool IsCrouched
{
virtual bool get() sealed;
}
property bool IsSniping
{
virtual bool get() sealed;
}
property bool IsSlow
{
virtual bool get() sealed;
}
property bool IsOnLadder
{
virtual bool get() sealed;
}
property bool IsInVehicle
{
virtual bool get() sealed;
}
property float MaxSpeed
{
float get() override sealed;
virtual void set(float value) sealed;
}
property IVehicleGameObj ^Vehicle
{
virtual IVehicleGameObj ^get() sealed;
protected:
void set(IVehicleGameObj ^value);
}
property String ^AnimationName
{
virtual String ^get() sealed;
protected:
void set(String ^value);
}
property IHumanStateClass ^HumanState
{
virtual IHumanStateClass ^get() sealed;
protected:
void set(IHumanStateClass ^value);
}
property bool IsLooking
{
virtual bool get() sealed;
}
property IntPtr FacialAnim
{
virtual IntPtr get() sealed;
}
property SoldierAIState AIState
{
virtual SoldierAIState get() sealed;
protected:
void set(SoldierAIState value);
}
property IntPtr InnateObserver
{
virtual IntPtr get() sealed;
virtual void set(IntPtr value) sealed;
}
property int KeyRing
{
virtual int get() sealed;
protected:
void set(int value);
}
property bool WantsPowerups
{
virtual bool get() sealed;
}
property bool AllowSpecialDamageStateLock
{
virtual bool get() sealed;
}
property bool IsVisible
{
bool get() override sealed;
virtual void set(bool value) sealed;
}
property bool IsTargetable
{
virtual bool get() sealed;
}
property bool FlyMode
{
virtual bool get() sealed;
protected:
void set(bool value);
}
property IHumanStateClass::HumanStateType State
{
virtual IHumanStateClass::HumanStateType get() sealed;
}
property IRenderObjClass ^WeaponRenderModel
{
virtual IRenderObjClass ^get() sealed;
protected:
void set(IRenderObjClass ^value);
}
property bool CanStealVehicles
{
virtual bool get() sealed;
virtual void set(bool value) sealed;
}
property bool CanDriveVehicles
{
virtual bool get() sealed;
virtual void set(bool value) sealed;
}
property bool BlockActionKey
{
virtual bool get() sealed;
virtual void set(bool value) sealed;
}
property bool Freeze
{
virtual bool get() sealed;
virtual void set(bool value) sealed;
}
property bool CanPlayDamageAnimations
{
virtual bool get() sealed;
virtual void set(bool value) sealed;
}
property float NetworkRescale
{
virtual float get() sealed;
virtual void set(float value) sealed;
}
property bool MovementLoitersAllowed
{
virtual bool get() sealed;
virtual void set(bool value) sealed;
}
property bool UseStockGhostBehavior
{
virtual bool get() sealed;
protected:
void set(bool value);
}
property bool OverrideMuzzleDirection
{
virtual bool get() sealed;
virtual void set(bool value) sealed;
}
property int ContactSurfaceType
{
virtual int get() sealed;
}
property float SkeletonHeight
{
virtual float get() sealed;
virtual void set(float value) sealed;
}
property float SkeletonWidth
{
virtual float get() sealed;
virtual void set(float value) sealed;
}
property int OverrideWeaponHoldStyle
{
virtual int get() sealed;
virtual void set(int value) sealed;
}
property IcPlayer ^Player
{
virtual IcPlayer ^get() sealed;
}
property IDAPlayerClass ^DAPlayer
{
virtual IDAPlayerClass ^get() sealed;
}
protected:
property ::SmartGameObj *InternalSmartGameObjPointer
{
::SmartGameObj *get() override;
}
property ::SoldierGameObj *InternalSoldierGameObjPointer
{
virtual ::SoldierGameObj *get();
}
property IRenderObjClass ^BackWeaponRenderModel
{
IRenderObjClass ^get();
void set(IRenderObjClass ^value);
}
property IRenderObjClass ^BackFlagRenderModel
{
IRenderObjClass ^get();
void set(IRenderObjClass ^value);
}
property IAnimControlClass ^WeaponAnimControl
{
IAnimControlClass ^get();
void set(IAnimControlClass ^value);
}
property ITransitionCompletionDataStruct ^TransitionCompletionData
{
ITransitionCompletionDataStruct ^get();
void set(ITransitionCompletionDataStruct ^value);
}
property float LegFacing
{
float get();
void set(float value);
}
property bool SyncLegs
{
bool get();
void set(bool value);
}
property bool LastLegMode
{
bool get();
void set(bool value);
}
property bool IsUsingGhostCollision
{
bool get();
void set(bool value);
}
property array<IDialogueClass ^> ^DialogList
{
array<IDialogueClass ^> ^get();
}
property IAudibleSoundClass ^CurrentSpeech
{
IAudibleSoundClass ^get();
void set(IAudibleSoundClass ^value);
}
property float HeadLookDuration
{
float get();
void set(float value);
}
property Vector3 HeadRotation
{
Vector3 get();
void set(Vector3 value);
}
property Vector3 HeadLookTarget
{
Vector3 get();
void set(Vector3 value);
}
property Vector3 HeadLookAngle
{
Vector3 get();
void set(Vector3 value);
}
property float HeadLookAngleTimer
{
float get();
void set(float value);
}
property int SubState
{
int get();
}
property ArmorWarheadManager::SpecialDamageType SpecialDamageMode
{
ArmorWarheadManager::SpecialDamageType get();
void set(ArmorWarheadManager::SpecialDamageType value);
}
property float SpecialDamageTimer
{
float get();
void set(float value);
}
property IReferencerClass ^SpecialDamageDamager
{
IReferencerClass ^get();
void set(IReferencerClass ^value);
}
property IntPtr SpecialDamageEffect
{
IntPtr get();
void set(IntPtr value);
}
property IntPtr HealingEffect
{
IntPtr get();
void set(IntPtr value);
}
property IReferencerClass ^FacingObject
{
IReferencerClass ^get();
void set(IReferencerClass ^value);
}
property bool FacingAllowBodyTurn
{
bool get();
void set(bool value);
}
property int InnateEnableBits
{
int get();
void set(int value);
}
property IntPtr SpeechAnim
{
IntPtr get();
void set(IntPtr value);
}
property float GenerateIdleFacialAnimTimer
{
float get();
void set(float value);
}
property IRenderObjClass ^HeadModel
{
IRenderObjClass ^get();
void set(IRenderObjClass ^value);
}
property IRenderObjClass ^EmotIconModel
{
IRenderObjClass ^get();
void set(IRenderObjClass ^value);
}
property float EmotIconTimer
{
float get();
void set(float value);
}
property bool LadderUpMask
{
bool get();
void set(bool value);
}
property bool LadderDownMask
{
bool get();
void set(bool value);
}
property float ReloadingTilt
{
float get();
void set(float value);
}
property bool WeaponChanged
{
bool get();
void set(bool value);
}
property IntPtr WaterWake
{
IntPtr get();
void set(IntPtr value);
}
property IDynamicVectorClass<IRenderObjClass ^> ^RenderObjList
{
IDynamicVectorClass<IRenderObjClass ^> ^get();
void set(IDynamicVectorClass<IRenderObjClass ^> ^value);
}
property int HeadBone
{
int get();
void set(int value);
}
property int NeckBone
{
int get();
void set(int value);
}
property float LastScale
{
float get();
void set(float value);
}
property bool UpdatedTarget
{
bool get();
void set(bool value);
}
property bool DoTilt
{
bool get();
void set(bool value);
}
property float LastSkeletonHeight
{
float get();
void set(float value);
}
property float LastSkeletonWidth
{
float get();
void set(float value);
}
property int OverrideWeaponHoldStyleId
{
int get();
void set(int value);
}
property bool EnableHumanAnimOverride
{
bool get();
void set(bool value);
}
};
} | 18.417166 | 121 | 0.68435 | [
"object"
] |
45805ef40c8c06795616ac0f1930dde596131654 | 4,697 | h | C | engine/platformX86UNIX/x86UNIXInputManager.h | ClayHanson/B4v21-Public-Repo | c812aa7bf2ecb267e02969c85f0c9c2a29be0d28 | [
"MIT"
] | 1 | 2020-08-18T19:45:34.000Z | 2020-08-18T19:45:34.000Z | engine/platformX86UNIX/x86UNIXInputManager.h | ClayHanson/B4v21-Launcher-Public-Repo | c812aa7bf2ecb267e02969c85f0c9c2a29be0d28 | [
"MIT"
] | null | null | null | engine/platformX86UNIX/x86UNIXInputManager.h | ClayHanson/B4v21-Launcher-Public-Repo | c812aa7bf2ecb267e02969c85f0c9c2a29be0d28 | [
"MIT"
] | null | null | null | //-----------------------------------------------------------------------------
// Torque Game Engine
// Copyright (C) GarageGames.com, Inc.
//-----------------------------------------------------------------------------
#ifndef _X86UNIXINPUTMANAGER_H_
#define _X86UNIXINPUTMANAGER_H_
#include "core/tVector.h"
#include "platform/platformInput.h"
#include "platformX86UNIX/platformX86UNIX.h"
#include <SDL/SDL_events.h>
#define NUM_KEYS ( KEY_OEM_102 + 1 )
#define KEY_FIRST KEY_ESCAPE
struct AsciiData
{
struct KeyData
{
U16 ascii;
bool isDeadChar;
};
KeyData upper;
KeyData lower;
KeyData goofy;
};
typedef struct _SDL_Joystick;
struct JoystickAxisInfo
{
S32 type;
S32 minValue;
S32 maxValue;
};
//------------------------------------------------------------------------------
class JoystickInputDevice : public InputDevice
{
public:
JoystickInputDevice(U8 deviceID);
~JoystickInputDevice();
bool activate();
bool deactivate();
bool isActive() { return( mActive ); }
U8 getDeviceType() { return( JoystickDeviceType ); }
U8 getDeviceID() { return( mDeviceID ); }
const char* getName();
const char* getJoystickAxesString();
void loadJoystickInfo();
void loadAxisInfo();
JoystickAxisInfo& getAxisInfo(int axisNum) { return mAxisList[axisNum]; }
bool process();
void reset();
private:
bool mActive;
U8 mDeviceID;
SDL_Joystick* mStick;
Vector<JoystickAxisInfo> mAxisList;
Vector<bool> mButtonState;
Vector<U8> mHatState;
S32 mNumAxes;
S32 mNumButtons;
S32 mNumHats;
S32 mNumBalls;
};
//------------------------------------------------------------------------------
class UInputManager : public InputManager
{
friend bool JoystickInputDevice::process(); // for joystick event funcs
friend void JoystickInputDevice::reset();
public:
UInputManager();
void init();
bool enable();
void disable();
void activate();
void deactivate();
void setWindowLocked(bool locked);
bool isActive() { return( mActive ); }
void onDeleteNotify( SimObject* object );
bool onAdd();
void onRemove();
void process();
bool enableKeyboard();
void disableKeyboard();
bool isKeyboardEnabled() { return( mKeyboardEnabled ); }
bool activateKeyboard();
void deactivateKeyboard();
bool isKeyboardActive() { return( mKeyboardActive ); }
bool enableMouse();
void disableMouse();
bool isMouseEnabled() { return( mMouseEnabled ); }
bool activateMouse();
void deactivateMouse();
bool isMouseActive() { return( mMouseActive ); }
bool enableJoystick();
void disableJoystick();
bool isJoystickEnabled() { return( mJoystickEnabled ); }
bool activateJoystick();
void deactivateJoystick();
bool isJoystickActive() { return( mJoystickActive ); }
void setLocking(bool enabled);
bool getLocking() { return mLocking; }
const char* getJoystickAxesString( U32 deviceID );
bool joystickDetected() { return mJoystickList.size() > 0; }
private:
typedef SimGroup Parent;
// the following vector is just for quick access during event processing.
// it does not manage the cleanup of the JoystickInputDevice objects
Vector<JoystickInputDevice*> mJoystickList;
bool mKeyboardEnabled;
bool mMouseEnabled;
bool mJoystickEnabled;
bool mKeyboardActive;
bool mMouseActive;
bool mJoystickActive;
bool mActive;
// Device state variables
S32 mModifierKeys;
bool mKeyboardState[256];
bool mMouseButtonState[3];
// last mousex and y are maintained when window is unlocked
S32 mLastMouseX;
S32 mLastMouseY;
void initJoystick();
void resetKeyboardState();
void resetMouseState();
void resetInputState();
void lockInput();
void unlockInput();
bool mLocking;
void joyHatEvent(U8 deviceID, U8 hatNum,
U8 prevHatState, U8 currHatState);
void joyButtonEvent(U8 deviceID, U8 buttonNum, bool pressed);
void joyButtonEvent(const SDL_Event& event);
void joyAxisEvent(const SDL_Event& event);
void joyAxisEvent(U8 deviceID, U8 axisNum, S16 axisValue);
void mouseButtonEvent(const SDL_Event& event);
void mouseMotionEvent(const SDL_Event& event);
void keyEvent(const SDL_Event& event);
bool processKeyEvent(InputEvent &event);
};
#endif // _H_X86UNIXINPUTMANAGER_
| 26.6875 | 80 | 0.608473 | [
"object",
"vector"
] |
45860992c5bc8229e601f0b70605bc7bb2dbc48b | 19,850 | h | C | include/num_collect/opt/dividing_rectangles.h | MusicScience37/numerical-collection-cpp | 490c24aae735ba25f1060b2941cff39050a41f8f | [
"Apache-2.0"
] | null | null | null | include/num_collect/opt/dividing_rectangles.h | MusicScience37/numerical-collection-cpp | 490c24aae735ba25f1060b2941cff39050a41f8f | [
"Apache-2.0"
] | null | null | null | include/num_collect/opt/dividing_rectangles.h | MusicScience37/numerical-collection-cpp | 490c24aae735ba25f1060b2941cff39050a41f8f | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2021 MusicScience37 (Kenta Kabashima)
*
* 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.
*/
/*!
* \file
* \brief Definition of dividing_rectangles class.
*/
#pragma once
#include <algorithm>
#include <limits>
#include <queue>
#include <tuple>
#include <type_traits>
#include <vector>
#include <Eigen/Core>
#include "num_collect/base/assert.h"
#include "num_collect/base/get_size.h"
#include "num_collect/base/norm.h"
#include "num_collect/logging/log_tag_view.h"
#include "num_collect/opt/optimizer_base.h"
#include "num_collect/util/is_eigen_vector.h"
#include "num_collect/util/safe_cast.h"
namespace num_collect::opt {
//! Tag of dividing_rectangles.
inline constexpr auto dividing_rectangles_tag =
logging::log_tag_view("num_collect::opt::dividing_rectangles");
/*!
* \brief Class of dividing rectangles (DIRECT) method \cite Jones1993 for
* optimization.
*
* \tparam ObjectiveFunction Type of the objective function.
*/
template <typename ObjectiveFunction, typename = void>
class dividing_rectangles;
/*!
* \brief Class of dividing rectangles (DIRECT) method \cite Jones1993 for
* optimization.
*
* \tparam ObjectiveFunction Type of the objective function.
*/
template <typename ObjectiveFunction>
class dividing_rectangles<ObjectiveFunction,
std::enable_if_t<
is_eigen_vector_v<typename ObjectiveFunction::variable_type> ||
std::is_floating_point_v<typename ObjectiveFunction::variable_type>>>
: public optimizer_base<dividing_rectangles<ObjectiveFunction>> {
public:
//! Type of the objective function.
using objective_function_type = ObjectiveFunction;
//! Type of variables.
using variable_type = typename objective_function_type::variable_type;
//! Type of function values.
using value_type = typename objective_function_type::value_type;
/*!
* \brief Construct.
*
* \param[in] obj_fun Objective function.
*/
explicit dividing_rectangles(
const objective_function_type& obj_fun = objective_function_type())
: optimizer_base<dividing_rectangles<ObjectiveFunction>>(
dividing_rectangles_tag),
obj_fun_(obj_fun) {}
/*!
* \brief Initialize the algorithm.
*
* \param[in] lower Lower limit.
* \param[in] upper Upper limit.
*/
void init(const variable_type& lower, const variable_type& upper) {
if constexpr (is_eigen_vector_v<variable_type>) {
NUM_COLLECT_ASSERT(lower.size() == upper.size());
}
lower_ = lower;
upper_ = upper;
width_ = upper_ - lower_;
dim_ = get_size(lower_);
const auto half = static_cast<value_type>(0.5);
const variable_type first_var = half * width_ + lower_;
obj_fun_.evaluate_on(first_var);
opt_variable_ = first_var;
opt_value_ = obj_fun_.value();
iterations_ = 0;
evaluations_ = 1;
rects_.clear();
rects_.emplace_back();
if constexpr (is_eigen_vector_v<variable_type>) {
rects_[0].push(
std::make_shared<rectangle>(variable_type::Zero(dim_),
variable_type::Ones(dim_), opt_value_));
} else {
rects_[0].push(
std::make_shared<rectangle>(static_cast<variable_type>(0),
static_cast<variable_type>(1), opt_value_));
}
}
/*!
* \copydoc num_collect::opt::optimizer_base::iterate
*/
void iterate() {
const auto divided_rects = determine_rects();
for (auto iter = std::rbegin(divided_rects);
iter != std::rend(divided_rects); ++iter) {
divide_rect(iter->first);
}
++iterations_;
}
/*!
* \copydoc num_collect::base::iterative_solver_base::is_stop_criteria_satisfied
*/
[[nodiscard]] auto is_stop_criteria_satisfied() const -> bool {
return evaluations() >= max_evaluations_;
}
/*!
* \copydoc num_collect::base::iterative_solver_base::configure_iteration_logger
*/
void configure_iteration_logger(
logging::iteration_logger& iteration_logger) const {
iteration_logger.append<index_type>(
"Iter.", [this] { return iterations(); });
iteration_logger.append<index_type>(
"Eval.", [this] { return evaluations(); });
iteration_logger.append<value_type>(
"Value", [this] { return opt_value(); });
}
/*!
* \copydoc num_collect::opt::optimizer_base::opt_variable
*/
[[nodiscard]] auto opt_variable() const -> const variable_type& {
return opt_variable_;
}
/*!
* \copydoc num_collect::opt::optimizer_base::opt_value
*/
[[nodiscard]] auto opt_value() const -> const value_type& {
return opt_value_;
}
/*!
* \copydoc num_collect::opt::optimizer_base::iterations
*/
[[nodiscard]] auto iterations() const noexcept -> index_type {
return iterations_;
}
/*!
* \copydoc num_collect::opt::optimizer_base::evaluations
*/
[[nodiscard]] auto evaluations() const noexcept -> index_type {
return evaluations_;
}
/*!
* \brief Set the maximum number of function evaluations.
*
* \param[in] value Value.
* \return This object.
*/
auto max_evaluations(index_type value) -> dividing_rectangles& {
NUM_COLLECT_ASSERT(value > 0);
max_evaluations_ = value;
return *this;
}
/*!
* \brief Set the minimum rate of improvement in the function value required
* for potentially optimal rectangles.
*
* \param[in] value Value.
* \return This object.
*/
auto min_rate_imp(value_type value) -> dividing_rectangles& {
NUM_COLLECT_ASSERT(value > 0);
min_rate_imp_ = value;
return *this;
}
private:
/*!
* \brief Class of hyper rectanble in DIRECT method.
*/
class rectangle {
public:
/*!
* \brief Construct.
*
* \param[in] lower Element-wise lower limit.
* \param[in] upper Element-wise upper limit.
* \param[in] value Function value at the center.
*/
rectangle(const variable_type& lower, const variable_type& upper,
const value_type& value)
: lower_(lower),
upper_(upper),
is_divided_(util::safe_cast<std::size_t>(get_size(lower)), false),
dist_(norm(lower - upper) * half),
value_(value) {}
/*!
* \brief Get element-wise lower limit.
*
* \return Element-wise lower limit.
*/
[[nodiscard]] auto lower() const -> const variable_type& {
return lower_;
}
/*!
* \brief Get element-wise upper limit.
*
* \return Element-wise upper limit.
*/
[[nodiscard]] auto upper() const -> const variable_type& {
return upper_;
}
/*!
* \brief Get whether each dimension is divided.
*
* \return Whether each dimension is divided.
*/
[[nodiscard]] auto is_divided() const -> const std::vector<bool>& {
return is_divided_;
}
/*!
* \brief Get distance between center point and end point.
*
* \return Distance between center point and end point.
*/
[[nodiscard]] auto dist() const -> const value_type& { return dist_; }
/*!
* \brief Get function value at the center.
*
* \return Function value at the center.
*/
[[nodiscard]] auto value() const -> const value_type& { return value_; }
/*!
* \brief Divide this object in place.
*
* \param[in] dim Dimension index.
* \param[in] lower New lower bound.
* \param[in] upper New upper bound.
* \param[in] value New value.
*/
void divide_in_place(index_type dim, value_type lower, value_type upper,
value_type value) {
NUM_COLLECT_DEBUG_ASSERT(lower < upper);
NUM_COLLECT_DEBUG_ASSERT(!is_divided_[dim]);
if constexpr (is_eigen_vector_v<variable_type>) {
lower_(dim) = lower;
upper_(dim) = upper;
} else {
lower_ = lower;
upper_ = upper;
}
dist_ = norm(lower_ - upper_) * half;
value_ = value;
is_divided_[dim] = true;
if (std::all_of(std::begin(is_divided_), std::end(is_divided_),
[](bool elem) { return elem; })) {
std::fill(
std::begin(is_divided_), std::end(is_divided_), false);
}
}
/*!
* \brief Divide this object and return the divided rectangle.
*
* \param[in] dim Dimension index.
* \param[in] lower New lower bound.
* \param[in] upper New upper bound.
* \param[in] value New value.
* \return Divided rectangle.
*/
[[nodiscard]] auto divide(index_type dim, value_type lower,
value_type upper, value_type value) const
-> std::shared_ptr<rectangle> {
auto ptr = std::make_shared<rectangle>(*this);
ptr->divide_in_place(dim, lower, upper, value);
return ptr;
}
private:
//! Half.
static inline const auto half = static_cast<value_type>(0.5);
//! Element-wise lower limit.
variable_type lower_;
//! Element-wise upper limit.
variable_type upper_;
/*!
* \brief Whether each dimension is divided.
*
* If all dimensions are divided once, flags are reset.
*/
std::vector<bool> is_divided_;
//! Distance between center point and end point.
value_type dist_;
//! Function value at the center.
value_type value_;
};
/*!
* \brief Class to compare rectangles.
*/
struct greater_rectangle {
/*!
* \brief Compare rectangles.
*
* \param[in] left Left-hand-side rectangle.
* \param[in] right Right-hand-side rectangle.
* \return Result of left > right.
*/
[[nodiscard]] auto operator()(const std::shared_ptr<rectangle>& left,
const std::shared_ptr<rectangle>& right) const -> bool {
return left->value() > right->value();
}
};
/*!
* \brief Evaluate function value.
*
* \param[in] variable Variable in unit hyper-cube.
* \return Function value.
*/
[[nodiscard]] auto evaluate_on(const variable_type& variable)
-> value_type {
variable_type actual_var;
if constexpr (is_eigen_vector_v<variable_type>) {
actual_var = variable.cwiseProduct(width_) + lower_;
} else {
actual_var = variable * width_ + lower_;
}
obj_fun_.evaluate_on(actual_var);
if (obj_fun_.value() < opt_value_) {
opt_variable_ = actual_var;
opt_value_ = obj_fun_.value();
}
++evaluations_;
return obj_fun_.value();
}
/*!
* \brief Search rectangles to divide.
*
* \return List of (index in rects_, slope).
*/
[[nodiscard]] auto determine_rects() const
-> std::vector<std::pair<std::size_t, value_type>> {
std::vector<std::pair<std::size_t, value_type>> search_rects;
std::size_t ind = 0;
// find the largest rectangle
for (; ind < rects_.size(); ++ind) {
if (!rects_[ind].empty()) {
break;
}
}
search_rects.emplace_back(ind, std::numeric_limits<value_type>::max());
++ind;
// convex full scan
for (; ind < rects_.size(); ++ind) {
if (rects_[ind].empty()) {
continue;
}
while (true) {
const auto& [last_ind, last_slope] = search_rects.back();
const auto slope = calculate_slope(
*(rects_[last_ind].top()), *(rects_[ind].top()));
if (slope <= last_slope) {
search_rects.emplace_back(ind, slope);
break;
}
search_rects.pop_back();
}
}
// remove rectangles which won't update optimal value
using std::abs;
const auto value_bound = opt_value_ - min_rate_imp_ * abs(opt_value_);
for (auto iter = search_rects.begin(); iter != search_rects.end();) {
const auto& [ind, slope] = *iter;
if (rects_[ind].top()->value() -
slope * rects_[ind].top()->dist() <=
value_bound) {
++iter;
} else {
iter = search_rects.erase(iter);
}
}
return search_rects;
}
/*!
* \brief Calculate slope.
*
* \param[in] larger_rect Larger rectangle.
* \param[in] smaller_rect Smaller rectangle.
* \return Slope.
*/
[[nodiscard]] static auto calculate_slope(const rectangle& larger_rect,
const rectangle& smaller_rect) -> value_type {
return (larger_rect.value() - smaller_rect.value()) /
(larger_rect.dist() - smaller_rect.dist());
}
/*!
* \brief Divide a rectangle.
*
* \param[in] index Index in rects_.
*/
void divide_rect(std::size_t index) {
if (index + 1 == rects_.size()) {
rects_.emplace_back();
}
const auto origin = rects_[index].top();
rects_[index].pop();
const auto [divided_dim, lower_value, upper_value] =
determine_divided_dimension(*origin);
value_type divided_lowest;
value_type divided_uppest;
if constexpr (is_eigen_vector_v<variable_type>) {
divided_lowest = origin->lower()(divided_dim);
divided_uppest = origin->upper()(divided_dim);
} else {
divided_lowest = origin->lower();
divided_uppest = origin->upper();
}
const auto [divided_lower, divided_upper] =
separate_section(divided_lowest, divided_uppest);
rects_[index + 1].push(origin->divide(
divided_dim, divided_lowest, divided_lower, lower_value));
rects_[index + 1].push(origin->divide(
divided_dim, divided_upper, divided_uppest, upper_value));
origin->divide_in_place(
divided_dim, divided_lower, divided_upper, origin->value());
rects_[index + 1].push(origin);
}
/*!
* \brief Determine the divided dimension of a rectangle.
*
* \param[in] rect Rectangle.
* \return Dimension index, function value at lower new point, and function
* value at upper new point.
*/
[[nodiscard]] auto determine_divided_dimension(const rectangle& rect)
-> std::tuple<index_type, value_type, value_type> {
value_type min_value = std::numeric_limits<value_type>::max();
index_type dim = 0;
value_type dim_lower_value{};
value_type dim_upper_value{};
for (index_type i = 0; i < dim_; ++i) {
if (rect.is_divided()[util::safe_cast<std::size_t>(i)]) {
continue;
}
value_type width;
if constexpr (is_eigen_vector_v<variable_type>) {
width = rect.upper()[i] - rect.lower()[i];
} else {
width = rect.upper() - rect.lower();
}
static const auto one_third = static_cast<value_type>(1.0 / 3.0);
const value_type diff = width * one_third;
static const auto half = static_cast<value_type>(0.5);
variable_type center = (rect.lower() + rect.upper()) * half;
value_type origin_center;
if constexpr (is_eigen_vector_v<variable_type>) {
origin_center = center[i];
} else {
origin_center = center;
}
value_type lower_value;
value_type upper_value;
if constexpr (is_eigen_vector_v<variable_type>) {
center[i] = origin_center - diff;
lower_value = evaluate_on(center);
center[i] = origin_center + diff;
upper_value = evaluate_on(center);
} else {
lower_value = evaluate_on(origin_center - diff);
upper_value = evaluate_on(origin_center + diff);
}
if (lower_value < min_value) {
min_value = lower_value;
dim = i;
dim_lower_value = lower_value;
dim_upper_value = upper_value;
}
if (upper_value < min_value) {
min_value = upper_value;
dim = i;
dim_lower_value = lower_value;
dim_upper_value = upper_value;
}
}
return {dim, dim_lower_value, dim_upper_value};
}
/*!
* \brief Separate a section.
*
* \param[in] lowest Lower limit of the section.
* \param[in] uppest Upper limit of the section.
* \return Lower, upper point to separate the section.
*/
[[nodiscard]] static auto separate_section(value_type lowest,
value_type uppest) -> std::pair<value_type, value_type> {
const auto width = uppest - lowest;
static const auto one_third = static_cast<value_type>(1.0 / 3.0);
static const auto two_thirds = static_cast<value_type>(2.0 / 3.0);
return {lowest + one_third * width, lowest + two_thirds * width};
}
//! Objective function.
objective_function_type obj_fun_;
/*!
* \brief Rectangles.
*
* Rectangles are listed per size.
*/
std::vector<std::priority_queue<std::shared_ptr<rectangle>,
std::vector<std::shared_ptr<rectangle>>, greater_rectangle>>
rects_{};
//! Element-wise lower limit.
variable_type lower_{};
//! Element-wise upper limit.
variable_type upper_{};
//! Element-wise width.
variable_type width_{};
//! Number of dimension.
index_type dim_{0};
//! Current optimal variable.
variable_type opt_variable_{};
//! Current optimal value.
value_type opt_value_{};
//! Number of iterations.
index_type iterations_{0};
//! Number of function evaluations.
index_type evaluations_{0};
//! Default maximum number of function evaluations.
static constexpr index_type default_max_evaluations = 10000;
//! Maximum number of function evaluations.
index_type max_evaluations_{default_max_evaluations};
/*!
* \brief Default minimum rate of improvement in the function value required
* for potentially optimal rectangles.
*/
static inline const auto default_min_rate_imp =
static_cast<value_type>(1e-4);
/*!
* \brief Minimum rate of improvement in the function value required for
* potentially optimal rectangles.
*/
value_type min_rate_imp_{default_min_rate_imp};
};
} // namespace num_collect::opt
| 32.276423 | 84 | 0.585441 | [
"object",
"vector"
] |
458cfc9aaf94e291023d619c5449a150a6a25267 | 148,956 | h | C | hwy/ops/wasm_128-inl.h | malaterre/highway | 779e0c5539a85ec3a35c15f170c7604f5e63f9f1 | [
"Apache-2.0"
] | null | null | null | hwy/ops/wasm_128-inl.h | malaterre/highway | 779e0c5539a85ec3a35c15f170c7604f5e63f9f1 | [
"Apache-2.0"
] | null | null | null | hwy/ops/wasm_128-inl.h | malaterre/highway | 779e0c5539a85ec3a35c15f170c7604f5e63f9f1 | [
"Apache-2.0"
] | null | null | null | // Copyright 2019 Google LLC
//
// 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.
// 128-bit WASM vectors and operations.
// External include guard in highway.h - see comment there.
#include <stddef.h>
#include <stdint.h>
#include <wasm_simd128.h>
#include "hwy/base.h"
#include "hwy/ops/shared-inl.h"
#ifdef HWY_WASM_OLD_NAMES
#define wasm_i8x16_shuffle wasm_v8x16_shuffle
#define wasm_i16x8_shuffle wasm_v16x8_shuffle
#define wasm_i32x4_shuffle wasm_v32x4_shuffle
#define wasm_i64x2_shuffle wasm_v64x2_shuffle
#define wasm_u16x8_extend_low_u8x16 wasm_i16x8_widen_low_u8x16
#define wasm_u32x4_extend_low_u16x8 wasm_i32x4_widen_low_u16x8
#define wasm_i32x4_extend_low_i16x8 wasm_i32x4_widen_low_i16x8
#define wasm_i16x8_extend_low_i8x16 wasm_i16x8_widen_low_i8x16
#define wasm_u32x4_extend_high_u16x8 wasm_i32x4_widen_high_u16x8
#define wasm_i32x4_extend_high_i16x8 wasm_i32x4_widen_high_i16x8
#define wasm_i32x4_trunc_sat_f32x4 wasm_i32x4_trunc_saturate_f32x4
#define wasm_u8x16_add_sat wasm_u8x16_add_saturate
#define wasm_u8x16_sub_sat wasm_u8x16_sub_saturate
#define wasm_u16x8_add_sat wasm_u16x8_add_saturate
#define wasm_u16x8_sub_sat wasm_u16x8_sub_saturate
#define wasm_i8x16_add_sat wasm_i8x16_add_saturate
#define wasm_i8x16_sub_sat wasm_i8x16_sub_saturate
#define wasm_i16x8_add_sat wasm_i16x8_add_saturate
#define wasm_i16x8_sub_sat wasm_i16x8_sub_saturate
#endif
HWY_BEFORE_NAMESPACE();
namespace hwy {
namespace HWY_NAMESPACE {
template <typename T>
using Full128 = Simd<T, 16 / sizeof(T), 0>;
template <typename T>
using Full64 = Simd<T, 8 / sizeof(T), 0>;
namespace detail {
template <typename T>
struct Raw128 {
using type = __v128_u;
};
template <>
struct Raw128<float> {
using type = __f32x4;
};
} // namespace detail
template <typename T, size_t N = 16 / sizeof(T)>
class Vec128 {
using Raw = typename detail::Raw128<T>::type;
public:
// Compound assignment. Only usable if there is a corresponding non-member
// binary operator overload. For example, only f32 and f64 support division.
HWY_INLINE Vec128& operator*=(const Vec128 other) {
return *this = (*this * other);
}
HWY_INLINE Vec128& operator/=(const Vec128 other) {
return *this = (*this / other);
}
HWY_INLINE Vec128& operator+=(const Vec128 other) {
return *this = (*this + other);
}
HWY_INLINE Vec128& operator-=(const Vec128 other) {
return *this = (*this - other);
}
HWY_INLINE Vec128& operator&=(const Vec128 other) {
return *this = (*this & other);
}
HWY_INLINE Vec128& operator|=(const Vec128 other) {
return *this = (*this | other);
}
HWY_INLINE Vec128& operator^=(const Vec128 other) {
return *this = (*this ^ other);
}
Raw raw;
};
template <typename T>
using Vec64 = Vec128<T, 8 / sizeof(T)>;
// FF..FF or 0.
template <typename T, size_t N = 16 / sizeof(T)>
struct Mask128 {
typename detail::Raw128<T>::type raw;
};
namespace detail {
// Deduce Simd<T, N, 0> from Vec128<T, N>
struct DeduceD {
template <typename T, size_t N>
Simd<T, N, 0> operator()(Vec128<T, N>) const {
return Simd<T, N, 0>();
}
};
} // namespace detail
template <class V>
using DFromV = decltype(detail::DeduceD()(V()));
template <class V>
using TFromV = TFromD<DFromV<V>>;
// ------------------------------ BitCast
namespace detail {
HWY_INLINE __v128_u BitCastToInteger(__v128_u v) { return v; }
HWY_INLINE __v128_u BitCastToInteger(__f32x4 v) {
return static_cast<__v128_u>(v);
}
HWY_INLINE __v128_u BitCastToInteger(__f64x2 v) {
return static_cast<__v128_u>(v);
}
template <typename T, size_t N>
HWY_INLINE Vec128<uint8_t, N * sizeof(T)> BitCastToByte(Vec128<T, N> v) {
return Vec128<uint8_t, N * sizeof(T)>{BitCastToInteger(v.raw)};
}
// Cannot rely on function overloading because return types differ.
template <typename T>
struct BitCastFromInteger128 {
HWY_INLINE __v128_u operator()(__v128_u v) { return v; }
};
template <>
struct BitCastFromInteger128<float> {
HWY_INLINE __f32x4 operator()(__v128_u v) { return static_cast<__f32x4>(v); }
};
template <typename T, size_t N>
HWY_INLINE Vec128<T, N> BitCastFromByte(Simd<T, N, 0> /* tag */,
Vec128<uint8_t, N * sizeof(T)> v) {
return Vec128<T, N>{BitCastFromInteger128<T>()(v.raw)};
}
} // namespace detail
template <typename T, size_t N, typename FromT>
HWY_API Vec128<T, N> BitCast(Simd<T, N, 0> d,
Vec128<FromT, N * sizeof(T) / sizeof(FromT)> v) {
return detail::BitCastFromByte(d, detail::BitCastToByte(v));
}
// ------------------------------ Zero
// Returns an all-zero vector/part.
template <typename T, size_t N, HWY_IF_LE128(T, N)>
HWY_API Vec128<T, N> Zero(Simd<T, N, 0> /* tag */) {
return Vec128<T, N>{wasm_i32x4_splat(0)};
}
template <size_t N, HWY_IF_LE128(float, N)>
HWY_API Vec128<float, N> Zero(Simd<float, N, 0> /* tag */) {
return Vec128<float, N>{wasm_f32x4_splat(0.0f)};
}
template <class D>
using VFromD = decltype(Zero(D()));
// ------------------------------ Set
// Returns a vector/part with all lanes set to "t".
template <size_t N, HWY_IF_LE128(uint8_t, N)>
HWY_API Vec128<uint8_t, N> Set(Simd<uint8_t, N, 0> /* tag */, const uint8_t t) {
return Vec128<uint8_t, N>{wasm_i8x16_splat(static_cast<int8_t>(t))};
}
template <size_t N, HWY_IF_LE128(uint16_t, N)>
HWY_API Vec128<uint16_t, N> Set(Simd<uint16_t, N, 0> /* tag */,
const uint16_t t) {
return Vec128<uint16_t, N>{wasm_i16x8_splat(static_cast<int16_t>(t))};
}
template <size_t N, HWY_IF_LE128(uint32_t, N)>
HWY_API Vec128<uint32_t, N> Set(Simd<uint32_t, N, 0> /* tag */,
const uint32_t t) {
return Vec128<uint32_t, N>{wasm_i32x4_splat(static_cast<int32_t>(t))};
}
template <size_t N, HWY_IF_LE128(uint64_t, N)>
HWY_API Vec128<uint64_t, N> Set(Simd<uint64_t, N, 0> /* tag */,
const uint64_t t) {
return Vec128<uint64_t, N>{wasm_i64x2_splat(static_cast<int64_t>(t))};
}
template <size_t N, HWY_IF_LE128(int8_t, N)>
HWY_API Vec128<int8_t, N> Set(Simd<int8_t, N, 0> /* tag */, const int8_t t) {
return Vec128<int8_t, N>{wasm_i8x16_splat(t)};
}
template <size_t N, HWY_IF_LE128(int16_t, N)>
HWY_API Vec128<int16_t, N> Set(Simd<int16_t, N, 0> /* tag */, const int16_t t) {
return Vec128<int16_t, N>{wasm_i16x8_splat(t)};
}
template <size_t N, HWY_IF_LE128(int32_t, N)>
HWY_API Vec128<int32_t, N> Set(Simd<int32_t, N, 0> /* tag */, const int32_t t) {
return Vec128<int32_t, N>{wasm_i32x4_splat(t)};
}
template <size_t N, HWY_IF_LE128(int64_t, N)>
HWY_API Vec128<int64_t, N> Set(Simd<int64_t, N, 0> /* tag */, const int64_t t) {
return Vec128<int64_t, N>{wasm_i64x2_splat(t)};
}
template <size_t N, HWY_IF_LE128(float, N)>
HWY_API Vec128<float, N> Set(Simd<float, N, 0> /* tag */, const float t) {
return Vec128<float, N>{wasm_f32x4_splat(t)};
}
HWY_DIAGNOSTICS(push)
HWY_DIAGNOSTICS_OFF(disable : 4700, ignored "-Wuninitialized")
// Returns a vector with uninitialized elements.
template <typename T, size_t N, HWY_IF_LE128(T, N)>
HWY_API Vec128<T, N> Undefined(Simd<T, N, 0> d) {
return Zero(d);
}
HWY_DIAGNOSTICS(pop)
// Returns a vector with lane i=[0, N) set to "first" + i.
template <typename T, size_t N, typename T2>
Vec128<T, N> Iota(const Simd<T, N, 0> d, const T2 first) {
HWY_ALIGN T lanes[16 / sizeof(T)];
for (size_t i = 0; i < 16 / sizeof(T); ++i) {
lanes[i] = static_cast<T>(first + static_cast<T2>(i));
}
return Load(d, lanes);
}
// ================================================== ARITHMETIC
// ------------------------------ Addition
// Unsigned
template <size_t N>
HWY_API Vec128<uint8_t, N> operator+(const Vec128<uint8_t, N> a,
const Vec128<uint8_t, N> b) {
return Vec128<uint8_t, N>{wasm_i8x16_add(a.raw, b.raw)};
}
template <size_t N>
HWY_API Vec128<uint16_t, N> operator+(const Vec128<uint16_t, N> a,
const Vec128<uint16_t, N> b) {
return Vec128<uint16_t, N>{wasm_i16x8_add(a.raw, b.raw)};
}
template <size_t N>
HWY_API Vec128<uint32_t, N> operator+(const Vec128<uint32_t, N> a,
const Vec128<uint32_t, N> b) {
return Vec128<uint32_t, N>{wasm_i32x4_add(a.raw, b.raw)};
}
template <size_t N>
HWY_API Vec128<uint64_t, N> operator+(const Vec128<uint64_t, N> a,
const Vec128<uint64_t, N> b) {
return Vec128<uint64_t, N>{wasm_i64x2_add(a.raw, b.raw)};
}
// Signed
template <size_t N>
HWY_API Vec128<int8_t, N> operator+(const Vec128<int8_t, N> a,
const Vec128<int8_t, N> b) {
return Vec128<int8_t, N>{wasm_i8x16_add(a.raw, b.raw)};
}
template <size_t N>
HWY_API Vec128<int16_t, N> operator+(const Vec128<int16_t, N> a,
const Vec128<int16_t, N> b) {
return Vec128<int16_t, N>{wasm_i16x8_add(a.raw, b.raw)};
}
template <size_t N>
HWY_API Vec128<int32_t, N> operator+(const Vec128<int32_t, N> a,
const Vec128<int32_t, N> b) {
return Vec128<int32_t, N>{wasm_i32x4_add(a.raw, b.raw)};
}
template <size_t N>
HWY_API Vec128<int64_t, N> operator+(const Vec128<int64_t, N> a,
const Vec128<int64_t, N> b) {
return Vec128<int64_t, N>{wasm_i64x2_add(a.raw, b.raw)};
}
// Float
template <size_t N>
HWY_API Vec128<float, N> operator+(const Vec128<float, N> a,
const Vec128<float, N> b) {
return Vec128<float, N>{wasm_f32x4_add(a.raw, b.raw)};
}
// ------------------------------ Subtraction
// Unsigned
template <size_t N>
HWY_API Vec128<uint8_t, N> operator-(const Vec128<uint8_t, N> a,
const Vec128<uint8_t, N> b) {
return Vec128<uint8_t, N>{wasm_i8x16_sub(a.raw, b.raw)};
}
template <size_t N>
HWY_API Vec128<uint16_t, N> operator-(Vec128<uint16_t, N> a,
Vec128<uint16_t, N> b) {
return Vec128<uint16_t, N>{wasm_i16x8_sub(a.raw, b.raw)};
}
template <size_t N>
HWY_API Vec128<uint32_t, N> operator-(const Vec128<uint32_t, N> a,
const Vec128<uint32_t, N> b) {
return Vec128<uint32_t, N>{wasm_i32x4_sub(a.raw, b.raw)};
}
template <size_t N>
HWY_API Vec128<uint64_t, N> operator-(const Vec128<uint64_t, N> a,
const Vec128<uint64_t, N> b) {
return Vec128<uint64_t, N>{wasm_i64x2_sub(a.raw, b.raw)};
}
// Signed
template <size_t N>
HWY_API Vec128<int8_t, N> operator-(const Vec128<int8_t, N> a,
const Vec128<int8_t, N> b) {
return Vec128<int8_t, N>{wasm_i8x16_sub(a.raw, b.raw)};
}
template <size_t N>
HWY_API Vec128<int16_t, N> operator-(const Vec128<int16_t, N> a,
const Vec128<int16_t, N> b) {
return Vec128<int16_t, N>{wasm_i16x8_sub(a.raw, b.raw)};
}
template <size_t N>
HWY_API Vec128<int32_t, N> operator-(const Vec128<int32_t, N> a,
const Vec128<int32_t, N> b) {
return Vec128<int32_t, N>{wasm_i32x4_sub(a.raw, b.raw)};
}
template <size_t N>
HWY_API Vec128<int64_t, N> operator-(const Vec128<int64_t, N> a,
const Vec128<int64_t, N> b) {
return Vec128<int64_t, N>{wasm_i64x2_sub(a.raw, b.raw)};
}
// Float
template <size_t N>
HWY_API Vec128<float, N> operator-(const Vec128<float, N> a,
const Vec128<float, N> b) {
return Vec128<float, N>{wasm_f32x4_sub(a.raw, b.raw)};
}
// ------------------------------ SaturatedAdd
// Returns a + b clamped to the destination range.
// Unsigned
template <size_t N>
HWY_API Vec128<uint8_t, N> SaturatedAdd(const Vec128<uint8_t, N> a,
const Vec128<uint8_t, N> b) {
return Vec128<uint8_t, N>{wasm_u8x16_add_sat(a.raw, b.raw)};
}
template <size_t N>
HWY_API Vec128<uint16_t, N> SaturatedAdd(const Vec128<uint16_t, N> a,
const Vec128<uint16_t, N> b) {
return Vec128<uint16_t, N>{wasm_u16x8_add_sat(a.raw, b.raw)};
}
// Signed
template <size_t N>
HWY_API Vec128<int8_t, N> SaturatedAdd(const Vec128<int8_t, N> a,
const Vec128<int8_t, N> b) {
return Vec128<int8_t, N>{wasm_i8x16_add_sat(a.raw, b.raw)};
}
template <size_t N>
HWY_API Vec128<int16_t, N> SaturatedAdd(const Vec128<int16_t, N> a,
const Vec128<int16_t, N> b) {
return Vec128<int16_t, N>{wasm_i16x8_add_sat(a.raw, b.raw)};
}
// ------------------------------ SaturatedSub
// Returns a - b clamped to the destination range.
// Unsigned
template <size_t N>
HWY_API Vec128<uint8_t, N> SaturatedSub(const Vec128<uint8_t, N> a,
const Vec128<uint8_t, N> b) {
return Vec128<uint8_t, N>{wasm_u8x16_sub_sat(a.raw, b.raw)};
}
template <size_t N>
HWY_API Vec128<uint16_t, N> SaturatedSub(const Vec128<uint16_t, N> a,
const Vec128<uint16_t, N> b) {
return Vec128<uint16_t, N>{wasm_u16x8_sub_sat(a.raw, b.raw)};
}
// Signed
template <size_t N>
HWY_API Vec128<int8_t, N> SaturatedSub(const Vec128<int8_t, N> a,
const Vec128<int8_t, N> b) {
return Vec128<int8_t, N>{wasm_i8x16_sub_sat(a.raw, b.raw)};
}
template <size_t N>
HWY_API Vec128<int16_t, N> SaturatedSub(const Vec128<int16_t, N> a,
const Vec128<int16_t, N> b) {
return Vec128<int16_t, N>{wasm_i16x8_sub_sat(a.raw, b.raw)};
}
// ------------------------------ Average
// Returns (a + b + 1) / 2
// Unsigned
template <size_t N>
HWY_API Vec128<uint8_t, N> AverageRound(const Vec128<uint8_t, N> a,
const Vec128<uint8_t, N> b) {
return Vec128<uint8_t, N>{wasm_u8x16_avgr(a.raw, b.raw)};
}
template <size_t N>
HWY_API Vec128<uint16_t, N> AverageRound(const Vec128<uint16_t, N> a,
const Vec128<uint16_t, N> b) {
return Vec128<uint16_t, N>{wasm_u16x8_avgr(a.raw, b.raw)};
}
// ------------------------------ Absolute value
// Returns absolute value, except that LimitsMin() maps to LimitsMax() + 1.
template <size_t N>
HWY_API Vec128<int8_t, N> Abs(const Vec128<int8_t, N> v) {
return Vec128<int8_t, N>{wasm_i8x16_abs(v.raw)};
}
template <size_t N>
HWY_API Vec128<int16_t, N> Abs(const Vec128<int16_t, N> v) {
return Vec128<int16_t, N>{wasm_i16x8_abs(v.raw)};
}
template <size_t N>
HWY_API Vec128<int32_t, N> Abs(const Vec128<int32_t, N> v) {
return Vec128<int32_t, N>{wasm_i32x4_abs(v.raw)};
}
template <size_t N>
HWY_API Vec128<int64_t, N> Abs(const Vec128<int64_t, N> v) {
return Vec128<int64_t, N>{wasm_i64x2_abs(v.raw)};
}
template <size_t N>
HWY_API Vec128<float, N> Abs(const Vec128<float, N> v) {
return Vec128<float, N>{wasm_f32x4_abs(v.raw)};
}
// ------------------------------ Shift lanes by constant #bits
// Unsigned
template <int kBits, size_t N>
HWY_API Vec128<uint16_t, N> ShiftLeft(const Vec128<uint16_t, N> v) {
return Vec128<uint16_t, N>{wasm_i16x8_shl(v.raw, kBits)};
}
template <int kBits, size_t N>
HWY_API Vec128<uint16_t, N> ShiftRight(const Vec128<uint16_t, N> v) {
return Vec128<uint16_t, N>{wasm_u16x8_shr(v.raw, kBits)};
}
template <int kBits, size_t N>
HWY_API Vec128<uint32_t, N> ShiftLeft(const Vec128<uint32_t, N> v) {
return Vec128<uint32_t, N>{wasm_i32x4_shl(v.raw, kBits)};
}
template <int kBits, size_t N>
HWY_API Vec128<uint64_t, N> ShiftLeft(const Vec128<uint64_t, N> v) {
return Vec128<uint64_t, N>{wasm_i64x2_shl(v.raw, kBits)};
}
template <int kBits, size_t N>
HWY_API Vec128<uint32_t, N> ShiftRight(const Vec128<uint32_t, N> v) {
return Vec128<uint32_t, N>{wasm_u32x4_shr(v.raw, kBits)};
}
template <int kBits, size_t N>
HWY_API Vec128<uint64_t, N> ShiftRight(const Vec128<uint64_t, N> v) {
return Vec128<uint64_t, N>{wasm_u64x2_shr(v.raw, kBits)};
}
// Signed
template <int kBits, size_t N>
HWY_API Vec128<int16_t, N> ShiftLeft(const Vec128<int16_t, N> v) {
return Vec128<int16_t, N>{wasm_i16x8_shl(v.raw, kBits)};
}
template <int kBits, size_t N>
HWY_API Vec128<int16_t, N> ShiftRight(const Vec128<int16_t, N> v) {
return Vec128<int16_t, N>{wasm_i16x8_shr(v.raw, kBits)};
}
template <int kBits, size_t N>
HWY_API Vec128<int32_t, N> ShiftLeft(const Vec128<int32_t, N> v) {
return Vec128<int32_t, N>{wasm_i32x4_shl(v.raw, kBits)};
}
template <int kBits, size_t N>
HWY_API Vec128<int64_t, N> ShiftLeft(const Vec128<int64_t, N> v) {
return Vec128<int64_t, N>{wasm_i64x2_shl(v.raw, kBits)};
}
template <int kBits, size_t N>
HWY_API Vec128<int32_t, N> ShiftRight(const Vec128<int32_t, N> v) {
return Vec128<int32_t, N>{wasm_i32x4_shr(v.raw, kBits)};
}
template <int kBits, size_t N>
HWY_API Vec128<int64_t, N> ShiftRight(const Vec128<int64_t, N> v) {
return Vec128<int64_t, N>{wasm_i64x2_shr(v.raw, kBits)};
}
// 8-bit
template <int kBits, typename T, size_t N, HWY_IF_LANE_SIZE(T, 1)>
HWY_API Vec128<T, N> ShiftLeft(const Vec128<T, N> v) {
const DFromV<decltype(v)> d8;
// Use raw instead of BitCast to support N=1.
const Vec128<T, N> shifted{ShiftLeft<kBits>(Vec128<MakeWide<T>>{v.raw}).raw};
return kBits == 1
? (v + v)
: (shifted & Set(d8, static_cast<T>((0xFF << kBits) & 0xFF)));
}
template <int kBits, size_t N>
HWY_API Vec128<uint8_t, N> ShiftRight(const Vec128<uint8_t, N> v) {
const DFromV<decltype(v)> d8;
// Use raw instead of BitCast to support N=1.
const Vec128<uint8_t, N> shifted{
ShiftRight<kBits>(Vec128<uint16_t>{v.raw}).raw};
return shifted & Set(d8, 0xFF >> kBits);
}
template <int kBits, size_t N>
HWY_API Vec128<int8_t, N> ShiftRight(const Vec128<int8_t, N> v) {
const DFromV<decltype(v)> di;
const RebindToUnsigned<decltype(di)> du;
const auto shifted = BitCast(di, ShiftRight<kBits>(BitCast(du, v)));
const auto shifted_sign = BitCast(di, Set(du, 0x80 >> kBits));
return (shifted ^ shifted_sign) - shifted_sign;
}
// ------------------------------ RotateRight (ShiftRight, Or)
template <int kBits, typename T, size_t N>
HWY_API Vec128<T, N> RotateRight(const Vec128<T, N> v) {
constexpr size_t kSizeInBits = sizeof(T) * 8;
static_assert(0 <= kBits && kBits < kSizeInBits, "Invalid shift count");
if (kBits == 0) return v;
return Or(ShiftRight<kBits>(v), ShiftLeft<kSizeInBits - kBits>(v));
}
// ------------------------------ Shift lanes by same variable #bits
// After https://reviews.llvm.org/D108415 shift argument became unsigned.
HWY_DIAGNOSTICS(push)
HWY_DIAGNOSTICS_OFF(disable : 4245 4365, ignored "-Wsign-conversion")
// Unsigned
template <size_t N>
HWY_API Vec128<uint16_t, N> ShiftLeftSame(const Vec128<uint16_t, N> v,
const int bits) {
return Vec128<uint16_t, N>{wasm_i16x8_shl(v.raw, bits)};
}
template <size_t N>
HWY_API Vec128<uint16_t, N> ShiftRightSame(const Vec128<uint16_t, N> v,
const int bits) {
return Vec128<uint16_t, N>{wasm_u16x8_shr(v.raw, bits)};
}
template <size_t N>
HWY_API Vec128<uint32_t, N> ShiftLeftSame(const Vec128<uint32_t, N> v,
const int bits) {
return Vec128<uint32_t, N>{wasm_i32x4_shl(v.raw, bits)};
}
template <size_t N>
HWY_API Vec128<uint32_t, N> ShiftRightSame(const Vec128<uint32_t, N> v,
const int bits) {
return Vec128<uint32_t, N>{wasm_u32x4_shr(v.raw, bits)};
}
template <size_t N>
HWY_API Vec128<uint64_t, N> ShiftLeftSame(const Vec128<uint64_t, N> v,
const int bits) {
return Vec128<uint64_t, N>{wasm_i64x2_shl(v.raw, bits)};
}
template <size_t N>
HWY_API Vec128<uint64_t, N> ShiftRightSame(const Vec128<uint64_t, N> v,
const int bits) {
return Vec128<uint64_t, N>{wasm_u64x2_shr(v.raw, bits)};
}
// Signed
template <size_t N>
HWY_API Vec128<int16_t, N> ShiftLeftSame(const Vec128<int16_t, N> v,
const int bits) {
return Vec128<int16_t, N>{wasm_i16x8_shl(v.raw, bits)};
}
template <size_t N>
HWY_API Vec128<int16_t, N> ShiftRightSame(const Vec128<int16_t, N> v,
const int bits) {
return Vec128<int16_t, N>{wasm_i16x8_shr(v.raw, bits)};
}
template <size_t N>
HWY_API Vec128<int32_t, N> ShiftLeftSame(const Vec128<int32_t, N> v,
const int bits) {
return Vec128<int32_t, N>{wasm_i32x4_shl(v.raw, bits)};
}
template <size_t N>
HWY_API Vec128<int32_t, N> ShiftRightSame(const Vec128<int32_t, N> v,
const int bits) {
return Vec128<int32_t, N>{wasm_i32x4_shr(v.raw, bits)};
}
template <size_t N>
HWY_API Vec128<int64_t, N> ShiftLeftSame(const Vec128<int64_t, N> v,
const int bits) {
return Vec128<int64_t, N>{wasm_i64x2_shl(v.raw, bits)};
}
template <size_t N>
HWY_API Vec128<int64_t, N> ShiftRightSame(const Vec128<int64_t, N> v,
const int bits) {
return Vec128<int64_t, N>{wasm_i64x2_shr(v.raw, bits)};
}
// 8-bit
template <typename T, size_t N, HWY_IF_LANE_SIZE(T, 1)>
HWY_API Vec128<T, N> ShiftLeftSame(const Vec128<T, N> v, const int bits) {
const DFromV<decltype(v)> d8;
// Use raw instead of BitCast to support N=1.
const Vec128<T, N> shifted{
ShiftLeftSame(Vec128<MakeWide<T>>{v.raw}, bits).raw};
return shifted & Set(d8, static_cast<T>((0xFF << bits) & 0xFF));
}
template <size_t N>
HWY_API Vec128<uint8_t, N> ShiftRightSame(Vec128<uint8_t, N> v,
const int bits) {
const DFromV<decltype(v)> d8;
// Use raw instead of BitCast to support N=1.
const Vec128<uint8_t, N> shifted{
ShiftRightSame(Vec128<uint16_t>{v.raw}, bits).raw};
return shifted & Set(d8, 0xFF >> bits);
}
template <size_t N>
HWY_API Vec128<int8_t, N> ShiftRightSame(Vec128<int8_t, N> v, const int bits) {
const DFromV<decltype(v)> di;
const RebindToUnsigned<decltype(di)> du;
const auto shifted = BitCast(di, ShiftRightSame(BitCast(du, v), bits));
const auto shifted_sign = BitCast(di, Set(du, 0x80 >> bits));
return (shifted ^ shifted_sign) - shifted_sign;
}
// ignore Wsign-conversion
HWY_DIAGNOSTICS(pop)
// ------------------------------ Minimum
// Unsigned
template <size_t N>
HWY_API Vec128<uint8_t, N> Min(Vec128<uint8_t, N> a, Vec128<uint8_t, N> b) {
return Vec128<uint8_t, N>{wasm_u8x16_min(a.raw, b.raw)};
}
template <size_t N>
HWY_API Vec128<uint16_t, N> Min(Vec128<uint16_t, N> a, Vec128<uint16_t, N> b) {
return Vec128<uint16_t, N>{wasm_u16x8_min(a.raw, b.raw)};
}
template <size_t N>
HWY_API Vec128<uint32_t, N> Min(Vec128<uint32_t, N> a, Vec128<uint32_t, N> b) {
return Vec128<uint32_t, N>{wasm_u32x4_min(a.raw, b.raw)};
}
template <size_t N>
HWY_API Vec128<uint64_t, N> Min(Vec128<uint64_t, N> a, Vec128<uint64_t, N> b) {
alignas(16) uint64_t min[2];
min[0] = HWY_MIN(wasm_u64x2_extract_lane(a.raw, 0),
wasm_u64x2_extract_lane(b.raw, 0));
min[1] = HWY_MIN(wasm_u64x2_extract_lane(a.raw, 1),
wasm_u64x2_extract_lane(b.raw, 1));
return Vec128<uint64_t, N>{wasm_v128_load(min)};
}
// Signed
template <size_t N>
HWY_API Vec128<int8_t, N> Min(Vec128<int8_t, N> a, Vec128<int8_t, N> b) {
return Vec128<int8_t, N>{wasm_i8x16_min(a.raw, b.raw)};
}
template <size_t N>
HWY_API Vec128<int16_t, N> Min(Vec128<int16_t, N> a, Vec128<int16_t, N> b) {
return Vec128<int16_t, N>{wasm_i16x8_min(a.raw, b.raw)};
}
template <size_t N>
HWY_API Vec128<int32_t, N> Min(Vec128<int32_t, N> a, Vec128<int32_t, N> b) {
return Vec128<int32_t, N>{wasm_i32x4_min(a.raw, b.raw)};
}
template <size_t N>
HWY_API Vec128<int64_t, N> Min(Vec128<int64_t, N> a, Vec128<int64_t, N> b) {
alignas(16) int64_t min[4];
min[0] = HWY_MIN(wasm_i64x2_extract_lane(a.raw, 0),
wasm_i64x2_extract_lane(b.raw, 0));
min[1] = HWY_MIN(wasm_i64x2_extract_lane(a.raw, 1),
wasm_i64x2_extract_lane(b.raw, 1));
return Vec128<int64_t, N>{wasm_v128_load(min)};
}
// Float
template <size_t N>
HWY_API Vec128<float, N> Min(Vec128<float, N> a, Vec128<float, N> b) {
return Vec128<float, N>{wasm_f32x4_min(a.raw, b.raw)};
}
// ------------------------------ Maximum
// Unsigned
template <size_t N>
HWY_API Vec128<uint8_t, N> Max(Vec128<uint8_t, N> a, Vec128<uint8_t, N> b) {
return Vec128<uint8_t, N>{wasm_u8x16_max(a.raw, b.raw)};
}
template <size_t N>
HWY_API Vec128<uint16_t, N> Max(Vec128<uint16_t, N> a, Vec128<uint16_t, N> b) {
return Vec128<uint16_t, N>{wasm_u16x8_max(a.raw, b.raw)};
}
template <size_t N>
HWY_API Vec128<uint32_t, N> Max(Vec128<uint32_t, N> a, Vec128<uint32_t, N> b) {
return Vec128<uint32_t, N>{wasm_u32x4_max(a.raw, b.raw)};
}
template <size_t N>
HWY_API Vec128<uint64_t, N> Max(Vec128<uint64_t, N> a, Vec128<uint64_t, N> b) {
alignas(16) uint64_t max[2];
max[0] = HWY_MAX(wasm_u64x2_extract_lane(a.raw, 0),
wasm_u64x2_extract_lane(b.raw, 0));
max[1] = HWY_MAX(wasm_u64x2_extract_lane(a.raw, 1),
wasm_u64x2_extract_lane(b.raw, 1));
return Vec128<uint64_t, N>{wasm_v128_load(max)};
}
// Signed
template <size_t N>
HWY_API Vec128<int8_t, N> Max(Vec128<int8_t, N> a, Vec128<int8_t, N> b) {
return Vec128<int8_t, N>{wasm_i8x16_max(a.raw, b.raw)};
}
template <size_t N>
HWY_API Vec128<int16_t, N> Max(Vec128<int16_t, N> a, Vec128<int16_t, N> b) {
return Vec128<int16_t, N>{wasm_i16x8_max(a.raw, b.raw)};
}
template <size_t N>
HWY_API Vec128<int32_t, N> Max(Vec128<int32_t, N> a, Vec128<int32_t, N> b) {
return Vec128<int32_t, N>{wasm_i32x4_max(a.raw, b.raw)};
}
template <size_t N>
HWY_API Vec128<int64_t, N> Max(Vec128<int64_t, N> a, Vec128<int64_t, N> b) {
alignas(16) int64_t max[2];
max[0] = HWY_MAX(wasm_i64x2_extract_lane(a.raw, 0),
wasm_i64x2_extract_lane(b.raw, 0));
max[1] = HWY_MAX(wasm_i64x2_extract_lane(a.raw, 1),
wasm_i64x2_extract_lane(b.raw, 1));
return Vec128<int64_t, N>{wasm_v128_load(max)};
}
// Float
template <size_t N>
HWY_API Vec128<float, N> Max(Vec128<float, N> a, Vec128<float, N> b) {
return Vec128<float, N>{wasm_f32x4_max(a.raw, b.raw)};
}
// ------------------------------ Integer multiplication
// Unsigned
template <size_t N>
HWY_API Vec128<uint16_t, N> operator*(const Vec128<uint16_t, N> a,
const Vec128<uint16_t, N> b) {
return Vec128<uint16_t, N>{wasm_i16x8_mul(a.raw, b.raw)};
}
template <size_t N>
HWY_API Vec128<uint32_t, N> operator*(const Vec128<uint32_t, N> a,
const Vec128<uint32_t, N> b) {
return Vec128<uint32_t, N>{wasm_i32x4_mul(a.raw, b.raw)};
}
// Signed
template <size_t N>
HWY_API Vec128<int16_t, N> operator*(const Vec128<int16_t, N> a,
const Vec128<int16_t, N> b) {
return Vec128<int16_t, N>{wasm_i16x8_mul(a.raw, b.raw)};
}
template <size_t N>
HWY_API Vec128<int32_t, N> operator*(const Vec128<int32_t, N> a,
const Vec128<int32_t, N> b) {
return Vec128<int32_t, N>{wasm_i32x4_mul(a.raw, b.raw)};
}
// Returns the upper 16 bits of a * b in each lane.
template <size_t N>
HWY_API Vec128<uint16_t, N> MulHigh(const Vec128<uint16_t, N> a,
const Vec128<uint16_t, N> b) {
// TODO(eustas): replace, when implemented in WASM.
const auto al = wasm_u32x4_extend_low_u16x8(a.raw);
const auto ah = wasm_u32x4_extend_high_u16x8(a.raw);
const auto bl = wasm_u32x4_extend_low_u16x8(b.raw);
const auto bh = wasm_u32x4_extend_high_u16x8(b.raw);
const auto l = wasm_i32x4_mul(al, bl);
const auto h = wasm_i32x4_mul(ah, bh);
// TODO(eustas): shift-right + narrow?
return Vec128<uint16_t, N>{
wasm_i16x8_shuffle(l, h, 1, 3, 5, 7, 9, 11, 13, 15)};
}
template <size_t N>
HWY_API Vec128<int16_t, N> MulHigh(const Vec128<int16_t, N> a,
const Vec128<int16_t, N> b) {
// TODO(eustas): replace, when implemented in WASM.
const auto al = wasm_i32x4_extend_low_i16x8(a.raw);
const auto ah = wasm_i32x4_extend_high_i16x8(a.raw);
const auto bl = wasm_i32x4_extend_low_i16x8(b.raw);
const auto bh = wasm_i32x4_extend_high_i16x8(b.raw);
const auto l = wasm_i32x4_mul(al, bl);
const auto h = wasm_i32x4_mul(ah, bh);
// TODO(eustas): shift-right + narrow?
return Vec128<int16_t, N>{
wasm_i16x8_shuffle(l, h, 1, 3, 5, 7, 9, 11, 13, 15)};
}
// Multiplies even lanes (0, 2 ..) and returns the double-width result.
template <size_t N>
HWY_API Vec128<int64_t, (N + 1) / 2> MulEven(const Vec128<int32_t, N> a,
const Vec128<int32_t, N> b) {
// TODO(eustas): replace, when implemented in WASM.
const auto kEvenMask = wasm_i32x4_make(-1, 0, -1, 0);
const auto ae = wasm_v128_and(a.raw, kEvenMask);
const auto be = wasm_v128_and(b.raw, kEvenMask);
return Vec128<int64_t, (N + 1) / 2>{wasm_i64x2_mul(ae, be)};
}
template <size_t N>
HWY_API Vec128<uint64_t, (N + 1) / 2> MulEven(const Vec128<uint32_t, N> a,
const Vec128<uint32_t, N> b) {
// TODO(eustas): replace, when implemented in WASM.
const auto kEvenMask = wasm_i32x4_make(-1, 0, -1, 0);
const auto ae = wasm_v128_and(a.raw, kEvenMask);
const auto be = wasm_v128_and(b.raw, kEvenMask);
return Vec128<uint64_t, (N + 1) / 2>{wasm_i64x2_mul(ae, be)};
}
// ------------------------------ Negate
template <typename T, size_t N, HWY_IF_FLOAT(T)>
HWY_API Vec128<T, N> Neg(const Vec128<T, N> v) {
return Xor(v, SignBit(DFromV<decltype(v)>()));
}
template <size_t N>
HWY_API Vec128<int8_t, N> Neg(const Vec128<int8_t, N> v) {
return Vec128<int8_t, N>{wasm_i8x16_neg(v.raw)};
}
template <size_t N>
HWY_API Vec128<int16_t, N> Neg(const Vec128<int16_t, N> v) {
return Vec128<int16_t, N>{wasm_i16x8_neg(v.raw)};
}
template <size_t N>
HWY_API Vec128<int32_t, N> Neg(const Vec128<int32_t, N> v) {
return Vec128<int32_t, N>{wasm_i32x4_neg(v.raw)};
}
template <size_t N>
HWY_API Vec128<int64_t, N> Neg(const Vec128<int64_t, N> v) {
return Vec128<int64_t, N>{wasm_i64x2_neg(v.raw)};
}
// ------------------------------ Floating-point mul / div
template <size_t N>
HWY_API Vec128<float, N> operator*(Vec128<float, N> a, Vec128<float, N> b) {
return Vec128<float, N>{wasm_f32x4_mul(a.raw, b.raw)};
}
template <size_t N>
HWY_API Vec128<float, N> operator/(const Vec128<float, N> a,
const Vec128<float, N> b) {
return Vec128<float, N>{wasm_f32x4_div(a.raw, b.raw)};
}
// Approximate reciprocal
template <size_t N>
HWY_API Vec128<float, N> ApproximateReciprocal(const Vec128<float, N> v) {
const Vec128<float, N> one = Vec128<float, N>{wasm_f32x4_splat(1.0f)};
return one / v;
}
// Absolute value of difference.
template <size_t N>
HWY_API Vec128<float, N> AbsDiff(const Vec128<float, N> a,
const Vec128<float, N> b) {
return Abs(a - b);
}
// ------------------------------ Floating-point multiply-add variants
// Returns mul * x + add
template <size_t N>
HWY_API Vec128<float, N> MulAdd(const Vec128<float, N> mul,
const Vec128<float, N> x,
const Vec128<float, N> add) {
// TODO(eustas): replace, when implemented in WASM.
// TODO(eustas): is it wasm_f32x4_qfma?
return mul * x + add;
}
// Returns add - mul * x
template <size_t N>
HWY_API Vec128<float, N> NegMulAdd(const Vec128<float, N> mul,
const Vec128<float, N> x,
const Vec128<float, N> add) {
// TODO(eustas): replace, when implemented in WASM.
return add - mul * x;
}
// Returns mul * x - sub
template <size_t N>
HWY_API Vec128<float, N> MulSub(const Vec128<float, N> mul,
const Vec128<float, N> x,
const Vec128<float, N> sub) {
// TODO(eustas): replace, when implemented in WASM.
// TODO(eustas): is it wasm_f32x4_qfms?
return mul * x - sub;
}
// Returns -mul * x - sub
template <size_t N>
HWY_API Vec128<float, N> NegMulSub(const Vec128<float, N> mul,
const Vec128<float, N> x,
const Vec128<float, N> sub) {
// TODO(eustas): replace, when implemented in WASM.
return Neg(mul) * x - sub;
}
// ------------------------------ Floating-point square root
// Full precision square root
template <size_t N>
HWY_API Vec128<float, N> Sqrt(const Vec128<float, N> v) {
return Vec128<float, N>{wasm_f32x4_sqrt(v.raw)};
}
// Approximate reciprocal square root
template <size_t N>
HWY_API Vec128<float, N> ApproximateReciprocalSqrt(const Vec128<float, N> v) {
// TODO(eustas): find cheaper a way to calculate this.
const Vec128<float, N> one = Vec128<float, N>{wasm_f32x4_splat(1.0f)};
return one / Sqrt(v);
}
// ------------------------------ Floating-point rounding
// Toward nearest integer, ties to even
template <size_t N>
HWY_API Vec128<float, N> Round(const Vec128<float, N> v) {
return Vec128<float, N>{wasm_f32x4_nearest(v.raw)};
}
// Toward zero, aka truncate
template <size_t N>
HWY_API Vec128<float, N> Trunc(const Vec128<float, N> v) {
return Vec128<float, N>{wasm_f32x4_trunc(v.raw)};
}
// Toward +infinity, aka ceiling
template <size_t N>
HWY_API Vec128<float, N> Ceil(const Vec128<float, N> v) {
return Vec128<float, N>{wasm_f32x4_ceil(v.raw)};
}
// Toward -infinity, aka floor
template <size_t N>
HWY_API Vec128<float, N> Floor(const Vec128<float, N> v) {
return Vec128<float, N>{wasm_f32x4_floor(v.raw)};
}
// ================================================== COMPARE
// Comparisons fill a lane with 1-bits if the condition is true, else 0.
template <typename TFrom, typename TTo, size_t N>
HWY_API Mask128<TTo, N> RebindMask(Simd<TTo, N, 0> /*tag*/,
Mask128<TFrom, N> m) {
static_assert(sizeof(TFrom) == sizeof(TTo), "Must have same size");
return Mask128<TTo, N>{m.raw};
}
template <typename T, size_t N>
HWY_API Mask128<T, N> TestBit(Vec128<T, N> v, Vec128<T, N> bit) {
static_assert(!hwy::IsFloat<T>(), "Only integer vectors supported");
return (v & bit) == bit;
}
// ------------------------------ Equality
// Unsigned
template <size_t N>
HWY_API Mask128<uint8_t, N> operator==(const Vec128<uint8_t, N> a,
const Vec128<uint8_t, N> b) {
return Mask128<uint8_t, N>{wasm_i8x16_eq(a.raw, b.raw)};
}
template <size_t N>
HWY_API Mask128<uint16_t, N> operator==(const Vec128<uint16_t, N> a,
const Vec128<uint16_t, N> b) {
return Mask128<uint16_t, N>{wasm_i16x8_eq(a.raw, b.raw)};
}
template <size_t N>
HWY_API Mask128<uint32_t, N> operator==(const Vec128<uint32_t, N> a,
const Vec128<uint32_t, N> b) {
return Mask128<uint32_t, N>{wasm_i32x4_eq(a.raw, b.raw)};
}
template <size_t N>
HWY_API Mask128<uint64_t, N> operator==(const Vec128<uint64_t, N> a,
const Vec128<uint64_t, N> b) {
return Mask128<uint64_t, N>{wasm_i64x2_eq(a.raw, b.raw)};
}
// Signed
template <size_t N>
HWY_API Mask128<int8_t, N> operator==(const Vec128<int8_t, N> a,
const Vec128<int8_t, N> b) {
return Mask128<int8_t, N>{wasm_i8x16_eq(a.raw, b.raw)};
}
template <size_t N>
HWY_API Mask128<int16_t, N> operator==(Vec128<int16_t, N> a,
Vec128<int16_t, N> b) {
return Mask128<int16_t, N>{wasm_i16x8_eq(a.raw, b.raw)};
}
template <size_t N>
HWY_API Mask128<int32_t, N> operator==(const Vec128<int32_t, N> a,
const Vec128<int32_t, N> b) {
return Mask128<int32_t, N>{wasm_i32x4_eq(a.raw, b.raw)};
}
template <size_t N>
HWY_API Mask128<int64_t, N> operator==(const Vec128<int64_t, N> a,
const Vec128<int64_t, N> b) {
return Mask128<int64_t, N>{wasm_i64x2_eq(a.raw, b.raw)};
}
// Float
template <size_t N>
HWY_API Mask128<float, N> operator==(const Vec128<float, N> a,
const Vec128<float, N> b) {
return Mask128<float, N>{wasm_f32x4_eq(a.raw, b.raw)};
}
// ------------------------------ Inequality
// Unsigned
template <size_t N>
HWY_API Mask128<uint8_t, N> operator!=(const Vec128<uint8_t, N> a,
const Vec128<uint8_t, N> b) {
return Mask128<uint8_t, N>{wasm_i8x16_ne(a.raw, b.raw)};
}
template <size_t N>
HWY_API Mask128<uint16_t, N> operator!=(const Vec128<uint16_t, N> a,
const Vec128<uint16_t, N> b) {
return Mask128<uint16_t, N>{wasm_i16x8_ne(a.raw, b.raw)};
}
template <size_t N>
HWY_API Mask128<uint32_t, N> operator!=(const Vec128<uint32_t, N> a,
const Vec128<uint32_t, N> b) {
return Mask128<uint32_t, N>{wasm_i32x4_ne(a.raw, b.raw)};
}
template <size_t N>
HWY_API Mask128<uint64_t, N> operator!=(const Vec128<uint64_t, N> a,
const Vec128<uint64_t, N> b) {
return Mask128<uint64_t, N>{wasm_i64x2_ne(a.raw, b.raw)};
}
// Signed
template <size_t N>
HWY_API Mask128<int8_t, N> operator!=(const Vec128<int8_t, N> a,
const Vec128<int8_t, N> b) {
return Mask128<int8_t, N>{wasm_i8x16_ne(a.raw, b.raw)};
}
template <size_t N>
HWY_API Mask128<int16_t, N> operator!=(const Vec128<int16_t, N> a,
const Vec128<int16_t, N> b) {
return Mask128<int16_t, N>{wasm_i16x8_ne(a.raw, b.raw)};
}
template <size_t N>
HWY_API Mask128<int32_t, N> operator!=(const Vec128<int32_t, N> a,
const Vec128<int32_t, N> b) {
return Mask128<int32_t, N>{wasm_i32x4_ne(a.raw, b.raw)};
}
template <size_t N>
HWY_API Mask128<int64_t, N> operator!=(const Vec128<int64_t, N> a,
const Vec128<int64_t, N> b) {
return Mask128<int64_t, N>{wasm_i64x2_ne(a.raw, b.raw)};
}
// Float
template <size_t N>
HWY_API Mask128<float, N> operator!=(const Vec128<float, N> a,
const Vec128<float, N> b) {
return Mask128<float, N>{wasm_f32x4_ne(a.raw, b.raw)};
}
// ------------------------------ Strict inequality
template <size_t N>
HWY_API Mask128<int8_t, N> operator>(const Vec128<int8_t, N> a,
const Vec128<int8_t, N> b) {
return Mask128<int8_t, N>{wasm_i8x16_gt(a.raw, b.raw)};
}
template <size_t N>
HWY_API Mask128<int16_t, N> operator>(const Vec128<int16_t, N> a,
const Vec128<int16_t, N> b) {
return Mask128<int16_t, N>{wasm_i16x8_gt(a.raw, b.raw)};
}
template <size_t N>
HWY_API Mask128<int32_t, N> operator>(const Vec128<int32_t, N> a,
const Vec128<int32_t, N> b) {
return Mask128<int32_t, N>{wasm_i32x4_gt(a.raw, b.raw)};
}
template <size_t N>
HWY_API Mask128<int64_t, N> operator>(const Vec128<int64_t, N> a,
const Vec128<int64_t, N> b) {
return Mask128<int64_t, N>{wasm_i64x2_gt(a.raw, b.raw)};
}
template <size_t N>
HWY_API Mask128<uint8_t, N> operator>(const Vec128<uint8_t, N> a,
const Vec128<uint8_t, N> b) {
return Mask128<uint8_t, N>{wasm_u8x16_gt(a.raw, b.raw)};
}
template <size_t N>
HWY_API Mask128<uint16_t, N> operator>(const Vec128<uint16_t, N> a,
const Vec128<uint16_t, N> b) {
return Mask128<uint16_t, N>{wasm_u16x8_gt(a.raw, b.raw)};
}
template <size_t N>
HWY_API Mask128<uint32_t, N> operator>(const Vec128<uint32_t, N> a,
const Vec128<uint32_t, N> b) {
return Mask128<uint32_t, N>{wasm_u32x4_gt(a.raw, b.raw)};
}
template <size_t N>
HWY_API Mask128<uint64_t, N> operator>(const Vec128<uint64_t, N> a,
const Vec128<uint64_t, N> b) {
const DFromV<decltype(a)> d;
const Repartition<uint32_t, decltype(d)> d32;
const auto a32 = BitCast(d32, a);
const auto b32 = BitCast(d32, b);
// If the upper halves are not equal, this is the answer.
const auto m_gt = a32 > b32;
// Otherwise, the lower half decides.
const auto m_eq = a32 == b32;
const auto lo_in_hi = wasm_i32x4_shuffle(m_gt.raw, m_gt.raw, 0, 0, 2, 2);
const auto lo_gt = And(m_eq, MaskFromVec(VFromD<decltype(d32)>{lo_in_hi}));
const auto gt = Or(lo_gt, m_gt);
// Copy result in upper 32 bits to lower 32 bits.
return Mask128<uint64_t, N>{wasm_i32x4_shuffle(gt.raw, gt.raw, 1, 1, 3, 3)};
}
template <size_t N>
HWY_API Mask128<float, N> operator>(const Vec128<float, N> a,
const Vec128<float, N> b) {
return Mask128<float, N>{wasm_f32x4_gt(a.raw, b.raw)};
}
template <typename T, size_t N>
HWY_API Mask128<T, N> operator<(const Vec128<T, N> a, const Vec128<T, N> b) {
return operator>(b, a);
}
// ------------------------------ Weak inequality
// Float <= >=
template <size_t N>
HWY_API Mask128<float, N> operator<=(const Vec128<float, N> a,
const Vec128<float, N> b) {
return Mask128<float, N>{wasm_f32x4_le(a.raw, b.raw)};
}
template <size_t N>
HWY_API Mask128<float, N> operator>=(const Vec128<float, N> a,
const Vec128<float, N> b) {
return Mask128<float, N>{wasm_f32x4_ge(a.raw, b.raw)};
}
// ------------------------------ FirstN (Iota, Lt)
template <typename T, size_t N>
HWY_API Mask128<T, N> FirstN(const Simd<T, N, 0> d, size_t num) {
const RebindToSigned<decltype(d)> di; // Signed comparisons may be cheaper.
return RebindMask(d, Iota(di, 0) < Set(di, static_cast<MakeSigned<T>>(num)));
}
// ================================================== LOGICAL
// ------------------------------ Not
template <typename T, size_t N>
HWY_API Vec128<T, N> Not(Vec128<T, N> v) {
return Vec128<T, N>{wasm_v128_not(v.raw)};
}
// ------------------------------ And
template <typename T, size_t N>
HWY_API Vec128<T, N> And(Vec128<T, N> a, Vec128<T, N> b) {
return Vec128<T, N>{wasm_v128_and(a.raw, b.raw)};
}
// ------------------------------ AndNot
// Returns ~not_mask & mask.
template <typename T, size_t N>
HWY_API Vec128<T, N> AndNot(Vec128<T, N> not_mask, Vec128<T, N> mask) {
return Vec128<T, N>{wasm_v128_andnot(mask.raw, not_mask.raw)};
}
// ------------------------------ Or
template <typename T, size_t N>
HWY_API Vec128<T, N> Or(Vec128<T, N> a, Vec128<T, N> b) {
return Vec128<T, N>{wasm_v128_or(a.raw, b.raw)};
}
// ------------------------------ Xor
template <typename T, size_t N>
HWY_API Vec128<T, N> Xor(Vec128<T, N> a, Vec128<T, N> b) {
return Vec128<T, N>{wasm_v128_xor(a.raw, b.raw)};
}
// ------------------------------ OrAnd
template <typename T, size_t N>
HWY_API Vec128<T, N> OrAnd(Vec128<T, N> o, Vec128<T, N> a1, Vec128<T, N> a2) {
return Or(o, And(a1, a2));
}
// ------------------------------ IfVecThenElse
template <typename T, size_t N>
HWY_API Vec128<T, N> IfVecThenElse(Vec128<T, N> mask, Vec128<T, N> yes,
Vec128<T, N> no) {
return IfThenElse(MaskFromVec(mask), yes, no);
}
// ------------------------------ Operator overloads (internal-only if float)
template <typename T, size_t N>
HWY_API Vec128<T, N> operator&(const Vec128<T, N> a, const Vec128<T, N> b) {
return And(a, b);
}
template <typename T, size_t N>
HWY_API Vec128<T, N> operator|(const Vec128<T, N> a, const Vec128<T, N> b) {
return Or(a, b);
}
template <typename T, size_t N>
HWY_API Vec128<T, N> operator^(const Vec128<T, N> a, const Vec128<T, N> b) {
return Xor(a, b);
}
// ------------------------------ CopySign
template <typename T, size_t N>
HWY_API Vec128<T, N> CopySign(const Vec128<T, N> magn,
const Vec128<T, N> sign) {
static_assert(IsFloat<T>(), "Only makes sense for floating-point");
const auto msb = SignBit(DFromV<decltype(magn)>());
return Or(AndNot(msb, magn), And(msb, sign));
}
template <typename T, size_t N>
HWY_API Vec128<T, N> CopySignToAbs(const Vec128<T, N> abs,
const Vec128<T, N> sign) {
static_assert(IsFloat<T>(), "Only makes sense for floating-point");
return Or(abs, And(SignBit(DFromV<decltype(abs)>()), sign));
}
// ------------------------------ BroadcastSignBit (compare)
template <typename T, size_t N, HWY_IF_NOT_LANE_SIZE(T, 1)>
HWY_API Vec128<T, N> BroadcastSignBit(const Vec128<T, N> v) {
return ShiftRight<sizeof(T) * 8 - 1>(v);
}
template <size_t N>
HWY_API Vec128<int8_t, N> BroadcastSignBit(const Vec128<int8_t, N> v) {
const DFromV<decltype(v)> d;
return VecFromMask(d, v < Zero(d));
}
// ------------------------------ Mask
// Mask and Vec are the same (true = FF..FF).
template <typename T, size_t N>
HWY_API Mask128<T, N> MaskFromVec(const Vec128<T, N> v) {
return Mask128<T, N>{v.raw};
}
template <typename T, size_t N>
HWY_API Vec128<T, N> VecFromMask(Simd<T, N, 0> /* tag */, Mask128<T, N> v) {
return Vec128<T, N>{v.raw};
}
// mask ? yes : no
template <typename T, size_t N>
HWY_API Vec128<T, N> IfThenElse(Mask128<T, N> mask, Vec128<T, N> yes,
Vec128<T, N> no) {
return Vec128<T, N>{wasm_v128_bitselect(yes.raw, no.raw, mask.raw)};
}
// mask ? yes : 0
template <typename T, size_t N>
HWY_API Vec128<T, N> IfThenElseZero(Mask128<T, N> mask, Vec128<T, N> yes) {
return yes & VecFromMask(DFromV<decltype(yes)>(), mask);
}
// mask ? 0 : no
template <typename T, size_t N>
HWY_API Vec128<T, N> IfThenZeroElse(Mask128<T, N> mask, Vec128<T, N> no) {
return AndNot(VecFromMask(DFromV<decltype(no)>(), mask), no);
}
template <typename T, size_t N>
HWY_API Vec128<T, N> IfNegativeThenElse(Vec128<T, N> v, Vec128<T, N> yes,
Vec128<T, N> no) {
static_assert(IsSigned<T>(), "Only works for signed/float");
const DFromV<decltype(v)> d;
const RebindToSigned<decltype(d)> di;
v = BitCast(d, BroadcastSignBit(BitCast(di, v)));
return IfThenElse(MaskFromVec(v), yes, no);
}
template <typename T, size_t N, HWY_IF_FLOAT(T)>
HWY_API Vec128<T, N> ZeroIfNegative(Vec128<T, N> v) {
const DFromV<decltype(v)> d;
const auto zero = Zero(d);
return IfThenElse(Mask128<T, N>{(v > zero).raw}, v, zero);
}
// ------------------------------ Mask logical
template <typename T, size_t N>
HWY_API Mask128<T, N> Not(const Mask128<T, N> m) {
return MaskFromVec(Not(VecFromMask(Simd<T, N, 0>(), m)));
}
template <typename T, size_t N>
HWY_API Mask128<T, N> And(const Mask128<T, N> a, Mask128<T, N> b) {
const Simd<T, N, 0> d;
return MaskFromVec(And(VecFromMask(d, a), VecFromMask(d, b)));
}
template <typename T, size_t N>
HWY_API Mask128<T, N> AndNot(const Mask128<T, N> a, Mask128<T, N> b) {
const Simd<T, N, 0> d;
return MaskFromVec(AndNot(VecFromMask(d, a), VecFromMask(d, b)));
}
template <typename T, size_t N>
HWY_API Mask128<T, N> Or(const Mask128<T, N> a, Mask128<T, N> b) {
const Simd<T, N, 0> d;
return MaskFromVec(Or(VecFromMask(d, a), VecFromMask(d, b)));
}
template <typename T, size_t N>
HWY_API Mask128<T, N> Xor(const Mask128<T, N> a, Mask128<T, N> b) {
const Simd<T, N, 0> d;
return MaskFromVec(Xor(VecFromMask(d, a), VecFromMask(d, b)));
}
// ------------------------------ Shl (BroadcastSignBit, IfThenElse)
// The x86 multiply-by-Pow2() trick will not work because WASM saturates
// float->int correctly to 2^31-1 (not 2^31). Because WASM's shifts take a
// scalar count operand, per-lane shift instructions would require extract_lane
// for each lane, and hoping that shuffle is correctly mapped to a native
// instruction. Using non-vector shifts would incur a store-load forwarding
// stall when loading the result vector. We instead test bits of the shift
// count to "predicate" a shift of the entire vector by a constant.
template <typename T, size_t N, HWY_IF_LANE_SIZE(T, 2)>
HWY_API Vec128<T, N> operator<<(Vec128<T, N> v, const Vec128<T, N> bits) {
const DFromV<decltype(v)> d;
Mask128<T, N> mask;
// Need a signed type for BroadcastSignBit.
auto test = BitCast(RebindToSigned<decltype(d)>(), bits);
// Move the highest valid bit of the shift count into the sign bit.
test = ShiftLeft<12>(test);
mask = RebindMask(d, MaskFromVec(BroadcastSignBit(test)));
test = ShiftLeft<1>(test); // next bit (descending order)
v = IfThenElse(mask, ShiftLeft<8>(v), v);
mask = RebindMask(d, MaskFromVec(BroadcastSignBit(test)));
test = ShiftLeft<1>(test); // next bit (descending order)
v = IfThenElse(mask, ShiftLeft<4>(v), v);
mask = RebindMask(d, MaskFromVec(BroadcastSignBit(test)));
test = ShiftLeft<1>(test); // next bit (descending order)
v = IfThenElse(mask, ShiftLeft<2>(v), v);
mask = RebindMask(d, MaskFromVec(BroadcastSignBit(test)));
return IfThenElse(mask, ShiftLeft<1>(v), v);
}
template <typename T, size_t N, HWY_IF_LANE_SIZE(T, 4)>
HWY_API Vec128<T, N> operator<<(Vec128<T, N> v, const Vec128<T, N> bits) {
const DFromV<decltype(v)> d;
Mask128<T, N> mask;
// Need a signed type for BroadcastSignBit.
auto test = BitCast(RebindToSigned<decltype(d)>(), bits);
// Move the highest valid bit of the shift count into the sign bit.
test = ShiftLeft<27>(test);
mask = RebindMask(d, MaskFromVec(BroadcastSignBit(test)));
test = ShiftLeft<1>(test); // next bit (descending order)
v = IfThenElse(mask, ShiftLeft<16>(v), v);
mask = RebindMask(d, MaskFromVec(BroadcastSignBit(test)));
test = ShiftLeft<1>(test); // next bit (descending order)
v = IfThenElse(mask, ShiftLeft<8>(v), v);
mask = RebindMask(d, MaskFromVec(BroadcastSignBit(test)));
test = ShiftLeft<1>(test); // next bit (descending order)
v = IfThenElse(mask, ShiftLeft<4>(v), v);
mask = RebindMask(d, MaskFromVec(BroadcastSignBit(test)));
test = ShiftLeft<1>(test); // next bit (descending order)
v = IfThenElse(mask, ShiftLeft<2>(v), v);
mask = RebindMask(d, MaskFromVec(BroadcastSignBit(test)));
return IfThenElse(mask, ShiftLeft<1>(v), v);
}
template <typename T, size_t N, HWY_IF_LANE_SIZE(T, 8)>
HWY_API Vec128<T, N> operator<<(Vec128<T, N> v, const Vec128<T, N> bits) {
const DFromV<decltype(v)> d;
alignas(16) T lanes[2];
alignas(16) T bits_lanes[2];
Store(v, d, lanes);
Store(bits, d, bits_lanes);
lanes[0] <<= bits_lanes[0];
lanes[1] <<= bits_lanes[1];
return Load(d, lanes);
}
// ------------------------------ Shr (BroadcastSignBit, IfThenElse)
template <typename T, size_t N, HWY_IF_LANE_SIZE(T, 2)>
HWY_API Vec128<T, N> operator>>(Vec128<T, N> v, const Vec128<T, N> bits) {
const DFromV<decltype(v)> d;
Mask128<T, N> mask;
// Need a signed type for BroadcastSignBit.
auto test = BitCast(RebindToSigned<decltype(d)>(), bits);
// Move the highest valid bit of the shift count into the sign bit.
test = ShiftLeft<12>(test);
mask = RebindMask(d, MaskFromVec(BroadcastSignBit(test)));
test = ShiftLeft<1>(test); // next bit (descending order)
v = IfThenElse(mask, ShiftRight<8>(v), v);
mask = RebindMask(d, MaskFromVec(BroadcastSignBit(test)));
test = ShiftLeft<1>(test); // next bit (descending order)
v = IfThenElse(mask, ShiftRight<4>(v), v);
mask = RebindMask(d, MaskFromVec(BroadcastSignBit(test)));
test = ShiftLeft<1>(test); // next bit (descending order)
v = IfThenElse(mask, ShiftRight<2>(v), v);
mask = RebindMask(d, MaskFromVec(BroadcastSignBit(test)));
return IfThenElse(mask, ShiftRight<1>(v), v);
}
template <typename T, size_t N, HWY_IF_LANE_SIZE(T, 4)>
HWY_API Vec128<T, N> operator>>(Vec128<T, N> v, const Vec128<T, N> bits) {
const DFromV<decltype(v)> d;
Mask128<T, N> mask;
// Need a signed type for BroadcastSignBit.
auto test = BitCast(RebindToSigned<decltype(d)>(), bits);
// Move the highest valid bit of the shift count into the sign bit.
test = ShiftLeft<27>(test);
mask = RebindMask(d, MaskFromVec(BroadcastSignBit(test)));
test = ShiftLeft<1>(test); // next bit (descending order)
v = IfThenElse(mask, ShiftRight<16>(v), v);
mask = RebindMask(d, MaskFromVec(BroadcastSignBit(test)));
test = ShiftLeft<1>(test); // next bit (descending order)
v = IfThenElse(mask, ShiftRight<8>(v), v);
mask = RebindMask(d, MaskFromVec(BroadcastSignBit(test)));
test = ShiftLeft<1>(test); // next bit (descending order)
v = IfThenElse(mask, ShiftRight<4>(v), v);
mask = RebindMask(d, MaskFromVec(BroadcastSignBit(test)));
test = ShiftLeft<1>(test); // next bit (descending order)
v = IfThenElse(mask, ShiftRight<2>(v), v);
mask = RebindMask(d, MaskFromVec(BroadcastSignBit(test)));
return IfThenElse(mask, ShiftRight<1>(v), v);
}
// ================================================== MEMORY
// ------------------------------ Load
template <typename T>
HWY_API Vec128<T> Load(Full128<T> /* tag */, const T* HWY_RESTRICT aligned) {
return Vec128<T>{wasm_v128_load(aligned)};
}
template <typename T, size_t N>
HWY_API Vec128<T, N> MaskedLoad(Mask128<T, N> m, Simd<T, N, 0> d,
const T* HWY_RESTRICT aligned) {
return IfThenElseZero(m, Load(d, aligned));
}
// Partial load.
template <typename T, size_t N, HWY_IF_LE64(T, N)>
HWY_API Vec128<T, N> Load(Simd<T, N, 0> /* tag */, const T* HWY_RESTRICT p) {
Vec128<T, N> v;
CopyBytes<sizeof(T) * N>(p, &v);
return v;
}
// LoadU == Load.
template <typename T, size_t N>
HWY_API Vec128<T, N> LoadU(Simd<T, N, 0> d, const T* HWY_RESTRICT p) {
return Load(d, p);
}
// 128-bit SIMD => nothing to duplicate, same as an unaligned load.
template <typename T, size_t N, HWY_IF_LE128(T, N)>
HWY_API Vec128<T, N> LoadDup128(Simd<T, N, 0> d, const T* HWY_RESTRICT p) {
return Load(d, p);
}
// ------------------------------ Store
template <typename T>
HWY_API void Store(Vec128<T> v, Full128<T> /* tag */, T* HWY_RESTRICT aligned) {
wasm_v128_store(aligned, v.raw);
}
// Partial store.
template <typename T, size_t N, HWY_IF_LE64(T, N)>
HWY_API void Store(Vec128<T, N> v, Simd<T, N, 0> /* tag */, T* HWY_RESTRICT p) {
CopyBytes<sizeof(T) * N>(&v, p);
}
HWY_API void Store(const Vec128<float, 1> v, Simd<float, 1, 0> /* tag */,
float* HWY_RESTRICT p) {
*p = wasm_f32x4_extract_lane(v.raw, 0);
}
// StoreU == Store.
template <typename T, size_t N>
HWY_API void StoreU(Vec128<T, N> v, Simd<T, N, 0> d, T* HWY_RESTRICT p) {
Store(v, d, p);
}
// ------------------------------ Non-temporal stores
// Same as aligned stores on non-x86.
template <typename T, size_t N>
HWY_API void Stream(Vec128<T, N> v, Simd<T, N, 0> /* tag */,
T* HWY_RESTRICT aligned) {
wasm_v128_store(aligned, v.raw);
}
// ------------------------------ Scatter (Store)
template <typename T, size_t N, typename Offset, HWY_IF_LE128(T, N)>
HWY_API void ScatterOffset(Vec128<T, N> v, Simd<T, N, 0> d,
T* HWY_RESTRICT base,
const Vec128<Offset, N> offset) {
static_assert(sizeof(T) == sizeof(Offset), "Must match for portability");
alignas(16) T lanes[N];
Store(v, d, lanes);
alignas(16) Offset offset_lanes[N];
Store(offset, Rebind<Offset, decltype(d)>(), offset_lanes);
uint8_t* base_bytes = reinterpret_cast<uint8_t*>(base);
for (size_t i = 0; i < N; ++i) {
CopyBytes<sizeof(T)>(&lanes[i], base_bytes + offset_lanes[i]);
}
}
template <typename T, size_t N, typename Index, HWY_IF_LE128(T, N)>
HWY_API void ScatterIndex(Vec128<T, N> v, Simd<T, N, 0> d, T* HWY_RESTRICT base,
const Vec128<Index, N> index) {
static_assert(sizeof(T) == sizeof(Index), "Must match for portability");
alignas(16) T lanes[N];
Store(v, d, lanes);
alignas(16) Index index_lanes[N];
Store(index, Rebind<Index, decltype(d)>(), index_lanes);
for (size_t i = 0; i < N; ++i) {
base[index_lanes[i]] = lanes[i];
}
}
// ------------------------------ Gather (Load/Store)
template <typename T, size_t N, typename Offset>
HWY_API Vec128<T, N> GatherOffset(const Simd<T, N, 0> d,
const T* HWY_RESTRICT base,
const Vec128<Offset, N> offset) {
static_assert(sizeof(T) == sizeof(Offset), "Must match for portability");
alignas(16) Offset offset_lanes[N];
Store(offset, Rebind<Offset, decltype(d)>(), offset_lanes);
alignas(16) T lanes[N];
const uint8_t* base_bytes = reinterpret_cast<const uint8_t*>(base);
for (size_t i = 0; i < N; ++i) {
CopyBytes<sizeof(T)>(base_bytes + offset_lanes[i], &lanes[i]);
}
return Load(d, lanes);
}
template <typename T, size_t N, typename Index>
HWY_API Vec128<T, N> GatherIndex(const Simd<T, N, 0> d,
const T* HWY_RESTRICT base,
const Vec128<Index, N> index) {
static_assert(sizeof(T) == sizeof(Index), "Must match for portability");
alignas(16) Index index_lanes[N];
Store(index, Rebind<Index, decltype(d)>(), index_lanes);
alignas(16) T lanes[N];
for (size_t i = 0; i < N; ++i) {
lanes[i] = base[index_lanes[i]];
}
return Load(d, lanes);
}
// ================================================== SWIZZLE
// ------------------------------ Extract lane
// Gets the single value stored in a vector/part.
template <size_t N>
HWY_API uint8_t GetLane(const Vec128<uint8_t, N> v) {
return static_cast<uint8_t>(wasm_i8x16_extract_lane(v.raw, 0));
}
template <size_t N>
HWY_API int8_t GetLane(const Vec128<int8_t, N> v) {
return static_cast<int8_t>(wasm_i8x16_extract_lane(v.raw, 0));
}
template <size_t N>
HWY_API uint16_t GetLane(const Vec128<uint16_t, N> v) {
return static_cast<uint16_t>(wasm_i16x8_extract_lane(v.raw, 0));
}
template <size_t N>
HWY_API int16_t GetLane(const Vec128<int16_t, N> v) {
return static_cast<int16_t>(wasm_i16x8_extract_lane(v.raw, 0));
}
template <size_t N>
HWY_API uint32_t GetLane(const Vec128<uint32_t, N> v) {
return static_cast<uint32_t>(wasm_i32x4_extract_lane(v.raw, 0));
}
template <size_t N>
HWY_API int32_t GetLane(const Vec128<int32_t, N> v) {
return static_cast<int32_t>(wasm_i32x4_extract_lane(v.raw, 0));
}
template <size_t N>
HWY_API uint64_t GetLane(const Vec128<uint64_t, N> v) {
return static_cast<uint64_t>(wasm_i64x2_extract_lane(v.raw, 0));
}
template <size_t N>
HWY_API int64_t GetLane(const Vec128<int64_t, N> v) {
return static_cast<int64_t>(wasm_i64x2_extract_lane(v.raw, 0));
}
template <size_t N>
HWY_API float GetLane(const Vec128<float, N> v) {
return wasm_f32x4_extract_lane(v.raw, 0);
}
// ------------------------------ LowerHalf
template <typename T, size_t N>
HWY_API Vec128<T, N / 2> LowerHalf(Simd<T, N / 2, 0> /* tag */,
Vec128<T, N> v) {
return Vec128<T, N / 2>{v.raw};
}
template <typename T, size_t N>
HWY_API Vec128<T, N / 2> LowerHalf(Vec128<T, N> v) {
return LowerHalf(Simd<T, N / 2, 0>(), v);
}
// ------------------------------ ShiftLeftBytes
// 0x01..0F, kBytes = 1 => 0x02..0F00
template <int kBytes, typename T, size_t N>
HWY_API Vec128<T, N> ShiftLeftBytes(Simd<T, N, 0> /* tag */, Vec128<T, N> v) {
static_assert(0 <= kBytes && kBytes <= 16, "Invalid kBytes");
const __i8x16 zero = wasm_i8x16_splat(0);
switch (kBytes) {
case 0:
return v;
case 1:
return Vec128<T, N>{wasm_i8x16_shuffle(v.raw, zero, 16, 0, 1, 2, 3, 4, 5,
6, 7, 8, 9, 10, 11, 12, 13, 14)};
case 2:
return Vec128<T, N>{wasm_i8x16_shuffle(v.raw, zero, 16, 16, 0, 1, 2, 3, 4,
5, 6, 7, 8, 9, 10, 11, 12, 13)};
case 3:
return Vec128<T, N>{wasm_i8x16_shuffle(v.raw, zero, 16, 16, 16, 0, 1, 2,
3, 4, 5, 6, 7, 8, 9, 10, 11, 12)};
case 4:
return Vec128<T, N>{wasm_i8x16_shuffle(v.raw, zero, 16, 16, 16, 16, 0, 1,
2, 3, 4, 5, 6, 7, 8, 9, 10, 11)};
case 5:
return Vec128<T, N>{wasm_i8x16_shuffle(v.raw, zero, 16, 16, 16, 16, 16, 0,
1, 2, 3, 4, 5, 6, 7, 8, 9, 10)};
case 6:
return Vec128<T, N>{wasm_i8x16_shuffle(v.raw, zero, 16, 16, 16, 16, 16,
16, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9)};
case 7:
return Vec128<T, N>{wasm_i8x16_shuffle(
v.raw, zero, 16, 16, 16, 16, 16, 16, 16, 0, 1, 2, 3, 4, 5, 6, 7, 8)};
case 8:
return Vec128<T, N>{wasm_i8x16_shuffle(
v.raw, zero, 16, 16, 16, 16, 16, 16, 16, 16, 0, 1, 2, 3, 4, 5, 6, 7)};
case 9:
return Vec128<T, N>{wasm_i8x16_shuffle(v.raw, zero, 16, 16, 16, 16, 16,
16, 16, 16, 16, 0, 1, 2, 3, 4, 5,
6)};
case 10:
return Vec128<T, N>{wasm_i8x16_shuffle(v.raw, zero, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 0, 1, 2, 3, 4,
5)};
case 11:
return Vec128<T, N>{wasm_i8x16_shuffle(v.raw, zero, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 0, 1, 2, 3,
4)};
case 12:
return Vec128<T, N>{wasm_i8x16_shuffle(v.raw, zero, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 0, 1,
2, 3)};
case 13:
return Vec128<T, N>{wasm_i8x16_shuffle(v.raw, zero, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16, 0,
1, 2)};
case 14:
return Vec128<T, N>{wasm_i8x16_shuffle(v.raw, zero, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16, 16,
0, 1)};
case 15:
return Vec128<T, N>{wasm_i8x16_shuffle(v.raw, zero, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16, 16,
16, 0)};
}
return Vec128<T, N>{zero};
}
template <int kBytes, typename T, size_t N>
HWY_API Vec128<T, N> ShiftLeftBytes(Vec128<T, N> v) {
return ShiftLeftBytes<kBytes>(Simd<T, N, 0>(), v);
}
// ------------------------------ ShiftLeftLanes
template <int kLanes, typename T, size_t N>
HWY_API Vec128<T, N> ShiftLeftLanes(Simd<T, N, 0> d, const Vec128<T, N> v) {
const Repartition<uint8_t, decltype(d)> d8;
return BitCast(d, ShiftLeftBytes<kLanes * sizeof(T)>(BitCast(d8, v)));
}
template <int kLanes, typename T, size_t N>
HWY_API Vec128<T, N> ShiftLeftLanes(const Vec128<T, N> v) {
return ShiftLeftLanes<kLanes>(DFromV<decltype(v)>(), v);
}
// ------------------------------ ShiftRightBytes
namespace detail {
// Helper function allows zeroing invalid lanes in caller.
template <int kBytes, typename T, size_t N>
HWY_API __i8x16 ShrBytes(const Vec128<T, N> v) {
static_assert(0 <= kBytes && kBytes <= 16, "Invalid kBytes");
const __i8x16 zero = wasm_i8x16_splat(0);
switch (kBytes) {
case 0:
return v.raw;
case 1:
return wasm_i8x16_shuffle(v.raw, zero, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16);
case 2:
return wasm_i8x16_shuffle(v.raw, zero, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 15, 16, 16);
case 3:
return wasm_i8x16_shuffle(v.raw, zero, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 15, 16, 16, 16);
case 4:
return wasm_i8x16_shuffle(v.raw, zero, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13,
14, 15, 16, 16, 16, 16);
case 5:
return wasm_i8x16_shuffle(v.raw, zero, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 16, 16, 16, 16);
case 6:
return wasm_i8x16_shuffle(v.raw, zero, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 16, 16, 16, 16, 16);
case 7:
return wasm_i8x16_shuffle(v.raw, zero, 7, 8, 9, 10, 11, 12, 13, 14, 15,
16, 16, 16, 16, 16, 16, 16);
case 8:
return wasm_i8x16_shuffle(v.raw, zero, 8, 9, 10, 11, 12, 13, 14, 15, 16,
16, 16, 16, 16, 16, 16, 16);
case 9:
return wasm_i8x16_shuffle(v.raw, zero, 9, 10, 11, 12, 13, 14, 15, 16, 16,
16, 16, 16, 16, 16, 16, 16);
case 10:
return wasm_i8x16_shuffle(v.raw, zero, 10, 11, 12, 13, 14, 15, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16);
case 11:
return wasm_i8x16_shuffle(v.raw, zero, 11, 12, 13, 14, 15, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16);
case 12:
return wasm_i8x16_shuffle(v.raw, zero, 12, 13, 14, 15, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16);
case 13:
return wasm_i8x16_shuffle(v.raw, zero, 13, 14, 15, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16);
case 14:
return wasm_i8x16_shuffle(v.raw, zero, 14, 15, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16);
case 15:
return wasm_i8x16_shuffle(v.raw, zero, 15, 16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16);
case 16:
return zero;
}
}
} // namespace detail
// 0x01..0F, kBytes = 1 => 0x0001..0E
template <int kBytes, typename T, size_t N>
HWY_API Vec128<T, N> ShiftRightBytes(Simd<T, N, 0> /* tag */, Vec128<T, N> v) {
// For partial vectors, clear upper lanes so we shift in zeros.
if (N != 16 / sizeof(T)) {
const Vec128<T> vfull{v.raw};
v = Vec128<T, N>{IfThenElseZero(FirstN(Full128<T>(), N), vfull).raw};
}
return Vec128<T, N>{detail::ShrBytes<kBytes>(v)};
}
// ------------------------------ ShiftRightLanes
template <int kLanes, typename T, size_t N>
HWY_API Vec128<T, N> ShiftRightLanes(Simd<T, N, 0> d, const Vec128<T, N> v) {
const Repartition<uint8_t, decltype(d)> d8;
return BitCast(d, ShiftRightBytes<kLanes * sizeof(T)>(d8, BitCast(d8, v)));
}
// ------------------------------ UpperHalf (ShiftRightBytes)
// Full input: copy hi into lo (smaller instruction encoding than shifts).
template <typename T>
HWY_API Vec64<T> UpperHalf(Full64<T> /* tag */, const Vec128<T> v) {
return Vec64<T>{wasm_i32x4_shuffle(v.raw, v.raw, 2, 3, 2, 3)};
}
HWY_API Vec64<float> UpperHalf(Full64<float> /* tag */, const Vec128<float> v) {
return Vec64<float>{wasm_i32x4_shuffle(v.raw, v.raw, 2, 3, 2, 3)};
}
// Partial
template <typename T, size_t N, HWY_IF_LE64(T, N)>
HWY_API Vec128<T, (N + 1) / 2> UpperHalf(Half<Simd<T, N, 0>> /* tag */,
Vec128<T, N> v) {
const DFromV<decltype(v)> d;
const RebindToUnsigned<decltype(d)> du;
const auto vu = BitCast(du, v);
const auto upper = BitCast(d, ShiftRightBytes<N * sizeof(T) / 2>(du, vu));
return Vec128<T, (N + 1) / 2>{upper.raw};
}
// ------------------------------ CombineShiftRightBytes
template <int kBytes, typename T, class V = Vec128<T>>
HWY_API V CombineShiftRightBytes(Full128<T> /* tag */, V hi, V lo) {
static_assert(0 <= kBytes && kBytes <= 16, "Invalid kBytes");
switch (kBytes) {
case 0:
return lo;
case 1:
return V{wasm_i8x16_shuffle(lo.raw, hi.raw, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16)};
case 2:
return V{wasm_i8x16_shuffle(lo.raw, hi.raw, 2, 3, 4, 5, 6, 7, 8, 9, 10,
11, 12, 13, 14, 15, 16, 17)};
case 3:
return V{wasm_i8x16_shuffle(lo.raw, hi.raw, 3, 4, 5, 6, 7, 8, 9, 10, 11,
12, 13, 14, 15, 16, 17, 18)};
case 4:
return V{wasm_i8x16_shuffle(lo.raw, hi.raw, 4, 5, 6, 7, 8, 9, 10, 11, 12,
13, 14, 15, 16, 17, 18, 19)};
case 5:
return V{wasm_i8x16_shuffle(lo.raw, hi.raw, 5, 6, 7, 8, 9, 10, 11, 12, 13,
14, 15, 16, 17, 18, 19, 20)};
case 6:
return V{wasm_i8x16_shuffle(lo.raw, hi.raw, 6, 7, 8, 9, 10, 11, 12, 13,
14, 15, 16, 17, 18, 19, 20, 21)};
case 7:
return V{wasm_i8x16_shuffle(lo.raw, hi.raw, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20, 21, 22)};
case 8:
return V{wasm_i8x16_shuffle(lo.raw, hi.raw, 8, 9, 10, 11, 12, 13, 14, 15,
16, 17, 18, 19, 20, 21, 22, 23)};
case 9:
return V{wasm_i8x16_shuffle(lo.raw, hi.raw, 9, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24)};
case 10:
return V{wasm_i8x16_shuffle(lo.raw, hi.raw, 10, 11, 12, 13, 14, 15, 16,
17, 18, 19, 20, 21, 22, 23, 24, 25)};
case 11:
return V{wasm_i8x16_shuffle(lo.raw, hi.raw, 11, 12, 13, 14, 15, 16, 17,
18, 19, 20, 21, 22, 23, 24, 25, 26)};
case 12:
return V{wasm_i8x16_shuffle(lo.raw, hi.raw, 12, 13, 14, 15, 16, 17, 18,
19, 20, 21, 22, 23, 24, 25, 26, 27)};
case 13:
return V{wasm_i8x16_shuffle(lo.raw, hi.raw, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27, 28)};
case 14:
return V{wasm_i8x16_shuffle(lo.raw, hi.raw, 14, 15, 16, 17, 18, 19, 20,
21, 22, 23, 24, 25, 26, 27, 28, 29)};
case 15:
return V{wasm_i8x16_shuffle(lo.raw, hi.raw, 15, 16, 17, 18, 19, 20, 21,
22, 23, 24, 25, 26, 27, 28, 29, 30)};
}
return hi;
}
template <int kBytes, typename T, size_t N, HWY_IF_LE64(T, N),
class V = Vec128<T, N>>
HWY_API V CombineShiftRightBytes(Simd<T, N, 0> d, V hi, V lo) {
constexpr size_t kSize = N * sizeof(T);
static_assert(0 < kBytes && kBytes < kSize, "kBytes invalid");
const Repartition<uint8_t, decltype(d)> d8;
const Full128<uint8_t> d_full8;
using V8 = VFromD<decltype(d_full8)>;
const V8 hi8{BitCast(d8, hi).raw};
// Move into most-significant bytes
const V8 lo8 = ShiftLeftBytes<16 - kSize>(V8{BitCast(d8, lo).raw});
const V8 r = CombineShiftRightBytes<16 - kSize + kBytes>(d_full8, hi8, lo8);
return V{BitCast(Full128<T>(), r).raw};
}
// ------------------------------ Broadcast/splat any lane
template <int kLane, typename T, size_t N, HWY_IF_LANE_SIZE(T, 2)>
HWY_API Vec128<T, N> Broadcast(const Vec128<T, N> v) {
static_assert(0 <= kLane && kLane < N, "Invalid lane");
return Vec128<T, N>{wasm_i16x8_shuffle(v.raw, v.raw, kLane, kLane, kLane,
kLane, kLane, kLane, kLane, kLane)};
}
template <int kLane, typename T, size_t N, HWY_IF_LANE_SIZE(T, 4)>
HWY_API Vec128<T, N> Broadcast(const Vec128<T, N> v) {
static_assert(0 <= kLane && kLane < N, "Invalid lane");
return Vec128<T, N>{
wasm_i32x4_shuffle(v.raw, v.raw, kLane, kLane, kLane, kLane)};
}
template <int kLane, typename T, size_t N, HWY_IF_LANE_SIZE(T, 8)>
HWY_API Vec128<T, N> Broadcast(const Vec128<T, N> v) {
static_assert(0 <= kLane && kLane < N, "Invalid lane");
return Vec128<T, N>{wasm_i64x2_shuffle(v.raw, v.raw, kLane, kLane)};
}
// ------------------------------ TableLookupBytes
// Returns vector of bytes[from[i]]. "from" is also interpreted as bytes, i.e.
// lane indices in [0, 16).
template <typename T, size_t N, typename TI, size_t NI>
HWY_API Vec128<TI, NI> TableLookupBytes(const Vec128<T, N> bytes,
const Vec128<TI, NI> from) {
// Not yet available in all engines, see
// https://github.com/WebAssembly/simd/blob/bdcc304b2d379f4601c2c44ea9b44ed9484fde7e/proposals/simd/ImplementationStatus.md
// V8 implementation of this had a bug, fixed on 2021-04-03:
// https://chromium-review.googlesource.com/c/v8/v8/+/2822951
#if 0
return Vec128<TI, NI>{wasm_i8x16_swizzle(bytes.raw, from.raw)};
#else
alignas(16) uint8_t control[16];
alignas(16) uint8_t input[16];
alignas(16) uint8_t output[16];
wasm_v128_store(control, from.raw);
wasm_v128_store(input, bytes.raw);
for (size_t i = 0; i < 16; ++i) {
output[i] = control[i] < 16 ? input[control[i]] : 0;
}
return Vec128<TI, NI>{wasm_v128_load(output)};
#endif
}
template <typename T, size_t N, typename TI, size_t NI>
HWY_API Vec128<TI, NI> TableLookupBytesOr0(const Vec128<T, N> bytes,
const Vec128<TI, NI> from) {
const Simd<TI, NI, 0> d;
// Mask size must match vector type, so cast everything to this type.
Repartition<int8_t, decltype(d)> di8;
Repartition<int8_t, Simd<T, N, 0>> d_bytes8;
const auto msb = BitCast(di8, from) < Zero(di8);
const auto lookup =
TableLookupBytes(BitCast(d_bytes8, bytes), BitCast(di8, from));
return BitCast(d, IfThenZeroElse(msb, lookup));
}
// ------------------------------ Hard-coded shuffles
// Notation: let Vec128<int32_t> have lanes 3,2,1,0 (0 is least-significant).
// Shuffle0321 rotates one lane to the right (the previous least-significant
// lane is now most-significant). These could also be implemented via
// CombineShiftRightBytes but the shuffle_abcd notation is more convenient.
// Swap 32-bit halves in 64-bit halves.
template <typename T, size_t N>
HWY_API Vec128<T, N> Shuffle2301(const Vec128<T, N> v) {
static_assert(sizeof(T) == 4, "Only for 32-bit lanes");
static_assert(N == 2 || N == 4, "Does not make sense for N=1");
return Vec128<T, N>{wasm_i32x4_shuffle(v.raw, v.raw, 1, 0, 3, 2)};
}
// Swap 64-bit halves
template <typename T>
HWY_API Vec128<T> Shuffle01(const Vec128<T> v) {
static_assert(sizeof(T) == 8, "Only for 64-bit lanes");
return Vec128<T>{wasm_i64x2_shuffle(v.raw, v.raw, 1, 0)};
}
template <typename T>
HWY_API Vec128<T> Shuffle1032(const Vec128<T> v) {
static_assert(sizeof(T) == 4, "Only for 32-bit lanes");
return Vec128<T>{wasm_i64x2_shuffle(v.raw, v.raw, 1, 0)};
}
// Rotate right 32 bits
template <typename T>
HWY_API Vec128<T> Shuffle0321(const Vec128<T> v) {
static_assert(sizeof(T) == 4, "Only for 32-bit lanes");
return Vec128<T>{wasm_i32x4_shuffle(v.raw, v.raw, 1, 2, 3, 0)};
}
// Rotate left 32 bits
template <typename T>
HWY_API Vec128<T> Shuffle2103(const Vec128<T> v) {
static_assert(sizeof(T) == 4, "Only for 32-bit lanes");
return Vec128<T>{wasm_i32x4_shuffle(v.raw, v.raw, 3, 0, 1, 2)};
}
// Reverse
template <typename T>
HWY_API Vec128<T> Shuffle0123(const Vec128<T> v) {
static_assert(sizeof(T) == 4, "Only for 32-bit lanes");
return Vec128<T>{wasm_i32x4_shuffle(v.raw, v.raw, 3, 2, 1, 0)};
}
// ------------------------------ TableLookupLanes
// Returned by SetTableIndices for use by TableLookupLanes.
template <typename T, size_t N>
struct Indices128 {
__v128_u raw;
};
template <typename T, size_t N, typename TI, HWY_IF_LE128(T, N)>
HWY_API Indices128<T, N> IndicesFromVec(Simd<T, N, 0> d, Vec128<TI, N> vec) {
static_assert(sizeof(T) == sizeof(TI), "Index size must match lane");
#if HWY_IS_DEBUG_BUILD
const Rebind<TI, decltype(d)> di;
HWY_DASSERT(AllFalse(di, Lt(vec, Zero(di))) &&
AllTrue(di, Lt(vec, Set(di, static_cast<TI>(N)))));
#endif
const Repartition<uint8_t, decltype(d)> d8;
using V8 = VFromD<decltype(d8)>;
const Repartition<uint16_t, decltype(d)> d16;
// Broadcast each lane index to all bytes of T and shift to bytes
static_assert(sizeof(T) == 4 || sizeof(T) == 8, "");
if (sizeof(T) == 4) {
alignas(16) constexpr uint8_t kBroadcastLaneBytes[16] = {
0, 0, 0, 0, 4, 4, 4, 4, 8, 8, 8, 8, 12, 12, 12, 12};
const V8 lane_indices =
TableLookupBytes(BitCast(d8, vec), Load(d8, kBroadcastLaneBytes));
const V8 byte_indices =
BitCast(d8, ShiftLeft<2>(BitCast(d16, lane_indices)));
alignas(16) constexpr uint8_t kByteOffsets[16] = {0, 1, 2, 3, 0, 1, 2, 3,
0, 1, 2, 3, 0, 1, 2, 3};
return Indices128<T, N>{Add(byte_indices, Load(d8, kByteOffsets)).raw};
} else {
alignas(16) constexpr uint8_t kBroadcastLaneBytes[16] = {
0, 0, 0, 0, 0, 0, 0, 0, 8, 8, 8, 8, 8, 8, 8, 8};
const V8 lane_indices =
TableLookupBytes(BitCast(d8, vec), Load(d8, kBroadcastLaneBytes));
const V8 byte_indices =
BitCast(d8, ShiftLeft<3>(BitCast(d16, lane_indices)));
alignas(16) constexpr uint8_t kByteOffsets[16] = {0, 1, 2, 3, 4, 5, 6, 7,
0, 1, 2, 3, 4, 5, 6, 7};
return Indices128<T, N>{Add(byte_indices, Load(d8, kByteOffsets)).raw};
}
}
template <typename T, size_t N, typename TI, HWY_IF_LE128(T, N)>
HWY_API Indices128<T, N> SetTableIndices(Simd<T, N, 0> d, const TI* idx) {
const Rebind<TI, decltype(d)> di;
return IndicesFromVec(d, LoadU(di, idx));
}
template <typename T, size_t N>
HWY_API Vec128<T, N> TableLookupLanes(Vec128<T, N> v, Indices128<T, N> idx) {
using TI = MakeSigned<T>;
const DFromV<decltype(v)> d;
const Rebind<TI, decltype(d)> di;
return BitCast(d, TableLookupBytes(BitCast(di, v), Vec128<TI, N>{idx.raw}));
}
// ------------------------------ Reverse (Shuffle0123, Shuffle2301, Shuffle01)
// Single lane: no change
template <typename T>
HWY_API Vec128<T, 1> Reverse(Simd<T, 1, 0> /* tag */, const Vec128<T, 1> v) {
return v;
}
// Two lanes: shuffle
template <typename T, HWY_IF_LANE_SIZE(T, 4)>
HWY_API Vec128<T, 2> Reverse(Simd<T, 2, 0> /* tag */, const Vec128<T, 2> v) {
return Vec128<T, 2>{Shuffle2301(Vec128<T>{v.raw}).raw};
}
template <typename T, HWY_IF_LANE_SIZE(T, 8)>
HWY_API Vec128<T> Reverse(Full128<T> /* tag */, const Vec128<T> v) {
return Shuffle01(v);
}
// Four lanes: shuffle
template <typename T, HWY_IF_LANE_SIZE(T, 4)>
HWY_API Vec128<T> Reverse(Full128<T> /* tag */, const Vec128<T> v) {
return Shuffle0123(v);
}
// 16-bit
template <typename T, size_t N, HWY_IF_LANE_SIZE(T, 2)>
HWY_API Vec128<T, N> Reverse(Simd<T, N, 0> d, const Vec128<T, N> v) {
const RepartitionToWide<RebindToUnsigned<decltype(d)>> du32;
return BitCast(d, RotateRight<16>(Reverse(du32, BitCast(du32, v))));
}
// ------------------------------ Reverse2
template <typename T, size_t N, HWY_IF_LANE_SIZE(T, 2)>
HWY_API Vec128<T, N> Reverse2(Simd<T, N, 0> d, const Vec128<T, N> v) {
const RepartitionToWide<RebindToUnsigned<decltype(d)>> du32;
return BitCast(d, RotateRight<16>(BitCast(du32, v)));
}
template <typename T, size_t N, HWY_IF_LANE_SIZE(T, 4)>
HWY_API Vec128<T, N> Reverse2(Simd<T, N, 0> /* tag */, const Vec128<T, N> v) {
return Shuffle2301(v);
}
template <typename T, size_t N, HWY_IF_LANE_SIZE(T, 8)>
HWY_API Vec128<T, N> Reverse2(Simd<T, N, 0> /* tag */, const Vec128<T, N> v) {
return Shuffle01(v);
}
// ------------------------------ Reverse4
template <typename T, size_t N, HWY_IF_LANE_SIZE(T, 2)>
HWY_API Vec128<T, N> Reverse4(Simd<T, N, 0> d, const Vec128<T, N> v) {
const RebindToUnsigned<decltype(d)> du;
return BitCast(d, Vec128<uint16_t, N>{wasm_i16x8_shuffle(v.raw, v.raw, 3, 2,
1, 0, 7, 6, 5, 4)});
}
template <typename T, size_t N, HWY_IF_LANE_SIZE(T, 4)>
HWY_API Vec128<T, N> Reverse4(Simd<T, N, 0> /* tag */, const Vec128<T, N> v) {
return Shuffle0123(v);
}
template <typename T, size_t N, HWY_IF_LANE_SIZE(T, 8)>
HWY_API Vec128<T, N> Reverse4(Simd<T, N, 0> /* tag */, const Vec128<T, N>) {
HWY_ASSERT(0); // don't have 8 u64 lanes
}
// ------------------------------ Reverse8
template <typename T, size_t N, HWY_IF_LANE_SIZE(T, 2)>
HWY_API Vec128<T, N> Reverse8(Simd<T, N, 0> d, const Vec128<T, N> v) {
return Reverse(d, v);
}
template <typename T, size_t N, HWY_IF_NOT_LANE_SIZE(T, 2)>
HWY_API Vec128<T, N> Reverse8(Simd<T, N, 0>, const Vec128<T, N>) {
HWY_ASSERT(0); // don't have 8 lanes unless 16-bit
}
// ------------------------------ InterleaveLower
template <size_t N>
HWY_API Vec128<uint8_t, N> InterleaveLower(Vec128<uint8_t, N> a,
Vec128<uint8_t, N> b) {
return Vec128<uint8_t, N>{wasm_i8x16_shuffle(
a.raw, b.raw, 0, 16, 1, 17, 2, 18, 3, 19, 4, 20, 5, 21, 6, 22, 7, 23)};
}
template <size_t N>
HWY_API Vec128<uint16_t, N> InterleaveLower(Vec128<uint16_t, N> a,
Vec128<uint16_t, N> b) {
return Vec128<uint16_t, N>{
wasm_i16x8_shuffle(a.raw, b.raw, 0, 8, 1, 9, 2, 10, 3, 11)};
}
template <size_t N>
HWY_API Vec128<uint32_t, N> InterleaveLower(Vec128<uint32_t, N> a,
Vec128<uint32_t, N> b) {
return Vec128<uint32_t, N>{wasm_i32x4_shuffle(a.raw, b.raw, 0, 4, 1, 5)};
}
template <size_t N>
HWY_API Vec128<uint64_t, N> InterleaveLower(Vec128<uint64_t, N> a,
Vec128<uint64_t, N> b) {
return Vec128<uint64_t, N>{wasm_i64x2_shuffle(a.raw, b.raw, 0, 2)};
}
template <size_t N>
HWY_API Vec128<int8_t, N> InterleaveLower(Vec128<int8_t, N> a,
Vec128<int8_t, N> b) {
return Vec128<int8_t, N>{wasm_i8x16_shuffle(
a.raw, b.raw, 0, 16, 1, 17, 2, 18, 3, 19, 4, 20, 5, 21, 6, 22, 7, 23)};
}
template <size_t N>
HWY_API Vec128<int16_t, N> InterleaveLower(Vec128<int16_t, N> a,
Vec128<int16_t, N> b) {
return Vec128<int16_t, N>{
wasm_i16x8_shuffle(a.raw, b.raw, 0, 8, 1, 9, 2, 10, 3, 11)};
}
template <size_t N>
HWY_API Vec128<int32_t, N> InterleaveLower(Vec128<int32_t, N> a,
Vec128<int32_t, N> b) {
return Vec128<int32_t, N>{wasm_i32x4_shuffle(a.raw, b.raw, 0, 4, 1, 5)};
}
template <size_t N>
HWY_API Vec128<int64_t, N> InterleaveLower(Vec128<int64_t, N> a,
Vec128<int64_t, N> b) {
return Vec128<int64_t, N>{wasm_i64x2_shuffle(a.raw, b.raw, 0, 2)};
}
template <size_t N>
HWY_API Vec128<float, N> InterleaveLower(Vec128<float, N> a,
Vec128<float, N> b) {
return Vec128<float, N>{wasm_i32x4_shuffle(a.raw, b.raw, 0, 4, 1, 5)};
}
// Additional overload for the optional tag.
template <class V>
HWY_API V InterleaveLower(DFromV<V> /* tag */, V a, V b) {
return InterleaveLower(a, b);
}
// ------------------------------ InterleaveUpper (UpperHalf)
// All functions inside detail lack the required D parameter.
namespace detail {
template <size_t N>
HWY_API Vec128<uint8_t, N> InterleaveUpper(Vec128<uint8_t, N> a,
Vec128<uint8_t, N> b) {
return Vec128<uint8_t, N>{wasm_i8x16_shuffle(a.raw, b.raw, 8, 24, 9, 25, 10,
26, 11, 27, 12, 28, 13, 29, 14,
30, 15, 31)};
}
template <size_t N>
HWY_API Vec128<uint16_t, N> InterleaveUpper(Vec128<uint16_t, N> a,
Vec128<uint16_t, N> b) {
return Vec128<uint16_t, N>{
wasm_i16x8_shuffle(a.raw, b.raw, 4, 12, 5, 13, 6, 14, 7, 15)};
}
template <size_t N>
HWY_API Vec128<uint32_t, N> InterleaveUpper(Vec128<uint32_t, N> a,
Vec128<uint32_t, N> b) {
return Vec128<uint32_t, N>{wasm_i32x4_shuffle(a.raw, b.raw, 2, 6, 3, 7)};
}
template <size_t N>
HWY_API Vec128<uint64_t, N> InterleaveUpper(Vec128<uint64_t, N> a,
Vec128<uint64_t, N> b) {
return Vec128<uint64_t, N>{wasm_i64x2_shuffle(a.raw, b.raw, 1, 3)};
}
template <size_t N>
HWY_API Vec128<int8_t, N> InterleaveUpper(Vec128<int8_t, N> a,
Vec128<int8_t, N> b) {
return Vec128<int8_t, N>{wasm_i8x16_shuffle(a.raw, b.raw, 8, 24, 9, 25, 10,
26, 11, 27, 12, 28, 13, 29, 14,
30, 15, 31)};
}
template <size_t N>
HWY_API Vec128<int16_t, N> InterleaveUpper(Vec128<int16_t, N> a,
Vec128<int16_t, N> b) {
return Vec128<int16_t, N>{
wasm_i16x8_shuffle(a.raw, b.raw, 4, 12, 5, 13, 6, 14, 7, 15)};
}
template <size_t N>
HWY_API Vec128<int32_t, N> InterleaveUpper(Vec128<int32_t, N> a,
Vec128<int32_t, N> b) {
return Vec128<int32_t, N>{wasm_i32x4_shuffle(a.raw, b.raw, 2, 6, 3, 7)};
}
template <size_t N>
HWY_API Vec128<int64_t, N> InterleaveUpper(Vec128<int64_t, N> a,
Vec128<int64_t, N> b) {
return Vec128<int64_t, N>{wasm_i64x2_shuffle(a.raw, b.raw, 1, 3)};
}
template <size_t N>
HWY_API Vec128<float, N> InterleaveUpper(Vec128<float, N> a,
Vec128<float, N> b) {
return Vec128<float, N>{wasm_i32x4_shuffle(a.raw, b.raw, 2, 6, 3, 7)};
}
} // namespace detail
// Full
template <typename T, class V = Vec128<T>>
HWY_API V InterleaveUpper(Full128<T> /* tag */, V a, V b) {
return detail::InterleaveUpper(a, b);
}
// Partial
template <typename T, size_t N, HWY_IF_LE64(T, N), class V = Vec128<T, N>>
HWY_API V InterleaveUpper(Simd<T, N, 0> d, V a, V b) {
const Half<decltype(d)> d2;
return InterleaveLower(d, V{UpperHalf(d2, a).raw}, V{UpperHalf(d2, b).raw});
}
// ------------------------------ ZipLower/ZipUpper (InterleaveLower)
// Same as Interleave*, except that the return lanes are double-width integers;
// this is necessary because the single-lane scalar cannot return two values.
template <class V, class DW = RepartitionToWide<DFromV<V>>>
HWY_API VFromD<DW> ZipLower(V a, V b) {
return BitCast(DW(), InterleaveLower(a, b));
}
template <class V, class D = DFromV<V>, class DW = RepartitionToWide<D>>
HWY_API VFromD<DW> ZipLower(DW dw, V a, V b) {
return BitCast(dw, InterleaveLower(D(), a, b));
}
template <class V, class D = DFromV<V>, class DW = RepartitionToWide<D>>
HWY_API VFromD<DW> ZipUpper(DW dw, V a, V b) {
return BitCast(dw, InterleaveUpper(D(), a, b));
}
// ================================================== COMBINE
// ------------------------------ Combine (InterleaveLower)
// N = N/2 + N/2 (upper half undefined)
template <typename T, size_t N>
HWY_API Vec128<T, N> Combine(Simd<T, N, 0> d, Vec128<T, N / 2> hi_half,
Vec128<T, N / 2> lo_half) {
const Half<decltype(d)> d2;
const RebindToUnsigned<decltype(d2)> du2;
// Treat half-width input as one lane, and expand to two lanes.
using VU = Vec128<UnsignedFromSize<N * sizeof(T) / 2>, 2>;
const VU lo{BitCast(du2, lo_half).raw};
const VU hi{BitCast(du2, hi_half).raw};
return BitCast(d, InterleaveLower(lo, hi));
}
// ------------------------------ ZeroExtendVector (Combine, IfThenElseZero)
template <typename T, size_t N>
HWY_API Vec128<T, N> ZeroExtendVector(Simd<T, N, 0> d, Vec128<T, N / 2> lo) {
return IfThenElseZero(FirstN(d, N / 2), Vec128<T, N>{lo.raw});
}
// ------------------------------ ConcatLowerLower
// hiH,hiL loH,loL |-> hiL,loL (= lower halves)
template <typename T>
HWY_API Vec128<T> ConcatLowerLower(Full128<T> /* tag */, const Vec128<T> hi,
const Vec128<T> lo) {
return Vec128<T>{wasm_i64x2_shuffle(lo.raw, hi.raw, 0, 2)};
}
template <typename T, size_t N, HWY_IF_LE64(T, N)>
HWY_API Vec128<T, N> ConcatLowerLower(Simd<T, N, 0> d, const Vec128<T, N> hi,
const Vec128<T, N> lo) {
const Half<decltype(d)> d2;
return Combine(d, LowerHalf(d2, hi), LowerHalf(d2, lo));
}
// ------------------------------ ConcatUpperUpper
template <typename T>
HWY_API Vec128<T> ConcatUpperUpper(Full128<T> /* tag */, const Vec128<T> hi,
const Vec128<T> lo) {
return Vec128<T>{wasm_i64x2_shuffle(lo.raw, hi.raw, 1, 3)};
}
template <typename T, size_t N, HWY_IF_LE64(T, N)>
HWY_API Vec128<T, N> ConcatUpperUpper(Simd<T, N, 0> d, const Vec128<T, N> hi,
const Vec128<T, N> lo) {
const Half<decltype(d)> d2;
return Combine(d, UpperHalf(d2, hi), UpperHalf(d2, lo));
}
// ------------------------------ ConcatLowerUpper
template <typename T>
HWY_API Vec128<T> ConcatLowerUpper(Full128<T> d, const Vec128<T> hi,
const Vec128<T> lo) {
return CombineShiftRightBytes<8>(d, hi, lo);
}
template <typename T, size_t N, HWY_IF_LE64(T, N)>
HWY_API Vec128<T, N> ConcatLowerUpper(Simd<T, N, 0> d, const Vec128<T, N> hi,
const Vec128<T, N> lo) {
const Half<decltype(d)> d2;
return Combine(d, LowerHalf(d2, hi), UpperHalf(d2, lo));
}
// ------------------------------ ConcatUpperLower
template <typename T, size_t N>
HWY_API Vec128<T, N> ConcatUpperLower(Simd<T, N, 0> d, const Vec128<T, N> hi,
const Vec128<T, N> lo) {
return IfThenElse(FirstN(d, Lanes(d) / 2), lo, hi);
}
// ------------------------------ ConcatOdd
// 32-bit full
template <typename T, HWY_IF_LANE_SIZE(T, 4)>
HWY_API Vec128<T> ConcatOdd(Full128<T> /* tag */, Vec128<T> hi, Vec128<T> lo) {
return Vec128<T>{wasm_i32x4_shuffle(lo.raw, hi.raw, 1, 3, 5, 7)};
}
// 32-bit partial
template <typename T, HWY_IF_LANE_SIZE(T, 4)>
HWY_API Vec128<T, 2> ConcatOdd(Simd<T, 2, 0> /* tag */, Vec128<T, 2> hi,
Vec128<T, 2> lo) {
return InterleaveUpper(Simd<T, 2, 0>(), lo, hi);
}
// 64-bit full - no partial because we need at least two inputs to have
// even/odd.
template <typename T, HWY_IF_LANE_SIZE(T, 8)>
HWY_API Vec128<T> ConcatOdd(Full128<T> /* tag */, Vec128<T> hi, Vec128<T> lo) {
return InterleaveUpper(Full128<T>(), lo, hi);
}
// ------------------------------ ConcatEven (InterleaveLower)
// 32-bit full
template <typename T, HWY_IF_LANE_SIZE(T, 4)>
HWY_API Vec128<T> ConcatEven(Full128<T> /* tag */, Vec128<T> hi, Vec128<T> lo) {
return Vec128<T>{wasm_i32x4_shuffle(lo.raw, hi.raw, 0, 2, 4, 6)};
}
// 32-bit partial
template <typename T, HWY_IF_LANE_SIZE(T, 4)>
HWY_API Vec128<T, 2> ConcatEven(Simd<T, 2, 0> /* tag */, Vec128<T, 2> hi,
Vec128<T, 2> lo) {
return InterleaveLower(Simd<T, 2, 0>(), lo, hi);
}
// 64-bit full - no partial because we need at least two inputs to have
// even/odd.
template <typename T, HWY_IF_LANE_SIZE(T, 8)>
HWY_API Vec128<T> ConcatEven(Full128<T> /* tag */, Vec128<T> hi, Vec128<T> lo) {
return InterleaveLower(Full128<T>(), lo, hi);
}
// ------------------------------ DupEven (InterleaveLower)
template <typename T, size_t N, HWY_IF_LANE_SIZE(T, 4)>
HWY_API Vec128<T, N> DupEven(Vec128<T, N> v) {
return Vec128<T, N>{wasm_i32x4_shuffle(v.raw, v.raw, 0, 0, 2, 2)};
}
template <typename T, size_t N, HWY_IF_LANE_SIZE(T, 8)>
HWY_API Vec128<T, N> DupEven(const Vec128<T, N> v) {
return InterleaveLower(DFromV<decltype(v)>(), v, v);
}
// ------------------------------ DupOdd (InterleaveUpper)
template <typename T, size_t N, HWY_IF_LANE_SIZE(T, 4)>
HWY_API Vec128<T, N> DupOdd(Vec128<T, N> v) {
return Vec128<T, N>{wasm_i32x4_shuffle(v.raw, v.raw, 1, 1, 3, 3)};
}
template <typename T, size_t N, HWY_IF_LANE_SIZE(T, 8)>
HWY_API Vec128<T, N> DupOdd(const Vec128<T, N> v) {
return InterleaveUpper(DFromV<decltype(v)>(), v, v);
}
// ------------------------------ OddEven
namespace detail {
template <typename T, size_t N>
HWY_INLINE Vec128<T, N> OddEven(hwy::SizeTag<1> /* tag */, const Vec128<T, N> a,
const Vec128<T, N> b) {
const DFromV<decltype(a)> d;
const Repartition<uint8_t, decltype(d)> d8;
alignas(16) constexpr uint8_t mask[16] = {0xFF, 0, 0xFF, 0, 0xFF, 0, 0xFF, 0,
0xFF, 0, 0xFF, 0, 0xFF, 0, 0xFF, 0};
return IfThenElse(MaskFromVec(BitCast(d, Load(d8, mask))), b, a);
}
template <typename T, size_t N>
HWY_INLINE Vec128<T, N> OddEven(hwy::SizeTag<2> /* tag */, const Vec128<T, N> a,
const Vec128<T, N> b) {
return Vec128<T, N>{
wasm_i16x8_shuffle(a.raw, b.raw, 8, 1, 10, 3, 12, 5, 14, 7)};
}
template <typename T, size_t N>
HWY_INLINE Vec128<T, N> OddEven(hwy::SizeTag<4> /* tag */, const Vec128<T, N> a,
const Vec128<T, N> b) {
return Vec128<T, N>{wasm_i32x4_shuffle(a.raw, b.raw, 4, 1, 6, 3)};
}
template <typename T, size_t N>
HWY_INLINE Vec128<T, N> OddEven(hwy::SizeTag<8> /* tag */, const Vec128<T, N> a,
const Vec128<T, N> b) {
return Vec128<T, N>{wasm_i64x2_shuffle(a.raw, b.raw, 2, 1)};
}
} // namespace detail
template <typename T, size_t N>
HWY_API Vec128<T, N> OddEven(const Vec128<T, N> a, const Vec128<T, N> b) {
return detail::OddEven(hwy::SizeTag<sizeof(T)>(), a, b);
}
template <size_t N>
HWY_API Vec128<float, N> OddEven(const Vec128<float, N> a,
const Vec128<float, N> b) {
return Vec128<float, N>{wasm_i32x4_shuffle(a.raw, b.raw, 4, 1, 6, 3)};
}
// ------------------------------ OddEvenBlocks
template <typename T, size_t N>
HWY_API Vec128<T, N> OddEvenBlocks(Vec128<T, N> /* odd */, Vec128<T, N> even) {
return even;
}
// ------------------------------ SwapAdjacentBlocks
template <typename T, size_t N>
HWY_API Vec128<T, N> SwapAdjacentBlocks(Vec128<T, N> v) {
return v;
}
// ------------------------------ ReverseBlocks
// Single block: no change
template <typename T>
HWY_API Vec128<T> ReverseBlocks(Full128<T> /* tag */, const Vec128<T> v) {
return v;
}
// ================================================== CONVERT
// ------------------------------ Promotions (part w/ narrow lanes -> full)
// Unsigned: zero-extend.
template <size_t N>
HWY_API Vec128<uint16_t, N> PromoteTo(Simd<uint16_t, N, 0> /* tag */,
const Vec128<uint8_t, N> v) {
return Vec128<uint16_t, N>{wasm_u16x8_extend_low_u8x16(v.raw)};
}
template <size_t N>
HWY_API Vec128<uint32_t, N> PromoteTo(Simd<uint32_t, N, 0> /* tag */,
const Vec128<uint8_t, N> v) {
return Vec128<uint32_t, N>{
wasm_u32x4_extend_low_u16x8(wasm_u16x8_extend_low_u8x16(v.raw))};
}
template <size_t N>
HWY_API Vec128<int16_t, N> PromoteTo(Simd<int16_t, N, 0> /* tag */,
const Vec128<uint8_t, N> v) {
return Vec128<int16_t, N>{wasm_u16x8_extend_low_u8x16(v.raw)};
}
template <size_t N>
HWY_API Vec128<int32_t, N> PromoteTo(Simd<int32_t, N, 0> /* tag */,
const Vec128<uint8_t, N> v) {
return Vec128<int32_t, N>{
wasm_u32x4_extend_low_u16x8(wasm_u16x8_extend_low_u8x16(v.raw))};
}
template <size_t N>
HWY_API Vec128<uint32_t, N> PromoteTo(Simd<uint32_t, N, 0> /* tag */,
const Vec128<uint16_t, N> v) {
return Vec128<uint32_t, N>{wasm_u32x4_extend_low_u16x8(v.raw)};
}
template <size_t N>
HWY_API Vec128<uint64_t, N> PromoteTo(Simd<uint64_t, N, 0> /* tag */,
const Vec128<uint32_t, N> v) {
return Vec128<uint64_t, N>{wasm_u64x2_extend_low_u32x4(v.raw)};
}
template <size_t N>
HWY_API Vec128<int32_t, N> PromoteTo(Simd<int32_t, N, 0> /* tag */,
const Vec128<uint16_t, N> v) {
return Vec128<int32_t, N>{wasm_u32x4_extend_low_u16x8(v.raw)};
}
// Signed: replicate sign bit.
template <size_t N>
HWY_API Vec128<int16_t, N> PromoteTo(Simd<int16_t, N, 0> /* tag */,
const Vec128<int8_t, N> v) {
return Vec128<int16_t, N>{wasm_i16x8_extend_low_i8x16(v.raw)};
}
template <size_t N>
HWY_API Vec128<int32_t, N> PromoteTo(Simd<int32_t, N, 0> /* tag */,
const Vec128<int8_t, N> v) {
return Vec128<int32_t, N>{
wasm_i32x4_extend_low_i16x8(wasm_i16x8_extend_low_i8x16(v.raw))};
}
template <size_t N>
HWY_API Vec128<int32_t, N> PromoteTo(Simd<int32_t, N, 0> /* tag */,
const Vec128<int16_t, N> v) {
return Vec128<int32_t, N>{wasm_i32x4_extend_low_i16x8(v.raw)};
}
template <size_t N>
HWY_API Vec128<int64_t, N> PromoteTo(Simd<int64_t, N, 0> /* tag */,
const Vec128<int32_t, N> v) {
return Vec128<int64_t, N>{wasm_i64x2_extend_low_i32x4(v.raw)};
}
template <size_t N>
HWY_API Vec128<double, N> PromoteTo(Simd<double, N, 0> /* tag */,
const Vec128<int32_t, N> v) {
return Vec128<double, N>{wasm_f64x2_convert_low_i32x4(v.raw)};
}
template <size_t N>
HWY_API Vec128<float, N> PromoteTo(Simd<float, N, 0> df32,
const Vec128<float16_t, N> v) {
const RebindToSigned<decltype(df32)> di32;
const RebindToUnsigned<decltype(df32)> du32;
// Expand to u32 so we can shift.
const auto bits16 = PromoteTo(du32, Vec128<uint16_t, N>{v.raw});
const auto sign = ShiftRight<15>(bits16);
const auto biased_exp = ShiftRight<10>(bits16) & Set(du32, 0x1F);
const auto mantissa = bits16 & Set(du32, 0x3FF);
const auto subnormal =
BitCast(du32, ConvertTo(df32, BitCast(di32, mantissa)) *
Set(df32, 1.0f / 16384 / 1024));
const auto biased_exp32 = biased_exp + Set(du32, 127 - 15);
const auto mantissa32 = ShiftLeft<23 - 10>(mantissa);
const auto normal = ShiftLeft<23>(biased_exp32) | mantissa32;
const auto bits32 = IfThenElse(biased_exp == Zero(du32), subnormal, normal);
return BitCast(df32, ShiftLeft<31>(sign) | bits32);
}
template <size_t N>
HWY_API Vec128<float, N> PromoteTo(Simd<float, N, 0> df32,
const Vec128<bfloat16_t, N> v) {
const Rebind<uint16_t, decltype(df32)> du16;
const RebindToSigned<decltype(df32)> di32;
return BitCast(df32, ShiftLeft<16>(PromoteTo(di32, BitCast(du16, v))));
}
// ------------------------------ Demotions (full -> part w/ narrow lanes)
template <size_t N>
HWY_API Vec128<uint16_t, N> DemoteTo(Simd<uint16_t, N, 0> /* tag */,
const Vec128<int32_t, N> v) {
return Vec128<uint16_t, N>{wasm_u16x8_narrow_i32x4(v.raw, v.raw)};
}
template <size_t N>
HWY_API Vec128<int16_t, N> DemoteTo(Simd<int16_t, N, 0> /* tag */,
const Vec128<int32_t, N> v) {
return Vec128<int16_t, N>{wasm_i16x8_narrow_i32x4(v.raw, v.raw)};
}
template <size_t N>
HWY_API Vec128<uint8_t, N> DemoteTo(Simd<uint8_t, N, 0> /* tag */,
const Vec128<int32_t, N> v) {
const auto intermediate = wasm_i16x8_narrow_i32x4(v.raw, v.raw);
return Vec128<uint8_t, N>{
wasm_u8x16_narrow_i16x8(intermediate, intermediate)};
}
template <size_t N>
HWY_API Vec128<uint8_t, N> DemoteTo(Simd<uint8_t, N, 0> /* tag */,
const Vec128<int16_t, N> v) {
return Vec128<uint8_t, N>{wasm_u8x16_narrow_i16x8(v.raw, v.raw)};
}
template <size_t N>
HWY_API Vec128<int8_t, N> DemoteTo(Simd<int8_t, N, 0> /* tag */,
const Vec128<int32_t, N> v) {
const auto intermediate = wasm_i16x8_narrow_i32x4(v.raw, v.raw);
return Vec128<int8_t, N>{wasm_i8x16_narrow_i16x8(intermediate, intermediate)};
}
template <size_t N>
HWY_API Vec128<int8_t, N> DemoteTo(Simd<int8_t, N, 0> /* tag */,
const Vec128<int16_t, N> v) {
return Vec128<int8_t, N>{wasm_i8x16_narrow_i16x8(v.raw, v.raw)};
}
template <size_t N>
HWY_API Vec128<int32_t, N> DemoteTo(Simd<int32_t, N, 0> /* di */,
const Vec128<double, N> v) {
return Vec128<int32_t, N>{wasm_i32x4_trunc_sat_f64x2_zero(v.raw)};
}
template <size_t N>
HWY_API Vec128<float16_t, N> DemoteTo(Simd<float16_t, N, 0> df16,
const Vec128<float, N> v) {
const RebindToUnsigned<decltype(df16)> du16;
const Rebind<uint32_t, decltype(du16)> du;
const RebindToSigned<decltype(du)> di;
const auto bits32 = BitCast(du, v);
const auto sign = ShiftRight<31>(bits32);
const auto biased_exp32 = ShiftRight<23>(bits32) & Set(du, 0xFF);
const auto mantissa32 = bits32 & Set(du, 0x7FFFFF);
const auto k15 = Set(di, 15);
const auto exp = Min(BitCast(di, biased_exp32) - Set(di, 127), k15);
const auto is_tiny = exp < Set(di, -24);
const auto is_subnormal = exp < Set(di, -14);
const auto biased_exp16 =
BitCast(du, IfThenZeroElse(is_subnormal, exp + k15));
const auto sub_exp = BitCast(du, Set(di, -14) - exp); // [1, 11)
const auto sub_m = (Set(du, 1) << (Set(du, 10) - sub_exp)) +
(mantissa32 >> (Set(du, 13) + sub_exp));
const auto mantissa16 = IfThenElse(RebindMask(du, is_subnormal), sub_m,
ShiftRight<13>(mantissa32)); // <1024
const auto sign16 = ShiftLeft<15>(sign);
const auto normal16 = sign16 | ShiftLeft<10>(biased_exp16) | mantissa16;
const auto bits16 = IfThenZeroElse(is_tiny, BitCast(di, normal16));
return Vec128<float16_t, N>{DemoteTo(du16, bits16).raw};
}
template <size_t N>
HWY_API Vec128<bfloat16_t, N> DemoteTo(Simd<bfloat16_t, N, 0> dbf16,
const Vec128<float, N> v) {
const Rebind<int32_t, decltype(dbf16)> di32;
const Rebind<uint32_t, decltype(dbf16)> du32; // for logical shift right
const Rebind<uint16_t, decltype(dbf16)> du16;
const auto bits_in_32 = BitCast(di32, ShiftRight<16>(BitCast(du32, v)));
return BitCast(dbf16, DemoteTo(du16, bits_in_32));
}
template <size_t N>
HWY_API Vec128<bfloat16_t, 2 * N> ReorderDemote2To(
Simd<bfloat16_t, 2 * N, 0> dbf16, Vec128<float, N> a, Vec128<float, N> b) {
const RebindToUnsigned<decltype(dbf16)> du16;
const Repartition<uint32_t, decltype(dbf16)> du32;
const Vec128<uint32_t, N> b_in_even = ShiftRight<16>(BitCast(du32, b));
return BitCast(dbf16, OddEven(BitCast(du16, a), BitCast(du16, b_in_even)));
}
// For already range-limited input [0, 255].
template <size_t N>
HWY_API Vec128<uint8_t, N> U8FromU32(const Vec128<uint32_t, N> v) {
const auto intermediate = wasm_i16x8_narrow_i32x4(v.raw, v.raw);
return Vec128<uint8_t, N>{
wasm_u8x16_narrow_i16x8(intermediate, intermediate)};
}
// ------------------------------ Convert i32 <=> f32 (Round)
template <size_t N>
HWY_API Vec128<float, N> ConvertTo(Simd<float, N, 0> /* tag */,
const Vec128<int32_t, N> v) {
return Vec128<float, N>{wasm_f32x4_convert_i32x4(v.raw)};
}
// Truncates (rounds toward zero).
template <size_t N>
HWY_API Vec128<int32_t, N> ConvertTo(Simd<int32_t, N, 0> /* tag */,
const Vec128<float, N> v) {
return Vec128<int32_t, N>{wasm_i32x4_trunc_sat_f32x4(v.raw)};
}
template <size_t N>
HWY_API Vec128<int32_t, N> NearestInt(const Vec128<float, N> v) {
return ConvertTo(Simd<int32_t, N, 0>(), Round(v));
}
// ================================================== MISC
// ------------------------------ SumsOf8 (ShiftRight, Add)
template <size_t N>
HWY_API Vec128<uint64_t, N / 8> SumsOf8(const Vec128<uint8_t, N> v) {
const DFromV<decltype(v)> du8;
const RepartitionToWide<decltype(du8)> du16;
const RepartitionToWide<decltype(du16)> du32;
const RepartitionToWide<decltype(du32)> du64;
using VU16 = VFromD<decltype(du16)>;
const VU16 vFDB97531 = ShiftRight<8>(BitCast(du16, v));
const VU16 vECA86420 = And(BitCast(du16, v), Set(du16, 0xFF));
const VU16 sFE_DC_BA_98_76_54_32_10 = Add(vFDB97531, vECA86420);
const VU16 szz_FE_zz_BA_zz_76_zz_32 =
BitCast(du16, ShiftRight<16>(BitCast(du32, sFE_DC_BA_98_76_54_32_10)));
const VU16 sxx_FC_xx_B8_xx_74_xx_30 =
Add(sFE_DC_BA_98_76_54_32_10, szz_FE_zz_BA_zz_76_zz_32);
const VU16 szz_zz_xx_FC_zz_zz_xx_74 =
BitCast(du16, ShiftRight<32>(BitCast(du64, sxx_FC_xx_B8_xx_74_xx_30)));
const VU16 sxx_xx_xx_F8_xx_xx_xx_70 =
Add(sxx_FC_xx_B8_xx_74_xx_30, szz_zz_xx_FC_zz_zz_xx_74);
return And(BitCast(du64, sxx_xx_xx_F8_xx_xx_xx_70), Set(du64, 0xFFFF));
}
// ------------------------------ LoadMaskBits (TestBit)
namespace detail {
template <typename T, size_t N, HWY_IF_LANE_SIZE(T, 1)>
HWY_INLINE Mask128<T, N> LoadMaskBits(Simd<T, N, 0> d, uint64_t bits) {
const RebindToUnsigned<decltype(d)> du;
// Easier than Set(), which would require an >8-bit type, which would not
// compile for T=uint8_t, N=1.
const Vec128<T, N> vbits{wasm_i32x4_splat(static_cast<int32_t>(bits))};
// Replicate bytes 8x such that each byte contains the bit that governs it.
alignas(16) constexpr uint8_t kRep8[16] = {0, 0, 0, 0, 0, 0, 0, 0,
1, 1, 1, 1, 1, 1, 1, 1};
const auto rep8 = TableLookupBytes(vbits, Load(du, kRep8));
alignas(16) constexpr uint8_t kBit[16] = {1, 2, 4, 8, 16, 32, 64, 128,
1, 2, 4, 8, 16, 32, 64, 128};
return RebindMask(d, TestBit(rep8, LoadDup128(du, kBit)));
}
template <typename T, size_t N, HWY_IF_LANE_SIZE(T, 2)>
HWY_INLINE Mask128<T, N> LoadMaskBits(Simd<T, N, 0> d, uint64_t bits) {
const RebindToUnsigned<decltype(d)> du;
alignas(16) constexpr uint16_t kBit[8] = {1, 2, 4, 8, 16, 32, 64, 128};
return RebindMask(
d, TestBit(Set(du, static_cast<uint16_t>(bits)), Load(du, kBit)));
}
template <typename T, size_t N, HWY_IF_LANE_SIZE(T, 4)>
HWY_INLINE Mask128<T, N> LoadMaskBits(Simd<T, N, 0> d, uint64_t bits) {
const RebindToUnsigned<decltype(d)> du;
alignas(16) constexpr uint32_t kBit[8] = {1, 2, 4, 8};
return RebindMask(
d, TestBit(Set(du, static_cast<uint32_t>(bits)), Load(du, kBit)));
}
template <typename T, size_t N, HWY_IF_LANE_SIZE(T, 8)>
HWY_INLINE Mask128<T, N> LoadMaskBits(Simd<T, N, 0> d, uint64_t bits) {
const RebindToUnsigned<decltype(d)> du;
alignas(16) constexpr uint64_t kBit[8] = {1, 2};
return RebindMask(d, TestBit(Set(du, bits), Load(du, kBit)));
}
} // namespace detail
// `p` points to at least 8 readable bytes, not all of which need be valid.
template <typename T, size_t N, HWY_IF_LE128(T, N)>
HWY_API Mask128<T, N> LoadMaskBits(Simd<T, N, 0> d,
const uint8_t* HWY_RESTRICT bits) {
uint64_t mask_bits = 0;
CopyBytes<(N + 7) / 8>(bits, &mask_bits);
return detail::LoadMaskBits(d, mask_bits);
}
// ------------------------------ Mask
namespace detail {
// Full
template <typename T>
HWY_INLINE uint64_t BitsFromMask(hwy::SizeTag<1> /*tag*/,
const Mask128<T> mask) {
alignas(16) uint64_t lanes[2];
wasm_v128_store(lanes, mask.raw);
constexpr uint64_t kMagic = 0x103070F1F3F80ULL;
const uint64_t lo = ((lanes[0] * kMagic) >> 56);
const uint64_t hi = ((lanes[1] * kMagic) >> 48) & 0xFF00;
return (hi + lo);
}
// 64-bit
template <typename T>
HWY_INLINE uint64_t BitsFromMask(hwy::SizeTag<1> /*tag*/,
const Mask128<T, 8> mask) {
constexpr uint64_t kMagic = 0x103070F1F3F80ULL;
return (static_cast<uint64_t>(wasm_i64x2_extract_lane(mask.raw, 0)) *
kMagic) >>
56;
}
// 32-bit or less: need masking
template <typename T, size_t N, HWY_IF_LE32(T, N)>
HWY_INLINE uint64_t BitsFromMask(hwy::SizeTag<1> /*tag*/,
const Mask128<T, N> mask) {
uint64_t bytes = static_cast<uint64_t>(wasm_i64x2_extract_lane(mask.raw, 0));
// Clear potentially undefined bytes.
bytes &= (1ULL << (N * 8)) - 1;
constexpr uint64_t kMagic = 0x103070F1F3F80ULL;
return (bytes * kMagic) >> 56;
}
template <typename T, size_t N>
HWY_INLINE uint64_t BitsFromMask(hwy::SizeTag<2> /*tag*/,
const Mask128<T, N> mask) {
// Remove useless lower half of each u16 while preserving the sign bit.
const __i16x8 zero = wasm_i16x8_splat(0);
const Mask128<uint8_t, N> mask8{wasm_i8x16_narrow_i16x8(mask.raw, zero)};
return BitsFromMask(hwy::SizeTag<1>(), mask8);
}
template <typename T, size_t N>
HWY_INLINE uint64_t BitsFromMask(hwy::SizeTag<4> /*tag*/,
const Mask128<T, N> mask) {
const __i32x4 mask_i = static_cast<__i32x4>(mask.raw);
const __i32x4 slice = wasm_i32x4_make(1, 2, 4, 8);
const __i32x4 sliced_mask = wasm_v128_and(mask_i, slice);
alignas(16) uint32_t lanes[4];
wasm_v128_store(lanes, sliced_mask);
return lanes[0] | lanes[1] | lanes[2] | lanes[3];
}
template <typename T, size_t N>
HWY_INLINE uint64_t BitsFromMask(hwy::SizeTag<8> /*tag*/,
const Mask128<T, N> mask) {
const __i64x2 mask_i = static_cast<__i64x2>(mask.raw);
const __i64x2 slice = wasm_i64x2_make(1, 2);
const __i64x2 sliced_mask = wasm_v128_and(mask_i, slice);
alignas(16) uint64_t lanes[2];
wasm_v128_store(lanes, sliced_mask);
return lanes[0] | lanes[1];
}
// Returns the lowest N bits for the BitsFromMask result.
template <typename T, size_t N>
constexpr uint64_t OnlyActive(uint64_t bits) {
return ((N * sizeof(T)) == 16) ? bits : bits & ((1ull << N) - 1);
}
// Returns 0xFF for bytes with index >= N, otherwise 0.
template <size_t N>
constexpr __i8x16 BytesAbove() {
return /**/
(N == 0) ? wasm_i32x4_make(-1, -1, -1, -1)
: (N == 4) ? wasm_i32x4_make(0, -1, -1, -1)
: (N == 8) ? wasm_i32x4_make(0, 0, -1, -1)
: (N == 12) ? wasm_i32x4_make(0, 0, 0, -1)
: (N == 16) ? wasm_i32x4_make(0, 0, 0, 0)
: (N == 2) ? wasm_i16x8_make(0, -1, -1, -1, -1, -1, -1, -1)
: (N == 6) ? wasm_i16x8_make(0, 0, 0, -1, -1, -1, -1, -1)
: (N == 10) ? wasm_i16x8_make(0, 0, 0, 0, 0, -1, -1, -1)
: (N == 14) ? wasm_i16x8_make(0, 0, 0, 0, 0, 0, 0, -1)
: (N == 1) ? wasm_i8x16_make(0, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1, -1)
: (N == 3) ? wasm_i8x16_make(0, 0, 0, -1, -1, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1)
: (N == 5) ? wasm_i8x16_make(0, 0, 0, 0, 0, -1, -1, -1, -1, -1, -1, -1,
-1, -1, -1, -1)
: (N == 7) ? wasm_i8x16_make(0, 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1, -1,
-1, -1, -1)
: (N == 9) ? wasm_i8x16_make(0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, -1, -1,
-1, -1, -1)
: (N == 11)
? wasm_i8x16_make(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, -1, -1, -1)
: (N == 13)
? wasm_i8x16_make(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, -1, -1)
: wasm_i8x16_make(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1);
}
template <typename T, size_t N>
HWY_INLINE uint64_t BitsFromMask(const Mask128<T, N> mask) {
return OnlyActive<T, N>(BitsFromMask(hwy::SizeTag<sizeof(T)>(), mask));
}
template <typename T>
HWY_INLINE size_t CountTrue(hwy::SizeTag<1> tag, const Mask128<T> m) {
return PopCount(BitsFromMask(tag, m));
}
template <typename T>
HWY_INLINE size_t CountTrue(hwy::SizeTag<2> tag, const Mask128<T> m) {
return PopCount(BitsFromMask(tag, m));
}
template <typename T>
HWY_INLINE size_t CountTrue(hwy::SizeTag<4> /*tag*/, const Mask128<T> m) {
const __i32x4 var_shift = wasm_i32x4_make(1, 2, 4, 8);
const __i32x4 shifted_bits = wasm_v128_and(m.raw, var_shift);
alignas(16) uint64_t lanes[2];
wasm_v128_store(lanes, shifted_bits);
return PopCount(lanes[0] | lanes[1]);
}
template <typename T>
HWY_INLINE size_t CountTrue(hwy::SizeTag<8> /*tag*/, const Mask128<T> m) {
alignas(16) int64_t lanes[2];
wasm_v128_store(lanes, m.raw);
return static_cast<size_t>(-(lanes[0] + lanes[1]));
}
} // namespace detail
// `p` points to at least 8 writable bytes.
template <typename T, size_t N>
HWY_API size_t StoreMaskBits(const Simd<T, N, 0> /* tag */,
const Mask128<T, N> mask, uint8_t* bits) {
const uint64_t mask_bits = detail::BitsFromMask(mask);
const size_t kNumBytes = (N + 7) / 8;
CopyBytes<kNumBytes>(&mask_bits, bits);
return kNumBytes;
}
template <typename T, size_t N>
HWY_API size_t CountTrue(const Simd<T, N, 0> /* tag */, const Mask128<T> m) {
return detail::CountTrue(hwy::SizeTag<sizeof(T)>(), m);
}
// Partial vector
template <typename T, size_t N, HWY_IF_LE64(T, N)>
HWY_API size_t CountTrue(const Simd<T, N, 0> d, const Mask128<T, N> m) {
// Ensure all undefined bytes are 0.
const Mask128<T, N> mask{detail::BytesAbove<N * sizeof(T)>()};
return CountTrue(d, Mask128<T>{AndNot(mask, m).raw});
}
// Full vector
template <typename T>
HWY_API bool AllFalse(const Full128<T> d, const Mask128<T> m) {
#if 0
// Casting followed by wasm_i8x16_any_true results in wasm error:
// i32.eqz[0] expected type i32, found i8x16.popcnt of type s128
const auto v8 = BitCast(Full128<int8_t>(), VecFromMask(d, m));
return !wasm_i8x16_any_true(v8.raw);
#else
(void)d;
return (wasm_i64x2_extract_lane(m.raw, 0) |
wasm_i64x2_extract_lane(m.raw, 1)) == 0;
#endif
}
// Full vector
namespace detail {
template <typename T>
HWY_INLINE bool AllTrue(hwy::SizeTag<1> /*tag*/, const Mask128<T> m) {
return wasm_i8x16_all_true(m.raw);
}
template <typename T>
HWY_INLINE bool AllTrue(hwy::SizeTag<2> /*tag*/, const Mask128<T> m) {
return wasm_i16x8_all_true(m.raw);
}
template <typename T>
HWY_INLINE bool AllTrue(hwy::SizeTag<4> /*tag*/, const Mask128<T> m) {
return wasm_i32x4_all_true(m.raw);
}
template <typename T>
HWY_INLINE bool AllTrue(hwy::SizeTag<8> /*tag*/, const Mask128<T> m) {
return wasm_i64x2_all_true(m.raw);
}
} // namespace detail
template <typename T, size_t N>
HWY_API bool AllTrue(const Simd<T, N, 0> /* tag */, const Mask128<T> m) {
return detail::AllTrue(hwy::SizeTag<sizeof(T)>(), m);
}
// Partial vectors
template <typename T, size_t N, HWY_IF_LE64(T, N)>
HWY_API bool AllFalse(Simd<T, N, 0> /* tag */, const Mask128<T, N> m) {
// Ensure all undefined bytes are 0.
const Mask128<T, N> mask{detail::BytesAbove<N * sizeof(T)>()};
return AllFalse(Full128<T>(), Mask128<T>{AndNot(mask, m).raw});
}
template <typename T, size_t N, HWY_IF_LE64(T, N)>
HWY_API bool AllTrue(const Simd<T, N, 0> /* d */, const Mask128<T, N> m) {
// Ensure all undefined bytes are FF.
const Mask128<T, N> mask{detail::BytesAbove<N * sizeof(T)>()};
return AllTrue(Full128<T>(), Mask128<T>{Or(mask, m).raw});
}
template <typename T, size_t N>
HWY_API intptr_t FindFirstTrue(const Simd<T, N, 0> /* tag */,
const Mask128<T, N> mask) {
const uint64_t bits = detail::BitsFromMask(mask);
return bits ? static_cast<intptr_t>(Num0BitsBelowLS1Bit_Nonzero64(bits)) : -1;
}
// ------------------------------ Compress
namespace detail {
template <typename T, size_t N>
HWY_INLINE Vec128<T, N> Idx16x8FromBits(const uint64_t mask_bits) {
HWY_DASSERT(mask_bits < 256);
const Simd<T, N, 0> d;
const Rebind<uint8_t, decltype(d)> d8;
const Simd<uint16_t, N, 0> du;
// We need byte indices for TableLookupBytes (one vector's worth for each of
// 256 combinations of 8 mask bits). Loading them directly requires 4 KiB. We
// can instead store lane indices and convert to byte indices (2*lane + 0..1),
// with the doubling baked into the table. Unpacking nibbles is likely more
// costly than the higher cache footprint from storing bytes.
alignas(16) constexpr uint8_t table[256 * 8] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0,
0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0,
0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 2, 4, 0, 0, 0, 0,
0, 0, 0, 2, 4, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0, 0, 0, 0,
0, 6, 0, 0, 0, 0, 0, 0, 2, 6, 0, 0, 0, 0, 0, 0, 0, 2,
6, 0, 0, 0, 0, 0, 4, 6, 0, 0, 0, 0, 0, 0, 0, 4, 6, 0,
0, 0, 0, 0, 2, 4, 6, 0, 0, 0, 0, 0, 0, 2, 4, 6, 0, 0,
0, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 8, 0, 0, 0, 0, 0, 0,
2, 8, 0, 0, 0, 0, 0, 0, 0, 2, 8, 0, 0, 0, 0, 0, 4, 8,
0, 0, 0, 0, 0, 0, 0, 4, 8, 0, 0, 0, 0, 0, 2, 4, 8, 0,
0, 0, 0, 0, 0, 2, 4, 8, 0, 0, 0, 0, 6, 8, 0, 0, 0, 0,
0, 0, 0, 6, 8, 0, 0, 0, 0, 0, 2, 6, 8, 0, 0, 0, 0, 0,
0, 2, 6, 8, 0, 0, 0, 0, 4, 6, 8, 0, 0, 0, 0, 0, 0, 4,
6, 8, 0, 0, 0, 0, 2, 4, 6, 8, 0, 0, 0, 0, 0, 2, 4, 6,
8, 0, 0, 0, 10, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 0, 0, 0,
0, 0, 2, 10, 0, 0, 0, 0, 0, 0, 0, 2, 10, 0, 0, 0, 0, 0,
4, 10, 0, 0, 0, 0, 0, 0, 0, 4, 10, 0, 0, 0, 0, 0, 2, 4,
10, 0, 0, 0, 0, 0, 0, 2, 4, 10, 0, 0, 0, 0, 6, 10, 0, 0,
0, 0, 0, 0, 0, 6, 10, 0, 0, 0, 0, 0, 2, 6, 10, 0, 0, 0,
0, 0, 0, 2, 6, 10, 0, 0, 0, 0, 4, 6, 10, 0, 0, 0, 0, 0,
0, 4, 6, 10, 0, 0, 0, 0, 2, 4, 6, 10, 0, 0, 0, 0, 0, 2,
4, 6, 10, 0, 0, 0, 8, 10, 0, 0, 0, 0, 0, 0, 0, 8, 10, 0,
0, 0, 0, 0, 2, 8, 10, 0, 0, 0, 0, 0, 0, 2, 8, 10, 0, 0,
0, 0, 4, 8, 10, 0, 0, 0, 0, 0, 0, 4, 8, 10, 0, 0, 0, 0,
2, 4, 8, 10, 0, 0, 0, 0, 0, 2, 4, 8, 10, 0, 0, 0, 6, 8,
10, 0, 0, 0, 0, 0, 0, 6, 8, 10, 0, 0, 0, 0, 2, 6, 8, 10,
0, 0, 0, 0, 0, 2, 6, 8, 10, 0, 0, 0, 4, 6, 8, 10, 0, 0,
0, 0, 0, 4, 6, 8, 10, 0, 0, 0, 2, 4, 6, 8, 10, 0, 0, 0,
0, 2, 4, 6, 8, 10, 0, 0, 12, 0, 0, 0, 0, 0, 0, 0, 0, 12,
0, 0, 0, 0, 0, 0, 2, 12, 0, 0, 0, 0, 0, 0, 0, 2, 12, 0,
0, 0, 0, 0, 4, 12, 0, 0, 0, 0, 0, 0, 0, 4, 12, 0, 0, 0,
0, 0, 2, 4, 12, 0, 0, 0, 0, 0, 0, 2, 4, 12, 0, 0, 0, 0,
6, 12, 0, 0, 0, 0, 0, 0, 0, 6, 12, 0, 0, 0, 0, 0, 2, 6,
12, 0, 0, 0, 0, 0, 0, 2, 6, 12, 0, 0, 0, 0, 4, 6, 12, 0,
0, 0, 0, 0, 0, 4, 6, 12, 0, 0, 0, 0, 2, 4, 6, 12, 0, 0,
0, 0, 0, 2, 4, 6, 12, 0, 0, 0, 8, 12, 0, 0, 0, 0, 0, 0,
0, 8, 12, 0, 0, 0, 0, 0, 2, 8, 12, 0, 0, 0, 0, 0, 0, 2,
8, 12, 0, 0, 0, 0, 4, 8, 12, 0, 0, 0, 0, 0, 0, 4, 8, 12,
0, 0, 0, 0, 2, 4, 8, 12, 0, 0, 0, 0, 0, 2, 4, 8, 12, 0,
0, 0, 6, 8, 12, 0, 0, 0, 0, 0, 0, 6, 8, 12, 0, 0, 0, 0,
2, 6, 8, 12, 0, 0, 0, 0, 0, 2, 6, 8, 12, 0, 0, 0, 4, 6,
8, 12, 0, 0, 0, 0, 0, 4, 6, 8, 12, 0, 0, 0, 2, 4, 6, 8,
12, 0, 0, 0, 0, 2, 4, 6, 8, 12, 0, 0, 10, 12, 0, 0, 0, 0,
0, 0, 0, 10, 12, 0, 0, 0, 0, 0, 2, 10, 12, 0, 0, 0, 0, 0,
0, 2, 10, 12, 0, 0, 0, 0, 4, 10, 12, 0, 0, 0, 0, 0, 0, 4,
10, 12, 0, 0, 0, 0, 2, 4, 10, 12, 0, 0, 0, 0, 0, 2, 4, 10,
12, 0, 0, 0, 6, 10, 12, 0, 0, 0, 0, 0, 0, 6, 10, 12, 0, 0,
0, 0, 2, 6, 10, 12, 0, 0, 0, 0, 0, 2, 6, 10, 12, 0, 0, 0,
4, 6, 10, 12, 0, 0, 0, 0, 0, 4, 6, 10, 12, 0, 0, 0, 2, 4,
6, 10, 12, 0, 0, 0, 0, 2, 4, 6, 10, 12, 0, 0, 8, 10, 12, 0,
0, 0, 0, 0, 0, 8, 10, 12, 0, 0, 0, 0, 2, 8, 10, 12, 0, 0,
0, 0, 0, 2, 8, 10, 12, 0, 0, 0, 4, 8, 10, 12, 0, 0, 0, 0,
0, 4, 8, 10, 12, 0, 0, 0, 2, 4, 8, 10, 12, 0, 0, 0, 0, 2,
4, 8, 10, 12, 0, 0, 6, 8, 10, 12, 0, 0, 0, 0, 0, 6, 8, 10,
12, 0, 0, 0, 2, 6, 8, 10, 12, 0, 0, 0, 0, 2, 6, 8, 10, 12,
0, 0, 4, 6, 8, 10, 12, 0, 0, 0, 0, 4, 6, 8, 10, 12, 0, 0,
2, 4, 6, 8, 10, 12, 0, 0, 0, 2, 4, 6, 8, 10, 12, 0, 14, 0,
0, 0, 0, 0, 0, 0, 0, 14, 0, 0, 0, 0, 0, 0, 2, 14, 0, 0,
0, 0, 0, 0, 0, 2, 14, 0, 0, 0, 0, 0, 4, 14, 0, 0, 0, 0,
0, 0, 0, 4, 14, 0, 0, 0, 0, 0, 2, 4, 14, 0, 0, 0, 0, 0,
0, 2, 4, 14, 0, 0, 0, 0, 6, 14, 0, 0, 0, 0, 0, 0, 0, 6,
14, 0, 0, 0, 0, 0, 2, 6, 14, 0, 0, 0, 0, 0, 0, 2, 6, 14,
0, 0, 0, 0, 4, 6, 14, 0, 0, 0, 0, 0, 0, 4, 6, 14, 0, 0,
0, 0, 2, 4, 6, 14, 0, 0, 0, 0, 0, 2, 4, 6, 14, 0, 0, 0,
8, 14, 0, 0, 0, 0, 0, 0, 0, 8, 14, 0, 0, 0, 0, 0, 2, 8,
14, 0, 0, 0, 0, 0, 0, 2, 8, 14, 0, 0, 0, 0, 4, 8, 14, 0,
0, 0, 0, 0, 0, 4, 8, 14, 0, 0, 0, 0, 2, 4, 8, 14, 0, 0,
0, 0, 0, 2, 4, 8, 14, 0, 0, 0, 6, 8, 14, 0, 0, 0, 0, 0,
0, 6, 8, 14, 0, 0, 0, 0, 2, 6, 8, 14, 0, 0, 0, 0, 0, 2,
6, 8, 14, 0, 0, 0, 4, 6, 8, 14, 0, 0, 0, 0, 0, 4, 6, 8,
14, 0, 0, 0, 2, 4, 6, 8, 14, 0, 0, 0, 0, 2, 4, 6, 8, 14,
0, 0, 10, 14, 0, 0, 0, 0, 0, 0, 0, 10, 14, 0, 0, 0, 0, 0,
2, 10, 14, 0, 0, 0, 0, 0, 0, 2, 10, 14, 0, 0, 0, 0, 4, 10,
14, 0, 0, 0, 0, 0, 0, 4, 10, 14, 0, 0, 0, 0, 2, 4, 10, 14,
0, 0, 0, 0, 0, 2, 4, 10, 14, 0, 0, 0, 6, 10, 14, 0, 0, 0,
0, 0, 0, 6, 10, 14, 0, 0, 0, 0, 2, 6, 10, 14, 0, 0, 0, 0,
0, 2, 6, 10, 14, 0, 0, 0, 4, 6, 10, 14, 0, 0, 0, 0, 0, 4,
6, 10, 14, 0, 0, 0, 2, 4, 6, 10, 14, 0, 0, 0, 0, 2, 4, 6,
10, 14, 0, 0, 8, 10, 14, 0, 0, 0, 0, 0, 0, 8, 10, 14, 0, 0,
0, 0, 2, 8, 10, 14, 0, 0, 0, 0, 0, 2, 8, 10, 14, 0, 0, 0,
4, 8, 10, 14, 0, 0, 0, 0, 0, 4, 8, 10, 14, 0, 0, 0, 2, 4,
8, 10, 14, 0, 0, 0, 0, 2, 4, 8, 10, 14, 0, 0, 6, 8, 10, 14,
0, 0, 0, 0, 0, 6, 8, 10, 14, 0, 0, 0, 2, 6, 8, 10, 14, 0,
0, 0, 0, 2, 6, 8, 10, 14, 0, 0, 4, 6, 8, 10, 14, 0, 0, 0,
0, 4, 6, 8, 10, 14, 0, 0, 2, 4, 6, 8, 10, 14, 0, 0, 0, 2,
4, 6, 8, 10, 14, 0, 12, 14, 0, 0, 0, 0, 0, 0, 0, 12, 14, 0,
0, 0, 0, 0, 2, 12, 14, 0, 0, 0, 0, 0, 0, 2, 12, 14, 0, 0,
0, 0, 4, 12, 14, 0, 0, 0, 0, 0, 0, 4, 12, 14, 0, 0, 0, 0,
2, 4, 12, 14, 0, 0, 0, 0, 0, 2, 4, 12, 14, 0, 0, 0, 6, 12,
14, 0, 0, 0, 0, 0, 0, 6, 12, 14, 0, 0, 0, 0, 2, 6, 12, 14,
0, 0, 0, 0, 0, 2, 6, 12, 14, 0, 0, 0, 4, 6, 12, 14, 0, 0,
0, 0, 0, 4, 6, 12, 14, 0, 0, 0, 2, 4, 6, 12, 14, 0, 0, 0,
0, 2, 4, 6, 12, 14, 0, 0, 8, 12, 14, 0, 0, 0, 0, 0, 0, 8,
12, 14, 0, 0, 0, 0, 2, 8, 12, 14, 0, 0, 0, 0, 0, 2, 8, 12,
14, 0, 0, 0, 4, 8, 12, 14, 0, 0, 0, 0, 0, 4, 8, 12, 14, 0,
0, 0, 2, 4, 8, 12, 14, 0, 0, 0, 0, 2, 4, 8, 12, 14, 0, 0,
6, 8, 12, 14, 0, 0, 0, 0, 0, 6, 8, 12, 14, 0, 0, 0, 2, 6,
8, 12, 14, 0, 0, 0, 0, 2, 6, 8, 12, 14, 0, 0, 4, 6, 8, 12,
14, 0, 0, 0, 0, 4, 6, 8, 12, 14, 0, 0, 2, 4, 6, 8, 12, 14,
0, 0, 0, 2, 4, 6, 8, 12, 14, 0, 10, 12, 14, 0, 0, 0, 0, 0,
0, 10, 12, 14, 0, 0, 0, 0, 2, 10, 12, 14, 0, 0, 0, 0, 0, 2,
10, 12, 14, 0, 0, 0, 4, 10, 12, 14, 0, 0, 0, 0, 0, 4, 10, 12,
14, 0, 0, 0, 2, 4, 10, 12, 14, 0, 0, 0, 0, 2, 4, 10, 12, 14,
0, 0, 6, 10, 12, 14, 0, 0, 0, 0, 0, 6, 10, 12, 14, 0, 0, 0,
2, 6, 10, 12, 14, 0, 0, 0, 0, 2, 6, 10, 12, 14, 0, 0, 4, 6,
10, 12, 14, 0, 0, 0, 0, 4, 6, 10, 12, 14, 0, 0, 2, 4, 6, 10,
12, 14, 0, 0, 0, 2, 4, 6, 10, 12, 14, 0, 8, 10, 12, 14, 0, 0,
0, 0, 0, 8, 10, 12, 14, 0, 0, 0, 2, 8, 10, 12, 14, 0, 0, 0,
0, 2, 8, 10, 12, 14, 0, 0, 4, 8, 10, 12, 14, 0, 0, 0, 0, 4,
8, 10, 12, 14, 0, 0, 2, 4, 8, 10, 12, 14, 0, 0, 0, 2, 4, 8,
10, 12, 14, 0, 6, 8, 10, 12, 14, 0, 0, 0, 0, 6, 8, 10, 12, 14,
0, 0, 2, 6, 8, 10, 12, 14, 0, 0, 0, 2, 6, 8, 10, 12, 14, 0,
4, 6, 8, 10, 12, 14, 0, 0, 0, 4, 6, 8, 10, 12, 14, 0, 2, 4,
6, 8, 10, 12, 14, 0, 0, 2, 4, 6, 8, 10, 12, 14};
const Vec128<uint8_t, 2 * N> byte_idx{Load(d8, table + mask_bits * 8).raw};
const Vec128<uint16_t, N> pairs = ZipLower(byte_idx, byte_idx);
return BitCast(d, pairs + Set(du, 0x0100));
}
template <typename T, size_t N>
HWY_INLINE Vec128<T, N> Idx32x4FromBits(const uint64_t mask_bits) {
HWY_DASSERT(mask_bits < 16);
// There are only 4 lanes, so we can afford to load the index vector directly.
alignas(16) constexpr uint8_t packed_array[16 * 16] = {
0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, //
0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, //
4, 5, 6, 7, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, //
0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 0, 1, 2, 3, //
8, 9, 10, 11, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, //
0, 1, 2, 3, 8, 9, 10, 11, 0, 1, 2, 3, 0, 1, 2, 3, //
4, 5, 6, 7, 8, 9, 10, 11, 0, 1, 2, 3, 0, 1, 2, 3, //
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 0, 1, 2, 3, //
12, 13, 14, 15, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3, //
0, 1, 2, 3, 12, 13, 14, 15, 0, 1, 2, 3, 0, 1, 2, 3, //
4, 5, 6, 7, 12, 13, 14, 15, 0, 1, 2, 3, 0, 1, 2, 3, //
0, 1, 2, 3, 4, 5, 6, 7, 12, 13, 14, 15, 0, 1, 2, 3, //
8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 3, 0, 1, 2, 3, //
0, 1, 2, 3, 8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 3, //
4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 3, //
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
const Simd<T, N, 0> d;
const Repartition<uint8_t, decltype(d)> d8;
return BitCast(d, Load(d8, packed_array + 16 * mask_bits));
}
template <typename T, size_t N>
HWY_INLINE Vec128<T, N> Idx64x2FromBits(const uint64_t mask_bits) {
HWY_DASSERT(mask_bits < 4);
// There are only 2 lanes, so we can afford to load the index vector directly.
alignas(16) constexpr uint8_t packed_array[4 * 16] = {
0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, //
0, 1, 2, 3, 4, 5, 6, 7, 0, 1, 2, 3, 4, 5, 6, 7, //
8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7, //
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
const Simd<T, N, 0> d;
const Repartition<uint8_t, decltype(d)> d8;
return BitCast(d, Load(d8, packed_array + 16 * mask_bits));
}
// Helper functions called by both Compress and CompressStore - avoids a
// redundant BitsFromMask in the latter.
template <typename T, size_t N>
HWY_INLINE Vec128<T, N> Compress(hwy::SizeTag<2> /*tag*/, Vec128<T, N> v,
const uint64_t mask_bits) {
const auto idx = detail::Idx16x8FromBits<T, N>(mask_bits);
const DFromV<decltype(v)> d;
const RebindToSigned<decltype(d)> di;
return BitCast(d, TableLookupBytes(BitCast(di, v), BitCast(di, idx)));
}
template <typename T, size_t N>
HWY_INLINE Vec128<T, N> Compress(hwy::SizeTag<4> /*tag*/, Vec128<T, N> v,
const uint64_t mask_bits) {
const auto idx = detail::Idx32x4FromBits<T, N>(mask_bits);
const DFromV<decltype(v)> d;
const RebindToSigned<decltype(d)> di;
return BitCast(d, TableLookupBytes(BitCast(di, v), BitCast(di, idx)));
}
template <typename T, size_t N>
HWY_INLINE Vec128<T, N> Compress(hwy::SizeTag<8> /*tag*/, Vec128<T, N> v,
const uint64_t mask_bits) {
const auto idx = detail::Idx64x2FromBits<T, N>(mask_bits);
const DFromV<decltype(v)> d;
const RebindToSigned<decltype(d)> di;
return BitCast(d, TableLookupBytes(BitCast(di, v), BitCast(di, idx)));
}
} // namespace detail
template <typename T, size_t N>
HWY_API Vec128<T, N> Compress(Vec128<T, N> v, const Mask128<T, N> mask) {
const uint64_t mask_bits = detail::BitsFromMask(mask);
return detail::Compress(hwy::SizeTag<sizeof(T)>(), v, mask_bits);
}
// ------------------------------ CompressBits
template <typename T, size_t N>
HWY_API Vec128<T, N> CompressBits(Vec128<T, N> v,
const uint8_t* HWY_RESTRICT bits) {
uint64_t mask_bits = 0;
constexpr size_t kNumBytes = (N + 7) / 8;
CopyBytes<kNumBytes>(bits, &mask_bits);
if (N < 8) {
mask_bits &= (1ull << N) - 1;
}
return detail::Compress(hwy::SizeTag<sizeof(T)>(), v, mask_bits);
}
// ------------------------------ CompressStore
template <typename T, size_t N>
HWY_API size_t CompressStore(Vec128<T, N> v, const Mask128<T, N> mask,
Simd<T, N, 0> d, T* HWY_RESTRICT unaligned) {
const uint64_t mask_bits = detail::BitsFromMask(mask);
const auto c = detail::Compress(hwy::SizeTag<sizeof(T)>(), v, mask_bits);
StoreU(c, d, unaligned);
return PopCount(mask_bits);
}
// ------------------------------ CompressBlendedStore
template <typename T, size_t N>
HWY_API size_t CompressBlendedStore(Vec128<T, N> v, Mask128<T, N> m,
Simd<T, N, 0> d,
T* HWY_RESTRICT unaligned) {
const RebindToUnsigned<decltype(d)> du; // so we can support fp16/bf16
using TU = TFromD<decltype(du)>;
const uint64_t mask_bits = detail::BitsFromMask(m);
const size_t count = PopCount(mask_bits);
const Mask128<TU, N> store_mask = FirstN(du, count);
const Vec128<TU, N> compressed =
detail::Compress(hwy::SizeTag<sizeof(T)>(), BitCast(du, v), mask_bits);
const Vec128<TU, N> prev = BitCast(du, LoadU(d, unaligned));
StoreU(BitCast(d, IfThenElse(store_mask, compressed, prev)), d, unaligned);
return count;
}
// ------------------------------ CompressBitsStore
template <typename T, size_t N>
HWY_API size_t CompressBitsStore(Vec128<T, N> v,
const uint8_t* HWY_RESTRICT bits,
Simd<T, N, 0> d, T* HWY_RESTRICT unaligned) {
uint64_t mask_bits = 0;
constexpr size_t kNumBytes = (N + 7) / 8;
CopyBytes<kNumBytes>(bits, &mask_bits);
if (N < 8) {
mask_bits &= (1ull << N) - 1;
}
const auto c = detail::Compress(hwy::SizeTag<sizeof(T)>(), v, mask_bits);
StoreU(c, d, unaligned);
return PopCount(mask_bits);
}
// ------------------------------ StoreInterleaved3 (CombineShiftRightBytes,
// TableLookupBytes)
// 128 bits
HWY_API void StoreInterleaved3(const Vec128<uint8_t> a, const Vec128<uint8_t> b,
const Vec128<uint8_t> c, Full128<uint8_t> d,
uint8_t* HWY_RESTRICT unaligned) {
const auto k5 = Set(d, 5);
const auto k6 = Set(d, 6);
// Shuffle (a,b,c) vector bytes to (MSB on left): r5, bgr[4:0].
// 0x80 so lanes to be filled from other vectors are 0 for blending.
alignas(16) static constexpr uint8_t tbl_r0[16] = {
0, 0x80, 0x80, 1, 0x80, 0x80, 2, 0x80, 0x80, //
3, 0x80, 0x80, 4, 0x80, 0x80, 5};
alignas(16) static constexpr uint8_t tbl_g0[16] = {
0x80, 0, 0x80, 0x80, 1, 0x80, //
0x80, 2, 0x80, 0x80, 3, 0x80, 0x80, 4, 0x80, 0x80};
const auto shuf_r0 = Load(d, tbl_r0);
const auto shuf_g0 = Load(d, tbl_g0); // cannot reuse r0 due to 5 in MSB
const auto shuf_b0 = CombineShiftRightBytes<15>(d, shuf_g0, shuf_g0);
const auto r0 = TableLookupBytes(a, shuf_r0); // 5..4..3..2..1..0
const auto g0 = TableLookupBytes(b, shuf_g0); // ..4..3..2..1..0.
const auto b0 = TableLookupBytes(c, shuf_b0); // .4..3..2..1..0..
const auto int0 = r0 | g0 | b0;
StoreU(int0, d, unaligned + 0 * 16);
// Second vector: g10,r10, bgr[9:6], b5,g5
const auto shuf_r1 = shuf_b0 + k6; // .A..9..8..7..6..
const auto shuf_g1 = shuf_r0 + k5; // A..9..8..7..6..5
const auto shuf_b1 = shuf_g0 + k5; // ..9..8..7..6..5.
const auto r1 = TableLookupBytes(a, shuf_r1);
const auto g1 = TableLookupBytes(b, shuf_g1);
const auto b1 = TableLookupBytes(c, shuf_b1);
const auto int1 = r1 | g1 | b1;
StoreU(int1, d, unaligned + 1 * 16);
// Third vector: bgr[15:11], b10
const auto shuf_r2 = shuf_b1 + k6; // ..F..E..D..C..B.
const auto shuf_g2 = shuf_r1 + k5; // .F..E..D..C..B..
const auto shuf_b2 = shuf_g1 + k5; // F..E..D..C..B..A
const auto r2 = TableLookupBytes(a, shuf_r2);
const auto g2 = TableLookupBytes(b, shuf_g2);
const auto b2 = TableLookupBytes(c, shuf_b2);
const auto int2 = r2 | g2 | b2;
StoreU(int2, d, unaligned + 2 * 16);
}
// 64 bits
HWY_API void StoreInterleaved3(const Vec128<uint8_t, 8> a,
const Vec128<uint8_t, 8> b,
const Vec128<uint8_t, 8> c, Full64<uint8_t> d,
uint8_t* HWY_RESTRICT unaligned) {
// Use full vectors for the shuffles and first result.
const Full128<uint8_t> d_full;
const auto k5 = Set(d_full, 5);
const auto k6 = Set(d_full, 6);
const Vec128<uint8_t> full_a{a.raw};
const Vec128<uint8_t> full_b{b.raw};
const Vec128<uint8_t> full_c{c.raw};
// Shuffle (a,b,c) vector bytes to (MSB on left): r5, bgr[4:0].
// 0x80 so lanes to be filled from other vectors are 0 for blending.
alignas(16) static constexpr uint8_t tbl_r0[16] = {
0, 0x80, 0x80, 1, 0x80, 0x80, 2, 0x80, 0x80, //
3, 0x80, 0x80, 4, 0x80, 0x80, 5};
alignas(16) static constexpr uint8_t tbl_g0[16] = {
0x80, 0, 0x80, 0x80, 1, 0x80, //
0x80, 2, 0x80, 0x80, 3, 0x80, 0x80, 4, 0x80, 0x80};
const auto shuf_r0 = Load(d_full, tbl_r0);
const auto shuf_g0 = Load(d_full, tbl_g0); // cannot reuse r0 due to 5 in MSB
const auto shuf_b0 = CombineShiftRightBytes<15>(d_full, shuf_g0, shuf_g0);
const auto r0 = TableLookupBytes(full_a, shuf_r0); // 5..4..3..2..1..0
const auto g0 = TableLookupBytes(full_b, shuf_g0); // ..4..3..2..1..0.
const auto b0 = TableLookupBytes(full_c, shuf_b0); // .4..3..2..1..0..
const auto int0 = r0 | g0 | b0;
StoreU(int0, d_full, unaligned + 0 * 16);
// Second (HALF) vector: bgr[7:6], b5,g5
const auto shuf_r1 = shuf_b0 + k6; // ..7..6..
const auto shuf_g1 = shuf_r0 + k5; // .7..6..5
const auto shuf_b1 = shuf_g0 + k5; // 7..6..5.
const auto r1 = TableLookupBytes(full_a, shuf_r1);
const auto g1 = TableLookupBytes(full_b, shuf_g1);
const auto b1 = TableLookupBytes(full_c, shuf_b1);
const decltype(Zero(d)) int1{(r1 | g1 | b1).raw};
StoreU(int1, d, unaligned + 1 * 16);
}
// <= 32 bits
template <size_t N, HWY_IF_LE32(uint8_t, N)>
HWY_API void StoreInterleaved3(const Vec128<uint8_t, N> a,
const Vec128<uint8_t, N> b,
const Vec128<uint8_t, N> c,
Simd<uint8_t, N, 0> /*tag*/,
uint8_t* HWY_RESTRICT unaligned) {
// Use full vectors for the shuffles and result.
const Full128<uint8_t> d_full;
const Vec128<uint8_t> full_a{a.raw};
const Vec128<uint8_t> full_b{b.raw};
const Vec128<uint8_t> full_c{c.raw};
// Shuffle (a,b,c) vector bytes to bgr[3:0].
// 0x80 so lanes to be filled from other vectors are 0 for blending.
alignas(16) static constexpr uint8_t tbl_r0[16] = {
0, 0x80, 0x80, 1, 0x80, 0x80, 2, 0x80, 0x80, 3, 0x80, 0x80, //
0x80, 0x80, 0x80, 0x80};
const auto shuf_r0 = Load(d_full, tbl_r0);
const auto shuf_g0 = CombineShiftRightBytes<15>(d_full, shuf_r0, shuf_r0);
const auto shuf_b0 = CombineShiftRightBytes<14>(d_full, shuf_r0, shuf_r0);
const auto r0 = TableLookupBytes(full_a, shuf_r0); // ......3..2..1..0
const auto g0 = TableLookupBytes(full_b, shuf_g0); // .....3..2..1..0.
const auto b0 = TableLookupBytes(full_c, shuf_b0); // ....3..2..1..0..
const auto int0 = r0 | g0 | b0;
alignas(16) uint8_t buf[16];
StoreU(int0, d_full, buf);
CopyBytes<N * 3>(buf, unaligned);
}
// ------------------------------ StoreInterleaved4
// 128 bits
HWY_API void StoreInterleaved4(const Vec128<uint8_t> v0,
const Vec128<uint8_t> v1,
const Vec128<uint8_t> v2,
const Vec128<uint8_t> v3, Full128<uint8_t> d8,
uint8_t* HWY_RESTRICT unaligned) {
const RepartitionToWide<decltype(d8)> d16;
const RepartitionToWide<decltype(d16)> d32;
// let a,b,c,d denote v0..3.
const auto ba0 = ZipLower(d16, v0, v1); // b7 a7 .. b0 a0
const auto dc0 = ZipLower(d16, v2, v3); // d7 c7 .. d0 c0
const auto ba8 = ZipUpper(d16, v0, v1);
const auto dc8 = ZipUpper(d16, v2, v3);
const auto dcba_0 = ZipLower(d32, ba0, dc0); // d..a3 d..a0
const auto dcba_4 = ZipUpper(d32, ba0, dc0); // d..a7 d..a4
const auto dcba_8 = ZipLower(d32, ba8, dc8); // d..aB d..a8
const auto dcba_C = ZipUpper(d32, ba8, dc8); // d..aF d..aC
StoreU(BitCast(d8, dcba_0), d8, unaligned + 0 * 16);
StoreU(BitCast(d8, dcba_4), d8, unaligned + 1 * 16);
StoreU(BitCast(d8, dcba_8), d8, unaligned + 2 * 16);
StoreU(BitCast(d8, dcba_C), d8, unaligned + 3 * 16);
}
// 64 bits
HWY_API void StoreInterleaved4(const Vec128<uint8_t, 8> in0,
const Vec128<uint8_t, 8> in1,
const Vec128<uint8_t, 8> in2,
const Vec128<uint8_t, 8> in3,
Full64<uint8_t> /* tag */,
uint8_t* HWY_RESTRICT unaligned) {
// Use full vectors to reduce the number of stores.
const Full128<uint8_t> d_full8;
const RepartitionToWide<decltype(d_full8)> d16;
const RepartitionToWide<decltype(d16)> d32;
const Vec128<uint8_t> v0{in0.raw};
const Vec128<uint8_t> v1{in1.raw};
const Vec128<uint8_t> v2{in2.raw};
const Vec128<uint8_t> v3{in3.raw};
// let a,b,c,d denote v0..3.
const auto ba0 = ZipLower(d16, v0, v1); // b7 a7 .. b0 a0
const auto dc0 = ZipLower(d16, v2, v3); // d7 c7 .. d0 c0
const auto dcba_0 = ZipLower(d32, ba0, dc0); // d..a3 d..a0
const auto dcba_4 = ZipUpper(d32, ba0, dc0); // d..a7 d..a4
StoreU(BitCast(d_full8, dcba_0), d_full8, unaligned + 0 * 16);
StoreU(BitCast(d_full8, dcba_4), d_full8, unaligned + 1 * 16);
}
// <= 32 bits
template <size_t N, HWY_IF_LE32(uint8_t, N)>
HWY_API void StoreInterleaved4(const Vec128<uint8_t, N> in0,
const Vec128<uint8_t, N> in1,
const Vec128<uint8_t, N> in2,
const Vec128<uint8_t, N> in3,
Simd<uint8_t, N, 0> /*tag*/,
uint8_t* HWY_RESTRICT unaligned) {
// Use full vectors to reduce the number of stores.
const Full128<uint8_t> d_full8;
const RepartitionToWide<decltype(d_full8)> d16;
const RepartitionToWide<decltype(d16)> d32;
const Vec128<uint8_t> v0{in0.raw};
const Vec128<uint8_t> v1{in1.raw};
const Vec128<uint8_t> v2{in2.raw};
const Vec128<uint8_t> v3{in3.raw};
// let a,b,c,d denote v0..3.
const auto ba0 = ZipLower(d16, v0, v1); // b3 a3 .. b0 a0
const auto dc0 = ZipLower(d16, v2, v3); // d3 c3 .. d0 c0
const auto dcba_0 = ZipLower(d32, ba0, dc0); // d..a3 d..a0
alignas(16) uint8_t buf[16];
StoreU(BitCast(d_full8, dcba_0), d_full8, buf);
CopyBytes<4 * N>(buf, unaligned);
}
// ------------------------------ MulEven/Odd (Load)
HWY_INLINE Vec128<uint64_t> MulEven(const Vec128<uint64_t> a,
const Vec128<uint64_t> b) {
alignas(16) uint64_t mul[2];
mul[0] =
Mul128(static_cast<uint64_t>(wasm_i64x2_extract_lane(a.raw, 0)),
static_cast<uint64_t>(wasm_i64x2_extract_lane(b.raw, 0)), &mul[1]);
return Load(Full128<uint64_t>(), mul);
}
HWY_INLINE Vec128<uint64_t> MulOdd(const Vec128<uint64_t> a,
const Vec128<uint64_t> b) {
alignas(16) uint64_t mul[2];
mul[0] =
Mul128(static_cast<uint64_t>(wasm_i64x2_extract_lane(a.raw, 1)),
static_cast<uint64_t>(wasm_i64x2_extract_lane(b.raw, 1)), &mul[1]);
return Load(Full128<uint64_t>(), mul);
}
// ------------------------------ ReorderWidenMulAccumulate (MulAdd, ZipLower)
template <size_t N>
HWY_API Vec128<float, N> ReorderWidenMulAccumulate(Simd<float, N, 0> df32,
Vec128<bfloat16_t, 2 * N> a,
Vec128<bfloat16_t, 2 * N> b,
const Vec128<float, N> sum0,
Vec128<float, N>& sum1) {
const Repartition<uint16_t, decltype(df32)> du16;
const RebindToUnsigned<decltype(df32)> du32;
const Vec128<uint16_t, 2 * N> zero = Zero(du16);
const Vec128<uint32_t, N> a0 = ZipLower(du32, zero, BitCast(du16, a));
const Vec128<uint32_t, N> a1 = ZipUpper(du32, zero, BitCast(du16, a));
const Vec128<uint32_t, N> b0 = ZipLower(du32, zero, BitCast(du16, b));
const Vec128<uint32_t, N> b1 = ZipUpper(du32, zero, BitCast(du16, b));
sum1 = MulAdd(BitCast(df32, a1), BitCast(df32, b1), sum1);
return MulAdd(BitCast(df32, a0), BitCast(df32, b0), sum0);
}
// ------------------------------ Reductions
namespace detail {
// N=1 for any T: no-op
template <typename T>
HWY_INLINE Vec128<T, 1> SumOfLanes(hwy::SizeTag<sizeof(T)> /* tag */,
const Vec128<T, 1> v) {
return v;
}
template <typename T>
HWY_INLINE Vec128<T, 1> MinOfLanes(hwy::SizeTag<sizeof(T)> /* tag */,
const Vec128<T, 1> v) {
return v;
}
template <typename T>
HWY_INLINE Vec128<T, 1> MaxOfLanes(hwy::SizeTag<sizeof(T)> /* tag */,
const Vec128<T, 1> v) {
return v;
}
// u32/i32/f32:
// N=2
template <typename T>
HWY_INLINE Vec128<T, 2> SumOfLanes(hwy::SizeTag<4> /* tag */,
const Vec128<T, 2> v10) {
return v10 + Vec128<T, 2>{Shuffle2301(Vec128<T>{v10.raw}).raw};
}
template <typename T>
HWY_INLINE Vec128<T, 2> MinOfLanes(hwy::SizeTag<4> /* tag */,
const Vec128<T, 2> v10) {
return Min(v10, Vec128<T, 2>{Shuffle2301(Vec128<T>{v10.raw}).raw});
}
template <typename T>
HWY_INLINE Vec128<T, 2> MaxOfLanes(hwy::SizeTag<4> /* tag */,
const Vec128<T, 2> v10) {
return Max(v10, Vec128<T, 2>{Shuffle2301(Vec128<T>{v10.raw}).raw});
}
// N=4 (full)
template <typename T>
HWY_INLINE Vec128<T> SumOfLanes(hwy::SizeTag<4> /* tag */,
const Vec128<T> v3210) {
const Vec128<T> v1032 = Shuffle1032(v3210);
const Vec128<T> v31_20_31_20 = v3210 + v1032;
const Vec128<T> v20_31_20_31 = Shuffle0321(v31_20_31_20);
return v20_31_20_31 + v31_20_31_20;
}
template <typename T>
HWY_INLINE Vec128<T> MinOfLanes(hwy::SizeTag<4> /* tag */,
const Vec128<T> v3210) {
const Vec128<T> v1032 = Shuffle1032(v3210);
const Vec128<T> v31_20_31_20 = Min(v3210, v1032);
const Vec128<T> v20_31_20_31 = Shuffle0321(v31_20_31_20);
return Min(v20_31_20_31, v31_20_31_20);
}
template <typename T>
HWY_INLINE Vec128<T> MaxOfLanes(hwy::SizeTag<4> /* tag */,
const Vec128<T> v3210) {
const Vec128<T> v1032 = Shuffle1032(v3210);
const Vec128<T> v31_20_31_20 = Max(v3210, v1032);
const Vec128<T> v20_31_20_31 = Shuffle0321(v31_20_31_20);
return Max(v20_31_20_31, v31_20_31_20);
}
// u64/i64/f64:
// N=2 (full)
template <typename T>
HWY_INLINE Vec128<T> SumOfLanes(hwy::SizeTag<8> /* tag */,
const Vec128<T> v10) {
const Vec128<T> v01 = Shuffle01(v10);
return v10 + v01;
}
template <typename T>
HWY_INLINE Vec128<T> MinOfLanes(hwy::SizeTag<8> /* tag */,
const Vec128<T> v10) {
const Vec128<T> v01 = Shuffle01(v10);
return Min(v10, v01);
}
template <typename T>
HWY_INLINE Vec128<T> MaxOfLanes(hwy::SizeTag<8> /* tag */,
const Vec128<T> v10) {
const Vec128<T> v01 = Shuffle01(v10);
return Max(v10, v01);
}
// u16/i16
template <typename T, size_t N, HWY_IF_LANE_SIZE(T, 2), HWY_IF_GE32(T, N)>
HWY_API Vec128<T, N> MinOfLanes(hwy::SizeTag<2> /* tag */, Vec128<T, N> v) {
const DFromV<decltype(v)> d;
const Repartition<int32_t, decltype(d)> d32;
const auto even = And(BitCast(d32, v), Set(d32, 0xFFFF));
const auto odd = ShiftRight<16>(BitCast(d32, v));
const auto min = MinOfLanes(d32, Min(even, odd));
// Also broadcast into odd lanes.
return BitCast(d, Or(min, ShiftLeft<16>(min)));
}
template <typename T, size_t N, HWY_IF_LANE_SIZE(T, 2), HWY_IF_GE32(T, N)>
HWY_API Vec128<T, N> MaxOfLanes(hwy::SizeTag<2> /* tag */, Vec128<T, N> v) {
const DFromV<decltype(v)> d;
const Repartition<int32_t, decltype(d)> d32;
const auto even = And(BitCast(d32, v), Set(d32, 0xFFFF));
const auto odd = ShiftRight<16>(BitCast(d32, v));
const auto min = MaxOfLanes(d32, Max(even, odd));
// Also broadcast into odd lanes.
return BitCast(d, Or(min, ShiftLeft<16>(min)));
}
} // namespace detail
// Supported for u/i/f 32/64. Returns the same value in each lane.
template <typename T, size_t N>
HWY_API Vec128<T, N> SumOfLanes(Simd<T, N, 0> /* tag */, const Vec128<T, N> v) {
return detail::SumOfLanes(hwy::SizeTag<sizeof(T)>(), v);
}
template <typename T, size_t N>
HWY_API Vec128<T, N> MinOfLanes(Simd<T, N, 0> /* tag */, const Vec128<T, N> v) {
return detail::MinOfLanes(hwy::SizeTag<sizeof(T)>(), v);
}
template <typename T, size_t N>
HWY_API Vec128<T, N> MaxOfLanes(Simd<T, N, 0> /* tag */, const Vec128<T, N> v) {
return detail::MaxOfLanes(hwy::SizeTag<sizeof(T)>(), v);
}
// ------------------------------ Lt128
namespace detail {
template <size_t kLanes, typename T, size_t N>
Mask128<T, N> ShiftMaskLeft(Mask128<T, N> m) {
return MaskFromVec(ShiftLeftLanes<kLanes>(VecFromMask(Simd<T, N, 0>(), m)));
}
} // namespace detail
template <typename T, size_t N, HWY_IF_LE128(T, N)>
HWY_INLINE Mask128<T, N> Lt128(Simd<T, N, 0> d, Vec128<T, N> a,
Vec128<T, N> b) {
static_assert(!IsSigned<T>() && sizeof(T) == 8, "Use u64");
// Truth table of Eq and Lt for Hi and Lo u64.
// (removed lines with (=H && cH) or (=L && cL) - cannot both be true)
// =H =L cH cL | out = cH | (=H & cL)
// 0 0 0 0 | 0
// 0 0 0 1 | 0
// 0 0 1 0 | 1
// 0 0 1 1 | 1
// 0 1 0 0 | 0
// 0 1 0 1 | 0
// 0 1 1 0 | 1
// 1 0 0 0 | 0
// 1 0 0 1 | 1
// 1 1 0 0 | 0
const Mask128<T, N> eqHL = Eq(a, b);
const Mask128<T, N> ltHL = Lt(a, b);
// We need to bring cL to the upper lane/bit corresponding to cH. Comparing
// the result of InterleaveUpper/Lower requires 9 ops, whereas shifting the
// comparison result leftwards requires only 4.
const Mask128<T, N> ltLx = detail::ShiftMaskLeft<1>(ltHL);
const Mask128<T, N> outHx = Or(ltHL, And(eqHL, ltLx));
const Vec128<T, N> vecHx = VecFromMask(d, outHx);
return MaskFromVec(InterleaveUpper(d, vecHx, vecHx));
}
// ------------------------------ Min128, Max128 (Lt128)
// Without a native OddEven, it seems infeasible to go faster than Lt128.
template <class D>
HWY_INLINE VFromD<D> Min128(D d, const VFromD<D> a, const VFromD<D> b) {
return IfThenElse(Lt128(d, a, b), a, b);
}
template <class D>
HWY_INLINE VFromD<D> Max128(D d, const VFromD<D> a, const VFromD<D> b) {
return IfThenElse(Lt128(d, a, b), b, a);
}
// ================================================== Operator wrapper
template <class V>
HWY_API V Add(V a, V b) {
return a + b;
}
template <class V>
HWY_API V Sub(V a, V b) {
return a - b;
}
template <class V>
HWY_API V Mul(V a, V b) {
return a * b;
}
template <class V>
HWY_API V Div(V a, V b) {
return a / b;
}
template <class V>
V Shl(V a, V b) {
return a << b;
}
template <class V>
V Shr(V a, V b) {
return a >> b;
}
template <class V>
HWY_API auto Eq(V a, V b) -> decltype(a == b) {
return a == b;
}
template <class V>
HWY_API auto Ne(V a, V b) -> decltype(a == b) {
return a != b;
}
template <class V>
HWY_API auto Lt(V a, V b) -> decltype(a == b) {
return a < b;
}
template <class V>
HWY_API auto Gt(V a, V b) -> decltype(a == b) {
return a > b;
}
template <class V>
HWY_API auto Ge(V a, V b) -> decltype(a == b) {
return a >= b;
}
template <class V>
HWY_API auto Le(V a, V b) -> decltype(a == b) {
return a <= b;
}
// NOLINTNEXTLINE(google-readability-namespace-comments)
} // namespace HWY_NAMESPACE
} // namespace hwy
HWY_AFTER_NAMESPACE();
| 38.361061 | 123 | 0.586522 | [
"vector"
] |
459a85dda5dd8e3d9ac626fc9155fd0a545cb897 | 9,823 | h | C | chrome/browser/ui/views/overlay/overlay_window_views.h | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/ui/views/overlay/overlay_window_views.h | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/ui/views/overlay/overlay_window_views.h | mghgroup/Glide-Browser | 6a4c1eaa6632ec55014fee87781c6bbbb92a2af5 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2021-01-05T23:43:46.000Z | 2021-01-07T23:36:34.000Z | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_UI_VIEWS_OVERLAY_OVERLAY_WINDOW_VIEWS_H_
#define CHROME_BROWSER_UI_VIEWS_OVERLAY_OVERLAY_WINDOW_VIEWS_H_
#include "content/public/browser/overlay_window.h"
#include "base/timer/timer.h"
#include "ui/gfx/geometry/size.h"
#include "ui/views/controls/button/button.h"
#include "ui/views/widget/widget.h"
#if defined(OS_CHROMEOS)
#include "ash/public/cpp/rounded_corner_decorator.h"
#endif
namespace views {
class BackToTabImageButton;
class CloseImageButton;
class PlaybackImageButton;
class ResizeHandleButton;
class SkipAdLabelButton;
class TrackImageButton;
} // namespace views
// The Chrome desktop implementation of OverlayWindow. This will only be
// implemented in views, which will support all desktop platforms.
class OverlayWindowViews : public content::OverlayWindow,
public views::ButtonListener,
public views::Widget {
public:
static std::unique_ptr<content::OverlayWindow> Create(
content::PictureInPictureWindowController* controller);
~OverlayWindowViews() override;
enum class WindowQuadrant { kBottomLeft, kBottomRight, kTopLeft, kTopRight };
// OverlayWindow:
bool IsActive() override;
void Close() override;
void ShowInactive() override;
void Hide() override;
bool IsVisible() override;
bool IsAlwaysOnTop() override;
gfx::Rect GetBounds() override;
void UpdateVideoSize(const gfx::Size& natural_size) override;
void SetPlaybackState(PlaybackState playback_state) override;
void SetPlayPauseButtonVisibility(bool is_visible) override;
void SetSkipAdButtonVisibility(bool is_visible) override;
void SetNextTrackButtonVisibility(bool is_visible) override;
void SetPreviousTrackButtonVisibility(bool is_visible) override;
void SetSurfaceId(const viz::SurfaceId& surface_id) override;
// views::Widget:
bool IsActive() const override;
bool IsVisible() const override;
void OnNativeBlur() override;
void OnNativeWidgetDestroyed() override;
gfx::Size GetMinimumSize() const override;
gfx::Size GetMaximumSize() const override;
void OnNativeWidgetMove() override;
void OnNativeWidgetSizeChanged(const gfx::Size& new_size) override;
void OnNativeWidgetWorkspaceChanged() override;
void OnKeyEvent(ui::KeyEvent* event) override;
void OnMouseEvent(ui::MouseEvent* event) override;
void OnGestureEvent(ui::GestureEvent* event) override;
// views::ButtonListener:
void ButtonPressed(views::Button* sender, const ui::Event& event) override;
// Gets the bounds of the controls.
gfx::Rect GetBackToTabControlsBounds();
gfx::Rect GetSkipAdControlsBounds();
gfx::Rect GetCloseControlsBounds();
gfx::Rect GetResizeHandleControlsBounds();
gfx::Rect GetPlayPauseControlsBounds();
gfx::Rect GetNextTrackControlsBounds();
gfx::Rect GetPreviousTrackControlsBounds();
// Gets the proper hit test component when the hit point is on the resize
// handle in order to force a drag-to-resize.
int GetResizeHTComponent() const;
// Returns true if the controls (e.g. close button, play/pause button) are
// visible.
bool AreControlsVisible() const;
views::PlaybackImageButton* play_pause_controls_view_for_testing() const;
views::TrackImageButton* next_track_controls_view_for_testing() const;
views::TrackImageButton* previous_track_controls_view_for_testing() const;
views::SkipAdLabelButton* skip_ad_controls_view_for_testing() const;
gfx::Point back_to_tab_image_position_for_testing() const;
gfx::Point close_image_position_for_testing() const;
gfx::Point resize_handle_position_for_testing() const;
OverlayWindowViews::PlaybackState playback_state_for_testing() const;
ui::Layer* video_layer_for_testing() const;
cc::Layer* GetLayerForTesting() override;
// Update the max size of the widget based on |work_area| and |window_size|.
// The return value is the new size of the window if it was resized and is
// only used for testing.
gfx::Size UpdateMaxSize(const gfx::Rect& work_area,
const gfx::Size& window_size);
private:
explicit OverlayWindowViews(
content::PictureInPictureWindowController* controller);
// Return the work area for the nearest display the widget is on.
gfx::Rect GetWorkAreaForWindow() const;
// Determine the intended bounds of |this|. This should be called when there
// is reason for the bounds to change, such as switching primary displays or
// playing a new video (i.e. different aspect ratio). This also updates
// |min_size_| and |max_size_|.
gfx::Rect CalculateAndUpdateWindowBounds();
// Set up the views::Views that will be shown on the window.
void SetUpViews();
// Finish initialization by performing the steps that require the root View.
void OnRootViewReady();
// Update the bounds of the layers on the window. This may introduce
// letterboxing.
void UpdateLayerBoundsWithLetterboxing(gfx::Size window_size);
// Updates the controls view::Views to reflect |is_visible|.
void UpdateControlsVisibility(bool is_visible);
// Updates the bounds of the controls.
void UpdateControlsBounds();
// Called when the bounds of the controls should be updated.
void OnUpdateControlsBounds();
// Update the size of each controls view as the size of the window changes.
void UpdateButtonControlsSize();
// Calculate and set the bounds of the controls.
gfx::Rect CalculateControlsBounds(int x, const gfx::Size& size);
void UpdateControlsPositions();
ui::Layer* GetControlsScrimLayer();
ui::Layer* GetBackToTabControlsLayer();
ui::Layer* GetCloseControlsLayer();
ui::Layer* GetResizeHandleLayer();
ui::Layer* GetControlsParentLayer();
// These values are persisted to logs. Entries should not be renumbered and
// numeric values should never be reused.
enum class OverlayWindowControl {
kBackToTab = 0,
kMuteDeprecated,
kSkipAd,
kClose,
kPlayPause,
kNextTrack,
kPreviousTrack,
kMaxValue = kPreviousTrack
};
void RecordButtonPressed(OverlayWindowControl);
void RecordTapGesture(OverlayWindowControl);
// Toggles the play/pause control through the |controller_| and updates the
// |play_pause_controls_view_| toggled state to reflect the current playing
// state.
void TogglePlayPause();
// Returns the current frame sink id for the surface displayed in the
// |video_view_]. If |video_view_| is not currently displaying a surface then
// returns nullptr.
const viz::FrameSinkId* GetCurrentFrameSinkId() const;
// Not owned; |controller_| owns |this|.
content::PictureInPictureWindowController* controller_;
// Whether or not the window has been shown before. This is used to determine
// sizing and placement. This is different from checking whether the window
// components has been initialized.
bool has_been_shown_ = false;
// Whether or not the play/pause button will be shown.
bool show_play_pause_button_ = false;
// The upper and lower bounds of |current_size_|. These are determined by the
// size of the primary display work area when Picture-in-Picture is initiated.
// TODO(apacible): Update these bounds when the display the window is on
// changes. http://crbug.com/819673
gfx::Size min_size_;
gfx::Size max_size_;
// Current bounds of the Picture-in-Picture window.
gfx::Rect window_bounds_;
// Bounds of |video_view_|.
gfx::Rect video_bounds_;
// The natural size of the video to show. This is used to compute sizing and
// ensuring factors such as aspect ratio is maintained.
gfx::Size natural_size_;
// Temporary storage for child Views. Used during the time between
// construction and initialization, when the views::View pointer members must
// already be initialized, but there is no root view to add them to yet.
std::vector<std::unique_ptr<views::View>> view_holder_;
// Views to be shown.
views::View* window_background_view_ = nullptr;
views::View* video_view_ = nullptr;
views::View* controls_scrim_view_ = nullptr;
views::CloseImageButton* close_controls_view_ = nullptr;
views::BackToTabImageButton* back_to_tab_controls_view_ = nullptr;
views::TrackImageButton* previous_track_controls_view_ = nullptr;
views::PlaybackImageButton* play_pause_controls_view_ = nullptr;
views::TrackImageButton* next_track_controls_view_ = nullptr;
views::SkipAdLabelButton* skip_ad_controls_view_ = nullptr;
views::ResizeHandleButton* resize_handle_view_ = nullptr;
#if defined(OS_CHROMEOS)
std::unique_ptr<ash::RoundedCornerDecorator> decorator_;
#endif
// Automatically hides the controls a few seconds after user tap gesture.
base::RetainingOneShotTimer hide_controls_timer_;
// Timer used to update controls bounds.
std::unique_ptr<base::OneShotTimer> update_controls_bounds_timer_;
// Current playback state on the video in Picture-in-Picture window. It is
// used to toggle play/pause/replay button.
PlaybackState playback_state_for_testing_ = kEndOfVideo;
// Whether or not the skip ad button will be shown. This is the
// case when Media Session "skipad" action is handled by the website.
bool show_skip_ad_button_ = false;
// Whether or not the next track button will be shown. This is the
// case when Media Session "nexttrack" action is handled by the website.
bool show_next_track_button_ = false;
// Whether or not the previous track button will be shown. This is the
// case when Media Session "previoustrack" action is handled by the website.
bool show_previous_track_button_ = false;
DISALLOW_COPY_AND_ASSIGN(OverlayWindowViews);
};
#endif // CHROME_BROWSER_UI_VIEWS_OVERLAY_OVERLAY_WINDOW_VIEWS_H_
| 38.980159 | 80 | 0.763616 | [
"geometry",
"vector"
] |
459f975308027b3737e063ac5abe3d000cb87ec1 | 21,754 | h | C | third_party/gecko-2/win32/include/nsIURI.h | bwp/SeleniumWebDriver | 58221fbe59fcbbde9d9a033a95d45d576b422747 | [
"Apache-2.0"
] | 1 | 2018-02-05T04:23:18.000Z | 2018-02-05T04:23:18.000Z | third_party/gecko-2/win32/include/nsIURI.h | bwp/SeleniumWebDriver | 58221fbe59fcbbde9d9a033a95d45d576b422747 | [
"Apache-2.0"
] | null | null | null | third_party/gecko-2/win32/include/nsIURI.h | bwp/SeleniumWebDriver | 58221fbe59fcbbde9d9a033a95d45d576b422747 | [
"Apache-2.0"
] | null | null | null | /*
* DO NOT EDIT. THIS FILE IS GENERATED FROM e:/builds/moz2_slave/rel-2.0-xr-w32-bld/build/netwerk/base/public/nsIURI.idl
*/
#ifndef __gen_nsIURI_h__
#define __gen_nsIURI_h__
#ifndef __gen_nsISupports_h__
#include "nsISupports.h"
#endif
/* For IDL files that don't want to include root IDL files. */
#ifndef NS_NO_VTABLE
#define NS_NO_VTABLE
#endif
#undef GetPort // XXX Windows!
#undef SetPort // XXX Windows!
/* starting interface: nsIURI */
#define NS_IURI_IID_STR "07a22cc0-0ce5-11d3-9331-00104ba0fd40"
#define NS_IURI_IID \
{0x07a22cc0, 0x0ce5, 0x11d3, \
{ 0x93, 0x31, 0x00, 0x10, 0x4b, 0xa0, 0xfd, 0x40 }}
/**
* URIs are essentially structured names for things -- anything. This interface
* provides accessors to set and query the most basic components of an URI.
* Subclasses, including nsIURL, impose greater structure on the URI.
*
* This interface follows Tim Berners-Lee's URI spec (RFC2396) [1], where the
* basic URI components are defined as such:
* <pre>
* ftp://username:password@hostname:portnumber/pathname
* \ / \ / \ / \ /\ /
* - --------------- ------ -------- -------
* | | | | |
* | | | | Path
* | | | Port
* | | Host /
* | UserPass /
* Scheme /
* \ /
* --------------------------------
* |
* PrePath
* </pre>
* The definition of the URI components has been extended to allow for
* internationalized domain names [2] and the more generic IRI structure [3].
*
* [1] http://www.ietf.org/rfc/rfc2396.txt
* [2] http://www.ietf.org/internet-drafts/draft-ietf-idn-idna-06.txt
* [3] http://www.ietf.org/internet-drafts/draft-masinter-url-i18n-08.txt
*/
/**
* nsIURI - interface for an uniform resource identifier w/ i18n support.
*
* AUTF8String attributes may contain unescaped UTF-8 characters.
* Consumers should be careful to escape the UTF-8 strings as necessary, but
* should always try to "display" the UTF-8 version as provided by this
* interface.
*
* AUTF8String attributes may also contain escaped characters.
*
* Unescaping URI segments is unadvised unless there is intimate
* knowledge of the underlying charset or there is no plan to display (or
* otherwise enforce a charset on) the resulting URI substring.
*
* The correct way to create an nsIURI from a string is via
* nsIIOService.newURI.
*/
class NS_NO_VTABLE NS_SCRIPTABLE nsIURI : public nsISupports {
public:
NS_DECLARE_STATIC_IID_ACCESSOR(NS_IURI_IID)
/************************************************************************
* The URI is broken down into the following principal components:
*/
/**
* Returns a string representation of the URI. Setting the spec causes
* the new spec to be parsed per the rules for the scheme the URI
* currently has. In particular, setting the spec to a URI string with a
* different scheme will generally produce incorrect results; no one
* outside of a protocol handler implementation should be doing that. If
* the URI stores information from the nsIIOService.newURI call used to
* create it other than just the parsed string, then behavior of this
* information on setting the spec attribute is undefined.
*
* Some characters may be escaped.
*/
/* attribute AUTF8String spec; */
NS_SCRIPTABLE NS_IMETHOD GetSpec(nsACString & aSpec) = 0;
NS_SCRIPTABLE NS_IMETHOD SetSpec(const nsACString & aSpec) = 0;
/**
* The prePath (eg. scheme://user:password@host:port) returns the string
* before the path. This is useful for authentication or managing sessions.
*
* Some characters may be escaped.
*/
/* readonly attribute AUTF8String prePath; */
NS_SCRIPTABLE NS_IMETHOD GetPrePath(nsACString & aPrePath) = 0;
/**
* The Scheme is the protocol to which this URI refers. The scheme is
* restricted to the US-ASCII charset per RFC2396. Setting this is
* highly discouraged outside of a protocol handler implementation, since
* that will generally lead to incorrect results.
*/
/* attribute ACString scheme; */
NS_SCRIPTABLE NS_IMETHOD GetScheme(nsACString & aScheme) = 0;
NS_SCRIPTABLE NS_IMETHOD SetScheme(const nsACString & aScheme) = 0;
/**
* The username:password (or username only if value doesn't contain a ':')
*
* Some characters may be escaped.
*/
/* attribute AUTF8String userPass; */
NS_SCRIPTABLE NS_IMETHOD GetUserPass(nsACString & aUserPass) = 0;
NS_SCRIPTABLE NS_IMETHOD SetUserPass(const nsACString & aUserPass) = 0;
/**
* The optional username and password, assuming the preHost consists of
* username:password.
*
* Some characters may be escaped.
*/
/* attribute AUTF8String username; */
NS_SCRIPTABLE NS_IMETHOD GetUsername(nsACString & aUsername) = 0;
NS_SCRIPTABLE NS_IMETHOD SetUsername(const nsACString & aUsername) = 0;
/* attribute AUTF8String password; */
NS_SCRIPTABLE NS_IMETHOD GetPassword(nsACString & aPassword) = 0;
NS_SCRIPTABLE NS_IMETHOD SetPassword(const nsACString & aPassword) = 0;
/**
* The host:port (or simply the host, if port == -1).
*
* Characters are NOT escaped.
*/
/* attribute AUTF8String hostPort; */
NS_SCRIPTABLE NS_IMETHOD GetHostPort(nsACString & aHostPort) = 0;
NS_SCRIPTABLE NS_IMETHOD SetHostPort(const nsACString & aHostPort) = 0;
/**
* The host is the internet domain name to which this URI refers. It could
* be an IPv4 (or IPv6) address literal. If supported, it could be a
* non-ASCII internationalized domain name.
*
* Characters are NOT escaped.
*/
/* attribute AUTF8String host; */
NS_SCRIPTABLE NS_IMETHOD GetHost(nsACString & aHost) = 0;
NS_SCRIPTABLE NS_IMETHOD SetHost(const nsACString & aHost) = 0;
/**
* A port value of -1 corresponds to the protocol's default port (eg. -1
* implies port 80 for http URIs).
*/
/* attribute long port; */
NS_SCRIPTABLE NS_IMETHOD GetPort(PRInt32 *aPort) = 0;
NS_SCRIPTABLE NS_IMETHOD SetPort(PRInt32 aPort) = 0;
/**
* The path, typically including at least a leading '/' (but may also be
* empty, depending on the protocol).
*
* Some characters may be escaped.
*/
/* attribute AUTF8String path; */
NS_SCRIPTABLE NS_IMETHOD GetPath(nsACString & aPath) = 0;
NS_SCRIPTABLE NS_IMETHOD SetPath(const nsACString & aPath) = 0;
/************************************************************************
* An URI supports the following methods:
*/
/**
* URI equivalence test (not a strict string comparison).
*
* eg. http://foo.com:80/ == http://foo.com/
*/
/* boolean equals (in nsIURI other); */
NS_SCRIPTABLE NS_IMETHOD Equals(nsIURI *other, PRBool *_retval NS_OUTPARAM) = 0;
/**
* An optimization to do scheme checks without requiring the users of nsIURI
* to GetScheme, thereby saving extra allocating and freeing. Returns true if
* the schemes match (case ignored).
*/
/* boolean schemeIs (in string scheme); */
NS_SCRIPTABLE NS_IMETHOD SchemeIs(const char *scheme, PRBool *_retval NS_OUTPARAM) = 0;
/**
* Clones the current URI. For some protocols, this is more than just an
* optimization. For example, under MacOS, the spec of a file URL does not
* necessarily uniquely identify a file since two volumes could share the
* same name.
*/
/* nsIURI clone (); */
NS_SCRIPTABLE NS_IMETHOD Clone(nsIURI **_retval NS_OUTPARAM) = 0;
/**
* This method resolves a relative string into an absolute URI string,
* using this URI as the base.
*
* NOTE: some implementations may have no concept of a relative URI.
*/
/* AUTF8String resolve (in AUTF8String relativePath); */
NS_SCRIPTABLE NS_IMETHOD Resolve(const nsACString & relativePath, nsACString & _retval NS_OUTPARAM) = 0;
/************************************************************************
* Additional attributes:
*/
/**
* The URI spec with an ASCII compatible encoding. Host portion follows
* the IDNA draft spec. Other parts are URL-escaped per the rules of
* RFC2396. The result is strictly ASCII.
*/
/* readonly attribute ACString asciiSpec; */
NS_SCRIPTABLE NS_IMETHOD GetAsciiSpec(nsACString & aAsciiSpec) = 0;
/**
* The URI host with an ASCII compatible encoding. Follows the IDNA
* draft spec for converting internationalized domain names (UTF-8) to
* ASCII for compatibility with existing internet infrasture.
*/
/* readonly attribute ACString asciiHost; */
NS_SCRIPTABLE NS_IMETHOD GetAsciiHost(nsACString & aAsciiHost) = 0;
/**
* The charset of the document from which this URI originated. An empty
* value implies UTF-8.
*
* If this value is something other than UTF-8 then the URI components
* (e.g., spec, prePath, username, etc.) will all be fully URL-escaped.
* Otherwise, the URI components may contain unescaped multibyte UTF-8
* characters.
*/
/* readonly attribute ACString originCharset; */
NS_SCRIPTABLE NS_IMETHOD GetOriginCharset(nsACString & aOriginCharset) = 0;
};
NS_DEFINE_STATIC_IID_ACCESSOR(nsIURI, NS_IURI_IID)
/* Use this macro when declaring classes that implement this interface. */
#define NS_DECL_NSIURI \
NS_SCRIPTABLE NS_IMETHOD GetSpec(nsACString & aSpec); \
NS_SCRIPTABLE NS_IMETHOD SetSpec(const nsACString & aSpec); \
NS_SCRIPTABLE NS_IMETHOD GetPrePath(nsACString & aPrePath); \
NS_SCRIPTABLE NS_IMETHOD GetScheme(nsACString & aScheme); \
NS_SCRIPTABLE NS_IMETHOD SetScheme(const nsACString & aScheme); \
NS_SCRIPTABLE NS_IMETHOD GetUserPass(nsACString & aUserPass); \
NS_SCRIPTABLE NS_IMETHOD SetUserPass(const nsACString & aUserPass); \
NS_SCRIPTABLE NS_IMETHOD GetUsername(nsACString & aUsername); \
NS_SCRIPTABLE NS_IMETHOD SetUsername(const nsACString & aUsername); \
NS_SCRIPTABLE NS_IMETHOD GetPassword(nsACString & aPassword); \
NS_SCRIPTABLE NS_IMETHOD SetPassword(const nsACString & aPassword); \
NS_SCRIPTABLE NS_IMETHOD GetHostPort(nsACString & aHostPort); \
NS_SCRIPTABLE NS_IMETHOD SetHostPort(const nsACString & aHostPort); \
NS_SCRIPTABLE NS_IMETHOD GetHost(nsACString & aHost); \
NS_SCRIPTABLE NS_IMETHOD SetHost(const nsACString & aHost); \
NS_SCRIPTABLE NS_IMETHOD GetPort(PRInt32 *aPort); \
NS_SCRIPTABLE NS_IMETHOD SetPort(PRInt32 aPort); \
NS_SCRIPTABLE NS_IMETHOD GetPath(nsACString & aPath); \
NS_SCRIPTABLE NS_IMETHOD SetPath(const nsACString & aPath); \
NS_SCRIPTABLE NS_IMETHOD Equals(nsIURI *other, PRBool *_retval NS_OUTPARAM); \
NS_SCRIPTABLE NS_IMETHOD SchemeIs(const char *scheme, PRBool *_retval NS_OUTPARAM); \
NS_SCRIPTABLE NS_IMETHOD Clone(nsIURI **_retval NS_OUTPARAM); \
NS_SCRIPTABLE NS_IMETHOD Resolve(const nsACString & relativePath, nsACString & _retval NS_OUTPARAM); \
NS_SCRIPTABLE NS_IMETHOD GetAsciiSpec(nsACString & aAsciiSpec); \
NS_SCRIPTABLE NS_IMETHOD GetAsciiHost(nsACString & aAsciiHost); \
NS_SCRIPTABLE NS_IMETHOD GetOriginCharset(nsACString & aOriginCharset);
/* Use this macro to declare functions that forward the behavior of this interface to another object. */
#define NS_FORWARD_NSIURI(_to) \
NS_SCRIPTABLE NS_IMETHOD GetSpec(nsACString & aSpec) { return _to GetSpec(aSpec); } \
NS_SCRIPTABLE NS_IMETHOD SetSpec(const nsACString & aSpec) { return _to SetSpec(aSpec); } \
NS_SCRIPTABLE NS_IMETHOD GetPrePath(nsACString & aPrePath) { return _to GetPrePath(aPrePath); } \
NS_SCRIPTABLE NS_IMETHOD GetScheme(nsACString & aScheme) { return _to GetScheme(aScheme); } \
NS_SCRIPTABLE NS_IMETHOD SetScheme(const nsACString & aScheme) { return _to SetScheme(aScheme); } \
NS_SCRIPTABLE NS_IMETHOD GetUserPass(nsACString & aUserPass) { return _to GetUserPass(aUserPass); } \
NS_SCRIPTABLE NS_IMETHOD SetUserPass(const nsACString & aUserPass) { return _to SetUserPass(aUserPass); } \
NS_SCRIPTABLE NS_IMETHOD GetUsername(nsACString & aUsername) { return _to GetUsername(aUsername); } \
NS_SCRIPTABLE NS_IMETHOD SetUsername(const nsACString & aUsername) { return _to SetUsername(aUsername); } \
NS_SCRIPTABLE NS_IMETHOD GetPassword(nsACString & aPassword) { return _to GetPassword(aPassword); } \
NS_SCRIPTABLE NS_IMETHOD SetPassword(const nsACString & aPassword) { return _to SetPassword(aPassword); } \
NS_SCRIPTABLE NS_IMETHOD GetHostPort(nsACString & aHostPort) { return _to GetHostPort(aHostPort); } \
NS_SCRIPTABLE NS_IMETHOD SetHostPort(const nsACString & aHostPort) { return _to SetHostPort(aHostPort); } \
NS_SCRIPTABLE NS_IMETHOD GetHost(nsACString & aHost) { return _to GetHost(aHost); } \
NS_SCRIPTABLE NS_IMETHOD SetHost(const nsACString & aHost) { return _to SetHost(aHost); } \
NS_SCRIPTABLE NS_IMETHOD GetPort(PRInt32 *aPort) { return _to GetPort(aPort); } \
NS_SCRIPTABLE NS_IMETHOD SetPort(PRInt32 aPort) { return _to SetPort(aPort); } \
NS_SCRIPTABLE NS_IMETHOD GetPath(nsACString & aPath) { return _to GetPath(aPath); } \
NS_SCRIPTABLE NS_IMETHOD SetPath(const nsACString & aPath) { return _to SetPath(aPath); } \
NS_SCRIPTABLE NS_IMETHOD Equals(nsIURI *other, PRBool *_retval NS_OUTPARAM) { return _to Equals(other, _retval); } \
NS_SCRIPTABLE NS_IMETHOD SchemeIs(const char *scheme, PRBool *_retval NS_OUTPARAM) { return _to SchemeIs(scheme, _retval); } \
NS_SCRIPTABLE NS_IMETHOD Clone(nsIURI **_retval NS_OUTPARAM) { return _to Clone(_retval); } \
NS_SCRIPTABLE NS_IMETHOD Resolve(const nsACString & relativePath, nsACString & _retval NS_OUTPARAM) { return _to Resolve(relativePath, _retval); } \
NS_SCRIPTABLE NS_IMETHOD GetAsciiSpec(nsACString & aAsciiSpec) { return _to GetAsciiSpec(aAsciiSpec); } \
NS_SCRIPTABLE NS_IMETHOD GetAsciiHost(nsACString & aAsciiHost) { return _to GetAsciiHost(aAsciiHost); } \
NS_SCRIPTABLE NS_IMETHOD GetOriginCharset(nsACString & aOriginCharset) { return _to GetOriginCharset(aOriginCharset); }
/* Use this macro to declare functions that forward the behavior of this interface to another object in a safe way. */
#define NS_FORWARD_SAFE_NSIURI(_to) \
NS_SCRIPTABLE NS_IMETHOD GetSpec(nsACString & aSpec) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetSpec(aSpec); } \
NS_SCRIPTABLE NS_IMETHOD SetSpec(const nsACString & aSpec) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetSpec(aSpec); } \
NS_SCRIPTABLE NS_IMETHOD GetPrePath(nsACString & aPrePath) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetPrePath(aPrePath); } \
NS_SCRIPTABLE NS_IMETHOD GetScheme(nsACString & aScheme) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetScheme(aScheme); } \
NS_SCRIPTABLE NS_IMETHOD SetScheme(const nsACString & aScheme) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetScheme(aScheme); } \
NS_SCRIPTABLE NS_IMETHOD GetUserPass(nsACString & aUserPass) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetUserPass(aUserPass); } \
NS_SCRIPTABLE NS_IMETHOD SetUserPass(const nsACString & aUserPass) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetUserPass(aUserPass); } \
NS_SCRIPTABLE NS_IMETHOD GetUsername(nsACString & aUsername) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetUsername(aUsername); } \
NS_SCRIPTABLE NS_IMETHOD SetUsername(const nsACString & aUsername) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetUsername(aUsername); } \
NS_SCRIPTABLE NS_IMETHOD GetPassword(nsACString & aPassword) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetPassword(aPassword); } \
NS_SCRIPTABLE NS_IMETHOD SetPassword(const nsACString & aPassword) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetPassword(aPassword); } \
NS_SCRIPTABLE NS_IMETHOD GetHostPort(nsACString & aHostPort) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetHostPort(aHostPort); } \
NS_SCRIPTABLE NS_IMETHOD SetHostPort(const nsACString & aHostPort) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetHostPort(aHostPort); } \
NS_SCRIPTABLE NS_IMETHOD GetHost(nsACString & aHost) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetHost(aHost); } \
NS_SCRIPTABLE NS_IMETHOD SetHost(const nsACString & aHost) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetHost(aHost); } \
NS_SCRIPTABLE NS_IMETHOD GetPort(PRInt32 *aPort) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetPort(aPort); } \
NS_SCRIPTABLE NS_IMETHOD SetPort(PRInt32 aPort) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetPort(aPort); } \
NS_SCRIPTABLE NS_IMETHOD GetPath(nsACString & aPath) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetPath(aPath); } \
NS_SCRIPTABLE NS_IMETHOD SetPath(const nsACString & aPath) { return !_to ? NS_ERROR_NULL_POINTER : _to->SetPath(aPath); } \
NS_SCRIPTABLE NS_IMETHOD Equals(nsIURI *other, PRBool *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->Equals(other, _retval); } \
NS_SCRIPTABLE NS_IMETHOD SchemeIs(const char *scheme, PRBool *_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->SchemeIs(scheme, _retval); } \
NS_SCRIPTABLE NS_IMETHOD Clone(nsIURI **_retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->Clone(_retval); } \
NS_SCRIPTABLE NS_IMETHOD Resolve(const nsACString & relativePath, nsACString & _retval NS_OUTPARAM) { return !_to ? NS_ERROR_NULL_POINTER : _to->Resolve(relativePath, _retval); } \
NS_SCRIPTABLE NS_IMETHOD GetAsciiSpec(nsACString & aAsciiSpec) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetAsciiSpec(aAsciiSpec); } \
NS_SCRIPTABLE NS_IMETHOD GetAsciiHost(nsACString & aAsciiHost) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetAsciiHost(aAsciiHost); } \
NS_SCRIPTABLE NS_IMETHOD GetOriginCharset(nsACString & aOriginCharset) { return !_to ? NS_ERROR_NULL_POINTER : _to->GetOriginCharset(aOriginCharset); }
#if 0
/* Use the code below as a template for the implementation class for this interface. */
/* Header file */
class nsURI : public nsIURI
{
public:
NS_DECL_ISUPPORTS
NS_DECL_NSIURI
nsURI();
private:
~nsURI();
protected:
/* additional members */
};
/* Implementation file */
NS_IMPL_ISUPPORTS1(nsURI, nsIURI)
nsURI::nsURI()
{
/* member initializers and constructor code */
}
nsURI::~nsURI()
{
/* destructor code */
}
/* attribute AUTF8String spec; */
NS_IMETHODIMP nsURI::GetSpec(nsACString & aSpec)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsURI::SetSpec(const nsACString & aSpec)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute AUTF8String prePath; */
NS_IMETHODIMP nsURI::GetPrePath(nsACString & aPrePath)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* attribute ACString scheme; */
NS_IMETHODIMP nsURI::GetScheme(nsACString & aScheme)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsURI::SetScheme(const nsACString & aScheme)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* attribute AUTF8String userPass; */
NS_IMETHODIMP nsURI::GetUserPass(nsACString & aUserPass)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsURI::SetUserPass(const nsACString & aUserPass)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* attribute AUTF8String username; */
NS_IMETHODIMP nsURI::GetUsername(nsACString & aUsername)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsURI::SetUsername(const nsACString & aUsername)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* attribute AUTF8String password; */
NS_IMETHODIMP nsURI::GetPassword(nsACString & aPassword)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsURI::SetPassword(const nsACString & aPassword)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* attribute AUTF8String hostPort; */
NS_IMETHODIMP nsURI::GetHostPort(nsACString & aHostPort)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsURI::SetHostPort(const nsACString & aHostPort)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* attribute AUTF8String host; */
NS_IMETHODIMP nsURI::GetHost(nsACString & aHost)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsURI::SetHost(const nsACString & aHost)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* attribute long port; */
NS_IMETHODIMP nsURI::GetPort(PRInt32 *aPort)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsURI::SetPort(PRInt32 aPort)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* attribute AUTF8String path; */
NS_IMETHODIMP nsURI::GetPath(nsACString & aPath)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
NS_IMETHODIMP nsURI::SetPath(const nsACString & aPath)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* boolean equals (in nsIURI other); */
NS_IMETHODIMP nsURI::Equals(nsIURI *other, PRBool *_retval NS_OUTPARAM)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* boolean schemeIs (in string scheme); */
NS_IMETHODIMP nsURI::SchemeIs(const char *scheme, PRBool *_retval NS_OUTPARAM)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* nsIURI clone (); */
NS_IMETHODIMP nsURI::Clone(nsIURI **_retval NS_OUTPARAM)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* AUTF8String resolve (in AUTF8String relativePath); */
NS_IMETHODIMP nsURI::Resolve(const nsACString & relativePath, nsACString & _retval NS_OUTPARAM)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute ACString asciiSpec; */
NS_IMETHODIMP nsURI::GetAsciiSpec(nsACString & aAsciiSpec)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute ACString asciiHost; */
NS_IMETHODIMP nsURI::GetAsciiHost(nsACString & aAsciiHost)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* readonly attribute ACString originCharset; */
NS_IMETHODIMP nsURI::GetOriginCharset(nsACString & aOriginCharset)
{
return NS_ERROR_NOT_IMPLEMENTED;
}
/* End of implementation class template. */
#endif
#endif /* __gen_nsIURI_h__ */
| 42.571429 | 182 | 0.718397 | [
"object"
] |
45a09c949b7f09c4a9e20b38b3e9f605fba341ce | 4,486 | h | C | QNShortVideo-With-TuTu-iOS/tusdkfilterprocessormodule/tusdkfilterprocessormodule/TuSDKFramework/TuSDK.framework/Versions/A/Headers/TuSDKCPStackFilterTableView.h | chenqian-dev/QNShortVideo-TuTu | e8af7ed1cf34944c3741b8c5984418ddcb3d3518 | [
"MIT"
] | 474 | 2017-05-05T03:45:03.000Z | 2022-03-16T09:46:27.000Z | ShortVideoUIDemo/ShortVideo/Effects/TuSDK/TuSDK-framework/TuSDK.framework/Versions/A/Headers/TuSDKCPStackFilterTableView.h | shiyulong-ios/PLShortVideoKit | 393c21dc5ed1a581d42d600e89b43c0edf8dac1b | [
"Apache-2.0"
] | 108 | 2017-05-05T11:54:06.000Z | 2021-09-28T03:27:47.000Z | ShortVideoUIDemo/ShortVideo/Effects/TuSDK/TuSDK-framework/TuSDK.framework/Versions/A/Headers/TuSDKCPStackFilterTableView.h | shiyulong-ios/PLShortVideoKit | 393c21dc5ed1a581d42d600e89b43c0edf8dac1b | [
"Apache-2.0"
] | 138 | 2017-05-05T03:52:58.000Z | 2021-11-03T08:58:19.000Z | //
// TuSDKCPStackFilterTableView.h
// TuSDK
//
// Created by Jimmy Zhao on 16/9/22.
// Copyright © 2016年 tusdk.com. All rights reserved.
//
#import "TuSDKICTableView.h"
#import "TuSDKCPGroupFilterItemCellBase.h"
@protocol TuSDKCPStackFilterTableViewInterface;
/**
* 滤镜分组列表行视图委托
*/
@protocol TuSDKCPStackFilterTableViewDelegate <NSObject>
/**
* 选中一个行视图
*
* @param tableView 滤镜分组列表
* @param cell 滤镜分组元素视图
* @param mode 滤镜分组元素
* @param indexPath 索引
*
* @return BOOL 是否允许选中
*/
- (BOOL)onTuSDKCPGroupFilterTableView:(UIView<TuSDKCPStackFilterTableViewInterface> *)tableView
selectedCell:(UITableViewCell<TuSDKCPGroupFilterItemCellInterface> *)cell
model:(TuSDKCPGroupFilterItem *)mode
indexPath:(NSIndexPath *)indexPath;
@end
#pragma mark - TuSDKCPStackFilterTableViewInterface
/**
* 滤镜分组列表接口
*/
@protocol TuSDKCPStackFilterTableViewInterface <NSObject>
/**
* 滤镜分组列表行视图委托
*/
@property (nonatomic, weak) id<TuSDKCPStackFilterTableViewDelegate> delegate;
/**
* 滤镜分组元素类型
*/
@property (nonatomic)lsqGroupFilterAction action;
/**
* 滤镜分组元素视图类 (默认:TuSDKCPGroupFilterItemCell, 需要继承 UITableViewCell<TuSDKCPGroupFilterItemCellInterface>)
*/
@property (nonatomic, strong) Class cellViewClazz;
/**
* 滤镜分组元素视图类 (默认:TuSDKCPGroupFilterGroupCellBase, 需要继承 UITableViewCell<TuSDKCPGroupFilterItemCellInterface>)
*/
@property (nonatomic, strong) Class stackViewClazz;
/**
* 行视图宽度
*/
@property (nonatomic)CGFloat cellWidth;
/**
* 折叠视图宽度
*/
@property (nonatomic)CGFloat stackViewWidth;
/**
* 当前选中的分区 ( —1 表示没有选中任何分区)
*/
@property (nonatomic)NSInteger selectedSection;
/**
* 数据列表
*/
@property (nonatomic, retain) NSArray *modeList;
/**
* 选中的滤镜
*/
@property (nonatomic, retain) TuSDKFilterOption *lasOpt;
/**
* 选中的单元格数据列表
*/
@property (nonatomic, retain) NSArray<TuSDKFilterOption *> *cellItemDatas;
/**
* 是否允许选择列表
*/
@property (nonatomic) BOOL allowsSelection;
/**
* 是否显示第一次选择后的图标
*/
@property (nonatomic) BOOL displaySelectionIcon;
/**
* 滤镜分组视图委托
*/
@property (nonatomic, weak) id<TuSDKCPGroupFilterGroupCellDelegate> groupDelegate;
/**
* 滤镜任务
*/
@property (nonatomic, assign) id<TuSDKTKFiltersTaskInterface> filterTask;
/**
* 选中索引
*
* @param position 索引
* @param toCenter 是否滚动到中心位置
* @param reload 是否刷新数据
*/
- (void)selectPostion:(NSUInteger)position scrollToCenter:(BOOL)toCenter reload:(BOOL)reload;
/**
* 刷新数据
*/
- (void)reloadData;
- (NSIndexPath *)indexPathForSelectedRow;
- (void)insertRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation;
- (void)deleteRowsAtIndexPaths:(NSArray *)indexPaths withRowAnimation:(UITableViewRowAnimation)animation;
- (void)scrollToRowAtIndexPath:(NSIndexPath *)indexPath atScrollPosition:(UITableViewScrollPosition)scrollPosition animated:(BOOL)animated;
@end
#pragma mark - TuSDKCPStackFilterTableView
/**
* 滤镜分组列表
*/
@interface TuSDKCPStackFilterTableView : UIView<UITableViewDataSource, UITableViewDelegate, TuSDKCPStackFilterTableViewInterface>
/**
* 滤镜分组元素类型
*/
@property (nonatomic)lsqGroupFilterAction action;
/**
* 滤镜分组元素视图类 (默认:TuSDKCPGroupFilterItemCellBase, 需要继承 UITableViewCell<TuSDKCPGroupFilterItemCellInterface>)
*/
@property (nonatomic, strong) Class cellViewClazz;
/**
* 滤镜列表区头视图类 (默认:TuSDKCPGroupFilterGroupCellBase, 需要继承 UITableViewCell<TuSDKCPGroupFilterItemCellInterface>)
*/
@property (nonatomic, strong) Class stackViewClazz;
/**
* 滤镜分组列表行视图委托
*/
@property (nonatomic, weak) id<TuSDKCPStackFilterTableViewDelegate> delegate;
/**
* 行视图宽度
*/
@property (nonatomic)CGFloat cellWidth;
/**
* 表头视图宽度
*/
@property (nonatomic)CGFloat stackViewWidth;
/**
* 当前选中的分区 ( —1 表示没有选中任何分区)
*/
@property (nonatomic)NSInteger selectedSection;
/**
* 数据列表
*/
@property (nonatomic, retain) NSArray *modeList;
/**
* 选中的滤镜
*/
@property (nonatomic, retain) TuSDKFilterOption *lasOpt;
/**
* 选中的单元格数据列表
*/
@property (nonatomic, retain) NSArray<TuSDKFilterOption *> *cellItemDatas;
/**
* 列表视图
*/
@property (nonatomic, readonly)TuSDKICTableView *tableView;
/**
* 是否允许选择列表
*/
@property (nonatomic) BOOL allowsSelection;
/**
* 是否显示第一次选择后的图标
*/
@property (nonatomic) BOOL displaySelectionIcon;
/**
* 滤镜分组视图委托
*/
@property (nonatomic, weak) id<TuSDKCPGroupFilterGroupCellDelegate> groupDelegate;
/**
* 滤镜任务
*/
@property (nonatomic, assign) id<TuSDKTKFiltersTaskInterface> filterTask;
@end
| 21.567308 | 139 | 0.730718 | [
"model"
] |
45a32ddf234ddf399a8b7989d38964c128fb8e34 | 32,162 | h | C | src/lib/EASTL/include/EASTL/chrono.h | moshik1/mcas | a6af06bc278993fb3ffe780f230d2396b2287c26 | [
"Apache-2.0"
] | 60 | 2020-04-28T08:15:07.000Z | 2022-03-08T10:35:15.000Z | src/lib/EASTL/include/EASTL/chrono.h | moshik1/mcas | a6af06bc278993fb3ffe780f230d2396b2287c26 | [
"Apache-2.0"
] | 66 | 2020-09-03T23:40:48.000Z | 2022-03-07T20:34:52.000Z | src/lib/EASTL/include/EASTL/chrono.h | moshik1/mcas | a6af06bc278993fb3ffe780f230d2396b2287c26 | [
"Apache-2.0"
] | 13 | 2019-11-02T06:30:36.000Z | 2022-01-26T01:56:42.000Z | /////////////////////////////////////////////////////////////////////////////
// Copyright (c) Electronic Arts Inc. All rights reserved.
/////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
// This file implements the eastl::chrono specification which is part of the
// standard STL date and time library. eastl::chrono implements all the
// mechanisms required to capture and manipulate times retrieved from the
// provided clocks. It implements the all of the features to allow type safe
// durations to be used in code.
///////////////////////////////////////////////////////////////////////////////
#ifndef EASTL_CHRONO_H
#define EASTL_CHRONO_H
#if defined(EA_PRAGMA_ONCE_SUPPORTED)
#pragma once
#endif
/* This file defines literal operator suffixes h, m, s, ms, us, ns, and min, which are system-reserved */
#pragma GCC system_header
#include <EASTL/internal/config.h>
#include <EASTL/type_traits.h>
#include <EASTL/numeric_limits.h>
#include <EASTL/ratio.h>
// TODO: move to platform specific cpp or header file
#if defined EA_PLATFORM_MICROSOFT
#pragma warning(push, 0)
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
EA_DISABLE_ALL_VC_WARNINGS()
#undef NOMINMAX
#define NOMINMAX
#include <Windows.h>
#ifdef min
#undef min
#endif
#ifdef max
#undef max
#endif
EA_RESTORE_ALL_VC_WARNINGS()
#pragma warning(pop)
#endif
#if defined(EA_PLATFORM_MICROSOFT) && !defined(EA_PLATFORM_MINGW)
#include <thr/xtimec.h>
#elif defined(EA_PLATFORM_SONY)
#include <Dinkum/threads/xtimec.h>
#include <kernel.h>
#elif defined(EA_PLATFORM_APPLE)
#include <mach/mach_time.h>
#elif defined(EA_PLATFORM_POSIX) || defined(EA_PLATFORM_MINGW) || defined(EA_PLATFORM_ANDROID)
// Posix means Linux, Unix, and Macintosh OSX, among others (including Linux-based mobile platforms).
#if defined(EA_PLATFORM_MINGW)
#include <pthread_time.h>
#endif
#include <time.h>
#if (defined(CLOCK_REALTIME) || defined(CLOCK_MONOTONIC))
#include <errno.h>
#else
#include <sys/time.h>
#include <unistd.h>
#endif
#endif
namespace eastl
{
namespace chrono
{
///////////////////////////////////////////////////////////////////////////////
// treat_as_floating_point
///////////////////////////////////////////////////////////////////////////////
template <class Rep>
struct treat_as_floating_point : is_floating_point<Rep> {};
///////////////////////////////////////////////////////////////////////////////
// 20.12.4, duration_values
///////////////////////////////////////////////////////////////////////////////
template <class Rep>
struct duration_values
{
public:
EASTL_FORCE_INLINE static EA_CONSTEXPR Rep zero() { return Rep(0); }
EASTL_FORCE_INLINE static EA_CONSTEXPR Rep max() { return eastl::numeric_limits<Rep>::max(); }
EASTL_FORCE_INLINE static EA_CONSTEXPR Rep min() { return eastl::numeric_limits<Rep>::lowest(); }
};
///////////////////////////////////////////////////////////////////////////////
// duration fwd_decl
///////////////////////////////////////////////////////////////////////////////
template <typename Rep, typename Period = ratio<1>>
class duration;
namespace Internal
{
///////////////////////////////////////////////////////////////////////////////
// IsRatio
///////////////////////////////////////////////////////////////////////////////
template <typename> struct IsRatio : eastl::false_type {};
template <intmax_t N, intmax_t D> struct IsRatio<ratio<N, D>> : eastl::true_type {};
template <intmax_t N, intmax_t D> struct IsRatio<const ratio<N, D>> : eastl::true_type {};
template <intmax_t N, intmax_t D> struct IsRatio<volatile ratio<N, D>> : eastl::true_type {};
template <intmax_t N, intmax_t D> struct IsRatio<const volatile ratio<N, D>> : eastl::true_type {};
///////////////////////////////////////////////////////////////////////////////
// IsDuration
///////////////////////////////////////////////////////////////////////////////
template<typename> struct IsDuration : eastl::false_type{};
template<typename Rep, typename Period> struct IsDuration<duration<Rep, Period>> : eastl::true_type{};
template<typename Rep, typename Period> struct IsDuration<const duration<Rep, Period>> : eastl::true_type{};
template<typename Rep, typename Period> struct IsDuration<volatile duration<Rep, Period>> : eastl::true_type{};
template<typename Rep, typename Period> struct IsDuration<const volatile duration<Rep, Period>> : eastl::true_type{};
///////////////////////////////////////////////////////////////////////////////
// RatioGCD
///////////////////////////////////////////////////////////////////////////////
template <class Period1, class Period2>
struct RatioGCD
{
static_assert(IsRatio<Period1>::value, "Period1 is not a eastl::ratio type");
static_assert(IsRatio<Period2>::value, "Period2 is not a eastl::ratio type");
typedef ratio<eastl::Internal::gcd<Period1::num, Period2::num>::value,
eastl::Internal::lcm<Period1::den, Period2::den>::value> type;
};
};
///////////////////////////////////////////////////////////////////////////////
// 20.12.5.7, duration_cast
///////////////////////////////////////////////////////////////////////////////
namespace Internal
{
template <typename FromDuration,
typename ToDuration,
typename CommonPeriod =
typename ratio_divide<typename FromDuration::period, typename ToDuration::period>::type,
typename CommonRep = typename eastl::decay<typename eastl::common_type<typename ToDuration::rep,
typename FromDuration::rep,
intmax_t>::type>::type,
bool = CommonPeriod::num == 1,
bool = CommonPeriod::den == 1>
struct DurationCastImpl;
template <typename FromDuration, typename ToDuration, typename CommonPeriod, typename CommonRep>
struct DurationCastImpl<FromDuration, ToDuration, CommonPeriod, CommonRep, true, true>
{
inline static ToDuration DoCast(const FromDuration& fd)
{
return ToDuration(static_cast<typename ToDuration::rep>(fd.count()));
}
};
template <typename FromDuration, typename ToDuration, typename CommonPeriod, typename CommonRep>
struct DurationCastImpl<FromDuration, ToDuration, CommonPeriod, CommonRep, false, true>
{
inline static ToDuration DoCast(const FromDuration& d)
{
return ToDuration(static_cast<typename ToDuration::rep>(static_cast<CommonRep>(d.count()) *
static_cast<CommonRep>(CommonPeriod::num)));
}
};
template <typename FromDuration, typename ToDuration, typename CommonPeriod, typename CommonRep>
struct DurationCastImpl<FromDuration, ToDuration, CommonPeriod, CommonRep, true, false>
{
inline static ToDuration DoCast(const FromDuration& d)
{
return ToDuration(static_cast<typename ToDuration::rep>(static_cast<CommonRep>(d.count()) /
static_cast<CommonRep>(CommonPeriod::den)));
}
};
template <typename FromDuration, typename ToDuration, typename CommonPeriod, typename CommonRep>
struct DurationCastImpl<FromDuration, ToDuration, CommonPeriod, CommonRep, false, false>
{
inline static ToDuration DoCast(const FromDuration& d)
{
return ToDuration(static_cast<typename ToDuration::rep>(static_cast<CommonRep>(d.count()) *
static_cast<CommonRep>(CommonPeriod::num) /
static_cast<CommonRep>(CommonPeriod::den)));
}
};
}; // namespace Internal
///////////////////////////////////////////////////////////////////////////////
// duration_cast
///////////////////////////////////////////////////////////////////////////////
template <typename ToDuration, typename Rep, typename Period>
inline typename eastl::enable_if<Internal::IsDuration<ToDuration>::value, ToDuration>::type
duration_cast(const duration<Rep, Period>& d)
{
typedef typename duration<Rep, Period>::this_type FromDuration;
return Internal::DurationCastImpl<FromDuration, ToDuration>::DoCast(d);
}
///////////////////////////////////////////////////////////////////////////////
// duration
///////////////////////////////////////////////////////////////////////////////
template <class Rep, class Period>
class duration
{
Rep mRep;
public:
typedef Rep rep;
typedef Period period;
typedef duration<Rep, Period> this_type;
#if defined(EA_COMPILER_NO_DEFAULTED_FUNCTIONS)
EA_CONSTEXPR duration()
: mRep() {}
duration(const duration& other)
: mRep(Rep(other.mRep)) {}
duration& operator=(const duration& other)
{ mRep = other.mRep; return *this; }
#else
EA_CONSTEXPR duration() = default;
duration(const duration&) = default;
duration& operator=(const duration&) = default;
#endif
///////////////////////////////////////////////////////////////////////////////
// conversion constructors
///////////////////////////////////////////////////////////////////////////////
template <class Rep2>
inline EA_CONSTEXPR explicit duration(
const Rep2& rep2,
typename eastl::enable_if<eastl::is_convertible<Rep2, Rep>::value &&
(treat_as_floating_point<Rep>::value ||
!treat_as_floating_point<Rep2>::value)>::type** = 0)
: mRep(static_cast<Rep>(rep2)) {}
template <class Rep2, class Period2>
EA_CONSTEXPR duration(const duration<Rep2, Period2>& d2,
typename eastl::enable_if<treat_as_floating_point<Rep>::value ||
(eastl::ratio_divide<Period2, Period>::type::den == 1 &&
!treat_as_floating_point<Rep2>::value),
void>::type** = 0)
: mRep(duration_cast<duration>(d2).count()) {}
///////////////////////////////////////////////////////////////////////////////
// returns the count of ticks
///////////////////////////////////////////////////////////////////////////////
EA_CONSTEXPR Rep count() const { return mRep; }
///////////////////////////////////////////////////////////////////////////////
// static accessors of special duration values
///////////////////////////////////////////////////////////////////////////////
EA_CONSTEXPR inline static duration zero() { return duration(duration_values<Rep>::zero()); }
EA_CONSTEXPR inline static duration min() { return duration(duration_values<Rep>::min()); }
EA_CONSTEXPR inline static duration max() { return duration(duration_values<Rep>::max()); }
///////////////////////////////////////////////////////////////////////////////
// const arithmetic operations
///////////////////////////////////////////////////////////////////////////////
EA_CONSTEXPR inline duration operator+() const { return *this; }
EA_CONSTEXPR inline duration operator-() const { return duration(0-mRep); }
///////////////////////////////////////////////////////////////////////////////
// arithmetic operations
///////////////////////////////////////////////////////////////////////////////
inline duration operator++(int) { return duration(mRep++); }
inline duration operator--(int) { return duration(mRep--); }
inline duration& operator++() { ++mRep; return *this; }
inline duration& operator--() { --mRep; return *this; }
inline duration& operator+=(const duration& d) { mRep += d.count(); return *this; }
inline duration& operator-=(const duration& d) { mRep -= d.count(); return *this; }
inline duration& operator*=(const Rep& rhs) { mRep *= rhs; return *this; }
inline duration& operator/=(const Rep& rhs) { mRep /= rhs; return *this; }
inline duration& operator%=(const Rep& rhs) { mRep %= rhs; return *this; }
inline duration& operator%=(const duration& d) { mRep %= d.count(); return *this; }
};
///////////////////////////////////////////////////////////////////////////////
// 20.12.5.5, arithmetic operations with durations as arguments
///////////////////////////////////////////////////////////////////////////////
template <typename Rep1, typename Period1, typename Rep2, typename Period2>
typename eastl::common_type<duration<Rep1, Period1>, duration<Rep2, Period2>>::type EASTL_FORCE_INLINE
operator+(const duration<Rep1, Period1>& lhs, const duration<Rep2, Period2>& rhs)
{
typedef typename eastl::common_type<duration<Rep1, Period1>, duration<Rep2, Period2>>::type common_duration_t;
return common_duration_t(common_duration_t(lhs).count() + common_duration_t(rhs).count());
}
template <typename Rep1, typename Period1, typename Rep2, typename Period2>
typename eastl::common_type<duration<Rep1, Period1>, duration<Rep2, Period2>>::type EASTL_FORCE_INLINE
operator-(const duration<Rep1, Period1>& lhs, const duration<Rep2, Period2>& rhs)
{
typedef typename eastl::common_type<duration<Rep1, Period1>, duration<Rep2, Period2>>::type common_duration_t;
return common_duration_t(common_duration_t(lhs).count() - common_duration_t(rhs).count());
}
template <typename Rep1, typename Period1, typename Rep2>
duration<typename eastl::common_type<Rep1, Rep2>::type, Period1> EASTL_FORCE_INLINE
operator*(const duration<Rep1, Period1>& lhs, const Rep2& rhs)
{
typedef typename duration<eastl::common_type<Rep1, Rep2>, Period1>::type common_duration_t;
return common_duration_t(common_duration_t(lhs).count() * rhs);
}
template <typename Rep1, typename Rep2, typename Period2>
duration<typename eastl::common_type<Rep1, Rep2>::type, Period2> EASTL_FORCE_INLINE
operator*(const Rep1& lhs, const duration<Rep2, Period2>& rhs)
{
typedef duration<typename eastl::common_type<Rep1, Rep2>::type, Period2> common_duration_t;
return common_duration_t(lhs * common_duration_t(rhs).count());
}
template <typename Rep1, typename Period1, typename Rep2>
duration<typename eastl::common_type<Rep1, Rep2>::type, Period1> EASTL_FORCE_INLINE
operator/(const duration<Rep1, Period1>& lhs, const Rep2& rhs)
{
typedef duration<typename eastl::common_type<Rep1, Rep2>::type, Period1> common_duration_t;
return common_duration_t(common_duration_t(lhs).count() / rhs);
}
template <typename Rep1, typename Period1, typename Rep2, typename Period2>
typename eastl::common_type<duration<Rep1, Period1>, duration<Rep2, Period2>>::type EASTL_FORCE_INLINE
operator/(const duration<Rep1, Period1>& lhs, const duration<Rep2, Period2>& rhs)
{
typedef typename eastl::common_type<duration<Rep1, Period1>, duration<Rep2, Period2>>::type common_duration_t;
return common_duration_t(common_duration_t(lhs).count() / common_duration_t(rhs).count());
}
template <typename Rep1, typename Period1, typename Rep2>
duration<typename eastl::common_type<Rep1, Rep2>::type, Period1> EASTL_FORCE_INLINE
operator%(const duration<Rep1, Period1>& lhs, const Rep2& rhs)
{
typedef duration<typename eastl::common_type<Rep1, Rep2>::type, Period1> common_duration_t;
return common_duration_t(common_duration_t(lhs).count() % rhs);
}
template <typename Rep1, typename Period1, typename Rep2, typename Period2>
typename eastl::common_type<duration<Rep1, Period1>, duration<Rep2, Period2>>::type EASTL_FORCE_INLINE
operator%(const duration<Rep1, Period1>& lhs, const duration<Rep2, Period2>& rhs)
{
typedef typename eastl::common_type<duration<Rep1, Period1>, duration<Rep2, Period2>>::type common_duration_t;
return common_duration_t(common_duration_t(lhs).count() % common_duration_t(rhs).count());
}
///////////////////////////////////////////////////////////////////////////////
// 20.12.5.6, compares two durations
///////////////////////////////////////////////////////////////////////////////
template <typename Rep1, typename Period1, typename Rep2, typename Period2>
EASTL_FORCE_INLINE bool operator==(const duration<Rep1, Period1>& lhs,
const duration<Rep2, Period2>& rhs)
{
typedef typename eastl::common_type<duration<Rep1, Period1>, duration<Rep2, Period2>>::type common_duration_t;
return common_duration_t(lhs).count() == common_duration_t(rhs).count();
}
template <typename Rep1, typename Period1, typename Rep2, typename Period2>
EASTL_FORCE_INLINE bool operator<(const duration<Rep1, Period1>& lhs,
const duration<Rep2, Period2>& rhs)
{
typedef typename eastl::common_type<duration<Rep1, Period1>, duration<Rep2, Period2>>::type common_duration_t;
return common_duration_t(lhs).count() < common_duration_t(rhs).count();
}
template <typename Rep1, typename Period1, typename Rep2, typename Period2>
EASTL_FORCE_INLINE bool operator!=(const duration<Rep1, Period1>& lhs,
const duration<Rep2, Period2>& rhs)
{
return !(lhs == rhs);
}
template <typename Rep1, typename Period1, typename Rep2, typename Period2>
EASTL_FORCE_INLINE bool operator<=(const duration<Rep1, Period1>& lhs,
const duration<Rep2, Period2>& rhs)
{
return !(rhs < lhs);
}
template <typename Rep1, typename Period1, typename Rep2, typename Period2>
EASTL_FORCE_INLINE bool operator>(const duration<Rep1, Period1>& lhs,
const duration<Rep2, Period2>& rhs)
{
return rhs < lhs;
}
template <typename Rep1, typename Period1, typename Rep2, typename Period2>
EASTL_FORCE_INLINE bool operator>=(const duration<Rep1, Period1>& lhs,
const duration<Rep2, Period2>& rhs)
{
return !(lhs < rhs);
}
///////////////////////////////////////////////////////////////////////////////
// standard duration units
///////////////////////////////////////////////////////////////////////////////
typedef duration<long long, nano> nanoseconds;
typedef duration<long long, micro> microseconds;
typedef duration<long long, milli> milliseconds;
typedef duration<long long> seconds;
typedef duration<int, ratio<60>> minutes;
typedef duration<int, ratio<3600>> hours;
///////////////////////////////////////////////////////////////////////////////
// 20.12.6, time_point
///////////////////////////////////////////////////////////////////////////////
template <typename Clock, typename Duration = typename Clock::duration>
class time_point
{
Duration mDuration;
public:
typedef Clock clock;
typedef Duration duration;
typedef typename Duration::rep rep;
typedef typename Duration::period period;
inline EA_CONSTEXPR time_point() : mDuration(Duration::zero()) {}
EA_CONSTEXPR explicit time_point(const Duration& other) : mDuration(other) {}
template <typename Duration2>
inline EA_CONSTEXPR time_point(
const time_point<Clock, Duration2>& t,
typename eastl::enable_if<eastl::is_convertible<Duration2, Duration>::value>::type** = 0)
: mDuration(t.time_since_epoch()) {}
EA_CONSTEXPR Duration time_since_epoch() const { return mDuration; }
time_point& operator+=(const Duration& d) { mDuration += d; return *this; }
time_point& operator-=(const Duration& d) { mDuration -= d; return *this; }
static EA_CONSTEXPR time_point min() { return time_point(Duration::min()); }
static EA_CONSTEXPR time_point max() { return time_point(Duration::max()); }
};
///////////////////////////////////////////////////////////////////////////////
// 20.12.6.5, time_point arithmetic
///////////////////////////////////////////////////////////////////////////////
template <class Clock, class Duration1, class Rep2, class Period2>
inline EA_CONSTEXPR time_point<Clock, typename eastl::common_type<Duration1, duration<Rep2, Period2>>::type>
operator+(const time_point<Clock, Duration1>& lhs, const duration<Rep2, Period2>& rhs)
{
typedef time_point<Clock, typename eastl::common_type<Duration1, duration<Rep2, Period2>>::type> common_timepoint_t;
return common_timepoint_t(lhs.time_since_epoch() + rhs);
}
template <class Rep1, class Period1, class Clock, class Duration2>
inline EA_CONSTEXPR time_point<Clock, typename eastl::common_type<Duration2, duration<Rep1, Period1>>::type>
operator+(const duration<Rep1, Period1>& lhs, const time_point<Clock, Duration2>& rhs)
{
typedef time_point<Clock, typename eastl::common_type<Duration2, duration<Rep1, Period1>>::type> common_timepoint_t;
return common_timepoint_t(lhs + rhs.time_since_epoch());
}
template <class Clock, class Duration1, class Rep2, class Period2>
inline EA_CONSTEXPR time_point<Clock, typename eastl::common_type<Duration1, duration<Rep2, Period2>>::type>
operator-(const time_point<Clock, Duration1>& lhs, const duration<Rep2, Period2>& rhs)
{
typedef time_point<Clock, typename eastl::common_type<Duration1, duration<Rep2, Period2>>::type> common_timepoint_t;
return common_timepoint_t(lhs.time_since_epoch() - rhs);
}
template <class Clock, class Duration1, class Duration2>
inline EA_CONSTEXPR typename eastl::common_type<Duration1, Duration2>::type operator-(
const time_point<Clock, Duration1>& lhs,
const time_point<Clock, Duration2>& rhs)
{
return lhs.time_since_epoch() - rhs.time_since_epoch();
}
template <class Clock, class Duration1, class Duration2>
inline EA_CONSTEXPR bool operator==(const time_point<Clock, Duration1>& lhs,
const time_point<Clock, Duration2>& rhs)
{
return lhs.time_since_epoch() == rhs.time_since_epoch();
}
template <class Clock, class Duration1, class Duration2>
inline EA_CONSTEXPR bool operator!=(const time_point<Clock, Duration1>& lhs,
const time_point<Clock, Duration2>& rhs)
{
return !(lhs == rhs);
}
template <class Clock, class Duration1, class Duration2>
inline EA_CONSTEXPR bool operator<(const time_point<Clock, Duration1>& lhs, const time_point<Clock, Duration2>& rhs)
{
return lhs.time_since_epoch() < rhs.time_since_epoch();
}
template <class Clock, class Duration1, class Duration2>
inline EA_CONSTEXPR bool operator<=(const time_point<Clock, Duration1>& lhs,
const time_point<Clock, Duration2>& rhs)
{
return !(rhs < lhs);
}
template <class Clock, class Duration1, class Duration2>
inline EA_CONSTEXPR bool operator>(const time_point<Clock, Duration1>& lhs, const time_point<Clock, Duration2>& rhs)
{
return rhs < lhs;
}
template <class Clock, class Duration1, class Duration2>
inline EA_CONSTEXPR bool operator>=(const time_point<Clock, Duration1>& lhs,
const time_point<Clock, Duration2>& rhs)
{
return !(lhs < rhs);
}
///////////////////////////////////////////////////////////////////////////////
// 20.12.6.7, time_point_cast
///////////////////////////////////////////////////////////////////////////////
template <typename ToDuration, typename Clock, typename Duration>
EA_CONSTEXPR time_point<Clock, ToDuration> time_point_cast(
const time_point<Clock, Duration>& t,
typename eastl::enable_if<Internal::IsDuration<ToDuration>::value>::type** = 0)
{
return time_point<Clock, ToDuration>(duration_cast<ToDuration>(t.time_since_epoch()));
}
///////////////////////////////////////////////////////////////////////////////
// 20.12.7, clocks
///////////////////////////////////////////////////////////////////////////////
namespace Internal
{
#if defined(EA_PLATFORM_MICROSOFT) && !defined(EA_PLATFORM_MINGW)
#define EASTL_NS_PER_TICK 1
#elif defined EA_PLATFORM_SONY
#define EASTL_NS_PER_TICK _XTIME_NSECS_PER_TICK
#elif defined EA_PLATFORM_POSIX
#define EASTL_NS_PER_TICK _XTIME_NSECS_PER_TICK
#else
#define EASTL_NS_PER_TICK 100
#endif
#if defined(EA_PLATFORM_POSIX)
typedef chrono::nanoseconds::period SystemClock_Period;
typedef chrono::nanoseconds::period SteadyClock_Period;
#else
typedef eastl::ratio_multiply<eastl::ratio<EASTL_NS_PER_TICK, 1>, nano>::type SystemClock_Period;
typedef eastl::ratio_multiply<eastl::ratio<EASTL_NS_PER_TICK, 1>, nano>::type SteadyClock_Period;
#endif
///////////////////////////////////////////////////////////////////////////////
// Internal::GetTicks
///////////////////////////////////////////////////////////////////////////////
inline uint64_t GetTicks()
{
#if defined EA_PLATFORM_MICROSOFT
auto queryFrequency = []
{
LARGE_INTEGER frequency;
QueryPerformanceFrequency(&frequency);
return double(1000000000.0L / frequency.QuadPart); // nanoseconds per tick
};
auto queryCounter = []
{
LARGE_INTEGER counter;
QueryPerformanceCounter(&counter);
return counter.QuadPart;
};
EA_DISABLE_VC_WARNING(4640) // warning C4640: construction of local static object is not thread-safe (VS2013)
static auto frequency = queryFrequency(); // cache cpu frequency on first call
EA_RESTORE_VC_WARNING()
return uint64_t(frequency * queryCounter());
#elif defined EA_PLATFORM_SONY
return sceKernelGetProcessTimeCounter();
#elif defined(EA_PLATFORM_APPLE)
return mach_absolute_time();
#elif defined(EA_PLATFORM_POSIX) // Posix means Linux, Unix, and Macintosh OSX, among others (including Linux-based mobile platforms).
#if (defined(CLOCK_REALTIME) || defined(CLOCK_MONOTONIC))
timespec ts;
int result = clock_gettime(CLOCK_MONOTONIC, &ts);
if(result == EINVAL
)
result = clock_gettime(CLOCK_REALTIME, &ts);
const uint64_t nNanoseconds = (uint64_t)ts.tv_nsec + ((uint64_t)ts.tv_sec * UINT64_C(1000000000));
return nNanoseconds;
#else
struct timeval tv;
gettimeofday(&tv, NULL);
const uint64_t nMicroseconds = (uint64_t)tv.tv_usec + ((uint64_t)tv.tv_sec * 1000000);
return nMicroseconds;
#endif
#else
#error "chrono not implemented for platform"
#endif
}
} // namespace Internal
///////////////////////////////////////////////////////////////////////////////
// system_clock
///////////////////////////////////////////////////////////////////////////////
class system_clock
{
public:
typedef long long rep; // signed arithmetic type representing the number of ticks in the clock's duration
typedef Internal::SystemClock_Period period;
typedef chrono::duration<rep, period> duration; // duration<rep, period>, capable of representing negative durations
typedef chrono::time_point<system_clock> time_point;
// true if the time between ticks is always increases monotonically
EA_CONSTEXPR_OR_CONST static bool is_steady = false;
// returns a time point representing the current point in time.
static time_point now() EA_NOEXCEPT
{
return time_point(duration(Internal::GetTicks()));
}
};
///////////////////////////////////////////////////////////////////////////////
// steady_clock
///////////////////////////////////////////////////////////////////////////////
class steady_clock
{
public:
typedef long long rep; // signed arithmetic type representing the number of ticks in the clock's duration
typedef Internal::SteadyClock_Period period;
typedef chrono::duration<rep, period> duration; // duration<rep, period>, capable of representing negative durations
typedef chrono::time_point<steady_clock> time_point;
// true if the time between ticks is always increases monotonically
EA_CONSTEXPR_OR_CONST static bool is_steady = true;
// returns a time point representing the current point in time.
static time_point now() EA_NOEXCEPT
{
return time_point(duration(Internal::GetTicks()));
}
};
///////////////////////////////////////////////////////////////////////////////
// high_resolution_clock
///////////////////////////////////////////////////////////////////////////////
typedef system_clock high_resolution_clock;
} // namespace chrono
///////////////////////////////////////////////////////////////////////////////
// duration common_type specialization
///////////////////////////////////////////////////////////////////////////////
template <typename Rep1, typename Period1, typename Rep2, typename Period2>
struct common_type<chrono::duration<Rep1, Period1>, chrono::duration<Rep2, Period2>>
{
typedef chrono::duration<typename eastl::decay<typename eastl::common_type<Rep1, Rep2>::type>::type,
typename chrono::Internal::RatioGCD<Period1, Period2>::type> type;
};
///////////////////////////////////////////////////////////////////////////////
// time_point common_type specialization
///////////////////////////////////////////////////////////////////////////////
template <typename Clock, typename Duration1, typename Duration2>
struct common_type<chrono::time_point<Clock, Duration1>, chrono::time_point<Clock, Duration2>>
{
typedef chrono::time_point<Clock, typename eastl::common_type<Duration1, Duration2>::type> type;
};
///////////////////////////////////////////////////////////////////////////////
// chrono_literals
///////////////////////////////////////////////////////////////////////////////
#if EASTL_USER_LITERALS_ENABLED && EASTL_INLINE_NAMESPACES_ENABLED
EA_DISABLE_VC_WARNING(4455) // disable warning C4455: literal suffix identifiers that do not start with an underscore are reserved
inline namespace literals
{
inline namespace chrono_literals
{
///////////////////////////////////////////////////////////////////////////////
// integer chrono literals
///////////////////////////////////////////////////////////////////////////////
EA_CONSTEXPR chrono::hours operator"" h(unsigned long long h) { return chrono::hours(h); }
EA_CONSTEXPR chrono::minutes operator"" min(unsigned long long m) { return chrono::minutes(m); }
EA_CONSTEXPR chrono::seconds operator"" s(unsigned long long s) { return chrono::seconds(s); }
EA_CONSTEXPR chrono::milliseconds operator"" ms(unsigned long long ms) { return chrono::milliseconds(ms); }
EA_CONSTEXPR chrono::microseconds operator"" us(unsigned long long us) { return chrono::microseconds(us); }
EA_CONSTEXPR chrono::nanoseconds operator"" ns(unsigned long long ns) { return chrono::nanoseconds(ns); }
///////////////////////////////////////////////////////////////////////////////
// float chrono literals
///////////////////////////////////////////////////////////////////////////////
EA_CONSTEXPR chrono::duration<long double, ratio<3600, 1>> operator"" h(long double h)
{ return chrono::duration<long double, ratio<3600, 1>>(h); }
EA_CONSTEXPR chrono::duration<long double, ratio<60, 1>> operator"" min(long double m)
{ return chrono::duration<long double, ratio<60, 1>>(m); }
EA_CONSTEXPR chrono::duration<long double> operator"" s(long double s)
{ return chrono::duration<long double>(s); }
EA_CONSTEXPR chrono::duration<float, milli> operator"" ms(long double ms)
{ return chrono::duration<long double, milli>(ms); }
EA_CONSTEXPR chrono::duration<float, micro> operator"" us(long double us)
{ return chrono::duration<long double, micro>(us); }
EA_CONSTEXPR chrono::duration<float, nano> operator"" ns(long double ns)
{ return chrono::duration<long double, nano>(ns); }
} // namespace chrono_literals
}// namespace literals
EA_RESTORE_VC_WARNING() // warning: 4455
#endif
} // namespace eastl
#if EASTL_USER_LITERALS_ENABLED && EASTL_INLINE_NAMESPACES_ENABLED
namespace chrono
{
using namespace eastl::literals::chrono_literals;
} // namespace chrono
#endif
#endif
| 43.17047 | 136 | 0.589827 | [
"object"
] |
45b024a79926c197bba525d7c613a47b0e65c9cc | 1,876 | h | C | deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgPlugins/txp/TXPPageManager.h | UM-ARM-Lab/mab_ms | f199f05b88060182cfbb47706bd1ff3479032c43 | [
"BSD-2-Clause"
] | 3 | 2018-08-20T12:12:43.000Z | 2021-06-06T09:43:27.000Z | deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgPlugins/txp/TXPPageManager.h | UM-ARM-Lab/mab_ms | f199f05b88060182cfbb47706bd1ff3479032c43 | [
"BSD-2-Clause"
] | null | null | null | deform_control/external_libs/OpenSceneGraph-2.8.5/src/osgPlugins/txp/TXPPageManager.h | UM-ARM-Lab/mab_ms | f199f05b88060182cfbb47706bd1ff3479032c43 | [
"BSD-2-Clause"
] | 1 | 2022-03-31T03:12:23.000Z | 2022-03-31T03:12:23.000Z | /***************************************************************************
* December 2003
*
* This TerraPage loader was re-written in a fashion to use PagedLOD
* to manage paging entirely, also includes a version of Terrex's smart mesh
* adapted to work with PagedLOD. The essential code by Boris Bralo is still present,
* slight modified.
* nick at terrex dot com
*
* Ported to PagedLOD technology by Trajce Nikolov (Nick) & Robert Osfield
*****************************************************************************/
/***************************************************************************
* OpenSceneGraph loader for Terrapage format database
* by Boris Bralo 2002
*
* based on/modifed sgl (Scene Graph Library) loader by Bryan Walsh
*
* This loader is based on/modified from Terrain Experts Performer Loader,
* and was ported to SGL by Bryan Walsh / bryanw at earthlink dot net
*
* That loader is redistributed under the terms listed on Terrain Experts
* website (www.terrex.com/www/pages/technology/technologypage.htm)
*
* "TerraPage is provided as an Open Source format for use by anyone...
* We supply the TerraPage C++ source code free of charge. Anyone
* can use it and redistribute it as needed (including our competitors).
* We do, however, ask that you keep the TERREX copyrights intact."
*
* Copyright Terrain Experts Inc. 1999.
* All Rights Reserved.
*
*****************************************************************************/
#ifndef __TXPPAGEMANAGER_H_
#define __TXPPAGEMANAGER_H_
#include "trpage_sys.h"
#include "trpage_read.h"
#include "trpage_managers.h"
#include <osg/Referenced>
namespace txp
{
class TXPPageManager : public trpgPageManager, public osg::Referenced
{
public:
TXPPageManager();
protected:
virtual ~TXPPageManager();
};
} // namespace
#endif // __TXPPAGEMANAGER_H_
| 32.344828 | 86 | 0.619403 | [
"mesh"
] |
45b66b07d4abc93e4304669e608108ec1eff960b | 8,311 | h | C | FreeBSD/sys/netgraph/ng_l2tp.h | TigerBSD/FreeBSD-Custom-ThinkPad | 3d092f261b362f73170871403397fc5d6b89d1dc | [
"0BSD"
] | 91 | 2018-11-24T05:33:58.000Z | 2022-03-16T05:58:05.000Z | FreeBSD/sys/netgraph/ng_l2tp.h | TigerBSD/FreeBSD-Custom-ThinkPad | 3d092f261b362f73170871403397fc5d6b89d1dc | [
"0BSD"
] | 21 | 2016-08-11T09:43:43.000Z | 2017-01-29T12:52:56.000Z | FreeBSD/sys/netgraph/ng_l2tp.h | TigerBSD/TigerBSD | 3d092f261b362f73170871403397fc5d6b89d1dc | [
"0BSD"
] | 18 | 2018-11-24T10:35:29.000Z | 2021-04-22T07:22:10.000Z | /*-
* Copyright (c) 2001-2002 Packet Design, LLC.
* All rights reserved.
*
* Subject to the following obligations and disclaimer of warranty,
* use and redistribution of this software, in source or object code
* forms, with or without modifications are expressly permitted by
* Packet Design; provided, however, that:
*
* (i) Any and all reproductions of the source or object code
* must include the copyright notice above and the following
* disclaimer of warranties; and
* (ii) No rights are granted, in any manner or form, to use
* Packet Design trademarks, including the mark "PACKET DESIGN"
* on advertising, endorsements, or otherwise except as such
* appears in the above copyright notice or in the software.
*
* THIS SOFTWARE IS BEING PROVIDED BY PACKET DESIGN "AS IS", AND
* TO THE MAXIMUM EXTENT PERMITTED BY LAW, PACKET DESIGN MAKES NO
* REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED, REGARDING
* THIS SOFTWARE, INCLUDING WITHOUT LIMITATION, ANY AND ALL IMPLIED
* WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE,
* OR NON-INFRINGEMENT. PACKET DESIGN DOES NOT WARRANT, GUARANTEE,
* OR MAKE ANY REPRESENTATIONS REGARDING THE USE OF, OR THE RESULTS
* OF THE USE OF THIS SOFTWARE IN TERMS OF ITS CORRECTNESS, ACCURACY,
* RELIABILITY OR OTHERWISE. IN NO EVENT SHALL PACKET DESIGN BE
* LIABLE FOR ANY DAMAGES RESULTING FROM OR ARISING OUT OF ANY USE
* OF THIS SOFTWARE, INCLUDING WITHOUT LIMITATION, ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, PUNITIVE, OR CONSEQUENTIAL
* DAMAGES, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, LOSS OF
* USE, DATA OR PROFITS, HOWEVER CAUSED AND UNDER 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 PACKET DESIGN IS ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*
* Author: Archie Cobbs <archie@freebsd.org>
*
* $FreeBSD$
*/
#ifndef _NETGRAPH_NG_L2TP_H_
#define _NETGRAPH_NG_L2TP_H_
/* Node type name and magic cookie */
#define NG_L2TP_NODE_TYPE "l2tp"
#define NGM_L2TP_COOKIE 1091515793
/* Hook names */
#define NG_L2TP_HOOK_CTRL "ctrl" /* control channel hook */
#define NG_L2TP_HOOK_LOWER "lower" /* hook to lower layers */
/* Session hooks: prefix plus hex session ID, e.g., "session_3e14" */
#define NG_L2TP_HOOK_SESSION_P "session_" /* session data hook (prefix) */
#define NG_L2TP_HOOK_SESSION_F "session_%04x" /* session data hook (format) */
/* Set initial sequence numbers to not yet enabled node. */
struct ng_l2tp_seq_config {
u_int16_t ns; /* sequence number to send next */
u_int16_t nr; /* sequence number to be recved next */
u_int16_t rack; /* last 'nr' received */
u_int16_t xack; /* last 'nr' sent */
};
/* Keep this in sync with the above structure definition. */
#define NG_L2TP_SEQ_CONFIG_TYPE_INFO { \
{ "ns", &ng_parse_uint16_type }, \
{ "nr", &ng_parse_uint16_type }, \
{ NULL } \
}
/* Configuration for a node */
struct ng_l2tp_config {
u_char enabled; /* enables traffic flow */
u_char match_id; /* tunnel id must match 'tunnel_id' */
u_int16_t tunnel_id; /* local tunnel id */
u_int16_t peer_id; /* peer's tunnel id */
u_int16_t peer_win; /* peer's max recv window size */
u_int16_t rexmit_max; /* max retransmits before failure */
u_int16_t rexmit_max_to; /* max delay between retransmits */
};
/* Keep this in sync with the above structure definition */
#define NG_L2TP_CONFIG_TYPE_INFO { \
{ "enabled", &ng_parse_uint8_type }, \
{ "match_id", &ng_parse_uint8_type }, \
{ "tunnel_id", &ng_parse_hint16_type }, \
{ "peer_id", &ng_parse_hint16_type }, \
{ "peer_win", &ng_parse_uint16_type }, \
{ "rexmit_max", &ng_parse_uint16_type }, \
{ "rexmit_max_to", &ng_parse_uint16_type }, \
{ NULL } \
}
/* Configuration for a session hook */
struct ng_l2tp_sess_config {
u_int16_t session_id; /* local session id */
u_int16_t peer_id; /* peer's session id */
u_char control_dseq; /* whether we control data sequencing */
u_char enable_dseq; /* whether to enable data sequencing */
u_char include_length; /* whether to include length field */
};
/* Keep this in sync with the above structure definition */
#define NG_L2TP_SESS_CONFIG_TYPE_INFO { \
{ "session_id", &ng_parse_hint16_type }, \
{ "peer_id", &ng_parse_hint16_type }, \
{ "control_dseq", &ng_parse_uint8_type }, \
{ "enable_dseq", &ng_parse_uint8_type }, \
{ "include_length", &ng_parse_uint8_type }, \
{ NULL } \
}
/* Statistics struct */
struct ng_l2tp_stats {
u_int32_t xmitPackets; /* number of packets xmit */
u_int32_t xmitOctets; /* number of octets xmit */
u_int32_t xmitZLBs; /* ack-only packets transmitted */
u_int32_t xmitDrops; /* xmits dropped due to full window */
u_int32_t xmitTooBig; /* ctrl pkts dropped because too big */
u_int32_t xmitInvalid; /* ctrl packets with no session ID */
u_int32_t xmitDataTooBig; /* data pkts dropped because too big */
u_int32_t xmitRetransmits; /* retransmitted packets */
u_int32_t recvPackets; /* number of packets rec'd */
u_int32_t recvOctets; /* number of octets rec'd */
u_int32_t recvRunts; /* too short packets rec'd */
u_int32_t recvInvalid; /* invalid packets rec'd */
u_int32_t recvWrongTunnel; /* packets rec'd with wrong tunnel id */
u_int32_t recvUnknownSID; /* pkts rec'd with unknown session id */
u_int32_t recvBadAcks; /* ctrl pkts rec'd with invalid 'nr' */
u_int32_t recvOutOfOrder; /* out of order ctrl pkts rec'd */
u_int32_t recvDuplicates; /* duplicate ctrl pkts rec'd */
u_int32_t recvDataDrops; /* dup/out of order data pkts rec'd */
u_int32_t recvZLBs; /* ack-only packets rec'd */
u_int32_t memoryFailures; /* times we couldn't allocate memory */
};
/* Keep this in sync with the above structure definition */
#define NG_L2TP_STATS_TYPE_INFO { \
{ "xmitPackets", &ng_parse_uint32_type }, \
{ "xmitOctets", &ng_parse_uint32_type }, \
{ "xmitZLBs", &ng_parse_uint32_type }, \
{ "xmitDrops", &ng_parse_uint32_type }, \
{ "xmitTooBig", &ng_parse_uint32_type }, \
{ "xmitInvalid", &ng_parse_uint32_type }, \
{ "xmitDataTooBig", &ng_parse_uint32_type }, \
{ "xmitRetransmits", &ng_parse_uint32_type }, \
{ "recvPackets", &ng_parse_uint32_type }, \
{ "recvOctets", &ng_parse_uint32_type }, \
{ "recvRunts", &ng_parse_uint32_type }, \
{ "recvInvalid", &ng_parse_uint32_type }, \
{ "recvWrongTunnel", &ng_parse_uint32_type }, \
{ "recvUnknownSID", &ng_parse_uint32_type }, \
{ "recvBadAcks", &ng_parse_uint32_type }, \
{ "recvOutOfOrder", &ng_parse_uint32_type }, \
{ "recvDuplicates", &ng_parse_uint32_type }, \
{ "recvDataDrops", &ng_parse_uint32_type }, \
{ "recvZLBs", &ng_parse_uint32_type }, \
{ "memoryFailures", &ng_parse_uint32_type }, \
{ NULL } \
}
/* Session statistics struct. */
struct ng_l2tp_session_stats {
u_int64_t xmitPackets; /* number of packets xmit */
u_int64_t xmitOctets; /* number of octets xmit */
u_int64_t recvPackets; /* number of packets received */
u_int64_t recvOctets; /* number of octets received */
};
/* Keep this in sync with the above structure definition. */
#define NG_L2TP_SESSION_STATS_TYPE_INFO { \
{ "xmitPackets", &ng_parse_uint64_type }, \
{ "xmitOctets", &ng_parse_uint64_type }, \
{ "recvPackets", &ng_parse_uint64_type }, \
{ "recvOctets", &ng_parse_uint64_type }, \
{ NULL } \
}
/* Netgraph commands */
enum {
NGM_L2TP_SET_CONFIG = 1, /* supply a struct ng_l2tp_config */
NGM_L2TP_GET_CONFIG, /* returns a struct ng_l2tp_config */
NGM_L2TP_SET_SESS_CONFIG, /* supply struct ng_l2tp_sess_config */
NGM_L2TP_GET_SESS_CONFIG, /* supply a session id (u_int16_t) */
NGM_L2TP_GET_STATS, /* returns struct ng_l2tp_stats */
NGM_L2TP_CLR_STATS, /* clears stats */
NGM_L2TP_GETCLR_STATS, /* returns & clears stats */
NGM_L2TP_GET_SESSION_STATS, /* returns session stats */
NGM_L2TP_CLR_SESSION_STATS, /* clears session stats */
NGM_L2TP_GETCLR_SESSION_STATS, /* returns & clears session stats */
NGM_L2TP_ACK_FAILURE, /* sent *from* node after ack timeout */
NGM_L2TP_SET_SEQ /* supply a struct ng_l2tp_seq_config */
};
#endif /* _NETGRAPH_NG_L2TP_H_ */
| 42.187817 | 78 | 0.711226 | [
"object"
] |
45b847923eb9249c642571d5fab9ab3190c82034 | 10,730 | c | C | src/libserver/roll_history.c | msuslu/rspamd | 95764f816a9e1251a755c6edad339637345cfe28 | [
"Apache-2.0"
] | null | null | null | src/libserver/roll_history.c | msuslu/rspamd | 95764f816a9e1251a755c6edad339637345cfe28 | [
"Apache-2.0"
] | null | null | null | src/libserver/roll_history.c | msuslu/rspamd | 95764f816a9e1251a755c6edad339637345cfe28 | [
"Apache-2.0"
] | 1 | 2022-02-20T17:41:48.000Z | 2022-02-20T17:41:48.000Z | /*-
* Copyright 2016 Vsevolod Stakhov
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "config.h"
#include "rspamd.h"
#include "libmime/message.h"
#include "lua/lua_common.h"
#include "unix-std.h"
#include "cfg_file_private.h"
static const gchar rspamd_history_magic_old[] = {'r', 's', 'h', '1'};
/**
* Returns new roll history
* @param pool pool for shared memory
* @return new structure
*/
struct roll_history *
rspamd_roll_history_new (rspamd_mempool_t *pool, guint max_rows,
struct rspamd_config *cfg)
{
struct roll_history *history;
lua_State *L = cfg->lua_state;
if (pool == NULL || max_rows == 0) {
return NULL;
}
history = rspamd_mempool_alloc0_shared (pool, sizeof (struct roll_history));
/*
* Here, we check if there is any plugin that handles history,
* in this case, we disable this code completely
*/
lua_getglobal (L, "rspamd_plugins");
if (lua_istable (L, -1)) {
lua_pushstring (L, "history");
lua_gettable (L, -2);
if (lua_istable (L, -1)) {
history->disabled = TRUE;
}
lua_pop (L, 1);
}
lua_pop (L, 1);
if (!history->disabled) {
history->rows = rspamd_mempool_alloc0_shared (pool,
sizeof (struct roll_history_row) * max_rows);
history->nrows = max_rows;
}
return history;
}
struct history_metric_callback_data {
gchar *pos;
gint remain;
};
static void
roll_history_symbols_callback (gpointer key, gpointer value, void *user_data)
{
struct history_metric_callback_data *cb = user_data;
struct rspamd_symbol_result *s = value;
guint wr;
if (s->flags & RSPAMD_SYMBOL_RESULT_IGNORED) {
return;
}
if (cb->remain > 0) {
wr = rspamd_snprintf (cb->pos, cb->remain, "%s, ", s->name);
cb->pos += wr;
cb->remain -= wr;
}
}
/**
* Update roll history with data from task
* @param history roll history object
* @param task task object
*/
void
rspamd_roll_history_update (struct roll_history *history,
struct rspamd_task *task)
{
guint row_num;
struct roll_history_row *row;
struct rspamd_scan_result *metric_res;
struct history_metric_callback_data cbdata;
struct rspamd_action *action;
if (history->disabled) {
return;
}
/* First of all obtain check and obtain row number */
g_atomic_int_compare_and_exchange (&history->cur_row, history->nrows, 0);
#if ((GLIB_MAJOR_VERSION == 2) && (GLIB_MINOR_VERSION > 30))
row_num = g_atomic_int_add (&history->cur_row, 1);
#else
row_num = g_atomic_int_exchange_and_add (&history->cur_row, 1);
#endif
if (row_num < history->nrows) {
row = &history->rows[row_num];
g_atomic_int_set (&row->completed, FALSE);
}
else {
/* Race condition */
history->cur_row = 0;
return;
}
/* Add information from task to roll history */
if (task->from_addr) {
rspamd_strlcpy (row->from_addr,
rspamd_inet_address_to_string (task->from_addr),
sizeof (row->from_addr));
}
else {
rspamd_strlcpy (row->from_addr, "unknown", sizeof (row->from_addr));
}
row->timestamp = task->task_timestamp;
/* Strings */
if (task->message) {
rspamd_strlcpy (row->message_id, MESSAGE_FIELD (task, message_id),
sizeof (row->message_id));
}
if (task->auth_user) {
rspamd_strlcpy (row->user, task->auth_user, sizeof (row->user));
}
else {
row->user[0] = '\0';
}
/* Get default metric */
metric_res = task->result;
if (metric_res == NULL) {
row->symbols[0] = '\0';
row->action = METRIC_ACTION_NOACTION;
}
else {
row->score = metric_res->score;
action = rspamd_check_action_metric (task, NULL, NULL);
row->action = action->action_type;
row->required_score = rspamd_task_get_required_score (task, metric_res);
cbdata.pos = row->symbols;
cbdata.remain = sizeof (row->symbols);
rspamd_task_symbol_result_foreach (task, NULL,
roll_history_symbols_callback,
&cbdata);
if (cbdata.remain > 0) {
/* Remove last whitespace and comma */
*cbdata.pos-- = '\0';
*cbdata.pos-- = '\0';
*cbdata.pos = '\0';
}
}
row->scan_time = task->time_real_finish - task->task_timestamp;
row->len = task->msg.len;
g_atomic_int_set (&row->completed, TRUE);
}
/**
* Load previously saved history from file
* @param history roll history object
* @param filename filename to load from
* @return TRUE if history has been loaded
*/
gboolean
rspamd_roll_history_load (struct roll_history *history, const gchar *filename)
{
gint fd;
struct stat st;
gchar magic[sizeof(rspamd_history_magic_old)];
ucl_object_t *top;
const ucl_object_t *cur, *elt;
struct ucl_parser *parser;
struct roll_history_row *row;
guint n, i;
g_assert (history != NULL);
if (history->disabled) {
return TRUE;
}
if (stat (filename, &st) == -1) {
msg_info ("cannot load history from %s: %s", filename,
strerror (errno));
return FALSE;
}
if ((fd = open (filename, O_RDONLY)) == -1) {
msg_info ("cannot load history from %s: %s", filename,
strerror (errno));
return FALSE;
}
/* Check for old format */
if (read (fd, magic, sizeof (magic)) == -1) {
close (fd);
msg_info ("cannot read history from %s: %s", filename,
strerror (errno));
return FALSE;
}
if (memcmp (magic, rspamd_history_magic_old, sizeof (magic)) == 0) {
close (fd);
msg_warn ("cannot read history from old format %s, "
"it will be replaced after restart", filename);
return FALSE;
}
parser = ucl_parser_new (0);
if (!ucl_parser_add_fd (parser, fd)) {
msg_warn ("cannot parse history file %s: %s", filename,
ucl_parser_get_error (parser));
ucl_parser_free (parser);
close (fd);
return FALSE;
}
top = ucl_parser_get_object (parser);
ucl_parser_free (parser);
close (fd);
if (top == NULL) {
msg_warn ("cannot parse history file %s: no object", filename);
return FALSE;
}
if (ucl_object_type (top) != UCL_ARRAY) {
msg_warn ("invalid object type read from: %s", filename);
ucl_object_unref (top);
return FALSE;
}
if (top->len > history->nrows) {
msg_warn ("stored history is larger than the current one: %ud (file) vs "
"%ud (history)", top->len, history->nrows);
n = history->nrows;
}
else if (top->len < history->nrows) {
msg_warn (
"stored history is smaller than the current one: %ud (file) vs "
"%ud (history)",
top->len, history->nrows);
n = top->len;
}
else {
n = top->len;
}
for (i = 0; i < n; i ++) {
cur = ucl_array_find_index (top, i);
if (cur != NULL && ucl_object_type (cur) == UCL_OBJECT) {
row = &history->rows[i];
memset (row, 0, sizeof (*row));
elt = ucl_object_lookup (cur, "time");
if (elt && ucl_object_type (elt) == UCL_FLOAT) {
row->timestamp = ucl_object_todouble (elt);
}
elt = ucl_object_lookup (cur, "id");
if (elt && ucl_object_type (elt) == UCL_STRING) {
rspamd_strlcpy (row->message_id, ucl_object_tostring (elt),
sizeof (row->message_id));
}
elt = ucl_object_lookup (cur, "symbols");
if (elt && ucl_object_type (elt) == UCL_STRING) {
rspamd_strlcpy (row->symbols, ucl_object_tostring (elt),
sizeof (row->symbols));
}
elt = ucl_object_lookup (cur, "user");
if (elt && ucl_object_type (elt) == UCL_STRING) {
rspamd_strlcpy (row->user, ucl_object_tostring (elt),
sizeof (row->user));
}
elt = ucl_object_lookup (cur, "from");
if (elt && ucl_object_type (elt) == UCL_STRING) {
rspamd_strlcpy (row->from_addr, ucl_object_tostring (elt),
sizeof (row->from_addr));
}
elt = ucl_object_lookup (cur, "len");
if (elt && ucl_object_type (elt) == UCL_INT) {
row->len = ucl_object_toint (elt);
}
elt = ucl_object_lookup (cur, "scan_time");
if (elt && ucl_object_type (elt) == UCL_FLOAT) {
row->scan_time = ucl_object_todouble (elt);
}
elt = ucl_object_lookup (cur, "score");
if (elt && ucl_object_type (elt) == UCL_FLOAT) {
row->score = ucl_object_todouble (elt);
}
elt = ucl_object_lookup (cur, "required_score");
if (elt && ucl_object_type (elt) == UCL_FLOAT) {
row->required_score = ucl_object_todouble (elt);
}
elt = ucl_object_lookup (cur, "action");
if (elt && ucl_object_type (elt) == UCL_INT) {
row->action = ucl_object_toint (elt);
}
row->completed = TRUE;
}
}
ucl_object_unref (top);
history->cur_row = n;
return TRUE;
}
/**
* Save history to file
* @param history roll history object
* @param filename filename to load from
* @return TRUE if history has been saved
*/
gboolean
rspamd_roll_history_save (struct roll_history *history, const gchar *filename)
{
gint fd;
FILE *fp;
ucl_object_t *obj, *elt;
guint i;
struct roll_history_row *row;
struct ucl_emitter_functions *emitter_func;
g_assert (history != NULL);
if (history->disabled) {
return TRUE;
}
if ((fd = open (filename, O_WRONLY | O_CREAT | O_TRUNC, 00600)) == -1) {
msg_info ("cannot save history to %s: %s", filename, strerror (errno));
return FALSE;
}
fp = fdopen (fd, "w");
obj = ucl_object_typed_new (UCL_ARRAY);
for (i = 0; i < history->nrows; i ++) {
row = &history->rows[i];
if (!row->completed) {
continue;
}
elt = ucl_object_typed_new (UCL_OBJECT);
ucl_object_insert_key (elt, ucl_object_fromdouble (row->timestamp),
"time", 0, false);
ucl_object_insert_key (elt, ucl_object_fromstring (row->message_id),
"id", 0, false);
ucl_object_insert_key (elt, ucl_object_fromstring (row->symbols),
"symbols", 0, false);
ucl_object_insert_key (elt, ucl_object_fromstring (row->user),
"user", 0, false);
ucl_object_insert_key (elt, ucl_object_fromstring (row->from_addr),
"from", 0, false);
ucl_object_insert_key (elt, ucl_object_fromint (row->len),
"len", 0, false);
ucl_object_insert_key (elt, ucl_object_fromdouble (row->scan_time),
"scan_time", 0, false);
ucl_object_insert_key (elt, ucl_object_fromdouble (row->score),
"score", 0, false);
ucl_object_insert_key (elt, ucl_object_fromdouble (row->required_score),
"required_score", 0, false);
ucl_object_insert_key (elt, ucl_object_fromint (row->action),
"action", 0, false);
ucl_array_append (obj, elt);
}
emitter_func = ucl_object_emit_file_funcs (fp);
ucl_object_emit_full (obj, UCL_EMIT_JSON_COMPACT, emitter_func, NULL);
ucl_object_emit_funcs_free (emitter_func);
ucl_object_unref (obj);
fclose (fp);
return TRUE;
}
| 24.837963 | 78 | 0.675489 | [
"object"
] |
45b9142e68f0af8efedda20bcbd5f697cf2b2751 | 6,897 | c | C | vos/tae53_changes/src/lib/tae/xcobr.c | NASA-AMMOS/VICAR | 4504c1f558855d9c6eaef89f4460217aa4909f8e | [
"BSD-3-Clause"
] | 16 | 2020-10-21T05:56:26.000Z | 2022-03-31T10:02:01.000Z | vos/tae53_changes/src/lib/tae/xcobr.c | NASA-AMMOS/VICAR | 4504c1f558855d9c6eaef89f4460217aa4909f8e | [
"BSD-3-Clause"
] | null | null | null | vos/tae53_changes/src/lib/tae/xcobr.c | NASA-AMMOS/VICAR | 4504c1f558855d9c6eaef89f4460217aa4909f8e | [
"BSD-3-Clause"
] | 2 | 2021-03-09T01:51:08.000Z | 2021-03-23T00:23:24.000Z | /****************************************************************************
* Copyright (c) 1993, 1994
* Century Computing, Inc.
* ALL RIGHTS RESERVED
*
* The software (programs, data bases and/or documentation) on or in
* any media can not be reproduced, disclosed, or used except under
* the terms of the TAE Plus Software License Agreement.
*
***************************************************************************/
/* FORTRAN to "C" outer bridge */
/*
* TAE version 4 XCO_ bridges for manipulation of collections of
* Vm Objects
* FORTRAN-callable.
*
* CHANGE LOG:
* 6/22/89 Initial Cut...rsg/AS
*
*/
#include "taeconf.inp" /* TAE configuration (REQUIRED) */
#include "forstr.inp" /* fortran-77 string struct */
#include "taeintproto.h"
FUNCTION VOID BRIDGE2_NAME(xco_add)
(
TAEINT *c, /* in: id of the collection to add the object to */
Id *objid, /* in: id of the object to be added to collection */
FORSTR *memnam, /* in: name ofthe member object */
TAEINT *type, /* in: type of the object */
TAEINT *status /* out: SUCCESS or error code */
);
FUNCTION VOID BRIDGE2_NAME(xco_remove)
(
TAEINT *colxid, /* in: collection id */
FORSTR *memnam, /* in: name of the member to be removed */
TAEINT *status /* out: SUCCESS or error code */
);
FUNCTION VOID BRIDGE2_NAME(xco_find)
(
TAEINT *colxid, /* in: collection id */
FORSTR *memnam, /* in: name of member object */
TAEINT *objid, /* out: id of the object found */
TAEINT *type, /* out: type of object specified in xcadd call */
TAEINT *status /* out: SUCCESS or error code */
);
FUNCTION VOID BRIDGE2_NAME(xco_find_next)
(
TAEINT *colxid, /* in: collection id */
FORSTR *memnam, /* in/out: name of member object */
TAEINT *objid, /* in/out: id of the object found */
TAEINT *type, /* out: type of object specified in xcadd call */
TAEINT *status /* out: SUCCESS or error code */
);
FUNCTION VOID BRIDGE2_NAME(xco_free)
(
TAEINT *colxid, /* in: collection id */
TAEINT *status /* out: SUCCESS or error code */
);
FUNCTION VOID BRIDGE2_NAME(xco_new)
(
TAEINT *colxid, /* out: collection id */
TAEINT *flags, /* in: currently ignored */
TAEINT *status /* out: SUCCESS or error code */
);
FUNCTION VOID BRIDGE2_NAME(xco_read_file)
(
TAEINT *colxid, /* in: collection id */
FORSTR *fspec, /* in: file specification of resource file */
TAEINT *mode, /* in: to be used for the vm objects created */
TAEINT *status /* out: SUCCESS or error code */
);
FUNCTION VOID BRIDGE2_NAME(xco_write_file)
(
TAEINT *colxid, /* in: collection id */
FORSTR *fspec, /* in: file specification of resouce file */
TAEINT *status /* out: SUCCESS or error code */
);
/*
* xco_add: add member to collection
*/
FUNCTION VOID BRIDGE1_NAME(xco_add)
(
TAEINT *colxid, /* in: id of the collection to add the object to */
TAEINT *objid, /* in: id of the object to be added to collection */
TEXT *memnam, /* in: text name ofthe member object */
TAEINT *type, /* in: type of the object */
TAEINT *status, /* out: SUCCESS or error code */
STRLEN memnaml
)
{
// This is actually *broken* on 64-bit systems, a 32 bit
// integer can't be cast to a 64 bit pointer. Leave this
// in place to get a clean compile, but trigger an error
// if this is actually called.
printf("Calling a broken function. This can't be fixed on a 64 bit system");
abort();
/* FORSTR memnamd; */
/* memnamd.length = GETLEN(memnaml); */
/* memnamd.pointer = memnam; */
/* BRIDGE2_NAME(xco_add) (colxid, objid, &memnamd, type, status); */
/* return; */
}
/*
* xco_remove: remove a member from the collection
*/
FUNCTION VOID BRIDGE1_NAME(xco_remove)
(
TAEINT *colxid, /* in: collection id */
TEXT *memnam, /* in: name of the member to be removed */
TAEINT *status, /* out: SUCCESS or error code */
STRLEN memnaml
)
{
FORSTR memnamd;
memnamd.length = GETLEN(memnaml);
memnamd.pointer = memnam;
BRIDGE2_NAME(xco_remove) (colxid, &memnamd, status);
}
/*
* xco_find: find specific member
*/
FUNCTION VOID BRIDGE1_NAME(xco_find)
(
TAEINT *colxid, /* in: collection id */
TEXT *memnam, /* in: text name of member object */
TAEINT *objid, /* out: id of the object found */
TAEINT *type, /* out: type of object specified in xcadd call */
TAEINT *status, /* out: SUCCESS or error code */
STRLEN memnaml
)
{
FORSTR memnamd;
memnamd.length = GETLEN(memnaml);
memnamd.pointer = memnam;
BRIDGE2_NAME(xco_find) (colxid, &memnamd, objid, type, status);
return;
}
/*
* xco_find_next: find next member
* (for looping through and operating on each member of a collection)
*/
FUNCTION VOID BRIDGE1_NAME(xco_find_next)
(
TAEINT *colxid, /* in: collection id */
TEXT *memnam, /* out: text name of next member object */
TAEINT *objid, /* out: id of the object found */
TAEINT *type, /* out: type of object specified in xcadd call */
TAEINT *status, /* out: SUCCESS or error code */
STRLEN memnaml
)
{
FORSTR memnamd;
memnamd.length = GETLEN(memnaml);
memnamd.pointer = memnam;
BRIDGE2_NAME(xco_find_next) ( colxid, &memnamd, objid, type, status);
return;
}
/*
* xco_free: free a collection
*/
FUNCTION VOID BRIDGE1_NAME(xco_free)
(
TAEINT *colxid, /* in: collection id */
TAEINT *status /* out: SUCCESS or error code */
)
{
BRIDGE2_NAME(xco_free) (colxid, status);
return;
}
/*
* xco_new: create an empty collection
*/
/* FUNCTION VOID BRIDGE1_NAME(xco_new) (colxid, flags, status) */
/* TAEINT *colxid; /\* out: collection id *\/ */
/* TAEINT *flags; /\* in: currently ignored *\/ */
/* TAEINT *status; /\* out: SUCCESS or error code *\/ */
/* { */
/* BRIDGE2_NAME(xcnew) (colxid, flags, status); */
/* return; */
/* } */
/*
* xco_read_file: read collection of vm objects from a tae plus resource file.
*/
FUNCTION VOID BRIDGE1_NAME(xco_read_file)
(
TAEINT *colxid, /* in: collection id */
TEXT *fspec, /* in: file specification of resource file */
TAEINT *mode, /* in: to be used for the vm objects created */
TAEINT *status, /* out: SUCCESS or error code */
STRLEN fspecl
)
{
FORSTR fspecd;
fspecd.length = GETLEN(fspecl);
fspecd.pointer = fspec;
BRIDGE2_NAME(xco_read_file) (colxid, &fspecd, mode, status);
return;
}
/*
* xco_write_file: write collection of vm objects to a tae plus resource file
*/
/* FUNCTION VOID BRIDGE1_NAME(xco_write_file) (colxid, fspec, status, fspecl) */
/* TAEINT *colxid; /\* in: collection id *\/ */
/* TEXT *fspec; /\* in: file specification of resouce file *\/ */
/* TAEINT *status; /\* out: SUCCESS or error code *\/ */
/* STRLEN fspecl; */
/* { */
/* FORSTR fspecd; */
/* fspecd.length = GETLEN(fspecl); */
/* fspecd.pointer = fspec; */
/* BRIDGE2_NAME(xcwfil) (colxid, &fspecd, status); */
/* return; */
/* } */
| 24.809353 | 81 | 0.638973 | [
"object"
] |
45b95a654d9820535a8ced862a9ca2e5a5d063cf | 1,982 | h | C | mace/ops/opencl/image/concat.h | fantasyRqg/mace | 6901d36099e533148952f8d403d28000fa240153 | [
"Apache-2.0"
] | 4,756 | 2018-06-28T01:42:29.000Z | 2022-03-31T11:27:43.000Z | mace/ops/opencl/image/concat.h | fantasyRqg/mace | 6901d36099e533148952f8d403d28000fa240153 | [
"Apache-2.0"
] | 725 | 2018-06-28T08:09:18.000Z | 2022-03-29T06:37:01.000Z | mace/ops/opencl/image/concat.h | fantasyRqg/mace | 6901d36099e533148952f8d403d28000fa240153 | [
"Apache-2.0"
] | 878 | 2018-06-28T01:42:33.000Z | 2022-03-31T07:08:50.000Z | // Copyright 2018 The MACE Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef MACE_OPS_OPENCL_IMAGE_CONCAT_H_
#define MACE_OPS_OPENCL_IMAGE_CONCAT_H_
#include "mace/ops/opencl/concat.h"
#include <memory>
#include <vector>
#include "mace/core/ops/op_context.h"
#include "mace/core/tensor.h"
#include "mace/runtimes/opencl/core/opencl_helper.h"
namespace mace {
namespace ops {
namespace opencl {
namespace image {
namespace concat {
MaceStatus Concat2(OpContext *context,
cl::Kernel *kernel,
const Tensor *input0,
const Tensor *input1,
std::vector<index_t> *prev_input_shape,
Tensor *output,
uint32_t *kwg_size);
MaceStatus ConcatN(OpContext *context,
cl::Kernel *kernel,
const std::vector<const Tensor *> &input_list,
Tensor *output,
uint32_t *kwg_size);
} // namespace concat
class ConcatKernel : public OpenCLConcatKernel {
public:
ConcatKernel() {}
MaceStatus Compute(
OpContext *context,
const std::vector<const Tensor *> &input_list,
const int32_t axis,
Tensor *output) override;
private:
cl::Kernel kernel_;
uint32_t kwg_size_;
std::vector<index_t> input_shape_;
};
} // namespace image
} // namespace opencl
} // namespace ops
} // namespace mace
#endif // MACE_OPS_OPENCL_IMAGE_CONCAT_H_
| 29.58209 | 75 | 0.674067 | [
"vector"
] |
45ba00ac5b2b75ec54544e8a89848b443688b5fe | 2,905 | h | C | ios/chrome/browser/ui/bookmarks/bookmark_home_view_controller.h | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | ios/chrome/browser/ui/bookmarks/bookmark_home_view_controller.h | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | ios/chrome/browser/ui/bookmarks/bookmark_home_view_controller.h | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef IOS_CHROME_BROWSER_UI_BOOKMARKS_HOME_VIEW_CONTROLLER_H_
#define IOS_CHROME_BROWSER_UI_BOOKMARKS_HOME_VIEW_CONTROLLER_H_
#import <UIKit/UIKit.h>
#include <set>
#include <vector>
#import "ios/chrome/browser/ui/table_view/chrome_table_view_controller.h"
@protocol ApplicationCommands;
@protocol UrlLoader;
class GURL;
namespace ios {
class ChromeBrowserState;
} // namespace ios
namespace bookmarks {
class BookmarkNode;
} // namespace bookmarks
@class BookmarkHomeViewController;
@protocol BookmarkHomeViewControllerDelegate
// The view controller wants to be dismissed. If |urls| is not empty, then
// the user has selected to navigate to those URLs in the current tab mode.
- (void)bookmarkHomeViewControllerWantsDismissal:
(BookmarkHomeViewController*)controller
navigationToUrls:(const std::vector<GURL>&)urls;
// The view controller wants to be dismissed. If |urls| is not empty, then
// the user has selected to navigate to those URLs with specified tab mode.
- (void)bookmarkHomeViewControllerWantsDismissal:
(BookmarkHomeViewController*)controller
navigationToUrls:(const std::vector<GURL>&)urls
inIncognito:(BOOL)inIncognito
newTab:(BOOL)newTab;
@end
// Class to navigate the bookmark hierarchy.
@interface BookmarkHomeViewController : ChromeTableViewController
// Delegate for presenters. Note that this delegate is currently being set only
// in case of handset, and not tablet. In the future it will be used by both
// cases.
@property(nonatomic, weak) id<BookmarkHomeViewControllerDelegate> homeDelegate;
// Initializers.
- (instancetype)initWithLoader:(id<UrlLoader>)loader
browserState:(ios::ChromeBrowserState*)browserState
dispatcher:(id<ApplicationCommands>)dispatcher
NS_DESIGNATED_INITIALIZER;
- (instancetype)initWithTableViewStyle:(UITableViewStyle)tableViewStyle
appBarStyle:
(ChromeTableViewControllerStyle)appBarStyle
NS_UNAVAILABLE;
// Setter to set _rootNode value.
- (void)setRootNode:(const bookmarks::BookmarkNode*)rootNode;
// Returns an array of BookmarkHomeViewControllers, one per BookmarkNode in the
// path from this view controller's node to the latest cached node (as
// determined by BookmarkPathCache). Includes |self| as the first element of
// the returned array. Sets the cached scroll position for the last element of
// the returned array, if appropriate.
- (NSArray<BookmarkHomeViewController*>*)cachedViewControllerStack;
@end
#endif // IOS_CHROME_BROWSER_UI_BOOKMARKS_HOME_VIEW_CONTROLLER_H_
| 37.727273 | 80 | 0.73494 | [
"vector"
] |
45be08a9218bd9ee1e962d1c30a7a83161a6db87 | 9,344 | h | C | ns-3-dev-git/src/lte/model/epc-sgw-pgw-application.h | rahul0324/Upgrade-AQM-Evaluation-Suite-of-ns-3 | 9d46441749da1059b2e9525d72fce61cb0e42150 | [
"MIT"
] | 1 | 2022-03-23T13:55:42.000Z | 2022-03-23T13:55:42.000Z | ns-3-dev-git/src/lte/model/epc-sgw-pgw-application.h | rahulkumdas/Upgrade-AQM-Evaluation-Suite-of-ns-3 | 9d46441749da1059b2e9525d72fce61cb0e42150 | [
"MIT"
] | null | null | null | ns-3-dev-git/src/lte/model/epc-sgw-pgw-application.h | rahulkumdas/Upgrade-AQM-Evaluation-Suite-of-ns-3 | 9d46441749da1059b2e9525d72fce61cb0e42150 | [
"MIT"
] | null | null | null | /* -*- Mode: C++; c-file-style: "gnu"; indent-tabs-mode:nil; -*- */
/*
* Copyright (c) 2011 Centre Tecnologic de Telecomunicacions de Catalunya (CTTC)
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation;
*
* 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
*
* Author: Jaume Nin <jnin@cttc.cat>
* Nicola Baldo <nbaldo@cttc.cat>
*/
#ifndef EPC_SGW_PGW_APPLICATION_H
#define EPC_SGW_PGW_APPLICATION_H
#include <ns3/address.h>
#include <ns3/socket.h>
#include <ns3/virtual-net-device.h>
#include <ns3/traced-callback.h>
#include <ns3/callback.h>
#include <ns3/ptr.h>
#include <ns3/object.h>
#include <ns3/eps-bearer.h>
#include <ns3/epc-tft.h>
#include <ns3/epc-tft-classifier.h>
#include <ns3/lte-common.h>
#include <ns3/application.h>
#include <ns3/epc-s1ap-sap.h>
#include <ns3/epc-s11-sap.h>
#include <map>
namespace ns3 {
/**
* \ingroup lte
*
* This application implements the SGW/PGW functionality.
*/
class EpcSgwPgwApplication : public Application
{
/// allow MemberEpcS11SapSgw<EpcSgwPgwApplication> class friend access
friend class MemberEpcS11SapSgw<EpcSgwPgwApplication>;
public:
/**
* \brief Get the type ID.
* \return the object TypeId
*/
static TypeId GetTypeId (void);
virtual void DoDispose ();
/**
* Constructor that binds the tap device to the callback methods.
*
* \param tunDevice TUN VirtualNetDevice used to tunnel IP packets from
* the Gi interface of the PGW/SGW over the
* internet over GTP-U/UDP/IP on the S1-U interface
* \param s1uSocket socket used to send GTP-U packets to the eNBs
*/
EpcSgwPgwApplication (const Ptr<VirtualNetDevice> tunDevice, const Ptr<Socket> s1uSocket);
/**
* Destructor
*/
virtual ~EpcSgwPgwApplication (void);
/**
* Method to be assigned to the callback of the Gi TUN VirtualNetDevice. It
* is called when the SGW/PGW receives a data packet from the
* internet (including IP headers) that is to be sent to the UE via
* its associated eNB, tunneling IP over GTP-U/UDP/IP.
*
* \param packet
* \param source
* \param dest
* \param protocolNumber
* \return true always
*/
bool RecvFromTunDevice (Ptr<Packet> packet, const Address& source, const Address& dest, uint16_t protocolNumber);
/**
* Method to be assigned to the recv callback of the S1-U socket. It
* is called when the SGW/PGW receives a data packet from the eNB
* that is to be forwarded to the internet.
*
* \param socket pointer to the S1-U socket
*/
void RecvFromS1uSocket (Ptr<Socket> socket);
/**
* Send a packet to the internet via the Gi interface of the SGW/PGW
*
* \param packet
* \param teid the Tunnel Enpoint Identifier
*/
void SendToTunDevice (Ptr<Packet> packet, uint32_t teid);
/**
* Send a packet to the SGW via the S1-U interface
*
* \param packet packet to be sent
* \param enbS1uAddress the address of the eNB
* \param teid the Tunnel Enpoint IDentifier
*/
void SendToS1uSocket (Ptr<Packet> packet, Ipv4Address enbS1uAddress, uint32_t teid);
/**
* Set the MME side of the S11 SAP
*
* \param s the MME side of the S11 SAP
*/
void SetS11SapMme (EpcS11SapMme * s);
/**
*
* \return the SGW side of the S11 SAP
*/
EpcS11SapSgw* GetS11SapSgw ();
/**
* Let the SGW be aware of a new eNB
*
* \param cellId the cell identifier
* \param enbAddr the address of the eNB
* \param sgwAddr the address of the SGW
*/
void AddEnb (uint16_t cellId, Ipv4Address enbAddr, Ipv4Address sgwAddr);
/**
* Let the SGW be aware of a new UE
*
* \param imsi the unique identifier of the UE
*/
void AddUe (uint64_t imsi);
/**
* set the address of a previously added UE
*
* \param imsi the unique identifier of the UE
* \param ueAddr the IPv4 address of the UE
*/
void SetUeAddress (uint64_t imsi, Ipv4Address ueAddr);
/**
* set the address of a previously added UE
*
* \param imsi the unique identifier of the UE
* \param ueAddr the IPv6 address of the UE
*/
void SetUeAddress6 (uint64_t imsi, Ipv6Address ueAddr);
/**
* TracedCallback signature for data Packet reception event.
*
* \param [in] packet The data packet sent from the internet.
*/
typedef void (* RxTracedCallback)
(Ptr<Packet> packet);
private:
// S11 SAP SGW methods
/**
* Create session request function
* \param msg EpcS11SapSgw::CreateSessionRequestMessage
*/
void DoCreateSessionRequest (EpcS11SapSgw::CreateSessionRequestMessage msg);
/**
* Modify bearer request function
* \param msg EpcS11SapSgw::ModifyBearerRequestMessage
*/
void DoModifyBearerRequest (EpcS11SapSgw::ModifyBearerRequestMessage msg);
/**
* Delete bearer command function
* \param req EpcS11SapSgw::DeleteBearerCommandMessage
*/
void DoDeleteBearerCommand (EpcS11SapSgw::DeleteBearerCommandMessage req);
/**
* Delete bearer response function
* \param req EpcS11SapSgw::DeleteBearerResponseMessage
*/
void DoDeleteBearerResponse (EpcS11SapSgw::DeleteBearerResponseMessage req);
/**
* store info for each UE connected to this SGW
*/
class UeInfo : public SimpleRefCount<UeInfo>
{
public:
UeInfo ();
/**
*
* \param tft the Traffic Flow Template of the new bearer to be added
* \param epsBearerId the ID of the EPS Bearer to be activated
* \param teid the TEID of the new bearer
*/
void AddBearer (Ptr<EpcTft> tft, uint8_t epsBearerId, uint32_t teid);
/**
* \brief Function, deletes contexts of bearer on SGW and PGW side
* \param bearerId the Bearer Id whose contexts to be removed
*/
void RemoveBearer (uint8_t bearerId);
/**
*
*
* \param p the IP packet from the internet to be classified
* \param protocolNumber the protocol number of the IP packet
*
* \return the corresponding bearer ID > 0 identifying the bearer
* among all the bearers of this UE; returns 0 if no bearers
* matches with the previously declared TFTs
*/
uint32_t Classify (Ptr<Packet> p, uint16_t protocolNumber);
/**
* \return the address of the eNB to which the UE is connected
*/
Ipv4Address GetEnbAddr ();
/**
* set the address of the eNB to which the UE is connected
*
* \param addr the address of the eNB
*/
void SetEnbAddr (Ipv4Address addr);
/**
* \return the IPv4 address of the UE
*/
Ipv4Address GetUeAddr ();
/**
* set the IPv4 address of the UE
*
* \param addr the IPv4 address of the UE
*/
void SetUeAddr (Ipv4Address addr);
/**
* \return the IPv6 address of the UE
*/
Ipv6Address GetUeAddr6 ();
/**
* set the IPv6 address of the UE
*
* \param addr the IPv6 address of the UE
*/
void SetUeAddr6 (Ipv6Address addr);
private:
EpcTftClassifier m_tftClassifier; ///< TFT classifier
Ipv4Address m_enbAddr; ///< ENB IPv4 address
Ipv4Address m_ueAddr; ///< UE IPv4 address
Ipv6Address m_ueAddr6; ///< UE IPv6 address
std::map<uint8_t, uint32_t> m_teidByBearerIdMap; ///< TEID By bearer ID Map
};
/**
* UDP socket to send and receive GTP-U packets to and from the S1-U interface
*/
Ptr<Socket> m_s1uSocket;
/**
* TUN VirtualNetDevice used for tunneling/detunneling IP packets
* from/to the internet over GTP-U/UDP/IP on the S1 interface
*/
Ptr<VirtualNetDevice> m_tunDevice;
/**
* Map telling for each UE IPv4 address the corresponding UE info
*/
std::map<Ipv4Address, Ptr<UeInfo> > m_ueInfoByAddrMap;
/**
* Map telling for each UE IPv6 address the corresponding UE info
*/
std::map<Ipv6Address, Ptr<UeInfo> > m_ueInfoByAddrMap6;
/**
* Map telling for each IMSI the corresponding UE info
*/
std::map<uint64_t, Ptr<UeInfo> > m_ueInfoByImsiMap;
/**
* UDP port to be used for GTP
*/
uint16_t m_gtpuUdpPort;
/**
* TEID count
*/
uint32_t m_teidCount;
/**
* MME side of the S11 SAP
*
*/
EpcS11SapMme* m_s11SapMme;
/**
* SGW side of the S11 SAP
*
*/
EpcS11SapSgw* m_s11SapSgw;
/// EnbInfo structure
struct EnbInfo
{
Ipv4Address enbAddr; ///< eNB IPv4 address
Ipv4Address sgwAddr; ///< SGW IPV4 address
};
std::map<uint16_t, EnbInfo> m_enbInfoByCellId; ///< eNB info by cell ID
/**
* \brief Callback to trace RX (reception) data packets at Tun Net Device from internet.
*/
TracedCallback<Ptr<Packet> > m_rxTunPktTrace;
/**
* \brief Callback to trace RX (reception) data packets from S1-U socket.
*/
TracedCallback<Ptr<Packet> > m_rxS1uPktTrace;
};
} //namespace ns3
#endif /* EPC_SGW_PGW_APPLICATION_H */
| 26.545455 | 115 | 0.672838 | [
"object"
] |
45bf13a80ae762a7e47feb61ddb9bc7532e7e8f0 | 1,059 | h | C | Medusa/Medusa/Graphics/State/ProgramRenderState.h | JamesLinus/Medusa | 243e1f67e76dba10a0b69d4154b47e884c3f191f | [
"MIT"
] | 1 | 2019-04-22T09:09:50.000Z | 2019-04-22T09:09:50.000Z | Medusa/Medusa/Graphics/State/ProgramRenderState.h | JamesLinus/Medusa | 243e1f67e76dba10a0b69d4154b47e884c3f191f | [
"MIT"
] | null | null | null | Medusa/Medusa/Graphics/State/ProgramRenderState.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 "Graphics/State/IRenderState.h"
#include "Graphics/GraphicsTypes.h"
#include "Core/Geometry/Rect2.h"
MEDUSA_BEGIN;
class ProgramRenderState:public IRenderState
{
MEDUSA_DECLARE_RTTI;
public:
ProgramRenderState(uint program=0);
virtual ~ProgramRenderState();
virtual void Apply()const override;
virtual ProgramRenderState* Clone()const override;
virtual void CopyFrom(const IRenderState& other)override;
virtual bool Equals(const IRenderState& state)const override;
virtual RenderStateType Type()const override {return GetTypeIdStatic();}
static RenderStateType GetTypeIdStatic(){return RenderStateType::Program;}
uint Program() const { return mProgram; }
void SetProgram(uint val) {RETURN_IF_EQUAL(mProgram, val); mProgram = val; OnStateChanged();}
static ProgramRenderState* Current();
protected:
uint mProgram;
};
MEDUSA_END; | 30.257143 | 95 | 0.759207 | [
"geometry"
] |
45bffeb58148d76c4a61738ba570bda17ce3cbb1 | 4,398 | h | C | components/consent_auditor/fake_consent_auditor.h | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/consent_auditor/fake_consent_auditor.h | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | components/consent_auditor/fake_consent_auditor.h | sarang-apps/darshan_browser | 173649bb8a7c656dc60784d19e7bb73e07c20daa | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2018 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef COMPONENTS_CONSENT_AUDITOR_FAKE_CONSENT_AUDITOR_H_
#define COMPONENTS_CONSENT_AUDITOR_FAKE_CONSENT_AUDITOR_H_
#include <string>
#include <vector>
#include "base/macros.h"
#include "components/consent_auditor/consent_auditor.h"
#include "testing/gmock/include/gmock/gmock.h"
using ::testing::Matcher;
namespace consent_auditor {
// TODO(markusheintz): Rename to MockConsentAuditor
class FakeConsentAuditor : public ConsentAuditor {
public:
FakeConsentAuditor();
~FakeConsentAuditor() override;
// ConsentAuditor implementation.
void RecordSyncConsent(
const CoreAccountId& account_id,
const sync_pb::UserConsentTypes::SyncConsent& consent) override;
MOCK_METHOD2(
RecordArcPlayConsent,
void(const CoreAccountId&,
const sync_pb::UserConsentTypes::ArcPlayTermsOfServiceConsent&));
MOCK_METHOD2(
RecordArcBackupAndRestoreConsent,
void(const CoreAccountId&,
const sync_pb::UserConsentTypes::ArcBackupAndRestoreConsent&));
MOCK_METHOD2(
RecordArcGoogleLocationServiceConsent,
void(const CoreAccountId&,
const sync_pb::UserConsentTypes::ArcGoogleLocationServiceConsent&));
void RecordAssistantActivityControlConsent(
const CoreAccountId& account_id,
const sync_pb::UserConsentTypes::AssistantActivityControlConsent& consent)
override;
void RecordLocalConsent(const std::string& feature,
const std::string& description_text,
const std::string& confirmation_text) override;
base::WeakPtr<syncer::ModelTypeControllerDelegate> GetControllerDelegate()
override;
// Methods for fake.
// TODO(markusheintz): Replace the usage of this methods in all tests.
void RecordGaiaConsent(const CoreAccountId& account_id,
consent_auditor::Feature feature,
const std::vector<int>& description_grd_ids,
int confirmation_grd_id,
consent_auditor::ConsentStatus status);
const CoreAccountId& account_id() const { return account_id_; }
const sync_pb::UserConsentTypes::SyncConsent& recorded_sync_consent() const {
return recorded_sync_consent_;
}
const sync_pb::UserConsentTypes::ArcPlayTermsOfServiceConsent&
recorded_play_consent() const {
return recorded_play_consent_;
}
const std::vector<std::vector<int>>& recorded_id_vectors() {
return recorded_id_vectors_;
}
const std::vector<int>& recorded_confirmation_ids() const {
return recorded_confirmation_ids_;
}
const std::vector<Feature>& recorded_features() { return recorded_features_; }
const std::vector<ConsentStatus>& recorded_statuses() {
return recorded_statuses_;
}
private:
CoreAccountId account_id_;
sync_pb::UserConsentTypes::SyncConsent recorded_sync_consent_;
sync_pb::UserConsentTypes_ArcPlayTermsOfServiceConsent recorded_play_consent_;
std::vector<std::vector<int>> recorded_id_vectors_;
std::vector<int> recorded_confirmation_ids_;
std::vector<Feature> recorded_features_;
std::vector<ConsentStatus> recorded_statuses_;
DISALLOW_COPY_AND_ASSIGN(FakeConsentAuditor);
};
MATCHER_P(ArcPlayConsentEq, expected_consent, "") {
const sync_pb::UserConsentTypes::ArcPlayTermsOfServiceConsent&
actual_consent = arg;
if (actual_consent.SerializeAsString() ==
expected_consent.SerializeAsString())
return true;
LOG(ERROR) << "ERROR: actual proto does not match the expected proto";
return false;
}
MATCHER_P(ArcGoogleLocationServiceConsentEq, expected_consent, "") {
const sync_pb::UserConsentTypes::ArcGoogleLocationServiceConsent&
actual_consent = arg;
if (actual_consent.SerializeAsString() ==
expected_consent.SerializeAsString())
return true;
LOG(ERROR) << "ERROR: actual proto does not match the expected proto";
return false;
}
MATCHER_P(ArcBackupAndRestoreConsentEq, expected_consent, "") {
if (arg.SerializeAsString() == expected_consent.SerializeAsString())
return true;
LOG(ERROR) << "ERROR: actual proto does not match the expected proto";
return false;
}
} // namespace consent_auditor
#endif // COMPONENTS_CONSENT_AUDITOR_FAKE_CONSENT_AUDITOR_H_
| 33.067669 | 80 | 0.744884 | [
"vector"
] |
45c0ddf4450836da0339c4a84664a89323b4cd1e | 16,593 | c | C | src/Client/MapGenerator.c | Andresian/ClassicalSharp | 58c24c4584b026b967e4dd5fcf65c51ab5c9868e | [
"BSD-3-Clause"
] | null | null | null | src/Client/MapGenerator.c | Andresian/ClassicalSharp | 58c24c4584b026b967e4dd5fcf65c51ab5c9868e | [
"BSD-3-Clause"
] | null | null | null | src/Client/MapGenerator.c | Andresian/ClassicalSharp | 58c24c4584b026b967e4dd5fcf65c51ab5c9868e | [
"BSD-3-Clause"
] | 1 | 2020-05-19T02:30:29.000Z | 2020-05-19T02:30:29.000Z | #include "MapGenerator.h"
#include "BlockID.h"
#include "ErrorHandler.h"
#include "ExtMath.h"
#include "Funcs.h"
#include "Noise.h"
#include "Platform.h"
#include "Random.h"
#include "TreeGen.h"
void FlatgrassGen_MapSet(Int32 yStart, Int32 yEnd, BlockID block) {
yStart = max(yStart, 0); yEnd = max(yEnd, 0);
Int32 startIndex = yStart * Gen_Length * Gen_Width;
Int32 endIndex = (yEnd * Gen_Length + (Gen_Length - 1)) * Gen_Width + (Gen_Width - 1);
Int32 count = (endIndex - startIndex) + 1, offset = 0;
Gen_CurrentProgress = 0.0f;
BlockID* ptr = Gen_Blocks;
while (offset < count) {
Int32 bytes = min(count - offset, Gen_Width * Gen_Length) * sizeof(BlockID);
Platform_MemSet(ptr, block, bytes);
ptr += bytes; offset += bytes;
Gen_CurrentProgress = (Real32)offset / count;
}
}
void FlatgrassGen_Generate(void) {
Gen_Blocks = Platform_MemAlloc(Gen_Width * Gen_Height * Gen_Length * sizeof(BlockID));
if (Gen_Blocks == NULL)
ErrorHandler_Fail("FlatgrassGen - failed to allocate Blocks array");
String dirtStr = String_FromConst("Setting dirt blocks");
Gen_CurrentState = dirtStr;
FlatgrassGen_MapSet(0, Gen_Height / 2 - 2, BLOCK_DIRT);
String grassStr = String_FromConst("Setting grass blocks");
Gen_CurrentState = grassStr;
FlatgrassGen_MapSet(Gen_Height / 2 - 1, Gen_Height / 2 - 1, BLOCK_GRASS);
}
Int32 waterLevel, oneY, volume, minHeight;
Int16* Heightmap;
Random rnd;
void NotchyGen_FillOblateSpheroid(Int32 x, Int32 y, Int32 z, Real32 radius, BlockID block) {
Int32 xStart = Math_Floor(max(x - radius, 0));
Int32 xEnd = Math_Floor(min(x + radius, Gen_MaxX));
Int32 yStart = Math_Floor(max(y - radius, 0));
Int32 yEnd = Math_Floor(min(y + radius, Gen_MaxY));
Int32 zStart = Math_Floor(max(z - radius, 0));
Int32 zEnd = Math_Floor(min(z + radius, Gen_MaxZ));
Real32 radiusSq = radius * radius;
Int32 xx, yy, zz;
for (yy = yStart; yy <= yEnd; yy++) {
Int32 dy = yy - y;
for (zz = zStart; zz <= zEnd; zz++) {
Int32 dz = zz - z;
for (xx = xStart; xx <= xEnd; xx++) {
Int32 dx = xx - x;
if ((dx * dx + 2 * dy * dy + dz * dz) < radiusSq) {
Int32 index = Gen_Pack(xx, yy, zz);
if (Gen_Blocks[index] == BLOCK_STONE)
Gen_Blocks[index] = block;
}
}
}
}
}
#define Stack_Push(index)\
stack[stack_size] = index;\
stack_size++;\
if (stack_size == 32768) {\
ErrorHandler_Fail("NotchyGen_FloodFail - stack limit hit");\
}
void NotchyGen_FloodFill(Int32 startIndex, BlockID block) {
if (startIndex < 0) return; /* y below map, immediately ignore */
/* This is way larger size than I actually have seen used, but we play it safe here.*/
Int32 stack[32768];
Int32 stack_size = 0;
Stack_Push(startIndex);
while (stack_size > 0) {
stack_size--;
Int32 index = stack[stack_size];
if (Gen_Blocks[index] != 0) continue;
Gen_Blocks[index] = block;
Int32 x = index % Gen_Width;
Int32 y = index / oneY;
Int32 z = (index / Gen_Width) % Gen_Length;
if (x > 0) { Stack_Push(index - 1); }
if (x < Gen_MaxX) { Stack_Push(index + 1); }
if (z > 0) { Stack_Push(index - Gen_Width); }
if (z < Gen_MaxZ) { Stack_Push(index + Gen_Width); }
if (y > 0) { Stack_Push(index - oneY); }
}
}
void NotchyGen_CreateHeightmap(void) {
CombinedNoise n1, n2;
CombinedNoise_Init(&n1, &rnd, 8, 8);
CombinedNoise_Init(&n2, &rnd, 8, 8);
OctaveNoise n3;
OctaveNoise_Init(&n3, &rnd, 6);
Int32 index = 0;
String state = String_FromConst("Building heightmap");
Gen_CurrentState = state;
Int32 x, z;
for (z = 0; z < Gen_Length; z++) {
Gen_CurrentProgress = (Real32)z / Gen_Length;
for (x = 0; x < Gen_Width; x++) {
Real32 hLow = CombinedNoise_Calc(&n1, x * 1.3f, z * 1.3f) / 6 - 4, height = hLow;
if (OctaveNoise_Calc(&n3, (Real32)x, (Real32)z) <= 0) {
Real32 hHigh = CombinedNoise_Calc(&n2, x * 1.3f, z * 1.3f) / 5 + 6;
height = max(hLow, hHigh);
}
height *= 0.5f;
if (height < 0) height *= 0.8f;
Int16 adjHeight = (Int16)(height + waterLevel);
minHeight = adjHeight < minHeight ? adjHeight : minHeight;
Heightmap[index++] = adjHeight;
}
}
}
Int32 NotchyGen_CreateStrataFast(void) {
/* Make lava layer at bottom */
Int32 mapIndex = 0;
Int32 x, y, z;
for (z = 0; z < Gen_Length; z++) {
for (x = 0; x < Gen_Width; x++) {
Gen_Blocks[mapIndex++] = BLOCK_LAVA;
}
}
/* Invariant: the lowest value dirtThickness can possible be is -14 */
Int32 stoneHeight = minHeight - 14;
if (stoneHeight <= 0) return 1; /* no layer is fully stone */
/* We can quickly fill in bottom solid layers */
for (y = 1; y <= stoneHeight; y++) {
for (z = 0; z < Gen_Length; z++) {
for (x = 0; x < Gen_Width; x++) {
Gen_Blocks[mapIndex++] = BLOCK_STONE;
}
}
}
return stoneHeight;
}
void NotchyGen_CreateStrata(void) {
OctaveNoise n;
OctaveNoise_Init(&n, &rnd, 8);
String state = String_FromConst("Creating strata");
Gen_CurrentState = state;
Int32 hMapIndex = 0, maxY = Gen_Height - 1, mapIndex = 0;
/* Try to bulk fill bottom of the map if possible */
Int32 minSTONEY = NotchyGen_CreateStrataFast();
Int32 x, y, z;
for (z = 0; z < Gen_Length; z++) {
Gen_CurrentProgress = (Real32)z / Gen_Length;
for (x = 0; x < Gen_Width; x++) {
Int32 dirtThickness = (Int32)(OctaveNoise_Calc(&n, (Real32)x, (Real32)z) / 24 - 4);
Int32 dirtHeight = Heightmap[hMapIndex++];
Int32 stoneHeight = dirtHeight + dirtThickness;
stoneHeight = min(stoneHeight, maxY);
dirtHeight = min(dirtHeight, maxY);
mapIndex = Gen_Pack(x, minSTONEY, z);
for (y = minSTONEY; y <= stoneHeight; y++) {
Gen_Blocks[mapIndex] = BLOCK_STONE; mapIndex += oneY;
}
stoneHeight = max(stoneHeight, 0);
mapIndex = Gen_Pack(x, (stoneHeight + 1), z);
for (y = stoneHeight + 1; y <= dirtHeight; y++) {
Gen_Blocks[mapIndex] = BLOCK_DIRT; mapIndex += oneY;
}
}
}
}
void NotchyGen_CarveCaves(void) {
Int32 cavesCount = volume / 8192;
String state = String_FromConst("Carving caves");
Gen_CurrentState = state;
Int32 i, j;
for (i = 0; i < cavesCount; i++) {
Gen_CurrentProgress = (Real32)i / cavesCount;
Real32 caveX = (Real32)Random_Next(&rnd, Gen_Width);
Real32 caveY = (Real32)Random_Next(&rnd, Gen_Height);
Real32 caveZ = (Real32)Random_Next(&rnd, Gen_Length);
Int32 caveLen = (Int32)(Random_Float(&rnd) * Random_Float(&rnd) * 200.0f);
Real32 theta = Random_Float(&rnd) * 2.0f * MATH_PI, deltaTheta = 0.0f;
Real32 phi = Random_Float(&rnd) * 2.0f * MATH_PI, deltaPhi = 0.0f;
Real32 caveRadius = Random_Float(&rnd) * Random_Float(&rnd);
for (j = 0; j < caveLen; j++) {
caveX += Math_Sin(theta) * Math_Cos(phi);
caveZ += Math_Cos(theta) * Math_Cos(phi);
caveY += Math_Sin(phi);
theta = theta + deltaTheta * 0.2f;
deltaTheta = deltaTheta * 0.9f + Random_Float(&rnd) - Random_Float(&rnd);
phi = phi * 0.5f + deltaPhi * 0.25f;
deltaPhi = deltaPhi * 0.75f + Random_Float(&rnd) - Random_Float(&rnd);
if (Random_Float(&rnd) < 0.25f) continue;
Int32 cenX = (Int32)(caveX + (Random_Next(&rnd, 4) - 2) * 0.2f);
Int32 cenY = (Int32)(caveY + (Random_Next(&rnd, 4) - 2) * 0.2f);
Int32 cenZ = (Int32)(caveZ + (Random_Next(&rnd, 4) - 2) * 0.2f);
Real32 radius = (Gen_Height - cenY) / (Real32)Gen_Height;
radius = 1.2f + (radius * 3.5f + 1.0f) * caveRadius;
radius = radius * Math_Sin(j * MATH_PI / caveLen);
NotchyGen_FillOblateSpheroid(cenX, cenY, cenZ, radius, BLOCK_AIR);
}
}
}
void NotchyGen_CarveOreVeins(Real32 abundance, const UInt8* state, BlockID block) {
Int32 numVeins = (Int32)(volume * abundance / 16384);
Gen_CurrentState = String_FromReadonly(state);
Int32 i, j;
for (i = 0; i < numVeins; i++) {
Gen_CurrentProgress = (Real32)i / numVeins;
Real32 veinX = (Real32)Random_Next(&rnd, Gen_Width);
Real32 veinY = (Real32)Random_Next(&rnd, Gen_Height);
Real32 veinZ = (Real32)Random_Next(&rnd, Gen_Length);
Int32 veinLen = (Int32)(Random_Float(&rnd) * Random_Float(&rnd) * 75 * abundance);
Real32 theta = Random_Float(&rnd) * 2.0f * MATH_PI, deltaTheta = 0.0f;
Real32 phi = Random_Float(&rnd) * 2.0f * MATH_PI, deltaPhi = 0.0f;
for (j = 0; j < veinLen; j++) {
veinX += Math_Sin(theta) * Math_Cos(phi);
veinZ += Math_Cos(theta) * Math_Cos(phi);
veinY += Math_Sin(phi);
theta = deltaTheta * 0.2f;
deltaTheta = deltaTheta * 0.9f + Random_Float(&rnd) - Random_Float(&rnd);
phi = phi * 0.5f + deltaPhi * 0.25f;
deltaPhi = deltaPhi * 0.9f + Random_Float(&rnd) - Random_Float(&rnd);
Real32 radius = abundance * Math_Sin(j * MATH_PI / veinLen) + 1.0f;
NotchyGen_FillOblateSpheroid((Int32)veinX, (Int32)veinY, (Int32)veinZ, radius, block);
}
}
}
void NotchyGen_FloodFillWaterBorders(void) {
Int32 waterY = waterLevel - 1;
Int32 index1 = Gen_Pack(0, waterY, 0);
Int32 index2 = Gen_Pack(0, waterY, Gen_Length - 1);
String state = String_FromConst("Flooding edge water");
Gen_CurrentState = state;
Int32 x, z;
for (x = 0; x < Gen_Width; x++) {
Gen_CurrentProgress = 0.0f + ((Real32)x / Gen_Width) * 0.5f;
NotchyGen_FloodFill(index1, BLOCK_WATER);
NotchyGen_FloodFill(index2, BLOCK_WATER);
index1++; index2++;
}
index1 = Gen_Pack(0, waterY, 0);
index2 = Gen_Pack(Gen_Width - 1, waterY, 0);
for (z = 0; z < Gen_Length; z++) {
Gen_CurrentProgress = 0.5f + ((Real32)z / Gen_Length) * 0.5f;
NotchyGen_FloodFill(index1, BLOCK_WATER);
NotchyGen_FloodFill(index2, BLOCK_WATER);
index1 += Gen_Width; index2 += Gen_Width;
}
}
void NotchyGen_FloodFillWater(void) {
Int32 numSources = Gen_Width * Gen_Length / 800;
String state = String_FromConst("Flooding water");
Gen_CurrentState = state;
Int32 i;
for (i = 0; i < numSources; i++) {
Gen_CurrentProgress = (Real32)i / numSources;
Int32 x = Random_Next(&rnd, Gen_Width);
Int32 z = Random_Next(&rnd, Gen_Length);
Int32 y = waterLevel - Random_Range(&rnd, 1, 3);
NotchyGen_FloodFill(Gen_Pack(x, y, z), BLOCK_WATER);
}
}
void NotchyGen_FloodFillLava(void) {
Int32 numSources = Gen_Width * Gen_Length / 20000;
String state = String_FromConst("Flooding lava");
Gen_CurrentState = state;
Int32 i;
for (i = 0; i < numSources; i++) {
Gen_CurrentProgress = (Real32)i / numSources;
Int32 x = Random_Next(&rnd, Gen_Width);
Int32 z = Random_Next(&rnd, Gen_Length);
Int32 y = (Int32)((waterLevel - 3) * Random_Float(&rnd) * Random_Float(&rnd));
NotchyGen_FloodFill(Gen_Pack(x, y, z), BLOCK_LAVA);
}
}
void NotchyGen_CreateSurfaceLayer(void) {
OctaveNoise n1, n2;
OctaveNoise_Init(&n1, &rnd, 8);
OctaveNoise_Init(&n2, &rnd, 8);
String state = String_FromConst("Creating surface");
Gen_CurrentState = state;
/* TODO: update heightmap */
Int32 hMapIndex = 0;
Int32 x, z;
for (z = 0; z < Gen_Length; z++) {
Gen_CurrentProgress = (Real32)z / Gen_Length;
for (x = 0; x < Gen_Width; x++) {
Int32 y = Heightmap[hMapIndex++];
if (y < 0 || y >= Gen_Height) continue;
Int32 index = Gen_Pack(x, y, z);
BlockID blockAbove = y >= Gen_MaxY ? BLOCK_AIR : Gen_Blocks[index + oneY];
if (blockAbove == BLOCK_WATER && (OctaveNoise_Calc(&n2, (Real32)x, (Real32)z) > 12)) {
Gen_Blocks[index] = BLOCK_GRAVEL;
}
else if (blockAbove == BLOCK_AIR) {
Gen_Blocks[index] = (y <= waterLevel && (OctaveNoise_Calc(&n1, (Real32)x, (Real32)z) > 8)) ? BLOCK_SAND : BLOCK_GRASS;
}
}
}
}
void NotchyGen_PlantFlowers(void) {
Int32 numPatches = Gen_Width * Gen_Length / 3000;
String state = String_FromConst("Planting flowers");
Gen_CurrentState = state;
Int32 i, j, k;
for (i = 0; i < numPatches; i++) {
Gen_CurrentProgress = (Real32)i / numPatches;
BlockID type = (BlockID)(BLOCK_DANDELION + Random_Next(&rnd, 2));
Int32 patchX = Random_Next(&rnd, Gen_Width), patchZ = Random_Next(&rnd, Gen_Length);
for (j = 0; j < 10; j++) {
Int32 flowerX = patchX, flowerZ = patchZ;
for (k = 0; k < 5; k++) {
flowerX += Random_Next(&rnd, 6) - Random_Next(&rnd, 6);
flowerZ += Random_Next(&rnd, 6) - Random_Next(&rnd, 6);
if (flowerX < 0 || flowerZ < 0 || flowerX >= Gen_Width || flowerZ >= Gen_Length)
continue;
Int32 flowerY = Heightmap[flowerZ * Gen_Width + flowerX] + 1;
if (flowerY <= 0 || flowerY >= Gen_Height) continue;
Int32 index = Gen_Pack(flowerX, flowerY, flowerZ);
if (Gen_Blocks[index] == BLOCK_AIR && Gen_Blocks[index - oneY] == BLOCK_GRASS)
Gen_Blocks[index] = type;
}
}
}
}
void NotchyGen_PlantMushrooms(void) {
Int32 numPatches = volume / 2000;
String state = String_FromConst("Planting mushrooms");
Gen_CurrentState = state;
Int32 i, j, k;
for (i = 0; i < numPatches; i++) {
Gen_CurrentProgress = (Real32)i / numPatches;
BlockID type = (BlockID)(BLOCK_BROWN_SHROOM + Random_Next(&rnd, 2));
Int32 patchX = Random_Next(&rnd, Gen_Width);
Int32 patchY = Random_Next(&rnd, Gen_Height);
Int32 patchZ = Random_Next(&rnd, Gen_Length);
for (j = 0; j < 20; j++) {
Int32 mushX = patchX, mushY = patchY, mushZ = patchZ;
for (k = 0; k < 5; k++) {
mushX += Random_Next(&rnd, 6) - Random_Next(&rnd, 6);
mushZ += Random_Next(&rnd, 6) - Random_Next(&rnd, 6);
if (mushX < 0 || mushZ < 0 || mushX >= Gen_Width || mushZ >= Gen_Length)
continue;
Int32 solidHeight = Heightmap[mushZ * Gen_Width + mushX];
if (mushY >= (solidHeight - 1))
continue;
Int32 index = Gen_Pack(mushX, mushY, mushZ);
if (Gen_Blocks[index] == BLOCK_AIR && Gen_Blocks[index - oneY] == BLOCK_STONE)
Gen_Blocks[index] = type;
}
}
}
}
void NotchyGen_PlantTrees(void) {
Int32 numPatches = Gen_Width * Gen_Length / 4000;
String state = String_FromConst("Planting trees");
Gen_CurrentState = state;
Tree_Width = Gen_Width; Tree_Height = Gen_Height; Tree_Length = Gen_Length;
Tree_Blocks = Gen_Blocks;
Tree_Rnd = &rnd;
Int32 i, j, k, m;
for (i = 0; i < numPatches; i++) {
Gen_CurrentProgress = (Real32)i / numPatches;
Int32 patchX = Random_Next(&rnd, Gen_Width), patchZ = Random_Next(&rnd, Gen_Length);
for (j = 0; j < 20; j++) {
Int32 treeX = patchX, treeZ = patchZ;
for (k = 0; k < 20; k++) {
treeX += Random_Next(&rnd, 6) - Random_Next(&rnd, 6);
treeZ += Random_Next(&rnd, 6) - Random_Next(&rnd, 6);
if (treeX < 0 || treeZ < 0 || treeX >= Gen_Width ||
treeZ >= Gen_Length || Random_Float(&rnd) >= 0.25)
continue;
Int32 treeY = Heightmap[treeZ * Gen_Width + treeX] + 1;
if (treeY >= Gen_Height) continue;
Int32 treeHeight = 5 + Random_Next(&rnd, 3);
Int32 index = Gen_Pack(treeX, treeY, treeZ);
BlockID blockUnder = treeY > 0 ? Gen_Blocks[index - oneY] : BLOCK_AIR;
if (blockUnder == BLOCK_GRASS && TreeGen_CanGrow(treeX, treeY, treeZ, treeHeight)) {
Vector3I coords[Tree_BufferCount];
BlockID blocks[Tree_BufferCount];
Int32 count = TreeGen_Grow(treeX, treeY, treeZ, treeHeight, coords, blocks);
for (m = 0; m < count; m++) {
index = Gen_Pack(coords[m].X, coords[m].Y, coords[m].Z);
Gen_Blocks[index] = blocks[m];
}
}
}
}
}
}
void NotchyGen_Generate(void) {
Heightmap = Platform_MemAlloc(Gen_Width * Gen_Length * sizeof(Int16));
if (Heightmap == NULL)
ErrorHandler_Fail("NotchyGen - Failed to allocate Heightmap array");
Gen_Blocks = Platform_MemAlloc(Gen_Width * Gen_Height * Gen_Length * sizeof(BlockID));
if (Gen_Blocks == NULL)
ErrorHandler_Fail("NotchyGen - Failed to allocate Blocks array");
oneY = Gen_Width * Gen_Length;
volume = Gen_Width * Gen_Length * Gen_Height;
waterLevel = Gen_Height / 2;
Random_Init(&rnd, Gen_Seed);
minHeight = Gen_Height;
Gen_CurrentProgress = 0.0f;
String state = String_FromConst("");
Gen_CurrentState = state;
NotchyGen_CreateHeightmap();
NotchyGen_CreateStrata();
NotchyGen_CarveCaves();
NotchyGen_CarveOreVeins(0.9f, "Carving coal ore", BLOCK_COAL_ORE);
NotchyGen_CarveOreVeins(0.7f, "Carving iron ore", BLOCK_IRON_ORE);
NotchyGen_CarveOreVeins(0.5f, "Carving gold ore", BLOCK_GOLD_ORE);
NotchyGen_FloodFillWaterBorders();
NotchyGen_FloodFillWater();
NotchyGen_FloodFillLava();
NotchyGen_CreateSurfaceLayer();
NotchyGen_PlantFlowers();
NotchyGen_PlantMushrooms();
NotchyGen_PlantTrees();
Platform_MemFree(Heightmap);
} | 33.319277 | 123 | 0.644549 | [
"solid"
] |
45c836350bf8478f92797543399cba106794b244 | 16,086 | h | C | aws-cpp-sdk-cloudformation/include/aws/cloudformation/model/ChangeSetSummary.h | ploki/aws-sdk-cpp | 17074e3e48c7411f81294e2ee9b1550c4dde842c | [
"Apache-2.0"
] | 2 | 2019-03-11T15:50:55.000Z | 2020-02-27T11:40:27.000Z | aws-cpp-sdk-cloudformation/include/aws/cloudformation/model/ChangeSetSummary.h | ploki/aws-sdk-cpp | 17074e3e48c7411f81294e2ee9b1550c4dde842c | [
"Apache-2.0"
] | 18 | 2018-05-15T16:41:07.000Z | 2018-05-21T00:46:30.000Z | aws-cpp-sdk-cloudformation/include/aws/cloudformation/model/ChangeSetSummary.h | ploki/aws-sdk-cpp | 17074e3e48c7411f81294e2ee9b1550c4dde842c | [
"Apache-2.0"
] | 1 | 2019-10-31T11:19:50.000Z | 2019-10-31T11:19:50.000Z | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. 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.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file 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 <aws/cloudformation/CloudFormation_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSStreamFwd.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/cloudformation/model/ExecutionStatus.h>
#include <aws/cloudformation/model/ChangeSetStatus.h>
#include <aws/core/utils/DateTime.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Xml
{
class XmlNode;
} // namespace Xml
} // namespace Utils
namespace CloudFormation
{
namespace Model
{
/**
* <p>The <code>ChangeSetSummary</code> structure describes a change set, its
* status, and the stack with which it's associated.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/cloudformation-2010-05-15/ChangeSetSummary">AWS
* API Reference</a></p>
*/
class AWS_CLOUDFORMATION_API ChangeSetSummary
{
public:
ChangeSetSummary();
ChangeSetSummary(const Aws::Utils::Xml::XmlNode& xmlNode);
ChangeSetSummary& operator=(const Aws::Utils::Xml::XmlNode& xmlNode);
void OutputToStream(Aws::OStream& ostream, const char* location, unsigned index, const char* locationValue) const;
void OutputToStream(Aws::OStream& oStream, const char* location) const;
/**
* <p>The ID of the stack with which the change set is associated.</p>
*/
inline const Aws::String& GetStackId() const{ return m_stackId; }
/**
* <p>The ID of the stack with which the change set is associated.</p>
*/
inline void SetStackId(const Aws::String& value) { m_stackIdHasBeenSet = true; m_stackId = value; }
/**
* <p>The ID of the stack with which the change set is associated.</p>
*/
inline void SetStackId(Aws::String&& value) { m_stackIdHasBeenSet = true; m_stackId = std::move(value); }
/**
* <p>The ID of the stack with which the change set is associated.</p>
*/
inline void SetStackId(const char* value) { m_stackIdHasBeenSet = true; m_stackId.assign(value); }
/**
* <p>The ID of the stack with which the change set is associated.</p>
*/
inline ChangeSetSummary& WithStackId(const Aws::String& value) { SetStackId(value); return *this;}
/**
* <p>The ID of the stack with which the change set is associated.</p>
*/
inline ChangeSetSummary& WithStackId(Aws::String&& value) { SetStackId(std::move(value)); return *this;}
/**
* <p>The ID of the stack with which the change set is associated.</p>
*/
inline ChangeSetSummary& WithStackId(const char* value) { SetStackId(value); return *this;}
/**
* <p>The name of the stack with which the change set is associated.</p>
*/
inline const Aws::String& GetStackName() const{ return m_stackName; }
/**
* <p>The name of the stack with which the change set is associated.</p>
*/
inline void SetStackName(const Aws::String& value) { m_stackNameHasBeenSet = true; m_stackName = value; }
/**
* <p>The name of the stack with which the change set is associated.</p>
*/
inline void SetStackName(Aws::String&& value) { m_stackNameHasBeenSet = true; m_stackName = std::move(value); }
/**
* <p>The name of the stack with which the change set is associated.</p>
*/
inline void SetStackName(const char* value) { m_stackNameHasBeenSet = true; m_stackName.assign(value); }
/**
* <p>The name of the stack with which the change set is associated.</p>
*/
inline ChangeSetSummary& WithStackName(const Aws::String& value) { SetStackName(value); return *this;}
/**
* <p>The name of the stack with which the change set is associated.</p>
*/
inline ChangeSetSummary& WithStackName(Aws::String&& value) { SetStackName(std::move(value)); return *this;}
/**
* <p>The name of the stack with which the change set is associated.</p>
*/
inline ChangeSetSummary& WithStackName(const char* value) { SetStackName(value); return *this;}
/**
* <p>The ID of the change set.</p>
*/
inline const Aws::String& GetChangeSetId() const{ return m_changeSetId; }
/**
* <p>The ID of the change set.</p>
*/
inline void SetChangeSetId(const Aws::String& value) { m_changeSetIdHasBeenSet = true; m_changeSetId = value; }
/**
* <p>The ID of the change set.</p>
*/
inline void SetChangeSetId(Aws::String&& value) { m_changeSetIdHasBeenSet = true; m_changeSetId = std::move(value); }
/**
* <p>The ID of the change set.</p>
*/
inline void SetChangeSetId(const char* value) { m_changeSetIdHasBeenSet = true; m_changeSetId.assign(value); }
/**
* <p>The ID of the change set.</p>
*/
inline ChangeSetSummary& WithChangeSetId(const Aws::String& value) { SetChangeSetId(value); return *this;}
/**
* <p>The ID of the change set.</p>
*/
inline ChangeSetSummary& WithChangeSetId(Aws::String&& value) { SetChangeSetId(std::move(value)); return *this;}
/**
* <p>The ID of the change set.</p>
*/
inline ChangeSetSummary& WithChangeSetId(const char* value) { SetChangeSetId(value); return *this;}
/**
* <p>The name of the change set.</p>
*/
inline const Aws::String& GetChangeSetName() const{ return m_changeSetName; }
/**
* <p>The name of the change set.</p>
*/
inline void SetChangeSetName(const Aws::String& value) { m_changeSetNameHasBeenSet = true; m_changeSetName = value; }
/**
* <p>The name of the change set.</p>
*/
inline void SetChangeSetName(Aws::String&& value) { m_changeSetNameHasBeenSet = true; m_changeSetName = std::move(value); }
/**
* <p>The name of the change set.</p>
*/
inline void SetChangeSetName(const char* value) { m_changeSetNameHasBeenSet = true; m_changeSetName.assign(value); }
/**
* <p>The name of the change set.</p>
*/
inline ChangeSetSummary& WithChangeSetName(const Aws::String& value) { SetChangeSetName(value); return *this;}
/**
* <p>The name of the change set.</p>
*/
inline ChangeSetSummary& WithChangeSetName(Aws::String&& value) { SetChangeSetName(std::move(value)); return *this;}
/**
* <p>The name of the change set.</p>
*/
inline ChangeSetSummary& WithChangeSetName(const char* value) { SetChangeSetName(value); return *this;}
/**
* <p>If the change set execution status is <code>AVAILABLE</code>, you can execute
* the change set. If you can’t execute the change set, the status indicates why.
* For example, a change set might be in an <code>UNAVAILABLE</code> state because
* AWS CloudFormation is still creating it or in an <code>OBSOLETE</code> state
* because the stack was already updated.</p>
*/
inline const ExecutionStatus& GetExecutionStatus() const{ return m_executionStatus; }
/**
* <p>If the change set execution status is <code>AVAILABLE</code>, you can execute
* the change set. If you can’t execute the change set, the status indicates why.
* For example, a change set might be in an <code>UNAVAILABLE</code> state because
* AWS CloudFormation is still creating it or in an <code>OBSOLETE</code> state
* because the stack was already updated.</p>
*/
inline void SetExecutionStatus(const ExecutionStatus& value) { m_executionStatusHasBeenSet = true; m_executionStatus = value; }
/**
* <p>If the change set execution status is <code>AVAILABLE</code>, you can execute
* the change set. If you can’t execute the change set, the status indicates why.
* For example, a change set might be in an <code>UNAVAILABLE</code> state because
* AWS CloudFormation is still creating it or in an <code>OBSOLETE</code> state
* because the stack was already updated.</p>
*/
inline void SetExecutionStatus(ExecutionStatus&& value) { m_executionStatusHasBeenSet = true; m_executionStatus = std::move(value); }
/**
* <p>If the change set execution status is <code>AVAILABLE</code>, you can execute
* the change set. If you can’t execute the change set, the status indicates why.
* For example, a change set might be in an <code>UNAVAILABLE</code> state because
* AWS CloudFormation is still creating it or in an <code>OBSOLETE</code> state
* because the stack was already updated.</p>
*/
inline ChangeSetSummary& WithExecutionStatus(const ExecutionStatus& value) { SetExecutionStatus(value); return *this;}
/**
* <p>If the change set execution status is <code>AVAILABLE</code>, you can execute
* the change set. If you can’t execute the change set, the status indicates why.
* For example, a change set might be in an <code>UNAVAILABLE</code> state because
* AWS CloudFormation is still creating it or in an <code>OBSOLETE</code> state
* because the stack was already updated.</p>
*/
inline ChangeSetSummary& WithExecutionStatus(ExecutionStatus&& value) { SetExecutionStatus(std::move(value)); return *this;}
/**
* <p>The state of the change set, such as <code>CREATE_IN_PROGRESS</code>,
* <code>CREATE_COMPLETE</code>, or <code>FAILED</code>.</p>
*/
inline const ChangeSetStatus& GetStatus() const{ return m_status; }
/**
* <p>The state of the change set, such as <code>CREATE_IN_PROGRESS</code>,
* <code>CREATE_COMPLETE</code>, or <code>FAILED</code>.</p>
*/
inline void SetStatus(const ChangeSetStatus& value) { m_statusHasBeenSet = true; m_status = value; }
/**
* <p>The state of the change set, such as <code>CREATE_IN_PROGRESS</code>,
* <code>CREATE_COMPLETE</code>, or <code>FAILED</code>.</p>
*/
inline void SetStatus(ChangeSetStatus&& value) { m_statusHasBeenSet = true; m_status = std::move(value); }
/**
* <p>The state of the change set, such as <code>CREATE_IN_PROGRESS</code>,
* <code>CREATE_COMPLETE</code>, or <code>FAILED</code>.</p>
*/
inline ChangeSetSummary& WithStatus(const ChangeSetStatus& value) { SetStatus(value); return *this;}
/**
* <p>The state of the change set, such as <code>CREATE_IN_PROGRESS</code>,
* <code>CREATE_COMPLETE</code>, or <code>FAILED</code>.</p>
*/
inline ChangeSetSummary& WithStatus(ChangeSetStatus&& value) { SetStatus(std::move(value)); return *this;}
/**
* <p>A description of the change set's status. For example, if your change set is
* in the <code>FAILED</code> state, AWS CloudFormation shows the error
* message.</p>
*/
inline const Aws::String& GetStatusReason() const{ return m_statusReason; }
/**
* <p>A description of the change set's status. For example, if your change set is
* in the <code>FAILED</code> state, AWS CloudFormation shows the error
* message.</p>
*/
inline void SetStatusReason(const Aws::String& value) { m_statusReasonHasBeenSet = true; m_statusReason = value; }
/**
* <p>A description of the change set's status. For example, if your change set is
* in the <code>FAILED</code> state, AWS CloudFormation shows the error
* message.</p>
*/
inline void SetStatusReason(Aws::String&& value) { m_statusReasonHasBeenSet = true; m_statusReason = std::move(value); }
/**
* <p>A description of the change set's status. For example, if your change set is
* in the <code>FAILED</code> state, AWS CloudFormation shows the error
* message.</p>
*/
inline void SetStatusReason(const char* value) { m_statusReasonHasBeenSet = true; m_statusReason.assign(value); }
/**
* <p>A description of the change set's status. For example, if your change set is
* in the <code>FAILED</code> state, AWS CloudFormation shows the error
* message.</p>
*/
inline ChangeSetSummary& WithStatusReason(const Aws::String& value) { SetStatusReason(value); return *this;}
/**
* <p>A description of the change set's status. For example, if your change set is
* in the <code>FAILED</code> state, AWS CloudFormation shows the error
* message.</p>
*/
inline ChangeSetSummary& WithStatusReason(Aws::String&& value) { SetStatusReason(std::move(value)); return *this;}
/**
* <p>A description of the change set's status. For example, if your change set is
* in the <code>FAILED</code> state, AWS CloudFormation shows the error
* message.</p>
*/
inline ChangeSetSummary& WithStatusReason(const char* value) { SetStatusReason(value); return *this;}
/**
* <p>The start time when the change set was created, in UTC.</p>
*/
inline const Aws::Utils::DateTime& GetCreationTime() const{ return m_creationTime; }
/**
* <p>The start time when the change set was created, in UTC.</p>
*/
inline void SetCreationTime(const Aws::Utils::DateTime& value) { m_creationTimeHasBeenSet = true; m_creationTime = value; }
/**
* <p>The start time when the change set was created, in UTC.</p>
*/
inline void SetCreationTime(Aws::Utils::DateTime&& value) { m_creationTimeHasBeenSet = true; m_creationTime = std::move(value); }
/**
* <p>The start time when the change set was created, in UTC.</p>
*/
inline ChangeSetSummary& WithCreationTime(const Aws::Utils::DateTime& value) { SetCreationTime(value); return *this;}
/**
* <p>The start time when the change set was created, in UTC.</p>
*/
inline ChangeSetSummary& WithCreationTime(Aws::Utils::DateTime&& value) { SetCreationTime(std::move(value)); return *this;}
/**
* <p>Descriptive information about the change set.</p>
*/
inline const Aws::String& GetDescription() const{ return m_description; }
/**
* <p>Descriptive information about the change set.</p>
*/
inline void SetDescription(const Aws::String& value) { m_descriptionHasBeenSet = true; m_description = value; }
/**
* <p>Descriptive information about the change set.</p>
*/
inline void SetDescription(Aws::String&& value) { m_descriptionHasBeenSet = true; m_description = std::move(value); }
/**
* <p>Descriptive information about the change set.</p>
*/
inline void SetDescription(const char* value) { m_descriptionHasBeenSet = true; m_description.assign(value); }
/**
* <p>Descriptive information about the change set.</p>
*/
inline ChangeSetSummary& WithDescription(const Aws::String& value) { SetDescription(value); return *this;}
/**
* <p>Descriptive information about the change set.</p>
*/
inline ChangeSetSummary& WithDescription(Aws::String&& value) { SetDescription(std::move(value)); return *this;}
/**
* <p>Descriptive information about the change set.</p>
*/
inline ChangeSetSummary& WithDescription(const char* value) { SetDescription(value); return *this;}
private:
Aws::String m_stackId;
bool m_stackIdHasBeenSet;
Aws::String m_stackName;
bool m_stackNameHasBeenSet;
Aws::String m_changeSetId;
bool m_changeSetIdHasBeenSet;
Aws::String m_changeSetName;
bool m_changeSetNameHasBeenSet;
ExecutionStatus m_executionStatus;
bool m_executionStatusHasBeenSet;
ChangeSetStatus m_status;
bool m_statusHasBeenSet;
Aws::String m_statusReason;
bool m_statusReasonHasBeenSet;
Aws::Utils::DateTime m_creationTime;
bool m_creationTimeHasBeenSet;
Aws::String m_description;
bool m_descriptionHasBeenSet;
};
} // namespace Model
} // namespace CloudFormation
} // namespace Aws
| 38.209026 | 137 | 0.673256 | [
"model"
] |
45ca2c806b8ca5365e2bcef87879de762f49a447 | 3,159 | h | C | code/AssetLib/Blender/BlenderBMesh.h | Mostro-Complexity/assimp | c3773542f5ac228f12dfd48b5062e9041f3b7e7d | [
"BSD-3-Clause"
] | 3 | 2018-05-29T12:18:08.000Z | 2018-06-20T16:14:13.000Z | code/AssetLib/Blender/BlenderBMesh.h | Mostro-Complexity/assimp | c3773542f5ac228f12dfd48b5062e9041f3b7e7d | [
"BSD-3-Clause"
] | null | null | null | code/AssetLib/Blender/BlenderBMesh.h | Mostro-Complexity/assimp | c3773542f5ac228f12dfd48b5062e9041f3b7e7d | [
"BSD-3-Clause"
] | 1 | 2022-03-23T23:38:26.000Z | 2022-03-23T23:38:26.000Z | /*
Open Asset Import Library (assimp)
----------------------------------------------------------------------
Copyright (c) 2006-2022, assimp team
All rights reserved.
Redistribution and use of this software 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 the assimp team, nor the names of its
contributors may be used to endorse or promote products
derived from this software without specific prior
written permission of the assimp team.
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.
----------------------------------------------------------------------
*/
/** @file BlenderBMesh.h
* @brief Conversion of Blender's new BMesh stuff
*/
#ifndef INCLUDED_AI_BLEND_BMESH_H
#define INCLUDED_AI_BLEND_BMESH_H
#include <assimp/LogAux.h>
namespace Assimp
{
// TinyFormatter.h
namespace Formatter
{
template < typename T,typename TR, typename A > class basic_formatter;
typedef class basic_formatter< char, std::char_traits< char >, std::allocator< char > > format;
}
// BlenderScene.h
namespace Blender
{
struct Mesh;
struct MPoly;
struct MLoop;
}
class BlenderBMeshConverter: public LogFunctions< BlenderBMeshConverter >
{
public:
BlenderBMeshConverter( const Blender::Mesh* mesh );
~BlenderBMeshConverter( );
bool ContainsBMesh( ) const;
const Blender::Mesh* TriangulateBMesh( );
private:
void AssertValidMesh( );
void AssertValidSizes( );
void PrepareTriMesh( );
void DestroyTriMesh( );
void ConvertPolyToFaces( const Blender::MPoly& poly );
void AddFace( int v1, int v2, int v3, int v4 = 0 );
void AddTFace( const float* uv1, const float* uv2, const float *uv3, const float* uv4 = 0 );
const Blender::Mesh* BMesh;
Blender::Mesh* triMesh;
friend class BlenderTessellatorGL;
friend class BlenderTessellatorP2T;
};
} // end of namespace Assimp
#endif // INCLUDED_AI_BLEND_BMESH_H
| 33.252632 | 103 | 0.695157 | [
"mesh"
] |
45ccbca9e1858b08a471ec84adc5bd961a596fc3 | 4,866 | h | C | Descending Europa/Temp/StagingArea/Data/il2cppOutput/mscorlib_System_UIntPtr3365854250MethodDeclarations.h | screwylightbulb/europa | 3dcc98369c8066cb2310143329535206751c8846 | [
"MIT"
] | 11 | 2016-07-22T19:58:09.000Z | 2021-09-21T12:51:40.000Z | Descending Europa/Temp/StagingArea/Data/il2cppOutput/mscorlib_System_UIntPtr3365854250MethodDeclarations.h | screwylightbulb/europa | 3dcc98369c8066cb2310143329535206751c8846 | [
"MIT"
] | 1 | 2018-05-07T14:32:13.000Z | 2018-05-08T09:15:30.000Z | iOS/Classes/Native/mscorlib_System_UIntPtr3365854250MethodDeclarations.h | mopsicus/unity-share-plugin-ios-android | 3ee99aef36034a1e4d7b156172953f9b4dfa696f | [
"MIT"
] | null | null | null | #pragma once
#include "il2cpp-config.h"
#ifndef _MSC_VER
# include <alloca.h>
#else
# include <malloc.h>
#endif
#include <stdint.h>
#include <assert.h>
#include <exception>
// System.Runtime.Serialization.SerializationInfo
struct SerializationInfo_t2185721892;
// System.Object
struct Il2CppObject;
// System.String
struct String_t;
#include "codegen/il2cpp-codegen.h"
#include "mscorlib_System_UIntPtr3365854250.h"
#include "mscorlib_System_Void2863195528.h"
#include "mscorlib_System_Runtime_Serialization_Serializatio2185721892.h"
#include "mscorlib_System_Runtime_Serialization_StreamingCon2761351129.h"
#include "mscorlib_System_Object4170816371.h"
// System.Void System.UIntPtr::.ctor(System.UInt64)
extern "C" void UIntPtr__ctor_m3952300446 (UIntPtr_t * __this, uint64_t ___value0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void System.UIntPtr::.ctor(System.UInt32)
extern "C" void UIntPtr__ctor_m3952297501 (UIntPtr_t * __this, uint32_t ___value0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void System.UIntPtr::.ctor(System.Void*)
extern "C" void UIntPtr__ctor_m1853619782 (UIntPtr_t * __this, void* ___value0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void System.UIntPtr::.cctor()
extern "C" void UIntPtr__cctor_m3952213328 (Il2CppObject * __this /* static, unused */, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void System.UIntPtr::System.Runtime.Serialization.ISerializable.GetObjectData(System.Runtime.Serialization.SerializationInfo,System.Runtime.Serialization.StreamingContext)
extern "C" void UIntPtr_System_Runtime_Serialization_ISerializable_GetObjectData_m1506461934 (UIntPtr_t * __this, SerializationInfo_t2185721892 * ___info0, StreamingContext_t2761351129 ___context1, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Boolean System.UIntPtr::Equals(System.Object)
extern "C" bool UIntPtr_Equals_m2746368876 (UIntPtr_t * __this, Il2CppObject * ___obj0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Int32 System.UIntPtr::GetHashCode()
extern "C" int32_t UIntPtr_GetHashCode_m939387472 (UIntPtr_t * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.UInt32 System.UIntPtr::ToUInt32()
extern "C" uint32_t UIntPtr_ToUInt32_m3683901238 (UIntPtr_t * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.UInt64 System.UIntPtr::ToUInt64()
extern "C" uint64_t UIntPtr_ToUInt64_m958857238 (UIntPtr_t * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void* System.UIntPtr::ToPointer()
extern "C" void* UIntPtr_ToPointer_m365084105 (UIntPtr_t * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.String System.UIntPtr::ToString()
extern "C" String_t* UIntPtr_ToString_m2250548790 (UIntPtr_t * __this, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Int32 System.UIntPtr::get_Size()
extern "C" int32_t UIntPtr_get_Size_m3534433933 (Il2CppObject * __this /* static, unused */, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Boolean System.UIntPtr::op_Equality(System.UIntPtr,System.UIntPtr)
extern "C" bool UIntPtr_op_Equality_m2619366549 (Il2CppObject * __this /* static, unused */, UIntPtr_t ___value10, UIntPtr_t ___value21, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Boolean System.UIntPtr::op_Inequality(System.UIntPtr,System.UIntPtr)
extern "C" bool UIntPtr_op_Inequality_m3507406160 (Il2CppObject * __this /* static, unused */, UIntPtr_t ___value10, UIntPtr_t ___value21, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.UInt64 System.UIntPtr::op_Explicit(System.UIntPtr)
extern "C" uint64_t UIntPtr_op_Explicit_m2238365276 (Il2CppObject * __this /* static, unused */, UIntPtr_t ___value0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.UInt32 System.UIntPtr::op_Explicit(System.UIntPtr)
extern "C" uint32_t UIntPtr_op_Explicit_m599953533 (Il2CppObject * __this /* static, unused */, UIntPtr_t ___value0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.UIntPtr System.UIntPtr::op_Explicit(System.UInt64)
extern "C" UIntPtr_t UIntPtr_op_Explicit_m1125931844 (Il2CppObject * __this /* static, unused */, uint64_t ___value0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.UIntPtr System.UIntPtr::op_Explicit(System.Void*)
extern "C" UIntPtr_t UIntPtr_op_Explicit_m376973280 (Il2CppObject * __this /* static, unused */, void* ___value0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.Void* System.UIntPtr::op_Explicit(System.UIntPtr)
extern "C" void* UIntPtr_op_Explicit_m555260452 (Il2CppObject * __this /* static, unused */, UIntPtr_t ___value0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
// System.UIntPtr System.UIntPtr::op_Explicit(System.UInt32)
extern "C" UIntPtr_t UIntPtr_op_Explicit_m1125928899 (Il2CppObject * __this /* static, unused */, uint32_t ___value0, const MethodInfo* method) IL2CPP_METHOD_ATTR;
| 70.521739 | 245 | 0.808467 | [
"object"
] |
45d427b37cb7ef92a4a47d53c3a0cb92249e9c8d | 4,725 | h | C | src/ObjRecRANSAC/Shapes/ORRPointSetShape.h | CRLab/ObjRecRANSAC | 32e6a422465d710f54e6fac3d96fd80bc862f679 | [
"Unlicense"
] | 30 | 2015-05-31T06:27:25.000Z | 2021-06-03T11:42:43.000Z | src/ObjRecRANSAC/Shapes/ORRPointSetShape.h | CRLab/ObjRecRANSAC | 32e6a422465d710f54e6fac3d96fd80bc862f679 | [
"Unlicense"
] | 3 | 2016-02-17T04:22:29.000Z | 2019-04-03T13:33:56.000Z | src/ObjRecRANSAC/Shapes/ORRPointSetShape.h | CRLab/ObjRecRANSAC | 32e6a422465d710f54e6fac3d96fd80bc862f679 | [
"Unlicense"
] | 26 | 2015-03-12T05:33:32.000Z | 2021-12-07T02:50:35.000Z | #ifndef _GEOMETRIC_SHAPE_H_
#define _GEOMETRIC_SHAPE_H_
#include "PointSetShape.h"
#include "../DataStructures/RangeImage/ORRRangeImage2.h"
#include <BasicToolsL1/Vector.h>
#include <BasicToolsL1/Matrix.h>
#include <vtkPolyData.h>
#include <algorithm>
#include <vector>
#include <list>
using namespace std;
class ORRPointSetShape: public PointSetShape
{
public:
inline ORRPointSetShape(UserData* userdata, vtkPolyData* polydata, const double* rigid_transform,
vtkPolyData* highResModel, int instanceNumber);
virtual ~ORRPointSetShape(){}
enum SceneState {SCENE_FREE = 0, SCENE_ON, SCENE_OFF};
int getInstanceNumber(){ return mInstanceNumber;}
const char* getLabel(){ return mLabel;}
SceneState getSceneState(){ return mSceneState;}
void setSceneState(SceneState state){ mSceneState = state;}
void setSceneStateOff(){ mSceneState = SCENE_OFF;}
void setSceneStateOn(){ mSceneState = SCENE_ON;}
bool isSceneStateOff(){ return mSceneState == SCENE_OFF;}
bool isSceneStateOn(){ return mSceneState == SCENE_ON;}
inline void getPoint1(double* p)const{ vec_copy3(m_p1, p);}
inline void getPoint2(double* p)const{ vec_copy3(m_p2, p);}
inline void getPoint3(double* p)const{ vec_copy3(m_p3, p);}
inline void getNormal1(double* n)const{ vec_copy3(m_n1, n);}
inline void getNormal2(double* n)const{ vec_copy3(m_n2, n);}
inline void getNormal3(double* n)const{ vec_copy3(m_n3, n);}
const double* getPoint1(){ return m_p1;}
const double* getPoint2(){ return m_p2;}
const double* getPoint3(){ return m_p3;}
const double* getNormal1(){ return m_n1;}
const double* getNormal2(){ return m_n2;}
const double* getNormal3(){ return m_n3;}
inline void setPoint1(const double* p){ vec_copy3(p, m_p1);}
inline void setPoint2(const double* p){ vec_copy3(p, m_p2);}
inline void setPoint3(const double* p){ vec_copy3(p, m_p3);}
inline void setNormal1(const double* n){ vec_copy3(n, m_n1);}
inline void setNormal2(const double* n){ vec_copy3(n, m_n2);}
inline void setNormal3(const double* n){ vec_copy3(n, m_n3);}
inline void addPixel(const ORRRangeImage2* image, int x, int y);
int getNumberOfOccupiedScenePixels(){ return (int)mLinearPixelIds.size();}
list<OctreeNode*>& getOctreeSceneNodes(){ return mSceneOctreeNodes;}
inline void sortLinearPixelIds();
const vector<int>& getLinearPixelIds(){ return mLinearPixelIds;}
void setShapeId(int id){ mShapeId = id;}
int getShapeId()const{ return mShapeId;}
protected:
int mInstanceNumber;
char mLabel[2048];
SceneState mSceneState;
double m_p1[3], m_p2[3], m_p3[3], m_n1[3], m_n2[3], m_n3[3];
int mShapeId;
// Needed in order to get the point ids of the points contained in each node
list<OctreeNode*> mSceneOctreeNodes;
vector<int> mLinearPixelIds;
};
//=== inline methods ==================================================================================================================
inline ORRPointSetShape::ORRPointSetShape(UserData* userdata, vtkPolyData* polydata, const double* rigid_transform,
vtkPolyData* highResModel, int instanceNumber)
: PointSetShape(userdata, polydata, rigid_transform, highResModel)
{
mInstanceNumber = instanceNumber;
mSceneState = ORRPointSetShape::SCENE_FREE;
mShapeId = -1;
if ( mUserData )
sprintf(mLabel, "%s_%i", mUserData->getLabel(), mInstanceNumber);
else
sprintf(mLabel, "point set shape %i", mInstanceNumber);
}
//=====================================================================================================================================
inline void ORRPointSetShape::addPixel(const ORRRangeImage2* image, int x, int y)
{
// Get the scene nodes at the pixel [x, y]
const list<OctreeNode*>* nodes = image->getOctreeNodes()[x][y];
if ( !nodes )
{
fprintf(stderr, "WARNING in 'ORRPointSetShape::%s()': there should be a list of nodes at pixel [%i, %i].\n", __func__, x, y);
fflush(stderr);
return;
}
// Save the linear id
mLinearPixelIds.push_back(image->getLinearId(x, y));
// Save the nodes
for ( list<OctreeNode*>::const_iterator node = nodes->begin() ; node != nodes->end() ; ++node )
mSceneOctreeNodes.push_back(*node);
}
//=====================================================================================================================================
inline bool compareIntFunc(int i,int j) { return (i<j); }
//=====================================================================================================================================
inline void ORRPointSetShape::sortLinearPixelIds()
{
sort(mLinearPixelIds.begin(), mLinearPixelIds.end(), compareIntFunc);
}
//=====================================================================================================================================
#endif /*_GEOMETRIC_SHAPE_H_*/
| 37.5 | 135 | 0.639788 | [
"shape",
"vector"
] |
45d4d0d53b2549b868402756bc87a5dc39454617 | 1,459 | h | C | System/Library/PrivateFrameworks/WebKitLegacy.framework/DOMHTMLAppletElement.h | lechium/tvOS130Headers | 6b47cdcd4a6f453b399aa9d742b5d0f7e3f732fd | [
"MIT"
] | 11 | 2019-11-06T04:48:48.000Z | 2022-02-09T17:48:15.000Z | System/Library/PrivateFrameworks/WebKitLegacy.framework/DOMHTMLAppletElement.h | lechium/tvOS130Headers | 6b47cdcd4a6f453b399aa9d742b5d0f7e3f732fd | [
"MIT"
] | 1 | 2020-04-16T01:41:56.000Z | 2020-04-16T04:32:00.000Z | System/Library/PrivateFrameworks/WebKitLegacy.framework/DOMHTMLAppletElement.h | lechium/tvOS130Headers | 6b47cdcd4a6f453b399aa9d742b5d0f7e3f732fd | [
"MIT"
] | 3 | 2019-12-22T20:17:53.000Z | 2021-01-25T09:47:49.000Z | /*
* This header is generated by classdump-dyld 1.0
* on Tuesday, November 5, 2019 at 2:47:01 AM Mountain Standard Time
* Operating System: Version 13.0 (Build 17J586)
* Image Source: /System/Library/PrivateFrameworks/WebKitLegacy.framework/WebKitLegacy
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos.
*/
#import <WebKitLegacy/DOMHTMLElement.h>
@class NSString;
@interface DOMHTMLAppletElement : DOMHTMLElement
@property (copy) NSString * align;
@property (copy) NSString * alt;
@property (copy) NSString * archive;
@property (copy) NSString * code;
@property (copy) NSString * codeBase;
@property (copy) NSString * height;
@property (assign) int hspace;
@property (copy) NSString * name;
@property (copy) NSString * object;
@property (assign) int vspace;
@property (copy) NSString * width;
-(BOOL)showsTapHighlight;
-(NSString *)name;
-(NSString *)object;
-(NSString *)code;
-(void)setObject:(NSString *)arg1 ;
-(void)setName:(NSString *)arg1 ;
-(NSString *)width;
-(NSString *)height;
-(void)setWidth:(NSString *)arg1 ;
-(void)setHeight:(NSString *)arg1 ;
-(void)setCode:(NSString *)arg1 ;
-(NSString *)align;
-(void)setAlign:(NSString *)arg1 ;
-(NSString *)alt;
-(void)setAlt:(NSString *)arg1 ;
-(NSString *)archive;
-(void)setArchive:(NSString *)arg1 ;
-(NSString *)codeBase;
-(void)setCodeBase:(NSString *)arg1 ;
-(int)hspace;
-(void)setHspace:(int)arg1 ;
-(int)vspace;
-(void)setVspace:(int)arg1 ;
@end
| 28.607843 | 85 | 0.717615 | [
"object"
] |
45d5fcd592076ed32d4da89a12763165fe8057a7 | 8,142 | c | C | rpython/rlib/src/boehm-rawrefcount.c | m4sterchain/mesapy | ed546d59a21b36feb93e2309d5c6b75aa0ad95c9 | [
"Apache-2.0",
"OpenSSL"
] | 381 | 2018-08-18T03:37:22.000Z | 2022-02-06T23:57:36.000Z | rpython/rlib/src/boehm-rawrefcount.c | m4sterchain/mesapy | ed546d59a21b36feb93e2309d5c6b75aa0ad95c9 | [
"Apache-2.0",
"OpenSSL"
] | 16 | 2018-09-22T18:12:47.000Z | 2022-02-22T20:03:59.000Z | rpython/rlib/src/boehm-rawrefcount.c | m4sterchain/mesapy | ed546d59a21b36feb93e2309d5c6b75aa0ad95c9 | [
"Apache-2.0",
"OpenSSL"
] | 30 | 2018-08-20T03:16:34.000Z | 2022-01-12T17:39:22.000Z | #include <stdlib.h>
#include <stdint.h>
#include <stdio.h>
#include <assert.h>
#include <limits.h>
#include <gc/gc.h>
#include <gc/gc_mark.h>
#ifdef TEST_BOEHM_RAWREFCOUNT
# define RPY_EXTERN /* nothing */
#else
# include "common_header.h"
#endif
#define REFCNT_FROM_PYPY (LONG_MAX / 4 + 1)
typedef struct pypy_header0 gcobj_t; /* opaque here */
#ifndef _WIN32
typedef intptr_t Py_ssize_t;
#else
typedef long Py_ssize_t;
#endif
/* this is the first two words of the PyObject structure used in
pypy/module/cpyext */
typedef struct {
Py_ssize_t ob_refcnt;
Py_ssize_t ob_pypy_link;
} pyobj_t;
struct link_s {
pyobj_t *pyobj; /* NULL if entry unused */
uintptr_t gcenc;
struct link_s *next_in_bucket;
};
#define MARKER_LIST_START ((pyobj_t *)-1)
static struct link_s **hash_buckets, *hash_list, *hash_free_list;
static uintptr_t hash_mask_bucket;
static intptr_t hash_list_walk_next = -1;
static uintptr_t hash_get_hash(gcobj_t *gcobj)
{
assert(gcobj != NULL);
uintptr_t h = (uintptr_t)gcobj;
assert((h & 1) == 0);
h -= (h >> 6);
return h & hash_mask_bucket;
}
static gcobj_t *decode_gcenc(uintptr_t gcenc)
{
if (gcenc & 1)
gcenc = ~gcenc;
return (gcobj_t *)gcenc;
}
static void hash_link(struct link_s *lnk)
{
uintptr_t h = hash_get_hash(decode_gcenc(lnk->gcenc));
lnk->next_in_bucket = hash_buckets[h];
hash_buckets[h] = lnk;
}
static void boehm_is_about_to_collect(void);
static void hash_grow_table(void)
{
static int rec = 0;
assert(!rec); /* recursive hash_grow_table() */
rec = 1;
if (hash_buckets == NULL)
GC_set_start_callback(boehm_is_about_to_collect);
uintptr_t i, num_buckets = (hash_mask_bucket + 1) * 2;
if (num_buckets < 16) num_buckets = 16;
assert((num_buckets & (num_buckets - 1)) == 0); /* power of two */
/* The new hash_buckets: an array of pointers to struct link_s, of
length a power of two, used as a dictionary hash table. It is
not allocated with Boehm because there is no point in Boehm looking
in it.
*/
struct link_s **new_buckets = calloc(num_buckets, sizeof(struct link_s *));
assert(new_buckets);
/* The new hash_list: the array of all struct link_s. Their order
is irrelevant. There is a GC_register_finalizer() on the 'gcenc'
field, so we don't move the array; instead we allocate a new array
to use in addition to the old one. There are a total of 2 to 4
times as many 'struct link_s' as the length of 'buckets'.
*/
uintptr_t num_list = num_buckets * 2;
struct link_s *new_list = GC_MALLOC(num_list * sizeof(struct link_s));
for (i = num_list; i-- > 1; ) {
new_list[i].next_in_bucket = hash_free_list;
hash_free_list = &new_list[i];
}
/* list[0] is abused to store a pointer to the previous list and
the length of the current list */
struct link_s *old_list = hash_list;
new_list[0].next_in_bucket = old_list;
new_list[0].gcenc = num_list;
new_list[0].pyobj = MARKER_LIST_START;
hash_list = new_list;
free(hash_buckets);
hash_buckets = new_buckets;
hash_mask_bucket = num_buckets - 1;
hash_list_walk_next = hash_mask_bucket;
/* re-add all old 'struct link_s' to the hash_buckets */
struct link_s *plist = old_list;
while (plist != NULL) {
uintptr_t count = plist[0].gcenc;
for (i = 1; i < count; i++) {
if (plist[i].gcenc != 0)
hash_link(&plist[i]);
}
plist = plist[0].next_in_bucket;
}
GC_reachable_here(old_list);
rec = 0;
}
static void hash_add_entry(gcobj_t *gcobj, pyobj_t *pyobj)
{
if (hash_free_list == NULL) {
hash_grow_table();
}
assert(pyobj->ob_pypy_link == 0);
struct link_s *lnk = hash_free_list;
hash_free_list = lnk->next_in_bucket;
lnk->pyobj = pyobj;
lnk->gcenc = (uintptr_t)gcobj;
pyobj->ob_pypy_link = (Py_ssize_t)lnk;
hash_link(lnk);
if (GC_base(gcobj) == NULL) {
/* 'gcobj' is probably a prebuilt object - it makes no */
/* sense to register it then, and it crashes Boehm in */
/* quite obscure ways */
}
else {
int j = GC_general_register_disappearing_link(
(void **)&lnk->gcenc, gcobj);
assert(j == GC_SUCCESS);
}
}
static pyobj_t *hash_get_entry(gcobj_t *gcobj)
{
if (hash_buckets == NULL)
return NULL;
uintptr_t h = hash_get_hash(gcobj);
struct link_s *lnk = hash_buckets[h];
while (lnk != NULL) {
assert(lnk->pyobj != NULL);
if (decode_gcenc(lnk->gcenc) == gcobj)
return lnk->pyobj;
lnk = lnk->next_in_bucket;
}
return NULL;
}
RPY_EXTERN
/*pyobj_t*/void *gc_rawrefcount_next_dead(void)
{
while (hash_list_walk_next >= 0) {
struct link_s *p, **pp = &hash_buckets[hash_list_walk_next];
while (1) {
p = *pp;
if (p == NULL)
break;
assert(p->pyobj != NULL);
if (p->gcenc == 0) {
/* quadratic time on the number of links from the same
bucket chain, but it should be small with very high
probability */
pyobj_t *result = p->pyobj;
#ifdef TEST_BOEHM_RAWREFCOUNT
printf("next_dead: %p\n", result);
#endif
assert(result->ob_refcnt == REFCNT_FROM_PYPY);
result->ob_refcnt = 1;
p->pyobj = NULL;
*pp = p->next_in_bucket;
p->next_in_bucket = hash_free_list;
hash_free_list = p;
return result;
}
else {
assert(p->gcenc != ~(uintptr_t)0);
pp = &p->next_in_bucket;
}
}
hash_list_walk_next--;
}
return NULL;
}
RPY_EXTERN
void gc_rawrefcount_create_link_pypy(/*gcobj_t*/void *gcobj,
/*pyobj_t*/void *pyobj)
{
gcobj_t *gcobj1 = (gcobj_t *)gcobj;
pyobj_t *pyobj1 = (pyobj_t *)pyobj;
assert(pyobj1->ob_pypy_link == 0);
/*assert(pyobj1->ob_refcnt >= REFCNT_FROM_PYPY);*/
/*^^^ could also be fixed just after the call to create_link_pypy()*/
hash_add_entry(gcobj1, pyobj1);
}
RPY_EXTERN
/*pyobj_t*/void *gc_rawrefcount_from_obj(/*gcobj_t*/void *gcobj)
{
return hash_get_entry((gcobj_t *)gcobj);
}
RPY_EXTERN
/*gcobj_t*/void *gc_rawrefcount_to_obj(/*pyobj_t*/void *pyobj)
{
pyobj_t *pyobj1 = (pyobj_t *)pyobj;
if (pyobj1->ob_pypy_link == 0)
return NULL;
struct link_s *lnk = (struct link_s *)pyobj1->ob_pypy_link;
assert(lnk->pyobj == pyobj1);
gcobj_t *g = decode_gcenc(lnk->gcenc);
assert(g != NULL);
return g;
}
static void boehm_is_about_to_collect(void)
{
struct link_s *plist = hash_list;
uintptr_t gcenc_union = 0;
while (plist != NULL) {
uintptr_t i, count = plist[0].gcenc;
for (i = 1; i < count; i++) {
if (plist[i].gcenc == 0)
continue;
pyobj_t *p = plist[i].pyobj;
assert(p != NULL);
assert(p->ob_refcnt >= REFCNT_FROM_PYPY);
#ifdef TEST_BOEHM_RAWREFCOUNT
printf("plist[%d].gcenc: %p ", (int)i, (void *)plist[i].gcenc);
#endif
if ((plist[i].gcenc & 1) ^ (p->ob_refcnt == REFCNT_FROM_PYPY)) {
/* ob_refcnt > FROM_PYPY: non-zero regular refcnt,
the gc obj must stay alive. decode gcenc.
---OR---
ob_refcnt == FROM_PYPY: no refs from C code, the
gc obj must not (necessarily) stay alive. encode gcenc.
*/
plist[i].gcenc = ~plist[i].gcenc;
}
gcenc_union |= plist[i].gcenc;
#ifdef TEST_BOEHM_RAWREFCOUNT
printf("-> %p\n", (void *)plist[i].gcenc);
#endif
}
plist = plist[0].next_in_bucket;
}
if (gcenc_union & 1) /* if there is at least one item potentially dead */
hash_list_walk_next = hash_mask_bucket;
}
| 28.770318 | 79 | 0.60059 | [
"object"
] |
45d8ec993117aa10179f813229e289ff198c6c32 | 2,269 | h | C | NYAlertViewController/NYAlertViewController.h | willyue/NYAlertViewController | 997e82d5fd9b359e5043329fe4f5f8d15c46fb0c | [
"MIT"
] | 671 | 2015-07-26T08:51:46.000Z | 2021-12-20T23:40:01.000Z | NYAlertViewController/NYAlertViewController.h | willyue/NYAlertViewController | 997e82d5fd9b359e5043329fe4f5f8d15c46fb0c | [
"MIT"
] | 31 | 2015-08-06T11:16:55.000Z | 2020-09-20T16:06:57.000Z | NYAlertViewController/NYAlertViewController.h | willyue/NYAlertViewController | 997e82d5fd9b359e5043329fe4f5f8d15c46fb0c | [
"MIT"
] | 128 | 2015-08-04T23:31:33.000Z | 2021-09-18T14:00:03.000Z | #import <UIKit/UIKit.h>
#import "NYAlertAction.h"
#import "NYAlertViewControllerConfiguration.h"
NS_ASSUME_NONNULL_BEGIN
@interface NYAlertViewController : UIViewController
- (instancetype)initWithOptions:(nullable NYAlertViewControllerConfiguration *)configuration
title:(nullable NSString *)title
message:(nullable NSString *)message
actions:(NSArray<NYAlertAction *> *)actions;
+ (instancetype)new NS_UNAVAILABLE;
- (instancetype)init NS_UNAVAILABLE;
- (instancetype)initWithNibName:(nullable NSString *)nibNameOrNil bundle:(nullable NSBundle *)nibBundleOrNil NS_UNAVAILABLE;
- (instancetype)initWithCoder:(NSCoder *)aDecoder NS_UNAVAILABLE;
/**
The configuration object used to initialize the alert view controller, or the default configuration if the alert view controller was initialized without a configuration.
*/
@property (nonatomic, readonly) NYAlertViewControllerConfiguration *configuration;
/**
The message displayed under the alert view's title.
*/
@property (nonatomic, nullable) NSString *message;
/**
The custom view displayed in the presented alert view
@discussion The default value of this property is nil. Set this property to a view that you create to add the custom view to the displayed alert view.
*/
@property (nonatomic, nullable) UIView *alertViewContentView;
/**
The maximum width at which to display the presented alert view.
*/
@property (nonatomic) CGFloat maximumWidth;
/**
An array of NYAlertAction objects representing the actions that the user can take in response to the alert view
*/
@property (nonatomic, readonly) NSArray<NYAlertAction *> *actions;
/**
An array of UITextField objects displayed by the alert view
@see addTextFieldWithConfigurationHandler:
*/
@property (nonatomic, readonly) NSArray<UITextField *> *textFields;
/**
Add a text field object to be displayed in the alert view
@param configurationHandler A block used to configure the text field. The block takes the text field object as a parameter, and can modify the properties of the text field prior to being displayed.
*/
- (void)addTextFieldWithConfigurationHandler:(void (^)(UITextField *textField))configurationHandler;
@end
NS_ASSUME_NONNULL_END
| 36.015873 | 198 | 0.767298 | [
"object"
] |
45da5fcf588279b09391d75416a7c8ced6235030 | 8,725 | h | C | PWGHF/correlationHF/AliHFOfflineCorrelator.h | wiechula/AliPhysics | 6c5c45a5c985747ee82328d8fd59222b34529895 | [
"BSD-3-Clause"
] | null | null | null | PWGHF/correlationHF/AliHFOfflineCorrelator.h | wiechula/AliPhysics | 6c5c45a5c985747ee82328d8fd59222b34529895 | [
"BSD-3-Clause"
] | null | null | null | PWGHF/correlationHF/AliHFOfflineCorrelator.h | wiechula/AliPhysics | 6c5c45a5c985747ee82328d8fd59222b34529895 | [
"BSD-3-Clause"
] | null | null | null | #ifndef AliHFOfflineCorrelator_H
#define AliHFOfflineCorrelator_H
/**************************************************************************
* Copyright(c) 1998-2016, ALICE Experiment at CERN, All rights reserved. *
* *
* Author: The ALICE Off-line Project. *
* Contributors are mentioned in the code where appropriate. *
* *
* Permission to use, copy, modify and distribute this software and its *
* documentation strictly for non-commercial purposes is hereby granted *
* without fee, provided that the above copyright notice appears in all *
* copies and that both the copyright notice and this permission notice *
* appear in the supporting documentation. The authors make no claims *
* about the suitability of this software for any purpose. It is *
* provided "as is" without express or implied warranty. *
**************************************************************************/
//
// Base class to perform D-h correlations offline (starting from D-meson and hadron TTrees)
//
//-----------------------------------------------------------------------
// Author F.Colamaria
// INFN Bari
// fabio.colamaria@cern.ch
//-----------------------------------------------------------------------
#include <iostream>
#include "TObject.h"
#include "TMath.h"
#include "TFile.h"
#include "TDirectoryFile.h"
#include "TList.h"
#include "TH2F.h"
#include "TH3F.h"
#include "TTree.h"
#include "TRandom3.h"
#include "TStopwatch.h"
#include "TDatabasePDG.h"
#include "AliHFAssociatedTrackCuts.h"
using std::vector;
class AliHFCorrelationBranchD : public TObject
{
public:
AliHFCorrelationBranchD(); // default constructor
Float_t phi_D;
Float_t eta_D;
Float_t pT_D;
Float_t mult_D;
Float_t zVtx_D;
Float_t cent_D;
Float_t invMass_D;
UInt_t period_D;
UInt_t orbit_D;
UShort_t BC_D;
Short_t IDtrig_D;
Short_t sel_D;
Float_t pXdaug1_D;
Float_t pXdaug2_D;
Float_t pYdaug1_D;
Float_t pYdaug2_D;
Float_t pZdaug1_D;
Float_t pZdaug2_D;
UShort_t hyp_D; //1 or 2 (no 3, because double hypotheses are filled as separate entries)
ClassDef(AliHFCorrelationBranchD,2);
};
class AliHFCorrelationBranchTr : public TObject
{
public:
AliHFCorrelationBranchTr(); // default constructor
Float_t phi_Tr;
Float_t eta_Tr;
Float_t pT_Tr;
Float_t mult_Tr;
Float_t zVtx_Tr;
Float_t cent_Tr;
UInt_t period_Tr;
UInt_t orbit_Tr;
UShort_t BC_Tr;
Short_t IDtrig_Tr;
Short_t IDtrig2_Tr;
Short_t IDtrig3_Tr;
Short_t IDtrig4_Tr;
Short_t sel_Tr;
ClassDef(AliHFCorrelationBranchTr,3);
};
class AliHFOfflineCorrelator : public TObject
{
public:
enum DMesonSpecies {kD0toKpi, kDplusKpipi, kDStarD0pi};
enum AnalysisType {kSE, kME};
AliHFOfflineCorrelator(); // default constructor
AliHFOfflineCorrelator(const AliHFOfflineCorrelator &source);
AliHFOfflineCorrelator& operator=(const AliHFOfflineCorrelator& source);
virtual ~AliHFOfflineCorrelator();
Bool_t SetDmesonSpecie(DMesonSpecies k);
void SetAnalysisType(AnalysisType k) {fAnType=k;}
void SetUseEfficiency(Bool_t eff) {fUseEff=eff;}
void AddInputFile(TString str) {fFileList.push_back(str); fNinputFiles++;}
void SetDirName(TString dirname) {fDirName=dirname;}
void SetTreeNames(TString nameD, TString nameTr) {fNameTreeD=nameD; fNameTreeTr=nameTr;}
void SetEffMapNames(TString cutObj, TString nameD, TString nameTr) {fNameCutObj=cutObj; fNameMapD=nameD; fNameMapTr=nameTr;}
void SetDPtBins(Int_t nBins, Double_t* ptDarray);
void AddAssocPtRange(Double_t lowPt, Double_t upPt) {fPtBinsTrLow.push_back(lowPt); fPtBinsTrUp.push_back(upPt);}
void MakeDetaDphiPlots(Double_t* MsigL, Double_t* MsigR, Double_t* MSB1L, Double_t* MSB1R, Double_t* MSB2L=0x0, Double_t* MSB2R=0x0); //makes 2D plots for sign.region and SB
void SetOutputFileName(TString namefile) {fOutputFileName=namefile;}
void SetPoolBins(Int_t nMultPools, Double_t* multBins, Int_t nzVtxPools, Double_t* zVtxBins);
void SetMaxTracksToCorrelate(Int_t maxTracks=-1) {fMaxTracks=maxTracks;}
void SetDLoopRange(Int_t minD=-1, Int_t maxD=-1) {fMinD=minD; fMaxD=maxD;}
void SetWeightPeriods(Bool_t wgh) {fWeightPeriods=wgh;}
void SetFirstBinNum(Int_t num=0) {fFirstBinNum=num;}
void SetNumSelD(Int_t sel) {fNumSelD=sel;}
void SetNumSelTr(Int_t sel) {fNumSelTr=sel;}
void SetCentralitySelection(Double_t min, Double_t max) {fMinCent=min; fMaxCent=max;} //activated only if both values are != 0
void SetRemoveSoftPionInME(Bool_t remove) {fRemoveSoftPiInME=remove;}
void SetDebugLevel(Int_t deb=0) {fDebug=deb;}
Bool_t Correlate();
void DefineOutputObjects();
void PrintCfg() const;
Bool_t CorrelateSingleFile(Int_t iFile);
void GetCorrelationsValue(AliHFCorrelationBranchD *brD, AliHFCorrelationBranchTr *brTr, Double_t &deltaPhi, Double_t &deltaEta);
Double_t GetEfficiencyWeight(AliHFCorrelationBranchD *brD, AliHFCorrelationBranchTr *brTr);
Double_t GetEfficiencyWeightDOnly(AliHFCorrelationBranchD *brD);
Bool_t IsSoftPionFromDstar(AliHFCorrelationBranchD *brD, AliHFCorrelationBranchTr *brTr);
Int_t PtBin(Double_t pt) const;
Int_t GetPoolBin(Double_t mult, Double_t zVtx) const;
Bool_t DefinePeriodWeights();
void NormalizeMEPlots();
void SaveOutputPlots();
private:
std::vector<TString> fFileList; //container of input filenames
Int_t fNinputFiles; //number of input files
TFile *fFile; //file containing the analysis output
TTree *fTreeD; //for D Tree allocation
TTree *fTreeTr; //for associated track Tree allocation
TList *fOutputDistr; //allocates the outputcorrelation plots
TList *fOutputMass; //allocates the mass plots
Int_t fNBinsPt; //number of D-meson pT bins
Int_t fnPools; //number of ME pools (total)
Int_t fnMultPools; //number of ME pools (multiplicity)
Int_t fnzVtxPools; //number of ME pools (z vertex)
Int_t fFirstBinNum; //number of first bin for the name of the output plots
Int_t fNumSelD; //number of selection for D meson (0=default selection; 1,2,3,... = alternate selections)
Int_t fNumSelTr; //number of selection for assoc tracks (0=default selection; 1,2,3,... = alternate selections)
Int_t fDebug;
Int_t fMinD; //start of loop on D mesons
Int_t fMaxD; //end of loop on D mesons
Int_t fMaxTracks; //maximum number of tracks (of the tree, i.e. integrated over everything) to be used in ME correlations
Double_t fMinCent; //minimum centrality
Double_t fMaxCent; //maximum centrality
std::vector<Double_t> fPtBinsDLow; //lower edges of D-meson pT bins
std::vector<Double_t> fPtBinsDUp; //upper edges of D-meson pT bins
std::vector<Double_t> fPtBinsTrLow;//lower edges of assoc. track pT bins
std::vector<Double_t> fPtBinsTrUp; //upper edges of assoc. track pT bins
std::vector<Double_t> fMassSignL; //lower mass edge of signal region
std::vector<Double_t> fMassSignR; //lower mass edge of signal region
std::vector<Double_t> fMassSB1L; //lower mass edge of signal region
std::vector<Double_t> fMassSB1R; //lower mass edge of signal region
std::vector<Double_t> fMassSB2L; //lower mass edge of signal region
std::vector<Double_t> fMassSB2R; //lower mass edge of signal region
std::vector<Double_t> fMultBins; //bin edges for ME pools (multiplicity)
std::vector<Double_t> fzVtxBins; //bin edges for ME pools (z vertex)
std::vector<Double_t> fPrdWeights; //period weights (if different number of tracks is used, in ME analysis)
TH3F* fMapEffTr;
TH2F* fMapEffD;
DMesonSpecies fDmesonSpecies;
AnalysisType fAnType;
TString fDmesonLabel;
TString fDirName;
TString fNameTreeTr;
TString fNameTreeD;
TString fNameMapTr;
TString fNameMapD;
TString fOutputFileName;
TString fNameCutObj;
Bool_t fUseEff; //flag to use D-meson and track efficiency
Bool_t fMake2DPlots; //flag to produce 2D plots for sign.region and SB
Bool_t fWeightPeriods; //flag to weight periods in ME analysis with max number of tracks used
Bool_t fRemoveSoftPiInME; //flag to remove soft pions in ME analysis for D0 meson (SE rejection is done in the task)
ClassDef(AliHFOfflineCorrelator,2); // class for plotting HF correlations
};
#endif
| 41.350711 | 177 | 0.683668 | [
"vector"
] |
45dcd3c61acf17b9bfe150dbd3e76c5766564826 | 5,422 | h | C | include/OTL/Core/UnpoweredFlyby.h | Jmbryan/OTL | 7ffb7fa77e55a2eb7373e41fa345c90d344a9c44 | [
"Zlib",
"MIT"
] | 7 | 2016-06-05T23:25:41.000Z | 2020-01-24T07:46:31.000Z | include/OTL/Core/UnpoweredFlyby.h | Jmbryan/OTL | 7ffb7fa77e55a2eb7373e41fa345c90d344a9c44 | [
"Zlib",
"MIT"
] | null | null | null | include/OTL/Core/UnpoweredFlyby.h | Jmbryan/OTL | 7ffb7fa77e55a2eb7373e41fa345c90d344a9c44 | [
"Zlib",
"MIT"
] | null | null | null | ////////////////////////////////////////////////////////////
//
// OTL - Orbital Trajectory Library
// Copyright (C) 2013-2018 Jason Bryan (Jmbryan10@gmail.com)
//
// This software is provided 'as-is', without any express or implied warranty.
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it freely,
// subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented;
// you must not claim that you wrote the original software.
// If you use this software in a product, an acknowledgment
// in the product documentation would be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such,
// and must not be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source distribution.
//
////////////////////////////////////////////////////////////
#pragma once
#include <OTL/Core/Flyby.h>
namespace otl
{
namespace keplerian
{
class OTL_CORE_API UnpoweredFlyby : public IFlybyAlgorithm
{
public:
////////////////////////////////////////////////////////////
/// \brief Evaluate the flyby maneuver
///
/// Calculates the absolute velocity after performing an
/// unpowered flyby (gravity assist). The altitude and
/// BPlaneAngle define the shape and orientation of the flyby
/// hyperbola respectively.
///
/// \param approachVelocity Absolute cartesian velocity before the flyby
/// \param orbitalBody OrbitalBody to flyby
/// \param altitude Minimum altitude of the flyby hyperbola
/// \param BPlaneAngle Orientation of the flyby hyperbola
/// \param [out] departureVelocity Absolute cartesian velocity after the flyby
///
////////////////////////////////////////////////////////////
virtual void Evaluate(const Vector3d& approachVelocity,
const OrbitalBody& orbitalBody,
double altitude,
double BPlaneAngle,
Vector3d& departureVelocity) override;
protected:
Vector3d m_VInfinityIn; ///< Temporary Vector3d for storing the relative approach velocity
Vector3d m_VInfinityOut; ///< Temporary Vector3d for storing the relative departure velocity
Vector3d m_B1; ///< Temporary Vector3d for defining the B-plane coordinate system
Vector3d m_B2; ///< Temporary Vector3d for defining the B-plane coordinate system
Vector3d m_B3; ///< Temporary Vector3d for defining the B-plane coordinate system
};
} // namespace keplerian
} // namespace otl
////////////////////////////////////////////////////////////
/// \class otl::keplerian::UnpoweredFlyby
/// \ingroup keplerian
///
/// Models the keplerian dynamics of an unpowered flyby.
///
/// Flybys (also refered to as gravity assist maneuvers)
/// work by exchanging momentum between a spacecraft and
/// an orbital body. A passing spacecraft may gain or lose
/// momentum simply by altering the direction in which
/// it passes by the orbital body. Stealing momentum from
/// the orbital body is effectively an orbit raising maneuver
/// (extends the apoapsis) whereas giving momentum to
/// the orbital body is effectively an orbit lowering
/// maneuver (shortens the periapsis).
///
/// An unpowered flyby differs from a powered flyby in
/// which it assumes that there is no net change in
/// relative velocity before and after passing by the
/// orbital body (i.e. no thrusting).
///
/// There are many ways to define the orientation of the flyby
/// hyperbola in 3D space. This implementation is based on
/// the method developed by Dario Izzo which uses the turn angle
/// along with the B-Plane inclination angle. The B-Plane
/// inclination angle is the angle of the hyperbolic plane
/// relative to the "B" reference frame which is defined as:
///
/// \f$ \hat{B_i} = \frac{V_\inf^-}{||V_\inf^-||} \f$\n
/// \f$ B_j = \hat{B_i} \times \frac{V_{planet}}{||V_{planet}||} \f$\n
/// \f$ \hat{B_j} = \frac{B_j}{||B_j||} \f$\n
/// \f$ B_k = \hat{B_i} \times \hat{B_j} \f$\n
/// \f$ \hat{B_k} = \frac{B_k}{||B_k||} \f$
///
/// Usage example:
/// \code
/// using otl;
/// using otl::keplerian;
///
/// IFlybyAlgorithm* flyby = new UnpoweredFlyby();
///
/// // Setup inputs
/// Vector3d approachVelocity = Vector3d(-1.0, 2.0, 3.0); // Absolute velocity before flyby (km/s)
/// Planet flybyPlanet("Venus"); // Venus flyby
/// double flybyAltitude = 500.0; // Periapsis of flyby hyperbola (m)
/// double BPlaneAngle = MATH_PI; // Orientation of flyby hyperbola
///
/// // Setup output
/// Vector3d departureVelocity; // Absolute velocity after flyby (km/s)
///
/// flyby->Evaluate(approachVelocity,
/// flybyPlanet,
/// flybyAltitude,
/// BPlaneAngle,
/// departureVelocity);
///
/// OTL_SAFE_DELETE(flyby);
/// \endcode
///
/// \reference D. Izzo. Advances in global optimisation for space trajectory design.
/// Proceedings of 25th International Symposium on Space Technology and Science, 2006.
///
//////////////////////////////////////////////////////////// | 41.075758 | 101 | 0.629473 | [
"shape",
"3d"
] |
45dd6e09db5f8b1a4fce3cb7c89929e741311bc5 | 16,677 | h | C | TPMCmd/tpm/include/prototypes/CryptHash_fp.h | vbendeb/ms-tpm-20-ref | fe5292ee9733b32b0215876d47e822e50654428b | [
"BSD-2-Clause"
] | null | null | null | TPMCmd/tpm/include/prototypes/CryptHash_fp.h | vbendeb/ms-tpm-20-ref | fe5292ee9733b32b0215876d47e822e50654428b | [
"BSD-2-Clause"
] | null | null | null | TPMCmd/tpm/include/prototypes/CryptHash_fp.h | vbendeb/ms-tpm-20-ref | fe5292ee9733b32b0215876d47e822e50654428b | [
"BSD-2-Clause"
] | null | null | null | /* Microsoft Reference Implementation for TPM 2.0
*
* The copyright in this software is being made available under the BSD License,
* included below. This software may be subject to other third party and
* contributor rights, including patent rights, and no such rights are granted
* under this license.
*
* Copyright (c) Microsoft Corporation
*
* All rights reserved.
*
* BSD License
*
* 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.
*
* 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.
*/
/*(Auto-generated)
* Created by TpmPrototypes; Version 3.0 July 18, 2017
* Date: Aug 30, 2019 Time: 02:11:54PM
*/
#ifndef _CRYPT_HASH_FP_H_
#define _CRYPT_HASH_FP_H_
//*** CryptHashInit()
// This function is called by _TPM_Init do perform the initialization operations for
// the library.
BOOL
CryptHashInit(
void
);
//*** CryptHashStartup()
// This function is called by TPM2_Startup(). It checks that the size of the
// HashDefArray is consistent with the HASH_COUNT.
BOOL
CryptHashStartup(
void
);
//*** CryptGetHashDef()
// This function accesses the hash descriptor associated with a hash a
// algorithm. The function returns a pointer to a 'null' descriptor if hashAlg is
// TPM_ALG_NULL or not a defined algorithm.
PHASH_DEF
CryptGetHashDef(
TPM_ALG_ID hashAlg
);
//*** CryptHashIsValidAlg()
// This function tests to see if an algorithm ID is a valid hash algorithm. If
// flag is true, then TPM_ALG_NULL is a valid hash.
// Return Type: BOOL
// TRUE(1) hashAlg is a valid, implemented hash on this TPM
// FALSE(0) hashAlg is not valid for this TPM
BOOL
CryptHashIsValidAlg(
TPM_ALG_ID hashAlg, // IN: the algorithm to check
BOOL flag // IN: TRUE if TPM_ALG_NULL is to be treated
// as a valid hash
);
//*** CryptHashGetAlgByIndex()
// This function is used to iterate through the hashes. TPM_ALG_NULL
// is returned for all indexes that are not valid hashes.
// If the TPM implements 3 hashes, then an 'index' value of 0 will
// return the first implemented hash and an 'index' of 2 will return the
// last. All other index values will return TPM_ALG_NULL.
//
// Return Type: TPM_ALG_ID
// TPM_ALG_xxx a hash algorithm
// TPM_ALG_NULL this can be used as a stop value
LIB_EXPORT TPM_ALG_ID
CryptHashGetAlgByIndex(
UINT32 index // IN: the index
);
//*** CryptHashGetDigestSize()
// Returns the size of the digest produced by the hash. If 'hashAlg' is not a hash
// algorithm, the TPM will FAIL.
// Return Type: UINT16
// 0 TPM_ALG_NULL
// > 0 the digest size
//
LIB_EXPORT UINT16
CryptHashGetDigestSize(
TPM_ALG_ID hashAlg // IN: hash algorithm to look up
);
//*** CryptHashGetBlockSize()
// Returns the size of the block used by the hash. If 'hashAlg' is not a hash
// algorithm, the TPM will FAIL.
// Return Type: UINT16
// 0 TPM_ALG_NULL
// > 0 the digest size
//
LIB_EXPORT UINT16
CryptHashGetBlockSize(
TPM_ALG_ID hashAlg // IN: hash algorithm to look up
);
//*** CryptHashGetOid()
// This function returns a pointer to DER=encoded OID for a hash algorithm. All OIDs
// are full OID values including the Tag (0x06) and length byte.
LIB_EXPORT const BYTE *
CryptHashGetOid(
TPM_ALG_ID hashAlg
);
//*** CryptHashGetContextAlg()
// This function returns the hash algorithm associated with a hash context.
TPM_ALG_ID
CryptHashGetContextAlg(
PHASH_STATE state // IN: the context to check
);
//*** CryptHashCopyState
// This function is used to clone a HASH_STATE.
LIB_EXPORT void
CryptHashCopyState(
HASH_STATE *out, // OUT: destination of the state
const HASH_STATE *in // IN: source of the state
);
//*** CryptHashExportState()
// This function is used to export a hash or HMAC hash state. This function
// would be called when preparing to context save a sequence object.
void
CryptHashExportState(
PCHASH_STATE internalFmt, // IN: the hash state formatted for use by
// library
PEXPORT_HASH_STATE externalFmt // OUT: the exported hash state
);
//*** CryptHashImportState()
// This function is used to import the hash state. This function
// would be called to import a hash state when the context of a sequence object
// was being loaded.
void
CryptHashImportState(
PHASH_STATE internalFmt, // OUT: the hash state formatted for use by
// the library
PCEXPORT_HASH_STATE externalFmt // IN: the exported hash state
);
//*** CryptHashStart()
// Functions starts a hash stack
// Start a hash stack and returns the digest size. As a side effect, the
// value of 'stateSize' in hashState is updated to indicate the number of bytes
// of state that were saved. This function calls GetHashServer() and that function
// will put the TPM into failure mode if the hash algorithm is not supported.
//
// This function does not use the sequence parameter. If it is necessary to import
// or export context, this will start the sequence in a local state
// and export the state to the input buffer. Will need to add a flag to the state
// structure to indicate that it needs to be imported before it can be used.
// (BLEH).
// Return Type: UINT16
// 0 hash is TPM_ALG_NULL
// >0 digest size
LIB_EXPORT UINT16
CryptHashStart(
PHASH_STATE hashState, // OUT: the running hash state
TPM_ALG_ID hashAlg // IN: hash algorithm
);
//*** CryptDigestUpdate()
// Add data to a hash or HMAC, SMAC stack.
//
void
CryptDigestUpdate(
PHASH_STATE hashState, // IN: the hash context information
UINT32 dataSize, // IN: the size of data to be added
const BYTE *data // IN: data to be hashed
);
//*** CryptHashEnd()
// Complete a hash or HMAC computation. This function will place the smaller of
// 'digestSize' or the size of the digest in 'dOut'. The number of bytes in the
// placed in the buffer is returned. If there is a failure, the returned value
// is <= 0.
// Return Type: UINT16
// 0 no data returned
// > 0 the number of bytes in the digest or dOutSize, whichever is smaller
LIB_EXPORT UINT16
CryptHashEnd(
PHASH_STATE hashState, // IN: the state of hash stack
UINT32 dOutSize, // IN: size of digest buffer
BYTE *dOut // OUT: hash digest
);
//*** CryptHashBlock()
// Start a hash, hash a single block, update 'digest' and return the size of
// the results.
//
// The 'digestSize' parameter can be smaller than the digest. If so, only the more
// significant bytes are returned.
// Return Type: UINT16
// >= 0 number of bytes placed in 'dOut'
LIB_EXPORT UINT16
CryptHashBlock(
TPM_ALG_ID hashAlg, // IN: The hash algorithm
UINT32 dataSize, // IN: size of buffer to hash
const BYTE *data, // IN: the buffer to hash
UINT32 dOutSize, // IN: size of the digest buffer
BYTE *dOut // OUT: digest buffer
);
//*** CryptDigestUpdate2B()
// This function updates a digest (hash or HMAC) with a TPM2B.
//
// This function can be used for both HMAC and hash functions so the
// 'digestState' is void so that either state type can be passed.
LIB_EXPORT void
CryptDigestUpdate2B(
PHASH_STATE state, // IN: the digest state
const TPM2B *bIn // IN: 2B containing the data
);
//*** CryptHashEnd2B()
// This function is the same as CryptCompleteHash() but the digest is
// placed in a TPM2B. This is the most common use and this is provided
// for specification clarity. 'digest.size' should be set to indicate the number of
// bytes to place in the buffer
// Return Type: UINT16
// >=0 the number of bytes placed in 'digest.buffer'
LIB_EXPORT UINT16
CryptHashEnd2B(
PHASH_STATE state, // IN: the hash state
P2B digest // IN: the size of the buffer Out: requested
// number of bytes
);
//*** CryptDigestUpdateInt()
// This function is used to include an integer value to a hash stack. The function
// marshals the integer into its canonical form before calling CryptDigestUpdate().
LIB_EXPORT void
CryptDigestUpdateInt(
void *state, // IN: the state of hash stack
UINT32 intSize, // IN: the size of 'intValue' in bytes
UINT64 intValue // IN: integer value to be hashed
);
//*** CryptHmacStart()
// This function is used to start an HMAC using a temp
// hash context. The function does the initialization
// of the hash with the HMAC key XOR iPad and updates the
// HMAC key XOR oPad.
//
// The function returns the number of bytes in a digest produced by 'hashAlg'.
// Return Type: UINT16
// >= 0 number of bytes in digest produced by 'hashAlg' (may be zero)
//
LIB_EXPORT UINT16
CryptHmacStart(
PHMAC_STATE state, // IN/OUT: the state buffer
TPM_ALG_ID hashAlg, // IN: the algorithm to use
UINT16 keySize, // IN: the size of the HMAC key
const BYTE *key // IN: the HMAC key
);
//*** CryptHmacEnd()
// This function is called to complete an HMAC. It will finish the current
// digest, and start a new digest. It will then add the oPadKey and the
// completed digest and return the results in dOut. It will not return more
// than dOutSize bytes.
// Return Type: UINT16
// >= 0 number of bytes in 'dOut' (may be zero)
LIB_EXPORT UINT16
CryptHmacEnd(
PHMAC_STATE state, // IN: the hash state buffer
UINT32 dOutSize, // IN: size of digest buffer
BYTE *dOut // OUT: hash digest
);
//*** CryptHmacStart2B()
// This function starts an HMAC and returns the size of the digest
// that will be produced.
//
// This function is provided to support the most common use of starting an HMAC
// with a TPM2B key.
//
// The caller must provide a block of memory in which the hash sequence state
// is kept. The caller should not alter the contents of this buffer until the
// hash sequence is completed or abandoned.
//
// Return Type: UINT16
// > 0 the digest size of the algorithm
// = 0 the hashAlg was TPM_ALG_NULL
LIB_EXPORT UINT16
CryptHmacStart2B(
PHMAC_STATE hmacState, // OUT: the state of HMAC stack. It will be used
// in HMAC update and completion
TPMI_ALG_HASH hashAlg, // IN: hash algorithm
P2B key // IN: HMAC key
);
//*** CryptHmacEnd2B()
// This function is the same as CryptHmacEnd() but the HMAC result
// is returned in a TPM2B which is the most common use.
// Return Type: UINT16
// >=0 the number of bytes placed in 'digest'
LIB_EXPORT UINT16
CryptHmacEnd2B(
PHMAC_STATE hmacState, // IN: the state of HMAC stack
P2B digest // OUT: HMAC
);
//** Mask and Key Generation Functions
//*** CryptMGF1()
// This function performs MGF1 using the selected hash. MGF1 is
// T(n) = T(n-1) || H(seed || counter).
// This function returns the length of the mask produced which
// could be zero if the digest algorithm is not supported
// Return Type: UINT16
// 0 hash algorithm was TPM_ALG_NULL
// > 0 should be the same as 'mSize'
LIB_EXPORT UINT16
CryptMGF1(
UINT32 mSize, // IN: length of the mask to be produced
BYTE *mask, // OUT: buffer to receive the mask
TPM_ALG_ID hashAlg, // IN: hash to use
UINT32 seedSize, // IN: size of the seed
BYTE *seed // IN: seed size
);
//*** CryptKDFa()
// This function performs the key generation according to Part 1 of the
// TPM specification.
//
// This function returns the number of bytes generated which may be zero.
//
// The 'key' and 'keyStream' pointers are not allowed to be NULL. The other
// pointer values may be NULL. The value of 'sizeInBits' must be no larger
// than (2^18)-1 = 256K bits (32385 bytes).
//
// The 'once' parameter is set to allow incremental generation of a large
// value. If this flag is TRUE, 'sizeInBits' will be used in the HMAC computation
// but only one iteration of the KDF is performed. This would be used for
// XOR obfuscation so that the mask value can be generated in digest-sized
// chunks rather than having to be generated all at once in an arbitrarily
// large buffer and then XORed into the result. If 'once' is TRUE, then
// 'sizeInBits' must be a multiple of 8.
//
// Any error in the processing of this command is considered fatal.
// Return Type: UINT16
// 0 hash algorithm is not supported or is TPM_ALG_NULL
// > 0 the number of bytes in the 'keyStream' buffer
LIB_EXPORT UINT16
CryptKDFa(
TPM_ALG_ID hashAlg, // IN: hash algorithm used in HMAC
const TPM2B *key, // IN: HMAC key
const TPM2B *label, // IN: a label for the KDF
const TPM2B *contextU, // IN: context U
const TPM2B *contextV, // IN: context V
UINT32 sizeInBits, // IN: size of generated key in bits
BYTE *keyStream, // OUT: key buffer
UINT32 *counterInOut, // IN/OUT: caller may provide the iteration
// counter for incremental operations to
// avoid large intermediate buffers.
UINT16 blocks // IN: If non-zero, this is the maximum number
// of blocks to be returned, regardless
// of sizeInBits
);
//*** CryptKDFe()
// This function implements KDFe() as defined in TPM specification part 1.
//
// This function returns the number of bytes generated which may be zero.
//
// The 'Z' and 'keyStream' pointers are not allowed to be NULL. The other
// pointer values may be NULL. The value of 'sizeInBits' must be no larger
// than (2^18)-1 = 256K bits (32385 bytes).
// Any error in the processing of this command is considered fatal.
// Return Type: UINT16
// 0 hash algorithm is not supported or is TPM_ALG_NULL
// > 0 the number of bytes in the 'keyStream' buffer
//
LIB_EXPORT UINT16
CryptKDFe(
TPM_ALG_ID hashAlg, // IN: hash algorithm used in HMAC
TPM2B *Z, // IN: Z
const TPM2B *label, // IN: a label value for the KDF
TPM2B *partyUInfo, // IN: PartyUInfo
TPM2B *partyVInfo, // IN: PartyVInfo
UINT32 sizeInBits, // IN: size of generated key in bits
BYTE *keyStream // OUT: key buffer
);
#endif // _CRYPT_HASH_FP_H_
| 40.775061 | 85 | 0.638784 | [
"object"
] |
45e202575d9f366864389189668bebb8036c0c80 | 17,469 | c | C | zircon/third_party/lib/acpica_r20190108/source/components/utilities/utalloc.c | zhangpf/fuchsia-rs | 903568f28ddf45f09157ead36d61b50322c9cf49 | [
"BSD-3-Clause"
] | 15 | 2019-11-16T04:33:32.000Z | 2022-01-09T23:30:06.000Z | sys/contrib/dev/acpica/source/components/utilities/utalloc.c | Giovan/DragonFlyBSD | e337742ba7a83bab13c251161f33f82ed7fc0e26 | [
"BSD-3-Clause"
] | 16 | 2020-09-04T19:01:11.000Z | 2021-05-28T03:23:09.000Z | zircon/third_party/lib/acpica_r20190108/source/components/utilities/utalloc.c | ZVNexus/fuchsia | c5610ad15208208c98693618a79c705af935270c | [
"BSD-3-Clause"
] | 2 | 2020-10-18T16:58:24.000Z | 2022-01-07T14:26:42.000Z | /******************************************************************************
*
* Module Name: utalloc - local memory allocation routines
*
*****************************************************************************/
/******************************************************************************
*
* 1. Copyright Notice
*
* Some or all of this work - Copyright (c) 1999 - 2019, Intel Corp.
* All rights reserved.
*
* 2. License
*
* 2.1. This is your license from Intel Corp. under its intellectual property
* rights. You may have additional license terms from the party that provided
* you this software, covering your right to use that party's intellectual
* property rights.
*
* 2.2. Intel grants, free of charge, to any person ("Licensee") obtaining a
* copy of the source code appearing in this file ("Covered Code") an
* irrevocable, perpetual, worldwide license under Intel's copyrights in the
* base code distributed originally by Intel ("Original Intel Code") to copy,
* make derivatives, distribute, use and display any portion of the Covered
* Code in any form, with the right to sublicense such rights; and
*
* 2.3. Intel grants Licensee a non-exclusive and non-transferable patent
* license (with the right to sublicense), under only those claims of Intel
* patents that are infringed by the Original Intel Code, to make, use, sell,
* offer to sell, and import the Covered Code and derivative works thereof
* solely to the minimum extent necessary to exercise the above copyright
* license, and in no event shall the patent license extend to any additions
* to or modifications of the Original Intel Code. No other license or right
* is granted directly or by implication, estoppel or otherwise;
*
* The above copyright and patent license is granted only if the following
* conditions are met:
*
* 3. Conditions
*
* 3.1. Redistribution of Source with Rights to Further Distribute Source.
* Redistribution of source code of any substantial portion of the Covered
* Code or modification with rights to further distribute source must include
* the above Copyright Notice, the above License, this list of Conditions,
* and the following Disclaimer and Export Compliance provision. In addition,
* Licensee must cause all Covered Code to which Licensee contributes to
* contain a file documenting the changes Licensee made to create that Covered
* Code and the date of any change. Licensee must include in that file the
* documentation of any changes made by any predecessor Licensee. Licensee
* must include a prominent statement that the modification is derived,
* directly or indirectly, from Original Intel Code.
*
* 3.2. Redistribution of Source with no Rights to Further Distribute Source.
* Redistribution of source code of any substantial portion of the Covered
* Code or modification without rights to further distribute source must
* include the following Disclaimer and Export Compliance provision in the
* documentation and/or other materials provided with distribution. In
* addition, Licensee may not authorize further sublicense of source of any
* portion of the Covered Code, and must include terms to the effect that the
* license from Licensee to its licensee is limited to the intellectual
* property embodied in the software Licensee provides to its licensee, and
* not to intellectual property embodied in modifications its licensee may
* make.
*
* 3.3. Redistribution of Executable. Redistribution in executable form of any
* substantial portion of the Covered Code or modification must reproduce the
* above Copyright Notice, and the following Disclaimer and Export Compliance
* provision in the documentation and/or other materials provided with the
* distribution.
*
* 3.4. Intel retains all right, title, and interest in and to the Original
* Intel Code.
*
* 3.5. Neither the name Intel nor any other trademark owned or controlled by
* Intel shall be used in advertising or otherwise to promote the sale, use or
* other dealings in products derived from or relating to the Covered Code
* without prior written authorization from Intel.
*
* 4. Disclaimer and Export Compliance
*
* 4.1. INTEL MAKES NO WARRANTY OF ANY KIND REGARDING ANY SOFTWARE PROVIDED
* HERE. ANY SOFTWARE ORIGINATING FROM INTEL OR DERIVED FROM INTEL SOFTWARE
* IS PROVIDED "AS IS," AND INTEL WILL NOT PROVIDE ANY SUPPORT, ASSISTANCE,
* INSTALLATION, TRAINING OR OTHER SERVICES. INTEL WILL NOT PROVIDE ANY
* UPDATES, ENHANCEMENTS OR EXTENSIONS. INTEL SPECIFICALLY DISCLAIMS ANY
* IMPLIED WARRANTIES OF MERCHANTABILITY, NONINFRINGEMENT AND FITNESS FOR A
* PARTICULAR PURPOSE.
*
* 4.2. IN NO EVENT SHALL INTEL HAVE ANY LIABILITY TO LICENSEE, ITS LICENSEES
* OR ANY OTHER THIRD PARTY, FOR ANY LOST PROFITS, LOST DATA, LOSS OF USE OR
* COSTS OF PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES, OR FOR ANY INDIRECT,
* SPECIAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THIS AGREEMENT, UNDER ANY
* CAUSE OF ACTION OR THEORY OF LIABILITY, AND IRRESPECTIVE OF WHETHER INTEL
* HAS ADVANCE NOTICE OF THE POSSIBILITY OF SUCH DAMAGES. THESE LIMITATIONS
* SHALL APPLY NOTWITHSTANDING THE FAILURE OF THE ESSENTIAL PURPOSE OF ANY
* LIMITED REMEDY.
*
* 4.3. Licensee shall not export, either directly or indirectly, any of this
* software or system incorporating such software without first obtaining any
* required license or other approval from the U. S. Department of Commerce or
* any other agency or department of the United States Government. In the
* event Licensee exports any such software from the United States or
* re-exports any such software from a foreign destination, Licensee shall
* ensure that the distribution and export/re-export of the software is in
* compliance with all laws, regulations, orders, or other restrictions of the
* U.S. Export Administration Regulations. Licensee agrees that neither it nor
* any of its subsidiaries will export/re-export any technical data, process,
* software, or service, directly or indirectly, to any country for which the
* United States government or any agency thereof requires an export license,
* other governmental approval, or letter of assurance, without first obtaining
* such license, approval or letter.
*
*****************************************************************************
*
* Alternatively, you may choose to be licensed under the terms of the
* following license:
*
* 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,
* without modification.
* 2. Redistributions in binary form must reproduce at minimum a disclaimer
* substantially similar to the "NO WARRANTY" disclaimer below
* ("Disclaimer") and any redistribution must be conditioned upon
* including a substantially similar Disclaimer requirement for further
* binary redistribution.
* 3. Neither the names of the above-listed copyright holders nor the names
* of any 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.
*
* Alternatively, you may choose to be licensed under the terms of the
* GNU General Public License ("GPL") version 2 as published by the Free
* Software Foundation.
*
*****************************************************************************/
#include "acpi.h"
#include "accommon.h"
#include "acdebug.h"
#define _COMPONENT ACPI_UTILITIES
ACPI_MODULE_NAME ("utalloc")
#if !defined (USE_NATIVE_ALLOCATE_ZEROED)
/*******************************************************************************
*
* FUNCTION: AcpiOsAllocateZeroed
*
* PARAMETERS: Size - Size of the allocation
*
* RETURN: Address of the allocated memory on success, NULL on failure.
*
* DESCRIPTION: Subsystem equivalent of calloc. Allocate and zero memory.
* This is the default implementation. Can be overridden via the
* USE_NATIVE_ALLOCATE_ZEROED flag.
*
******************************************************************************/
void *
AcpiOsAllocateZeroed (
ACPI_SIZE Size)
{
void *Allocation;
ACPI_FUNCTION_ENTRY ();
Allocation = AcpiOsAllocate (Size);
if (Allocation)
{
/* Clear the memory block */
memset (Allocation, 0, Size);
}
return (Allocation);
}
#endif /* !USE_NATIVE_ALLOCATE_ZEROED */
/*******************************************************************************
*
* FUNCTION: AcpiUtCreateCaches
*
* PARAMETERS: None
*
* RETURN: Status
*
* DESCRIPTION: Create all local caches
*
******************************************************************************/
ACPI_STATUS
AcpiUtCreateCaches (
void)
{
ACPI_STATUS Status;
/* Object Caches, for frequently used objects */
Status = AcpiOsCreateCache ("Acpi-Namespace", sizeof (ACPI_NAMESPACE_NODE),
ACPI_MAX_NAMESPACE_CACHE_DEPTH, &AcpiGbl_NamespaceCache);
if (ACPI_FAILURE (Status))
{
return (Status);
}
Status = AcpiOsCreateCache ("Acpi-State", sizeof (ACPI_GENERIC_STATE),
ACPI_MAX_STATE_CACHE_DEPTH, &AcpiGbl_StateCache);
if (ACPI_FAILURE (Status))
{
return (Status);
}
Status = AcpiOsCreateCache ("Acpi-Parse", sizeof (ACPI_PARSE_OBJ_COMMON),
ACPI_MAX_PARSE_CACHE_DEPTH, &AcpiGbl_PsNodeCache);
if (ACPI_FAILURE (Status))
{
return (Status);
}
Status = AcpiOsCreateCache ("Acpi-ParseExt", sizeof (ACPI_PARSE_OBJ_NAMED),
ACPI_MAX_EXTPARSE_CACHE_DEPTH, &AcpiGbl_PsNodeExtCache);
if (ACPI_FAILURE (Status))
{
return (Status);
}
Status = AcpiOsCreateCache ("Acpi-Operand", sizeof (ACPI_OPERAND_OBJECT),
ACPI_MAX_OBJECT_CACHE_DEPTH, &AcpiGbl_OperandCache);
if (ACPI_FAILURE (Status))
{
return (Status);
}
#ifdef ACPI_ASL_COMPILER
/*
* For use with the ASL-/ASL+ option. This cache keeps track of regular
* 0xA9 0x01 comments.
*/
Status = AcpiOsCreateCache ("Acpi-Comment", sizeof (ACPI_COMMENT_NODE),
ACPI_MAX_COMMENT_CACHE_DEPTH, &AcpiGbl_RegCommentCache);
if (ACPI_FAILURE (Status))
{
return (Status);
}
/*
* This cache keeps track of the starting addresses of where the comments
* lie. This helps prevent duplication of comments.
*/
Status = AcpiOsCreateCache ("Acpi-Comment-Addr", sizeof (ACPI_COMMENT_ADDR_NODE),
ACPI_MAX_COMMENT_CACHE_DEPTH, &AcpiGbl_CommentAddrCache);
if (ACPI_FAILURE (Status))
{
return (Status);
}
/*
* This cache will be used for nodes that represent files.
*/
Status = AcpiOsCreateCache ("Acpi-File", sizeof (ACPI_FILE_NODE),
ACPI_MAX_COMMENT_CACHE_DEPTH, &AcpiGbl_FileCache);
if (ACPI_FAILURE (Status))
{
return (Status);
}
#endif
#ifdef ACPI_DBG_TRACK_ALLOCATIONS
/* Memory allocation lists */
Status = AcpiUtCreateList ("Acpi-Global", 0,
&AcpiGbl_GlobalList);
if (ACPI_FAILURE (Status))
{
return (Status);
}
Status = AcpiUtCreateList ("Acpi-Namespace", sizeof (ACPI_NAMESPACE_NODE),
&AcpiGbl_NsNodeList);
if (ACPI_FAILURE (Status))
{
return (Status);
}
#endif
return (AE_OK);
}
/*******************************************************************************
*
* FUNCTION: AcpiUtDeleteCaches
*
* PARAMETERS: None
*
* RETURN: Status
*
* DESCRIPTION: Purge and delete all local caches
*
******************************************************************************/
ACPI_STATUS
AcpiUtDeleteCaches (
void)
{
#ifdef ACPI_DBG_TRACK_ALLOCATIONS
char Buffer[7];
if (AcpiGbl_DisplayFinalMemStats)
{
strcpy (Buffer, "MEMORY");
(void) AcpiDbDisplayStatistics (Buffer);
}
#endif
(void) AcpiOsDeleteCache (AcpiGbl_NamespaceCache);
AcpiGbl_NamespaceCache = NULL;
(void) AcpiOsDeleteCache (AcpiGbl_StateCache);
AcpiGbl_StateCache = NULL;
(void) AcpiOsDeleteCache (AcpiGbl_OperandCache);
AcpiGbl_OperandCache = NULL;
(void) AcpiOsDeleteCache (AcpiGbl_PsNodeCache);
AcpiGbl_PsNodeCache = NULL;
(void) AcpiOsDeleteCache (AcpiGbl_PsNodeExtCache);
AcpiGbl_PsNodeExtCache = NULL;
#ifdef ACPI_ASL_COMPILER
(void) AcpiOsDeleteCache (AcpiGbl_RegCommentCache);
AcpiGbl_RegCommentCache = NULL;
(void) AcpiOsDeleteCache (AcpiGbl_CommentAddrCache);
AcpiGbl_CommentAddrCache = NULL;
(void) AcpiOsDeleteCache (AcpiGbl_FileCache);
AcpiGbl_FileCache = NULL;
#endif
#ifdef ACPI_DBG_TRACK_ALLOCATIONS
/* Debug only - display leftover memory allocation, if any */
AcpiUtDumpAllocations (ACPI_UINT32_MAX, NULL);
/* Free memory lists */
AcpiOsFree (AcpiGbl_GlobalList);
AcpiGbl_GlobalList = NULL;
AcpiOsFree (AcpiGbl_NsNodeList);
AcpiGbl_NsNodeList = NULL;
#endif
return (AE_OK);
}
/*******************************************************************************
*
* FUNCTION: AcpiUtValidateBuffer
*
* PARAMETERS: Buffer - Buffer descriptor to be validated
*
* RETURN: Status
*
* DESCRIPTION: Perform parameter validation checks on an ACPI_BUFFER
*
******************************************************************************/
ACPI_STATUS
AcpiUtValidateBuffer (
ACPI_BUFFER *Buffer)
{
/* Obviously, the structure pointer must be valid */
if (!Buffer)
{
return (AE_BAD_PARAMETER);
}
/* Special semantics for the length */
if ((Buffer->Length == ACPI_NO_BUFFER) ||
(Buffer->Length == ACPI_ALLOCATE_BUFFER) ||
(Buffer->Length == ACPI_ALLOCATE_LOCAL_BUFFER))
{
return (AE_OK);
}
/* Length is valid, the buffer pointer must be also */
if (!Buffer->Pointer)
{
return (AE_BAD_PARAMETER);
}
return (AE_OK);
}
/*******************************************************************************
*
* FUNCTION: AcpiUtInitializeBuffer
*
* PARAMETERS: Buffer - Buffer to be validated
* RequiredLength - Length needed
*
* RETURN: Status
*
* DESCRIPTION: Validate that the buffer is of the required length or
* allocate a new buffer. Returned buffer is always zeroed.
*
******************************************************************************/
ACPI_STATUS
AcpiUtInitializeBuffer (
ACPI_BUFFER *Buffer,
ACPI_SIZE RequiredLength)
{
ACPI_SIZE InputBufferLength;
/* Parameter validation */
if (!Buffer || !RequiredLength)
{
return (AE_BAD_PARAMETER);
}
/*
* Buffer->Length is used as both an input and output parameter. Get the
* input actual length and set the output required buffer length.
*/
InputBufferLength = Buffer->Length;
Buffer->Length = RequiredLength;
/*
* The input buffer length contains the actual buffer length, or the type
* of buffer to be allocated by this routine.
*/
switch (InputBufferLength)
{
case ACPI_NO_BUFFER:
/* Return the exception (and the required buffer length) */
return (AE_BUFFER_OVERFLOW);
case ACPI_ALLOCATE_BUFFER:
/*
* Allocate a new buffer. We directectly call AcpiOsAllocate here to
* purposefully bypass the (optionally enabled) internal allocation
* tracking mechanism since we only want to track internal
* allocations. Note: The caller should use AcpiOsFree to free this
* buffer created via ACPI_ALLOCATE_BUFFER.
*/
Buffer->Pointer = AcpiOsAllocate (RequiredLength);
break;
case ACPI_ALLOCATE_LOCAL_BUFFER:
/* Allocate a new buffer with local interface to allow tracking */
Buffer->Pointer = ACPI_ALLOCATE (RequiredLength);
break;
default:
/* Existing buffer: Validate the size of the buffer */
if (InputBufferLength < RequiredLength)
{
return (AE_BUFFER_OVERFLOW);
}
break;
}
/* Validate allocation from above or input buffer pointer */
if (!Buffer->Pointer)
{
return (AE_NO_MEMORY);
}
/* Have a valid buffer, clear it */
memset (Buffer->Pointer, 0, RequiredLength);
return (AE_OK);
}
| 33.723938 | 85 | 0.657164 | [
"object"
] |
45e2b73b764b26250b4c42f1de31b826905e50c9 | 1,016 | h | C | DEM/Low/src/Core/ApplicationState.h | niello/deusexmachina | 2f698054fe82d8b40a0a0e58b86d64ffed0de06c | [
"MIT"
] | 15 | 2019-05-07T11:26:13.000Z | 2022-01-12T18:26:45.000Z | DEM/Low/src/Core/ApplicationState.h | niello/deusexmachina | 2f698054fe82d8b40a0a0e58b86d64ffed0de06c | [
"MIT"
] | 16 | 2021-10-04T17:15:31.000Z | 2022-03-20T09:34:29.000Z | DEM/Low/src/Core/ApplicationState.h | niello/deusexmachina | 2f698054fe82d8b40a0a0e58b86d64ffed0de06c | [
"MIT"
] | 2 | 2019-04-28T23:27:48.000Z | 2019-05-07T11:26:18.000Z | #pragma once
#include <Core/Object.h>
// Application state is a base class for user application logic. Application can
// switch between different states as a regular FSM. State transition has no
// duration, so all timed transition logic must be implemented inside a state.
// This class is not intended to be stateless and can store any data. Therefore
// it stores its host application because some stored objects may be app-specific.
namespace DEM::Core
{
class CApplication;
typedef Ptr<class CApplicationState> PApplicationState;
class CApplicationState : public ::Core::CObject
{
RTTI_CLASS_DECL(DEM::Core::CApplicationState, ::Core::CObject);
protected:
CApplication& App;
public:
CApplicationState(CApplication& Application) : App(Application) {}
virtual void OnEnter(CApplicationState* pFromState) {}
virtual void OnExit(CApplicationState* pToState) {}
virtual CApplicationState* Update(double FrameTime) { return this; }
CApplication& GetApplication() const { return App; }
};
}
| 29.028571 | 82 | 0.768701 | [
"object"
] |
45e3bd7ede343c35d10a578ef6d771cd65827ca2 | 964 | h | C | QingShanProject/QingShanProject/Driver/LeftPage/Controller/DriverDetailController.h | gunmm/QingshanApp | cfbc4cf1d6f8f6fee4969dd5c4badb38c5fc614c | [
"MIT"
] | null | null | null | QingShanProject/QingShanProject/Driver/LeftPage/Controller/DriverDetailController.h | gunmm/QingshanApp | cfbc4cf1d6f8f6fee4969dd5c4badb38c5fc614c | [
"MIT"
] | null | null | null | QingShanProject/QingShanProject/Driver/LeftPage/Controller/DriverDetailController.h | gunmm/QingshanApp | cfbc4cf1d6f8f6fee4969dd5c4badb38c5fc614c | [
"MIT"
] | null | null | null | //
// DriverDetailController.h
// QingShanProject
//
// Created by gunmm on 2018/10/17.
// Copyright © 2018年 gunmm. All rights reserved.
//
#import "BaseTableViewController.h"
#import "UserModel.h"
typedef void(^RefreshDriverBlock)(void);
@interface DriverDetailController : BaseTableViewController
@property (weak, nonatomic) IBOutlet UIImageView *driverImageView;
@property (weak, nonatomic) IBOutlet UILabel *driverNameLabel;
@property (weak, nonatomic) IBOutlet UIButton *driverPhoneBtn;
@property (weak, nonatomic) IBOutlet UITextField *driverIdCardLabel;
@property (weak, nonatomic) IBOutlet UITextField *driverLicenseLabel;
@property (weak, nonatomic) IBOutlet UITextField *driverQualificationLabel;
@property (weak, nonatomic) IBOutlet UITextField *driverScoreLabel;
@property (nonatomic, strong) UserModel *model;
@property (nonatomic, copy) RefreshDriverBlock refreshDriverBlock;
@property (nonatomic, assign) BOOL isAddSmallDriver;
@end
| 27.542857 | 75 | 0.791494 | [
"model"
] |
45e7bf3e6089d9f165fd07e5a850ad82831f1a65 | 27,762 | h | C | applications/MeshingApplication/custom_utilities/mmg_utilities.h | HubertBalcerzak/Kratos | c15689d53f06dabb36dc44c13eeac73d3e183916 | [
"BSD-4-Clause"
] | null | null | null | applications/MeshingApplication/custom_utilities/mmg_utilities.h | HubertBalcerzak/Kratos | c15689d53f06dabb36dc44c13eeac73d3e183916 | [
"BSD-4-Clause"
] | 1 | 2019-10-15T13:11:37.000Z | 2019-10-15T13:11:37.000Z | applications/MeshingApplication/custom_utilities/mmg_utilities.h | Gaoliu19910601/Kratos | 0bac5e132d02061680fc90f1e52d4930b5ed7fa3 | [
"BSD-4-Clause"
] | null | null | null | // KRATOS __ __ _____ ____ _ _ ___ _ _ ____
// | \/ | ____/ ___|| | | |_ _| \ | |/ ___|
// | |\/| | _| \___ \| |_| || || \| | | _
// | | | | |___ ___) | _ || || |\ | |_| |
// |_| |_|_____|____/|_| |_|___|_| \_|\____| APPLICATION
//
// License: BSD License
// license: MeshingApplication/license.txt
//
// Main authors: Vicente Mataix Ferrandiz
//
#if !defined(KRATOS_MMG_UTILITIES)
#define KRATOS_MMG_UTILITIES
// System includes
// External includes
// Project includes
#include "meshing_application.h"
#include "includes/key_hash.h"
#include "includes/model_part.h"
#include "includes/kratos_parameters.h"
#include "utilities/variable_utils.h"
#include "utilities/assign_unique_model_part_collection_tag_utility.h"
#include "processes/fast_transfer_between_model_parts_process.h"
// NOTE: The following contains the license of the MMG library
/* =============================================================================
** Copyright (c) Bx INP/Inria/UBordeaux/UPMC, 2004- .
**
** mmg is free software: you can redistribute it and/or modify it
** under the terms of the GNU Lesser General Public License as published
** by the Free Software Foundation, either version 3 of the License, or
** (at your option) any later version.
**
** mmg 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 Lesser General Public
** License for more details.
**
** You should have received a copy of the GNU Lesser General Public
** License and of the GNU General Public License along with mmg (in
** files COPYING.LESSER and COPYING). If not, see
** <http://www.gnu.org/licenses/>. Please read their terms carefully and
** use this copy of the mmg distribution only if you accept them.
** =============================================================================
*/
namespace Kratos
{
///@name Kratos Globals
///@{
///@}
///@name Type Definitions
///@{
/// Index definition
typedef std::size_t IndexType;
/// Size definition
typedef std::size_t SizeType;
/// Index vector
typedef std::vector<IndexType> IndexVectorType;
///@}
///@name Enum's
///@{
///@}
///@name Functions
///@{
///@}
///@name Kratos Classes
///@{
/**
* @struct MMGMeshInfo
* @ingroup MeshingApplication
* @brief Stores the Mmg mesh information
* @author Vicente Mataix Ferrandiz
*/
template<MMGLibrary TMMGLibrary>
struct MMGMeshInfo
{
// Info stored
SizeType NumberOfNodes;
SizeType NumberOfLines;
SizeType NumberOfTriangles;
SizeType NumberOfQuadrilaterals;
SizeType NumberOfPrism;
SizeType NumberOfTetrahedra;
/**
* @brief It returns the number of the first type of conditions
*/
SizeType NumberFirstTypeConditions() const;
/**
* @brief It returns the number of the second type of conditions
*/
SizeType NumberSecondTypeConditions() const;
/**
* @brief It returns the number of the first type of elements
*/
SizeType NumberFirstTypeElements() const;
/**
* @brief It returns the number of the second type of elements
*/
SizeType NumberSecondTypeElements() const;
};
/**
* @class MmgUtilities
* @ingroup MeshingApplication
* @brief Provides the Kratos interface to the MMG library API
* @author Vicente Mataix Ferrandiz
*/
template<MMGLibrary TMMGLibrary>
class KRATOS_API(MESHING_APPLICATION) MmgUtilities
{
public:
///@name Type Definitions
///@{
/// Pointer definition of MmgUtilities
KRATOS_CLASS_POINTER_DEFINITION(MmgUtilities);
/// Node definition
typedef Node <3> NodeType;
// Geometry definition
typedef Geometry<NodeType> GeometryType;
/// Spatial dimension
static constexpr SizeType Dimension = (TMMGLibrary == MMGLibrary::MMG2D) ? 2 : 3;
/// The type of array considered for the tensor
typedef typename std::conditional<Dimension == 2, array_1d<double, 3>, array_1d<double, 6>>::type TensorArrayType;
/// Double vector
typedef std::vector<double> DoubleVectorType;
/// Double vector map
typedef std::unordered_map<DoubleVectorType, IndexType, KeyHasherRange<DoubleVectorType>, KeyComparorRange<DoubleVectorType> > DoubleVectorMapType;
/// Index vector map
typedef std::unordered_map<IndexVectorType, IndexType, KeyHasherRange<IndexVectorType>, KeyComparorRange<IndexVectorType> > IndexVectorMapType;
/// Colors map
typedef std::unordered_map<IndexType,IndexType> ColorsMapType;
/// Index pair
typedef std::pair<IndexType,IndexType> IndexPairType;
/// Index and string vector pair
typedef std::pair<IndexType, std::vector<std::string>> IndexStringVectorPairType;
/// Definition of the zero tolerance
static constexpr double ZeroTolerance = std::numeric_limits<double>::epsilon();
///@}
///@name Enum's
///@{
///@}
///@name Life Cycle
///@{
///@}
///@name Access
///@{
///@}
///@name Inquiry
///@{
///@}
///@name Input and output
///@{
///@}
///@name Friends
///@{
///@}
///@name Operators
///@{
///@}
///@name Operations
///@{
/**
* @brief This method sets the echo level
* @param[in] EchoLevel Sets the echo level
*/
void SetEchoLevel(const SizeType EchoLevel);
/**
* @brief This method gets the echo level
* @return mEchoLevel Gets the echo level
*/
SizeType GetEchoLevel();
/**
* @brief This method sets the discretization method
* @param[in] Discretization Sets the discretization method
*/
void SetDiscretization(const DiscretizationOption Discretization);
/**
* @brief This method gets the discretization method
* @return mDiscretization Gets the discretization method
*/
DiscretizationOption GetDiscretization();
/**
* @brief This method sets if the regions must be removed
* @param[in] RemoveRegions Sets if the regions must be removed
*/
void SetRemoveRegions(const bool RemoveRegions);
/**
* @brief This method gets if the regions must be removed
* @return mRemoveRegions Gets if the regions must be removed
*/
bool GetRemoveRegions();
/**
* @brief It prints info about the current mesh
* @param[in,out] rMMGMeshInfo The number of nodes, conditions and elements
*/
void PrintAndGetMmgMeshInfo(MMGMeshInfo<TMMGLibrary>& rMMGMeshInfo);
/**
* @brief Returns a vector of ids of spatially repeated nodes
* @param[in,out] rModelPart The model part whose nodes are checked
*/
IndexVectorType FindDuplicateNodeIds(const ModelPart& rModelPart);
/**
* @brief Returns a vector of ids of repeated conditions
* @details For 2D and surface meshes it returns the ids of repeated edges found in the MMG mesh data structure. In 3D it returns ids of triangles.
*/
IndexVectorType CheckFirstTypeConditions();
/**
* @brief Returns a vector of ids of repeated conditions
* @details For 3D meshes it returns the ids of repeated quadrilaterals found in the MMG mesh data structure. Otherwise, it returns an empty vector.
*/
IndexVectorType CheckSecondTypeConditions();
/**
* @brief Returns a vector of ids of repeated elements
* @details For 2D and surface meshes it returns the ids of repeated triangles found in the MMG mesh data structure. In 3D it returns ids of tetrahedra.
*/
IndexVectorType CheckFirstTypeElements();
/**
* @brief Returns a vector of ids of repeated elements
* @details For 3D meshes it returns the ids of repeated prisms found in the MMG mesh data structure. Otherwise, it returns an empty vector.
*/
IndexVectorType CheckSecondTypeElements();
/**
* @brief It blocks certain nodes before remesh the model
* @param[in] iNode The index of the node
*/
void BlockNode(const IndexType iNode);
/**
* @brief It blocks certain conditions before remesh the model
* @param[in] iCondition The index of the condition
*/
void BlockCondition(const IndexType iCondition);
/**
* @brief It blocks certain elements before remesh the model
* @param[in] iElement The index of the element
*/
void BlockElement(const IndexType iElement);
/**
* @brief It creates the new node
* @details Each call to this function increments the internal counter of the MMG mesh data structure, extracts the coordinates of the current vertex and creates the new node with the extracted coordinates.
* @param[in,out] rModelPart The model part which owns the new node
* @param[in] iNode The index of the new node
* @param[out] Ref MMG point reference
* @param[out] IsRequired MMG required entity (0 or 1)
* @return pNode The pointer to the new node created
*/
NodeType::Pointer CreateNode(
ModelPart& rModelPart,
IndexType iNode,
int& Ref,
int& IsRequired
);
/**
* @brief It creates the new condition (first type, depends if the library work in 2D/3D/Surfaces)
* @details Each call to this function increments the internal counter of the MMG mesh data structure and extracts the vertices of the current edge.
* @param[in,out] rModelPart The model part of interest to study
* @param[in,out] rMapPointersRefCondition The pointer to the condition of reference
* @param[in] CondId The id of the new condition
* @param[out] Ref MMG edge reference
* @param[out] IsRequired MMG required entity (0 or 1)
* @param[in] SkipCreation Skips the creation of the new condition
* @return pCondition The pointer to the new condition created
*/
Condition::Pointer CreateFirstTypeCondition(
ModelPart& rModelPart,
std::unordered_map<IndexType,Condition::Pointer>& rMapPointersRefCondition,
const IndexType CondId,
int& Ref,
int& IsRequired,
bool SkipCreation
);
/**
* @brief It creates the new condition (second type, depends if the library work in 2D/3D/Surfaces)
* @param[in,out] rModelPart The model part of interest to study
* @param[in,out] rMapPointersRefCondition The pointer to the condition of reference
* @param[in] CondId The id of the condition
* @param[out] Ref MMG edge reference
* @param[out] IsRequired MMG required entity (0 or 1)
* @return pCondition The pointer to the new condition created
*/
Condition::Pointer CreateSecondTypeCondition(
ModelPart& rModelPart,
std::unordered_map<IndexType,Condition::Pointer>& rMapPointersRefCondition,
const IndexType CondId,
int& Ref,
int& IsRequired,
bool SkipCreation
);
/**
* @brief It creates the new element (first type, depends if the library work in 2D/3D/Surfaces)
* @param[in,out] rModelPart The model part of interest to study
* @param[in,out] rMapPointersRefElement The pointer to the element of reference
* @param[in] ElemId The id of the element
* @param[out] Ref MMG edge reference
* @param[out] IsRequired MMG required entity (0 or 1)
* @return pElement The pointer to the new condition created
*/
Element::Pointer CreateFirstTypeElement(
ModelPart& rModelPart,
std::unordered_map<IndexType,Element::Pointer>& rMapPointersRefElement,
const IndexType ElemId,
int& Ref,
int& IsRequired,
bool SkipCreation
);
/**
* @brief It creates the new element (second type, depends if the library work in 2D/3D/Surfaces)
* @param[in,out] rModelPart The model part of interest to study
* @param[in,out] rMapPointersRefElement The pointer to the element of reference
* @param[in] ElemId The id of the element
* @param[out] Ref MMG edge reference
* @param[out] IsRequired MMG required entity (0 or 1)
* @return pElement The pointer to the new condition created
*/
Element::Pointer CreateSecondTypeElement(
ModelPart& rModelPart,
std::unordered_map<IndexType,Element::Pointer>& rMapPointersRefElement,
const IndexType ElemId,
int& Ref,
int& IsRequired,
bool SkipCreation
);
/**
* @brief Initialisation of mesh and sol structures
* @details Initialisation of mesh and sol structures args of InitMesh:
* -# MMG5_ARG_start we start to give the args of a variadic func
* -# MMG5_ARG_ppMesh next arg will be a pointer over a MMG5_pMesh
* -# &mmgMesh pointer toward your MMG5_pMesh (that store your mesh)
* -# MMG5_ARG_ppMet next arg will be a pointer over a MMG5_pSol storing a metric
* -# &mmgSol pointer toward your MMG5_pSol (that store your metric)
*/
void InitMesh();
/**
* @brief Here the verbosity is set
*/
void InitVerbosity();
/**
* @brief Here the verbosity is set using the API
* @param[in] VerbosityMMG The equivalent verbosity level in the MMG API
*/
void InitVerbosityParameter(const IndexType VerbosityMMG);
/**
* @brief This sets the size of the mesh
* @param[in,out] rMMGMeshInfo The number of nodes, conditions and elements
*/
void SetMeshSize(MMGMeshInfo<TMMGLibrary>& rMMGMeshInfo);
/**
* @brief This sets the size of the solution for the scalar case
* @param[in] NumNodes Number of nodes
*/
void SetSolSizeScalar(const SizeType NumNodes);
/**
* @brief This sets the size of the solution for the vector case
* @param[in] NumNodes Number of nodes
*/
void SetSolSizeVector(const SizeType NumNodes);
/**
* @brief This sets the size of the solution for the tensor case
* @param[in] NumNodes Number of nodes
*/
void SetSolSizeTensor(const SizeType NumNodes);
/**
* @brief This sets the size of the displacement for lagrangian movement
* @param[in] NumNodes Number of nodes
*/
void SetDispSizeVector(const SizeType NumNodes);
/**
* @brief This checks the mesh data and prints if it is OK
*/
void CheckMeshData();
/**
* @brief This sets the output mesh
* @param[in] rInputName The input name
*/
void InputMesh(const std::string& rInputName);
/**
* @brief This sets the output sol
* @param[in] rInputName The input name
*/
void InputSol(const std::string& rInputName);
/**
* @brief This sets the output mesh
* @param[in] rOutputName The output name
*/
void OutputMesh(const std::string& rOutputName);
/**
* @brief This sets the output sol
* @param[in] rOutputName The output name
*/
void OutputSol(const std::string& rOutputName);
/**
* @brief This sets the output displacement
* @param[in] rOutputName The output name
*/
void OutputDisplacement(const std::string& rOutputName);
/**
* @brief This method generates the maps of reference for conditions and elements from an existing json
* @param[in] rOutputName The name of the files
* @param[in] rRefCondition The conditions of reference
* @param[in] rRefElement The elements of reference
*/
void OutputReferenceEntitities(
const std::string& rOutputName,
const std::unordered_map<IndexType,Condition::Pointer>& rRefCondition,
const std::unordered_map<IndexType,Element::Pointer>& rRefElement
);
/**
* @brief This frees the MMG structures
*/
void FreeAll();
/**
* @brief This loads the solution
*/
void MMGLibCallMetric(Parameters ConfigurationParameters);
/**
* @brief This loads the solution
*/
void MMGLibCallIsoSurface(Parameters ConfigurationParameters);
/**
* @brief This sets the nodes of the mesh
* @param[in] X Coordinate X
* @param[in] Y Coordinate Y
* @param[in] Z Coordinate Z
* @param[in] Color Reference of the node(submodelpart)
* @param[in] Index The index number of the node
*/
void SetNodes(
const double X,
const double Y,
const double Z,
const IndexType Color,
const IndexType Index
);
/**
* @brief This sets the conditions of the mesh
* @param[in,out] rGeometry The geometry of the condition
* @param[in] Color Reference of the node(submodelpart)
* @param[in] Index The index number of the node
*/
void SetConditions(
GeometryType& rGeometry,
const IndexType Color,
const IndexType Index
);
/**
* @brief This sets elements of the mesh
* @param[in,out] rGeometry The geometry of the element
* @param[in] Color Reference of the node(submodelpart)
* @param[in] Index The index number of the node
*/
void SetElements(
GeometryType& rGeometry,
const IndexType Color,
const IndexType Index
);
/**
* @brief This function is used to set the metric scalar
* @param[in] Metric The inverse of the size node
* @param[in] NodeId The id of the node
*/
void SetMetricScalar(
const double Metric,
const IndexType NodeId
);
/**
* @brief This function is used to set the metric vector (x, y, z)
* @param[in] rMetric This array contains the components of the metric vector
* @param[in] NodeId The id of the node
*/
void SetMetricVector(
const array_1d<double, Dimension>& rMetric,
const IndexType NodeId
);
/**
* @brief This function is used to set the Hessian metric tensor, note that when using the Hessian, more than one metric can be defined simultaneously, so in consecuence we need to define the elipsoid which defines the volume of maximal intersection
* @param[in] rMetric This array contains the components of the metric tensor in the MMG defined order
* @param[in] NodeId The id of the node
*/
void SetMetricTensor(
const TensorArrayType& rMetric,
const IndexType NodeId
);
/**
* @brief This function is used to set the displacement vector (x, y, z)
* @param[in] rMetric This array contains the components of the displacement vector
* @param[in] NodeId The id of the node
*/
void SetDisplacementVector(
const array_1d<double, 3>& rDisplacement,
const IndexType NodeId
);
/**
* @brief This function is used to retrieve the metric scalar
* @param[in,out] rMetric The inverse of the size node
*/
void GetMetricScalar(double& rMetric);
/**
* @brief This function is used to retrieve the metric vector (x, y, z)
* @param[in,out] rMetric This array contains the components of the metric vector
*/
void GetMetricVector(array_1d<double, Dimension>& rMetric);
/**
* @brief This function is used to retrieve the Hessian metric tensor, note that when using the Hessian, more than one metric can be defined simultaneously, so in consecuence we need to define the elipsoid which defines the volume of maximal intersection
* @param[in,out] rMetric This array contains the components of the metric tensor in the MMG defined order
*/
void GetMetricTensor(TensorArrayType& rMetric);
/**
* @brief This function is used to retrieve the displacement vector (x, y, z)
* @param[in,out] rDisplacement This array contains the components of the displacement vector
*/
void GetDisplacementVector(array_1d<double, 3>& rDisplacement);
/**
* @brief This function reorder the nodes, conditions and elements to avoid problems with non-consecutive ids
* @param[in,out] rModelPart The model part of interest to study
*/
void ReorderAllIds(ModelPart& rModelPart);
/**
* @brief This method generates mesh data from an existing model part
* @param[in,out] rModelPart The model part of interest to study
* @param[in,out] rColors Where the sub model parts IDs are stored
* @param[in,out] rColorMapCondition Auxiliar color map for conditions
* @param[in,out] rColorMapElement Auxiliar color map for elements
* @param[in] Framework The framework considered
* @param[in] CollapsePrismElements If the prisms elements are going to be collapsed
*/
void GenerateMeshDataFromModelPart(
ModelPart& rModelPart,
std::unordered_map<IndexType,std::vector<std::string>>& rColors,
ColorsMapType& rColorMapCondition,
ColorsMapType& rColorMapElement,
const FrameworkEulerLagrange Framework = FrameworkEulerLagrange::EULERIAN,
const bool CollapsePrismElements = false
);
/**
* @brief This method generates the maps of reference for conditions and elements
* @param[in] rModelPart The model part of interest to study
* @param[in] rColorMapCondition Auxiliar color map for conditions
* @param[in] rColorMapElement Auxiliar color map for elements
* @param[in,out] rRefCondition The conditions of reference
* @param[in,out] rRefElement The elements of reference
*/
void GenerateReferenceMaps(
ModelPart& rModelPart,
const ColorsMapType& rColorMapCondition,
const ColorsMapType& rColorMapElement,
std::unordered_map<IndexType,Condition::Pointer>& rRefCondition,
std::unordered_map<IndexType,Element::Pointer>& rRefElement
);
/**
* @brief This method generates solution (metric) data from an existing model part
* @param[in,out] rModelPart The model part of interest to study
*/
void GenerateSolDataFromModelPart(ModelPart& rModelPart);
/**
* @brief This method generates displacement data from an existing model part
* @param[in,out] rModelPart The model part of interest to study
*/
void GenerateDisplacementDataFromModelPart(ModelPart& rModelPart);
/**
* @brief This method writes mesh data to an existing model part
* @param[in,out] rModelPart The model part of interest to study
* @param[in] rColors Where the sub model parts IDs are stored
* @param[in] rDofs Storage for the dof of the node
* @param[in] rMMGMeshInfo The resulting mesh data
* @param[in] rMapPointersRefCondition The map of the conditions by reference (color)
* @param[in] rMapPointersRefElement The map of the elements by reference (color)
*/
void WriteMeshDataToModelPart(
ModelPart& rModelPart,
const std::unordered_map<IndexType,std::vector<std::string>>& rColors,
const NodeType::DofsContainerType& rDofs,
const MMGMeshInfo<TMMGLibrary>& rMMGMeshInfo,
std::unordered_map<IndexType,Condition::Pointer>& rMapPointersRefCondition,
std::unordered_map<IndexType,Element::Pointer>& rMapPointersRefElement
);
/**
* @brief This method writes sol data to an existing model part
* @param[in,out] rModelPart The model part of interest to study
*/
void WriteSolDataToModelPart(ModelPart& rModelPart);
/**
* @brief This method writes the maps of reference for conditions and elements from an existing json
* @param[in] rModelPart The model part of interest to study
* @param[in] rFilename The name of the files
* @param[in,out] rRefCondition The conditions of reference
* @param[in,out] rRefElement The elements of reference
*/
void WriteReferenceEntitities(
ModelPart& rModelPart,
const std::string& rFilename,
std::unordered_map<IndexType,Condition::Pointer>& rRefCondition,
std::unordered_map<IndexType,Element::Pointer>& rRefElement
);
/**
* @brief This function generates a list of submodelparts to be able to reassign flags after remesh
* @param[in,out] rModelPart The model part of interest to study
*/
void CreateAuxiliarSubModelPartForFlags(ModelPart& rModelPart);
/**
* @brief This function assigns the flags and clears the auxiliar sub model part for flags
* @param[in,out] rModelPart The model part of interest to study
*/
void AssignAndClearAuxiliarSubModelPartForFlags(ModelPart& rModelPart);
///@}
///@name Access
///@{
///@}
///@name Inquiry
///@{
///@}
///@name Input and output
///@{
/// Turn back information as a string.
std::string Info() const // override
{
return "MmgUtilities";
}
/// Print information about this object.
void PrintInfo(std::ostream& rOStream) const // override
{
rOStream << "MmgUtilities";
}
/// Print object's data.
void PrintData(std::ostream& rOStream) const // override
{
}
protected:
///@name Protected Member Variables
///@{
///@}
///@name Protected member Variables
///@{
///@}
///@name Protected Operators
///@{
///@}
///@name Protected Operations
///@{
///@}
///@name Protected Access
///@{
///@}
///@name Protected Inquiry
///@{
///@}
///@name Protected LifeCycle
///@{
///@}
private:
///@name Static Member Variables
///@{
///@}
///@name Member Variables
///@{
SizeType mEchoLevel = 0; /// The echo level of the utilities
bool mRemoveRegions = false; /// Cuttig-out specified regions during surface remeshing
DiscretizationOption mDiscretization = DiscretizationOption::STANDARD; /// Discretization The discretization type
///@}
///@name Private Operators
///@{
///@}
///@name Private Operations
///@{
/**
* @brief Sets a flag according to a given status over all submodelparts
* @param rFlag flag to be set
* @param FlagValue flag value to be set
*/
void ResursivelyAssignFlagEntities(
ModelPart& rModelPart,
const Flags& rFlag,
const bool FlagValue
)
{
// We call it recursively
for (auto& r_sub_model_part : rModelPart.SubModelParts()) {
VariableUtils().SetFlag(rFlag, FlagValue, r_sub_model_part.Conditions());
VariableUtils().SetFlag(rFlag, FlagValue, r_sub_model_part.Elements());
ResursivelyAssignFlagEntities(r_sub_model_part, rFlag, FlagValue);
}
}
///@}
///@name Private Access
///@{
///@}
///@name Private Inquiry
///@{
///@}
///@name Un accessible methods
///@{
// /// Assignment operator.
// MmgUtilities& operator=(MmgUtilities const& rOther);
// /// Copy constructor.
// MmgUtilities(MmgUtilities const& rOther);
///@}
};// class MmgUtilities
///@}
///@name Type Definitions
///@{
///@}
///@name Input and output
///@{
/// input stream function
template<MMGLibrary TMMGLibrary>
inline std::istream& operator >> (std::istream& rIStream,
MmgUtilities<TMMGLibrary>& rThis);
/// output stream function
template<MMGLibrary TMMGLibrary>
inline std::ostream& operator << (std::ostream& rOStream,
const MmgUtilities<TMMGLibrary>& rThis)
{
rThis.PrintInfo(rOStream);
rOStream << std::endl;
rThis.PrintData(rOStream);
return rOStream;
}
}// namespace Kratos.
#endif /* KRATOS_MMG_UTILITIES defined */
| 32.546307 | 258 | 0.651142 | [
"mesh",
"geometry",
"object",
"vector",
"model",
"3d"
] |
0496a8ce86afdc0eab6f3c43619ad02a21481fe3 | 3,041 | h | C | src/graphtools.h | ABohynDOE/oapackage | d4df98ee94ecd98e5e9eec62dc29df9a7ec8c9ce | [
"BSD-2-Clause"
] | 20 | 2015-11-06T07:24:29.000Z | 2022-03-28T22:02:19.000Z | src/graphtools.h | ABohynDOE/oapackage | d4df98ee94ecd98e5e9eec62dc29df9a7ec8c9ce | [
"BSD-2-Clause"
] | 37 | 2015-11-06T07:25:42.000Z | 2022-03-22T01:33:47.000Z | src/graphtools.h | ABohynDOE/oapackage | d4df98ee94ecd98e5e9eec62dc29df9a7ec8c9ce | [
"BSD-2-Clause"
] | 12 | 2016-08-16T15:09:57.000Z | 2022-03-06T11:48:55.000Z | /** \file graphtools.h
\brief This file contains definitions and functions related to graphs and designs.
Author: Pieter Eendebak <pieter.eendebak@gmail.com>, (C) 2016
Copyright: See COPYING file that comes with this distribution
*/
#pragma once
#include <vector>
#include "arraytools.h"
/** Isomorphism types for matrices
*
* Isotopy: permute rows, columns and symbols
* Matrix isomorphism: permute rows and columns
* Conference isomorphism: permute rows, columns and to row and column negations (values in 0, +1, -1)
* Orthogonal array isomorphism: permutations of rows, columns and column symbol permutations
*/
enum matrix_isomorphism_t {
/// isotopy: permute rows, columns and symbols
ISOTOPY,
/// permute rows and columns
MATRIX_ISOMORPHISM,
/// permute rows, columns and to row and column negations (values in 0, +1, -1)
CONFERENCE_ISOMORPHISM,
/// permutations of rows, columns and column symbol permutations
OA_ISOMORPHISM };
/// isomorphism type for column and row permtations and column permutations
const matrix_isomorphism_t CONFERENCE_RESTRICTED_ISOMORPHISM = OA_ISOMORPHISM;
namespace nauty {
#include "nauty.h"
/** Reduce a colored graph to Nauty minimal form
*
* The transformation returned is from the normal form to the specified graph.
*
* \param graph Graph in incidence matrix form
* \param colors Colors of the graph nodes
* \param verbose Verbosity level
* \return Relabelling of the graph vertices
*
*/
std::vector< int > reduceNauty (const array_link &graph, std::vector< int > colors, int verbose = 0);
}
/// Apply a vertex permutation to a graph
array_link transformGraph (const array_link &graph, const std::vector< int > vertex_permutation, int verbose = 1);
/// Reduce an orthogonal array to Nauty minimal form. the array transformation is returned
array_transformation_t reduceOAnauty (const array_link &array, int verbose = 0);
/// Reduce an orthogonal array to Nauty minimal form. the array transformation is returned
array_transformation_t reduceOAnauty (const array_link &array, int verbose, const arraydata_t &arrayclass);
/** Convert orthogonal array to graph representation
*
* The conversion method is as in Ryan and Bulutoglu.
* The resulting graph is bi-partite.
* The graph representation can be used for isomorphism testing.
*/
std::pair< array_link, std::vector< int > > array2graph (const array_link &array, int verbose = 1);
/** Convert orthogonal array to graph representation
*
* The conversion method is as in Ryan and Bulutoglu.
* The resulting graph is bi-partite.
* The graph representation can be used for isomorphism testing.
*/
std::pair< array_link, std::vector< int > > array2graph (const array_link &array, int verbose, const arraydata_t &arrayclass);
/// From a relabelling of the graph return the corresponding array transformation
array_transformation_t oagraph2transformation (const std::vector< int > &pp, const arraydata_t &arrayclass,
int verbose = 1);
| 37.085366 | 126 | 0.74778 | [
"vector"
] |
049afb7a91f02396db3c6ffcdc7ef1a0eed66b99 | 98,918 | c | C | media_driver/linux/common/os/mos_utilities_specific.c | shuangwan01/media-driver | 4ad202a509831e5ea5963b3d4b93e4c6d15ef404 | [
"Intel",
"BSD-3-Clause",
"MIT"
] | null | null | null | media_driver/linux/common/os/mos_utilities_specific.c | shuangwan01/media-driver | 4ad202a509831e5ea5963b3d4b93e4c6d15ef404 | [
"Intel",
"BSD-3-Clause",
"MIT"
] | null | null | null | media_driver/linux/common/os/mos_utilities_specific.c | shuangwan01/media-driver | 4ad202a509831e5ea5963b3d4b93e4c6d15ef404 | [
"Intel",
"BSD-3-Clause",
"MIT"
] | null | null | null | /*
* Copyright (c) 2009-2018, Intel Corporation
*
* 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 mos_utilities_specific.c
//! \brief This module implements the MOS wrapper functions for Linux/Android
//!
#include "mos_utilities_specific.h"
#include "mos_utilities.h"
#include "mos_util_debug.h"
#include <fcntl.h> // open
#include <stdlib.h> // atoi
#include <string.h> // strlen, strcat, etc.
#include <errno.h> // strerror(errno)
#include <time.h> // get_clocktime
#include <sys/stat.h> // fstat
#include <dlfcn.h> // dlopen, dlsym, dlclose
#include <sys/types.h>
#include <unistd.h>
#if _MEDIA_RESERVED
#include "codechal_user_settings_mgr_ext.h"
#include "vphal_user_settings_mgr_ext.h"
#endif // _MEDIA_RESERVED
#ifndef ANDROID
#include <sys/ipc.h> // System V IPC
#include <sys/types.h>
#include <sys/sem.h>
#include <signal.h>
#include <unistd.h> // fork
#else
#include <cutils/properties.h>
#endif // ANDROID
#include "mos_utilities_specific_next.h"
static const char* szUserFeatureFile = USER_FEATURE_FILE;
#if _MEDIA_RESERVED
static MediaUserSettingsMgr *codecUserFeatureExt = nullptr;
static MediaUserSettingsMgr *vpUserFeatureExt = nullptr;
#endif
#ifdef __cplusplus
void PerfUtility::startTick(std::string tag)
{
Tick newTick = {};
struct timespec ts = {};
// get start tick count
clock_gettime(CLOCK_REALTIME, &ts);
newTick.start = int(ts.tv_sec * 1000000) + int(ts.tv_nsec / 1000); // us
std::vector<Tick> *perf = nullptr;
std::map<std::string, std::vector<Tick>*>::iterator it;
it = records.find(tag);
if (it == records.end())
{
perf = new std::vector<Tick>;
perf->push_back(newTick);
records[tag] = perf;
}
else
{
it->second->push_back(newTick);
}
}
void PerfUtility::stopTick(std::string tag)
{
struct timespec ts = {};
std::map<std::string, std::vector<Tick>*>::iterator it;
it = records.find(tag);
if (it == records.end())
{
// should not happen
return;
}
// get stop tick count
clock_gettime(CLOCK_REALTIME, &ts);
it->second->back().stop = int(ts.tv_sec * 1000000) + int(ts.tv_nsec / 1000); // us
// calculate time interval
it->second->back().time = double(it->second->back().stop - it->second->back().start) / 1000.0; // ms
}
#endif // __cplusplus
//!
//! \brief Get current run time
//! \details Get current run time in us
//! \return double
//! Returns time in us
//!
double MOS_GetTime()
{
struct timespec ts = {};
clock_gettime(CLOCK_REALTIME, &ts);
return double(ts.tv_sec) * 1000000.0 + double(ts.tv_nsec) / 1000.0;
}
//!
//! \brief Linux specific user feature define, used in MOS_UserFeature_ParsePath
//! They can be unified with the win definitions, since they are identical.
//!
#define MOS_UF_SEPARATOR "\\"
#define MOS_UFKEY_EXT "UFKEY_EXTERNAL"
#define MOS_UFKEY_INT "UFKEY_INTERNAL"
PUFKEYOPS pUFKeyOps = nullptr;
extern int32_t MosMemAllocCounterNoUserFeature;
extern int32_t MosMemAllocCounterNoUserFeatureGfx;
//!
//! \brief Linux specific trace entry path and file description.
//!
const char * const MosTracePath = "/sys/kernel/debug/tracing/trace_marker";
static int32_t MosTraceFd = -1;
//!
//! \brief for int64_t/uint64_t format print warning
//!
#if __WORDSIZE == 64
#define __MOS64_PREFIX "l"
#else
#define __MOS64_PREFIX "ll"
#endif
#define MOSd64 __MOS64_PREFIX "d"
#define MOSu64 __MOS64_PREFIX "u"
//!
//! \brief mutex for mos utilities multi-threading protection
//!
MOS_MUTEX gMosUtilMutex = PTHREAD_MUTEX_INITIALIZER;
static uint32_t uiMOSUtilInitCount = 0; // number count of mos utilities init
MOS_STATUS MOS_SecureStrcat(char *strDestination, size_t numberOfElements, const char * const strSource)
{
if ( (strDestination == nullptr) || (strSource == nullptr) )
{
return MOS_STATUS_INVALID_PARAMETER;
}
if(strnlen(strDestination, numberOfElements) == numberOfElements) // Not null terminated
{
return MOS_STATUS_INVALID_PARAMETER;
}
if((strlen(strDestination) + strlen(strSource)) >= numberOfElements) // checks space for null termination.
{
return MOS_STATUS_INVALID_PARAMETER;
}
strcat(strDestination, strSource);
return MOS_STATUS_SUCCESS;
}
char *MOS_SecureStrtok(
char *strToken,
const char *strDelimit,
char **contex)
{
return strtok_r(strToken, strDelimit, contex);
}
MOS_STATUS MOS_SecureStrcpy(char *strDestination, size_t numberOfElements, const char * const strSource)
{
if ( (strDestination == nullptr) || (strSource == nullptr) )
{
return MOS_STATUS_INVALID_PARAMETER;
}
if ( numberOfElements <= strlen(strSource) ) // checks if there is space for null termination after copy.
{
return MOS_STATUS_INVALID_PARAMETER;
}
strcpy(strDestination, strSource);
return MOS_STATUS_SUCCESS;
}
MOS_STATUS MOS_SecureMemcpy(void *pDestination, size_t dstLength, PCVOID pSource, size_t srcLength)
{
if ( (pDestination == nullptr) || (pSource == nullptr) )
{
return MOS_STATUS_INVALID_PARAMETER;
}
if ( dstLength < srcLength )
{
return MOS_STATUS_INVALID_PARAMETER;
}
if(pDestination != pSource)
{
memcpy(pDestination, pSource, srcLength);
}
return MOS_STATUS_SUCCESS;
}
MOS_STATUS MOS_SecureFileOpen(
FILE **ppFile,
const char *filename,
const char *mode)
{
PFILE fp;
if ((ppFile == nullptr) || (filename == nullptr) || (mode == nullptr))
{
return MOS_STATUS_INVALID_PARAMETER;
}
fp = fopen(filename, mode);
if (fp == nullptr)
{
*ppFile = nullptr;
return MOS_STATUS_FILE_OPEN_FAILED;
}
else
{
*ppFile = fp;
return MOS_STATUS_SUCCESS;
}
}
int32_t MOS_SecureStringPrint(char *buffer, size_t bufSize, size_t length, const char * const format, ...)
{
int32_t iRet = -1;
va_list var_args;
if((buffer == nullptr) || (format == nullptr) || (bufSize < length))
{
return iRet;
}
va_start(var_args, format);
iRet = vsnprintf(buffer, length, format, var_args);
va_end(var_args);
return iRet;
}
MOS_STATUS MOS_SecureVStringPrint(char *buffer, size_t bufSize, size_t length, const char * const format, va_list var_args)
{
if((buffer == nullptr) || (format == nullptr) || (bufSize < length))
{
return MOS_STATUS_INVALID_PARAMETER;
}
vsnprintf(buffer, length, format, var_args);
return MOS_STATUS_SUCCESS;
}
MOS_STATUS MOS_GetFileSize(
HANDLE hFile,
uint32_t *lpFileSizeLow,
uint32_t *lpFileSizeHigh)
{
struct stat Buf;
MOS_UNUSED(lpFileSizeHigh);
if((hFile == nullptr) || (lpFileSizeLow == nullptr))
{
return MOS_STATUS_INVALID_PARAMETER;
}
if ( (fstat((intptr_t)hFile, &Buf)) < 0 )
{
*lpFileSizeLow = 0;
return MOS_STATUS_INVALID_FILE_SIZE;
}
*lpFileSizeLow = (uint32_t)Buf.st_size;
//to-do, lpFileSizeHigh store high 32-bit of File size
return MOS_STATUS_SUCCESS;
}
MOS_STATUS MOS_CreateDirectory(
char * const lpPathName)
{
uint32_t mode;
MOS_STATUS eStatus = MOS_STATUS_UNKNOWN;
MOS_OS_CHK_NULL(lpPathName);
// Set read/write access right for usr/group.
mode = S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IWGRP;
if (mkdir(lpPathName, mode) < 0 &&
errno != EEXIST) // Directory already exists, don't return failure in this case.
{
MOS_OS_ASSERTMESSAGE("Failed to create the directory '%s'. Error = %s", lpPathName, strerror(errno));
eStatus = MOS_STATUS_DIR_CREATE_FAILED;
goto finish;
}
eStatus = MOS_STATUS_SUCCESS;
finish:
return eStatus;
}
MOS_STATUS MOS_CreateFile(
PHANDLE pHandle,
char * const lpFileName,
uint32_t iOpenFlag)
{
int32_t iFileDescriptor;
uint32_t mode;
if((lpFileName == nullptr) || (pHandle == nullptr))
{
return MOS_STATUS_INVALID_PARAMETER;
}
//set read/write access right for usr/group, mMode only takes effect when
//O_CREAT is set
mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP;
if ( (iFileDescriptor = open(lpFileName, iOpenFlag, mode)) < 0 )
{
*pHandle = (HANDLE)((intptr_t) iFileDescriptor);
return MOS_STATUS_INVALID_HANDLE;
}
*pHandle = (HANDLE)((intptr_t) iFileDescriptor);
return MOS_STATUS_SUCCESS;
}
MOS_STATUS MOS_ReadFile(
HANDLE hFile,
void *lpBuffer,
uint32_t bytesToRead,
uint32_t *pBytesRead,
void *lpOverlapped)
{
size_t nNumBytesToRead;
ssize_t nNumBytesRead;
MOS_UNUSED(lpOverlapped);
if((hFile == nullptr) || (lpBuffer == nullptr) || (pBytesRead == nullptr))
{
return MOS_STATUS_INVALID_PARAMETER;
}
nNumBytesToRead = (size_t)bytesToRead;
nNumBytesRead = 0;
//To-do: process lpOverlapped
if ((nNumBytesRead = read((intptr_t)hFile, lpBuffer, nNumBytesToRead)) < 0)
{
*pBytesRead = 0;
return MOS_STATUS_FILE_READ_FAILED;
}
*pBytesRead = (uint32_t)nNumBytesRead;
return MOS_STATUS_SUCCESS;
}
MOS_STATUS MOS_WriteFile(
HANDLE hFile,
void *lpBuffer,
uint32_t bytesToWrite,
uint32_t *pbytesWritten,
void *lpOverlapped)
{
size_t nNumBytesToWrite;
ssize_t nNumBytesWritten;
MOS_UNUSED(lpOverlapped);
if((hFile == nullptr) || (lpBuffer == nullptr) || (pbytesWritten == nullptr))
{
return MOS_STATUS_INVALID_PARAMETER;
}
nNumBytesToWrite = (size_t)bytesToWrite;
nNumBytesWritten = 0;
//To-do, process lpOverlapped
if ((nNumBytesWritten = write((intptr_t)hFile, lpBuffer, nNumBytesToWrite)) < 0)
{
*pbytesWritten = 0;
return MOS_STATUS_FILE_WRITE_FAILED;
}
*pbytesWritten = (uint32_t)nNumBytesWritten;
return MOS_STATUS_SUCCESS;
}
MOS_STATUS MOS_SetFilePointer(
HANDLE hFile,
int32_t lDistanceToMove,
int32_t *lpDistanceToMoveHigh,
int32_t dwMoveMethod)
{
int32_t iOffSet;
int32_t iCurPos;
if(hFile == nullptr)
{
return MOS_STATUS_INVALID_PARAMETER;
}
if (lpDistanceToMoveHigh == nullptr)
{
iOffSet = lDistanceToMove;
}
else
{
//to-do, let lpDistanceToMoveHigh and lDistanceToMove form a 64-bit iOffSet
iOffSet = (int32_t)lDistanceToMove;
}
if ((iCurPos = lseek((intptr_t)hFile, iOffSet, dwMoveMethod)) < 0)
{
return MOS_STATUS_SET_FILE_POINTER_FAILED;
}
return MOS_STATUS_SUCCESS;
}
int32_t MOS_CloseHandle(HANDLE hObject)
{
int32_t iRet = false;
if(hObject != nullptr)
{
close((intptr_t)hObject);
iRet = true;
}
return iRet;
}
//library
MOS_STATUS MOS_LoadLibrary(const char * const lpLibFileName, PHMODULE phModule)
{
if (lpLibFileName == nullptr)
{
return MOS_STATUS_INVALID_PARAMETER;
}
*phModule = dlopen((const char *)lpLibFileName, RTLD_LAZY);
return ((*phModule != nullptr) ? MOS_STATUS_SUCCESS : MOS_STATUS_LOAD_LIBRARY_FAILED);
}
int32_t MOS_FreeLibrary (HMODULE hLibModule)
{
uint32_t iRet = 10; // Initialize to some non-zero value
if(hLibModule != nullptr)
{
iRet = dlclose(hLibModule);
}
return (iRet == 0) ? true : false;
}
void *MOS_GetProcAddress(HMODULE hModule, const char *lpProcName)
{
void *pSym = nullptr;
if (hModule == nullptr ||
lpProcName == nullptr)
{
MOS_OS_ASSERTMESSAGE("Invalid parameter.");
}
else
{
pSym = dlsym(hModule, lpProcName);
}
return pSym;
}
int32_t MOS_GetPid()
{
return(getpid());
}
//Performace
int32_t MOS_QueryPerformanceFrequency(uint64_t *pFrequency)
{
struct timespec Res;
int32_t iRet;
if(pFrequency == nullptr)
{
return false;
}
if ( (iRet = clock_getres(CLOCK_MONOTONIC, &Res)) != 0 )
{
return false;
}
// resolution (precision) can't be in seconds for current machine and OS
if (Res.tv_sec != 0)
{
return false;
}
*pFrequency = (uint64_t)((1000 * 1000 * 1000) / Res.tv_nsec);
return true;
}
int32_t MOS_QueryPerformanceCounter(uint64_t *pPerformanceCount)
{
struct timespec Res;
struct timespec t;
int32_t iRet;
if(pPerformanceCount == nullptr)
{
return false;
}
if ( (iRet = clock_getres (CLOCK_MONOTONIC, &Res)) != 0 )
{
return false;
}
if (Res.tv_sec != 0)
{ // resolution (precision) can't be in seconds for current machine and OS
return false;
}
if( (iRet = clock_gettime(CLOCK_MONOTONIC, &t)) != 0)
{
return false;
}
*pPerformanceCount = (uint64_t)((1000 * 1000 * 1000 * t.tv_sec + t.tv_nsec) / Res.tv_nsec);
return true;
}
void MOS_Sleep(uint32_t mSec)
{
usleep(1000 * mSec);
}
//User Feature
/*----------------------------------------------------------------------------
| Name : _UserFeature_FindKey
| Purpose : This function finds a key in keys linked list according to key
| name.
| Arguments : pKeyList [in] Key Linked list.
| pcKeyName [in] Name to the key to find.
| Returns : Matched uf_key data. otherwise return NULL.
| Comments :
\---------------------------------------------------------------------------*/
static MOS_UF_KEY* _UserFeature_FindKey(MOS_PUF_KEYLIST pKeyList, char * const pcKeyName)
{
int32_t iResult;
MOS_PUF_KEYLIST pTempNode;
iResult = -1;
for(pTempNode = pKeyList; pTempNode; pTempNode = pTempNode->pNext)
{
iResult = strcmp(pTempNode->pElem->pcKeyName, pcKeyName);
if ( iResult == 0 )
{
return pTempNode->pElem;
}
}
return nullptr; //not found
}
/*----------------------------------------------------------------------------
| Name : _UserFeature_FindValue
| Purpose : Find a value in values array of a key. Return position in values
| array
| Arguments : UFKey [in] Searched Key node.
| pcValueName [in] Value name.
| Returns : Matched value No. if it can be found, otherwise, return
| NOT_FOUND(-1);
| Comments :
\---------------------------------------------------------------------------*/
static int32_t _UserFeature_FindValue(MOS_UF_KEY UFKey, char * const pcValueName)
{
int32_t iResult;
int32_t i;
iResult = -1;
for ( i = 0; i < (int32_t)UFKey.ulValueNum; i++ )
{
iResult = strcmp(UFKey.pValueArray[i].pcValueName, pcValueName);
if ( iResult == 0 )
{
return i;
}
}
return NOT_FOUND;
}
/*----------------------------------------------------------------------------
| Name : _UserFeature_Add
| Purpose : Add new key to keys' linked list.
| Arguments : pKeyList [in] Key linked list.
| NewKey [in] Added new key.
| Returns : MOS_STATUS_SUCCESS success
| MOS_STATUS_INVALID_PARAMETER invalid NewKey
| MOS_STATUS_NO_SPACE no space left for allocate
| Comments :
\---------------------------------------------------------------------------*/
static MOS_STATUS _UserFeature_Add(MOS_PUF_KEYLIST *pKeyList, MOS_UF_KEY *NewKey)
{
MOS_UF_KEYNODE *pNewNode;
MOS_UF_KEYNODE *pTempNode;
MOS_UF_KEYNODE *pStartNode;
pNewNode = nullptr;
pTempNode = nullptr;
pStartNode = *pKeyList;
if ( NewKey == nullptr )
{
return MOS_STATUS_INVALID_PARAMETER;
}
pNewNode = (MOS_UF_KEYNODE*)MOS_AllocMemory(sizeof(MOS_UF_KEYNODE));
if (pNewNode == nullptr)
{
return MOS_STATUS_NO_SPACE;
}
pNewNode->pElem = NewKey;
if (*pKeyList == nullptr ) // the key list is empty
{
pNewNode->pNext = nullptr;
(*pKeyList) = pNewNode;
}
else // the key list is not empty, append to the front
{
pTempNode = pStartNode->pNext;
pStartNode->pNext = pNewNode;
pNewNode->pNext = pTempNode;
}
return MOS_STATUS_SUCCESS;
}
/*----------------------------------------------------------------------------
| Name : _UserFeature_Set
| Purpose : This function set a key to the key list.
| Arguments : pKeyList [in] Key linked list.
| NewKey [in] Set key content.
| Returns : MOS_STATUS_SUCCESS Operation success.
| MOS_STATUS_UNKNOWN Can't find key in User Feature File.
| MOS_STATUS_NO_SPACE no space left for allocate
| Comments :
\---------------------------------------------------------------------------*/
static MOS_STATUS _UserFeature_Set(MOS_PUF_KEYLIST *pKeyList, MOS_UF_KEY NewKey)
{
int32_t iPos;
MOS_UF_VALUE *pValueArray;
MOS_UF_KEY *Key;
void *ulValueBuf;
iPos = -1;
pValueArray = nullptr;
if ( (Key = _UserFeature_FindKey(*pKeyList, NewKey.pcKeyName)) == nullptr )
{
// can't find key in File
return MOS_STATUS_UNKNOWN;
}
// Prepare the ValueBuff of the NewKey
if ((ulValueBuf = MOS_AllocMemory(NewKey.pValueArray[0].ulValueLen)) == nullptr)
{
return MOS_STATUS_NO_SPACE;
}
if ( (iPos = _UserFeature_FindValue(*Key, NewKey.pValueArray[0].pcValueName)) == NOT_FOUND)
{
//not found, add a new value to key struct.
//reallocate memory for appending this value.
pValueArray = (MOS_UF_VALUE*)MOS_AllocMemory(sizeof(MOS_UF_VALUE)*(Key->ulValueNum+1));
if (pValueArray == nullptr)
{
MOS_FreeMemory(ulValueBuf);
return MOS_STATUS_NO_SPACE;
}
MOS_SecureMemcpy(pValueArray,
sizeof(MOS_UF_VALUE)*(Key->ulValueNum),
Key->pValueArray,
sizeof(MOS_UF_VALUE)*(Key->ulValueNum));
MOS_FreeMemory(Key->pValueArray);
Key->pValueArray = pValueArray;
iPos = Key->ulValueNum;
MOS_SecureStrcpy(Key->pValueArray[Key->ulValueNum].pcValueName,
MAX_USERFEATURE_LINE_LENGTH,
NewKey.pValueArray[0].pcValueName);
Key->ulValueNum ++;
}
else
{
//if found, the previous value buffer needs to be freed before reallocating
MOS_FreeMemory(Key->pValueArray[iPos].ulValueBuf);
}
Key->pValueArray[iPos].ulValueLen = NewKey.pValueArray[0].ulValueLen;
Key->pValueArray[iPos].ulValueType = NewKey.pValueArray[0].ulValueType;
Key->pValueArray[iPos].ulValueBuf = ulValueBuf;
MOS_ZeroMemory(Key->pValueArray[iPos].ulValueBuf, NewKey.pValueArray[0].ulValueLen);
MOS_SecureMemcpy(Key->pValueArray[iPos].ulValueBuf,
NewKey.pValueArray[0].ulValueLen,
NewKey.pValueArray[0].ulValueBuf,
NewKey.pValueArray[0].ulValueLen);
return MOS_STATUS_SUCCESS;
}
/*----------------------------------------------------------------------------
| Name : _UserFeature_Query
| Purpose : This function query a key's value and return matched key node
| content just with matched value content.
| Arguments : pKeyList [in] Key linked list.
| NewKey [in] New key content with matched value.
| Returns : MOS_STATUS_SUCCESS Operation success.
| MOS_STATUS_UNKNOWN Can't find key or value in User Feature File.
| Comments :
\---------------------------------------------------------------------------*/
static MOS_STATUS _UserFeature_Query(MOS_PUF_KEYLIST pKeyList, MOS_UF_KEY *NewKey)
{
int32_t iPos;
MOS_UF_VALUE *pValueArray;
MOS_UF_KEY *Key;
iPos = -1;
pValueArray = nullptr;
// can't find key in user feature
if ( (Key = _UserFeature_FindKey(pKeyList, NewKey->pcKeyName)) == nullptr )
{
return MOS_STATUS_UNKNOWN;
}
// can't find Value in the key
if ( (iPos = _UserFeature_FindValue(*Key, NewKey->pValueArray[0].pcValueName)) == NOT_FOUND)
{
return MOS_STATUS_UNKNOWN;
}
//get key content from user feature
MOS_SecureMemcpy(NewKey->pValueArray[0].ulValueBuf,
Key->pValueArray[iPos].ulValueLen,
Key->pValueArray[iPos].ulValueBuf,
Key->pValueArray[iPos].ulValueLen);
NewKey->pValueArray[0].ulValueLen = Key->pValueArray[iPos].ulValueLen;
NewKey->pValueArray[0].ulValueType = Key->pValueArray[iPos].ulValueType;
return MOS_STATUS_SUCCESS;
}
static MOS_STATUS _UserFeature_ReadNextTokenFromFile(FILE *pFile, const char *szFormat, char *szToken)
{
size_t nTokenSize = 0;
// Reads the next token from the given pFile.
if (fscanf(pFile, szFormat, szToken) <= 0)
{
MOS_OS_VERBOSEMESSAGE("Failed reading the next token from the user feature file. This is probably because the token does not exist in the user feature file.");
return MOS_STATUS_FILE_READ_FAILED;
}
// Converts to Unix-style line endings to prevent compatibility problems.
nTokenSize = strnlen(szToken, MAX_USERFEATURE_LINE_LENGTH);
if (szToken[nTokenSize-1] == '\r')
{
szToken[nTokenSize-1] = '\0';
}
return MOS_STATUS_SUCCESS;
}
/*----------------------------------------------------------------------------
| Name : _UserFeature_DumpFile
| Purpose : This function read the whole User Feature File and dump User Feature File
| data to key linked list.
| Arguments : szFileName [in] User Feature File name.
| pKeyList [out] Key Linked list.
| Returns : MOS_STATUS_SUCCESS Operation success.
| MOS_STATUS_USER_FEATURE_KEY_READ_FAILED User Feature File can't be open as read.
| MOS_STATUS_NO_SPACE no space left for allocate
| MOS_STATUS_UNKNOWN unknown user feature type found in User Feature File
| MOS_STATUS_INVALID_PARAMETER unknown items found in User Feature File
| Comments :
\---------------------------------------------------------------------------*/
static MOS_STATUS _UserFeature_DumpFile(const char * const szFileName, MOS_PUF_KEYLIST* pKeyList)
{
MOS_UF_KEY *CurKey;
MOS_UF_VALUE *CurValue;
char szTmp[MAX_USERFEATURE_LINE_LENGTH];
int32_t iResult;
size_t nSize;
int32_t bFirst;
int32_t iCount;
PFILE File;
int32_t bEmpty;
int32_t iCurId;
MOS_STATUS eStatus;
char *tmpChar; // Used in the 64-bit case to read uint64_t
CurValue = nullptr;
nSize = 0;
bFirst = 1; // 1 stand for "is the first key".
iCount = 0;
File = nullptr;
bEmpty = 0;
iCurId = 0;
eStatus = MOS_STATUS_SUCCESS;
CurKey = (MOS_UF_KEY*)MOS_AllocMemory(sizeof(MOS_UF_KEY));
if (CurKey == nullptr)
{
return MOS_STATUS_NO_SPACE;
}
CurKey->ulValueNum = 0;
CurKey->pcKeyName[0] = '\0';
CurKey->pValueArray = nullptr;
if ( (File = fopen(szFileName, "r")) == nullptr)
{
MOS_FreeMemory(CurKey);
return MOS_STATUS_USER_FEATURE_KEY_READ_FAILED;
}
while (feof(File) != EOF)
{
MOS_ZeroMemory(szTmp, MAX_USERFEATURE_LINE_LENGTH*sizeof(char ));
if (MOS_FAILED(_UserFeature_ReadNextTokenFromFile(File, MAX_UF_LINE_STRING_FORMAT, szTmp)))
{
break;
}
// set szDumpData with extracted File content.
iResult = strcmp(szTmp, UF_KEY_ID);
if ( iResult == 0 )
{
// It is a new key starting!
if (! bFirst )
{
// Add last key struct to contents when the key is not first.
// otherwise, continue to load key struct data.
CurKey->pValueArray = CurValue;
CurKey->ulValueNum = iCount;
if(_UserFeature_Add(pKeyList, CurKey) != MOS_STATUS_SUCCESS)
{
// if the CurKey didn't be added in pKeyList, free it.
MOS_FreeMemory(CurKey);
}
CurKey = (MOS_UF_KEY*)MOS_AllocMemory(sizeof(MOS_UF_KEY));
if (CurKey == nullptr)
{
eStatus = MOS_STATUS_NO_SPACE;
break;
}
} // if (! bFirst )
if (fscanf(File, "%x\n", (uint32_t*)&iCurId) <= 0)
{
break;
}
CurKey->UFKey = (void *)(intptr_t)iCurId;
MOS_ZeroMemory(szTmp, MAX_USERFEATURE_LINE_LENGTH * sizeof(char));
if (MOS_FAILED(_UserFeature_ReadNextTokenFromFile(File, MAX_UF_LINE_STRING_FORMAT, szTmp)))
{
break;
}
MOS_SecureStrcpy(CurKey->pcKeyName, MAX_USERFEATURE_LINE_LENGTH, szTmp);
CurKey->ulValueNum = 0;
// allocate capability length for valuearray.
CurValue = (MOS_UF_VALUE*)MOS_AllocMemory(sizeof(MOS_UF_VALUE)*UF_CAPABILITY);
if (CurValue == nullptr)
{
eStatus = MOS_STATUS_NO_SPACE;
break;
}
bFirst = 0;
iCount = 0; // next key's array number.
bEmpty = 1;
} // if ( iResult == 0 )
else // not a key
{
// Is it a value starting?
iResult = strcmp(szTmp, UF_VALUE_ID);
if ( iResult == 0 )
{
if (MOS_FAILED(_UserFeature_ReadNextTokenFromFile(File, MAX_UF_LINE_STRING_FORMAT, szTmp)))
{
break;
}
if (CurValue == nullptr)
{
break;
}
// Out of bounds technically based on how much memory we allocated
if (iCount < 0 || iCount >= UF_CAPABILITY)
{
eStatus = MOS_STATUS_USER_FEATURE_KEY_READ_FAILED;
break;
}
// Load value name;
MOS_SecureStrcpy(CurValue[iCount].pcValueName, MAX_USERFEATURE_LINE_LENGTH, szTmp);
// Load value type
if (MOS_FAILED(_UserFeature_ReadNextTokenFromFile(File, MAX_UF_LINE_STRING_FORMAT, szTmp)))
{
break;
}
CurValue[iCount].ulValueType = atoi(szTmp);
// Load value buffer.
switch ( CurValue[iCount].ulValueType )
{
case UF_DWORD: // 32-bit
if (MOS_FAILED(_UserFeature_ReadNextTokenFromFile(File, MAX_UF_LINE_STRING_FORMAT, szTmp)))
{
break;
}
CurValue[iCount].ulValueLen = sizeof(uint32_t);
CurValue[iCount].ulValueBuf = MOS_AllocMemory(sizeof(uint32_t));
if(CurValue[iCount].ulValueBuf == nullptr)
{
eStatus = MOS_STATUS_NO_SPACE;
break;
}
*(uint32_t*)(CurValue[iCount].ulValueBuf) = atoi(szTmp);
break;
case UF_QWORD: // 64-bit
if (MOS_FAILED(_UserFeature_ReadNextTokenFromFile(File, MAX_UF_LINE_STRING_FORMAT, szTmp)))
{
break;
}
CurValue[iCount].ulValueLen = sizeof(uint64_t);
CurValue[iCount].ulValueBuf = MOS_AllocMemory(sizeof(uint64_t));
if(CurValue[iCount].ulValueBuf == nullptr)
{
eStatus = MOS_STATUS_NO_SPACE;
break;
}
tmpChar = &szTmp[0];
*(uint64_t*)(CurValue[iCount].ulValueBuf) = strtoll(tmpChar,&tmpChar,0);
break;
case UF_SZ:
case UF_MULTI_SZ:
if (MOS_FAILED(_UserFeature_ReadNextTokenFromFile(File, MAX_UF_LINE_STRING_FORMAT, szTmp)))
{
break;
}
nSize = strlen(szTmp);
CurValue[iCount].ulValueLen = (nSize+1)*sizeof(char );
CurValue[iCount].ulValueBuf = MOS_AllocMemory(nSize+1);
if(CurValue[iCount].ulValueBuf == nullptr)
{
eStatus = MOS_STATUS_NO_SPACE;
break;
}
MOS_ZeroMemory(CurValue[iCount].ulValueBuf, nSize+1);
MOS_SecureMemcpy(CurValue[iCount].ulValueBuf, nSize, szTmp, nSize);
break;
default:
eStatus = MOS_STATUS_UNKNOWN;
}
if (eStatus != MOS_STATUS_SUCCESS)
{
break;
}
iCount ++; // do the error checking near the top
} // if ( iResult == 0 )
else // It is not a value starting, it's bad User Feature File.
{
int32_t iResult = strcmp(szTmp, "");
if ( !iResult )
{
continue;
}
else
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
break;
}
} // else ( iResult == 0 )
}
} // while (feof(File) != EOF)
if (eStatus == MOS_STATUS_SUCCESS)
{
if ( bEmpty && (strlen(CurKey->pcKeyName) > 0) &&
(CurKey->ulValueNum == 0) )
{
CurKey->pValueArray = CurValue;
CurKey->ulValueNum = iCount;
if(_UserFeature_Add(pKeyList, CurKey) != MOS_STATUS_SUCCESS)
{
// if the CurKey didn't be added in pKeyList, free it.
for (uint32_t i = 0; i < iCount; i++)
{
if (CurValue)
{
MOS_FreeMemory(CurValue[i].ulValueBuf);
}
}
MOS_FreeMemory(CurValue);
MOS_FreeMemory(CurKey);
}
}
else
{
for (uint32_t i = 0; i < iCount; i++)
{
if (CurValue)
{
MOS_FreeMemory(CurValue[i].ulValueBuf);
}
}
MOS_FreeMemory(CurValue);
MOS_FreeMemory(CurKey);
}
}
else
{
for (uint32_t i = 0; i < iCount; i++)
{
if (CurValue)
{
MOS_FreeMemory(CurValue[i].ulValueBuf);
}
}
MOS_FreeMemory(CurValue);
MOS_FreeMemory(CurKey);
}
MOS_SafeFreeMemory(CurValue);
fclose(File);
return eStatus;
}
/*----------------------------------------------------------------------------
| Name : _UserFeature_DumpDataToFile
| Purpose : This function dump key linked list data to File.
| Arguments : szFileName [in] A handle to the File.
| pKeyList [in] Reserved, any LPDWORD type value.
| Returns : MOS_STATUS_SUCCESS Operation success.
| MOS_STATUS_USER_FEATURE_KEY_WRITE_FAILED File can't be written.
| Comments :
\---------------------------------------------------------------------------*/
static MOS_STATUS _UserFeature_DumpDataToFile(const char *szFileName, MOS_PUF_KEYLIST pKeyList)
{
int32_t iResult;
PFILE File;
MOS_PUF_KEYLIST pKeyTmp;
int32_t j;
File = fopen(szFileName, "w+");
if ( !File )
{
return MOS_STATUS_USER_FEATURE_KEY_WRITE_FAILED;
}
for (pKeyTmp = pKeyList; pKeyTmp; pKeyTmp = pKeyTmp->pNext)
{
fprintf(File, "%s\n", UF_KEY_ID);
fprintf(File, "\t0x%.8x\n", (uint32_t)(uintptr_t)pKeyTmp->pElem->UFKey);
fprintf(File, "\t%s\n", pKeyTmp->pElem->pcKeyName);
for ( j = 0; j < (int32_t)pKeyTmp->pElem->ulValueNum; j ++ )
{
fprintf(File, "\t\t%s\n", UF_VALUE_ID);
if ( strlen(pKeyTmp->pElem->pValueArray[j].pcValueName) > 0 )
{
fprintf(File, "\t\t\t%s\n",
pKeyTmp->pElem->pValueArray[j].pcValueName);
}
fprintf(File, "\t\t\t%d\n", pKeyTmp->pElem->pValueArray[j].ulValueType);
if (pKeyTmp->pElem->pValueArray[j].ulValueBuf != nullptr)
{
switch (pKeyTmp->pElem->pValueArray[j].ulValueType)
{
case UF_SZ:
fprintf(File, "\t\t\t%s\n",
(char *)(pKeyTmp->pElem->pValueArray[j].ulValueBuf));
break;
case UF_DWORD:
case UF_QWORD:
fprintf(File, "\t\t\t%d\n",
*(uint32_t*)(pKeyTmp->pElem->pValueArray[j].ulValueBuf));
break;
default:
fprintf(File, "\t\t\t%s\n",
(char *)(pKeyTmp->pElem->pValueArray[j].ulValueBuf));
break;
} //switch (pKeyTmp->pElem->pValueArray[j].ulValueType)
}
} // for ( j = 0; j < (int32_t)pKeyTmp->pElem->ulValueNum; j ++ )
} //for (pKeyTmp = pKeyList; pKeyTmp; pKeyTmp = pKeyTmp->pNext)
fclose(File);
MOS_UserFeatureNotifyChangeKeyValue(nullptr, false, nullptr, true);
return MOS_STATUS_SUCCESS;
}
/*----------------------------------------------------------------------------
| Name : _UserFeature_FreeKeyList
| Purpose : Free key list
| Arguments : pKeyList [in] key list to be free.
| Returns : None
| Comments :
\---------------------------------------------------------------------------*/
static void _UserFeature_FreeKeyList(MOS_PUF_KEYLIST pKeyList)
{
MOS_PUF_KEYLIST pKeyTmp;
MOS_PUF_KEYLIST pKeyTmpNext;
uint32_t i;
pKeyTmp = pKeyList;
while(pKeyTmp)
{
pKeyTmpNext = pKeyTmp->pNext;
for(i=0;i<pKeyTmp->pElem->ulValueNum;i++)
{
MOS_FreeMemory(pKeyTmp->pElem->pValueArray[i].ulValueBuf);
}
MOS_FreeMemory(pKeyTmp->pElem->pValueArray);
MOS_FreeMemory(pKeyTmp->pElem);
MOS_FreeMemory(pKeyTmp);
pKeyTmp = pKeyTmpNext;
}
return;
}
/*----------------------------------------------------------------------------
| Name : _UserFeature_SetValue
| Purpose : Modify or add a value of the specified user feature key.
| Arguments : strKey [in] Pointer to user feature key name.
| pcValueName [in] Pointer to a string containing the name of
| the value to set. If a value with this name
| is not already present in the key, the
| function adds it to the key.
| uiValueType [in] Type of information to be stored.
| szValueData [in] Pointer to a null-terminated string
| containing the data to set for the default
| value of the specified key
| uiValueDataLen [in] Size of the string pointed to by the
| szValueData parameter, not including the
| terminating null character, in bytes
| Returns : MOS_STATUS_SUCCESS function success
| MOS_STATUS_INVALID_PARAMETER invalid paramater
| MOS_STATUS_USER_FEATURE_KEY_READ_FAILED User Feature File can't be open as read.
| MOS_STATUS_NO_SPACE no space left for allocate
| MOS_STATUS_UNKNOWN unknown user feature type found in User Feature File
| MOS_STATUS_INVALID_PARAMETER unknown items found in User Feature File
| MOS_STATUS_USER_FEATURE_KEY_WRITE_FAILED User Feature File can't be written.
| Comments :
\---------------------------------------------------------------------------*/
static MOS_STATUS _UserFeature_SetValue(
char * const strKey,
const char * const pcValueName,
uint32_t uiValueType,
void *pData,
int32_t nDataSize)
{
MOS_UF_KEY NewKey;
MOS_UF_VALUE NewValue;
MOS_STATUS eStatus;
MOS_PUF_KEYLIST pKeyList;
eStatus = MOS_STATUS_UNKNOWN;
pKeyList = nullptr;
if ( (strKey== nullptr) || (pcValueName == nullptr) )
{
return MOS_STATUS_INVALID_PARAMETER;
}
MOS_ZeroMemory(NewValue.pcValueName, MAX_USERFEATURE_LINE_LENGTH);
MOS_SecureStrcpy(NewValue.pcValueName, MAX_USERFEATURE_LINE_LENGTH, pcValueName);
NewValue.ulValueType = uiValueType;
if( NewValue.ulValueType == UF_DWORD)
{
NewValue.ulValueLen = sizeof(uint32_t);
}
else
{
NewValue.ulValueLen = nDataSize;
}
NewValue.ulValueBuf = pData;
MOS_ZeroMemory(NewKey.pcKeyName, MAX_USERFEATURE_LINE_LENGTH);
MOS_SecureStrcpy(NewKey.pcKeyName, MAX_USERFEATURE_LINE_LENGTH, strKey);
NewKey.pValueArray = &NewValue;
NewKey.ulValueNum = 1;
if ( (eStatus = _UserFeature_DumpFile(szUserFeatureFile, &pKeyList)) != MOS_STATUS_SUCCESS )
{
MOS_FreeMemory(pKeyList);
return eStatus;
}
if ( ( eStatus = _UserFeature_Set(&pKeyList, NewKey)) == MOS_STATUS_SUCCESS )
{
eStatus = _UserFeature_DumpDataToFile(szUserFeatureFile, pKeyList);
}
_UserFeature_FreeKeyList(pKeyList);
return eStatus;
}
/*----------------------------------------------------------------------------
| Name : _UserFeature_QueryValue
| Purpose : The QueryValue function retrieves the type and data for a
| specified value name associated with a special user feature key.
| Arguments : strKey [in] Pointer to user feature key name.
| pcValueName [in] Pointer to a string containing the name
| of the value to query.
| uiValueType [out] Output Value's type
| pData [out] Output value's content
| nDataSize [out] Output the size of value's content.
| Returns : MOS_STATUS_SUCCESS function success
| MOS_STATUS_INVALID_PARAMETER invalid paramater
| MOS_STATUS_USER_FEATURE_KEY_READ_FAILED User Feature File can't be open as read.
| MOS_STATUS_NO_SPACE no space left for allocate
| MOS_STATUS_UNKNOWN Can't find key or value in User Feature File.
| Comments :
\---------------------------------------------------------------------------*/
static MOS_STATUS _UserFeature_QueryValue(
char * const strKey,
const char * const pcValueName,
uint32_t *uiValueType,
void *pData,
int32_t *nDataSize)
{
MOS_UF_KEY NewKey;
MOS_UF_VALUE NewValue;
size_t nKeyLen, nValueLen;
MOS_STATUS eStatus;
MOS_PUF_KEYLIST pKeyList;
char strTempKey[MAX_USERFEATURE_LINE_LENGTH];
char strTempValueName[MAX_USERFEATURE_LINE_LENGTH];
eStatus = MOS_STATUS_UNKNOWN;
pKeyList = nullptr;
if ( (strKey == nullptr) || (pcValueName == nullptr))
{
return MOS_STATUS_INVALID_PARAMETER;
}
MOS_ZeroMemory(NewValue.pcValueName, MAX_USERFEATURE_LINE_LENGTH);
MOS_SecureStrcpy(NewValue.pcValueName, MAX_USERFEATURE_LINE_LENGTH, pcValueName);
NewValue.ulValueBuf = pData;
MOS_ZeroMemory(NewKey.pcKeyName, MAX_USERFEATURE_LINE_LENGTH);
MOS_SecureStrcpy(NewKey.pcKeyName, MAX_USERFEATURE_LINE_LENGTH, strKey);
NewKey.pValueArray = &NewValue;
NewKey.ulValueNum = 1;
if ( (eStatus = _UserFeature_DumpFile(szUserFeatureFile, &pKeyList)) == MOS_STATUS_SUCCESS)
{
if ( (eStatus = _UserFeature_Query(pKeyList, &NewKey)) == MOS_STATUS_SUCCESS )
{
if(uiValueType != nullptr)
{
*uiValueType = NewKey.pValueArray[0].ulValueType;
}
if (nDataSize != nullptr)
{
*nDataSize = NewKey.pValueArray[0].ulValueLen;
}
}
}
_UserFeature_FreeKeyList(pKeyList);
return eStatus;
}
/*----------------------------------------------------------------------------
| Name : _UserFeature_GetKeyIdbyName
| Purpose : Get ID of the user feature key bu its name
| Arguments : pcKeyName [in] Pointer to user feature key name.
| pUFKey [out] A UFKEY pointer to store returned UFKey
| Returns : If the function succeeds, the return value is MOS_STATUS_SUCCESS.
| If the function fails, the return value is a error code defined
| in mos_utilities.h.
| Comments :
\---------------------------------------------------------------------------*/
static MOS_STATUS _UserFeature_GetKeyIdbyName(const char *pcKeyName, void **pUFKey)
{
MOS_PUF_KEYLIST pKeyList;
int32_t iResult;
MOS_STATUS eStatus;
MOS_PUF_KEYLIST pTempNode;
pKeyList = nullptr;
iResult = -1;
if ( (eStatus = _UserFeature_DumpFile(szUserFeatureFile, &pKeyList)) !=
MOS_STATUS_SUCCESS )
{
MOS_FreeMemory(pKeyList);
return eStatus;
}
eStatus = MOS_STATUS_INVALID_PARAMETER;
for(pTempNode=pKeyList; pTempNode; pTempNode=pTempNode->pNext)
{
iResult = strcmp(pTempNode->pElem->pcKeyName, pcKeyName);
if ( iResult == 0 )
{
*pUFKey = pTempNode->pElem->UFKey;
eStatus = MOS_STATUS_SUCCESS;
break;
}
}
_UserFeature_FreeKeyList(pKeyList);
return eStatus;
}
/*----------------------------------------------------------------------------
| Name : _UserFeature_GetKeyNamebyId
| Purpose : Get name of the user feature key bu its ID
| Arguments : UFKey [in] ID of the user feature key
| pcKeyName [out] To store user feature key name.
| Returns : If the function succeeds, the return value is MOS_STATUS_SUCCESS.
| If the function fails, the return value is a error code defined
| in mos_utilities.h.
| Comments :
\---------------------------------------------------------------------------*/
static MOS_STATUS _UserFeature_GetKeyNamebyId(void *UFKey, char *pcKeyName)
{
MOS_PUF_KEYLIST pKeyList;
MOS_PUF_KEYLIST pTempNode;
MOS_STATUS eStatus;
pKeyList = nullptr;
switch((uintptr_t)UFKey)
{
case UFKEY_INTERNAL:
MOS_SecureStrcpy(pcKeyName, MAX_USERFEATURE_LINE_LENGTH, USER_FEATURE_KEY_INTERNAL);
eStatus = MOS_STATUS_SUCCESS;
break;
case UFKEY_EXTERNAL:
MOS_SecureStrcpy(pcKeyName, MAX_USERFEATURE_LINE_LENGTH, USER_FEATURE_KEY_EXTERNAL);
eStatus = MOS_STATUS_SUCCESS;
break;
default:
if ( (eStatus = _UserFeature_DumpFile(szUserFeatureFile, &pKeyList)) !=
MOS_STATUS_SUCCESS )
{
MOS_FreeMemory(pKeyList);
return eStatus;
}
eStatus = MOS_STATUS_UNKNOWN;
for(pTempNode=pKeyList;pTempNode;pTempNode=pTempNode->pNext)
{
if(pTempNode->pElem->UFKey == UFKey)
{
MOS_SecureStrcpy(pcKeyName, MAX_USERFEATURE_LINE_LENGTH, pTempNode->pElem->pcKeyName);
eStatus = MOS_STATUS_SUCCESS;
break;
}
}
_UserFeature_FreeKeyList(pKeyList);
break;
}
return eStatus;
}
/*----------------------------------------------------------------------------
| Name : MOS_CheckMountStatus
| Purpose : check mount status
| Arguments : pKeyWord [in] Keyword for the Mountpoint
| Returns : If the function succeeds, the return value is MOS_STATUS_SUCCESS.
| If the function fails, the return value is a error code defined
| in mos_utilities.h.
| Comments :
\---------------------------------------------------------------------------*/
MOS_STATUS MOS_CheckMountStatus(char *pKeyWord)
{
char sPartitionPath[MAX_UF_PATH] = {'\0'};
char sMountPoint[MAX_UF_PATH] = {'\0'};
char sSystemType[MAX_UF_PATH] = {'\0'};
char sTemp0[MAX_UF_PATH] = {'\0'};
char sTemp1[MAX_UF_PATH] = {'\0'};
char sTemp2[MAX_UF_PATH] = {'\0'};
FILE* file;
MOS_STATUS eStatus = MOS_STATUS_UNKNOWN;
file = fopen("/proc/mounts", "r");
MOS_OS_CHK_NULL(file);
MOS_OS_CHK_NULL(pKeyWord);
while( fscanf( file, "%255s %255s %255s %255s %255s %255s\n", sPartitionPath, sMountPoint, sSystemType, sTemp0, sTemp1, sTemp2 ) > 0 )
{
if( strcmp(sSystemType, pKeyWord) == 0 )
{
eStatus = MOS_STATUS_SUCCESS;
break;
}
if( strcmp(sMountPoint, pKeyWord) == 0 )
{
eStatus = MOS_STATUS_SUCCESS;
break;
}
}
finish:
if (file != nullptr)
{
fclose(file);
}
return eStatus;
}
#ifdef ANDROID
/*----------------------------------------------------------------------------
| Name : MOS_Strip_Chars
| Purpose : Strip some characters from a string
| Arguments : pstorestr [out] To store a striped string.
| pstring [in] string needed to be striped.
| pchars [in] stripped keyword.
| Returns : If the function succeeds, the return value is MOS_STATUS_SUCCESS.
| If the function fails, the return value is an error code defined
| in mos_utilities.h.
| Comments :
\---------------------------------------------------------------------------*/
MOS_STATUS MOS_StripChars(char *pstorestr, const char *pstring, const char *pchars)
{
int32_t counter = 0;
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
MOS_OS_CHK_NULL(pstring);
MOS_OS_CHK_NULL(pchars);
for ( ; *pstring; pstring++)
{
if (!strchr(pchars, *pstring))
{
pstorestr[ counter ] = *pstring;
++ counter;
}
}
pstorestr[counter] = 0;
finish:
return eStatus;
}
/*----------------------------------------------------------------------------
| Name : MOS_InitAndroidPropInfo
| Purpose : Init Android Property Info
| Returns : If the function succeeds, the return value is MOS_STATUS_SUCCESS.
| If the function fails, the return value is a error code defined
| in mos_utilities.h.
| Comments :
\---------------------------------------------------------------------------*/
MOS_STATUS MOS_InitAndroidPropInfo()
{
char prop[MOS_USER_CONTROL_MAX_DATA_SIZE];
MOS_STATUS eStatus = MOS_STATUS_UNKNOWN;
int32_t ret;
int32_t iUFKeyEnable;
MOS_USER_FEATURE_VALUE_DATA UserFeatureData;
eStatus = MOS_CheckMountStatus((char *)"/system");
if (eStatus == MOS_STATUS_SUCCESS)
{
eStatus = MOS_STATUS_UNKNOWN;
if (property_get("debug.LibVa.RegKeyEnable", prop, nullptr) > 0)
{
if (sscanf(prop, "%d\n", &iUFKeyEnable) > 0)
{
if (iUFKeyEnable == 1)
{
eStatus = MOS_STATUS_SUCCESS;
}
}
}
}
return eStatus;
}
/*----------------------------------------------------------------------------
| Name : MOS_GetAndroidPropPath
| Purpose : get AndroidProp path
| Arguments : pPath [out] store the path
| pUserFeature [in] User Feature data for input User Feature Key
| FuncType [in] Read/Write Type
| Returns : If the function succeeds, the return value is MOS_STATUS_SUCCESS.
| If the function fails, the return value is a error code defined
| in mos_utilities.h.
| Comments :
\---------------------------------------------------------------------------*/
MOS_STATUS MOS_GetAndroidPropPath(
char *pPath,
PMOS_USER_FEATURE_VALUE pUserFeature,
LINUX_UF_FUNC_TYPE FuncType)
{
char sPath[MAX_UF_PATH];
char sKey[MAX_UF_PATH];
char sFuncType[MAX_UF_PATH];
char pPrefixPath[MAX_UF_PATH];
char sUFName[MAX_UF_PATH];
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
MOS_OS_CHK_NULL(pUserFeature);
MOS_OS_CHK_NULL(pPath);
MOS_ZeroMemory(sPath, MAX_UF_PATH);
MOS_ZeroMemory(sKey, MAX_UF_PATH);
switch(pUserFeature->Type)
{
case MOS_USER_FEATURE_TYPE_USER:
MOS_SecureStrcpy(sKey, MAX_UF_PATH, UFINT_PATH_LINUX);
break;
case MOS_USER_FEATURE_TYPE_SYSTEM:
MOS_SecureStrcpy(sKey, MAX_UF_PATH, UFEXT_PATH_LINUX);
break;
default:
MOS_SecureStrcpy(sKey, MAX_UF_PATH, UFINT_PATH_LINUX);
break;
}// switch
MOS_ZeroMemory(sFuncType, MAX_UF_PATH);
switch(FuncType)
{
case LINUX_UF_FUNCTYPE_READ:
MOS_SecureStrcpy(sFuncType, MAX_UF_PATH, pUserFeature->pcPath);
break;
case LINUX_UF_FUNCTYPE_WRITE:
MOS_SecureStrcpy(sFuncType, MAX_UF_PATH, pUserFeature->pcWritePath);
break;
default:
MOS_SecureStrcpy(sFuncType, MAX_UF_PATH, pUserFeature->pcPath);
break;
}// switch
MOS_OS_CHK_STATUS(MOS_StripChars(sUFName,pUserFeature->pValueName," "));
snprintf(
sPath,
sizeof(sPath),
"%s.%s.%s",
sKey,
sFuncType,
sUFName);
MOS_SecureMemcpy(pPath, strlen(sPath)+1, sPath, strlen(sPath)+1);
finish:
return eStatus;
}
/*----------------------------------------------------------------------------
| Name : MOS_AndroidPropOpenKey
| Purpose : open a file for AndroidProp
| Arguments : pPath [in]
| Returns : If the function succeeds, the return value is MOS_STATUS_SUCCESS.
| If the function fails, the return value is a error code defined
| in mos_utilities.h.
| Comments :
\---------------------------------------------------------------------------*/
MOS_STATUS MOS_AndroidPropOpenKey(
char *pPath)
{
MOS_STATUS eStatus = MOS_STATUS_FILE_OPEN_FAILED;
char prop[MOS_USER_CONTROL_MAX_DATA_SIZE];
MOS_OS_CHK_NULL(pPath);
if (property_get(pPath, prop, nullptr) > 0)
{
eStatus = MOS_STATUS_SUCCESS;
}
finish:
return eStatus;
}
/*----------------------------------------------------------------------------
| Name : MOS_AndroidPropWriteValue
| Purpose : write a AndroidProp User Feature Data Value
| Arguments : pPath [in]
| pUserData [in] user feature key write value
| ValueType [in] Type of Data
| Returns : If the function succeeds, the return value is MOS_STATUS_SUCCESS.
| If the function fails, the return value is a error code defined
| in mos_utilities.h.
| Comments :
\---------------------------------------------------------------------------*/
MOS_STATUS MOS_AndroidPropWriteValue(
char *pPath,
PMOS_USER_FEATURE_VALUE_DATA pUserData,
MOS_USER_FEATURE_VALUE_TYPE ValueType)
{
MOS_STATUS eStatus = MOS_STATUS_USER_FEATURE_KEY_WRITE_FAILED;
char prop[MOS_USER_CONTROL_MAX_DATA_SIZE];
int32_t ret = 0;
MOS_OS_CHK_NULL(pPath);
MOS_OS_CHK_NULL(pUserData);
switch(ValueType)
{
case MOS_USER_FEATURE_VALUE_TYPE_BOOL:
ret = snprintf(prop, sizeof(prop), "%d\n", pUserData->bData);
break;
case MOS_USER_FEATURE_VALUE_TYPE_INT32:
ret = snprintf(prop, sizeof(prop), "%d\n", pUserData->i32Data);
break;
case MOS_USER_FEATURE_VALUE_TYPE_UINT32:
ret = snprintf(prop, sizeof(prop), "%u\n", pUserData->u32Data);
break;
case MOS_USER_FEATURE_VALUE_TYPE_INT64:
ret = snprintf(prop, sizeof(prop), "%" MOSd64 "\n", pUserData->i64Data);
break;
case MOS_USER_FEATURE_VALUE_TYPE_UINT64:
ret = snprintf(prop, sizeof(prop), "%" MOSu64 "\n", pUserData->u64Data);
break;
case MOS_USER_FEATURE_VALUE_TYPE_STRING:
if ((pUserData->StringData.pStringData != nullptr) && (strlen(pUserData->StringData.pStringData) != 0))
{
ret = snprintf(prop, sizeof(prop), "%s\n", pUserData->StringData.pStringData);
}
break;
default:
break;
}
if (ret > 0)
{
ret = property_set(pPath, prop);
if (ret == 0)
{
eStatus = MOS_STATUS_SUCCESS;
}
}
finish:
return eStatus;
}
/*----------------------------------------------------------------------------
| Name : MOS_AndroidPropCreateKey
| Purpose : set default value to AndroidProp User Feature Key according to userfeature
| Arguments : pUserFeature [in] value for ceated key
| FuncType [in] Type of function
| Returns : If the function succeeds, the return value is MOS_STATUS_SUCCESS.
| If the function fails, the return value is a error code defined
| in mos_utilities.h.
| Comments :
\---------------------------------------------------------------------------*/
MOS_STATUS MOS_AndroidPropCreateKey(
PMOS_USER_FEATURE_VALUE pUserFeature,
LINUX_UF_FUNC_TYPE FuncType)
{
char sPath[MAX_UF_PATH];
MOS_STATUS eStatus = MOS_STATUS_DIR_CREATE_FAILED;
MOS_USER_FEATURE_VALUE_DATA UserFeatureData;
MOS_USER_FEATURE_VALUE_TYPE ValueType = MOS_USER_FEATURE_VALUE_TYPE_INVALID;
char prop[MOS_USER_CONTROL_MAX_DATA_SIZE];
int32_t ret;
MOS_OS_CHK_NULL(pUserFeature);
MOS_ZeroMemory(&UserFeatureData, sizeof(UserFeatureData));
// create key
MOS_ZeroMemory(sPath, MAX_UF_PATH);
MOS_OS_CHK_STATUS(MOS_GetAndroidPropPath(sPath, pUserFeature, FuncType));
// set the default Data and Type value according to default value and type in pUserFeature.
MOS_OS_CHK_STATUS(MOS_AndroidPropWriteValue(sPath, &pUserFeature->Value, pUserFeature->ValueType));
finish:
return eStatus;
}
/*----------------------------------------------------------------------------
| Name : MOS_AndroidPropReadValue
| Purpose : read a AndroidProp User Feature Data Value
| Arguments : pPath [in]
| pUserData [out] To store user feature key value.
| ValueType [in] Type of Data
| Returns : If the function succeeds, the return value is MOS_STATUS_SUCCESS.
| If the function fails, the return value is a error code defined
| in mos_utilities.h.
| Comments :
\---------------------------------------------------------------------------*/
MOS_STATUS MOS_AndroidPropReadValue(
char *pPath,
PMOS_USER_FEATURE_VALUE_DATA pUserData,
MOS_USER_FEATURE_VALUE_TYPE ValueType)
{
MOS_USER_FEATURE_VALUE_DATA UserData;
char pcTmpStr[MOS_USER_CONTROL_MAX_DATA_SIZE];
MOS_STATUS eStatus = MOS_STATUS_USER_FEATURE_KEY_READ_FAILED;
char prop[MOS_USER_CONTROL_MAX_DATA_SIZE];
int32_t ret = 0;
MOS_OS_CHK_NULL(pPath);
MOS_OS_CHK_NULL(pUserData);
MOS_ZeroMemory(&UserData, sizeof(UserData));
if (property_get(pPath, prop, nullptr) > 0)
{
switch(ValueType)
{
case MOS_USER_FEATURE_VALUE_TYPE_BOOL:
ret = sscanf(prop, "%d\n", &pUserData->bData);
break;
case MOS_USER_FEATURE_VALUE_TYPE_INT32:
ret = sscanf(prop, "%d\n", &pUserData->i32Data);
break;
case MOS_USER_FEATURE_VALUE_TYPE_UINT32:
ret = sscanf(prop, "%u\n", &pUserData->u32Data);
break;
case MOS_USER_FEATURE_VALUE_TYPE_INT64:
ret = sscanf(prop, "%" MOSd64 "\n", &pUserData->i64Data);
break;
case MOS_USER_FEATURE_VALUE_TYPE_UINT64:
ret = sscanf(prop, "%" MOSu64 "\n", &pUserData->u64Data);
break;
case MOS_USER_FEATURE_VALUE_TYPE_STRING:
if( sscanf( prop, "%s\n", pcTmpStr) > 0 )
{
if (strlen(pcTmpStr) > 0)
{
MOS_SafeFreeMemory(pUserData->StringData.pStringData);
pUserData->StringData.pStringData = (char *)MOS_AllocAndZeroMemory(strlen(pcTmpStr)+1);
MOS_SecureMemcpy(pUserData->StringData.pStringData, strlen(pcTmpStr), pcTmpStr, MOS_MIN(strlen(pcTmpStr), MOS_USER_CONTROL_MAX_DATA_SIZE));
pUserData->StringData.uSize = strlen(pcTmpStr);
ret = pUserData->StringData.uSize;
}
}
break;
default:
break;
}
}
if (ret > 0)
{
eStatus = MOS_STATUS_SUCCESS;
}
finish:
return eStatus;
}
/*----------------------------------------------------------------------------
| Name : MOS_UserFeatureOpenKey_AndroidProp
| Purpose : Opens the specified user feature key.
| Arguments : UFKey [in] A handle to an open user feature key.
| lpSubKey [in] The name of the user feature subkey to be opened.
| ulOptions [in] This parameter is reserved and must be zero.
| samDesired [in] Reserved, could be any REGSAM type value
| phkResult [out] A pointer to a variable that receives a handle
| to the opened key.
| Returns : If the function succeeds, the return value is MOS_STATUS_SUCCESS.
| If the function fails, the return value is a error code defined
| in mos_utilities.h.
| Comments :
\---------------------------------------------------------------------------*/
MOS_STATUS MOS_UserFeatureOpenKey_AndroidProp(
void *UFKey,
const char *lpSubKey,
uint32_t ulOptions,
uint32_t samDesired,
void **phkResult)
{
char pcKeyName[MAX_USERFEATURE_LINE_LENGTH];
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
PMOS_USER_FEATURE_VALUE pUserFeature = nullptr;
char sPath[MAX_UF_PATH];
LINUX_UF_FUNC_TYPE FuncType = LINUX_UF_FUNCTYPE_INVALID;
MOS_UNUSED(UFKey);
MOS_UNUSED(ulOptions);
MOS_OS_CHK_NULL(lpSubKey);
pUserFeature = (PMOS_USER_FEATURE_VALUE)*phkResult;
MOS_OS_CHK_NULL(pUserFeature);
if( strcmp(lpSubKey, pUserFeature->pcWritePath) == 0 )
{
FuncType = LINUX_UF_FUNCTYPE_WRITE;
}
else if( strcmp(lpSubKey, pUserFeature->pcPath) == 0 )
{
FuncType = LINUX_UF_FUNCTYPE_READ;
}
MOS_ZeroMemory(sPath, MAX_UF_PATH);
MOS_OS_CHK_STATUS(MOS_GetAndroidPropPath(sPath, pUserFeature, FuncType));
if (MOS_AndroidPropOpenKey(sPath) != MOS_STATUS_SUCCESS)
{
// No Sub Key return directly
eStatus = MOS_STATUS_FILE_OPEN_FAILED;
// KEY_WRITE
if (samDesired == KEY_WRITE)
{
if (MOS_AndroidPropCreateKey(pUserFeature, FuncType) != MOS_STATUS_SUCCESS)
{
eStatus = MOS_STATUS_DIR_CREATE_FAILED;
}
}
else
{
eStatus = MOS_STATUS_FILE_OPEN_FAILED;
}
}
finish:
return eStatus;
}
/*----------------------------------------------------------------------------
| Name : MOS_UserFeatureGetValue_AndroidProp
| Purpose : Retrieves the type and data for the specified user feature value.
| Arguments : UFKey [in] A handle to an open user feature key.
| lpSubKey [in] The name of the user feature key. This key must be a
| subkey of the key specified by the UFKey parameter
| lpValue [in] The name of the user feature value.
| dwFlags [in] Reserved, could be any uint32_t type value
| pdwType [out] A pointer to a variable that receives a code
| indicating the type of data stored in the
| specified value.
| pvData [out] A pointer to a buffer that receives the value's
| data.
| pcbData [out] A pointer to a variable that specifies the size
| of the buffer pointed to by the pvData parameter,
| in bytes.
| Returns : If the function succeeds, the return value is MOS_STATUS_SUCCESS.
| If the function fails, the return value is a error code defined
| in mos_utilities.h.
| Comments :
\---------------------------------------------------------------------------*/
MOS_STATUS MOS_UserFeatureGetValue_AndroidProp(
void *UFKey,
const char *lpSubKey,
const char *lpValue,
uint32_t dwFlags,
uint32_t *pdwType,
void *pvData,
uint32_t *pcbData)
{
char pcKeyName[MAX_USERFEATURE_LINE_LENGTH];
int32_t dData;
int32_t index = 0;
PMOS_USER_FEATURE_VALUE pSettingsValue;
PMOS_USER_FEATURE_VALUE pUserFeature = nullptr;
char sPath[MAX_UF_PATH];
MOS_USER_FEATURE_VALUE_DATA UserFeatureData;
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
MOS_UNUSED(lpSubKey);
MOS_UNUSED(lpValue);
MOS_UNUSED(dwFlags);
MOS_UNUSED(pdwType);
if(UFKey == nullptr)
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
goto finish;
}
pUserFeature = (PMOS_USER_FEATURE_VALUE)UFKey;
MOS_ZeroMemory(sPath, MAX_UF_PATH);
MOS_OS_CHK_STATUS(MOS_GetAndroidPropPath(sPath, pUserFeature, LINUX_UF_FUNCTYPE_READ));
// Read Type
MOS_ZeroMemory(&UserFeatureData, sizeof(UserFeatureData));
if (MOS_AndroidPropReadValue(sPath, &UserFeatureData, pUserFeature->ValueType) == MOS_STATUS_SUCCESS)
{
// get key content from user feature
switch(pUserFeature->ValueType)
{
case MOS_USER_FEATURE_VALUE_TYPE_BINARY:
*(int32_t*)pvData = UserFeatureData.bData;
*(uint32_t*)pcbData = sizeof(int32_t);
break;
case MOS_USER_FEATURE_VALUE_TYPE_INT32:
*(int32_t*)pvData = UserFeatureData.i32Data;
*(uint32_t*)pcbData = sizeof(int32_t);
break;
case MOS_USER_FEATURE_VALUE_TYPE_INT64:
*(int64_t*)pvData = UserFeatureData.i64Data;
*(uint32_t*)pcbData = sizeof(int64_t);
break;
case MOS_USER_FEATURE_VALUE_TYPE_UINT32:
*(uint32_t*)pvData = UserFeatureData.u32Data;
*(uint32_t*)pcbData = sizeof(uint32_t);
break;
case MOS_USER_FEATURE_VALUE_TYPE_UINT64:
*(uint64_t*)pvData = UserFeatureData.u64Data;
*(uint32_t*)pcbData = sizeof(uint64_t);
break;
case MOS_USER_FEATURE_VALUE_TYPE_STRING:
MOS_SecureMemcpy(pvData, UserFeatureData.StringData.uSize, UserFeatureData.StringData.pStringData, UserFeatureData.StringData.uSize);
MOS_SafeFreeMemory(UserFeatureData.StringData.pStringData);
*(uint32_t*)pcbData = UserFeatureData.StringData.uSize;
break;
default:
break;
}// switch
}
else
{
eStatus = MOS_STATUS_FILE_NOT_FOUND;
}
finish:
return eStatus;
}
/*----------------------------------------------------------------------------
| Name : MOS_UserFeatureSetValueEx_AndroidProp
| Purpose : Sets the data and type of a specified value under a user feature key.
| Arguments : UFKey [in] A handle to an open user feature key.
| lpValueName [in] The name of the user feature value.
| Reserved [in] This parameter is reserved and must be NULL.
| dwType [in] The type of data pointed to by the lpData
| parameter.
| lpData [in] The data to be stored.
| cbData [in] The size of the information pointed to by the
| lpData parameter, in bytes.
| Returns : If the function succeeds, the return value is MOS_STATUS_SUCCESS.
| If the function fails, the return value is a error code defined
| in mos_utilities.h.
| Comments :
\---------------------------------------------------------------------------*/
MOS_STATUS MOS_UserFeatureSetValueEx_AndroidProp(
void *UFKey,
const char *lpValueName,
uint32_t Reserved,
uint32_t dwType,
uint8_t *lpData,
uint32_t cbData)
{
char pcKeyName[MAX_USERFEATURE_LINE_LENGTH];
int32_t dData;
int32_t index = 0;
uint32_t ui;
PMOS_USER_FEATURE_VALUE pUserFeature = nullptr;
char sPath[MAX_UF_PATH];
MOS_USER_FEATURE_VALUE_DATA UserFeatureData;
MOS_USER_FEATURE_VALUE_TYPE ValueType = MOS_USER_FEATURE_VALUE_TYPE_INVALID;
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
MOS_UNUSED(lpValueName);
MOS_UNUSED(Reserved);
MOS_UNUSED(dwType);
if(UFKey == nullptr)
{
eStatus = MOS_STATUS_INVALID_PARAMETER;
goto finish;
}
pUserFeature = (PMOS_USER_FEATURE_VALUE)UFKey;
for (ui = 0; ui < pUserFeature->uiNumOfValues; ui++)
{
// Check the Key exist or not
MOS_ZeroMemory(sPath, MAX_UF_PATH);
MOS_OS_CHK_STATUS(MOS_GetAndroidPropPath(sPath, pUserFeature, LINUX_UF_FUNCTYPE_WRITE));
if (MOS_AndroidPropOpenKey(sPath) != MOS_STATUS_SUCCESS){
// create the Key according to pFeatureValue->ValueType
if( MOS_AndroidPropCreateKey(pUserFeature, LINUX_UF_FUNCTYPE_WRITE) != MOS_STATUS_SUCCESS )
{
eStatus = MOS_STATUS_DIR_CREATE_FAILED;
goto finish;
}
}
MOS_ZeroMemory(&UserFeatureData, sizeof(UserFeatureData));
ValueType = (MOS_USER_FEATURE_VALUE_TYPE)pUserFeature->ValueType;
switch(ValueType)
{
case MOS_USER_FEATURE_VALUE_TYPE_BINARY:
UserFeatureData.bData =*(int32_t*)lpData ;
break;
case MOS_USER_FEATURE_VALUE_TYPE_INT32:
UserFeatureData.i32Data =*(int32_t*)lpData ;
break;
case MOS_USER_FEATURE_VALUE_TYPE_INT64:
UserFeatureData.i64Data =*(int64_t*)lpData;
break;
case MOS_USER_FEATURE_VALUE_TYPE_UINT32:
UserFeatureData.u32Data = *(uint32_t*)lpData;
break;
case MOS_USER_FEATURE_VALUE_TYPE_UINT64:
UserFeatureData.u64Data =*(uint64_t*)lpData;
break;
case MOS_USER_FEATURE_VALUE_TYPE_STRING:
UserFeatureData.StringData.pStringData =(char *)lpData;
UserFeatureData.StringData.uSize = cbData;
break;
default:
break;
}//switch
if (MOS_AndroidPropWriteValue(sPath, &UserFeatureData, ValueType) != MOS_STATUS_SUCCESS)
{
eStatus = MOS_STATUS_USER_FEATURE_KEY_WRITE_FAILED;
goto finish;
}
}
finish:
return eStatus;
}
#endif
/*----------------------------------------------------------------------------
| Name : MOS_UserFeatureOpenKey_File
| Purpose : Opens the specified user feature key.
| Arguments : UFKey [in] A handle to an open user feature key.
| lpSubKey [in] The name of the user feature subkey to be opened.
| ulOptions [in] This parameter is reserved and must be zero.
| samDesired [in] Reserved, could be any REGSAM type value
| phkResult [out] A pointer to a variable that receives a handle
| to the opened key.
| Returns : If the function succeeds, the return value is MOS_STATUS_SUCCESS.
| If the function fails, the return value is a error code defined
| in mos_utilities.h.
| Comments :
\---------------------------------------------------------------------------*/
MOS_STATUS MOS_UserFeatureOpenKey_File(
void *UFKey,
const char *lpSubKey,
uint32_t ulOptions, // reserved
uint32_t samDesired,
void **phkResult)
{
char pcKeyName[MAX_USERFEATURE_LINE_LENGTH];
MOS_STATUS iRet;
uintptr_t h_key = (uintptr_t)UFKey;
MOS_UNUSED(ulOptions);
MOS_UNUSED(samDesired);
if((h_key == 0) /*|| (lpSubKey == nullptr)*/ || (phkResult == nullptr)) //[SH]: subkey can be NULL???
{
return MOS_STATUS_INVALID_PARAMETER;
}
MOS_ZeroMemory(pcKeyName, MAX_USERFEATURE_LINE_LENGTH*sizeof(char));
switch(h_key)
{
case UFKEY_INTERNAL:
MOS_SecureStrcpy(pcKeyName, MAX_USERFEATURE_LINE_LENGTH, USER_FEATURE_KEY_INTERNAL);
break;
case UFKEY_EXTERNAL:
MOS_SecureStrcpy(pcKeyName, MAX_USERFEATURE_LINE_LENGTH, USER_FEATURE_KEY_EXTERNAL);
break;
default:
break;
}
MOS_SecureStrcat(pcKeyName, sizeof(pcKeyName), lpSubKey);
iRet = _UserFeature_GetKeyIdbyName(pcKeyName, phkResult);
return iRet;
}
/*----------------------------------------------------------------------------
| Name : MOS_UserFeatureGetValue_File
| Purpose : Retrieves the type and data for the specified user feature value.
| Arguments : UFKey [in] A handle to an open user feature key.
| lpSubKey [in] The name of the user feature key. This key must be a
| subkey of the key specified by the UFKey parameter
| lpValue [in] The name of the user feature value.
| dwFlags [in] Reserved, could be any uint32_t type value
| pdwType [out] A pointer to a variable that receives a code
| indicating the type of data stored in the
| specified value.
| pvData [out] A pointer to a buffer that receives the value's
| data.
| pcbData [out] A pointer to a variable that specifies the size
| of the buffer pointed to by the pvData parameter,
| in bytes.
| Returns : If the function succeeds, the return value is MOS_STATUS_SUCCESS.
| If the function fails, the return value is a error code defined
| in mos_utilities.h.
| Comments :
\---------------------------------------------------------------------------*/
MOS_STATUS MOS_UserFeatureGetValue_File(
void *UFKey,
const char *lpSubKey,
const char *lpValue,
uint32_t dwFlags,
uint32_t *pdwType,
void *pvData,
uint32_t *pcbData)
{
char pcKeyName[MAX_USERFEATURE_LINE_LENGTH];
MOS_STATUS eStatus;
MOS_UNUSED(dwFlags);
if(UFKey == nullptr)
{
return MOS_STATUS_INVALID_PARAMETER;
}
eStatus = MOS_STATUS_UNKNOWN;
MOS_ZeroMemory(pcKeyName, MAX_USERFEATURE_LINE_LENGTH * sizeof(char));
if ( (eStatus = _UserFeature_GetKeyNamebyId(UFKey,pcKeyName)) != MOS_STATUS_SUCCESS)
{
return eStatus;
}
if(lpSubKey != nullptr)
{
MOS_SecureStrcat(pcKeyName, sizeof(pcKeyName), lpSubKey);
}
eStatus = _UserFeature_QueryValue(pcKeyName,
lpValue,
(uint32_t*)pdwType,
pvData,
(int32_t*)pcbData);
return eStatus;
}
/*----------------------------------------------------------------------------
| Name : MOS_UserFeatureSetValueEx_File
| Purpose : Sets the data and type of a specified value under a user feature key.
| Arguments : UFKey [in] A handle to an open user feature key.
| lpValueName [in] The name of the user feature value.
| Reserved in] This parameter is reserved and must be NULL.
| dwType [in] The type of data pointed to by the lpData
| parameter.
| lpData [in] The data to be stored.
| cbData [in] The size of the information pointed to by the
| lpData parameter, in bytes.
| Returns : If the function succeeds, the return value is MOS_STATUS_SUCCESS.
| If the function fails, the return value is a error code defined
| in mos_utilities.h.
| Comments :
\---------------------------------------------------------------------------*/
MOS_STATUS MOS_UserFeatureSetValueEx_File(
void *UFKey,
const char *lpValueName,
uint32_t Reserved,
uint32_t dwType,
uint8_t *lpData,
uint32_t cbData)
{
char pcKeyName[MAX_USERFEATURE_LINE_LENGTH];
MOS_STATUS eStatus;
MOS_UNUSED(Reserved);
if (UFKey == nullptr)
{
return MOS_STATUS_INVALID_PARAMETER;
}
MOS_ZeroMemory(pcKeyName, MAX_USERFEATURE_LINE_LENGTH*sizeof(char));
if ((eStatus = _UserFeature_GetKeyNamebyId(UFKey,pcKeyName)) != MOS_STATUS_SUCCESS)
{
return eStatus;
}
eStatus = _UserFeature_SetValue(pcKeyName,lpValueName,dwType,lpData,cbData);
return eStatus;
}
MOS_STATUS MOS_OS_Utilities_Init(PMOS_USER_FEATURE_KEY_PATH_INFO userFeatureKeyPathInfo)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
MOS_UNUSED(userFeatureKeyPathInfo);
// lock mutex to avoid multi init in multi-threading env
MOS_LockMutex(&gMosUtilMutex);
#if (_DEBUG || _RELEASE_INTERNAL)
// Get use user feature file from env, instead of default.
FILE* fp = nullptr;
static char* tmpFile = getenv("GFX_FEATURE_FILE");
if (tmpFile != nullptr)
{
if ((fp = fopen(tmpFile, "r")) != nullptr)
{
szUserFeatureFile = tmpFile;
fclose(fp);
MOS_OS_NORMALMESSAGE("using %s for USER_FEATURE_FILE", szUserFeatureFile);
}
else
{
MOS_OS_ASSERTMESSAGE("Can't open %s for USER_FEATURE_FILE!!!", tmpFile);
eStatus = MOS_STATUS_FILE_NOT_FOUND;
goto finish;
}
}
#endif
if (uiMOSUtilInitCount == 0)
{
pUFKeyOps = (PUFKEYOPS)MOS_AllocAndZeroMemory(sizeof(UFKEYOPS));
MOS_OS_CHK_NULL(pUFKeyOps);
#ifdef ANDROID
if (MOS_InitAndroidPropInfo() == MOS_STATUS_SUCCESS)
{
pUFKeyOps->pfnUserFeatureOpenKey = MOS_UserFeatureOpenKey_AndroidProp;
pUFKeyOps->pfnUserFeatureGetValue = MOS_UserFeatureGetValue_AndroidProp;
pUFKeyOps->pfnUserFeatureSetValueEx = MOS_UserFeatureSetValueEx_AndroidProp;
}
else
#endif
{
pUFKeyOps->pfnUserFeatureOpenKey = MOS_UserFeatureOpenKey_File;
pUFKeyOps->pfnUserFeatureGetValue = MOS_UserFeatureGetValue_File;
pUFKeyOps->pfnUserFeatureSetValueEx = MOS_UserFeatureSetValueEx_File;
}
//Init MOS User Feature Key from mos desc table
eStatus = MOS_DeclareUserFeatureKeysForAllDescFields();
#if _MEDIA_RESERVED
codecUserFeatureExt = new CodechalUserSettingsMgr();
vpUserFeatureExt = new VphalUserSettingsMgr();
#endif // _MEDIA_RESERVED
eStatus = MOS_GenerateUserFeatureKeyXML();
#if MOS_MESSAGES_ENABLED
// Initialize MOS message params structure and HLT
MOS_MessageInit();
#endif // MOS_MESSAGES_ENABLED
MosMemAllocCounter = 0;
MosMemAllocFakeCounter = 0;
MosMemAllocCounterGfx = 0;
MOS_TraceEventInit();
}
uiMOSUtilInitCount++;
finish:
MOS_UnlockMutex(&gMosUtilMutex);
return eStatus;
}
MOS_STATUS MOS_OS_Utilities_Close()
{
int32_t MemoryCounter = 0;
MOS_USER_FEATURE_VALUE_WRITE_DATA UserFeatureWriteData = __NULL_USER_FEATURE_VALUE_WRITE_DATA__;
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
// lock mutex to avoid multi close in multi-threading env
MOS_LockMutex(&gMosUtilMutex);
uiMOSUtilInitCount--;
if (uiMOSUtilInitCount == 0 )
{
MOS_TraceEventClose();
MosMemAllocCounter -= MosMemAllocFakeCounter;
MemoryCounter = MosMemAllocCounter + MosMemAllocCounterGfx;
MosMemAllocCounterNoUserFeature = MosMemAllocCounter;
MosMemAllocCounterNoUserFeatureGfx = MosMemAllocCounterGfx;
MOS_OS_VERBOSEMESSAGE("MemNinja leak detection end");
UserFeatureWriteData.Value.i32Data = MemoryCounter;
UserFeatureWriteData.ValueID = __MEDIA_USER_FEATURE_VALUE_MEMNINJA_COUNTER_ID;
MOS_UserFeature_WriteValues_ID(NULL, &UserFeatureWriteData, 1);
eStatus = MOS_DestroyUserFeatureKeysForAllDescFields();
#if _MEDIA_RESERVED
if (codecUserFeatureExt)
{
delete codecUserFeatureExt;
codecUserFeatureExt = nullptr;
}
if (vpUserFeatureExt)
{
delete vpUserFeatureExt;
vpUserFeatureExt = nullptr;
}
#endif // _MEDIA_RESERVED
#if (_DEBUG || _RELEASE_INTERNAL)
// MOS maintains a reference counter,
// so if there still is another active lib instance, logs would still be printed.
MOS_MessageClose();
#endif
MOS_FreeMemory(pUFKeyOps);
pUFKeyOps = nullptr;
}
MOS_UnlockMutex(&gMosUtilMutex);
return eStatus;
}
MOS_STATUS MOS_UserFeatureOpenKey(
void *UFKey,
const char *lpSubKey,
uint32_t ulOptions,
uint32_t samDesired,
void **phkResult)
{
char pcKeyName[MAX_USERFEATURE_LINE_LENGTH];
MOS_STATUS iRet;
intptr_t h_key = (intptr_t)UFKey;
if((h_key == 0) /*|| (lpSubKey == nullptr)*/ || (phkResult == nullptr)) //[SH]: subkey can be NULL???
{
return MOS_STATUS_INVALID_PARAMETER;
}
if (( pUFKeyOps != nullptr) && (pUFKeyOps->pfnUserFeatureOpenKey != nullptr))
{
return pUFKeyOps->pfnUserFeatureOpenKey(UFKey, lpSubKey, ulOptions, samDesired, phkResult);
}
else
{
return MOS_UserFeatureOpenKey_File(UFKey, lpSubKey, ulOptions, samDesired, phkResult);
}
}
MOS_STATUS MOS_UserFeatureCloseKey(void *UFKey)
{
MOS_UNUSED(UFKey);
//always return success, because we actually dong't have a key opened.
return MOS_STATUS_SUCCESS;
}
MOS_STATUS MOS_UserFeatureGetValue(
void *UFKey,
const char *lpSubKey,
const char *lpValue,
uint32_t dwFlags,
uint32_t *pdwType,
void *pvData,
uint32_t *pcbData)
{
char pcKeyName[MAX_USERFEATURE_LINE_LENGTH];
MOS_STATUS eStatus;
if(UFKey == nullptr)
{
return MOS_STATUS_INVALID_PARAMETER;
}
eStatus = MOS_STATUS_UNKNOWN;
if (( pUFKeyOps != nullptr) && (pUFKeyOps->pfnUserFeatureGetValue != nullptr))
{
return pUFKeyOps->pfnUserFeatureGetValue(UFKey, lpSubKey, lpValue, dwFlags, pdwType, pvData, pcbData);
}
else
{
return MOS_UserFeatureGetValue_File(UFKey, lpSubKey, lpValue, dwFlags, pdwType, pvData, pcbData);
}
}
MOS_STATUS MOS_UserFeatureQueryValueEx(
void *UFKey,
char *lpValueName,
uint32_t *lpReserved,
uint32_t *lpType,
char *lpData,
uint32_t *lpcbData)
{
MOS_UNUSED(lpReserved);
return MOS_UserFeatureGetValue(UFKey, "", lpValueName, 0, lpType, lpData, lpcbData);
}
MOS_STATUS MOS_UserFeatureSetValueEx(
void *UFKey,
const char *lpValueName,
uint32_t Reserved,
uint32_t dwType,
uint8_t *lpData,
uint32_t cbData)
{
char pcKeyName[MAX_USERFEATURE_LINE_LENGTH];
MOS_STATUS eStatus;
if (UFKey == nullptr)
{
return MOS_STATUS_INVALID_PARAMETER;
}
if (( pUFKeyOps != nullptr) && (pUFKeyOps->pfnUserFeatureSetValueEx!= nullptr))
{
return pUFKeyOps->pfnUserFeatureSetValueEx(UFKey, lpValueName, Reserved, dwType, lpData, cbData);
}
else
{
return MOS_UserFeatureSetValueEx_File(UFKey, lpValueName, Reserved, dwType, lpData, cbData);
}
}
// Event Related Functions: Android does not support these
#ifndef ANDROID
MOS_STATUS MOS_UserFeatureNotifyChangeKeyValue(
void *UFKey,
int32_t bWatchSubtree,
HANDLE hEvent,
int32_t fAsynchronous)
{
key_t key;
int32_t semid;
struct sembuf operation[1] ;
key = ftok(szUserFeatureFile,1);
semid = semget(key,1,0);
//change semaphore
operation[0].sem_op = 1;
operation[0].sem_num = 0;
operation[0].sem_flg = SEM_UNDO;
semop(semid, operation, 1);
return MOS_STATUS_SUCCESS;
}
HANDLE MOS_CreateEventEx(
void *lpEventAttributes,
char *lpName,
uint32_t dwFlags)
{
int32_t semid;
key_t key;
union semun
{
int32_t val;
struct semid_ds *Buf;
unsigned short *array;
} semctl_arg;
semid = 0;
//Generate a unique key, U can also supply a value instead
key = ftok(szUserFeatureFile, 1);
semid = semget(key, 1, 0666 | IPC_CREAT );
semctl_arg.val = 0; //Setting semval to 0
semctl(semid, 0, SETVAL, semctl_arg);
HANDLE ret = reinterpret_cast<HANDLE>(semid);
return ret;
}
int32_t MOS_UserFeatureWaitForSingleObject(
PTP_WAIT* phNewWaitObject,
HANDLE hObject,
void *Callback,
void *Context)
{
int32_t iRet;
int32_t semid;
struct sembuf operation[1];
pid_t pid;
MOS_UserFeatureCallback pCallback;
LARGE_INTEGER largeInteger;
pCallback = (MOS_UserFeatureCallback)Callback;
iRet = 0;
largeInteger.QuadPart = (int64_t)hObject;
semid = largeInteger.u.LowPart;
if ((pid=fork()) == -1)
{
printf("error\n");
}
else if(pid == 0)
{
while(1)
{
operation[0].sem_op = -1;
operation[0].sem_num = 0;
//now waiting
semop(semid, operation, 1);
pCallback(Context, 0);
}
exit(0);
}
else
{
iRet = pid;
}
*phNewWaitObject = reinterpret_cast<PTP_WAIT>(iRet);
return (iRet != 0);
}
int32_t MOS_UnregisterWaitEx(PTP_WAIT hWaitHandle)
{
int32_t iPid;
LARGE_INTEGER largeInteger;
largeInteger.QuadPart = (int64_t)hWaitHandle;
iPid = largeInteger.u.LowPart;
kill(iPid,SIGKILL);
return true;
}
/*----------------------------------------------------------------------------
| Name : GMMDebugBreak
| Purpose : Fix compiling issue for Gmmlib on debug mode
| Arguments : N/A
| Returns : void
| Calls : N/A
| Callers : Several
\---------------------------------------------------------------------------*/
void GMMDebugBreak(const char *file, const char *function,const int32_t line)
{
// Not required for media driver
return;
}
/*----------------------------------------------------------------------------
| Name : GMMPrintMessage
| Purpose : Fix compiling issue for Gmmlib on debug mode
| Arguments : N/A
| Returns : void
| Calls : N/A
| Callers : Several
\---------------------------------------------------------------------------*/
void GMMPrintMessage(int32_t debuglevel, const char *function, ...)
{
// Not Required for media driver
return;
}
#else // ANDROID
MOS_STATUS MOS_UserFeatureNotifyChangeKeyValue(
void *UFKey,
int32_t bWatchSubtree,
HANDLE hEvent,
int32_t fAsynchronous)
{
MOS_UNUSED(UFKey);
MOS_UNUSED(bWatchSubtree);
MOS_UNUSED(hEvent);
MOS_UNUSED(fAsynchronous);
return MOS_STATUS_SUCCESS;
}
HANDLE MOS_CreateEventEx(
void *lpEventAttributes,
char *lpName,
uint32_t dwFlags)
{
MOS_UNUSED(lpEventAttributes);
MOS_UNUSED(lpName);
MOS_UNUSED(dwFlags);
return (HANDLE)1;
}
int32_t MOS_UserFeatureWaitForSingleObject(
PTP_WAIT* phNewWaitObject,
HANDLE hObject,
void *Callback,
void *Context)
{
MOS_UNUSED(phNewWaitObject);
MOS_UNUSED(hObject);
MOS_UNUSED(Callback);
MOS_UNUSED(Context);
return true;
}
int32_t MOS_UnregisterWaitEx(PTP_WAIT hWaitHandle)
{
MOS_UNUSED(hWaitHandle);
return true;
}
#endif // !ANDROID
MOS_STATUS MOS_UserFeature_ParsePath(
PMOS_USER_FEATURE_INTERFACE pOsUserFeatureInterface,
char * const pInputPath,
PMOS_USER_FEATURE_TYPE pUserFeatureType,
char **ppSubPath)
{
char *pValue;
MOS_USER_FEATURE_TYPE UserFeatureType;
size_t uUFKeyLen;
size_t uHKeyLen;
size_t uValLen;
size_t uSepLen;
MOS_UNUSED(pOsUserFeatureInterface);
//-------------------------------------------
// the UserFeature interface is not currently an actual interface, just a collection
// of functions, so pOsUserFeatureInterface will always be nullptr until this changes
//MOS_OS_ASSERT(pOsUserFeatureInterface);
MOS_OS_ASSERT(pInputPath);
MOS_OS_ASSERT(strlen(pInputPath) > 0);
MOS_OS_ASSERT(pUserFeatureType);
MOS_OS_ASSERT(ppSubPath);
//-------------------------------------------
pValue = nullptr;
pValue = strstr(pInputPath, MOS_UF_SEPARATOR);
if (!pValue)
{
MOS_OS_ASSERTMESSAGE("Invalid user feature key %s.", pInputPath);
return MOS_STATUS_INVALID_PARAMETER;
}
uUFKeyLen = strlen(pInputPath);
uValLen = strlen(pValue);
uSepLen = strlen(MOS_UF_SEPARATOR);
uHKeyLen = uUFKeyLen - uValLen;
if (uHKeyLen == 0)
{
MOS_OS_ASSERTMESSAGE("Invalid user feature key %s. Path separator in the begining.", pInputPath);
return MOS_STATUS_INVALID_PARAMETER;
}
if (uValLen <= uSepLen)
{
MOS_OS_ASSERTMESSAGE("Invalid user feature key %s. No value after path separator.", pInputPath);
return MOS_STATUS_INVALID_PARAMETER;
}
if ((uHKeyLen == strlen(MOS_UFKEY_EXT)) &&
(strncmp(pInputPath, MOS_UFKEY_EXT, uHKeyLen) == 0))
{
UserFeatureType = MOS_USER_FEATURE_TYPE_SYSTEM;
}
else if ((uHKeyLen == strlen(MOS_UFKEY_INT)) &&
(strncmp(pInputPath, MOS_UFKEY_INT, uHKeyLen) == 0))
{
UserFeatureType = MOS_USER_FEATURE_TYPE_USER;
}
else
{
MOS_OS_ASSERTMESSAGE("Invalid user feature key %s. Expected %s or %s.", pInputPath, MOS_UFKEY_EXT, MOS_UFKEY_INT);
return MOS_STATUS_INVALID_PARAMETER;
}
pValue = pValue + uSepLen;
*pUserFeatureType = UserFeatureType;
*ppSubPath = pValue;
return MOS_STATUS_SUCCESS;
}
uint32_t MOS_GetLogicalCoreNumber()
{
return sysconf(_SC_NPROCESSORS_CONF);
}
MOS_THREADHANDLE MOS_CreateThread(
void *ThreadFunction,
void *ThreadData)
{
MOS_THREADHANDLE Thread;
if (0 != pthread_create(&Thread, nullptr, (void *(*)(void *))ThreadFunction, ThreadData))
{
Thread = 0;
MOS_OS_ASSERTMESSAGE("Create thread failed.");
}
return Thread;
}
uint32_t MOS_GetThreadId(
MOS_THREADHANDLE hThread)
{
MOS_UNUSED(hThread);
return 0;
}
uint32_t MOS_GetCurrentThreadId()
{
return (uint32_t)pthread_self();
}
MOS_STATUS MOS_WaitThread(
MOS_THREADHANDLE hThread)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
if (hThread == 0)
{
MOS_OS_ASSERTMESSAGE("MOS wait thread failed, invalid thread handle.");
eStatus = MOS_STATUS_INVALID_PARAMETER;
}
else if (0 != pthread_join(hThread, nullptr))
{
MOS_OS_ASSERTMESSAGE("Failed to join thread.");
eStatus = MOS_STATUS_UNKNOWN;
}
return eStatus;
}
PMOS_MUTEX MOS_CreateMutex()
{
PMOS_MUTEX pMutex;
pMutex = (PMOS_MUTEX)MOS_AllocMemory(sizeof(*pMutex));
if (pMutex != nullptr)
{
if (pthread_mutex_init(pMutex, nullptr))
{
MOS_FreeMemory(pMutex);
pMutex = nullptr;
}
}
return pMutex;
}
MOS_STATUS MOS_DestroyMutex(PMOS_MUTEX pMutex)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
if (pMutex)
{
if (pthread_mutex_destroy(pMutex))
{
eStatus = MOS_STATUS_UNKNOWN;
}
MOS_FreeMemory(pMutex);
}
return eStatus;
}
MOS_STATUS MOS_LockMutex(PMOS_MUTEX pMutex)
{
MOS_OS_CHK_NULL_RETURN(pMutex);
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
if (pthread_mutex_lock(pMutex))
{
eStatus = MOS_STATUS_UNKNOWN;
}
return eStatus;
}
MOS_STATUS MOS_UnlockMutex(PMOS_MUTEX pMutex)
{
MOS_OS_CHK_NULL_RETURN(pMutex);
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
if (pthread_mutex_unlock(pMutex))
{
eStatus = MOS_STATUS_UNKNOWN;
}
return eStatus;
}
PMOS_SEMAPHORE MOS_CreateSemaphore(
uint32_t uiInitialCount,
uint32_t uiMaximumCount)
{
PMOS_SEMAPHORE pSemaphore = nullptr;
MOS_UNUSED(uiMaximumCount);
pSemaphore = (PMOS_SEMAPHORE)MOS_AllocMemory(sizeof(*pSemaphore));
if (!pSemaphore)
return nullptr;
if (sem_init(pSemaphore, 0, uiInitialCount))
{
MOS_SafeFreeMemory(pSemaphore);
pSemaphore = nullptr;
}
return pSemaphore;
}
MOS_STATUS MOS_DestroySemaphore(
PMOS_SEMAPHORE pSemaphore)
{
MOS_SafeFreeMemory(pSemaphore);
return MOS_STATUS_SUCCESS;
}
MOS_STATUS MOS_WaitSemaphore(
PMOS_SEMAPHORE pSemaphore,
uint32_t uiMilliseconds)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
if (uiMilliseconds == INFINITE)
{
if (sem_wait(pSemaphore))
{
eStatus = MOS_STATUS_UNKNOWN;
}
}
else
{
struct timespec time = {
(int32_t)uiMilliseconds / 1000000,
((int32_t)uiMilliseconds % 1000000) * 1000};
if (sem_timedwait(pSemaphore, &time))
{
eStatus = MOS_STATUS_UNKNOWN;
}
}
return eStatus;
}
MOS_STATUS MOS_PostSemaphore(
PMOS_SEMAPHORE pSemaphore,
uint32_t uiPostCount)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
if (uiPostCount > 0)
{
while (uiPostCount--)
{
if (sem_post(pSemaphore))
{
eStatus = MOS_STATUS_UNKNOWN;
break;
}
}
}
else
{
eStatus = MOS_STATUS_UNKNOWN;
}
return eStatus;
}
uint32_t MOS_WaitForSingleObject(
void *pObject,
uint32_t uiMilliseconds)
{
uint32_t WaitSignal = 0;
MOS_UNUSED(pObject);
MOS_UNUSED(uiMilliseconds);
return WaitSignal;
}
uint32_t MOS_WaitForMultipleObjects(
uint32_t uiThreadCount,
void **ppObjects,
uint32_t bWaitAll,
uint32_t uiMilliseconds)
{
MOS_UNUSED(uiThreadCount);
MOS_UNUSED(ppObjects);
MOS_UNUSED(bWaitAll);
MOS_UNUSED(uiMilliseconds);
return 0;
}
int32_t MOS_AtomicIncrement(
int32_t *pValue)
{
return __sync_fetch_and_add(pValue, 1);
}
int32_t MOS_AtomicDecrement(
int32_t *pValue)
{
return __sync_fetch_and_sub(pValue, 1);
}
VAStatus MOS_StatusToOsResult(
MOS_STATUS eStatus)
{
switch (eStatus)
{
case MOS_STATUS_SUCCESS: return VA_STATUS_SUCCESS;
case MOS_STATUS_NO_SPACE: return VA_STATUS_ERROR_ALLOCATION_FAILED;
case MOS_STATUS_INVALID_PARAMETER: return VA_STATUS_ERROR_INVALID_PARAMETER;
case MOS_STATUS_INVALID_HANDLE: return VA_STATUS_ERROR_INVALID_BUFFER;
case MOS_STATUS_NULL_POINTER: return VA_STATUS_ERROR_INVALID_CONTEXT;
default: return VA_STATUS_ERROR_OPERATION_FAILED;
}
return VA_STATUS_ERROR_OPERATION_FAILED;
}
MOS_STATUS OsResultToMOS_Status(
VAStatus eResult)
{
switch (eResult)
{
case VA_STATUS_SUCCESS: return MOS_STATUS_SUCCESS;
case VA_STATUS_ERROR_ALLOCATION_FAILED: return MOS_STATUS_NO_SPACE;
case VA_STATUS_ERROR_INVALID_PARAMETER: return MOS_STATUS_INVALID_PARAMETER;
case VA_STATUS_ERROR_INVALID_BUFFER: return MOS_STATUS_INVALID_HANDLE;
case VA_STATUS_ERROR_INVALID_CONTEXT: return MOS_STATUS_NULL_POINTER;
default: return MOS_STATUS_UNKNOWN;
}
return MOS_STATUS_UNKNOWN;
}
MOS_STATUS MOS_GetLocalTime(
struct tm* Tm)
{
MOS_STATUS eStatus = MOS_STATUS_SUCCESS;
struct tm *pTm;
time_t lTime = time(nullptr);
pTm = localtime(&lTime);
if(pTm == nullptr)
{
MOS_OS_ASSERTMESSAGE("Failed to get localtime.");
eStatus = MOS_STATUS_UNKNOWN;
return eStatus;
}
eStatus = MOS_SecureMemcpy(Tm, sizeof(struct tm), pTm, sizeof(struct tm));
return eStatus;
}
void MOS_TraceEventInit()
{
if (g_apoMosEnabled)
{
return MosUtilities::MosTraceEventInit();
}
// close first, if already opened.
if (MosTraceFd >= 0)
{
close(MosTraceFd);
MosTraceFd = -1;
}
MosTraceFd = open(MosTracePath, O_WRONLY);
return;
}
void MOS_TraceEventClose()
{
if (g_apoMosEnabled)
{
return MosUtilities::MosTraceEventClose();
}
if (MosTraceFd >= 0)
{
close(MosTraceFd);
MosTraceFd = -1;
}
return;
}
void MOS_TraceSetupInfo(uint32_t DrvVer, uint32_t PlatFamily, uint32_t RenderFamily, uint32_t DeviceID)
{
// not implemented
}
#define TRACE_EVENT_MAX_SIZE 4096
void MOS_TraceEvent(
uint16_t usId,
uint8_t ucType,
void * const pArg1,
uint32_t dwSize1,
void * const pArg2,
uint32_t dwSize2)
{
if (g_apoMosEnabled)
{
return MosUtilities::MosTraceEvent(usId, ucType, pArg1, dwSize1, pArg2, dwSize2);
}
if (MosTraceFd >= 0)
{
char *pTraceBuf = (char *)MOS_AllocAndZeroMemory(TRACE_EVENT_MAX_SIZE);
uint32_t nLen = 0;
if (pTraceBuf)
{
MOS_SecureStringPrint(pTraceBuf,
TRACE_EVENT_MAX_SIZE,
(TRACE_EVENT_MAX_SIZE-1),
"IMTE|%d|%d", // magic number IMTE (IntelMediaTraceEvent)
usId,
ucType);
nLen = strlen(pTraceBuf);
if (pArg1)
{
// convert raw event data to string. native raw data will be supported
// from linux kernel 4.10, hopefully we can skip this convert in the future.
const static char n2c[] = "0123456789ABCDEF";
unsigned char *pData = (unsigned char *)pArg1;
pTraceBuf[nLen++] = '|'; // prefix splite marker.
while(dwSize1-- > 0 && nLen < TRACE_EVENT_MAX_SIZE-2)
{
pTraceBuf[nLen++] = n2c[(*pData) >> 4];
pTraceBuf[nLen++] = n2c[(*pData++) & 0xf];
}
if (pArg2)
{
pData = (unsigned char *)pArg2;
while(dwSize2-- > 0 && nLen < TRACE_EVENT_MAX_SIZE-2)
{
pTraceBuf[nLen++] = n2c[(*pData) >> 4];
pTraceBuf[nLen++] = n2c[(*pData++) & 0xf];
}
}
}
size_t writeSize = write(MosTraceFd, pTraceBuf, nLen);
MOS_FreeMemory(pTraceBuf);
}
}
return;
}
void MOS_TraceDataDump(
const char * pcName,
uint32_t flags,
const void * pBuf,
uint32_t dwSize)
{
// not implemented
}
MOS_STATUS MOS_GfxInfoInit()
{
// not implemented
return MOS_STATUS_SUCCESS;
}
void MOS_GfxInfoClose()
{
// not implemented
}
void MOS_GfxInfo_RTErr(uint8_t ver,
uint16_t compId,
uint16_t FtrId,
uint32_t ErrorCode,
uint8_t num_of_triples,
...)
{
// not implemented
}
void MOS_GfxInfo(
uint8_t ver,
uint16_t compId,
uint32_t tmtryID,
uint8_t num_of_triples,
...)
{
// not implemented
}
| 32.147546 | 167 | 0.577488 | [
"vector"
] |
049c4bd997bb1d3912b7866627fb28e5bf161be1 | 11,987 | h | C | Mocastys/2DFramework/Common/GLCommon.h | Qucentis/Mocastys | 389dbe65676bfe3eeb50a6c51773a0a0becdcaa7 | [
"MIT"
] | 2 | 2015-02-02T06:43:29.000Z | 2015-02-18T06:44:24.000Z | Mocastys/2DFramework/Common/GLCommon.h | Qucentis/Mocastys | 389dbe65676bfe3eeb50a6c51773a0a0becdcaa7 | [
"MIT"
] | null | null | null | Mocastys/2DFramework/Common/GLCommon.h | Qucentis/Mocastys | 389dbe65676bfe3eeb50a6c51773a0a0becdcaa7 | [
"MIT"
] | null | null | null | #define DEGREES_TO_RADIANS(x) ((x) / 180.0 * M_PI)
#define RADIANS_TO_DEGREES(x) ((x) / M_PI * 180.0)
#import "NEONMatrix.h"
typedef Vertex3D Vector3D;
static inline GLfloat Vertex3DDistanceBetweenVertices
(Vertex3D vertex1, Vertex3D vertex2)
{
GLfloat deltaX, deltaY, deltaZ;
deltaX = vertex2.x - vertex1.x;
deltaY = vertex2.y - vertex1.y;
deltaZ = vertex2.z - vertex1.z;
return sqrtf((deltaX * deltaX) +
(deltaY * deltaY) +
(deltaZ * deltaZ));
}
static inline GLfloat Vector3DMagnitude(Vector3D vector)
{
return sqrtf((vector.x * vector.x) +
(vector.y * vector.y) +
(vector.z * vector.z));
}
static inline GLfloat Vector3DDotProduct
(Vector3D vector1, Vector3D vector2)
{
return (vector1.x*vector2.x) +
(vector1.y*vector2.y) +
(vector1.z*vector2.z);
}
static inline Vector3D Vector3DCrossProduct
(Vector3D vector1, Vector3D vector2)
{
Vector3D ret;
ret.x = (vector1.y * vector2.z) - (vector1.z * vector2.y);
ret.y = (vector1.z * vector2.x) - (vector1.x * vector2.z);
ret.z = (vector1.x * vector2.y) - (vector1.y * vector2.x);
return ret;
}
static inline void Vector3DNormalize(Vector3D *vector)
{
GLfloat vecMag = Vector3DMagnitude(*vector);
if ( vecMag == 0.0 )
{
vector->x = 1.0;
vector->y = 0.0;
vector->z = 0.0;
return;
}
vector->x /= vecMag;
vector->y /= vecMag;
vector->z /= vecMag;
}
static inline Vector3D Vector3DMakeWithStartAndEndPoints
(Vertex3D start, Vertex3D end)
{
Vector3D ret;
ret.x = end.x - start.x;
ret.y = end.y - start.y;
ret.z = end.z - start.z;
return ret;
}
static inline Vector3D Vector3DMakeNormalizedVectorWithStartAndEndPoints
(Vertex3D start, Vertex3D end)
{
Vector3D ret = Vector3DMakeWithStartAndEndPoints(start, end);
Vector3DNormalize(&ret);
return ret;
}
static inline void Vector3DFlip (Vector3D *vector)
{
vector->x = -vector->x;
vector->y = -vector->y;
vector->z = -vector->z;
}
typedef struct {
GLubyte red;
GLubyte green;
GLubyte blue;
GLubyte alpha;
} Color4B;
static inline void Vector3DCopy(Vector3D *source,Vector3D *destination)
{
destination->x = source->x;
destination->y = source->y;
destination->z = source->z;
}
static inline void Color4fCopy(Color4B *source,Color4B *destination)
{
destination->blue = source->blue;
destination->green = source->green;
destination->red = source->red;
destination->alpha = source->alpha;
}
static inline void Vector3DCopyS(Vector3D source,Vector3D *destination)
{
destination->x = source.x;
destination->y = source.y;
destination->z = source.z;
}
static inline void Color4fCopyS(Color4B source,Color4B *destination)
{
destination->blue = source.blue;
destination->green = source.green;
destination->red = source.red;
destination->alpha = source.alpha;
}
typedef float Matrix3D[16];
static inline void Matrix3DSetIdentity(Matrix3D matrix)
{
matrix[0] = matrix[5] = matrix[10] = matrix[15] = 1.0;
matrix[1] = matrix[2] = matrix[3] = matrix[4] = 0.0;
matrix[6] = matrix[7] = matrix[8] = matrix[9] = 0.0;
matrix[11] = matrix[12] = matrix[13] = matrix[14] = 0.0;
}
static inline void Matrix3DSetTranslation
(Matrix3D matrix, GLfloat xTranslate,
GLfloat yTranslate, GLfloat zTranslate)
{
matrix[0] = matrix[5] = matrix[10] = matrix[15] = 1.0;
matrix[1] = matrix[2] = matrix[3] = matrix[4] = 0.0;
matrix[6] = matrix[7] = matrix[8] = matrix[9] = 0.0;
matrix[11] = 0.0;
matrix[12] = xTranslate;
matrix[13] = yTranslate;
matrix[14] = zTranslate;
}
static inline void Matrix3DSetScaling
(Matrix3D matrix, GLfloat xScale,
GLfloat yScale, GLfloat zScale)
{
matrix[1] = matrix[2] = matrix[3] = matrix[4] = 0.0;
matrix[6] = matrix[7] = matrix[8] = matrix[9] = 0.0;
matrix[11] = matrix[12] = matrix[13] = matrix[14] = 0.0;
matrix[0] = xScale;
matrix[5] = yScale;
matrix[10] = zScale;
matrix[15] = 1.0;
}
static inline void Matrix3DSetUniformScaling
(Matrix3D matrix, GLfloat scale)
{
Matrix3DSetScaling(matrix, scale, scale, scale);
}
static inline void Matrix3DSetZRotationUsingRadians
(Matrix3D matrix, GLfloat radians)
{
matrix[0] = cosf(radians);
matrix[1] = sinf(radians);
matrix[4] = -matrix[1];
matrix[5] = matrix[0];
matrix[2] = matrix[3] = matrix[6] = matrix[7] = matrix[8] = 0.0;
matrix[9] = matrix[11] = matrix[12] = matrix[13] = matrix[14] = 0.0;
matrix[10] = matrix[15] = 1.0;
}
static inline void Matrix3DSetZRotationUsingDegrees
(Matrix3D matrix, GLfloat degrees)
{
Matrix3DSetZRotationUsingRadians(matrix, DEGREES_TO_RADIANS(degrees));
}
static inline void Matrix3DSetXRotationUsingRadians
(Matrix3D matrix, GLfloat radians)
{
matrix[0] = matrix[15] = 1.0;
matrix[1] = matrix[2] = matrix[3] = matrix[4] = 0.0;
matrix[7] = matrix[8] = 0.0;
matrix[11] = matrix[12] = matrix[13] = matrix[14] = 0.0;
matrix[5] = cosf(radians);
matrix[6] = -sinf(radians);
matrix[9] = -matrix[6];
matrix[10] = matrix[5];
}
static inline void Matrix3DSetXRotationUsingDegrees
(Matrix3D matrix, GLfloat degrees)
{
Matrix3DSetXRotationUsingRadians(matrix,DEGREES_TO_RADIANS(degrees));
}
static inline void Matrix3DSetYRotationUsingRadians
(Matrix3D matrix, GLfloat radians)
{
matrix[0] = cosf(radians);
matrix[2] = sinf(radians);
matrix[8] = -matrix[2];
matrix[10] = matrix[0];
matrix[1] = matrix[3] = matrix[4] = matrix[6] = matrix[7] = 0.0;
matrix[9] = matrix[11] = matrix[13] = matrix[12] = matrix[14] = 0.0;
matrix[5] = matrix[15] = 1.0;
}
static inline void Matrix3DSetYRotationUsingDegrees
(Matrix3D matrix, GLfloat degrees)
{
Matrix3DSetYRotationUsingRadians(matrix, DEGREES_TO_RADIANS(degrees));
}
static inline void Matrix3DSetRotationByRadians
(Matrix3D matrix, GLfloat radians, Vector3D vector)
{
GLfloat mag = sqrtf((vector.x * vector.x) +
(vector.y * vector.y) +
(vector.z * vector.z));
if (mag == 0.0)
{
vector.x = 1.0;
vector.y = 0.0;
vector.z = 0.0;
}
else if (mag != 1.0)
{
vector.x /= mag;
vector.y /= mag;
vector.z /= mag;
}
GLfloat c = cosf(radians);
GLfloat s = sinf(radians);
matrix[3] = matrix[7] = matrix[11] = 0.0;
matrix[12] = matrix[13] = matrix[14] = 0.0;
matrix[15] = 1.0;
matrix[0] = (vector.x * vector.x) * (1-c) + c;
matrix[1] = (vector.y * vector.x) * (1-c) + (vector.z * s);
matrix[2] = (vector.x * vector.z) * (1-c) - (vector.y * s);
matrix[4] = (vector.x * vector.y) * (1-c) - (vector.z * s);
matrix[5] = (vector.y * vector.y) * (1-c) + c;
matrix[6] = (vector.y * vector.z) * (1 - c) + (vector.x*s);
matrix[8] = (vector.x * vector.z) * (1 - c) + (vector.y*s);
matrix[9] = (vector.y * vector.z) * (1 - c) - (vector.x*s);
matrix[10] = (vector.z * vector.z) * (1 - c) + c;
}
static inline void Matrix3DSetRotationByDegrees
(Matrix3D matrix, GLfloat degrees, Vector3D vec)
{
Matrix3DSetRotationByRadians(matrix, DEGREES_TO_RADIANS(degrees), vec);
}
static inline void Matrix3DSetOrthoProjection(Matrix3D matrix, GLfloat left,
GLfloat right, GLfloat bottom, GLfloat top, GLfloat near, GLfloat far)
{
matrix[1] = matrix[2] = matrix[3] = matrix[4] = matrix[6] = 0.f;
matrix[7] = matrix[8] = matrix[9] = matrix[11] = 0.f;
matrix[0] = 2.f / (right - left);
matrix[5] = 2.f / (top - bottom);
matrix[10] = -2.f / (far - near);
matrix[12] = (right + left) / (right - left);
matrix[13] = (top + bottom) / (top - bottom);
matrix[14] = (far + near) / (far - near);
matrix[15] = 1.f;
}
static inline void Matrix3DSetFrustumProjection(Matrix3D matrix,
GLfloat left, GLfloat right,
GLfloat bottom, GLfloat top,
GLfloat zNear, GLfloat zFar)
{
matrix[1] = matrix[2] = matrix[3] = matrix[4] = 0.f;
matrix[6] = matrix[7] = matrix[12] = matrix[13] = matrix[15] = 0.f;
matrix[0] = 2 * zNear / (right - left);
matrix[5] = 2 * zNear / (top - bottom);
matrix[8] = (right + left) / (right - left);
matrix[9] = (top + bottom) / (top - bottom);
matrix[10] = -(zFar + zNear) / (zFar - zNear);
matrix[11] = -1.f;
matrix[14] = -(2 * zFar * zNear) / (zFar - zNear);
}
static inline void Matrix3DCopyS(Matrix3D source,Matrix3D destination)
{
for (int i =0;i<16;i++)
{
destination[i] = source[i];
}
}
static inline void Matrix3DCopy(Matrix3D *source,Matrix3D *destination)
{
for (int i =0;i<16;i++)
{
*(destination)[i]= *(source)[i];
}
}
static inline void Matrix3DSetPerspectiveProjectionWithFieldOfView
(Matrix3D matrix, GLfloat fieldOfVision, GLfloat near,
GLfloat far, GLfloat aspectRatio)
{
GLfloat size = near * tanf(DEGREES_TO_RADIANS(fieldOfVision) / 2.0);
Matrix3DSetFrustumProjection( matrix,
-size,
size,
-size / aspectRatio,
size / aspectRatio,
near,
far);
}
static inline void CGRectToVertex3D(CGRect _rect,Vertex3D* vertices)
{
vertices[0] = (Vertex3D){.x = _rect.origin.x, .y = _rect.origin.y, .z = 0};
vertices[1] = (Vertex3D){.x = _rect.origin.x + _rect.size.width , .y = _rect.origin.y, .z = 0};
vertices[2] = (Vertex3D){.x = _rect.origin.x + _rect.size.width , .y = _rect.origin.y + _rect.size.height, .z = 0};
vertices[3] = (Vertex3D){.x = _rect.origin.x, .y = _rect.origin.y, .z = 0};
vertices[4] = (Vertex3D){.x = _rect.origin.x, .y = _rect.origin.y + _rect.size.height, .z = 0};
vertices[5] = (Vertex3D){.x = _rect.origin.x + _rect.size.width, .y = _rect.origin.y + _rect.size.height, .z = 0};
}
typedef struct
{
GLfloat s;
GLfloat t;
} TextureCoord;
static inline void TextureCoordCopy(TextureCoord *source,TextureCoord *destination)
{
destination->s = source->s;
destination->t = source->t;
}
static inline void TextureCoordCopyS(TextureCoord source,TextureCoord *destination)
{
destination->s = source.s;
destination->t = source.t;
}
static inline void CGRectToTextureCoord(CGRect _rect,TextureCoord *texCoord)
{
texCoord[0] = (TextureCoord){.s = _rect.origin.x, .t = _rect.origin.y +_rect.size.height};
texCoord[1] = (TextureCoord){.s = _rect.origin.x + _rect.size.width , .t = _rect.origin.y+_rect.size.height};
texCoord[2] = (TextureCoord){.s = _rect.origin.x + _rect.size.width , .t = _rect.origin.y};
texCoord[3] = (TextureCoord){.s = _rect.origin.x, .t = _rect.origin.y +_rect.size.height};
texCoord[4] = (TextureCoord){.s = _rect.origin.x, .t = _rect.origin.y};
texCoord[5] = (TextureCoord){.s = _rect.origin.x + _rect.size.width, .t = _rect.origin.y};
}
static inline Color4B Color4BFromHex(int hex)
{
return (Color4B){.red = (0xff000000 & hex)>>24,.green = (0x00ff0000 & hex)>>16 ,.blue = (0x0000ff00 & hex)>>8,
.alpha = 0x000000ff & hex
};
}
typedef struct
{
Vertex3D vertex;
Color4B color;
} VertexColorData;
typedef struct
{
TextureCoord texCoord;
Vertex3D vertex;
Color4B color;
} TextureVertexColorData;
typedef struct
{
Matrix3D mvpMatrix;
Vertex3D vertex;
Color4B color;
} InstancedVertexColorData;
typedef struct
{
Matrix3D mvpMatrix;
TextureCoord texCoord;
Vertex3D vertex;
Color4B color;
} InstancedTextureVertexColorData;
typedef struct
{
Vertex3D vertex;
Color4B color;
float size;
} PointVertexColorSizeData;
| 30.042607 | 119 | 0.61258 | [
"vector"
] |
049cd63e3b598a5a2f9993e1050cf6ea9224eeed | 396 | h | C | Application/Structs.h | JorgeMarcano/WorldSim | c3a8b28b6ae1b9b9d903705c3c66067a8a43c90b | [
"Apache-2.0"
] | null | null | null | Application/Structs.h | JorgeMarcano/WorldSim | c3a8b28b6ae1b9b9d903705c3c66067a8a43c90b | [
"Apache-2.0"
] | null | null | null | Application/Structs.h | JorgeMarcano/WorldSim | c3a8b28b6ae1b9b9d903705c3c66067a8a43c90b | [
"Apache-2.0"
] | null | null | null | #ifndef STRUCTS_H
#define STRUCTS_H
typedef struct Space
{
int x;
int y;
} Space;
typedef struct Object
{
Space* location;
int xSpeed;
int ySpeed;
} Object;
#define OBJECT_COUNT 5
#define SPACE_X_SIZE 10
#define SPACE_Y_SIZE 10
#define SPACE_COUNT SPACE_X_SIZE * SPACE_Y_SIZE
#define OBJECT_SPEED_X_MAX 3
#define OBJECT_SPEED_Y_MAX 3
#endif
| 15.84 | 55 | 0.686869 | [
"object"
] |
04a0cb13aebfd13e8ee6361a2baa7a1ebdd147fa | 7,482 | h | C | src/Filtering/itktubeTubeEnhancingDiffusion2DImageFilter.h | kian-weimer/ITKTubeTK | 88da3195bfeca017745e7cddfe04f82571bd00ee | [
"Apache-2.0"
] | 27 | 2020-04-06T17:23:22.000Z | 2022-03-02T13:25:52.000Z | src/Filtering/itktubeTubeEnhancingDiffusion2DImageFilter.h | kian-weimer/ITKTubeTK | 88da3195bfeca017745e7cddfe04f82571bd00ee | [
"Apache-2.0"
] | 14 | 2020-04-09T00:23:15.000Z | 2022-02-26T13:02:35.000Z | src/Filtering/itktubeTubeEnhancingDiffusion2DImageFilter.h | kian-weimer/ITKTubeTK | 88da3195bfeca017745e7cddfe04f82571bd00ee | [
"Apache-2.0"
] | 14 | 2020-04-03T03:56:14.000Z | 2022-01-14T07:51:32.000Z | /*=========================================================================
Library: TubeTK
Copyright 2010 Kitware Inc. 28 Corporate Drive,
Clifton Park, NY, 12065, USA.
All rights reserved.
Licensed under the Apache License, Version 2.0 ( the "License" );
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
=========================================================================*/
#ifndef __itktubeTubeEnhancingDiffusion2DImageFilter_h
#define __itktubeTubeEnhancingDiffusion2DImageFilter_h
#include <itkImageToImageFilter.h>
#include <vector>
namespace itk
{
namespace tube
{
/** \class TubeEnhancingDiffusion2DImageFilter
*
* Complete rewrite of previous versions, only using itk/vnl routines
* for derivatives, eigensystem calculations and diffusion. Internally,
* the input image image is converted to internal precision ( float ) for
* calculation, and converted back when returning the results.
*
* Uses simple forward Euler scheme ( explicit ) with 3x3 stencil,
* see, e.g., PhD of Joachim Weickert for theory and implementation regarding
* the construction of this discretization scheme. See 'Tube Enhancing
* Diffusion', Manniesing, media 2006, for information regarding the
* construction of the diffusion tensor.
*
* - Stores all elements of the Hessian of the complete image during
* diffusion. An alternative implementation is to only store the
* scale for which the vesselness has maximum response, and to
* recalculate the Hessian ( locally ) during diffusion. Also stores
* the current image, i.e., at iteration i + temp image, therefore the
* complete memory consumption approximately peaks at 8 times the input
* image ( input image in float )
* - The Hessian is stored as six individual images, an alternative
* implementation is to use the itk symmetric second rank tensor
* as pixel type ( and e.g. using the class SymmetricEigenAnalysisImage
* Filter ). However, we are lazy, and using this since we rely
* on vnl data types and its eigensystem calculations
* - note: most of computation time is spent at calculation of vesselness
* response
*
* - PixelT short, 2D
* Precision float, 2D
*
* - todo
* - using parallelism/threading e.g., over scales
* - completely ITK-fying, e.g., eigenvalues calculation
* - possibly embedding within itk-diffusion framework
* - itk expert to have a look at use of iterators
* ( there must be a potential gain there )
*
* email: r.manniesing@erasmusmc.nl
*/
template< class TPixel = short int, unsigned int VDimension = 2 >
class TubeEnhancingDiffusion2DImageFilter
: public ImageToImageFilter< Image< TPixel, VDimension >,
Image< TPixel, VDimension > >
{
public:
typedef float Precision;
typedef Image<TPixel, VDimension> ImageType;
typedef Image<Precision, VDimension> PrecisionImageType;
typedef TubeEnhancingDiffusion2DImageFilter Self;
typedef ImageToImageFilter<ImageType, ImageType> Superclass;
typedef SmartPointer< Self > Pointer;
typedef SmartPointer< const Self > ConstPointer;
itkNewMacro( Self );
itkTypeMacro( TubeEnhancingDiffusion2DImageFilter, ImageToImageFilter );
/** Set/Get time step */
itkSetMacro( TimeStep, Precision );
itkGetMacro( TimeStep, Precision );
/** Set/Get iterations */
itkSetMacro( Iterations, unsigned int );
itkGetMacro( Iterations, unsigned int );
/** Set/Get for how many iterations do we recalculate tubeness */
itkSetMacro( RecalculateTubeness, unsigned int );
itkGetMacro( RecalculateTubeness, unsigned int );
/** Set/Get sensitive of the filter to blobness */
itkSetMacro( Beta, Precision );
itkGetMacro( Beta, Precision );
/** Set/Get sensitive of the filter to second order structureness */
itkSetMacro( Gamma, Precision );
itkGetMacro( Gamma, Precision );
/** Set/Get epsilon */
itkSetMacro( Epsilon, Precision );
itkGetMacro( Epsilon, Precision );
/** Set/Get Omega */
itkSetMacro( Omega, Precision );
itkGetMacro( Omega, Precision );
/** Set/Get Sensitivity */
itkSetMacro( Sensitivity, Precision );
itkGetMacro( Sensitivity, Precision );
void SetScales( const std::vector<Precision> &scales )
{
m_Scales = scales;
}
itkBooleanMacro( DarkObjectLightBackground );
itkSetMacro( DarkObjectLightBackground, bool );
itkGetMacro( DarkObjectLightBackground, bool );
itkBooleanMacro( Verbose );
itkSetMacro( Verbose, bool );
itkGetMacro( Verbose, bool );
// some defaults for lowdose example
// used in the paper
void SetDefaultPars( void )
{
m_TimeStep = 0.05;
m_Iterations = 50;
m_RecalculateTubeness = 11;
m_Beta = 0.5;
m_Gamma = 5.0;
m_Epsilon = 0.01;
m_Omega = 25.0;
m_Sensitivity = 20.0;
m_Scales.resize( 2 );
m_Scales[0] = 6;
m_Scales[1] = 8;
m_DarkObjectLightBackground = true;
m_Verbose = true;
}
protected:
TubeEnhancingDiffusion2DImageFilter( void );
~TubeEnhancingDiffusion2DImageFilter( void ) {}
void PrintSelf( std::ostream &os, Indent indent ) const override;
void GenerateData( void ) override;
private:
TubeEnhancingDiffusion2DImageFilter( const Self& );
void operator=( const Self& );
Precision m_TimeStep;
unsigned int m_Iterations;
unsigned int m_RecalculateTubeness;
Precision m_Beta;
Precision m_Gamma;
Precision m_Epsilon;
Precision m_Omega;
Precision m_Sensitivity;
std::vector<Precision> m_Scales;
bool m_DarkObjectLightBackground;
bool m_Verbose;
unsigned int m_CurrentIteration;
// current Hessian for which we have maximum vessel response
typename PrecisionImageType::Pointer m_Dxx;
typename PrecisionImageType::Pointer m_Dxy;
typename PrecisionImageType::Pointer m_Dyy;
void VED2DSingleIteration( typename PrecisionImageType::Pointer );
// Calculates maximum vessel response of the range
// of scales and stores the Hessian of each voxel
// into the member images m_Dij.
void MaxTubeResponse( const typename PrecisionImageType::Pointer );
// calculates diffusion tensor
// based on current values of Hessian ( for which we have
// maximum vessel response ).
void DiffusionTensor( void );
// Sorted increasing magnitude: l1, l2
inline Precision TubenessFunction2D ( const Precision, const Precision );
}; // End class TubeEnhancingDiffusion2DImageFilter
} // End namespace tube
} // End namespace itk
#ifndef ITK_MANUAL_INSTANTIATION
#include "itktubeTubeEnhancingDiffusion2DImageFilter.hxx"
#endif
#endif // End !defined( __itktubeTubeEnhancingDiffusion2DImageFilter_h )
| 33.855204 | 77 | 0.678161 | [
"vector"
] |
04a2d155df4118cf19058005b33da066b82f5175 | 6,850 | h | C | src/api/iot_common.h | deviceWISE/device-cloud-lib | 4563175f0cbd1765f778718ca191ff1563780c4e | [
"ECL-2.0",
"Apache-2.0"
] | 5 | 2019-04-19T08:38:15.000Z | 2021-03-13T01:34:06.000Z | src/api/iot_common.h | deviceWISE/device-cloud-lib | 4563175f0cbd1765f778718ca191ff1563780c4e | [
"ECL-2.0",
"Apache-2.0"
] | 1 | 2019-05-26T13:52:39.000Z | 2019-05-30T09:16:39.000Z | src/api/iot_common.h | deviceWISE/device-cloud-lib | 4563175f0cbd1765f778718ca191ff1563780c4e | [
"ECL-2.0",
"Apache-2.0"
] | 3 | 2018-08-21T14:49:35.000Z | 2021-07-30T15:27:20.000Z | /**
* @file
* @brief header file declaring internal library functions
*
* @copyright Copyright (C) 2016 Wind River Systems, Inc. All Rights Reserved.
*
* @license 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."
*/
#ifndef IOT_COMMON_H
#define IOT_COMMON_H
#include "shared/iot_types.h"
#include <stdarg.h> /* for va_end, va_list, va_start */
/**
* @brief type of conversion to perform
*/
enum iot_conversion_type
{
/** @brief do not perform any conversion */
IOT_CONVERSION_NONE = 0,
/** @brief perform basic conversion (only perform if no loss of precision)
*
* to float32:
* - any float32 with a value < FLT_MAX
* - all int8, int16, int32, int64, uint8, uint16, uint32, uint64 can be converted to float32
*
* to float64:
* - all float32 can be converted to float64
* - all int8, int16, int32, int64, uint8, uint16, uint32, uint64 can be converted to float32
*
* to int8 (:
* - all int16, int32, int64 with a value in range: -128 - 127
* - all uint8, uint16, uint32, uint64 with a value in range: 0 - 127
*
* to int16:
* - all int8, uint8 can be converted to int16
* - all int32, int64 with a value in range: -32,768 - 32,767
* - all uint16, uint32, uint64 with a value in range: 0 - 32,767
*
* to int32:
* - all int8, int16, uint8, uint16 can be converted to int32
* - all int64 with a value in range: -2,147,483,648 - 2,147,483,647
* - all uint32, uint64 with a value in range: 0 - 2,147,483,647
*
* to int64:
* - all int8, int16, int32, uint8, uint16, uint32 can all be converted to int64
* - all uint64 with a value in range: 0 - 9,223,372,036,854,775,807
*
* to boolean, location, raw, string:
* - nothing converts
*
* to uint8:
* - all uint16, uint32, uint64 with a value: <= 255
* - all int8, int16, int32, int64 with a value in range: 0 - 255
*
* to uint16:
* - all uint8 can be converted to uint16
* - all uint32, uint64 with a value a value: <= 65,535
* - all int8, int16, int32, int64 with a value in range: 0 - 65,535
*
* to uint32:
* - all uint8, uint16 can be converted to uint32
* - all uint64 with a value: <= 4,294,967,295
* - all int8, int16, int32, int64 with a value in range: 0 - 4,294,967,295
*
* to uint64:
* - all uint8, uint16, uint32 can all be converted to uint64
* - all int8, int16, int32, int64 with a value >= 0
*/
IOT_CONVERSION_BASIC,
/** @brief perform advanced conversion
*
* to boolean:
* - all numbers can be converted to boolean
* - any raw containing data can be converted to boolean
* - any string starting with:
* - "("", '0', 'f', 'F', 'N', 'n', "Of", "OF", "oF" ) are IOT_FALSE
* - all other values are IOT_TRUE
*
* to float32:
* to float64:
* - all integers are converted to float32
* - strings starting optionally with '-' or numbers and optionally a .
*
* to int8:
* to int16:
* to int32:
* to int64:
* - all floats are down-casted converted to integers
* - strings starting optionally with '-' until a non-number character
*
* to location:
* - nothing converts to locations
*
* to raw:
* - strings containing base64 data can be converted to raw
*
* to string:
* - all numbers (floats and integers) can be converted to strings
* - boolean values can be converted to strings
* - raw data can be converted to base64 string
*
* to uint8:
* to uint16:
* to uint32:
* to uint64:
* - all floats are down-casted converted to unsigned integers
* - strings until the first non-number character
*/
IOT_CONVERSION_ADVANCED
};
/** @brief Enumeration for the type of conversion to allow */
typedef enum iot_conversion_type iot_conversion_type_t;
/**
* @brief Common function to retrieve a value from a iot_data structure
*
* @param[in] obj structure to retrieve data from
* @param[in] convert allow conversion to desired
* type, if possible
* @param[in] type type of data to retrieve
* @param[out] args pointer to store result,
* based on @p type parameter
*
* @retval IOT_STATUS_BAD_PARAMETER invalid parameter passed to
* function
* @retval IOT_STATUS_BAD_REQUEST type is either incorrect or
* value has not been set
* @retval IOT_STATUS_SUCCESS on success
*
* @see iot_common_arg_set
*/
IOT_SECTION iot_status_t iot_common_arg_get( const struct iot_data *obj,
iot_bool_t convert, iot_type_t type, va_list args );
/**
* @brief Sets the value of a iot_data structure
*
* @param[in,out] obj structure to set data of
* @param[in] heap_alloc allocate memory on heap and
* have @p obj take ownership, if
* required (raw & string types)
* @param[in] type type of data to set
* @param[in] args argument holding value to set,
* based on @p type parameter
*
* @retval IOT_STATUS_BAD_PARAMETER invalid parameter passed to
* function
* @retval IOT_STATUS_SUCCESS on success
*
* @see iot_commmon_arg_get
*/
IOT_SECTION iot_status_t iot_common_arg_set( struct iot_data *obj,
iot_bool_t heap_alloc, iot_type_t type, va_list args );
/**
* @brief Determines if two data objects can be converted
*
* @param[in] conversion type of conversion to perform
* @param[in] to_type type being converted to
* @param[in] from object being converted from
*
* @retval IOT_FALSE conversion is not possible
* @retval IOT_TRUE conversion is possible
*/
IOT_SECTION iot_bool_t iot_common_data_convert_check(
iot_conversion_type_t conversion,
iot_type_t to_type,
const struct iot_data *from );
IOT_SECTION iot_bool_t iot_common_data_convert(
iot_conversion_type_t conversion,
iot_type_t to_type,
struct iot_data *obj );
#endif /* ifndef IOT_COMMON_H */
| 36.052632 | 95 | 0.610365 | [
"object"
] |
04abf510a9d9f2757fa365768bb2f5bcf41022ca | 1,187 | h | C | hbe/alg/RS.h | maumueller/rehashing | 38fe7a1a71fcc5ecd10384fac01bfeb134ea5fad | [
"MIT"
] | 20 | 2019-05-14T20:08:08.000Z | 2021-09-22T20:48:29.000Z | hbe/alg/RS.h | maumueller/rehashing | 38fe7a1a71fcc5ecd10384fac01bfeb134ea5fad | [
"MIT"
] | 2 | 2020-10-06T09:47:52.000Z | 2020-10-09T04:27:39.000Z | hbe/alg/RS.h | maumueller/rehashing | 38fe7a1a71fcc5ecd10384fac01bfeb134ea5fad | [
"MIT"
] | 2 | 2019-08-11T22:29:45.000Z | 2020-10-08T20:02:46.000Z | #ifndef HBE_RS_H
#define HBE_RS_H
#include <Eigen/Dense>
#include "MoMEstimator.h"
#include "kernel.h"
using Eigen::MatrixXd;
using Eigen::VectorXd;
///
/// Random sampling estimator
///
class RS : public MoMEstimator {
public:
/// Default constructor.
/// \param data dataset
/// \param k kernel
RS(shared_ptr<MatrixXd> data, shared_ptr<Kernel> k);
/// Constructor with fixed reservoir size.
/// \param data the whole dataset
/// \param k kernel
/// \param samples size of the reservoir
RS(shared_ptr<MatrixXd> data, shared_ptr<Kernel> k, int samples);
protected:
///
/// \param q: query
/// \param L: median of L means
/// \param m: means of m samples
/// \return: a vector of L elements, where each element is a sum of m random samples
///
std::vector<double> MoM(VectorXd q, int L, int m);
private:
///
/// Reservoir of random samples. Could be the entire dataset of a subset of the dataset.
///
shared_ptr<MatrixXd> X;
///
/// Number of points in the reservoir.
///
int numPoints;
///
/// Kernel function.
///
shared_ptr<Kernel> kernel;
};
#endif //HBE_RS_H
| 20.824561 | 92 | 0.629318 | [
"vector"
] |
04b2f0dea44f8810420af08bdee04eb90f3bb6ed | 4,639 | h | C | ui/base/models/table_model.h | junmin-zhu/chromium-rivertrail | eb1a57aca71fe68d96e48af8998dcfbe45171ee1 | [
"BSD-3-Clause"
] | 5 | 2018-03-10T13:08:42.000Z | 2021-07-26T15:02:11.000Z | ui/base/models/table_model.h | quisquous/chromium | b25660e05cddc9d0c3053b3514f07037acc69a10 | [
"BSD-3-Clause"
] | 1 | 2015-07-21T08:02:01.000Z | 2015-07-21T08:02:01.000Z | ui/base/models/table_model.h | jianglong0156/chromium.src | d496dfeebb0f282468827654c2b3769b3378c087 | [
"BSD-3-Clause"
] | 6 | 2016-11-14T10:13:35.000Z | 2021-01-23T15:29:53.000Z | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef UI_BASE_MODELS_TABLE_MODEL_H_
#define UI_BASE_MODELS_TABLE_MODEL_H_
#include <vector>
#include "base/string16.h"
#include "ui/base/ui_export.h"
#include "unicode/coll.h"
namespace gfx {
class ImageSkia;
}
namespace ui {
class TableModelObserver;
// The model driving the TableView.
class UI_EXPORT TableModel {
public:
// See HasGroups, get GetGroupID for details as to how this is used.
struct Group {
// The title text for the group.
string16 title;
// Unique id for the group.
int id;
};
typedef std::vector<Group> Groups;
// Number of rows in the model.
virtual int RowCount() = 0;
// Returns the value at a particular location in text.
virtual string16 GetText(int row, int column_id) = 0;
// Returns the small icon (16x16) that should be displayed in the first
// column before the text. This is only used when the TableView was created
// with the ICON_AND_TEXT table type. Returns an isNull() image if there is
// no image.
virtual gfx::ImageSkia GetIcon(int row);
// Returns the tooltip, if any, to show for a particular row. If there are
// multiple columns in the row, this will only be shown when hovering over
// column zero.
virtual string16 GetTooltip(int row);
// If true, this row should be indented.
virtual bool ShouldIndent(int row);
// Returns true if the TableView has groups. Groups provide a way to visually
// delineate the rows in a table view. When groups are enabled table view
// shows a visual separator for each group, followed by all the rows in
// the group.
//
// On win2k a visual separator is not rendered for the group headers.
virtual bool HasGroups();
// Returns the groups.
// This is only used if HasGroups returns true.
virtual Groups GetGroups();
// Returns the group id of the specified row.
// This is only used if HasGroups returns true.
virtual int GetGroupID(int row);
// Sets the observer for the model. The TableView should NOT take ownership
// of the observer.
virtual void SetObserver(TableModelObserver* observer) = 0;
// Compares the values in the column with id |column_id| for the two rows.
// Returns a value < 0, == 0 or > 0 as to whether the first value is
// <, == or > the second value.
//
// This implementation does a case insensitive locale specific string
// comparison.
virtual int CompareValues(int row1, int row2, int column_id);
// Reset the collator.
void ClearCollator();
protected:
virtual ~TableModel() {}
// Returns the collator used by CompareValues.
icu::Collator* GetCollator();
};
// TableColumn specifies the title, alignment and size of a particular column.
struct UI_EXPORT TableColumn {
enum Alignment {
LEFT, RIGHT, CENTER
};
TableColumn();
TableColumn(int id, const string16& title,
Alignment alignment, int width);
TableColumn(int id, const string16& title,
Alignment alignment, int width, float percent);
// It's common (but not required) to use the title's IDS_* tag as the column
// id. In this case, the provided conveniences look up the title string on
// bahalf of the caller.
TableColumn(int id, Alignment alignment, int width);
TableColumn(int id, Alignment alignment, int width, float percent);
// A unique identifier for the column.
int id;
// The title for the column.
string16 title;
// Alignment for the content.
Alignment alignment;
// The size of a column may be specified in two ways:
// 1. A fixed width. Set the width field to a positive number and the
// column will be given that width, in pixels.
// 2. As a percentage of the available width. If width is -1, and percent is
// > 0, the column is given a width of
// available_width * percent / total_percent.
// 3. If the width == -1 and percent == 0, the column is autosized based on
// the width of the column header text.
//
// Sizing is done in four passes. Fixed width columns are given
// their width, percentages are applied, autosized columns are autosized,
// and finally percentages are applied again taking into account the widths
// of autosized columns.
int width;
float percent;
// The minimum width required for all items in this column
// (including the header)
// to be visible.
int min_visible_width;
// Is this column sortable? Default is false
bool sortable;
};
} // namespace ui
#endif // UI_BASE_MODELS_TABLE_MODEL_H_
| 31.344595 | 79 | 0.708558 | [
"vector",
"model"
] |
04b59281141776ec2b38fa4112047571e2516dbb | 5,713 | h | C | sr/lsri/commands/gas2ack/asm86.h | ducis/operating-system-labs | 7df84f3dae792ee96461497b7d47414d24d233ee | [
"MIT"
] | 2 | 2018-03-01T13:45:41.000Z | 2018-03-01T14:11:47.000Z | src.clean/commands/gas2ack/asm86.h | ducis/operating-system-labs | 7df84f3dae792ee96461497b7d47414d24d233ee | [
"MIT"
] | null | null | null | src.clean/commands/gas2ack/asm86.h | ducis/operating-system-labs | 7df84f3dae792ee96461497b7d47414d24d233ee | [
"MIT"
] | null | null | null | /* asm86.h - 80X86 assembly intermediate Author: Kees J. Bot
* 27 Jun 1993
*/
typedef enum opcode { /* 80486 opcodes, from the i486 reference manual.
* Synonyms left out, some new words invented.
*/
DOT_ALIGN,
DOT_ASCII, DOT_ASCIZ,
DOT_ASSERT, /* Pseudo's invented */
DOT_BASE,
DOT_COMM, DOT_LCOMM,
DOT_DATA1,
DOT_DATA2,
DOT_DATA4,
DOT_DEFINE, DOT_EXTERN,
DOT_EQU,
DOT_FILE, DOT_LINE,
DOT_LABEL,
DOT_LIST, DOT_NOLIST,
DOT_SPACE,
DOT_SYMB,
DOT_TEXT, DOT_ROM, DOT_DATA, DOT_BSS, DOT_END,
DOT_USE16, DOT_USE32,
AAA,
AAD,
AAM,
AAS,
ADC,
ADD,
AND,
ARPL,
BOUND,
BSF,
BSR,
BSWAP,
BT,
BTC,
BTR,
BTS,
CALL, CALLF, /* CALLF added */
CBW,
CLC,
CLD,
CLI,
CLTS,
CMC,
CMP,
CMPS,
CMPXCHG,
CPUID,
CWD,
DAA,
DAS,
DEC,
DIV,
ENTER,
F2XM1,
FABS,
FADD, FADDD, FADDS, FADDP, FIADDL, FIADDS,
FBLD,
FBSTP,
FCHS,
FCLEX,
FCOMD, FCOMS, FCOMPD, FCOMPS, FCOMPP,
FCOS,
FDECSTP,
FDIVD, FDIVS, FDIVP, FIDIVL, FIDIVS,
FDIVRD, FDIVRS, FDIVRP, FIDIVRL, FIDIVRS,
FFREE,
FICOM, FICOMP,
FILDQ, FILDL, FILDS,
FINCSTP,
FINIT,
FISTL, FISTS, FISTP,
FLDX, FLDD, FLDS,
FLD1, FLDL2T, FLDL2E, FLDPI, FLDLG2, FLDLN2, FLDZ,
FLDCW,
FLDENV,
FMULD, FMULS, FMULP, FIMULL, FIMULS,
FNINIT,
FNOP,
FNSAVE,
FNSTCW,
FNSTSW,
FPATAN,
FPREM,
FPREM1,
FPTAN,
FRNDINT,
FRSTOR,
FSAVE,
FWAIT,
FXRSTOR,
FXSAVE,
FSCALE,
FSIN,
FSINCOS,
FSQRT,
FSTD, FSTS, FSTP, FSTPX, FSTPD, FSTPS,
FSTCW,
FSTENV,
FSTSW,
FSUBD, FSUBS, FSUBP, FISUBL, FISUBS,
FSUBRD, FSUBRS, FSUBPR, FISUBRL, FISUBRS,
FTST,
FUCOM, FUCOMP, FUCOMPP,
FXAM,
FXCH,
FXTRACT,
FYL2X,
FYL2XP1,
HLT,
IDIV,
IMUL,
IN,
INC,
INS,
INT, INTO,
INVD,
INVLPG,
IRET, IRETD,
JA, JAE, JB, JBE, JCXZ, JE, JG, JGE, JL,
JLE, JNE, JNO, JNP, JNS, JO, JP, JS,
JMP, JMPF, /* JMPF added */
LAHF,
LAR,
LEA,
LEAVE,
LGDT, LIDT,
LGS, LSS, LDS, LES, LFS,
LLDT,
LMSW,
LOCK,
LODS,
LOOP, LOOPE, LOOPNE,
LSL,
LTR,
MFENCE,
MOV,
MOVS,
MOVSX,
MOVSXB,
MOVZX,
MOVZXB,
MUL,
NEG,
NOP,
NOT,
OR,
OUT,
OUTS,
PAUSE,
POP,
POPA,
POPAD,
POPF,
PUSH,
PUSHA,
PUSHAD,
PUSHF,
RCL, RCR, ROL, ROR,
RDMSR,
RDPMC,
RDTSC,
RET, RETF, /* RETF added */
SAHF,
SAL, SAR, SHL, SHR,
SBB,
SCAS,
SETA, SETAE, SETB, SETBE, SETE, SETG, SETGE, SETL,
SETLE, SETNE, SETNO, SETNP, SETNS, SETO, SETP, SETS,
SGDT, SIDT,
SHLD,
SHRD,
SLDT,
SMSW,
STC,
STD,
STI,
STOS,
STR,
SUB,
TEST,
VERR, VERW,
WAIT,
WBINVD,
WRMSR,
XADD,
XCHG,
XLAT,
XOR,
COMMENT,
C_PREPROCESSOR,
UNKNOWN
} opcode_t;
#define is_pseudo(o) ((o) <= DOT_USE32)
#define N_OPCODES ((int) XOR + 1)
#define OPZ 0x01 /* Operand size prefix. */
#define ADZ 0x02 /* Address size prefix. */
typedef enum optype {
NONE, PSEUDO, JUMP, JUMP16, BYTE, WORD, OWORD /* Ordered list! */
} optype_t;
typedef enum repeat {
ONCE, REP, REPE, REPNE
} repeat_t;
typedef enum segment {
DEFSEG, CSEG, DSEG, ESEG, FSEG, GSEG, SSEG
} segment_t;
typedef struct expression {
int operator;
struct expression *left, *middle, *right;
char *name;
size_t len;
unsigned magic;
} expression_t;
typedef struct asm86 {
opcode_t opcode; /* DOT_TEXT, MOV, ... */
char *file; /* Name of the file it is found in. */
long line; /* Line number. */
optype_t optype; /* Type of operands: byte, word... */
int oaz; /* Operand/address size prefix? */
repeat_t rep; /* Repeat prefix used on this instr. */
segment_t seg; /* Segment override. */
expression_t *args; /* Arguments in ACK order. */
unsigned magic;
char * raw_string; /* each instruction can have a comment.
Instruction can be empty if the
comment is the only thing on the
line. Or the instruction can be a
preprocessor macro. It may span
multiple lines and does not contain
any instruction
*/
} asm86_t;
expression_t *new_expr(void);
void del_expr(expression_t *a);
asm86_t *new_asm86(void);
void del_asm86(asm86_t *a);
int isregister(const char *name);
#define IS_REG8(n) ((n) >= 1 && (n) <=8)
#define IS_REG16(n) ((n) >= 9 && (n) <=16)
#define IS_REG32(n) ((n) >= 17 && (n) <=24)
#define IS_REGSEG(n) ((n) >= 25 && (n) <=30)
#define IS_REGCR(n) ((n) >= 31 && (n) <=35)
#define segreg2seg(reg) ((segment_t)(reg - 25 + 1))
/*
* Format of the arguments of the asm86_t structure:
*
*
* ACK assembly operands expression_t cell:
* or part of operand: {operator, left, middle, right, name, len}
*
* [expr] {'[', nil, expr, nil}
* word {'W', nil, nil, nil, word}
* "string" {'S', nil, nil, nil, "string", strlen("string")}
* label = expr {'=', nil, expr, nil, label}
* expr * expr {'*', expr, nil, expr}
* - expr {'-', nil, expr, nil}
* (memory) {'(', nil, memory, nil}
* offset(base)(index*n) {'O', offset, base, index*n}
* base {'B', nil, nil, nil, base}
* index*4 {'4', nil, nil, nil, index}
* operand, oplist {',', operand, nil, oplist}
* label : {':', nil, nil, nil, label}
*
* The precedence of operators is ignored. The expression is simply copied
* as is, including parentheses. Problems like missing operators in the
* target language will have to be handled by rewriting the source language.
* 16-bit or 32-bit registers must be used where they are required by the
* target assembler even though ACK makes no difference between 'ax' and
* 'eax'. Asmconv is smart enough to transform compiler output. Human made
* assembly can be fixed up to be transformable.
*/
| 19.975524 | 77 | 0.610362 | [
"transform"
] |
04b90ad6dbf901dd575c3969ffeec777aae8114a | 5,072 | h | C | proj/libcalc2d/include/images/mmImagesCalculationMethodContainerWindows.h | ogx/Calculation2D | 79f9d05986227e4677a8f88309c2eb6512a3de69 | [
"Unlicense",
"MIT"
] | null | null | null | proj/libcalc2d/include/images/mmImagesCalculationMethodContainerWindows.h | ogx/Calculation2D | 79f9d05986227e4677a8f88309c2eb6512a3de69 | [
"Unlicense",
"MIT"
] | 1 | 2015-04-18T16:56:43.000Z | 2015-04-18T16:56:43.000Z | proj/libcalc2d/include/images/mmImagesCalculationMethodContainerWindows.h | ogx/Calculation2D | 79f9d05986227e4677a8f88309c2eb6512a3de69 | [
"Unlicense",
"MIT"
] | null | null | null | //******************************************************************************
//******************************************************************************
//
// images calculation method Container for Windows OS class
//
//
// Description: This header defines implementation of
// mmImages::mmImagesCalculationMethodContainerI interface
// for Windows OS using dlls.
//
//******************************************************************************
//******************************************************************************
#ifndef mmImagesCalculationMethodContainerForWindowsOSH
#define mmImagesCalculationMethodContainerForWindowsOSH
#include <interfaces\mmICalculationMethodContainer.h>
#include <log\mmLogSender.h>
////////////////////////////////////////////////////////////////////////////////
/// Definition of function type returning number of supported images
/// calculation method types.
////////////////////////////////////////////////////////////////////////////////
typedef mmInt (__stdcall *mmDLLGetSupportedImagesCalculationMethodCount)(void);
////////////////////////////////////////////////////////////////////////////////
/// Definition of function type returning structure
/// mmImages::mmImagesCalculationMethodI::sCalculationMethodParams
/// defining supported images calculation method.
////////////////////////////////////////////////////////////////////////////////
typedef mmImages::mmImagesCalculationMethodI::sCalculationMethodParams (__stdcall *mmDLLGetSupportedImagesCalculationMethodDef)(mmInt);
namespace mmImages
{
////////////////////////////////////////////////////////////////////////////////
/// Implementation of mmImages::mmImagesCalculationMethodContainerI interface for
/// windows operating system with using of dll loading.
////////////////////////////////////////////////////////////////////////////////
class mmImagesCalculationMethodContainerForWindows: public mmImagesCalculationMethodContainerI, mmLog::mmLogSender
{
private: // definitions
////////////////////////////////////////////////////////////////////////////////
/// Structure defining dll with images calculation method definition.
////////////////////////////////////////////////////////////////////////////////
typedef struct
{
////////////////////////////////////////////////////////////////////////////////
/// DLL name with full path.
////////////////////////////////////////////////////////////////////////////////
mmString sDLLName;
////////////////////////////////////////////////////////////////////////////////
/// Definition of images calculation method supported by this DLL.
////////////////////////////////////////////////////////////////////////////////
std::vector<mmImages::mmImagesCalculationMethodI::sCalculationMethodParams> vImagesCalculationMethodDefs;
} sImagesCalculationMethodInDLL;
private: // fields
////////////////////////////////////////////////////////////////////////////////
/// This vector stores available Images calculation method definitions.
////////////////////////////////////////////////////////////////////////////////
std::vector<sImagesCalculationMethodInDLL> m_vAvailableDLLs;
private: // methods
////////////////////////////////////////////////////////////////////////////////
/// This method fills all DLLs stored in application directory into m_vAvailableDLLs
/// structure.
////////////////////////////////////////////////////////////////////////////////
void SearchForDLLLibraries(void);
////////////////////////////////////////////////////////////////////////////////
/// This method searches for DLLs supporting images calculation method
/// interface and writes found calculation method names into m_vAvailableDLLs
/// structure.
////////////////////////////////////////////////////////////////////////////////
void SearchForImagesCalculationMethodsInDLLLibraries(void);
public: // methods
////////////////////////////////////////////////////////////////////////////////
/// Constructor.
///
/// @param[in] p_psMainWindow pointer to main window object
/// @param[in] p_psLogReceiver pointer to log object
////////////////////////////////////////////////////////////////////////////////
mmImagesCalculationMethodContainerForWindows(mmLog::mmLogReceiverI *p_psLogReceiver = NULL);
////////////////////////////////////////////////////////////////////////////////
/// Destructor.
////////////////////////////////////////////////////////////////////////////////
~mmImagesCalculationMethodContainerForWindows();
std::vector<mmImages::mmImagesCalculationMethodI::sCalculationMethodParams> GetAvailableImagesCalculationMethods(void);
std::map<mmString, mmString> GetMethodFileMapping(void) const;
mmImages::mmImagesCalculationMethodI* InitializeImagesCalculationMethod(mmString const & p_sCalculationMethodName);
};
};
#endif
| 52.833333 | 136 | 0.440852 | [
"object",
"vector"
] |
04bedef149e74a827d326b4103a160e8d05c38bc | 1,753 | h | C | chrome/browser/vr/vr_controller_model.h | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/vr/vr_controller_model.h | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/vr/vr_controller_model.h | metux/chromium-deb | 3c08e9b89a1b6f95f103a61ff4f528dbcd57fc42 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | // Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef CHROME_BROWSER_VR_VR_CONTROLLER_MODEL_H_
#define CHROME_BROWSER_VR_VR_CONTROLLER_MODEL_H_
#include <memory>
#include "chrome/browser/vr/gltf_asset.h"
#include "third_party/skia/include/core/SkImage.h"
#include "ui/gfx/geometry/point.h"
#include "ui/gl/gl_bindings.h"
namespace vr {
class VrControllerModel {
public:
enum State {
IDLE = 0,
TOUCHPAD,
APP,
SYSTEM,
// New ControllerStates should be added here, before STATE_COUNT.
STATE_COUNT,
};
explicit VrControllerModel(
std::unique_ptr<vr::gltf::Asset> gltf_asset,
std::vector<std::unique_ptr<vr::gltf::Buffer>> buffers);
~VrControllerModel();
const GLvoid* ElementsBuffer() const;
GLsizeiptr ElementsBufferSize() const;
const GLvoid* IndicesBuffer() const;
GLenum DrawMode() const;
GLsizeiptr IndicesBufferSize() const;
const vr::gltf::Accessor* IndicesAccessor() const;
const vr::gltf::Accessor* PositionAccessor() const;
const vr::gltf::Accessor* TextureCoordinateAccessor() const;
void SetBaseTexture(sk_sp<SkImage> image);
void SetTexture(int state, sk_sp<SkImage> patch);
sk_sp<SkImage> GetTexture(int state) const;
static std::unique_ptr<VrControllerModel> LoadFromResources();
private:
std::unique_ptr<vr::gltf::Asset> gltf_asset_;
sk_sp<SkImage> base_texture_;
sk_sp<SkImage> textures_[STATE_COUNT];
std::vector<std::unique_ptr<vr::gltf::Buffer>> buffers_;
const char* Buffer() const;
const vr::gltf::Accessor* Accessor(const std::string& key) const;
};
} // namespace vr
#endif // CHROME_BROWSER_VR_VR_CONTROLLER_MODEL_H_
| 29.216667 | 73 | 0.743297 | [
"geometry",
"vector"
] |
04bfa28fa359faccd08b7cc46b8add273396bfc9 | 707 | h | C | dcdr-worker/include/dcdr/database/SQLiteCursor.h | pacmancoder/dcdr | 15d2003ee1e52c5f9deed73f826e460c6ca374d8 | [
"MIT"
] | 2 | 2018-04-28T11:30:45.000Z | 2019-08-07T16:21:57.000Z | dcdr-worker/include/dcdr/database/SQLiteCursor.h | pacmancoder/dcdr | 15d2003ee1e52c5f9deed73f826e460c6ca374d8 | [
"MIT"
] | 8 | 2017-10-15T22:30:59.000Z | 2018-05-13T20:15:50.000Z | dcdr-worker/include/dcdr/database/SQLiteCursor.h | pacmancoder/dcdr | 15d2003ee1e52c5f9deed73f826e460c6ca374d8 | [
"MIT"
] | null | null | null | #pragma once
#include <dcdr/database/ICursor.h>
#include <memory>
#include <sqlite3.h>
namespace Dcdr::Database
{
class SQLiteCursor : public ICursor
{
public:
explicit SQLiteCursor(std::shared_ptr<sqlite3_stmt> statement);
bool is_null(size_t column) const override;
int32_t get_int(size_t column) const override;
int64_t get_int64(size_t column) const override;
double get_double(size_t column) const override;
std::string get_string(size_t column) const override;
std::vector<uint8_t> get_blob(size_t column) const override;
bool next() override;
private:
std::shared_ptr<sqlite3_stmt> statement_;
};
} | 22.806452 | 71 | 0.684583 | [
"vector"
] |
04c00d01f47f47ca42e875460ee2fa16ae0e9288 | 41,612 | c | C | src/psg/rfchan_device.c | DanIverson/OpenVnmrJ | 0db324603dbd8f618a6a9526b9477a999c5a4cc3 | [
"Apache-2.0"
] | 32 | 2016-06-17T05:04:26.000Z | 2022-03-28T17:54:44.000Z | src/psg/rfchan_device.c | DanIverson/OpenVnmrJ | 0db324603dbd8f618a6a9526b9477a999c5a4cc3 | [
"Apache-2.0"
] | 128 | 2016-07-13T17:09:02.000Z | 2022-03-28T17:53:52.000Z | src/psg/rfchan_device.c | DanIverson/OpenVnmrJ | 0db324603dbd8f618a6a9526b9477a999c5a4cc3 | [
"Apache-2.0"
] | 102 | 2016-01-23T15:27:16.000Z | 2022-03-20T05:41:54.000Z | /*
* Copyright (C) 2015 University of Oregon
*
* You may distribute under the terms of either the GNU General Public
* License or the Apache License, as specified in the LICENSE file.
*
* For more information, see the LICENSE file.
*/
/* All Channel functions are in this file */
/*-------------------------------------------------------------
| rfchan_device.c - RF Channel functions are referenced in this file
| Author: Greg Brissey 12/07/89
| Modified Author Purpose
| -------- ------ -------
|
+-------------------------------------------------------------*/
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <sys/types.h> /* for caddr_t */
#include "rfconst.h"
#include "acodes.h"
#include "oopc.h"
#include "acqparms.h"
#include "aptable.h"
#include "macros.h"
#include "abort.h"
extern int bgflag;
#ifdef DEBUG
#define DPRINT(level, str) \
if (bgflag >= level) fprintf(stdout,str)
#define DPRINT1(level, str, arg1) \
if (bgflag >= level) fprintf(stdout,str,arg1)
#define DPRINT2(level, str, arg1, arg2) \
if (bgflag >= level) fprintf(stdout,str,arg1,arg2)
#define DPRINT3(level, str, arg1, arg2, arg3) \
if (bgflag >= level) fprintf(stdout,str,arg1,arg2,arg3)
#define DPRINT4(level, str, arg1, arg2, arg3, arg4) \
if (bgflag >= level) fprintf(stdout,str,arg1,arg2,arg3,arg4)
#else
#define DPRINT(level, str)
#define DPRINT1(level, str, arg2)
#define DPRINT2(level, str, arg1, arg2)
#define DPRINT3(level, str, arg1, arg2, arg3)
#define DPRINT4(level, str, arg1, arg2, arg3, arg4)
#endif
extern char *ObjError(), *ObjCmd();
extern int okinhwloop();
extern int SetAttnAttr(Object attnobj, ...);
extern int attr_valtype(int attribute);
extern void HSgate(int ch, int state);
extern void settable90(int device, char arg[]);
extern void notinhwloop(char *name);
extern int ClearTable();
extern int Device();
extern int putcode();
extern int ap_interface;
extern int SkipHSlineTest;
#define DPRTLEVEL 1
#define NO_TABLE_USE 0
#define OK_TO_USE_TABLE 1
#define RTVAL 1
#define ABSVAL 0
typedef struct
{
#include "rfchan_device.p"
} RFChan_Object;
/* bad form to cheat like this */
typedef struct
{
#include "freq_device.p"
} Freq_Object;
/* base class dispatcher */
#define Base(this,msg,par,res) Device(this,msg,par,res)
extern int curfifocount;
extern int presHSlines;
extern int fifolpsize;
static void setphase90();
static void setphase();
static int init_attr();
static int set_attr();
static int get_attr();
static void setlkdecphase90(int device, int value);
static void setattn(Object obj, Msg_Set_Param *param, int use_table,
Msg_Set_Result *result, char *objname, int *ap_ovrride);
static void setlkdecphase90(int device, int value);
static int hibandbitmask = 0; /* dev_channel bit is set if in
* highband */
static void set_sisunity_rfband(int setwhat, int value, c68int dev_channel);
static void select_sisunity_rfband(RFChan_Object *this);
static void set_xmtrx2bit(Object obj, RFChan_Object *this);
static void set_mixerbit(Object obj, RFChan_Object *this);
static void set_ampbandrelay(Object obj, RFChan_Object *this, double basefreq);
/*-------------------------------------------------------------
| RFChan_Device()/4 - Message Handler for RFChan_devices.
| Author: Greg Brissey 12/07/89
+-------------------------------------------------------------*/
int
RFChan_Device(this, msg, param, result)
RFChan_Object *this;
Message msg;
caddr_t param;
caddr_t result;
{
int error = 0;
switch (msg)
{
case MSG_NEW_DEV_r:
error = init_attr(result);
break;
case MSG_SET_RFCHAN_ATTR_pr:
error = set_attr(this, param, result);
break;
case MSG_GET_RFCHAN_ATTR_pr:
error = get_attr(this, param, result);
break;
default:
error = Base(this, msg, param, result);
break;
}
return (error);
}
/*----------------------------------------------------------
| init_attr()/1 - create a new RFChannel device structure
| Author: Greg Brissey
+----------------------------------------------------------*/
static int init_attr(Msg_New_Result *result)
{
result->object = (Object) malloc(sizeof(RFChan_Object));
if (result->object == (Object) 0)
{
fprintf(stderr, "Insuffient memory for New RF Channel Device!!");
return (NO_MEMORY);
}
ClearTable(result->object, sizeof(RFChan_Object)); /* besure all clear */
result->object->dispatch = (Functionp) RFChan_Device;
return (0);
}
/*----------------------------------------------------------
| set_attr()/3 - static routine that has access to Channel device
| attributes, address,register,bytes,mode
| Author: Greg Brissey 6/14/89
+----------------------------------------------------------*/
static int set_attr(RFChan_Object *this, Msg_Set_Param *param, Msg_Set_Result *result)
{
int error = 0;
extern double calcoffsetsyn();
extern double calcfixedoffset();
result->resultcode = result->genfifowrds = result->reqvalue = 0;
result->DBreqvalue = 0.0;
switch (param->setwhat)
{
case SET_XMTRTYPE:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to %d, for device: '%s'\n",
ObjCmd(param->setwhat), param->value, this->objname);
/* this->newtrans = *( (int *) (param->argptr)); */
this->newxmtr = (int) param->value;
break;
case SET_AMPTYPE:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to %d, for device: '%s'\n",
ObjCmd(param->setwhat), param->value, this->objname);
this->newamp = param->value;
break;
case SET_XMTR2AMPBDBIT:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to %d, for device: '%s'\n",
ObjCmd(param->setwhat), param->value, this->objname);
this->xmtr2ampbit = param->value; /* relay bit for amp hi/low
* band */
break;
case SET_XMTRX2BIT:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to %d, for device: '%s'\n",
ObjCmd(param->setwhat), param->value, this->objname);
this->xmtrx2bit = param->value; /* relay bit for amp hi/low
* band */
break;
case SET_AMPHIMIN:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to %lf, for device: '%s'\n",
ObjCmd(param->setwhat), param->DBvalue, this->objname);
this->amphibandmin = param->DBvalue;
break;
case SET_FREQOBJ:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to 0x%lx, for device: '%s'\n",
ObjCmd(param->setwhat), *((Object *) param->valptr), this->objname);
this->FreqObj = *((Object *) param->valptr);
break;
case SET_ATTNOBJ:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to 0x%lx, for device: '%s'\n",
ObjCmd(param->setwhat), *((Object *) param->valptr), this->objname);
this->AttnObj = *((Object *) param->valptr);
break;
case SET_HS_OBJ:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to 0x%lx, for device: '%s'\n",
ObjCmd(param->setwhat), *((Object *) param->valptr), this->objname);
this->HSObj = *((Object *) param->valptr);
break;
case SET_MIXER_OBJ:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to 0x%lx, for device: '%s'\n",
ObjCmd(param->setwhat), *((Object *) param->valptr), this->objname);
this->MixerObj = *((Object *) param->valptr);
break;
case SET_MOD_OBJ:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to 0x%lx, for device: '%s'\n",
ObjCmd(param->setwhat), *((Object *) param->valptr), this->objname);
this->ModulObj = *((Object *) param->valptr);
break;
case SET_XGMODE_OBJ:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to 0x%lx, for device: '%s'\n",
ObjCmd(param->setwhat), *((Object *) param->valptr), this->objname);
this->GateObj = *((Object *) param->valptr);
break;
case SET_LNATTNOBJ:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to 0x%lx, for device: '%s'\n",
ObjCmd(param->setwhat), *((Object *) param->valptr), this->objname);
this->LnAttnObj = *((Object *) param->valptr);
break;
case SET_HLBRELAYOBJ:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to 0x%lx, for device: '%s'\n",
ObjCmd(param->setwhat), *((Object *) param->valptr), this->objname);
this->HLBrelayObj = *((Object *) param->valptr);
break;
case SET_XMTRX2OBJ:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to 0x%lx, for device: '%s'\n",
ObjCmd(param->setwhat), *((Object *) param->valptr), this->objname);
this->XmtrX2Obj = *((Object *) param->valptr);
break;
case SET_MOD_MODE:
DPRINT1(DPRTLEVEL,"SET_MOD_MODE for %s\n",this->objname);
param->setwhat = SET_MASK;
error = Send(this->ModulObj, MSG_SET_AP_ATTR_pr, param, result);
break;
case SET_GATE_MODE:
DPRINT1(DPRTLEVEL,"SET_MOD_MODE for %s\n",this->objname);
param->setwhat = SET_MASK;
error = Send(this->GateObj, MSG_SET_AP_ATTR_pr, param, result);
break;
case SET_HSSEL_FALSE:
param->setwhat = SET_FALSE;
error = Send(this->HSObj, MSG_SET_APBIT_MASK_pr, param, result);
break;
case SET_HSSEL_TRUE:
param->setwhat = SET_TRUE;
error = Send(this->HSObj, MSG_SET_APBIT_MASK_pr, param, result);
break;
case SET_HS_VALUE:
param->setwhat = SET_VALUE;
error = Send(this->HSObj, MSG_SET_AP_ATTR_pr, param, result);
break;
case SET_MIXER_VALUE:
if (param->value < 0)
{
/* standard creation of acodes */
param->setwhat = SET_VALUE;
error = Send(this->MixerObj, MSG_SET_AP_ATTR_pr, param, result);
}
else
{
/* create acodes in global table given by param->value */
param->setwhat = SET_GTAB;
error = Send(this->MixerObj, MSG_SET_AP_ATTR_pr, param, result);
}
break;
case SET_MOD_VALUE:
param->setwhat = SET_VALUE;
error = Send(this->ModulObj, MSG_SET_AP_ATTR_pr, param, result);
break;
case SET_XGMODE_VALUE:
param->setwhat = SET_VALUE;
error = Send(this->GateObj, MSG_SET_AP_ATTR_pr, param, result);
break;
case SET_SPECFREQ: /* sfrq or dfrq */
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to %lf, for device: '%s'\n",
ObjCmd(param->setwhat), param->DBvalue, this->objname);
/* set base frequency */
error = Send(this->FreqObj, MSG_SET_FREQ_ATTR_pr, param, result);
if (error < 0)
{
abort_message("%s : %s '%s'\n", this->objname, ObjError(error),
ObjCmd(param->setwhat));
}
set_ampbandrelay(this->HLBrelayObj, this,param->DBvalue);
if (this->XmtrX2Obj != (Object) NULL)
set_xmtrx2bit(this->XmtrX2Obj, this);
break;
case SET_INIT_OFFSET: /* initial setting of tof or dof frequency */
case SET_OFFSETFREQ: /* subsequent setting of tof or dof frequency */
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to %lf, for device: '%s'\n",
ObjCmd(param->setwhat), param->DBvalue, this->objname);
/* set base frequency */
error = Send(this->FreqObj, MSG_SET_FREQ_ATTR_pr, param, result);
if (error < 0)
{
abort_message("%s : %s '%s'\n", this->objname, ObjError(error),
ObjCmd(param->setwhat));
}
/* select the high or low band of the transmitter for SIS Unity*/
select_sisunity_rfband(this);
if (this->XmtrX2Obj != (Object) NULL)
set_xmtrx2bit(this->XmtrX2Obj, this);
if (this->MixerObj != (Object) NULL)
set_mixerbit(this->MixerObj, this);
break;
case SET_PTSOPTIONS:
case SET_IFFREQ:
case SET_RFTYPE:
case SET_H1FREQ:
case SET_RFBAND:
case SET_FREQSTEP:
case SET_OSYNBFRQ:
case SET_OSYNCFRQ:
case SET_OVRUNDRFLG:
case SET_SWEEPCENTER:
case SET_SWEEPWIDTH:
case SET_SWEEPNP:
case SET_SWEEPMODE:
case SET_INITSWEEP:
case SET_INCRSWEEP:
case SET_OFFSETFREQ_STORE:
case SET_FREQ_FROMSTORAGE:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to %lf, for device: '%s'\n",
ObjCmd(param->setwhat), param->DBvalue, this->objname);
error = Send(this->FreqObj, MSG_SET_FREQ_ATTR_pr, param, result);
if (error < 0)
{
abort_message("%s : %s '%s'\n", this->objname, ObjError(error),
ObjCmd(param->setwhat));
}
break;
case SET_FREQVALUE: /* generate acode for frequency */
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to %lf, for device: '%s'\n",
ObjCmd(param->setwhat), param->DBvalue, this->objname);
param->setwhat = SET_VALUE;
error = Send(this->FreqObj, MSG_SET_FREQ_ATTR_pr, param, result);
if (error < 0)
{
abort_message("%s : %s '%s'\n", this->FreqObj->objname, ObjError(error),
ObjCmd(param->setwhat));
}
/* If SIS unity system this will set rfband acodes */
set_sisunity_rfband(SET_VALUE,0,this->dev_channel);
break;
case SET_FREQLIST: /* gen acode for frequency table list */
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to %lf, for device: '%s'\n",
ObjCmd(param->setwhat), param->DBvalue, this->objname);
param->setwhat = SET_GTAB;
error = Send(this->FreqObj, MSG_SET_FREQ_ATTR_pr, param, result);
if (error < 0)
{
abort_message("%s : %s '%s'\n", this->FreqObj->objname, ObjError(error),
ObjCmd(param->setwhat));
}
/* If SIS unity system this will set rfband acodes */
set_sisunity_rfband(SET_GTAB,param->value,this->dev_channel);
break;
case SET_RTPWR:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to %d, for device: '%s'\n",
ObjCmd(param->setwhat), param->value, this->objname);
if (this->AttnObj != NULL) /* no attenuator */
{
param->setwhat = SET_RTPARAM; /* use attn object command */
setattn(this->AttnObj, param, OK_TO_USE_TABLE, result, this->objname,
this->ap_ovrride);
}
else
{
if (ix == 1)
fprintf(stdout,
"%s: '%s' statement ignored due to system configuration.\n",
this->objname, ObjCmd(param->setwhat));
return(error);
}
break;
case SET_RTPWRF:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to %d, for device: '%s'\n",
ObjCmd(param->setwhat), param->value, this->objname);
if (this->LnAttnObj != NULL) /* no fine attenuator */
{
param->setwhat = SET_RTPARAM; /* use attn object command */
setattn(this->LnAttnObj, param, OK_TO_USE_TABLE, result, this->objname,
this->ap_ovrride);
}
else
{
if (ix == 1)
fprintf(stdout,
"%s: '%s' statement ignored due to system configuration.\n",
this->objname, ObjCmd(param->setwhat));
return(error);
}
break;
case SET_PWR:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to %d, for device: '%s'\n",
ObjCmd(param->setwhat), param->value, this->objname);
if (this->AttnObj != NULL) /* no coarse attenuator */
{
param->setwhat = SET_VALUE; /* use attn object command */
setattn(this->AttnObj, param, NO_TABLE_USE, result, this->objname,
this->ap_ovrride);
}
else
{
if (ix == 1)
fprintf(stdout,
"%s: '%s' statement ignored due to system configuration.\n",
this->objname, ObjCmd(param->setwhat));
return(error);
}
break;
case SET_PWRF:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to %d, for device: '%s'\n",
ObjCmd(param->setwhat), param->value, this->objname);
if (this->LnAttnObj != NULL) /* no fine attenuator */
{
param->setwhat = SET_VALUE; /* use attn object command */
if (param->value < 0)
param->value = 0;
else if (param->value > 4095)
param->value = 4095;
setattn(this->LnAttnObj, param, NO_TABLE_USE, result, this->objname,
this->ap_ovrride);
}
else
{
if (ix == 1)
fprintf(stdout,
"%s: '%s' statement ignored due to system configuration.\n",
this->objname, ObjCmd(param->setwhat));
return(error);
}
break;
case SET_GATE_PHASE:
{
putcode(APBOUT);
putcode(1);
putcode(APSELECT | 0xb00 | ( 0x92 + (this->dev_channel - 1) * 16) );
putcode(APWRITE | 0xb00 | param->value );
curfifocount += 2;
break;
}
case SET_PHLINE0:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to 0x%x, for device: '%s'\n",
ObjCmd(param->setwhat), param->value, this->objname);
this->phasetbl[0] = param->value;
break;
case SET_PHLINE90:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to 0x%x, for device: '%s'\n",
ObjCmd(param->setwhat), param->value, this->objname);
this->phasetbl[1] = param->value;
break;
case SET_PHLINE180:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to 0x%x, for device: '%s'\n",
ObjCmd(param->setwhat), param->value, this->objname);
this->phasetbl[2] = param->value;
break;
case SET_PHLINE270:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to 0x%x, for device: '%s'\n",
ObjCmd(param->setwhat), param->value, this->objname);
this->phasetbl[3] = param->value;
break;
case SET_PHASEBITS:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to 0x%x, for device: '%s'\n",
ObjCmd(param->setwhat), param->value, this->objname);
this->phasebits = param->value;
break;
case SET_PHASESTEP:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to %lf, for device: '%s'\n",
ObjCmd(param->setwhat), param->DBvalue, this->objname);
if (!this->newxmtr)
{
abort_message("%s: requires direct synthesis RF on %s\n",
ObjCmd(param->setwhat), this->objname);
}
notinhwloop("stepsize");
if (ap_interface < 4)
this->phasestep = (int) ((param->DBvalue * 2.0) + .50005);
else
this->phasestep = (int) ((param->DBvalue * 4.0) + .50005);
putcode(PHASESTEP);
putcode(this->dev_channel); /* TRans = 1, Dec = 2 */
putcode(this->phasestep);
break;
case SET_PHASEAPADR:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to %d, for device: '%s'\n",
ObjCmd(param->setwhat), param->value, this->objname);
this->sphaseaddr = param->value;
break;
case SET_PHASE_REG:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to %d, for device: '%s'\n",
ObjCmd(param->setwhat), param->value, this->objname);
this->sphasereg = param->value;
break;
case SET_PHASE_MODE:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to %d, for device: '%s'\n",
ObjCmd(param->setwhat), param->value, this->objname);
this->sphasemode = param->value;
break;
case SET_PHASEATTR:
DPRINT2(DPRTLEVEL,
"set_attr: Cmd: '%s' for device: '%s'\n",
ObjCmd(param->setwhat), this->objname);
putcode(SETPHATTR); /* new acode */
putcode(this->dev_channel);
{
putcode( (((this->phasetbl[0]) >> 16) & 0xffff) );
putcode( ((this->phasetbl[0]) & 0xffff) );
putcode( (((this->phasetbl[1]) >> 16) & 0xffff) );
putcode( ((this->phasetbl[1]) & 0xffff) );
putcode( (((this->phasetbl[2]) >> 16) & 0xffff) );
putcode( ((this->phasetbl[2]) & 0xffff) );
putcode( (((this->phasetbl[3]) >> 16) & 0xffff) );
putcode( ((this->phasetbl[3]) & 0xffff) );
putcode( (((this->phasebits)>>16) & 0xffff) );
putcode( ((this->phasebits) & 0xffff) );
}
putcode(this->sphaseaddr);
if (ap_interface == 4) putcode(this->sphasereg);
break;
case SET_RTPHASE90:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to %d, for device: '%s'\n",
ObjCmd(param->setwhat), param->value, this->objname);
if (this->newxmtr == TRUE) /* not for lock/decoup brd this->newxmtr == TRUE+1 */
{
setphase90(this->dev_channel, param->value);
}
else if (this->newxmtr == TRUE+1)
{
setlkdecphase90(this->dev_channel, param->value);
}
break;
case SET_PHASE90:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to %s, for device: '%s'\n",
ObjCmd(param->setwhat), param->valptr, this->objname);
if (param->valptr[0] != '\0')
settable90(this->dev_channel, param->valptr);
break;
case SET_RTPHASE:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to %d, for device: '%s'\n",
ObjCmd(param->setwhat), param->value, this->objname);
/* Check RF consistency. */
if (!this->newxmtr)
{
abort_message("%s: requires direct synthesis RF on %s\n",
ObjCmd(param->setwhat), this->objname);
}
if (this->newxmtr == TRUE) /* not for lock/decoup brd this->newxmtr == TRUE+1 */
{
setphase(this->dev_channel, param->value, RTVAL, OK_TO_USE_TABLE,
this->ap_ovrride,this->sphasemode);
}
break;
case SET_PHASE:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to %d, for device: '%s'\n",
ObjCmd(param->setwhat), param->value, this->objname);
/* Check RF consistency. */
if (!this->newxmtr)
{
abort_message("%s: requires direct synthesis RF on %s\n",
ObjCmd(param->setwhat), this->objname);
}
setphase(this->dev_channel, param->value, ABSVAL, NO_TABLE_USE,
this->ap_ovrride,this->sphasemode);
break;
case SET_APOVRADR:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to 0x%lx, for device: '%s'\n",
ObjCmd(param->setwhat), param->valptr, this->objname);
this->ap_ovrride = ((int *) param->valptr);
break;
case SET_HSLADDR:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to 0x%lx, for device: '%s'\n",
ObjCmd(param->setwhat), param->valptr, this->objname);
this->HSlineptr = ((int *) param->valptr);
break;
case SET_RCVRGATEBIT:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to 0x%x, for device: '%s'\n",
ObjCmd(param->setwhat), param->value, this->objname);
/* HSline bit to gate xmtr with */
this->rcvrgateHSbit = param->value; /* create bit mask for gate */
break;
case SET_XMTRGATEBIT:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to 0x%x, for device: '%s'\n",
ObjCmd(param->setwhat), param->value, this->objname);
/* HSline bit to gate xmtr with */
this->xmtrgateHSbit = param->value; /* create bit mask for gate */
break;
case SET_RCVRGATE:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to %d, for device: '%s'\n",
ObjCmd(param->setwhat), param->value, this->objname);
/* Receiver gate is inverted polarity */
if (param->value)
HSgate(this->rcvrgateHSbit,FALSE);
else
HSgate(this->rcvrgateHSbit,TRUE);
break;
case SET_XMTRGATE:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to %d, for device: '%s'\n",
ObjCmd(param->setwhat), param->value, this->objname);
if (param->value)
HSgate(this->xmtrgateHSbit,TRUE);
else
HSgate(this->xmtrgateHSbit,FALSE);
if (this->newxmtr > TRUE ) /* (this->newxmtr == TRUE+1). i.e. lock/dec rftype */
{
/* lock/dec on/off must be handled in the console because the lockpower must be
re-established, since the decoupler power will effect the lock power from
altering the 20 db atten in the magnet leg
*/
/* bit 0 - LO 0=on,1=off (off for decoupling */
/* bit 1 - Lk/Dec Xmtr Gate 0=off,1=on */
/* bit 7 - Lk/Dec Decoupler enable 1=on 0=off */
Msg_Set_Param decparam;
Msg_Set_Result decresult;
int error;
int apadr,apreg;
decparam.setwhat = GET_ADR;
error = Send(this->HSObj, MSG_GET_AP_ATTR_pr, &decparam, &decresult);
if (error < 0)
{
abort_message("%s : %s '%s'\n", this->objname, ObjError(error),
ObjCmd(param->setwhat));
}
apadr = decresult.reqvalue;
decparam.setwhat = GET_REG;
decresult.reqvalue = 0;
error = Send(this->HSObj, MSG_GET_AP_ATTR_pr, &decparam, &decresult);
if (error < 0)
{
abort_message("%s : %s '%s'\n", this->objname, ObjError(error),
ObjCmd(param->setwhat));
}
apreg = decresult.reqvalue;
if (param->value)
{
/* turn on Lk/Dec Decoupler Xmtr Gate */
putcode((c68int) LOCKDEC_ON_OFF);
putcode((c68int) (apadr << 8) | (0xff & apreg));
putcode((c68int) param->value); /* 1 = On */
putcode((c68int) 32); /* 32 = STD AP delay 400 nsec */
#ifdef XXX
decparam.setwhat = SET_MASK;
decparam.value = 0x83; /* 0x80 dec enable, 2 - Dec Xmtr Gate On, 1 LO off */
error = Send(this->HSObj, MSG_SET_AP_ATTR_pr, &decparam, &decresult);
decparam.setwhat = SET_VALUE;
error = Send(this->HSObj, MSG_SET_AP_ATTR_pr, &decparam, &decresult);
#endif
if ( (ix == 1) && (bgflag) )
fprintf(stderr,"lock/dec: Turn-On Xmtr: apaddr: 0x%x\n",(apadr << 8) | (0xff & apreg));
}
else
{
/* turn Off Lk/Dec Decoupler Xmtr Gate */
putcode((c68int) LOCKDEC_ON_OFF);
putcode((c68int) (apadr << 8) | (0xff & apreg));
putcode((c68int) param->value); /* 1 = On */
putcode((c68int) 32); /* 32 = STD AP delay 400 nsec */
#ifdef XXX
decparam.setwhat = SET_MASK;
decparam.value = 0x01; /* 0x00 dec disable, 1 - Dec Xmtr Gate Off, LO off */
error = Send(this->HSObj, MSG_SET_AP_ATTR_pr, &decparam, &decresult);
decparam.setwhat = SET_VALUE;
error = Send(this->HSObj, MSG_SET_AP_ATTR_pr, &decparam, &decresult);
#endif
if ( (ix == 1) && (bgflag) )
fprintf(stderr,"lock/dec: Turn-Off Xmtr: apaddr: 0x%x\n",(apadr << 8) | (0xff & apreg));
}
}
break;
case SET_WGGATEBIT:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to %d, for device: '%s'\n",
ObjCmd(param->setwhat), param->value, this->objname);
/* HSline bit to gate wg with */
this->wg_gateHSbit = param->value; /* relay bit for amp hi/low
* band */
break;
case SET_WGGATE:
DPRINT3(DPRTLEVEL,
"set_attr: Cmd: '%s' to %d, for device: '%s'\n",
ObjCmd(param->setwhat), param->value, this->objname);
if (param->value)
HSgate(this->wg_gateHSbit,TRUE);
else
HSgate(this->wg_gateHSbit,FALSE);
break;
default:
error = UNKNOWN_RFCHAN_ATTR;
result->resultcode = UNKNOWN_RFCHAN_ATTR;
break;
}
return (error);
}
/*----------------------------------------------------------
| get_attr()/3 - static routine that has access to RF Chan device
| Author: Greg Brissey 12/07/89
+----------------------------------------------------------*/
static int get_attr(RFChan_Object *this, Msg_Set_Param *param, Msg_Set_Result *result)
{
int error = 0;
Msg_Set_Param forAttn; /* Used to get current attenuator value */
Msg_Set_Result xresult; /* Used to get maximum attenuator value */
result->resultcode = 0;
result->genfifowrds = 0;
result->reqvalue = 0;
switch (param->setwhat)
{
case GET_XMTRTYPE:
result->reqvalue = this->newxmtr;
DPRINT3(DPRTLEVEL,
"get_attr: Cmd: '%s', is %d for device: '%s'\n",
ObjCmd(param->setwhat), result->reqvalue, this->objname);
break;
case GET_AMPTYPE: /* obsserve, decoupler, etc */
result->reqvalue = this->newamp;
DPRINT3(DPRTLEVEL,
"get_attr: Cmd: '%s', is %d for device: '%s'\n",
ObjCmd(param->setwhat), result->reqvalue, this->objname);
break;
case GET_PHASEBITS:
result->reqvalue = this->phasebits;
DPRINT3(DPRTLEVEL,
"get_attr: Cmd: '%s', is 0x%x for device: '%s'\n",
ObjCmd(param->setwhat), result->reqvalue, this->objname);
break;
case GET_HIBANDMASK: /* obsserve, decoupler, etc */
result->reqvalue = hibandbitmask; /* static param */
DPRINT3(DPRTLEVEL,
"get_attr: Cmd: '%s', is 0x%x for device: '%s'\n",
ObjCmd(param->setwhat), result->reqvalue, this->objname);
break;
case GET_AMPHIBAND: /* amplifier band for this channel */
result->reqvalue = (hibandbitmask & (1 << this->dev_channel)) ?
1 : 0;
DPRINT3(DPRTLEVEL,
"get_attr: Cmd: '%s', is 0x%x for device: '%s'\n",
ObjCmd(param->setwhat), result->reqvalue, this->objname);
break;
case GET_XMTRGATE:
result->reqvalue = *this->HSlineptr;
DPRINT3(DPRTLEVEL,
"get_attr: Cmd: '%s', is 0x%x for device: '%s'\n",
ObjCmd(param->setwhat), result->reqvalue, this->objname);
break;
case GET_XMTRGATEBIT: /* HSline bit to gate xmtr with */
result->reqvalue = this->xmtrgateHSbit;
DPRINT3(DPRTLEVEL,
"get_attr: Cmd: '%s' to 0x%x, for device: '%s'\n",
ObjCmd(param->setwhat), param->value, this->objname);
break;
/* Respond to these requests by passing them to the Frequency Object
that is part of each RF Channel Object. */
case GET_OF_FREQ:
case GET_PTS_FREQ:
case GET_SPEC_FREQ:
case GET_BASE_FREQ:
case GET_RFBAND:
case GET_FREQSTEP:
case GET_SWEEPCENTER:
case GET_SWEEPWIDTH:
case GET_SWEEPNP:
case GET_SWEEPINCR:
case GET_SWEEPMODE:
case GET_SWEEPMAXWIDTH:
case GET_LBANDMAX:
case GET_MAXXMTRFREQ:
DPRINT2(DPRTLEVEL,
"get_attr: Cmd: '%s' is forwarded to device: '%s'\n",
ObjCmd(param->setwhat), this->FreqObj->objname);
error = Send(this->FreqObj, MSG_GET_FREQ_ATTR_pr, param, result);
if (error < 0)
{
abort_message("%s : %s '%s'\n", this->objname, ObjError(error),
ObjCmd(param->setwhat));
}
break;
/* Respond to this request by asking the Attenuator Object for its value. */
/* Find out its maximum value, if 127 or 255 (for 255 high bit is rf */
/* band bit) divide value by 2 and round up. */
case GET_PWR:
forAttn.setwhat = GET_VALUE;
error = Send(this->AttnObj, MSG_GET_ATTN_ATTR_pr, &forAttn, result);
if (error < 0)
{
abort_message("%s : %s '%s'\n", this->objname, ObjError(error),
ObjCmd(param->setwhat));
}
forAttn.setwhat = GET_MAXVAL;
xresult.reqvalue = 0;
error = Send(this->AttnObj, MSG_GET_ATTN_ATTR_pr, &forAttn, &xresult);
if (error < 0)
{
abort_message("%s : %s '%s'\n", this->objname, ObjError(error),
ObjCmd(param->setwhat));
}
if ((xresult.reqvalue == SIS_UNITY_ATTN_MAX) ||
(xresult.reqvalue == 255) )
{
result->reqvalue = (result->reqvalue/2) + (result->reqvalue%2);
}
break;
case GET_PWRF:
if (this->LnAttnObj != NULL) /* no fine attenuator */
{
forAttn.setwhat = GET_VALUE;
error = Send(this->LnAttnObj, MSG_GET_ATTN_ATTR_pr,
&forAttn, result);
if (error < 0)
{
abort_message("%s : %s '%s'\n", this->objname, ObjError(error),
ObjCmd(param->setwhat));
}
}
else
error = -1;
break;
default:
error = UNKNOWN_RFCHAN_ATTR;
result->resultcode = UNKNOWN_RFCHAN_ATTR;
}
return (error);
}
/*---------------------------------------------------------------------
| SetRFChanAttr - Set Channel Device to List of Attributes
| Author: Greg Brissey 8/18/88
+---------------------------------------------------------------------*/
/*VARARGS2*/
int SetRFChanAttr(Object obj, ...)
{
va_list vargs;
int error = 0;
int error2 = 0;
Msg_Set_Param param;
Msg_Set_Result result;
va_start(vargs, obj);
/* Options allways follow the format 'Option,(value),Option,(value),etc' */
while ((param.setwhat = va_arg(vargs, int)) != 0)
{
switch (attr_valtype(param.setwhat))
{
case NO_VALUE:
break;
case INTEGER:
param.value = (int) va_arg(vargs, int);
break;
case DOUBLE:
param.DBvalue = (double) va_arg(vargs, double);
break;
case POINTER:
param.valptr = (char *) va_arg(vargs, long);
break;
default:
abort_message("Value Type unknown for Object.");
}
error = Send(obj, MSG_SET_RFCHAN_ATTR_pr, ¶m, &result);
if (error < 0)
{
error2 = Send(obj, MSG_SET_DEV_ATTR_pr, ¶m, &result);
if (error2 < 0)
{
abort_message("%s : %s '%s'\n", obj->objname, ObjError(error),
ObjCmd(param.setwhat));
}
}
}
va_end(vargs);
return (error);
}
/*----------------------------------------------------------------------
| setattn()/6 - generic routine to set an attenutor through its Object
+-----------------------------------------------------------------------*/
static void setattn(Object obj, Msg_Set_Param *param, int use_table,
Msg_Set_Result *result, char *objname, int *ap_ovrride)
{
int error;
okinhwloop();
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
if ( fifolpsize < 100 )
{
if (*ap_ovrride)
{
*ap_ovrride = 0;
}
else
{
G_Delay(DELAY_TIME, 0.2e-6, 0); /* allows high-speed lines to be set
* prior to addressing the AP bus.
* S.F. */
}
}
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/*********************************************
* Set up table access for power statement. *
*********************************************/
if (use_table == OK_TO_USE_TABLE)
{
if ((param->value >= t1) && (param->value <= t60))
{
param->value = tablertv(param->value);
}
}
error = Send(obj, MSG_SET_ATTN_ATTR_pr, param, result);
if (error < 0)
{
abort_message("%s : %s '%s'\n", objname, ObjError(error),
ObjCmd(param->setwhat));
}
return;
}
/*----------------------------------------------------------------------
| setphase90()/4 - generic routine to set phase quadrent
+-----------------------------------------------------------------------*/
static void
setphase90(device, value)
int device;
int value;
{
okinhwloop(); /* legal in hardware loop */
/*********************************************
* Set up table access for phase statement. *
*********************************************/
if ((value >= t1) && (value <= t60))
{
value = tablertv(value);
}
putcode(SETPHAS90); /* replaces TXPHASE, DECPHASE */
putcode(device);
putcode(value);
return;
}
/*----------------------------------------------------------------------
| setlkdecphase90()/4 - routine to set phase quadrent of lock/decouper brd
+-----------------------------------------------------------------------*/
static void setlkdecphase90(int device, int value)
{
okinhwloop(); /* legal in hardware loop */
/*********************************************
* Set up table access for phase statement. *
*********************************************/
if ((value >= t1) && (value <= t60))
{
value = tablertv(value);
}
putcode(LOCKDECPHS90); /* replaces TXPHASE, DECPHASE */
putcode(device);
putcode(value);
return;
}
/*----------------------------------------------------------------------
| setphase()/5 - generic routine to set small angle & quadrent phase
+-----------------------------------------------------------------------*/
static void
setphase(device, value, rtflag, use_table, ap_ovrride, mode)
int device;
int value;
int rtflag;
int use_table;
int *ap_ovrride;
int mode;
{
int flags;
okinhwloop(); /* legal in hardware loop */
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
if ( fifolpsize < 100 ) /* Just for old OB board */
{
if (*ap_ovrride)
{
*ap_ovrride = 0;
}
else
{
G_Delay(DELAY_TIME, 0.2e-6, 0); /* allows high-speed lines to be set
* prior to addressing the AP bus.
* S.F. */
}
}
/* ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ */
/*********************************************
* Set up table access for phase statement. *
*********************************************/
flags = 0x0;
if (use_table == OK_TO_USE_TABLE)
{
if ((value >= t1) && (value <= t60))
{
value = tablertv(value);
}
}
else
flags = 0x0100;
if (rtflag) flags = 0x0; /* rt value */
if (mode == 2)
flags |= 0x0200;
putcode(SETPHASE);
putcode((device) | flags);
putcode(value);
if (mode == 2)
curfifocount += 3; /* Unity+ gets 3 fifo words */
else
curfifocount++; /* Unity gets 1, increment current fifo count */
return;
}
/*-----------------------------------------------------
| set transmitter to Amplifier Band Relay
+-----------------------------------------------------*/
static void set_ampbandrelay(Object obj, RFChan_Object *this, double basefreq)
{
int error = 0;
Msg_Set_Param chparam;
Msg_Set_Result chresult;
if (obj != NULL)
{
/* based on the base frequency set routing relay to proper band of Amp. */
/* For Hydra this is double checked in initfunc.c set_ampbit() */
chparam.setwhat = (basefreq > this->amphibandmin) ?
SET_FALSE : SET_TRUE;
chparam.value = this->xmtr2ampbit; /* OBS_RELAY, DEC_RELAY, DEC2_RELAY */
/* HILO_CH1, HILO_CH2, HILO_CH3 */
error = Send(obj, MSG_SET_APBIT_MASK_pr, &chparam, &chresult);
if (error < 0)
{
abort_message("%s : %s '%s'\n", this->objname, ObjError(error),
ObjCmd(chparam.setwhat));
}
/* set global channel high band bit mask */
if (chparam.setwhat == SET_FALSE)
hibandbitmask |= (1 << this->dev_channel);
else
hibandbitmask &= ~(1 << this->dev_channel);
}
}
/*-----------------------------------------------------
| set transmitter mixer relay
+-----------------------------------------------------*/
static void set_mixerbit(Object obj, RFChan_Object *this)
{
int error = 0;
Msg_Set_Param chparam;
Msg_Set_Result chresult;
if (obj != NULL)
{ chparam.setwhat = GET_SPEC_FREQ;
error = Send(this->FreqObj, MSG_GET_FREQ_ATTR_pr, &chparam, &chresult);
if (error < 0)
{
abort_message("%s : %s '%s'\n", this->objname, ObjError(error),
ObjCmd(chparam.setwhat));
}
/* base on the rf band of the frequency set xmtr board doubling line. */
chparam.setwhat = SET_MASK;
chparam.value = (chresult.DBreqvalue > 1.5e8 ) ? 0x80 : 0x0;
error = Send(obj, MSG_SET_AP_ATTR_pr, &chparam, &chresult);
if (error < 0)
{
abort_message("%s : %s '%s'\n", this->objname, ObjError(error),
ObjCmd(chparam.setwhat));
}
}
}
/*-----------------------------------------------------
| set transmitter to Amplifier Band Relay
+-----------------------------------------------------*/
static void set_xmtrx2bit(Object obj, RFChan_Object *this)
{
int error = 0;
Msg_Set_Param chparam;
Msg_Set_Result chresult;
if (obj != NULL)
{
chparam.setwhat = GET_RFBAND;
error = Send(this->FreqObj, MSG_GET_FREQ_ATTR_pr, &chparam, &chresult);
if (error < 0)
{
abort_message("%s : %s '%s'\n", this->objname, ObjError(error),
ObjCmd(chparam.setwhat));
}
/* base on the rf band of the frequency set xmtr board doubling line. */
chparam.setwhat = (chresult.reqvalue == RF_HIGH_BAND) ?
SET_TRUE : SET_FALSE;
chparam.value = this->xmtrx2bit; /* OBS_XMTR_HI_LOW_BAND,DEC_..,DEC2_..
* */
error = Send(obj, MSG_SET_APBIT_MASK_pr, &chparam, &chresult);
if (error < 0)
{
abort_message("%s : %s '%s'\n", this->objname, ObjError(error),
ObjCmd(chparam.setwhat));
}
}
}
/*-----------------------------------------------------------------------
| For SIS Unity Systems
| select_sisunity_rfband
| - Selects a high or low band
| for either the observe or decouple transmitter.
| - The setting of the band is done in the same apbus
| location as the signal attenuation is selected.
| The signal attenuation is in the lower 7 bits the
| rf band selection is in the msb.
| - Increments frq_codes by ??;
+------------------------------------------------------------------------*/
static void select_sisunity_rfband(RFChan_Object *this)
{
int error = 0;
int band_select;
Msg_Set_Param chparam;
Msg_Set_Result chresult;
if ((cattn[this->dev_channel] == SIS_UNITY_ATTN_MAX) &&
((rftype[this->dev_channel-1] == 'c') ||
(rftype[this->dev_channel-1] == 'C')))
{
chparam.setwhat = GET_RFBAND;
error = Send(this->FreqObj, MSG_GET_FREQ_ATTR_pr, &chparam, &chresult);
if (error < 0)
{
abort_message("%s : %s '%s'\n", this->objname, ObjError(error),
ObjCmd(chparam.setwhat));
}
band_select = (chresult.reqvalue == RF_HIGH_BAND) ?
1 : 0;
if (this->dev_channel == OBSERVE)
SetAttnAttr(ToAttn, SET_RFBAND, band_select,NULL);
if (this->dev_channel == DECOUPLER)
SetAttnAttr(DoAttn, SET_RFBAND, band_select,NULL);
}
}
/*-----------------------------------------------------------------------
| For SIS Unity Systems
| set_sisunity_rfband
| - Creates the apwords to select a high or low band.
| - The setting of the band is done in the same apbus
| location as the signal attenuation is selected.
| The signal attenuation is in the lower 7 bits the
| rf band selection is in the msb.
| - Increments frq_codes by ??;
+------------------------------------------------------------------------*/
static void set_sisunity_rfband(int setwhat, int value, c68int dev_channel)
{
if ((cattn[dev_channel] == SIS_UNITY_ATTN_MAX) &&
((rftype[dev_channel-1] == 'c') || (rftype[dev_channel-1] == 'C')) )
{
if (dev_channel == OBSERVE)
SetAttnAttr(ToAttn, setwhat, value,NULL);
if (dev_channel == DECOUPLER)
SetAttnAttr(DoAttn, setwhat, value,NULL);
}
}
| 31.263711 | 105 | 0.572984 | [
"object"
] |
04c297b350460896ef78427ab2df3ade212e3edf | 863 | h | C | Source/GFF.h | alex-ekstrom/HGT-Finder | 69bd39cee51750442968e283013fbb217b2f0ee1 | [
"X11"
] | 5 | 2018-08-29T01:01:28.000Z | 2021-04-17T03:11:01.000Z | Source/GFF.h | alex-ekstrom/HGT-Finder | 69bd39cee51750442968e283013fbb217b2f0ee1 | [
"X11"
] | 5 | 2018-10-26T20:04:37.000Z | 2020-07-25T16:32:56.000Z | Source/GFF.h | alex-ekstrom/HGT-Finder | 69bd39cee51750442968e283013fbb217b2f0ee1 | [
"X11"
] | 6 | 2019-08-22T12:03:56.000Z | 2020-09-21T10:37:19.000Z | #ifndef GFF_H
#define GFF_H
#include <iostream>
#include <fstream>
#include <sstream>
#include <vector>
#include <unordered_map>
#include <map>
using namespace std;
struct GFFNode
{
string seqid;
string source;
string type;
int start;
int end;
string score;
string strand;
string phase;
map<string, string> attributes;
string getAttribute(string key);
};
class GFF
{
public:
GFF(string f);
GFF(string f, string type);
void initWithFile();
GFFNode operator[](int i);
void setFile(string f);
string getFile();
vector<GFFNode>::iterator begin();
vector<GFFNode>::iterator last();
vector<GFFNode>::iterator end();
int size();
void printGFF();
private:
vector<GFFNode> data;
string file;
string type;
void parseLine(string l);
map<string, string> getAttributes(string fullAttributes);
string editName_p(string name);
};
#endif | 14.627119 | 58 | 0.716107 | [
"vector"
] |
04ccc66e575593685ddee26bf1133a69ff6a0de0 | 102,533 | c | C | osprey/kg++fe/gnu/integrate.c | sharugupta/OpenUH | daddd76858a53035f5d713f648d13373c22506e8 | [
"BSD-2-Clause"
] | null | null | null | osprey/kg++fe/gnu/integrate.c | sharugupta/OpenUH | daddd76858a53035f5d713f648d13373c22506e8 | [
"BSD-2-Clause"
] | null | null | null | osprey/kg++fe/gnu/integrate.c | sharugupta/OpenUH | daddd76858a53035f5d713f648d13373c22506e8 | [
"BSD-2-Clause"
] | null | null | null | /* Procedure integration for GCC.
Copyright (C) 1988, 1991, 1993, 1994, 1995, 1996, 1997, 1998,
1999, 2000, 2001, 2002 Free Software Foundation, Inc.
Contributed by Michael Tiemann (tiemann@cygnus.com)
This file is part of GCC.
GCC 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.
GCC 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 GCC; see the file COPYING. If not, write to the Free
Software Foundation, 59 Temple Place - Suite 330, Boston, MA
02111-1307, USA. */
#include "config.h"
#include "system.h"
#include "rtl.h"
#include "tree.h"
#include "tm_p.h"
#include "regs.h"
#include "flags.h"
#include "debug.h"
#include "insn-config.h"
#include "expr.h"
#include "output.h"
#include "recog.h"
#include "integrate.h"
#include "real.h"
#include "except.h"
#include "function.h"
#include "toplev.h"
#include "intl.h"
#include "loop.h"
#include "params.h"
#include "ggc.h"
#include "target.h"
#include "langhooks.h"
/* Similar, but round to the next highest integer that meets the
alignment. */
#define CEIL_ROUND(VALUE,ALIGN) (((VALUE) + (ALIGN) - 1) & ~((ALIGN)- 1))
/* Default max number of insns a function can have and still be inline.
This is overridden on RISC machines. */
#ifndef INTEGRATE_THRESHOLD
/* Inlining small functions might save more space then not inlining at
all. Assume 1 instruction for the call and 1.5 insns per argument. */
#define INTEGRATE_THRESHOLD(DECL) \
(optimize_size \
? (1 + (3 * list_length (DECL_ARGUMENTS (DECL))) / 2) \
: (8 * (8 + list_length (DECL_ARGUMENTS (DECL)))))
#endif
/* Private type used by {get/has}_func_hard_reg_initial_val. */
typedef struct initial_value_pair GTY(()) {
rtx hard_reg;
rtx pseudo;
} initial_value_pair;
typedef struct initial_value_struct GTY(()) {
int num_entries;
int max_entries;
initial_value_pair * GTY ((length ("%h.num_entries"))) entries;
} initial_value_struct;
static void setup_initial_hard_reg_value_integration PARAMS ((struct function *, struct inline_remap *));
static rtvec initialize_for_inline PARAMS ((tree));
static void note_modified_parmregs PARAMS ((rtx, rtx, void *));
static void integrate_parm_decls PARAMS ((tree, struct inline_remap *,
rtvec));
static tree integrate_decl_tree PARAMS ((tree,
struct inline_remap *));
static void subst_constants PARAMS ((rtx *, rtx,
struct inline_remap *, int));
static void set_block_origin_self PARAMS ((tree));
static void set_block_abstract_flags PARAMS ((tree, int));
static void process_reg_param PARAMS ((struct inline_remap *, rtx,
rtx));
void set_decl_abstract_flags PARAMS ((tree, int));
static void mark_stores PARAMS ((rtx, rtx, void *));
static void save_parm_insns PARAMS ((rtx, rtx));
static void copy_insn_list PARAMS ((rtx, struct inline_remap *,
rtx));
static void copy_insn_notes PARAMS ((rtx, struct inline_remap *,
int));
static int compare_blocks PARAMS ((const PTR, const PTR));
static int find_block PARAMS ((const PTR, const PTR));
/* Used by copy_rtx_and_substitute; this indicates whether the function is
called for the purpose of inlining or some other purpose (i.e. loop
unrolling). This affects how constant pool references are handled.
This variable contains the FUNCTION_DECL for the inlined function. */
static struct function *inlining = 0;
/* Returns the Ith entry in the label_map contained in MAP. If the
Ith entry has not yet been set, return a fresh label. This function
performs a lazy initialization of label_map, thereby avoiding huge memory
explosions when the label_map gets very large. */
rtx
get_label_from_map (map, i)
struct inline_remap *map;
int i;
{
rtx x = map->label_map[i];
if (x == NULL_RTX)
x = map->label_map[i] = gen_label_rtx ();
return x;
}
/* Return false if the function FNDECL cannot be inlined on account of its
attributes, true otherwise. */
bool
function_attribute_inlinable_p (fndecl)
tree fndecl;
{
if (targetm.attribute_table)
{
tree a;
for (a = DECL_ATTRIBUTES (fndecl); a; a = TREE_CHAIN (a))
{
tree name = TREE_PURPOSE (a);
int i;
for (i = 0; targetm.attribute_table[i].name != NULL; i++)
if (is_attribute_p (targetm.attribute_table[i].name, name))
return (*targetm.function_attribute_inlinable_p) (fndecl);
}
}
return true;
}
/* Zero if the current function (whose FUNCTION_DECL is FNDECL)
is safe and reasonable to integrate into other functions.
Nonzero means value is a warning msgid with a single %s
for the function's name. */
const char *
function_cannot_inline_p (fndecl)
tree fndecl;
{
rtx insn;
tree last = tree_last (TYPE_ARG_TYPES (TREE_TYPE (fndecl)));
/* For functions marked as inline increase the maximum size to
MAX_INLINE_INSNS_RTL (--param max-inline-insn-rtl=<n>). For
regular functions use the limit given by INTEGRATE_THRESHOLD.
Note that the RTL inliner is not used by the languages that use
the tree inliner (C, C++). */
int max_insns = (DECL_INLINE (fndecl))
? (MAX_INLINE_INSNS_RTL
+ 8 * list_length (DECL_ARGUMENTS (fndecl)))
: INTEGRATE_THRESHOLD (fndecl);
int ninsns = 0;
tree parms;
if (DECL_UNINLINABLE (fndecl))
return N_("function cannot be inline");
/* No inlines with varargs. */
if (last && TREE_VALUE (last) != void_type_node)
return N_("varargs function cannot be inline");
if (current_function_calls_alloca)
return N_("function using alloca cannot be inline");
if (current_function_calls_setjmp)
return N_("function using setjmp cannot be inline");
if (current_function_calls_eh_return)
return N_("function uses __builtin_eh_return");
if (current_function_contains_functions)
return N_("function with nested functions cannot be inline");
if (forced_labels)
return
N_("function with label addresses used in initializers cannot inline");
if (current_function_cannot_inline)
return current_function_cannot_inline;
/* If its not even close, don't even look. */
if (get_max_uid () > 3 * max_insns)
return N_("function too large to be inline");
/* We can't inline functions that return structures
the old-fashioned PCC way, copying into a static block. */
if (current_function_returns_pcc_struct)
return N_("inline functions not supported for this return value type");
/* We can't inline functions that return structures of varying size. */
if (TREE_CODE (TREE_TYPE (TREE_TYPE (fndecl))) != VOID_TYPE
&& int_size_in_bytes (TREE_TYPE (TREE_TYPE (fndecl))) < 0)
return N_("function with varying-size return value cannot be inline");
/* Cannot inline a function with a varying size argument or one that
receives a transparent union. */
for (parms = DECL_ARGUMENTS (fndecl); parms; parms = TREE_CHAIN (parms))
{
if (int_size_in_bytes (TREE_TYPE (parms)) < 0)
return N_("function with varying-size parameter cannot be inline");
else if (TREE_CODE (TREE_TYPE (parms)) == UNION_TYPE
&& TYPE_TRANSPARENT_UNION (TREE_TYPE (parms)))
return N_("function with transparent unit parameter cannot be inline");
}
if (get_max_uid () > max_insns)
{
for (ninsns = 0, insn = get_first_nonparm_insn ();
insn && ninsns < max_insns;
insn = NEXT_INSN (insn))
if (INSN_P (insn))
ninsns++;
if (ninsns >= max_insns)
return N_("function too large to be inline");
}
/* We will not inline a function which uses computed goto. The addresses of
its local labels, which may be tucked into global storage, are of course
not constant across instantiations, which causes unexpected behavior. */
if (current_function_has_computed_jump)
return N_("function with computed jump cannot inline");
/* We cannot inline a nested function that jumps to a nonlocal label. */
if (current_function_has_nonlocal_goto)
return N_("function with nonlocal goto cannot be inline");
/* We can't inline functions that return a PARALLEL rtx. */
if (DECL_RTL_SET_P (DECL_RESULT (fndecl)))
{
rtx result = DECL_RTL (DECL_RESULT (fndecl));
if (GET_CODE (result) == PARALLEL)
return N_("inline functions not supported for this return value type");
}
/* If the function has a target specific attribute attached to it,
then we assume that we should not inline it. This can be overriden
by the target if it defines TARGET_FUNCTION_ATTRIBUTE_INLINABLE_P. */
if (!function_attribute_inlinable_p (fndecl))
return N_("function with target specific attribute(s) cannot be inlined");
return NULL;
}
/* Map pseudo reg number into the PARM_DECL for the parm living in the reg.
Zero for a reg that isn't a parm's home.
Only reg numbers less than max_parm_reg are mapped here. */
static tree *parmdecl_map;
/* In save_for_inline, nonzero if past the parm-initialization insns. */
static int in_nonparm_insns;
/* Subroutine for `save_for_inline'. Performs initialization
needed to save FNDECL's insns and info for future inline expansion. */
static rtvec
initialize_for_inline (fndecl)
tree fndecl;
{
int i;
rtvec arg_vector;
tree parms;
/* Clear out PARMDECL_MAP. It was allocated in the caller's frame. */
memset ((char *) parmdecl_map, 0, max_parm_reg * sizeof (tree));
arg_vector = rtvec_alloc (list_length (DECL_ARGUMENTS (fndecl)));
for (parms = DECL_ARGUMENTS (fndecl), i = 0;
parms;
parms = TREE_CHAIN (parms), i++)
{
rtx p = DECL_RTL (parms);
/* If we have (mem (addressof (mem ...))), use the inner MEM since
otherwise the copy_rtx call below will not unshare the MEM since
it shares ADDRESSOF. */
if (GET_CODE (p) == MEM && GET_CODE (XEXP (p, 0)) == ADDRESSOF
&& GET_CODE (XEXP (XEXP (p, 0), 0)) == MEM)
p = XEXP (XEXP (p, 0), 0);
RTVEC_ELT (arg_vector, i) = p;
if (GET_CODE (p) == REG)
parmdecl_map[REGNO (p)] = parms;
else if (GET_CODE (p) == CONCAT)
{
rtx preal = gen_realpart (GET_MODE (XEXP (p, 0)), p);
rtx pimag = gen_imagpart (GET_MODE (preal), p);
if (GET_CODE (preal) == REG)
parmdecl_map[REGNO (preal)] = parms;
if (GET_CODE (pimag) == REG)
parmdecl_map[REGNO (pimag)] = parms;
}
/* This flag is cleared later
if the function ever modifies the value of the parm. */
TREE_READONLY (parms) = 1;
}
return arg_vector;
}
/* Copy NODE (which must be a DECL, but not a PARM_DECL). The DECL
originally was in the FROM_FN, but now it will be in the
TO_FN. */
tree
copy_decl_for_inlining (decl, from_fn, to_fn)
tree decl;
tree from_fn;
tree to_fn;
{
tree copy;
/* Copy the declaration. */
if (TREE_CODE (decl) == PARM_DECL || TREE_CODE (decl) == RESULT_DECL)
{
tree type;
int invisiref = 0;
/* See if the frontend wants to pass this by invisible reference. */
if (TREE_CODE (decl) == PARM_DECL
&& DECL_ARG_TYPE (decl) != TREE_TYPE (decl)
&& POINTER_TYPE_P (DECL_ARG_TYPE (decl))
&& TREE_TYPE (DECL_ARG_TYPE (decl)) == TREE_TYPE (decl))
{
invisiref = 1;
type = DECL_ARG_TYPE (decl);
}
else
type = TREE_TYPE (decl);
/* For a parameter, we must make an equivalent VAR_DECL, not a
new PARM_DECL. */
copy = build_decl (VAR_DECL, DECL_NAME (decl), type);
if (!invisiref)
{
TREE_ADDRESSABLE (copy) = TREE_ADDRESSABLE (decl);
TREE_READONLY (copy) = TREE_READONLY (decl);
TREE_THIS_VOLATILE (copy) = TREE_THIS_VOLATILE (decl);
}
else
{
TREE_ADDRESSABLE (copy) = 0;
TREE_READONLY (copy) = 1;
TREE_THIS_VOLATILE (copy) = 0;
}
}
else
{
copy = copy_node (decl);
/* The COPY is not abstract; it will be generated in TO_FN. */
DECL_ABSTRACT (copy) = 0;
(*lang_hooks.dup_lang_specific_decl) (copy);
/* TREE_ADDRESSABLE isn't used to indicate that a label's
address has been taken; it's for internal bookkeeping in
expand_goto_internal. */
if (TREE_CODE (copy) == LABEL_DECL)
TREE_ADDRESSABLE (copy) = 0;
}
/* Set the DECL_ABSTRACT_ORIGIN so the debugging routines know what
declaration inspired this copy. */
DECL_ABSTRACT_ORIGIN (copy) = DECL_ORIGIN (decl);
/* The new variable/label has no RTL, yet. */
SET_DECL_RTL (copy, NULL_RTX);
/* These args would always appear unused, if not for this. */
TREE_USED (copy) = 1;
/* Set the context for the new declaration. */
if (!DECL_CONTEXT (decl))
/* Globals stay global. */
;
else if (DECL_CONTEXT (decl) != from_fn)
/* Things that weren't in the scope of the function we're inlining
from aren't in the scope we're inlining too, either. */
;
else if (TREE_STATIC (decl))
/* Function-scoped static variables should say in the original
function. */
;
else
/* Ordinary automatic local variables are now in the scope of the
new function. */
DECL_CONTEXT (copy) = to_fn;
return copy;
}
/* Make the insns and PARM_DECLs of the current function permanent
and record other information in DECL_SAVED_INSNS to allow inlining
of this function in subsequent calls.
This routine need not copy any insns because we are not going
to immediately compile the insns in the insn chain. There
are two cases when we would compile the insns for FNDECL:
(1) when FNDECL is expanded inline, and (2) when FNDECL needs to
be output at the end of other compilation, because somebody took
its address. In the first case, the insns of FNDECL are copied
as it is expanded inline, so FNDECL's saved insns are not
modified. In the second case, FNDECL is used for the last time,
so modifying the rtl is not a problem.
We don't have to worry about FNDECL being inline expanded by
other functions which are written at the end of compilation
because flag_no_inline is turned on when we begin writing
functions at the end of compilation. */
void
save_for_inline (fndecl)
tree fndecl;
{
rtx insn;
rtvec argvec;
rtx first_nonparm_insn;
/* Set up PARMDECL_MAP which maps pseudo-reg number to its PARM_DECL.
Later we set TREE_READONLY to 0 if the parm is modified inside the fn.
Also set up ARG_VECTOR, which holds the unmodified DECL_RTX values
for the parms, prior to elimination of virtual registers.
These values are needed for substituting parms properly. */
if (! flag_no_inline)
parmdecl_map = (tree *) xmalloc (max_parm_reg * sizeof (tree));
/* Make and emit a return-label if we have not already done so. */
if (return_label == 0)
{
return_label = gen_label_rtx ();
emit_label (return_label);
}
if (! flag_no_inline)
argvec = initialize_for_inline (fndecl);
else
argvec = NULL;
/* Delete basic block notes created by early run of find_basic_block.
The notes would be later used by find_basic_blocks to reuse the memory
for basic_block structures on already freed obstack. */
for (insn = get_insns (); insn ; insn = NEXT_INSN (insn))
if (GET_CODE (insn) == NOTE && NOTE_LINE_NUMBER (insn) == NOTE_INSN_BASIC_BLOCK)
delete_related_insns (insn);
/* If there are insns that copy parms from the stack into pseudo registers,
those insns are not copied. `expand_inline_function' must
emit the correct code to handle such things. */
insn = get_insns ();
if (GET_CODE (insn) != NOTE)
abort ();
if (! flag_no_inline)
{
/* Get the insn which signals the end of parameter setup code. */
first_nonparm_insn = get_first_nonparm_insn ();
/* Now just scan the chain of insns to see what happens to our
PARM_DECLs. If a PARM_DECL is used but never modified, we
can substitute its rtl directly when expanding inline (and
perform constant folding when its incoming value is
constant). Otherwise, we have to copy its value into a new
register and track the new register's life. */
in_nonparm_insns = 0;
save_parm_insns (insn, first_nonparm_insn);
cfun->inl_max_label_num = max_label_num ();
cfun->inl_last_parm_insn = cfun->x_last_parm_insn;
cfun->original_arg_vector = argvec;
}
cfun->original_decl_initial = DECL_INITIAL (fndecl);
cfun->no_debugging_symbols = (write_symbols == NO_DEBUG);
DECL_SAVED_INSNS (fndecl) = cfun;
/* Clean up. */
if (! flag_no_inline)
free (parmdecl_map);
}
/* Scan the chain of insns to see what happens to our PARM_DECLs. If a
PARM_DECL is used but never modified, we can substitute its rtl directly
when expanding inline (and perform constant folding when its incoming
value is constant). Otherwise, we have to copy its value into a new
register and track the new register's life. */
static void
save_parm_insns (insn, first_nonparm_insn)
rtx insn;
rtx first_nonparm_insn;
{
if (insn == NULL_RTX)
return;
for (insn = NEXT_INSN (insn); insn; insn = NEXT_INSN (insn))
{
if (insn == first_nonparm_insn)
in_nonparm_insns = 1;
if (INSN_P (insn))
{
/* Record what interesting things happen to our parameters. */
note_stores (PATTERN (insn), note_modified_parmregs, NULL);
/* If this is a CALL_PLACEHOLDER insn then we need to look into the
three attached sequences: normal call, sibling call and tail
recursion. */
if (GET_CODE (insn) == CALL_INSN
&& GET_CODE (PATTERN (insn)) == CALL_PLACEHOLDER)
{
int i;
for (i = 0; i < 3; i++)
save_parm_insns (XEXP (PATTERN (insn), i),
first_nonparm_insn);
}
}
}
}
/* Note whether a parameter is modified or not. */
static void
note_modified_parmregs (reg, x, data)
rtx reg;
rtx x ATTRIBUTE_UNUSED;
void *data ATTRIBUTE_UNUSED;
{
if (GET_CODE (reg) == REG && in_nonparm_insns
&& REGNO (reg) < max_parm_reg
&& REGNO (reg) >= FIRST_PSEUDO_REGISTER
&& parmdecl_map[REGNO (reg)] != 0)
TREE_READONLY (parmdecl_map[REGNO (reg)]) = 0;
}
/* Unfortunately, we need a global copy of const_equiv map for communication
with a function called from note_stores. Be *very* careful that this
is used properly in the presence of recursion. */
varray_type global_const_equiv_varray;
#define FIXED_BASE_PLUS_P(X) \
(GET_CODE (X) == PLUS && GET_CODE (XEXP (X, 1)) == CONST_INT \
&& GET_CODE (XEXP (X, 0)) == REG \
&& REGNO (XEXP (X, 0)) >= FIRST_VIRTUAL_REGISTER \
&& REGNO (XEXP (X, 0)) <= LAST_VIRTUAL_REGISTER)
/* Called to set up a mapping for the case where a parameter is in a
register. If it is read-only and our argument is a constant, set up the
constant equivalence.
If LOC is REG_USERVAR_P, the usual case, COPY must also have that flag set
if it is a register.
Also, don't allow hard registers here; they might not be valid when
substituted into insns. */
static void
process_reg_param (map, loc, copy)
struct inline_remap *map;
rtx loc, copy;
{
if ((GET_CODE (copy) != REG && GET_CODE (copy) != SUBREG)
|| (GET_CODE (copy) == REG && REG_USERVAR_P (loc)
&& ! REG_USERVAR_P (copy))
|| (GET_CODE (copy) == REG
&& REGNO (copy) < FIRST_PSEUDO_REGISTER))
{
rtx temp = copy_to_mode_reg (GET_MODE (loc), copy);
REG_USERVAR_P (temp) = REG_USERVAR_P (loc);
if (CONSTANT_P (copy) || FIXED_BASE_PLUS_P (copy))
SET_CONST_EQUIV_DATA (map, temp, copy, CONST_AGE_PARM);
copy = temp;
}
map->reg_map[REGNO (loc)] = copy;
}
/* Compare two BLOCKs for qsort. The key we sort on is the
BLOCK_ABSTRACT_ORIGIN of the blocks. We cannot just subtract the
two pointers, because it may overflow sizeof(int). */
static int
compare_blocks (v1, v2)
const PTR v1;
const PTR v2;
{
tree b1 = *((const tree *) v1);
tree b2 = *((const tree *) v2);
char *p1 = (char *) BLOCK_ABSTRACT_ORIGIN (b1);
char *p2 = (char *) BLOCK_ABSTRACT_ORIGIN (b2);
if (p1 == p2)
return 0;
return p1 < p2 ? -1 : 1;
}
/* Compare two BLOCKs for bsearch. The first pointer corresponds to
an original block; the second to a remapped equivalent. */
static int
find_block (v1, v2)
const PTR v1;
const PTR v2;
{
const union tree_node *b1 = (const union tree_node *) v1;
tree b2 = *((const tree *) v2);
char *p1 = (char *) b1;
char *p2 = (char *) BLOCK_ABSTRACT_ORIGIN (b2);
if (p1 == p2)
return 0;
return p1 < p2 ? -1 : 1;
}
/* Integrate the procedure defined by FNDECL. Note that this function
may wind up calling itself. Since the static variables are not
reentrant, we do not assign them until after the possibility
of recursion is eliminated.
If IGNORE is nonzero, do not produce a value.
Otherwise store the value in TARGET if it is nonzero and that is convenient.
Value is:
(rtx)-1 if we could not substitute the function
0 if we substituted it and it does not produce a value
else an rtx for where the value is stored. */
rtx
expand_inline_function (fndecl, parms, target, ignore, type,
structure_value_addr)
tree fndecl, parms;
rtx target;
int ignore;
tree type;
rtx structure_value_addr;
{
struct function *inlining_previous;
struct function *inl_f = DECL_SAVED_INSNS (fndecl);
tree formal, actual, block;
rtx parm_insns = inl_f->emit->x_first_insn;
rtx insns = (inl_f->inl_last_parm_insn
? NEXT_INSN (inl_f->inl_last_parm_insn)
: parm_insns);
tree *arg_trees;
rtx *arg_vals;
int max_regno;
int i;
int min_labelno = inl_f->emit->x_first_label_num;
int max_labelno = inl_f->inl_max_label_num;
int nargs;
rtx loc;
rtx stack_save = 0;
rtx temp;
struct inline_remap *map = 0;
rtvec arg_vector = inl_f->original_arg_vector;
rtx static_chain_value = 0;
int inl_max_uid;
int eh_region_offset;
/* The pointer used to track the true location of the memory used
for MAP->LABEL_MAP. */
rtx *real_label_map = 0;
/* Allow for equivalences of the pseudos we make for virtual fp and ap. */
max_regno = inl_f->emit->x_reg_rtx_no + 3;
if (max_regno < FIRST_PSEUDO_REGISTER)
abort ();
/* Pull out the decl for the function definition; fndecl may be a
local declaration, which would break DECL_ABSTRACT_ORIGIN. */
fndecl = inl_f->decl;
nargs = list_length (DECL_ARGUMENTS (fndecl));
if (cfun->preferred_stack_boundary < inl_f->preferred_stack_boundary)
cfun->preferred_stack_boundary = inl_f->preferred_stack_boundary;
/* Check that the parms type match and that sufficient arguments were
passed. Since the appropriate conversions or default promotions have
already been applied, the machine modes should match exactly. */
for (formal = DECL_ARGUMENTS (fndecl), actual = parms;
formal;
formal = TREE_CHAIN (formal), actual = TREE_CHAIN (actual))
{
tree arg;
enum machine_mode mode;
if (actual == 0)
return (rtx) (size_t) -1;
arg = TREE_VALUE (actual);
mode = TYPE_MODE (DECL_ARG_TYPE (formal));
if (arg == error_mark_node
|| mode != TYPE_MODE (TREE_TYPE (arg))
/* If they are block mode, the types should match exactly.
They don't match exactly if TREE_TYPE (FORMAL) == ERROR_MARK_NODE,
which could happen if the parameter has incomplete type. */
|| (mode == BLKmode
&& (TYPE_MAIN_VARIANT (TREE_TYPE (arg))
!= TYPE_MAIN_VARIANT (TREE_TYPE (formal)))))
return (rtx) (size_t) -1;
}
/* Extra arguments are valid, but will be ignored below, so we must
evaluate them here for side-effects. */
for (; actual; actual = TREE_CHAIN (actual))
expand_expr (TREE_VALUE (actual), const0_rtx,
TYPE_MODE (TREE_TYPE (TREE_VALUE (actual))), 0);
/* Expand the function arguments. Do this first so that any
new registers get created before we allocate the maps. */
arg_vals = (rtx *) xmalloc (nargs * sizeof (rtx));
arg_trees = (tree *) xmalloc (nargs * sizeof (tree));
for (formal = DECL_ARGUMENTS (fndecl), actual = parms, i = 0;
formal;
formal = TREE_CHAIN (formal), actual = TREE_CHAIN (actual), i++)
{
/* Actual parameter, converted to the type of the argument within the
function. */
tree arg = convert (TREE_TYPE (formal), TREE_VALUE (actual));
/* Mode of the variable used within the function. */
enum machine_mode mode = TYPE_MODE (TREE_TYPE (formal));
int invisiref = 0;
arg_trees[i] = arg;
loc = RTVEC_ELT (arg_vector, i);
/* If this is an object passed by invisible reference, we copy the
object into a stack slot and save its address. If this will go
into memory, we do nothing now. Otherwise, we just expand the
argument. */
if (GET_CODE (loc) == MEM && GET_CODE (XEXP (loc, 0)) == REG
&& REGNO (XEXP (loc, 0)) > LAST_VIRTUAL_REGISTER)
{
rtx stack_slot = assign_temp (TREE_TYPE (arg), 1, 1, 1);
store_expr (arg, stack_slot, 0);
arg_vals[i] = XEXP (stack_slot, 0);
invisiref = 1;
}
else if (GET_CODE (loc) != MEM)
{
if (GET_MODE (loc) != TYPE_MODE (TREE_TYPE (arg)))
{
int unsignedp = TREE_UNSIGNED (TREE_TYPE (formal));
enum machine_mode pmode = TYPE_MODE (TREE_TYPE (formal));
pmode = promote_mode (TREE_TYPE (formal), pmode,
&unsignedp, 0);
if (GET_MODE (loc) != pmode)
abort ();
/* The mode if LOC and ARG can differ if LOC was a variable
that had its mode promoted via PROMOTED_MODE. */
arg_vals[i] = convert_modes (pmode,
TYPE_MODE (TREE_TYPE (arg)),
expand_expr (arg, NULL_RTX, mode,
EXPAND_SUM),
unsignedp);
}
else
arg_vals[i] = expand_expr (arg, NULL_RTX, mode, EXPAND_SUM);
}
else
arg_vals[i] = 0;
if (arg_vals[i] != 0
&& (! TREE_READONLY (formal)
/* If the parameter is not read-only, copy our argument through
a register. Also, we cannot use ARG_VALS[I] if it overlaps
TARGET in any way. In the inline function, they will likely
be two different pseudos, and `safe_from_p' will make all
sorts of smart assumptions about their not conflicting.
But if ARG_VALS[I] overlaps TARGET, these assumptions are
wrong, so put ARG_VALS[I] into a fresh register.
Don't worry about invisible references, since their stack
temps will never overlap the target. */
|| (target != 0
&& ! invisiref
&& (GET_CODE (arg_vals[i]) == REG
|| GET_CODE (arg_vals[i]) == SUBREG
|| GET_CODE (arg_vals[i]) == MEM)
&& reg_overlap_mentioned_p (arg_vals[i], target))
/* ??? We must always copy a SUBREG into a REG, because it might
get substituted into an address, and not all ports correctly
handle SUBREGs in addresses. */
|| (GET_CODE (arg_vals[i]) == SUBREG)))
arg_vals[i] = copy_to_mode_reg (GET_MODE (loc), arg_vals[i]);
if (arg_vals[i] != 0 && GET_CODE (arg_vals[i]) == REG
&& POINTER_TYPE_P (TREE_TYPE (formal)))
mark_reg_pointer (arg_vals[i],
TYPE_ALIGN (TREE_TYPE (TREE_TYPE (formal))));
}
/* Allocate the structures we use to remap things. */
map = (struct inline_remap *) xcalloc (1, sizeof (struct inline_remap));
map->fndecl = fndecl;
VARRAY_TREE_INIT (map->block_map, 10, "block_map");
map->reg_map = (rtx *) xcalloc (max_regno, sizeof (rtx));
/* We used to use alloca here, but the size of what it would try to
allocate would occasionally cause it to exceed the stack limit and
cause unpredictable core dumps. */
real_label_map
= (rtx *) xmalloc ((max_labelno) * sizeof (rtx));
map->label_map = real_label_map;
map->local_return_label = NULL_RTX;
inl_max_uid = (inl_f->emit->x_cur_insn_uid + 1);
map->insn_map = (rtx *) xcalloc (inl_max_uid, sizeof (rtx));
map->min_insnno = 0;
map->max_insnno = inl_max_uid;
map->integrating = 1;
map->compare_src = NULL_RTX;
map->compare_mode = VOIDmode;
/* const_equiv_varray maps pseudos in our routine to constants, so
it needs to be large enough for all our pseudos. This is the
number we are currently using plus the number in the called
routine, plus 15 for each arg, five to compute the virtual frame
pointer, and five for the return value. This should be enough
for most cases. We do not reference entries outside the range of
the map.
??? These numbers are quite arbitrary and were obtained by
experimentation. At some point, we should try to allocate the
table after all the parameters are set up so we can more accurately
estimate the number of pseudos we will need. */
VARRAY_CONST_EQUIV_INIT (map->const_equiv_varray,
(max_reg_num ()
+ (max_regno - FIRST_PSEUDO_REGISTER)
+ 15 * nargs
+ 10),
"expand_inline_function");
map->const_age = 0;
/* Record the current insn in case we have to set up pointers to frame
and argument memory blocks. If there are no insns yet, add a dummy
insn that can be used as an insertion point. */
map->insns_at_start = get_last_insn ();
if (map->insns_at_start == 0)
map->insns_at_start = emit_note (NULL, NOTE_INSN_DELETED);
map->regno_pointer_align = inl_f->emit->regno_pointer_align;
map->x_regno_reg_rtx = inl_f->emit->x_regno_reg_rtx;
/* Update the outgoing argument size to allow for those in the inlined
function. */
if (inl_f->outgoing_args_size > current_function_outgoing_args_size)
current_function_outgoing_args_size = inl_f->outgoing_args_size;
/* If the inline function needs to make PIC references, that means
that this function's PIC offset table must be used. */
if (inl_f->uses_pic_offset_table)
current_function_uses_pic_offset_table = 1;
/* If this function needs a context, set it up. */
if (inl_f->needs_context)
static_chain_value = lookup_static_chain (fndecl);
if (GET_CODE (parm_insns) == NOTE
&& NOTE_LINE_NUMBER (parm_insns) > 0)
{
rtx note = emit_note (NOTE_SOURCE_FILE (parm_insns),
NOTE_LINE_NUMBER (parm_insns));
if (note)
RTX_INTEGRATED_P (note) = 1;
}
/* Process each argument. For each, set up things so that the function's
reference to the argument will refer to the argument being passed.
We only replace REG with REG here. Any simplifications are done
via const_equiv_map.
We make two passes: In the first, we deal with parameters that will
be placed into registers, since we need to ensure that the allocated
register number fits in const_equiv_map. Then we store all non-register
parameters into their memory location. */
/* Don't try to free temp stack slots here, because we may put one of the
parameters into a temp stack slot. */
for (i = 0; i < nargs; i++)
{
rtx copy = arg_vals[i];
loc = RTVEC_ELT (arg_vector, i);
/* There are three cases, each handled separately. */
if (GET_CODE (loc) == MEM && GET_CODE (XEXP (loc, 0)) == REG
&& REGNO (XEXP (loc, 0)) > LAST_VIRTUAL_REGISTER)
{
/* This must be an object passed by invisible reference (it could
also be a variable-sized object, but we forbid inlining functions
with variable-sized arguments). COPY is the address of the
actual value (this computation will cause it to be copied). We
map that address for the register, noting the actual address as
an equivalent in case it can be substituted into the insns. */
if (GET_CODE (copy) != REG)
{
temp = copy_addr_to_reg (copy);
if (CONSTANT_P (copy) || FIXED_BASE_PLUS_P (copy))
SET_CONST_EQUIV_DATA (map, temp, copy, CONST_AGE_PARM);
copy = temp;
}
map->reg_map[REGNO (XEXP (loc, 0))] = copy;
}
else if (GET_CODE (loc) == MEM)
{
/* This is the case of a parameter that lives in memory. It
will live in the block we allocate in the called routine's
frame that simulates the incoming argument area. Do nothing
with the parameter now; we will call store_expr later. In
this case, however, we must ensure that the virtual stack and
incoming arg rtx values are expanded now so that we can be
sure we have enough slots in the const equiv map since the
store_expr call can easily blow the size estimate. */
if (DECL_SAVED_INSNS (fndecl)->args_size != 0)
copy_rtx_and_substitute (virtual_incoming_args_rtx, map, 0);
}
else if (GET_CODE (loc) == REG)
process_reg_param (map, loc, copy);
else if (GET_CODE (loc) == CONCAT)
{
rtx locreal = gen_realpart (GET_MODE (XEXP (loc, 0)), loc);
rtx locimag = gen_imagpart (GET_MODE (XEXP (loc, 0)), loc);
rtx copyreal = gen_realpart (GET_MODE (locreal), copy);
rtx copyimag = gen_imagpart (GET_MODE (locimag), copy);
process_reg_param (map, locreal, copyreal);
process_reg_param (map, locimag, copyimag);
}
else
abort ();
}
/* Tell copy_rtx_and_substitute to handle constant pool SYMBOL_REFs
specially. This function can be called recursively, so we need to
save the previous value. */
inlining_previous = inlining;
inlining = inl_f;
/* Now do the parameters that will be placed in memory. */
for (formal = DECL_ARGUMENTS (fndecl), i = 0;
formal; formal = TREE_CHAIN (formal), i++)
{
loc = RTVEC_ELT (arg_vector, i);
if (GET_CODE (loc) == MEM
/* Exclude case handled above. */
&& ! (GET_CODE (XEXP (loc, 0)) == REG
&& REGNO (XEXP (loc, 0)) > LAST_VIRTUAL_REGISTER))
{
rtx note = emit_note (DECL_SOURCE_FILE (formal),
DECL_SOURCE_LINE (formal));
if (note)
RTX_INTEGRATED_P (note) = 1;
/* Compute the address in the area we reserved and store the
value there. */
temp = copy_rtx_and_substitute (loc, map, 1);
subst_constants (&temp, NULL_RTX, map, 1);
apply_change_group ();
if (! memory_address_p (GET_MODE (temp), XEXP (temp, 0)))
temp = change_address (temp, VOIDmode, XEXP (temp, 0));
store_expr (arg_trees[i], temp, 0);
}
}
/* Deal with the places that the function puts its result.
We are driven by what is placed into DECL_RESULT.
Initially, we assume that we don't have anything special handling for
REG_FUNCTION_RETURN_VALUE_P. */
map->inline_target = 0;
loc = (DECL_RTL_SET_P (DECL_RESULT (fndecl))
? DECL_RTL (DECL_RESULT (fndecl)) : NULL_RTX);
if (TYPE_MODE (type) == VOIDmode)
/* There is no return value to worry about. */
;
else if (GET_CODE (loc) == MEM)
{
if (GET_CODE (XEXP (loc, 0)) == ADDRESSOF)
{
temp = copy_rtx_and_substitute (loc, map, 1);
subst_constants (&temp, NULL_RTX, map, 1);
apply_change_group ();
target = temp;
}
else
{
if (! structure_value_addr
|| ! aggregate_value_p (DECL_RESULT (fndecl)))
abort ();
/* Pass the function the address in which to return a structure
value. Note that a constructor can cause someone to call us
with STRUCTURE_VALUE_ADDR, but the initialization takes place
via the first parameter, rather than the struct return address.
We have two cases: If the address is a simple register
indirect, use the mapping mechanism to point that register to
our structure return address. Otherwise, store the structure
return value into the place that it will be referenced from. */
if (GET_CODE (XEXP (loc, 0)) == REG)
{
temp = force_operand (structure_value_addr, NULL_RTX);
temp = force_reg (Pmode, temp);
/* A virtual register might be invalid in an insn, because
it can cause trouble in reload. Since we don't have access
to the expanders at map translation time, make sure we have
a proper register now.
If a virtual register is actually valid, cse or combine
can put it into the mapped insns. */
if (REGNO (temp) >= FIRST_VIRTUAL_REGISTER
&& REGNO (temp) <= LAST_VIRTUAL_REGISTER)
temp = copy_to_mode_reg (Pmode, temp);
map->reg_map[REGNO (XEXP (loc, 0))] = temp;
if (CONSTANT_P (structure_value_addr)
|| GET_CODE (structure_value_addr) == ADDRESSOF
|| (GET_CODE (structure_value_addr) == PLUS
&& (XEXP (structure_value_addr, 0)
== virtual_stack_vars_rtx)
&& (GET_CODE (XEXP (structure_value_addr, 1))
== CONST_INT)))
{
SET_CONST_EQUIV_DATA (map, temp, structure_value_addr,
CONST_AGE_PARM);
}
}
else
{
temp = copy_rtx_and_substitute (loc, map, 1);
subst_constants (&temp, NULL_RTX, map, 0);
apply_change_group ();
emit_move_insn (temp, structure_value_addr);
}
}
}
else if (ignore)
/* We will ignore the result value, so don't look at its structure.
Note that preparations for an aggregate return value
do need to be made (above) even if it will be ignored. */
;
else if (GET_CODE (loc) == REG)
{
/* The function returns an object in a register and we use the return
value. Set up our target for remapping. */
/* Machine mode function was declared to return. */
enum machine_mode departing_mode = TYPE_MODE (type);
/* (Possibly wider) machine mode it actually computes
(for the sake of callers that fail to declare it right).
We have to use the mode of the result's RTL, rather than
its type, since expand_function_start may have promoted it. */
enum machine_mode arriving_mode
= GET_MODE (DECL_RTL (DECL_RESULT (fndecl)));
rtx reg_to_map;
/* Don't use MEMs as direct targets because on some machines
substituting a MEM for a REG makes invalid insns.
Let the combiner substitute the MEM if that is valid. */
if (target == 0 || GET_CODE (target) != REG
|| GET_MODE (target) != departing_mode)
{
/* Don't make BLKmode registers. If this looks like
a BLKmode object being returned in a register, get
the mode from that, otherwise abort. */
if (departing_mode == BLKmode)
{
if (REG == GET_CODE (DECL_RTL (DECL_RESULT (fndecl))))
{
departing_mode = GET_MODE (DECL_RTL (DECL_RESULT (fndecl)));
arriving_mode = departing_mode;
}
else
abort ();
}
target = gen_reg_rtx (departing_mode);
}
/* If function's value was promoted before return,
avoid machine mode mismatch when we substitute INLINE_TARGET.
But TARGET is what we will return to the caller. */
if (arriving_mode != departing_mode)
{
/* Avoid creating a paradoxical subreg wider than
BITS_PER_WORD, since that is illegal. */
if (GET_MODE_BITSIZE (arriving_mode) > BITS_PER_WORD)
{
if (!TRULY_NOOP_TRUNCATION (GET_MODE_BITSIZE (departing_mode),
GET_MODE_BITSIZE (arriving_mode)))
/* Maybe could be handled by using convert_move () ? */
abort ();
reg_to_map = gen_reg_rtx (arriving_mode);
target = gen_lowpart (departing_mode, reg_to_map);
}
else
reg_to_map = gen_rtx_SUBREG (arriving_mode, target, 0);
}
else
reg_to_map = target;
/* Usually, the result value is the machine's return register.
Sometimes it may be a pseudo. Handle both cases. */
if (REG_FUNCTION_VALUE_P (loc))
map->inline_target = reg_to_map;
else
map->reg_map[REGNO (loc)] = reg_to_map;
}
else if (GET_CODE (loc) == CONCAT)
{
enum machine_mode departing_mode = TYPE_MODE (type);
enum machine_mode arriving_mode
= GET_MODE (DECL_RTL (DECL_RESULT (fndecl)));
if (departing_mode != arriving_mode)
abort ();
if (GET_CODE (XEXP (loc, 0)) != REG
|| GET_CODE (XEXP (loc, 1)) != REG)
abort ();
/* Don't use MEMs as direct targets because on some machines
substituting a MEM for a REG makes invalid insns.
Let the combiner substitute the MEM if that is valid. */
if (target == 0 || GET_CODE (target) != REG
|| GET_MODE (target) != departing_mode)
target = gen_reg_rtx (departing_mode);
if (GET_CODE (target) != CONCAT)
abort ();
map->reg_map[REGNO (XEXP (loc, 0))] = XEXP (target, 0);
map->reg_map[REGNO (XEXP (loc, 1))] = XEXP (target, 1);
}
else
abort ();
/* Remap the exception handler data pointer from one to the other. */
temp = get_exception_pointer (inl_f);
if (temp)
map->reg_map[REGNO (temp)] = get_exception_pointer (cfun);
/* Initialize label_map. get_label_from_map will actually make
the labels. */
memset ((char *) &map->label_map[min_labelno], 0,
(max_labelno - min_labelno) * sizeof (rtx));
/* Make copies of the decls of the symbols in the inline function, so that
the copies of the variables get declared in the current function. Set
up things so that lookup_static_chain knows that to interpret registers
in SAVE_EXPRs for TYPE_SIZEs as local. */
inline_function_decl = fndecl;
integrate_parm_decls (DECL_ARGUMENTS (fndecl), map, arg_vector);
block = integrate_decl_tree (inl_f->original_decl_initial, map);
BLOCK_ABSTRACT_ORIGIN (block) = DECL_ORIGIN (fndecl);
inline_function_decl = 0;
/* Make a fresh binding contour that we can easily remove. Do this after
expanding our arguments so cleanups are properly scoped. */
expand_start_bindings_and_block (0, block);
/* Sort the block-map so that it will be easy to find remapped
blocks later. */
qsort (&VARRAY_TREE (map->block_map, 0),
map->block_map->elements_used,
sizeof (tree),
compare_blocks);
/* Perform postincrements before actually calling the function. */
emit_queue ();
/* Clean up stack so that variables might have smaller offsets. */
do_pending_stack_adjust ();
/* Save a copy of the location of const_equiv_varray for
mark_stores, called via note_stores. */
global_const_equiv_varray = map->const_equiv_varray;
/* If the called function does an alloca, save and restore the
stack pointer around the call. This saves stack space, but
also is required if this inline is being done between two
pushes. */
if (inl_f->calls_alloca)
emit_stack_save (SAVE_BLOCK, &stack_save, NULL_RTX);
/* Map pseudos used for initial hard reg values. */
setup_initial_hard_reg_value_integration (inl_f, map);
/* Now copy the insns one by one. */
copy_insn_list (insns, map, static_chain_value);
/* Duplicate the EH regions. This will create an offset from the
region numbers in the function we're inlining to the region
numbers in the calling function. This must wait until after
copy_insn_list, as we need the insn map to be complete. */
eh_region_offset = duplicate_eh_regions (inl_f, map);
/* Now copy the REG_NOTES for those insns. */
copy_insn_notes (insns, map, eh_region_offset);
/* If the insn sequence required one, emit the return label. */
if (map->local_return_label)
emit_label (map->local_return_label);
/* Restore the stack pointer if we saved it above. */
if (inl_f->calls_alloca)
emit_stack_restore (SAVE_BLOCK, stack_save, NULL_RTX);
if (! cfun->x_whole_function_mode_p)
/* In statement-at-a-time mode, we just tell the front-end to add
this block to the list of blocks at this binding level. We
can't do it the way it's done for function-at-a-time mode the
superblocks have not been created yet. */
(*lang_hooks.decls.insert_block) (block);
else
{
BLOCK_CHAIN (block)
= BLOCK_CHAIN (DECL_INITIAL (current_function_decl));
BLOCK_CHAIN (DECL_INITIAL (current_function_decl)) = block;
}
/* End the scope containing the copied formal parameter variables
and copied LABEL_DECLs. We pass NULL_TREE for the variables list
here so that expand_end_bindings will not check for unused
variables. That's already been checked for when the inlined
function was defined. */
expand_end_bindings (NULL_TREE, 1, 1);
/* Must mark the line number note after inlined functions as a repeat, so
that the test coverage code can avoid counting the call twice. This
just tells the code to ignore the immediately following line note, since
there already exists a copy of this note before the expanded inline call.
This line number note is still needed for debugging though, so we can't
delete it. */
if (flag_test_coverage)
emit_note (0, NOTE_INSN_REPEATED_LINE_NUMBER);
emit_line_note (input_filename, lineno);
/* If the function returns a BLKmode object in a register, copy it
out of the temp register into a BLKmode memory object. */
if (target
&& TYPE_MODE (TREE_TYPE (TREE_TYPE (fndecl))) == BLKmode
&& ! aggregate_value_p (TREE_TYPE (TREE_TYPE (fndecl))))
target = copy_blkmode_from_reg (0, target, TREE_TYPE (TREE_TYPE (fndecl)));
if (structure_value_addr)
{
target = gen_rtx_MEM (TYPE_MODE (type),
memory_address (TYPE_MODE (type),
structure_value_addr));
set_mem_attributes (target, type, 1);
}
/* Make sure we free the things we explicitly allocated with xmalloc. */
if (real_label_map)
free (real_label_map);
VARRAY_FREE (map->const_equiv_varray);
free (map->reg_map);
free (map->insn_map);
free (map);
free (arg_vals);
free (arg_trees);
inlining = inlining_previous;
return target;
}
/* Make copies of each insn in the given list using the mapping
computed in expand_inline_function. This function may call itself for
insns containing sequences.
Copying is done in two passes, first the insns and then their REG_NOTES.
If static_chain_value is nonzero, it represents the context-pointer
register for the function. */
static void
copy_insn_list (insns, map, static_chain_value)
rtx insns;
struct inline_remap *map;
rtx static_chain_value;
{
int i;
rtx insn;
rtx temp;
#ifdef HAVE_cc0
rtx cc0_insn = 0;
#endif
rtx static_chain_mem = 0;
/* Copy the insns one by one. Do this in two passes, first the insns and
then their REG_NOTES. */
/* This loop is very similar to the loop in copy_loop_body in unroll.c. */
for (insn = insns; insn; insn = NEXT_INSN (insn))
{
rtx copy, pattern, set;
map->orig_asm_operands_vector = 0;
switch (GET_CODE (insn))
{
case INSN:
pattern = PATTERN (insn);
set = single_set (insn);
copy = 0;
if (GET_CODE (pattern) == USE
&& GET_CODE (XEXP (pattern, 0)) == REG
&& REG_FUNCTION_VALUE_P (XEXP (pattern, 0)))
/* The (USE (REG n)) at return from the function should
be ignored since we are changing (REG n) into
inline_target. */
break;
/* Ignore setting a function value that we don't want to use. */
if (map->inline_target == 0
&& set != 0
&& GET_CODE (SET_DEST (set)) == REG
&& REG_FUNCTION_VALUE_P (SET_DEST (set)))
{
if (volatile_refs_p (SET_SRC (set)))
{
rtx new_set;
/* If we must not delete the source,
load it into a new temporary. */
copy = emit_insn (copy_rtx_and_substitute (pattern, map, 0));
new_set = single_set (copy);
if (new_set == 0)
abort ();
SET_DEST (new_set)
= gen_reg_rtx (GET_MODE (SET_DEST (new_set)));
}
/* If the source and destination are the same and it
has a note on it, keep the insn. */
else if (rtx_equal_p (SET_DEST (set), SET_SRC (set))
&& REG_NOTES (insn) != 0)
copy = emit_insn (copy_rtx_and_substitute (pattern, map, 0));
else
break;
}
/* Similarly if an ignored return value is clobbered. */
else if (map->inline_target == 0
&& GET_CODE (pattern) == CLOBBER
&& GET_CODE (XEXP (pattern, 0)) == REG
&& REG_FUNCTION_VALUE_P (XEXP (pattern, 0)))
break;
/* Look for the address of the static chain slot. The
rtx_equal_p comparisons against the
static_chain_incoming_rtx below may fail if the static
chain is in memory and the address specified is not
"legitimate". This happens on Xtensa where the static
chain is at a negative offset from argp and where only
positive offsets are legitimate. When the RTL is
generated, the address is "legitimized" by copying it
into a register, causing the rtx_equal_p comparisons to
fail. This workaround looks for code that sets a
register to the address of the static chain. Subsequent
memory references via that register can then be
identified as static chain references. We assume that
the register is only assigned once, and that the static
chain address is only live in one register at a time. */
else if (static_chain_value != 0
&& set != 0
&& GET_CODE (static_chain_incoming_rtx) == MEM
&& GET_CODE (SET_DEST (set)) == REG
&& rtx_equal_p (SET_SRC (set),
XEXP (static_chain_incoming_rtx, 0)))
{
static_chain_mem =
gen_rtx_MEM (GET_MODE (static_chain_incoming_rtx),
SET_DEST (set));
/* emit the instruction in case it is used for something
other than setting the static chain; if it's not used,
it can always be removed as dead code */
copy = emit_insn (copy_rtx_and_substitute (pattern, map, 0));
}
/* If this is setting the static chain rtx, omit it. */
else if (static_chain_value != 0
&& set != 0
&& (rtx_equal_p (SET_DEST (set),
static_chain_incoming_rtx)
|| (static_chain_mem
&& rtx_equal_p (SET_DEST (set), static_chain_mem))))
break;
/* If this is setting the static chain pseudo, set it from
the value we want to give it instead. */
else if (static_chain_value != 0
&& set != 0
&& (rtx_equal_p (SET_SRC (set),
static_chain_incoming_rtx)
|| (static_chain_mem
&& rtx_equal_p (SET_SRC (set), static_chain_mem))))
{
rtx newdest = copy_rtx_and_substitute (SET_DEST (set), map, 1);
copy = emit_move_insn (newdest, static_chain_value);
if (GET_CODE (static_chain_incoming_rtx) != MEM)
static_chain_value = 0;
}
/* If this is setting the virtual stack vars register, this must
be the code at the handler for a builtin longjmp. The value
saved in the setjmp buffer will be the address of the frame
we've made for this inlined instance within our frame. But we
know the offset of that value so we can use it to reconstruct
our virtual stack vars register from that value. If we are
copying it from the stack pointer, leave it unchanged. */
else if (set != 0
&& rtx_equal_p (SET_DEST (set), virtual_stack_vars_rtx))
{
HOST_WIDE_INT offset;
temp = map->reg_map[REGNO (SET_DEST (set))];
temp = VARRAY_CONST_EQUIV (map->const_equiv_varray,
REGNO (temp)).rtx;
if (rtx_equal_p (temp, virtual_stack_vars_rtx))
offset = 0;
else if (GET_CODE (temp) == PLUS
&& rtx_equal_p (XEXP (temp, 0), virtual_stack_vars_rtx)
&& GET_CODE (XEXP (temp, 1)) == CONST_INT)
offset = INTVAL (XEXP (temp, 1));
else
abort ();
if (rtx_equal_p (SET_SRC (set), stack_pointer_rtx))
temp = SET_SRC (set);
else
temp = force_operand (plus_constant (SET_SRC (set),
- offset),
NULL_RTX);
copy = emit_move_insn (virtual_stack_vars_rtx, temp);
}
else
copy = emit_insn (copy_rtx_and_substitute (pattern, map, 0));
/* REG_NOTES will be copied later. */
#ifdef HAVE_cc0
/* If this insn is setting CC0, it may need to look at
the insn that uses CC0 to see what type of insn it is.
In that case, the call to recog via validate_change will
fail. So don't substitute constants here. Instead,
do it when we emit the following insn.
For example, see the pyr.md file. That machine has signed and
unsigned compares. The compare patterns must check the
following branch insn to see which what kind of compare to
emit.
If the previous insn set CC0, substitute constants on it as
well. */
if (sets_cc0_p (PATTERN (copy)) != 0)
cc0_insn = copy;
else
{
if (cc0_insn)
try_constants (cc0_insn, map);
cc0_insn = 0;
try_constants (copy, map);
}
#else
try_constants (copy, map);
#endif
INSN_SCOPE (copy) = INSN_SCOPE (insn);
break;
case JUMP_INSN:
if (map->integrating && returnjump_p (insn))
{
if (map->local_return_label == 0)
map->local_return_label = gen_label_rtx ();
pattern = gen_jump (map->local_return_label);
}
else
pattern = copy_rtx_and_substitute (PATTERN (insn), map, 0);
copy = emit_jump_insn (pattern);
#ifdef HAVE_cc0
if (cc0_insn)
try_constants (cc0_insn, map);
cc0_insn = 0;
#endif
try_constants (copy, map);
INSN_SCOPE (copy) = INSN_SCOPE (insn);
/* If this used to be a conditional jump insn but whose branch
direction is now know, we must do something special. */
if (any_condjump_p (insn) && onlyjump_p (insn) && map->last_pc_value)
{
#ifdef HAVE_cc0
/* If the previous insn set cc0 for us, delete it. */
if (only_sets_cc0_p (PREV_INSN (copy)))
delete_related_insns (PREV_INSN (copy));
#endif
/* If this is now a no-op, delete it. */
if (map->last_pc_value == pc_rtx)
{
delete_related_insns (copy);
copy = 0;
}
else
/* Otherwise, this is unconditional jump so we must put a
BARRIER after it. We could do some dead code elimination
here, but jump.c will do it just as well. */
emit_barrier ();
}
break;
case CALL_INSN:
/* If this is a CALL_PLACEHOLDER insn then we need to copy the
three attached sequences: normal call, sibling call and tail
recursion. */
if (GET_CODE (PATTERN (insn)) == CALL_PLACEHOLDER)
{
rtx sequence[3];
rtx tail_label;
for (i = 0; i < 3; i++)
{
rtx seq;
sequence[i] = NULL_RTX;
seq = XEXP (PATTERN (insn), i);
if (seq)
{
start_sequence ();
copy_insn_list (seq, map, static_chain_value);
sequence[i] = get_insns ();
end_sequence ();
}
}
/* Find the new tail recursion label.
It will already be substituted into sequence[2]. */
tail_label = copy_rtx_and_substitute (XEXP (PATTERN (insn), 3),
map, 0);
copy = emit_call_insn (gen_rtx_CALL_PLACEHOLDER (VOIDmode,
sequence[0],
sequence[1],
sequence[2],
tail_label));
break;
}
pattern = copy_rtx_and_substitute (PATTERN (insn), map, 0);
copy = emit_call_insn (pattern);
SIBLING_CALL_P (copy) = SIBLING_CALL_P (insn);
CONST_OR_PURE_CALL_P (copy) = CONST_OR_PURE_CALL_P (insn);
INSN_SCOPE (copy) = INSN_SCOPE (insn);
/* Because the USAGE information potentially contains objects other
than hard registers, we need to copy it. */
CALL_INSN_FUNCTION_USAGE (copy)
= copy_rtx_and_substitute (CALL_INSN_FUNCTION_USAGE (insn),
map, 0);
#ifdef HAVE_cc0
if (cc0_insn)
try_constants (cc0_insn, map);
cc0_insn = 0;
#endif
try_constants (copy, map);
/* Be lazy and assume CALL_INSNs clobber all hard registers. */
for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
VARRAY_CONST_EQUIV (map->const_equiv_varray, i).rtx = 0;
break;
case CODE_LABEL:
copy = emit_label (get_label_from_map (map,
CODE_LABEL_NUMBER (insn)));
LABEL_NAME (copy) = LABEL_NAME (insn);
map->const_age++;
break;
case BARRIER:
copy = emit_barrier ();
break;
case NOTE:
if (NOTE_LINE_NUMBER (insn) == NOTE_INSN_DELETED_LABEL)
{
copy = emit_label (get_label_from_map (map,
CODE_LABEL_NUMBER (insn)));
LABEL_NAME (copy) = NOTE_SOURCE_FILE (insn);
map->const_age++;
break;
}
/* NOTE_INSN_FUNCTION_END and NOTE_INSN_FUNCTION_BEG are
discarded because it is important to have only one of
each in the current function.
NOTE_INSN_DELETED notes aren't useful. */
if (NOTE_LINE_NUMBER (insn) != NOTE_INSN_FUNCTION_END
&& NOTE_LINE_NUMBER (insn) != NOTE_INSN_FUNCTION_BEG
&& NOTE_LINE_NUMBER (insn) != NOTE_INSN_DELETED)
{
copy = emit_note (NOTE_SOURCE_FILE (insn),
NOTE_LINE_NUMBER (insn));
if (copy
&& (NOTE_LINE_NUMBER (copy) == NOTE_INSN_BLOCK_BEG
|| NOTE_LINE_NUMBER (copy) == NOTE_INSN_BLOCK_END)
&& NOTE_BLOCK (insn))
{
tree *mapped_block_p;
mapped_block_p
= (tree *) bsearch (NOTE_BLOCK (insn),
&VARRAY_TREE (map->block_map, 0),
map->block_map->elements_used,
sizeof (tree),
find_block);
if (!mapped_block_p)
abort ();
else
NOTE_BLOCK (copy) = *mapped_block_p;
}
else if (copy
&& NOTE_LINE_NUMBER (copy) == NOTE_INSN_EXPECTED_VALUE)
NOTE_EXPECTED_VALUE (copy)
= copy_rtx_and_substitute (NOTE_EXPECTED_VALUE (insn),
map, 0);
}
else
copy = 0;
break;
default:
abort ();
}
if (copy)
RTX_INTEGRATED_P (copy) = 1;
map->insn_map[INSN_UID (insn)] = copy;
}
}
/* Copy the REG_NOTES. Increment const_age, so that only constants
from parameters can be substituted in. These are the only ones
that are valid across the entire function. */
static void
copy_insn_notes (insns, map, eh_region_offset)
rtx insns;
struct inline_remap *map;
int eh_region_offset;
{
rtx insn, new_insn;
map->const_age++;
for (insn = insns; insn; insn = NEXT_INSN (insn))
{
if (! INSN_P (insn))
continue;
new_insn = map->insn_map[INSN_UID (insn)];
if (! new_insn)
continue;
if (REG_NOTES (insn))
{
rtx next, note = copy_rtx_and_substitute (REG_NOTES (insn), map, 0);
/* We must also do subst_constants, in case one of our parameters
has const type and constant value. */
subst_constants (¬e, NULL_RTX, map, 0);
apply_change_group ();
REG_NOTES (new_insn) = note;
/* Delete any REG_LABEL notes from the chain. Remap any
REG_EH_REGION notes. */
for (; note; note = next)
{
next = XEXP (note, 1);
if (REG_NOTE_KIND (note) == REG_LABEL)
remove_note (new_insn, note);
else if (REG_NOTE_KIND (note) == REG_EH_REGION
&& INTVAL (XEXP (note, 0)) > 0)
XEXP (note, 0) = GEN_INT (INTVAL (XEXP (note, 0))
+ eh_region_offset);
}
}
if (GET_CODE (insn) == CALL_INSN
&& GET_CODE (PATTERN (insn)) == CALL_PLACEHOLDER)
{
int i;
for (i = 0; i < 3; i++)
copy_insn_notes (XEXP (PATTERN (insn), i), map, eh_region_offset);
}
if (GET_CODE (insn) == JUMP_INSN
&& GET_CODE (PATTERN (insn)) == RESX)
XINT (PATTERN (new_insn), 0) += eh_region_offset;
}
}
/* Given a chain of PARM_DECLs, ARGS, copy each decl into a VAR_DECL,
push all of those decls and give each one the corresponding home. */
static void
integrate_parm_decls (args, map, arg_vector)
tree args;
struct inline_remap *map;
rtvec arg_vector;
{
tree tail;
int i;
for (tail = args, i = 0; tail; tail = TREE_CHAIN (tail), i++)
{
tree decl = copy_decl_for_inlining (tail, map->fndecl,
current_function_decl);
rtx new_decl_rtl
= copy_rtx_and_substitute (RTVEC_ELT (arg_vector, i), map, 1);
/* We really should be setting DECL_INCOMING_RTL to something reasonable
here, but that's going to require some more work. */
/* DECL_INCOMING_RTL (decl) = ?; */
/* Fully instantiate the address with the equivalent form so that the
debugging information contains the actual register, instead of the
virtual register. Do this by not passing an insn to
subst_constants. */
subst_constants (&new_decl_rtl, NULL_RTX, map, 1);
apply_change_group ();
SET_DECL_RTL (decl, new_decl_rtl);
}
}
/* Given a BLOCK node LET, push decls and levels so as to construct in the
current function a tree of contexts isomorphic to the one that is given.
MAP, if nonzero, is a pointer to an inline_remap map which indicates how
registers used in the DECL_RTL field should be remapped. If it is zero,
no mapping is necessary. */
static tree
integrate_decl_tree (let, map)
tree let;
struct inline_remap *map;
{
tree t;
tree new_block;
tree *next;
new_block = make_node (BLOCK);
VARRAY_PUSH_TREE (map->block_map, new_block);
next = &BLOCK_VARS (new_block);
for (t = BLOCK_VARS (let); t; t = TREE_CHAIN (t))
{
tree d;
d = copy_decl_for_inlining (t, map->fndecl, current_function_decl);
if (DECL_RTL_SET_P (t))
{
rtx r;
SET_DECL_RTL (d, copy_rtx_and_substitute (DECL_RTL (t), map, 1));
/* Fully instantiate the address with the equivalent form so that the
debugging information contains the actual register, instead of the
virtual register. Do this by not passing an insn to
subst_constants. */
r = DECL_RTL (d);
subst_constants (&r, NULL_RTX, map, 1);
SET_DECL_RTL (d, r);
if (GET_CODE (r) == REG)
REGNO_DECL (REGNO (r)) = d;
else if (GET_CODE (r) == CONCAT)
{
REGNO_DECL (REGNO (XEXP (r, 0))) = d;
REGNO_DECL (REGNO (XEXP (r, 1))) = d;
}
apply_change_group ();
}
/* Add this declaration to the list of variables in the new
block. */
*next = d;
next = &TREE_CHAIN (d);
}
next = &BLOCK_SUBBLOCKS (new_block);
for (t = BLOCK_SUBBLOCKS (let); t; t = BLOCK_CHAIN (t))
{
*next = integrate_decl_tree (t, map);
BLOCK_SUPERCONTEXT (*next) = new_block;
next = &BLOCK_CHAIN (*next);
}
TREE_USED (new_block) = TREE_USED (let);
BLOCK_ABSTRACT_ORIGIN (new_block) = let;
return new_block;
}
/* Create a new copy of an rtx. Recursively copies the operands of the rtx,
except for those few rtx codes that are sharable.
We always return an rtx that is similar to that incoming rtx, with the
exception of possibly changing a REG to a SUBREG or vice versa. No
rtl is ever emitted.
If FOR_LHS is nonzero, if means we are processing something that will
be the LHS of a SET. In that case, we copy RTX_UNCHANGING_P even if
inlining since we need to be conservative in how it is set for
such cases.
Handle constants that need to be placed in the constant pool by
calling `force_const_mem'. */
rtx
copy_rtx_and_substitute (orig, map, for_lhs)
rtx orig;
struct inline_remap *map;
int for_lhs;
{
rtx copy, temp;
int i, j;
RTX_CODE code;
enum machine_mode mode;
const char *format_ptr;
int regno;
if (orig == 0)
return 0;
code = GET_CODE (orig);
mode = GET_MODE (orig);
switch (code)
{
case REG:
/* If the stack pointer register shows up, it must be part of
stack-adjustments (*not* because we eliminated the frame pointer!).
Small hard registers are returned as-is. Pseudo-registers
go through their `reg_map'. */
regno = REGNO (orig);
if (regno <= LAST_VIRTUAL_REGISTER
|| (map->integrating
&& DECL_SAVED_INSNS (map->fndecl)->internal_arg_pointer == orig))
{
/* Some hard registers are also mapped,
but others are not translated. */
if (map->reg_map[regno] != 0)
return map->reg_map[regno];
/* If this is the virtual frame pointer, make space in current
function's stack frame for the stack frame of the inline function.
Copy the address of this area into a pseudo. Map
virtual_stack_vars_rtx to this pseudo and set up a constant
equivalence for it to be the address. This will substitute the
address into insns where it can be substituted and use the new
pseudo where it can't. */
else if (regno == VIRTUAL_STACK_VARS_REGNUM)
{
rtx loc, seq;
int size = get_func_frame_size (DECL_SAVED_INSNS (map->fndecl));
#ifdef FRAME_GROWS_DOWNWARD
int alignment
= (DECL_SAVED_INSNS (map->fndecl)->stack_alignment_needed
/ BITS_PER_UNIT);
/* In this case, virtual_stack_vars_rtx points to one byte
higher than the top of the frame area. So make sure we
allocate a big enough chunk to keep the frame pointer
aligned like a real one. */
if (alignment)
size = CEIL_ROUND (size, alignment);
#endif
start_sequence ();
loc = assign_stack_temp (BLKmode, size, 1);
loc = XEXP (loc, 0);
#ifdef FRAME_GROWS_DOWNWARD
/* In this case, virtual_stack_vars_rtx points to one byte
higher than the top of the frame area. So compute the offset
to one byte higher than our substitute frame. */
loc = plus_constant (loc, size);
#endif
map->reg_map[regno] = temp
= force_reg (Pmode, force_operand (loc, NULL_RTX));
#ifdef STACK_BOUNDARY
mark_reg_pointer (map->reg_map[regno], STACK_BOUNDARY);
#endif
SET_CONST_EQUIV_DATA (map, temp, loc, CONST_AGE_PARM);
seq = get_insns ();
end_sequence ();
emit_insn_after (seq, map->insns_at_start);
return temp;
}
else if (regno == VIRTUAL_INCOMING_ARGS_REGNUM
|| (map->integrating
&& (DECL_SAVED_INSNS (map->fndecl)->internal_arg_pointer
== orig)))
{
/* Do the same for a block to contain any arguments referenced
in memory. */
rtx loc, seq;
int size = DECL_SAVED_INSNS (map->fndecl)->args_size;
start_sequence ();
loc = assign_stack_temp (BLKmode, size, 1);
loc = XEXP (loc, 0);
/* When arguments grow downward, the virtual incoming
args pointer points to the top of the argument block,
so the remapped location better do the same. */
#ifdef ARGS_GROW_DOWNWARD
loc = plus_constant (loc, size);
#endif
map->reg_map[regno] = temp
= force_reg (Pmode, force_operand (loc, NULL_RTX));
#ifdef STACK_BOUNDARY
mark_reg_pointer (map->reg_map[regno], STACK_BOUNDARY);
#endif
SET_CONST_EQUIV_DATA (map, temp, loc, CONST_AGE_PARM);
seq = get_insns ();
end_sequence ();
emit_insn_after (seq, map->insns_at_start);
return temp;
}
else if (REG_FUNCTION_VALUE_P (orig))
{
/* This is a reference to the function return value. If
the function doesn't have a return value, error. If the
mode doesn't agree, and it ain't BLKmode, make a SUBREG. */
if (map->inline_target == 0)
{
if (rtx_equal_function_value_matters)
/* This is an ignored return value. We must not
leave it in with REG_FUNCTION_VALUE_P set, since
that would confuse subsequent inlining of the
current function into a later function. */
return gen_rtx_REG (GET_MODE (orig), regno);
else
/* Must be unrolling loops or replicating code if we
reach here, so return the register unchanged. */
return orig;
}
else if (GET_MODE (map->inline_target) != BLKmode
&& mode != GET_MODE (map->inline_target))
return gen_lowpart (mode, map->inline_target);
else
return map->inline_target;
}
#if defined (LEAF_REGISTERS) && defined (LEAF_REG_REMAP)
/* If leaf_renumber_regs_insn() might remap this register to
some other number, make sure we don't share it with the
inlined function, otherwise delayed optimization of the
inlined function may change it in place, breaking our
reference to it. We may still shared it within the
function, so create an entry for this register in the
reg_map. */
if (map->integrating && regno < FIRST_PSEUDO_REGISTER
&& LEAF_REGISTERS[regno] && LEAF_REG_REMAP (regno) != regno)
{
if (!map->leaf_reg_map[regno][mode])
map->leaf_reg_map[regno][mode] = gen_rtx_REG (mode, regno);
return map->leaf_reg_map[regno][mode];
}
#endif
else
return orig;
abort ();
}
if (map->reg_map[regno] == NULL)
{
map->reg_map[regno] = gen_reg_rtx (mode);
REG_USERVAR_P (map->reg_map[regno]) = REG_USERVAR_P (orig);
REG_LOOP_TEST_P (map->reg_map[regno]) = REG_LOOP_TEST_P (orig);
RTX_UNCHANGING_P (map->reg_map[regno]) = RTX_UNCHANGING_P (orig);
/* A reg with REG_FUNCTION_VALUE_P true will never reach here. */
if (REG_POINTER (map->x_regno_reg_rtx[regno]))
mark_reg_pointer (map->reg_map[regno],
map->regno_pointer_align[regno]);
}
return map->reg_map[regno];
case SUBREG:
copy = copy_rtx_and_substitute (SUBREG_REG (orig), map, for_lhs);
return simplify_gen_subreg (GET_MODE (orig), copy,
GET_MODE (SUBREG_REG (orig)),
SUBREG_BYTE (orig));
case ADDRESSOF:
copy = gen_rtx_ADDRESSOF (mode,
copy_rtx_and_substitute (XEXP (orig, 0),
map, for_lhs),
0, ADDRESSOF_DECL (orig));
regno = ADDRESSOF_REGNO (orig);
if (map->reg_map[regno])
regno = REGNO (map->reg_map[regno]);
else if (regno > LAST_VIRTUAL_REGISTER)
{
temp = XEXP (orig, 0);
map->reg_map[regno] = gen_reg_rtx (GET_MODE (temp));
REG_USERVAR_P (map->reg_map[regno]) = REG_USERVAR_P (temp);
REG_LOOP_TEST_P (map->reg_map[regno]) = REG_LOOP_TEST_P (temp);
RTX_UNCHANGING_P (map->reg_map[regno]) = RTX_UNCHANGING_P (temp);
/* A reg with REG_FUNCTION_VALUE_P true will never reach here. */
/* Objects may initially be represented as registers, but
but turned into a MEM if their address is taken by
put_var_into_stack. Therefore, the register table may have
entries which are MEMs.
We briefly tried to clear such entries, but that ended up
cascading into many changes due to the optimizers not being
prepared for empty entries in the register table. So we've
decided to allow the MEMs in the register table for now. */
if (REG_P (map->x_regno_reg_rtx[regno])
&& REG_POINTER (map->x_regno_reg_rtx[regno]))
mark_reg_pointer (map->reg_map[regno],
map->regno_pointer_align[regno]);
regno = REGNO (map->reg_map[regno]);
}
ADDRESSOF_REGNO (copy) = regno;
return copy;
case USE:
case CLOBBER:
/* USE and CLOBBER are ordinary, but we convert (use (subreg foo))
to (use foo) if the original insn didn't have a subreg.
Removing the subreg distorts the VAX movstrhi pattern
by changing the mode of an operand. */
copy = copy_rtx_and_substitute (XEXP (orig, 0), map, code == CLOBBER);
if (GET_CODE (copy) == SUBREG && GET_CODE (XEXP (orig, 0)) != SUBREG)
copy = SUBREG_REG (copy);
return gen_rtx_fmt_e (code, VOIDmode, copy);
/* We need to handle "deleted" labels that appear in the DECL_RTL
of a LABEL_DECL. */
case NOTE:
if (NOTE_LINE_NUMBER (orig) != NOTE_INSN_DELETED_LABEL)
break;
/* ... FALLTHRU ... */
case CODE_LABEL:
LABEL_PRESERVE_P (get_label_from_map (map, CODE_LABEL_NUMBER (orig)))
= LABEL_PRESERVE_P (orig);
return get_label_from_map (map, CODE_LABEL_NUMBER (orig));
case LABEL_REF:
copy
= gen_rtx_LABEL_REF
(mode,
LABEL_REF_NONLOCAL_P (orig) ? XEXP (orig, 0)
: get_label_from_map (map, CODE_LABEL_NUMBER (XEXP (orig, 0))));
LABEL_OUTSIDE_LOOP_P (copy) = LABEL_OUTSIDE_LOOP_P (orig);
/* The fact that this label was previously nonlocal does not mean
it still is, so we must check if it is within the range of
this function's labels. */
LABEL_REF_NONLOCAL_P (copy)
= (LABEL_REF_NONLOCAL_P (orig)
&& ! (CODE_LABEL_NUMBER (XEXP (copy, 0)) >= get_first_label_num ()
&& CODE_LABEL_NUMBER (XEXP (copy, 0)) < max_label_num ()));
/* If we have made a nonlocal label local, it means that this
inlined call will be referring to our nonlocal goto handler.
So make sure we create one for this block; we normally would
not since this is not otherwise considered a "call". */
if (LABEL_REF_NONLOCAL_P (orig) && ! LABEL_REF_NONLOCAL_P (copy))
function_call_count++;
return copy;
case PC:
case CC0:
case CONST_INT:
case CONST_VECTOR:
return orig;
case SYMBOL_REF:
/* Symbols which represent the address of a label stored in the constant
pool must be modified to point to a constant pool entry for the
remapped label. Otherwise, symbols are returned unchanged. */
if (CONSTANT_POOL_ADDRESS_P (orig))
{
struct function *f = inlining ? inlining : cfun;
rtx constant = get_pool_constant_for_function (f, orig);
enum machine_mode const_mode = get_pool_mode_for_function (f, orig);
if (inlining)
{
rtx temp = force_const_mem (const_mode,
copy_rtx_and_substitute (constant,
map, 0));
temp = XEXP (temp, 0);
#ifdef POINTERS_EXTEND_UNSIGNED
if (GET_MODE (temp) != GET_MODE (orig))
temp = convert_memory_address (GET_MODE (orig), temp);
#endif
return temp;
}
else if (GET_CODE (constant) == LABEL_REF)
return XEXP (force_const_mem
(GET_MODE (orig),
copy_rtx_and_substitute (constant, map, for_lhs)),
0);
}
return orig;
case CONST_DOUBLE:
/* We have to make a new copy of this CONST_DOUBLE because don't want
to use the old value of CONST_DOUBLE_MEM. Also, this may be a
duplicate of a CONST_DOUBLE we have already seen. */
if (GET_MODE_CLASS (GET_MODE (orig)) == MODE_FLOAT)
{
REAL_VALUE_TYPE d;
REAL_VALUE_FROM_CONST_DOUBLE (d, orig);
return CONST_DOUBLE_FROM_REAL_VALUE (d, GET_MODE (orig));
}
else
return immed_double_const (CONST_DOUBLE_LOW (orig),
CONST_DOUBLE_HIGH (orig), VOIDmode);
case CONST:
/* Make new constant pool entry for a constant
that was in the pool of the inline function. */
if (RTX_INTEGRATED_P (orig))
abort ();
break;
case ASM_OPERANDS:
/* If a single asm insn contains multiple output operands then
it contains multiple ASM_OPERANDS rtx's that share the input
and constraint vecs. We must make sure that the copied insn
continues to share it. */
if (map->orig_asm_operands_vector == ASM_OPERANDS_INPUT_VEC (orig))
{
copy = rtx_alloc (ASM_OPERANDS);
RTX_FLAG (copy, volatil) = RTX_FLAG (orig, volatil);
PUT_MODE (copy, GET_MODE (orig));
ASM_OPERANDS_TEMPLATE (copy) = ASM_OPERANDS_TEMPLATE (orig);
ASM_OPERANDS_OUTPUT_CONSTRAINT (copy)
= ASM_OPERANDS_OUTPUT_CONSTRAINT (orig);
ASM_OPERANDS_OUTPUT_IDX (copy) = ASM_OPERANDS_OUTPUT_IDX (orig);
ASM_OPERANDS_INPUT_VEC (copy) = map->copy_asm_operands_vector;
ASM_OPERANDS_INPUT_CONSTRAINT_VEC (copy)
= map->copy_asm_constraints_vector;
ASM_OPERANDS_SOURCE_FILE (copy) = ASM_OPERANDS_SOURCE_FILE (orig);
ASM_OPERANDS_SOURCE_LINE (copy) = ASM_OPERANDS_SOURCE_LINE (orig);
return copy;
}
break;
case CALL:
/* This is given special treatment because the first
operand of a CALL is a (MEM ...) which may get
forced into a register for cse. This is undesirable
if function-address cse isn't wanted or if we won't do cse. */
#ifndef NO_FUNCTION_CSE
if (! (optimize && ! flag_no_function_cse))
#endif
{
rtx copy
= gen_rtx_MEM (GET_MODE (XEXP (orig, 0)),
copy_rtx_and_substitute (XEXP (XEXP (orig, 0), 0),
map, 0));
MEM_COPY_ATTRIBUTES (copy, XEXP (orig, 0));
return
gen_rtx_CALL (GET_MODE (orig), copy,
copy_rtx_and_substitute (XEXP (orig, 1), map, 0));
}
break;
case SET:
/* If this is setting fp or ap, it means that we have a nonlocal goto.
Adjust the setting by the offset of the area we made.
If the nonlocal goto is into the current function,
this will result in unnecessarily bad code, but should work. */
if (SET_DEST (orig) == virtual_stack_vars_rtx
|| SET_DEST (orig) == virtual_incoming_args_rtx)
{
/* In case a translation hasn't occurred already, make one now. */
rtx equiv_reg;
rtx equiv_loc;
HOST_WIDE_INT loc_offset;
copy_rtx_and_substitute (SET_DEST (orig), map, for_lhs);
equiv_reg = map->reg_map[REGNO (SET_DEST (orig))];
equiv_loc = VARRAY_CONST_EQUIV (map->const_equiv_varray,
REGNO (equiv_reg)).rtx;
loc_offset
= GET_CODE (equiv_loc) == REG ? 0 : INTVAL (XEXP (equiv_loc, 1));
return gen_rtx_SET (VOIDmode, SET_DEST (orig),
force_operand
(plus_constant
(copy_rtx_and_substitute (SET_SRC (orig),
map, 0),
- loc_offset),
NULL_RTX));
}
else
return gen_rtx_SET (VOIDmode,
copy_rtx_and_substitute (SET_DEST (orig), map, 1),
copy_rtx_and_substitute (SET_SRC (orig), map, 0));
break;
case MEM:
if (inlining
&& GET_CODE (XEXP (orig, 0)) == SYMBOL_REF
&& CONSTANT_POOL_ADDRESS_P (XEXP (orig, 0)))
{
enum machine_mode const_mode
= get_pool_mode_for_function (inlining, XEXP (orig, 0));
rtx constant
= get_pool_constant_for_function (inlining, XEXP (orig, 0));
constant = copy_rtx_and_substitute (constant, map, 0);
/* If this was an address of a constant pool entry that itself
had to be placed in the constant pool, it might not be a
valid address. So the recursive call might have turned it
into a register. In that case, it isn't a constant any
more, so return it. This has the potential of changing a
MEM into a REG, but we'll assume that it safe. */
if (! CONSTANT_P (constant))
return constant;
return validize_mem (force_const_mem (const_mode, constant));
}
copy = gen_rtx_MEM (mode, copy_rtx_and_substitute (XEXP (orig, 0),
map, 0));
MEM_COPY_ATTRIBUTES (copy, orig);
/* If inlining and this is not for the LHS, turn off RTX_UNCHANGING_P
since this may be an indirect reference to a parameter and the
actual may not be readonly. */
if (inlining && !for_lhs)
RTX_UNCHANGING_P (copy) = 0;
/* If inlining, squish aliasing data that references the subroutine's
parameter list, since that's no longer applicable. */
if (inlining && MEM_EXPR (copy)
&& TREE_CODE (MEM_EXPR (copy)) == INDIRECT_REF
&& TREE_CODE (TREE_OPERAND (MEM_EXPR (copy), 0)) == PARM_DECL)
set_mem_expr (copy, NULL_TREE);
return copy;
default:
break;
}
copy = rtx_alloc (code);
PUT_MODE (copy, mode);
RTX_FLAG (copy, in_struct) = RTX_FLAG (orig, in_struct);
RTX_FLAG (copy, volatil) = RTX_FLAG (orig, volatil);
RTX_FLAG (copy, unchanging) = RTX_FLAG (orig, unchanging);
format_ptr = GET_RTX_FORMAT (GET_CODE (copy));
for (i = 0; i < GET_RTX_LENGTH (GET_CODE (copy)); i++)
{
switch (*format_ptr++)
{
case '0':
/* Copy this through the wide int field; that's safest. */
X0WINT (copy, i) = X0WINT (orig, i);
break;
case 'e':
XEXP (copy, i)
= copy_rtx_and_substitute (XEXP (orig, i), map, for_lhs);
break;
case 'u':
/* Change any references to old-insns to point to the
corresponding copied insns. */
XEXP (copy, i) = map->insn_map[INSN_UID (XEXP (orig, i))];
break;
case 'E':
XVEC (copy, i) = XVEC (orig, i);
if (XVEC (orig, i) != NULL && XVECLEN (orig, i) != 0)
{
XVEC (copy, i) = rtvec_alloc (XVECLEN (orig, i));
for (j = 0; j < XVECLEN (copy, i); j++)
XVECEXP (copy, i, j)
= copy_rtx_and_substitute (XVECEXP (orig, i, j),
map, for_lhs);
}
break;
case 'w':
XWINT (copy, i) = XWINT (orig, i);
break;
case 'i':
XINT (copy, i) = XINT (orig, i);
break;
case 's':
XSTR (copy, i) = XSTR (orig, i);
break;
case 't':
XTREE (copy, i) = XTREE (orig, i);
break;
default:
abort ();
}
}
if (code == ASM_OPERANDS && map->orig_asm_operands_vector == 0)
{
map->orig_asm_operands_vector = ASM_OPERANDS_INPUT_VEC (orig);
map->copy_asm_operands_vector = ASM_OPERANDS_INPUT_VEC (copy);
map->copy_asm_constraints_vector
= ASM_OPERANDS_INPUT_CONSTRAINT_VEC (copy);
}
return copy;
}
/* Substitute known constant values into INSN, if that is valid. */
void
try_constants (insn, map)
rtx insn;
struct inline_remap *map;
{
int i;
map->num_sets = 0;
/* First try just updating addresses, then other things. This is
important when we have something like the store of a constant
into memory and we can update the memory address but the machine
does not support a constant source. */
subst_constants (&PATTERN (insn), insn, map, 1);
apply_change_group ();
subst_constants (&PATTERN (insn), insn, map, 0);
apply_change_group ();
/* Show we don't know the value of anything stored or clobbered. */
note_stores (PATTERN (insn), mark_stores, NULL);
map->last_pc_value = 0;
#ifdef HAVE_cc0
map->last_cc0_value = 0;
#endif
/* Set up any constant equivalences made in this insn. */
for (i = 0; i < map->num_sets; i++)
{
if (GET_CODE (map->equiv_sets[i].dest) == REG)
{
int regno = REGNO (map->equiv_sets[i].dest);
MAYBE_EXTEND_CONST_EQUIV_VARRAY (map, regno);
if (VARRAY_CONST_EQUIV (map->const_equiv_varray, regno).rtx == 0
/* Following clause is a hack to make case work where GNU C++
reassigns a variable to make cse work right. */
|| ! rtx_equal_p (VARRAY_CONST_EQUIV (map->const_equiv_varray,
regno).rtx,
map->equiv_sets[i].equiv))
SET_CONST_EQUIV_DATA (map, map->equiv_sets[i].dest,
map->equiv_sets[i].equiv, map->const_age);
}
else if (map->equiv_sets[i].dest == pc_rtx)
map->last_pc_value = map->equiv_sets[i].equiv;
#ifdef HAVE_cc0
else if (map->equiv_sets[i].dest == cc0_rtx)
map->last_cc0_value = map->equiv_sets[i].equiv;
#endif
}
}
/* Substitute known constants for pseudo regs in the contents of LOC,
which are part of INSN.
If INSN is zero, the substitution should always be done (this is used to
update DECL_RTL).
These changes are taken out by try_constants if the result is not valid.
Note that we are more concerned with determining when the result of a SET
is a constant, for further propagation, than actually inserting constants
into insns; cse will do the latter task better.
This function is also used to adjust address of items previously addressed
via the virtual stack variable or virtual incoming arguments registers.
If MEMONLY is nonzero, only make changes inside a MEM. */
static void
subst_constants (loc, insn, map, memonly)
rtx *loc;
rtx insn;
struct inline_remap *map;
int memonly;
{
rtx x = *loc;
int i, j;
enum rtx_code code;
const char *format_ptr;
int num_changes = num_validated_changes ();
rtx new = 0;
enum machine_mode op0_mode = MAX_MACHINE_MODE;
code = GET_CODE (x);
switch (code)
{
case PC:
case CONST_INT:
case CONST_DOUBLE:
case CONST_VECTOR:
case SYMBOL_REF:
case CONST:
case LABEL_REF:
case ADDRESS:
return;
#ifdef HAVE_cc0
case CC0:
if (! memonly)
validate_change (insn, loc, map->last_cc0_value, 1);
return;
#endif
case USE:
case CLOBBER:
/* The only thing we can do with a USE or CLOBBER is possibly do
some substitutions in a MEM within it. */
if (GET_CODE (XEXP (x, 0)) == MEM)
subst_constants (&XEXP (XEXP (x, 0), 0), insn, map, 0);
return;
case REG:
/* Substitute for parms and known constants. Don't replace
hard regs used as user variables with constants. */
if (! memonly)
{
int regno = REGNO (x);
struct const_equiv_data *p;
if (! (regno < FIRST_PSEUDO_REGISTER && REG_USERVAR_P (x))
&& (size_t) regno < VARRAY_SIZE (map->const_equiv_varray)
&& (p = &VARRAY_CONST_EQUIV (map->const_equiv_varray, regno),
p->rtx != 0)
&& p->age >= map->const_age)
validate_change (insn, loc, p->rtx, 1);
}
return;
case SUBREG:
/* SUBREG applied to something other than a reg
should be treated as ordinary, since that must
be a special hack and we don't know how to treat it specially.
Consider for example mulsidi3 in m68k.md.
Ordinary SUBREG of a REG needs this special treatment. */
if (! memonly && GET_CODE (SUBREG_REG (x)) == REG)
{
rtx inner = SUBREG_REG (x);
rtx new = 0;
/* We can't call subst_constants on &SUBREG_REG (x) because any
constant or SUBREG wouldn't be valid inside our SUBEG. Instead,
see what is inside, try to form the new SUBREG and see if that is
valid. We handle two cases: extracting a full word in an
integral mode and extracting the low part. */
subst_constants (&inner, NULL_RTX, map, 0);
new = simplify_gen_subreg (GET_MODE (x), inner,
GET_MODE (SUBREG_REG (x)),
SUBREG_BYTE (x));
if (new)
validate_change (insn, loc, new, 1);
else
cancel_changes (num_changes);
return;
}
break;
case MEM:
subst_constants (&XEXP (x, 0), insn, map, 0);
/* If a memory address got spoiled, change it back. */
if (! memonly && insn != 0 && num_validated_changes () != num_changes
&& ! memory_address_p (GET_MODE (x), XEXP (x, 0)))
cancel_changes (num_changes);
return;
case SET:
{
/* Substitute constants in our source, and in any arguments to a
complex (e..g, ZERO_EXTRACT) destination, but not in the destination
itself. */
rtx *dest_loc = &SET_DEST (x);
rtx dest = *dest_loc;
rtx src, tem;
enum machine_mode compare_mode = VOIDmode;
/* If SET_SRC is a COMPARE which subst_constants would turn into
COMPARE of 2 VOIDmode constants, note the mode in which comparison
is to be done. */
if (GET_CODE (SET_SRC (x)) == COMPARE)
{
src = SET_SRC (x);
if (GET_MODE_CLASS (GET_MODE (src)) == MODE_CC
#ifdef HAVE_cc0
|| dest == cc0_rtx
#endif
)
{
compare_mode = GET_MODE (XEXP (src, 0));
if (compare_mode == VOIDmode)
compare_mode = GET_MODE (XEXP (src, 1));
}
}
subst_constants (&SET_SRC (x), insn, map, memonly);
src = SET_SRC (x);
while (GET_CODE (*dest_loc) == ZERO_EXTRACT
|| GET_CODE (*dest_loc) == SUBREG
|| GET_CODE (*dest_loc) == STRICT_LOW_PART)
{
if (GET_CODE (*dest_loc) == ZERO_EXTRACT)
{
subst_constants (&XEXP (*dest_loc, 1), insn, map, memonly);
subst_constants (&XEXP (*dest_loc, 2), insn, map, memonly);
}
dest_loc = &XEXP (*dest_loc, 0);
}
/* Do substitute in the address of a destination in memory. */
if (GET_CODE (*dest_loc) == MEM)
subst_constants (&XEXP (*dest_loc, 0), insn, map, 0);
/* Check for the case of DEST a SUBREG, both it and the underlying
register are less than one word, and the SUBREG has the wider mode.
In the case, we are really setting the underlying register to the
source converted to the mode of DEST. So indicate that. */
if (GET_CODE (dest) == SUBREG
&& GET_MODE_SIZE (GET_MODE (dest)) <= UNITS_PER_WORD
&& GET_MODE_SIZE (GET_MODE (SUBREG_REG (dest))) <= UNITS_PER_WORD
&& (GET_MODE_SIZE (GET_MODE (SUBREG_REG (dest)))
<= GET_MODE_SIZE (GET_MODE (dest)))
&& (tem = gen_lowpart_if_possible (GET_MODE (SUBREG_REG (dest)),
src)))
src = tem, dest = SUBREG_REG (dest);
/* If storing a recognizable value save it for later recording. */
if ((map->num_sets < MAX_RECOG_OPERANDS)
&& (CONSTANT_P (src)
|| (GET_CODE (src) == REG
&& (REGNO (src) == VIRTUAL_INCOMING_ARGS_REGNUM
|| REGNO (src) == VIRTUAL_STACK_VARS_REGNUM))
|| (GET_CODE (src) == PLUS
&& GET_CODE (XEXP (src, 0)) == REG
&& (REGNO (XEXP (src, 0)) == VIRTUAL_INCOMING_ARGS_REGNUM
|| REGNO (XEXP (src, 0)) == VIRTUAL_STACK_VARS_REGNUM)
&& CONSTANT_P (XEXP (src, 1)))
|| GET_CODE (src) == COMPARE
#ifdef HAVE_cc0
|| dest == cc0_rtx
#endif
|| (dest == pc_rtx
&& (src == pc_rtx || GET_CODE (src) == RETURN
|| GET_CODE (src) == LABEL_REF))))
{
/* Normally, this copy won't do anything. But, if SRC is a COMPARE
it will cause us to save the COMPARE with any constants
substituted, which is what we want for later. */
rtx src_copy = copy_rtx (src);
map->equiv_sets[map->num_sets].equiv = src_copy;
map->equiv_sets[map->num_sets++].dest = dest;
if (compare_mode != VOIDmode
&& GET_CODE (src) == COMPARE
&& (GET_MODE_CLASS (GET_MODE (src)) == MODE_CC
#ifdef HAVE_cc0
|| dest == cc0_rtx
#endif
)
&& GET_MODE (XEXP (src, 0)) == VOIDmode
&& GET_MODE (XEXP (src, 1)) == VOIDmode)
{
map->compare_src = src_copy;
map->compare_mode = compare_mode;
}
}
}
return;
default:
break;
}
format_ptr = GET_RTX_FORMAT (code);
/* If the first operand is an expression, save its mode for later. */
if (*format_ptr == 'e')
op0_mode = GET_MODE (XEXP (x, 0));
for (i = 0; i < GET_RTX_LENGTH (code); i++)
{
switch (*format_ptr++)
{
case '0':
break;
case 'e':
if (XEXP (x, i))
subst_constants (&XEXP (x, i), insn, map, memonly);
break;
case 'u':
case 'i':
case 's':
case 'w':
case 'n':
case 't':
case 'B':
break;
case 'E':
if (XVEC (x, i) != NULL && XVECLEN (x, i) != 0)
for (j = 0; j < XVECLEN (x, i); j++)
subst_constants (&XVECEXP (x, i, j), insn, map, memonly);
break;
default:
abort ();
}
}
/* If this is a commutative operation, move a constant to the second
operand unless the second operand is already a CONST_INT. */
if (! memonly
&& (GET_RTX_CLASS (code) == 'c' || code == NE || code == EQ)
&& CONSTANT_P (XEXP (x, 0)) && GET_CODE (XEXP (x, 1)) != CONST_INT)
{
rtx tem = XEXP (x, 0);
validate_change (insn, &XEXP (x, 0), XEXP (x, 1), 1);
validate_change (insn, &XEXP (x, 1), tem, 1);
}
/* Simplify the expression in case we put in some constants. */
if (! memonly)
switch (GET_RTX_CLASS (code))
{
case '1':
if (op0_mode == MAX_MACHINE_MODE)
abort ();
new = simplify_unary_operation (code, GET_MODE (x),
XEXP (x, 0), op0_mode);
break;
case '<':
{
enum machine_mode op_mode = GET_MODE (XEXP (x, 0));
if (op_mode == VOIDmode)
op_mode = GET_MODE (XEXP (x, 1));
new = simplify_relational_operation (code, op_mode,
XEXP (x, 0), XEXP (x, 1));
#ifdef FLOAT_STORE_FLAG_VALUE
if (new != 0 && GET_MODE_CLASS (GET_MODE (x)) == MODE_FLOAT)
{
enum machine_mode mode = GET_MODE (x);
if (new == const0_rtx)
new = CONST0_RTX (mode);
else
{
REAL_VALUE_TYPE val;
/* Avoid automatic aggregate initialization. */
val = FLOAT_STORE_FLAG_VALUE (mode);
new = CONST_DOUBLE_FROM_REAL_VALUE (val, mode);
}
}
#endif
break;
}
case '2':
case 'c':
new = simplify_binary_operation (code, GET_MODE (x),
XEXP (x, 0), XEXP (x, 1));
break;
case 'b':
case '3':
if (op0_mode == MAX_MACHINE_MODE)
abort ();
if (code == IF_THEN_ELSE)
{
rtx op0 = XEXP (x, 0);
if (GET_RTX_CLASS (GET_CODE (op0)) == '<'
&& GET_MODE (op0) == VOIDmode
&& ! side_effects_p (op0)
&& XEXP (op0, 0) == map->compare_src
&& GET_MODE (XEXP (op0, 1)) == VOIDmode)
{
/* We have compare of two VOIDmode constants for which
we recorded the comparison mode. */
rtx temp =
simplify_relational_operation (GET_CODE (op0),
map->compare_mode,
XEXP (op0, 0),
XEXP (op0, 1));
if (temp == const0_rtx)
new = XEXP (x, 2);
else if (temp == const1_rtx)
new = XEXP (x, 1);
}
}
if (!new)
new = simplify_ternary_operation (code, GET_MODE (x), op0_mode,
XEXP (x, 0), XEXP (x, 1),
XEXP (x, 2));
break;
}
if (new)
validate_change (insn, loc, new, 1);
}
/* Show that register modified no longer contain known constants. We are
called from note_stores with parts of the new insn. */
static void
mark_stores (dest, x, data)
rtx dest;
rtx x ATTRIBUTE_UNUSED;
void *data ATTRIBUTE_UNUSED;
{
int regno = -1;
enum machine_mode mode = VOIDmode;
/* DEST is always the innermost thing set, except in the case of
SUBREGs of hard registers. */
if (GET_CODE (dest) == REG)
regno = REGNO (dest), mode = GET_MODE (dest);
else if (GET_CODE (dest) == SUBREG && GET_CODE (SUBREG_REG (dest)) == REG)
{
regno = REGNO (SUBREG_REG (dest));
if (regno < FIRST_PSEUDO_REGISTER)
regno += subreg_regno_offset (REGNO (SUBREG_REG (dest)),
GET_MODE (SUBREG_REG (dest)),
SUBREG_BYTE (dest),
GET_MODE (dest));
mode = GET_MODE (SUBREG_REG (dest));
}
if (regno >= 0)
{
unsigned int uregno = regno;
unsigned int last_reg = (uregno >= FIRST_PSEUDO_REGISTER ? uregno
: uregno + HARD_REGNO_NREGS (uregno, mode) - 1);
unsigned int i;
/* Ignore virtual stack var or virtual arg register since those
are handled separately. */
if (uregno != VIRTUAL_INCOMING_ARGS_REGNUM
&& uregno != VIRTUAL_STACK_VARS_REGNUM)
for (i = uregno; i <= last_reg; i++)
if ((size_t) i < VARRAY_SIZE (global_const_equiv_varray))
VARRAY_CONST_EQUIV (global_const_equiv_varray, i).rtx = 0;
}
}
/* Given a pointer to some BLOCK node, if the BLOCK_ABSTRACT_ORIGIN for the
given BLOCK node is NULL, set the BLOCK_ABSTRACT_ORIGIN for the node so
that it points to the node itself, thus indicating that the node is its
own (abstract) origin. Additionally, if the BLOCK_ABSTRACT_ORIGIN for
the given node is NULL, recursively descend the decl/block tree which
it is the root of, and for each other ..._DECL or BLOCK node contained
therein whose DECL_ABSTRACT_ORIGINs or BLOCK_ABSTRACT_ORIGINs are also
still NULL, set *their* DECL_ABSTRACT_ORIGIN or BLOCK_ABSTRACT_ORIGIN
values to point to themselves. */
static void
set_block_origin_self (stmt)
tree stmt;
{
if (BLOCK_ABSTRACT_ORIGIN (stmt) == NULL_TREE)
{
BLOCK_ABSTRACT_ORIGIN (stmt) = stmt;
{
tree local_decl;
for (local_decl = BLOCK_VARS (stmt);
local_decl != NULL_TREE;
local_decl = TREE_CHAIN (local_decl))
set_decl_origin_self (local_decl); /* Potential recursion. */
}
{
tree subblock;
for (subblock = BLOCK_SUBBLOCKS (stmt);
subblock != NULL_TREE;
subblock = BLOCK_CHAIN (subblock))
set_block_origin_self (subblock); /* Recurse. */
}
}
}
/* Given a pointer to some ..._DECL node, if the DECL_ABSTRACT_ORIGIN for
the given ..._DECL node is NULL, set the DECL_ABSTRACT_ORIGIN for the
node to so that it points to the node itself, thus indicating that the
node represents its own (abstract) origin. Additionally, if the
DECL_ABSTRACT_ORIGIN for the given node is NULL, recursively descend
the decl/block tree of which the given node is the root of, and for
each other ..._DECL or BLOCK node contained therein whose
DECL_ABSTRACT_ORIGINs or BLOCK_ABSTRACT_ORIGINs are also still NULL,
set *their* DECL_ABSTRACT_ORIGIN or BLOCK_ABSTRACT_ORIGIN values to
point to themselves. */
void
set_decl_origin_self (decl)
tree decl;
{
if (DECL_ABSTRACT_ORIGIN (decl) == NULL_TREE)
{
DECL_ABSTRACT_ORIGIN (decl) = decl;
if (TREE_CODE (decl) == FUNCTION_DECL)
{
tree arg;
for (arg = DECL_ARGUMENTS (decl); arg; arg = TREE_CHAIN (arg))
DECL_ABSTRACT_ORIGIN (arg) = arg;
if (DECL_INITIAL (decl) != NULL_TREE
&& DECL_INITIAL (decl) != error_mark_node)
set_block_origin_self (DECL_INITIAL (decl));
}
}
}
/* Given a pointer to some BLOCK node, and a boolean value to set the
"abstract" flags to, set that value into the BLOCK_ABSTRACT flag for
the given block, and for all local decls and all local sub-blocks
(recursively) which are contained therein. */
static void
set_block_abstract_flags (stmt, setting)
tree stmt;
int setting;
{
tree local_decl;
tree subblock;
BLOCK_ABSTRACT (stmt) = setting;
for (local_decl = BLOCK_VARS (stmt);
local_decl != NULL_TREE;
local_decl = TREE_CHAIN (local_decl))
set_decl_abstract_flags (local_decl, setting);
for (subblock = BLOCK_SUBBLOCKS (stmt);
subblock != NULL_TREE;
subblock = BLOCK_CHAIN (subblock))
set_block_abstract_flags (subblock, setting);
}
/* Given a pointer to some ..._DECL node, and a boolean value to set the
"abstract" flags to, set that value into the DECL_ABSTRACT flag for the
given decl, and (in the case where the decl is a FUNCTION_DECL) also
set the abstract flags for all of the parameters, local vars, local
blocks and sub-blocks (recursively) to the same setting. */
void
set_decl_abstract_flags (decl, setting)
tree decl;
int setting;
{
DECL_ABSTRACT (decl) = setting;
if (TREE_CODE (decl) == FUNCTION_DECL)
{
tree arg;
for (arg = DECL_ARGUMENTS (decl); arg; arg = TREE_CHAIN (arg))
DECL_ABSTRACT (arg) = setting;
if (DECL_INITIAL (decl) != NULL_TREE
&& DECL_INITIAL (decl) != error_mark_node)
set_block_abstract_flags (DECL_INITIAL (decl), setting);
}
}
/* Output the assembly language code for the function FNDECL
from its DECL_SAVED_INSNS. Used for inline functions that are output
at end of compilation instead of where they came in the source. */
static GTY(()) struct function *old_cfun;
void
output_inline_function (fndecl)
tree fndecl;
{
enum debug_info_type old_write_symbols = write_symbols;
const struct gcc_debug_hooks *const old_debug_hooks = debug_hooks;
struct function *f = DECL_SAVED_INSNS (fndecl);
old_cfun = cfun;
cfun = f;
current_function_decl = fndecl;
set_new_last_label_num (f->inl_max_label_num);
/* We're not deferring this any longer. */
DECL_DEFER_OUTPUT (fndecl) = 0;
/* If requested, suppress debugging information. */
if (f->no_debugging_symbols)
{
write_symbols = NO_DEBUG;
debug_hooks = &do_nothing_debug_hooks;
}
/* Make sure warnings emitted by the optimizers (e.g. control reaches
end of non-void function) is not wildly incorrect. */
input_filename = DECL_SOURCE_FILE (fndecl);
lineno = DECL_SOURCE_LINE (fndecl);
/* Compile this function all the way down to assembly code. As a
side effect this destroys the saved RTL representation, but
that's okay, because we don't need to inline this anymore. */
rest_of_compilation (fndecl);
DECL_INLINE (fndecl) = 0;
cfun = old_cfun;
current_function_decl = old_cfun ? old_cfun->decl : 0;
write_symbols = old_write_symbols;
debug_hooks = old_debug_hooks;
}
/* Functions to keep track of the values hard regs had at the start of
the function. */
rtx
get_hard_reg_initial_reg (fun, reg)
struct function *fun;
rtx reg;
{
struct initial_value_struct *ivs = fun->hard_reg_initial_vals;
int i;
if (ivs == 0)
return NULL_RTX;
for (i = 0; i < ivs->num_entries; i++)
if (rtx_equal_p (ivs->entries[i].pseudo, reg))
return ivs->entries[i].hard_reg;
return NULL_RTX;
}
rtx
has_func_hard_reg_initial_val (fun, reg)
struct function *fun;
rtx reg;
{
struct initial_value_struct *ivs = fun->hard_reg_initial_vals;
int i;
if (ivs == 0)
return NULL_RTX;
for (i = 0; i < ivs->num_entries; i++)
if (rtx_equal_p (ivs->entries[i].hard_reg, reg))
return ivs->entries[i].pseudo;
return NULL_RTX;
}
rtx
get_func_hard_reg_initial_val (fun, reg)
struct function *fun;
rtx reg;
{
struct initial_value_struct *ivs = fun->hard_reg_initial_vals;
rtx rv = has_func_hard_reg_initial_val (fun, reg);
if (rv)
return rv;
if (ivs == 0)
{
fun->hard_reg_initial_vals = (void *) ggc_alloc (sizeof (initial_value_struct));
ivs = fun->hard_reg_initial_vals;
ivs->num_entries = 0;
ivs->max_entries = 5;
ivs->entries = (initial_value_pair *) ggc_alloc (5 * sizeof (initial_value_pair));
}
if (ivs->num_entries >= ivs->max_entries)
{
ivs->max_entries += 5;
ivs->entries =
(initial_value_pair *) ggc_realloc (ivs->entries,
ivs->max_entries
* sizeof (initial_value_pair));
}
ivs->entries[ivs->num_entries].hard_reg = reg;
ivs->entries[ivs->num_entries].pseudo = gen_reg_rtx (GET_MODE (reg));
return ivs->entries[ivs->num_entries++].pseudo;
}
rtx
get_hard_reg_initial_val (mode, regno)
enum machine_mode mode;
int regno;
{
return get_func_hard_reg_initial_val (cfun, gen_rtx_REG (mode, regno));
}
rtx
has_hard_reg_initial_val (mode, regno)
enum machine_mode mode;
int regno;
{
return has_func_hard_reg_initial_val (cfun, gen_rtx_REG (mode, regno));
}
static void
setup_initial_hard_reg_value_integration (inl_f, remap)
struct function *inl_f;
struct inline_remap *remap;
{
struct initial_value_struct *ivs = inl_f->hard_reg_initial_vals;
int i;
if (ivs == 0)
return;
for (i = 0; i < ivs->num_entries; i ++)
remap->reg_map[REGNO (ivs->entries[i].pseudo)]
= get_func_hard_reg_initial_val (cfun, ivs->entries[i].hard_reg);
}
void
emit_initial_value_sets ()
{
struct initial_value_struct *ivs = cfun->hard_reg_initial_vals;
int i;
rtx seq;
if (ivs == 0)
return;
start_sequence ();
for (i = 0; i < ivs->num_entries; i++)
emit_move_insn (ivs->entries[i].pseudo, ivs->entries[i].hard_reg);
seq = get_insns ();
end_sequence ();
emit_insn_after (seq, get_insns ());
}
/* If the backend knows where to allocate pseudos for hard
register initial values, register these allocations now. */
void
allocate_initial_values (reg_equiv_memory_loc)
rtx *reg_equiv_memory_loc ATTRIBUTE_UNUSED;
{
#ifdef ALLOCATE_INITIAL_VALUE
struct initial_value_struct *ivs = cfun->hard_reg_initial_vals;
int i;
if (ivs == 0)
return;
for (i = 0; i < ivs->num_entries; i++)
{
int regno = REGNO (ivs->entries[i].pseudo);
rtx x = ALLOCATE_INITIAL_VALUE (ivs->entries[i].hard_reg);
if (x == NULL_RTX || REG_N_SETS (REGNO (ivs->entries[i].pseudo)) > 1)
; /* Do nothing. */
else if (GET_CODE (x) == MEM)
reg_equiv_memory_loc[regno] = x;
else if (GET_CODE (x) == REG)
{
reg_renumber[regno] = REGNO (x);
/* Poke the regno right into regno_reg_rtx
so that even fixed regs are accepted. */
REGNO (ivs->entries[i].pseudo) = REGNO (x);
}
else abort ();
}
#endif
}
#include "gt-integrate.h"
| 32.212692 | 105 | 0.665347 | [
"object"
] |
04d59803ef473a0d5b9720d84c3faff5ea3dd1e4 | 43,813 | c | C | netbsd/sys/arch/amiga/dev/idesc.c | MarginC/kame | 2ef74fe29e4cca9b4a87a1d5041191a9e2e8be30 | [
"BSD-3-Clause"
] | 91 | 2015-01-05T15:18:31.000Z | 2022-03-11T16:43:28.000Z | netbsd/sys/arch/amiga/dev/idesc.c | MarginC/kame | 2ef74fe29e4cca9b4a87a1d5041191a9e2e8be30 | [
"BSD-3-Clause"
] | 1 | 2016-02-25T15:57:55.000Z | 2016-02-25T16:01:02.000Z | netbsd/sys/arch/amiga/dev/idesc.c | MarginC/kame | 2ef74fe29e4cca9b4a87a1d5041191a9e2e8be30 | [
"BSD-3-Clause"
] | 21 | 2015-02-07T08:23:07.000Z | 2021-12-14T06:01:49.000Z | /* $NetBSD: idesc.c,v 1.38.2.3 1999/04/19 04:25:33 cjs Exp $ */
/*
* Copyright (c) 1994 Michael L. Hitch
* Copyright (c) 1993, 1994 Charles M. Hannum.
* Copyright (c) 1990 The Regents of the University of California.
* All rights reserved.
*
* This code is derived from software contributed to Berkeley by
* Don Ahn.
*
* 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. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by the University of
* California, Berkeley and its contributors.
* 4. Neither the name of the University 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 REGENTS 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 REGENTS 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.
*
* @(#)wd.c 7.4 (Berkeley) 5/25/91
*/
/*
* Copyright (c) 1994 Michael L. Hitch
* All rights reserved.
*
* 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. All advertising materials mentioning features or use of this software
* must display the following acknowledgement:
* This product includes software developed by Brad Pepers
* 4. The name of the author may not be used to endorse or promote products
* derived from this software without specific prior written permission
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``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 AUTHOR 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.
*/
/*
* A4000 IDE interface, emulating a SCSI controller
*/
#include <sys/param.h>
#include <sys/systm.h>
#include <sys/device.h>
#include <sys/buf.h>
#include <sys/dkstat.h>
#include <sys/disklabel.h>
#include <sys/dkstat.h>
#include <sys/malloc.h>
#include <sys/proc.h>
#include <sys/reboot.h>
#include <sys/file.h>
#include <sys/ioctl.h>
#include <dev/scsipi/scsi_all.h>
#include <dev/scsipi/scsipi_all.h>
#include <dev/scsipi/scsipi_disk.h>
#include <dev/scsipi/scsi_disk.h>
#include <dev/scsipi/scsiconf.h>
#include <dev/scsipi/atapi_all.h>
#include <dev/ata/atareg.h>
#include <amiga/amiga/device.h>
#include <amiga/amiga/cia.h>
#include <amiga/amiga/custom.h>
#include <amiga/amiga/isr.h>
#include <amiga/dev/zbusvar.h>
#include "atapibus.h"
#include "idesc.h"
#define b_cylin b_resid
/* defines */
struct regs {
volatile u_short ide_data; /* 00 */
char ____pad0[4];
volatile u_char ide_error; /* 06 */
#define ide_precomp ide_error
char ____pad1[3];
volatile u_char ide_seccnt; /* 0a */
#define ide_ireason ide_seccnt /* interrupt reason (ATAPI) */
char ____pad2[3];
volatile u_char ide_sector; /* 0e */
char ____pad3[3];
volatile u_char ide_cyl_lo; /* 12 */
char ____pad4[3];
volatile u_char ide_cyl_hi; /* 16 */
char ____pad5[3];
volatile u_char ide_sdh; /* 1a */
char ____pad6[3];
volatile u_char ide_command; /* 1e */
#define ide_status ide_command
char ____pad7;
char ____pad8[0xfe0];
volatile short ide_intpnd; /* 1000 */
char ____pad9[24];
volatile u_char ide_altsts; /* 101a */
#define ide_ctlr ide_altsts
};
typedef volatile struct regs *ide_regmap_p;
#define IDES_BUSY 0x80 /* controller busy bit */
#define IDES_READY 0x40 /* selected drive is ready */
#define IDES_WRTFLT 0x20 /* Write fault */
#define IDES_SEEKCMPLT 0x10 /* Seek complete */
#define IDES_DRQ 0x08 /* Data request bit */
#define IDES_ECCCOR 0x04 /* ECC correction made in data */
#define IDES_INDEX 0x02 /* Index pulse from selected drive */
#define IDES_ERR 0x01 /* Error detect bit */
#define IDEC_RESTORE 0x10
#define IDEC_READ 0x20
#define IDEC_WRITE 0x30
#define IDEC_XXX 0x40
#define IDEC_FORMAT 0x50
#define IDEC_XXXX 0x70
#define IDEC_DIAGNOSE 0x90
#define IDEC_IDC 0x91
#define IDEC_READP 0xec
#define IDECTL_IDS 0x02 /* Interrupt disable */
#define IDECTL_RST 0x04 /* Controller reset */
/* ATAPI commands */
#define ATAPI_NOP 0x00
#define ATAPI_SOFT_RST 0x08
#define ATAPI_PACKET 0xa0
#define ATAPI_IDENTIFY 0xa1
/* ATAPI ireason */
#define IDEI_CMD 0x01 /* command(1) or data(0) */
#define IDEI_IN 0x02 /* transfer to(1) to from(0) host */
#define IDEI_RELEASE 0x04 /* bus released until finished */
#define PHASE_CMDOUT (IDES_DRQ | IDEI_CMD)
#define PHASE_DATAIN (IDES_DRQ | IDEI_IN)
#define PHASE_DATAOUT (IDES_DRQ)
#define PHASE_COMPLETED (IDEI_IN | IDEI_CMD)
#define PHASE_ABORTED (0)
struct ideparams {
/* drive info */
short idep_config; /* general configuration */
short idep_fixedcyl; /* number of non-removable cylinders */
short idep_removcyl; /* number of removable cylinders */
short idep_heads; /* number of heads */
short idep_unfbytespertrk; /* number of unformatted bytes/track */
short idep_unfbytes; /* number of unformatted bytes/sector */
short idep_sectors; /* number of sectors */
short idep_minisg; /* minimum bytes in inter-sector gap*/
short idep_minplo; /* minimum bytes in postamble */
short idep_vendstat; /* number of words of vendor status */
/* controller info */
char idep_cnsn[20]; /* controller serial number */
short idep_cntype; /* controller type */
#define IDETYPE_SINGLEPORTSECTOR 1 /* single port, single sector buffer */
#define IDETYPE_DUALPORTMULTI 2 /* dual port, multiple sector buffer */
#define IDETYPE_DUALPORTMULTICACHE 3 /* above plus track cache */
short idep_cnsbsz; /* sector buffer size, in sectors */
short idep_necc; /* ecc bytes appended */
char idep_rev[8]; /* firmware revision */
char idep_model[40]; /* model name */
short idep_nsecperint; /* sectors per interrupt */
short idep_usedmovsd; /* can use double word read/write? */
};
/*
* Per drive structure.
* N per controller (presently 2) (DRVS_PER_CTLR)
*/
struct ide_softc {
struct device sc_dev;
long sc_bcount; /* byte count left */
long sc_mbcount; /* total byte count left */
short sc_skip; /* blocks already transferred */
short sc_mskip; /* blocks already transfereed for multi */
long sc_blknum; /* starting block of active request */
u_char *sc_buf; /* buffer address of active request */
long sc_blkcnt; /* block count of active request */
int sc_flags;
#define IDEF_ALIVE 0x01 /* it's a valid device */
#define IDEF_ATAPI 0x02 /* it's an ATAPI device */
#define IDEF_ACAPLEN 0x04
#define IDEF_ACAPDRQ 0x08
#define IDEF_SENSE 0x10 /* Doing a request sense command */
short sc_error;
char sc_drive;
char sc_state;
long sc_secpercyl;
long sc_sectors;
struct buf sc_dq;
struct ideparams sc_params;
};
struct ide_pending {
TAILQ_ENTRY(ide_pending) link;
struct scsipi_xfer *xs;
};
/*
* Per controller structure.
*/
struct idec_softc
{
struct device sc_dev;
struct isr sc_isr;
struct scsipi_link sc_link; /* proto for sub devices */
struct scsipi_adapter sc_adapter;
ide_regmap_p sc_cregs; /* driver specific regs */
volatile u_char *sc_a1200; /* A1200 interrupt control */
TAILQ_HEAD(,ide_pending) sc_xslist; /* LIFO */
struct ide_pending sc_xsstore[8][8]; /* one for every unit */
struct scsipi_xfer *sc_xs; /* transfer from high level code */
int sc_flags;
#define IDECF_ALIVE 0x01 /* Controller is alive */
#define IDECF_ACTIVE 0x02
#define IDECF_SINGLE 0x04 /* sector at a time mode */
#define IDECF_READ 0x08 /* Current operation is read */
#define IDECF_A1200 0x10 /* A1200 IDE */
struct ide_softc *sc_cur; /* drive we are currently doing work for */
int state;
int saved;
int retry;
char sc_status;
char sc_error;
char sc_stat[2];
struct ide_softc sc_ide[2];
};
int ide_scsicmd __P((struct scsipi_xfer *));
void idescattach __P((struct device *, struct device *, void *));
int idescmatch __P((struct device *, struct cfdata *, void *));
int ideicmd __P((struct idec_softc *, int, void *, int, void *, int));
int idego __P((struct idec_softc *, struct scsipi_xfer *));
int idegetsense __P((struct idec_softc *, struct scsipi_xfer *));
void ideabort __P((struct idec_softc *, ide_regmap_p, char *));
void ideerror __P((struct idec_softc *, ide_regmap_p, u_char));
int idestart __P((struct idec_softc *));
int idereset __P((struct idec_softc *));
void idesetdelay __P((int));
void ide_scsidone __P((struct idec_softc *, int));
void ide_donextcmd __P((struct idec_softc *));
int idesc_intr __P((void *));
int ide_atapi_icmd __P((struct idec_softc *, int, void *, int, void *, int));
int ide_atapi_start __P((struct idec_softc *));
int ide_atapi_intr __P((struct idec_softc *));
void ide_atapi_done __P((struct idec_softc *));
struct scsipi_device idesc_scsidev = {
NULL, /* use default error handler */
NULL, /* do not have a start functio */
NULL, /* have no async handler */
NULL, /* Use default done routine */
};
struct cfattach idesc_ca = {
sizeof(struct idec_softc), idescmatch, idescattach
};
struct {
short ide_err;
char scsi_sense_key;
char scsi_sense_qual;
} sense_convert[] = {
{ 0x0001, 0x03, 0x13}, /* Data address mark not found */
{ 0x0002, 0x04, 0x06}, /* Reference position not found */
{ 0x0004, 0x05, 0x20}, /* Invalid command */
{ 0x0010, 0x03, 0x12}, /* ID address mark not found */
{ 0x0020, 0x06, 0x00}, /* Media changed */
{ 0x0040, 0x03, 0x11}, /* Unrecovered read error */
{ 0x0080, 0x03, 0x11}, /* Bad block mark detected */
{ 0x0000, 0x05, 0x00} /* unknown */
};
/*
* protos.
*/
int idecommand __P((struct ide_softc *, int, int, int, int, int));
int idewait __P((struct idec_softc *, int));
int idegetctlr __P((struct ide_softc *));
int ideiread __P((struct ide_softc *, long, u_char *, int));
int ideiwrite __P((struct ide_softc *, long, u_char *, int));
#define wait_for_drq(ide) idewait(ide, IDES_DRQ)
#define wait_for_ready(ide) idewait(ide, IDES_READY | IDES_SEEKCMPLT)
#define wait_for_unbusy(ide) idewait(ide,0)
int ide_no_int = 0;
#ifdef DEBUG
void ide_dump_regs __P((ide_regmap_p));
int ide_debug = 0;
#define TRACE0(arg) if (ide_debug > 1) printf(arg)
#define TRACE1(arg1,arg2) if (ide_debug > 1) printf(arg1,arg2)
#define QPRINTF(a) if (ide_debug > 1) printf a
#else /* !DEBUG */
#define TRACE0(arg)
#define TRACE1(arg1,arg2)
#define QPRINTF(a)
#endif /* !DEBUG */
/*
* if we are an A4000 we are here.
*/
int
idescmatch(pdp, cfp, auxp)
struct device *pdp;
struct cfdata *cfp;
void *auxp;
{
char *mbusstr;
mbusstr = auxp;
if ((is_a4000() || is_a1200()) && matchname(auxp, "idesc"))
return(1);
return(0);
}
void
idescattach(pdp, dp, auxp)
struct device *pdp, *dp;
void *auxp;
{
ide_regmap_p rp;
struct idec_softc *sc;
int i;
sc = (struct idec_softc *)dp;
if (is_a4000())
sc->sc_cregs = rp = (ide_regmap_p) ztwomap(0xdd2020);
else {
/* Let's hope the A1200 will work with the same regs */
sc->sc_cregs = rp = (ide_regmap_p) ztwomap(0xda0000);
sc->sc_a1200 = ztwomap(0xda8000 + 0x1000);
sc->sc_flags |= IDECF_A1200;
printf(" A1200 @ %p:%p", rp, sc->sc_a1200);
}
#ifdef DEBUG
if (ide_debug)
ide_dump_regs(rp);
#endif
if (idereset(sc) != 0) {
#ifdef DEBUG_ATAPI
printf("\nIDE reset failed, checking ATAPI ");
#endif
rp->ide_sdh = 0xb0; /* slave */
#ifdef DEBUG_ATAPI
printf(" cyl lo %x hi %x\n", rp->ide_cyl_lo, rp->ide_cyl_hi);
#endif
delay(500000);
idereset(sc);
}
#ifdef DEBUG_ATAPI
if (rp->ide_cyl_lo == 0x14 && rp->ide_cyl_hi == 0xeb)
printf(" ATAPI drive present?\n");
#endif
rp->ide_error = 0x5a;
rp->ide_cyl_lo = 0xa5;
if (rp->ide_error == 0x5a || rp->ide_cyl_lo != 0xa5) {
printf ("\n");
return;
}
/* test if controller will reset */
if (idereset(sc) != 0) {
delay (500000);
if (idereset(sc) != 0) {
printf (" IDE controller did not reset\n");
return;
}
}
/* Dummy up the unit structures */
sc->sc_ide[0].sc_dev.dv_parent = (void *) sc;
sc->sc_ide[1].sc_dev.dv_parent = (void *) sc;
#if 0 /* Amiga ROM does this; it also takes a lot of time on the Seacrate */
/* Execute a controller only command. */
if (idecommand(&sc->sc_ide[0], 0, 0, 0, 0, IDEC_DIAGNOSE) != 0 ||
wait_for_unbusy(sc) != 0) {
printf (" ide attach failed\n");
return;
}
#endif
#ifdef DEBUG
if (ide_debug)
ide_dump_regs(rp);
#endif
idereset(sc);
for (i = 0; i < 2; ++i) {
rp->ide_sdh = 0xa0 | (i << 4);
sc->sc_ide[i].sc_drive = i;
if ((rp->ide_status & IDES_READY) == 0) {
int len;
struct ataparams id;
u_short *p = (u_short *)&id;
sc->sc_ide[i].sc_flags |= IDEF_ATAPI;
if (idecommand(&sc->sc_ide[i], 0, 0, 0, 0, ATAPI_SOFT_RST)
!= 0) {
#ifdef DEBUG_ATAPI
printf("\nATAPI_SOFT_RESET failed for drive %d",
i);
#endif
continue;
}
if (wait_for_unbusy(sc) != 0) {
#ifdef DEBUG_ATAPI
printf("\nATAPI wait for unbusy failed");
#endif
continue;
}
if (idecommand(&sc->sc_ide[i], DEV_BSIZE, 0, 0, 0,
ATAPI_IDENTIFY) != 0 ||
wait_for_drq(sc) != 0) {
#ifdef DEBUG_ATAPI
printf("\nATAPI_IDENTIFY failed for drive %d",
i);
#endif
continue;
}
len = DEV_BSIZE;
#ifdef DEBUG_ATAPI
printf("\nATAPI_IDENTIFY returned %d/%d bytes",
rp->ide_cyl_lo + rp->ide_cyl_hi * 256, DEV_BSIZE);
#endif
while (len) {
if (p < (u_short *)(&id + 1))
*p++ = rp->ide_data;
else
rp->ide_data;
len -= 2;
}
bswap(id.atap_model, sizeof(id.atap_model));
bswap(id.atap_serial, sizeof(id.atap_serial));
bswap(id.atap_revision, sizeof(id.atap_revision));
strncpy(sc->sc_ide[i].sc_params.idep_model, id.atap_model,
sizeof(sc->sc_ide[i].sc_params.idep_model));
strncpy(sc->sc_ide[i].sc_params.idep_rev, id.atap_revision,
sizeof(sc->sc_ide[i].sc_params.idep_rev));
for (len = sizeof(id.atap_model) - 1;
id.atap_model[len] == ' ' && len != 0; --len)
;
if (len < sizeof(id.atap_model) - 1)
id.atap_model[len] = 0;
for (len = sizeof(id.atap_serial) - 1;
id.atap_serial[len] == ' ' && len != 0; --len)
;
if (len < sizeof(id.atap_serial) - 1)
id.atap_serial[len] = 0;
for (len = sizeof(id.atap_revision) - 1;
id.atap_revision[len] == ' ' && len != 0; --len)
;
if (len < sizeof(id.atap_revision) - 1)
id.atap_revision[len] = 0;
bswap((char *)&id.atap_config, sizeof(id.atap_config));
#ifdef DEBUG_ATAPI
printf("\nATAPI device: type %x", ATAPI_CFG_TYPE(id.atap_config));
printf(" cyls %04x heads %04x",
id.atap_cylinders, id.atap_heads);
printf(" bpt %04x bps %04x",
id.__retired1[0],
id.__retired2[0]);
printf(" drq_rem %02x", id.atap_config& 0xff);
printf("\n model %s rev %s ser %s", id.atap_model,
id.atap_revision, id.atap_serial);
printf("\n cap %04x%04x sect %04x%04x",
id.atap_curcapacity[0], id.atap_curcapacity[1],
id.atap_capacity[0], id.atap_capacity[1]);
#endif
if (id.atap_config & ATAPI_CFG_CMD_16)
sc->sc_ide[i].sc_flags |= IDEF_ACAPLEN;
if ((id.atap_config & ATAPI_CFG_DRQ_MASK) == ATAPI_CFG_IRQ_DRQ)
sc->sc_ide[i].sc_flags |= IDEF_ACAPDRQ;
}
sc->sc_ide[i].sc_flags |= IDEF_ALIVE;
rp->ide_ctlr = 0;
}
printf ("\n");
sc->sc_adapter.scsipi_cmd = ide_scsicmd;
sc->sc_adapter.scsipi_minphys = minphys;
sc->sc_link.scsipi_scsi.channel = SCSI_CHANNEL_ONLY_ONE;
sc->sc_link.adapter_softc = sc;
sc->sc_link.scsipi_scsi.adapter_target = 7;
sc->sc_link.adapter = &sc->sc_adapter;
sc->sc_link.device = &idesc_scsidev;
sc->sc_link.openings = 1;
sc->sc_link.scsipi_scsi.max_target = 7;
sc->sc_link.scsipi_scsi.max_lun = 7;
sc->sc_link.type = BUS_SCSI;
TAILQ_INIT(&sc->sc_xslist);
sc->sc_isr.isr_intr = idesc_intr;
sc->sc_isr.isr_arg = sc;
sc->sc_isr.isr_ipl = 2;
add_isr (&sc->sc_isr);
/*
* attach all "scsi" units on us
*/
config_found(dp, &sc->sc_link, scsiprint);
}
/*
* used by specific ide controller
*
*/
int
ide_scsicmd(xs)
struct scsipi_xfer *xs;
{
struct ide_pending *pendp;
struct idec_softc *dev;
struct scsipi_link *slp;
int flags, s;
slp = xs->sc_link;
dev = slp->adapter_softc;
flags = xs->flags;
if (flags & SCSI_DATA_UIO)
panic("ide: scsi data uio requested");
if (dev->sc_xs && flags & SCSI_POLL)
panic("ide_scsicmd: busy");
s = splbio();
pendp = &dev->sc_xsstore[slp->scsipi_scsi.target][slp->scsipi_scsi.lun];
if (pendp->xs) {
splx(s);
return(TRY_AGAIN_LATER);
}
if (dev->sc_xs) {
pendp->xs = xs;
TAILQ_INSERT_TAIL(&dev->sc_xslist, pendp, link);
splx(s);
return(SUCCESSFULLY_QUEUED);
}
pendp->xs = NULL;
dev->sc_xs = xs;
splx(s);
/*
* nothing is pending do it now.
*/
ide_donextcmd(dev);
if (flags & SCSI_POLL)
return(COMPLETE);
return(SUCCESSFULLY_QUEUED);
}
/*
* entered with dev->sc_xs pointing to the next xfer to perform
*/
void
ide_donextcmd(dev)
struct idec_softc *dev;
{
struct scsipi_xfer *xs;
struct scsipi_link *slp;
int flags, stat;
xs = dev->sc_xs;
slp = xs->sc_link;
flags = xs->flags;
if (flags & SCSI_RESET)
idereset(dev);
dev->sc_stat[0] = -1;
/* Weed out invalid targets & LUNs here */
if (slp->scsipi_scsi.target > 1 || slp->scsipi_scsi.lun != 0) {
ide_scsidone(dev, -1);
return;
}
if (flags & SCSI_POLL || ide_no_int)
stat = ideicmd(dev, slp->scsipi_scsi.target, xs->cmd, xs->cmdlen,
xs->data, xs->datalen);
else if (idego(dev, xs) == 0)
return;
else
stat = dev->sc_stat[0];
if (dev->sc_xs)
ide_scsidone(dev, stat);
}
void
ide_scsidone(dev, stat)
struct idec_softc *dev;
int stat;
{
struct ide_pending *pendp;
struct scsipi_xfer *xs;
int s, donext;
xs = dev->sc_xs;
#ifdef DIAGNOSTIC
if (xs == NULL)
panic("ide_scsidone");
#endif
/*
* is this right?
*/
xs->status = stat;
if (stat == 0)
xs->resid = 0;
else {
switch(stat) {
case SCSI_CHECK:
if ((stat = idegetsense(dev, xs)) != 0)
goto bad_sense;
xs->error = XS_SENSE;
break;
case SCSI_BUSY:
xs->error = XS_BUSY;
break;
bad_sense:
default:
xs->error = XS_DRIVER_STUFFUP;
QPRINTF(("ide_scsicmd() bad %x\n", stat));
break;
}
}
xs->flags |= ITSDONE;
/*
* grab next command before scsipi_done()
* this way no single device can hog scsi resources.
*/
s = splbio();
pendp = dev->sc_xslist.tqh_first;
if (pendp == NULL) {
donext = 0;
dev->sc_xs = NULL;
} else {
donext = 1;
TAILQ_REMOVE(&dev->sc_xslist, pendp, link);
dev->sc_xs = pendp->xs;
pendp->xs = NULL;
}
splx(s);
scsipi_done(xs);
if (donext)
ide_donextcmd(dev);
}
int
idegetsense(dev, xs)
struct idec_softc *dev;
struct scsipi_xfer *xs;
{
struct scsipi_sense rqs;
struct scsipi_link *slp;
if (dev->sc_cur->sc_flags & IDEF_ATAPI)
return (0);
slp = xs->sc_link;
rqs.opcode = REQUEST_SENSE;
rqs.byte2 = slp->scsipi_scsi.lun << 5;
#ifdef not_yet
rqs.length = xs->req_sense_length ? xs->req_sense_length :
sizeof(xs->sense.scsi_sense);
#else
rqs.length = sizeof(xs->sense.scsi_sense);
#endif
rqs.unused[0] = rqs.unused[1] = rqs.control = 0;
return(ideicmd(dev, slp->scsipi_scsi.target, &rqs, sizeof(rqs),
&xs->sense.scsi_sense, rqs.length));
}
#ifdef DEBUG
void
ide_dump_regs(regs)
ide_regmap_p regs;
{
printf ("ide regs: %04x %02x %02x %02x %02x %02x %02x %02x\n",
regs->ide_data, regs->ide_error, regs->ide_seccnt,
regs->ide_sector, regs->ide_cyl_lo, regs->ide_cyl_hi,
regs->ide_sdh, regs->ide_command);
}
#endif
int
idereset(sc)
struct idec_softc *sc;
{
ide_regmap_p regs=sc->sc_cregs;
regs->ide_ctlr = IDECTL_RST | IDECTL_IDS;
delay(1000);
regs->ide_ctlr = IDECTL_IDS;
delay(1000);
(void) regs->ide_error;
if (wait_for_unbusy(sc) < 0) {
printf("%s: reset failed\n", sc->sc_dev.dv_xname);
return (1);
}
return (0);
}
int
idewait (sc, mask)
struct idec_softc *sc;
int mask;
{
ide_regmap_p regs = sc->sc_cregs;
int timeout = 0;
int status = sc->sc_status = regs->ide_status;
if ((status & IDES_BUSY) == 0 && (status & mask) == mask)
return (0);
#ifdef DEBUG
if (ide_debug)
printf ("idewait busy: %02x\n", status);
#endif
for (;;) {
status = sc->sc_status = regs->ide_status;
if ((status & IDES_BUSY) == 0 && (status & mask) == mask)
break;
#if 0
if (status & IDES_ERR)
break;
#endif
if (++timeout > 10000) {
#ifdef DEBUG_ATAPI
printf ("idewait timeout status %02x error %02x\n",
status, regs->ide_error);
#endif
return (-1);
}
delay (1000);
}
if (status & IDES_ERR) {
sc->sc_error = regs->ide_error;
#ifdef DEBUG
if (ide_debug)
printf ("idewait: status %02x error %02x\n", status,
sc->sc_error);
#endif
}
#ifdef DEBUG
else if (ide_debug)
printf ("idewait delay %d %02x\n", timeout, status);
#endif
return (status & IDES_ERR);
}
int
idecommand (ide, cylin, head, sector, count, cmd)
struct ide_softc *ide;
int cylin, head, sector, count;
int cmd;
{
struct idec_softc *idec = (void *)ide->sc_dev.dv_parent;
ide_regmap_p regs = idec->sc_cregs;
int stat;
#ifdef DEBUG
if (ide_debug)
printf ("idecommand: cmd = %02x\n", cmd);
#endif
if (wait_for_unbusy(idec) < 0)
return (-1);
regs->ide_sdh = 0xa0 | (ide->sc_drive << 4) | head;
if (cmd == IDEC_DIAGNOSE || cmd == IDEC_IDC || ide->sc_flags & IDEF_ATAPI)
stat = wait_for_unbusy(idec);
else
stat = idewait(idec, IDES_READY);
if (stat < 0) printf ("idecommand:%d stat %d\n", ide->sc_drive, stat);
if (stat < 0)
return (-1);
regs->ide_precomp = 0;
regs->ide_cyl_lo = cylin;
regs->ide_cyl_hi = cylin >> 8;
regs->ide_sector = sector;
regs->ide_seccnt = count;
regs->ide_command = cmd;
return (0);
}
int
idegetctlr(dev)
struct ide_softc *dev;
{
struct idec_softc *idec = (void *)dev->sc_dev.dv_parent;
ide_regmap_p regs = idec->sc_cregs;
char tb[DEV_BSIZE];
short *tbp = (short *) tb;
int i;
if (idecommand(dev, 0, 0, 0, 0, IDEC_READP) != 0 ||
wait_for_drq(idec) != 0) {
return (-1);
} else {
for (i = 0; i < DEV_BSIZE / 2; ++i)
*tbp++ = ntohs(regs->ide_data);
for (i = 0; i < DEV_BSIZE; i += 2) {
char temp;
temp = tb[i];
tb[i] = tb[i + 1];
tb[i + 1] = temp;
}
bcopy (tb, &dev->sc_params, sizeof (struct ideparams));
dev->sc_sectors = dev->sc_params.idep_sectors;
dev->sc_secpercyl = dev->sc_sectors *
dev->sc_params.idep_heads;
}
return (0);
}
int
ideiread(ide, block, buf, nblks)
struct ide_softc *ide;
long block;
u_char *buf;
int nblks;
{
int cylin, head, sector;
int stat;
u_short *bufp = (u_short *) buf;
int i;
struct idec_softc *idec = (void *) ide->sc_dev.dv_parent;
ide_regmap_p regs = idec->sc_cregs;
cylin = block / ide->sc_secpercyl;
head = (block % ide->sc_secpercyl) / ide->sc_sectors;
sector = block % ide->sc_sectors + 1;
stat = idecommand(ide, cylin, head, sector, nblks, IDEC_READ);
if (stat != 0)
return (-1);
while (nblks--) {
if (wait_for_drq(idec) != 0)
return (-1);
for (i = 0; i < DEV_BSIZE / 2 / 16; ++i) {
*bufp++ = regs->ide_data;
*bufp++ = regs->ide_data;
*bufp++ = regs->ide_data;
*bufp++ = regs->ide_data;
*bufp++ = regs->ide_data;
*bufp++ = regs->ide_data;
*bufp++ = regs->ide_data;
*bufp++ = regs->ide_data;
*bufp++ = regs->ide_data;
*bufp++ = regs->ide_data;
*bufp++ = regs->ide_data;
*bufp++ = regs->ide_data;
*bufp++ = regs->ide_data;
*bufp++ = regs->ide_data;
*bufp++ = regs->ide_data;
*bufp++ = regs->ide_data;
}
}
idec->sc_stat[0] = 0;
return (0);
}
int
ideiwrite(ide, block, buf, nblks)
struct ide_softc *ide;
long block;
u_char *buf;
int nblks;
{
int cylin, head, sector;
int stat;
u_short *bufp = (u_short *) buf;
int i;
struct idec_softc *idec = (void *) ide->sc_dev.dv_parent;
ide_regmap_p regs = idec->sc_cregs;
cylin = block / ide->sc_secpercyl;
head = (block % ide->sc_secpercyl) / ide->sc_sectors;
sector = block % ide->sc_sectors + 1;
stat = idecommand(ide, cylin, head, sector, nblks, IDEC_WRITE);
if (stat != 0)
return (-1);
while (nblks--) {
if (wait_for_drq(idec) != 0)
return (-1);
for (i = 0; i < DEV_BSIZE / 2 / 16; ++i) {
regs->ide_data = *bufp++;
regs->ide_data = *bufp++;
regs->ide_data = *bufp++;
regs->ide_data = *bufp++;
regs->ide_data = *bufp++;
regs->ide_data = *bufp++;
regs->ide_data = *bufp++;
regs->ide_data = *bufp++;
regs->ide_data = *bufp++;
regs->ide_data = *bufp++;
regs->ide_data = *bufp++;
regs->ide_data = *bufp++;
regs->ide_data = *bufp++;
regs->ide_data = *bufp++;
regs->ide_data = *bufp++;
regs->ide_data = *bufp++;
}
if (wait_for_unbusy(idec) != 0)
printf ("ideiwrite: timeout waiting for unbusy\n");
}
idec->sc_stat[0] = 0;
return (0);
}
int
ideicmd(dev, target, cbuf, clen, buf, len)
struct idec_softc *dev;
int target;
void *cbuf;
int clen;
void *buf;
int len;
{
struct ide_softc *ide;
int i;
int lba;
int nblks;
struct scsipi_inquiry_data *inqbuf;
struct {
struct scsi_mode_header header;
struct scsi_blk_desc blk_desc;
union scsi_disk_pages pages;
} *mdsnbuf;
#ifdef DEBUG
if (ide_debug > 1)
printf ("ideicmd: target %d cmd %02x\n", target,
*((u_char *)cbuf));
#endif
if (target > 1)
return (-1); /* invalid unit */
ide = &dev->sc_ide[target];
if ((ide->sc_flags & IDEF_ALIVE) == 0)
return (-1);
if(ide->sc_flags & IDEF_ATAPI) {
#ifdef DEBUG
if (ide_debug)
printf("ideicmd: atapi cmd %02x\n", *((u_char *)cbuf));
#endif
return (ide_atapi_icmd(dev, target, cbuf, clen, buf, len));
}
if (*((u_char *)cbuf) != REQUEST_SENSE)
ide->sc_error = 0;
switch (*((u_char *)cbuf)) {
case TEST_UNIT_READY:
dev->sc_stat[0] = 0;
return (0);
case INQUIRY:
dev->sc_stat[0] = idegetctlr(ide);
if (dev->sc_stat[0] != 0)
return (dev->sc_stat[0]);
inqbuf = (void *) buf;
bzero (buf, len);
inqbuf->device = 0;
inqbuf->dev_qual2 = 0; /* XXX check RMB? */
inqbuf->version = 2;
inqbuf->response_format = 2;
inqbuf->additional_length = 31;
for (i = 0; i < 8; ++i)
inqbuf->vendor[i] = ide->sc_params.idep_model[i];
for (i = 0; i < 16; ++i)
inqbuf->product[i] = ide->sc_params.idep_model[i+8];
for (i = 0; i < 4; ++i)
inqbuf->revision[i] = ide->sc_params.idep_rev[i];
return (0);
case READ_CAPACITY:
*((long *)buf) = ide->sc_params.idep_sectors *
ide->sc_params.idep_heads *
ide->sc_params.idep_fixedcyl - 1;
*((long *)buf + 1) = ide->sc_flags & IDEF_ATAPI ?
512 : /* XXX 512 byte blocks */
2048; /* XXX */
dev->sc_stat[0] = 0;
return (0);
case READ_BIG:
lba = *((long *)((char *)cbuf + 2));
nblks = *((u_short *)((char *)cbuf + 7));
return (ideiread(ide, lba, buf, nblks));
case SCSI_READ_COMMAND:
lba = *((long *)cbuf) & 0x001fffff;
nblks = *((u_char *)((char *)cbuf + 4));
if (nblks == 0)
nblks = 256;
return (ideiread(ide, lba, buf, nblks));
case WRITE_BIG:
lba = *((long *)((char *)cbuf + 2));
nblks = *((u_short *)((char *)cbuf + 7));
return (ideiwrite(ide, lba, buf, nblks));
case SCSI_WRITE_COMMAND:
lba = *((long *)cbuf) & 0x001fffff;
nblks = *((u_char *)((char *)cbuf + 4));
if (nblks == 0)
nblks = 256;
return (ideiwrite(ide, lba, buf, nblks));
case PREVENT_ALLOW:
case START_STOP: /* and LOAD */
dev->sc_stat[0] = 0;
return (0);
case SCSI_MODE_SENSE:
mdsnbuf = (void*) buf;
bzero(buf, *((u_char *)cbuf + 4));
switch (*((u_char *)cbuf + 2) & 0x3f) {
case 4:
mdsnbuf->header.data_length = 27;
mdsnbuf->header.blk_desc_len = 8;
mdsnbuf->blk_desc.blklen[1] = 512 >> 8;
mdsnbuf->pages.rigid_geometry.pg_code = 4;
mdsnbuf->pages.rigid_geometry.pg_length = 16;
_lto3b(ide->sc_params.idep_fixedcyl,
mdsnbuf->pages.rigid_geometry.ncyl);
mdsnbuf->pages.rigid_geometry.nheads =
ide->sc_params.idep_heads;
dev->sc_stat[0] = 0;
return (0);
default:
printf ("ide: mode sense page %x not simulated\n",
*((u_char *)cbuf + 2) & 0x3f);
return (-1);
}
case REQUEST_SENSE:
/* convert sc_error to SCSI sense */
bzero (buf, *((u_char *)cbuf + 4));
*((u_char *) buf) = 0x70;
*((u_char *) buf + 7) = 10;
i = 0;
while (sense_convert[i].ide_err) {
if (sense_convert[i].ide_err & ide->sc_error)
break;
++i;
}
*((u_char *) buf + 2) = sense_convert[i].scsi_sense_key;
*((u_char *) buf + 12) = sense_convert[i].scsi_sense_qual;
dev->sc_stat[0] = 0;
return (0);
case 0x01 /*REWIND*/:
case 0x04 /*CMD_FORMAT_UNIT*/:
case 0x05 /*READ_BLOCK_LIMITS*/:
case SCSI_REASSIGN_BLOCKS:
case 0x10 /*WRITE_FILEMARKS*/:
case 0x11 /*SPACE*/:
case SCSI_MODE_SELECT:
default:
printf ("ide: unhandled SCSI command %02x\n", *((u_char *)cbuf));
ide->sc_error = 0x04;
dev->sc_stat[0] = SCSI_CHECK;
return (SCSI_CHECK);
}
}
int
idego(dev, xs)
struct idec_softc *dev;
struct scsipi_xfer *xs;
{
struct ide_softc *ide = &dev->sc_ide[xs->sc_link->scsipi_scsi.target];
long lba;
int nblks;
#if 0
cdb->cdb[1] |= unit << 5;
#endif
ide->sc_buf = xs->data;
ide->sc_bcount = xs->datalen;
#ifdef DEBUG
if (ide_debug > 1)
printf ("ide_go: %02x\n", xs->cmd->opcode);
#endif
if(ide->sc_flags & IDEF_ATAPI) {
#ifdef DEBUG
if (ide_debug)
printf("idego: atapi cmd %02x\n", xs->cmd->opcode);
#endif
dev->sc_cur = ide;
ide->sc_flags &= ~IDEF_SENSE;
return (idestart(dev));
}
if (xs->cmd->opcode != SCSI_READ_COMMAND && xs->cmd->opcode != READ_BIG &&
xs->cmd->opcode != SCSI_WRITE_COMMAND && xs->cmd->opcode != WRITE_BIG) {
ideicmd (dev, xs->sc_link->scsipi_scsi.target, xs->cmd, xs->cmdlen,
xs->data, xs->datalen);
return (1);
}
switch (xs->cmd->opcode) {
case SCSI_READ_COMMAND:
case SCSI_WRITE_COMMAND:
lba = *((long *)xs->cmd) & 0x001fffff;
nblks = xs->cmd->bytes[3];
if (nblks == 0)
nblks = 256;
break;
case READ_BIG:
case WRITE_BIG:
lba = *((long *)&xs->cmd->bytes[1]);
nblks = *((short *)&xs->cmd->bytes[6]);
break;
default:
panic ("idego bad SCSI command");
}
ide->sc_blknum = lba;
ide->sc_blkcnt = nblks;
ide->sc_skip = ide->sc_mskip = 0;
dev->sc_flags &= ~IDECF_READ;
if (xs->cmd->opcode == SCSI_READ_COMMAND || xs->cmd->opcode == READ_BIG)
dev->sc_flags |= IDECF_READ;
dev->sc_cur = ide;
return (idestart (dev));
}
int
idestart(dev)
struct idec_softc *dev;
{
long blknum, cylin, head, sector;
int command, count;
struct ide_softc *ide = dev->sc_cur;
short *bf;
int i;
ide_regmap_p regs = dev->sc_cregs;
dev->sc_flags |= IDECF_ACTIVE;
if (ide->sc_flags & IDEF_ATAPI)
return(ide_atapi_start(dev));
blknum = ide->sc_blknum + ide->sc_skip;
if (ide->sc_mskip == 0) {
ide->sc_mbcount = ide->sc_bcount;
}
cylin = blknum / ide->sc_secpercyl;
head = (blknum % ide->sc_secpercyl) / ide->sc_sectors;
sector = blknum % ide->sc_sectors;
++sector;
if (ide->sc_mskip == 0 || dev->sc_flags & IDECF_SINGLE) {
count = howmany(ide->sc_mbcount, DEV_BSIZE);
command = (dev->sc_flags & IDECF_READ) ?
IDEC_READ : IDEC_WRITE;
if (idecommand(ide, cylin, head, sector, count, command) != 0) {
printf ("idestart: timeout waiting for unbusy\n");
#if 0
bp->b_error = EINVAL;
bp->b_flags |= B_ERROR;
idfinish(&dev->sc_ide[0], bp);
#endif
ide_scsidone(dev, dev->sc_stat[0]);
return (1);
}
}
dev->sc_stat[0] = 0;
if (dev->sc_flags & IDECF_READ)
return (0);
if (wait_for_drq(dev) < 0) {
printf ("idestart: timeout waiting for drq\n");
}
#define W1 (regs->ide_data = *bf++)
for (i = 0, bf = (short *) (ide->sc_buf + ide->sc_skip * DEV_BSIZE);
i < DEV_BSIZE / 2 / 16; ++i) {
W1; W1; W1; W1; W1; W1; W1; W1;
W1; W1; W1; W1; W1; W1; W1; W1;
}
return (0);
}
int
idesc_intr(arg)
void *arg;
{
struct idec_softc *dev = arg;
ide_regmap_p regs;
struct ide_softc *ide;
short dummy;
short *bf;
int i;
regs = dev->sc_cregs;
if (dev->sc_flags & IDECF_A1200) {
if (*dev->sc_a1200 & 0x80) {
#if 0
printf ("idesc_intr: A1200 interrupt %x\n", *dev->sc_a1200);
#endif
dummy = regs->ide_status; /* XXX */
*dev->sc_a1200 = 0x7c | (*dev->sc_a1200 & 0x03);
}
else
return (0);
} else {
if (regs->ide_intpnd >= 0)
return (0);
dummy = regs->ide_status;
}
#ifdef DEBUG
if (ide_debug)
printf ("idesc_intr: %02x\n", dummy);
#endif
if ((dev->sc_flags & IDECF_ACTIVE) == 0)
return (1);
if (dev->sc_cur->sc_flags & IDEF_ATAPI)
return (ide_atapi_intr(dev));
dev->sc_flags &= ~IDECF_ACTIVE;
if (wait_for_unbusy(dev) < 0)
printf ("idesc_intr: timeout waiting for unbusy\n");
ide = dev->sc_cur;
if (dummy & IDES_ERR) {
dev->sc_stat[0] = SCSI_CHECK;
ide->sc_error = regs->ide_error;
#ifdef DEBUG
printf("idesc_intr: error %02x, %02x\n", ide->sc_error, dummy);
#endif
ide_scsidone(dev, dev->sc_stat[0]);
}
if (dev->sc_flags & IDECF_READ) {
#define R2 (*bf++ = regs->ide_data)
bf = (short *) (ide->sc_buf + ide->sc_skip * DEV_BSIZE);
if (wait_for_drq(dev) != 0)
printf ("idesc_intr: read error detected late\n");
for (i = 0; i < DEV_BSIZE / 2 / 16; ++i) {
R2; R2; R2; R2; R2; R2; R2; R2;
R2; R2; R2; R2; R2; R2; R2; R2;
}
}
ide->sc_skip++;
ide->sc_mskip++;
ide->sc_bcount -= DEV_BSIZE;
ide->sc_mbcount -= DEV_BSIZE;
#ifdef DEBUG
if (ide_debug)
printf ("idesc_intr: sc_bcount %ld\n", ide->sc_bcount);
#endif
if (ide->sc_bcount == 0)
ide_scsidone(dev, dev->sc_stat[0]);
else
/* Check return value here? */
idestart (dev);
return (1);
}
int ide_atapi_start(dev)
struct idec_softc *dev;
{
ide_regmap_p regs = dev->sc_cregs;
struct scsipi_xfer *xs;
int clen;
if (wait_for_unbusy(dev) != 0) {
printf("ide_atapi_start: not ready, st = %02x\n",
regs->ide_status);
dev->sc_stat[0] = -1;
ide_scsidone(dev, dev->sc_stat[0]);
return (-1);
}
xs = dev->sc_xs;
clen = dev->sc_cur->sc_flags & IDEF_ACAPLEN ? 16 : 12;
if (idecommand(dev->sc_cur,
(xs->datalen < 0xffff) ? xs->datalen : 0xfffe, 0, 0, 0,
ATAPI_PACKET) != 0) {
printf("ide_atapi_start: send packet failed\n");
dev->sc_stat[0] = -1;
ide_scsidone(dev, dev->sc_stat[0]);
return(-1);
}
if (!(dev->sc_cur->sc_flags & IDEF_ACAPDRQ)) {
int i;
u_short *bf;
union {
struct scsipi_rw_big rw_big;
struct scsi_mode_sense_big md_big;
} cmd;
/* Wait for cmd i/o phase */
for (i = 20000; i > 0; --i) {
int phase;
phase = (regs->ide_ireason & (IDEI_CMD | IDEI_IN)) |
(regs->ide_status & IDES_DRQ);
if (phase == PHASE_CMDOUT)
break;
delay(10);
}
#ifdef DEBUG
if (ide_debug)
printf("atapi_start: wait for cmd i/o phase i = %d\n", i);
#endif
bf = (u_short *)xs->cmd;
switch (xs->cmd->opcode) {
case SCSI_READ_COMMAND:
case SCSI_WRITE_COMMAND:
bzero((char *)&cmd, sizeof(cmd.rw_big));
cmd.rw_big.opcode = xs->cmd->opcode | 0x20;
cmd.rw_big.addr[3] = xs->cmd->bytes[2];
cmd.rw_big.addr[2] = xs->cmd->bytes[1];
cmd.rw_big.addr[1] = xs->cmd->bytes[0] & 0x0f;
cmd.rw_big.length[1] = xs->cmd->bytes[3];
if (xs->cmd->bytes[3] == 0)
cmd.rw_big.length[0] = 1;
bf = (u_short *)&cmd.rw_big;
break;
case SCSI_MODE_SENSE:
case SCSI_MODE_SELECT:
bzero((char *)&cmd, sizeof(cmd.md_big));
cmd.md_big.opcode = xs->cmd->opcode |= 0x40;
cmd.md_big.byte2 = xs->cmd->bytes[0];
cmd.md_big.page = xs->cmd->bytes[1];
cmd.md_big.length[1] = xs->cmd->bytes[3];
bf = (u_short *)&cmd.md_big;
break;
}
for (i = 0; i < clen; i += 2)
regs->ide_data = *bf++;
}
return (0);
}
int
ide_atapi_icmd(dev, target, cbuf, clen, buf, len)
struct idec_softc *dev;
int target;
void *cbuf;
int clen;
void *buf;
int len;
{
struct ide_softc *ide = &dev->sc_ide[target];
struct scsipi_xfer *xs = dev->sc_xs;
ide_regmap_p regs = dev->sc_cregs;
int i;
u_short *bf;
clen = dev->sc_flags & IDEF_ACAPLEN ? 16 : 12;
ide->sc_buf = buf;
ide->sc_bcount = len;
if (wait_for_unbusy(dev) != 0) {
printf("ide_atapi_icmd: not ready, st = %02x\n",
regs->ide_status);
dev->sc_stat[0] = -1;
return (-1);
}
if (idecommand(ide, (len < 0xffff) ? len : 0xfffe, 0, 0, 0,
ATAPI_PACKET) != 0) {
printf("ide_atapi_icmd: send packet failed\n");
dev->sc_stat[0] = -1;
return(-1);
}
/* Wait for cmd i/o phase */
for (i = 20000; i > 0; --i) {
int phase;
phase = (regs->ide_ireason & (IDEI_CMD | IDEI_IN)) |
(regs->ide_status & IDES_DRQ);
if (phase == PHASE_CMDOUT)
break;
delay(10);
}
#ifdef DEBUG
if (ide_debug)
printf("atapi_icmd: wait for cmd i/o phase i = %d\n", i);
#endif
for (i = 0, bf = (u_short *)cbuf; i < clen; i += 2)
regs->ide_data = *bf++;
/* Wait for data i/o phase */
for (i = 20000; i > 0; --i) {
int phase;
phase = (regs->ide_ireason & (IDEI_CMD | IDEI_IN)) |
(regs->ide_status & IDES_DRQ);
if (phase != PHASE_CMDOUT)
break;
delay(10);
}
#ifdef DEBUG
if (ide_debug)
printf("atapi_icmd: wait for data i/o phase i = %d\n", i);
#endif
dev->sc_cur = ide;
while ((xs->flags & ITSDONE) == 0) {
ide_atapi_intr(dev);
for (i = 2000; i > 0; --i)
if ((regs->ide_status & IDES_DRQ) == 0)
break;
#ifdef DEBUG
if (ide_debug)
printf("atapi_icmd: intr i = %d\n", i);
#endif
}
return (1);
}
int
ide_atapi_intr(dev)
struct idec_softc *dev;
{
struct ide_softc *ide = dev->sc_cur;
struct scsipi_xfer *xs = dev->sc_xs;
ide_regmap_p regs = dev->sc_cregs;
u_short *bf;
int phase;
int len;
int status;
int err;
int ire;
int retries = 0;
union {
struct scsipi_rw_big rw_big;
struct scsi_mode_sense_big md_big;
} cmd;
if (wait_for_unbusy(dev) < 0) {
if ((regs->ide_status & IDES_ERR) == 0) {
printf("atapi_intr: controller busy\n");
return (0);
} else {
xs->error = XS_SHORTSENSE;
xs->sense.atapi_sense = regs->ide_error;
ide_atapi_done(dev);
return (0);
}
}
again:
len = regs->ide_cyl_lo + 256 * regs->ide_cyl_hi;
status = regs->ide_status;
err = regs->ide_error;
ire = regs->ide_ireason;
phase = (ire & (IDEI_CMD | IDEI_IN)) | (status & IDES_DRQ);
#ifdef DEBUG
if (ide_debug)
printf("ide_atapi_intr: len %d st %x err %x ire %x :",
len, status, err, ire);
#endif
switch(phase) {
case PHASE_CMDOUT:
#ifdef DEBUG
if (ide_debug)
printf("PHASE_CMDOUT\n");
#endif
len = ide->sc_flags & IDEF_ACAPLEN ? 16 : 12;
bf = (u_short *)xs->cmd;
switch (xs->cmd->opcode) {
case SCSI_READ_COMMAND:
case SCSI_WRITE_COMMAND:
bzero((char *)&cmd, sizeof(cmd.rw_big));
cmd.rw_big.opcode = xs->cmd->opcode | 0x20;
cmd.rw_big.addr[3] = xs->cmd->bytes[2];
cmd.rw_big.addr[2] = xs->cmd->bytes[1];
cmd.rw_big.addr[1] = xs->cmd->bytes[0] & 0x0f;
cmd.rw_big.length[1] = xs->cmd->bytes[3];
if (xs->cmd->bytes[3] == 0)
cmd.rw_big.length[0] = 1;
bf = (u_short *)&cmd.rw_big;
break;
case SCSI_MODE_SENSE:
case SCSI_MODE_SELECT:
bzero((char *)&cmd, sizeof(cmd.md_big));
cmd.md_big.opcode = xs->cmd->opcode |= 0x40;
cmd.md_big.byte2 = xs->cmd->bytes[0];
cmd.md_big.page = xs->cmd->bytes[1];
cmd.md_big.length[1] = xs->cmd->bytes[3];
bf = (u_short *)&cmd.md_big;
break;
}
#ifdef DEBUG
if (ide_debug > 1) {
int i;
for (i = 0; i < len; ++i)
printf("%s%02x ", i == 0 ? "cmd: " : " ",
*((u_char *)bf + i));
printf("\n");
}
#endif
while (len > 0) {
regs->ide_data = *bf++;
len -= 2;
}
return (1);
case PHASE_DATAOUT:
#ifdef DEBUG
if (ide_debug)
printf("PHASE_DATAOUT\n");
#endif
if (ide->sc_bcount < len) {
printf("ide_atapi_intr: write only %ld of %d bytes\n",
ide->sc_bcount, len);
len = ide->sc_bcount; /* XXXXXXXXXXXXX */
}
bf = (u_short *)ide->sc_buf;
ide->sc_buf += len;
ide->sc_bcount -= len;
while (len > 0) {
regs->ide_data = *bf++;
len -= 2;
}
return (1);
case PHASE_DATAIN:
#ifdef DEBUG
if (ide_debug)
printf("PHASE_DATAIN\n");
#endif
if (ide->sc_bcount < len) {
printf("ide_atapi_intr: read only %ld of %d bytes\n",
ide->sc_bcount, len);
len = ide->sc_bcount; /* XXXXXXXXXXXXX */
}
bf = (u_short *)ide->sc_buf;
ide->sc_buf += len;
ide->sc_bcount -= len;
while (len > DEV_BSIZE) {
R2; R2; R2; R2; R2; R2; R2; R2;
R2; R2; R2; R2; R2; R2; R2; R2;
len -= 16 * 2;
}
while (len > 0) {
*bf++ = regs->ide_data;
len -= 2;
}
return (1);
case PHASE_ABORTED:
case PHASE_COMPLETED:
#ifdef DEBUG
if (ide_debug)
printf("PHASE_COMPLETED\n");
#endif
if (ide->sc_flags & IDEF_SENSE) {
ide->sc_flags &= ~IDEF_SENSE;
if ((status & IDES_ERR) == 0)
xs->error = XS_SENSE;
} else if (status & IDES_ERR) {
struct scsipi_sense rqs;
#ifdef DEBUG_ATAPI
printf("ide_atapi_intr: error status %x err %x\n",
status, err);
#endif
xs->error = XS_SHORTSENSE;
xs->sense.atapi_sense = err;
ide->sc_flags |= IDEF_SENSE;
rqs.opcode = REQUEST_SENSE;
rqs.byte2 = xs->sc_link->scsipi_scsi.lun << 5;
rqs.length = sizeof(xs->sense.scsi_sense);
rqs.unused[0] = rqs.unused[1] = rqs.control = 0;
ide_atapi_icmd(dev, xs->sc_link->scsipi_scsi.target,
&rqs, sizeof(rqs), &xs->sense.scsi_sense,
sizeof(xs->sense.scsi_sense));
return(1);
}
#ifdef DEBUG_ATAPI
if (ide->sc_bcount != 0)
printf("ide_atapi_intr: %ld bytes remaining\n", ide->sc_bcount);
#endif
break;
default:
if (++retries < 500) {
delay(100);
goto again;
}
printf("ide_atapi_intr: unknown phase %x\n", phase);
if (status & IDES_ERR) {
xs->error = XS_SHORTSENSE;
xs->sense.atapi_sense = err;
} else
xs->error = XS_DRIVER_STUFFUP;
}
dev->sc_flags &= ~IDECF_ACTIVE;
ide_atapi_done(dev);
return (1);
}
void
ide_atapi_done(dev)
struct idec_softc *dev;
{
struct scsipi_xfer *xs = dev->sc_xs;
if (xs->error == XS_SHORTSENSE) {
int atapi_sense = xs->sense.atapi_sense;
bzero((char *)&xs->sense.scsi_sense, sizeof(xs->sense.scsi_sense));
xs->sense.scsi_sense.error_code = 0x70;
xs->sense.scsi_sense.flags = atapi_sense >> 4;
if (atapi_sense & 0x01)
xs->sense.scsi_sense.flags |= SSD_ILI;
if (atapi_sense & 0x02)
xs->sense.scsi_sense.flags |= SSD_EOM;
#if 0
if (atapi_sense & 0x04)
; /* command aborted */
#endif
ide_scsidone(dev, SCSI_CHECK);
return;
}
if (xs->error == XS_SENSE) {
ide_scsidone(dev, SCSI_CHECK);
return;
}
ide_scsidone(dev, 0); /* ??? */
}
| 26.12582 | 78 | 0.653733 | [
"model"
] |
04e144aa5bbca8434ffe550a41fe6546235a8753 | 41,673 | h | C | sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/pthread.h | openharmony-gitee-mirror/device_bearpi_bearpi_hm_nano | c463575de065aad080f730ffbd479628eb821105 | [
"BSD-3-Clause"
] | 1 | 2022-02-15T08:51:55.000Z | 2022-02-15T08:51:55.000Z | sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/pthread.h | openharmony-gitee-mirror/device_bearpi_bearpi_hm_nano | c463575de065aad080f730ffbd479628eb821105 | [
"BSD-3-Clause"
] | null | null | null | sdk_liteos/platform/os/Huawei_LiteOS/components/lib/libc/musl/include/pthread.h | openharmony-gitee-mirror/device_bearpi_bearpi_hm_nano | c463575de065aad080f730ffbd479628eb821105 | [
"BSD-3-Clause"
] | 1 | 2021-12-15T09:54:37.000Z | 2021-12-15T09:54:37.000Z | /**
* @defgroup posix POSIX
* @defgroup pthread Thread
* @ingroup posix
*/
#ifndef _PTHREAD_H
#define _PTHREAD_H
#ifdef __cplusplus
extern "C" {
#endif
#ifdef __LITEOS__
#include "bits/pthread_types.h"
#include "los_list.h"
#include "los_task_pri.h"
#endif
#include <features.h>
#ifdef __LITEOS__
typedef struct {
LOS_DL_LIST stMuxList; /**< Mutex blocking linked list*/
LosTaskCB* pstOwner; /**< Task that involves the mutex*/
UINT16 usMuxCount; /**< Mutex counter value*/
} MUX_CB_P;
#endif
#define __NEED_time_t
#define __NEED_clockid_t
#define __NEED_struct_timespec
#define __NEED_sigset_t
#define __NEED_pthread_t
#define __NEED_pthread_attr_t
#define __NEED_pthread_mutexattr_t
#define __NEED_pthread_condattr_t
#define __NEED_pthread_rwlockattr_t
#define __NEED_pthread_barrierattr_t
#define __NEED_pthread_mutex_t
#define __NEED_pthread_cond_t
#define __NEED_pthread_rwlock_t
#define __NEED_pthread_barrier_t
#define __NEED_pthread_spinlock_t
#define __NEED_pthread_key_t
#define __NEED_pthread_once_t
#define __NEED_size_t
#include <bits/alltypes.h>
#include <sched.h>
#include <time.h>
#ifdef __LITEOS__
typedef struct pthread_mutexattr {
UINT8 protocol; /**< Mutex protocol. The value range is [0, 2].*/
UINT8 prioceiling; /**< Upper priority limit of a mutex. The value range is [0, 31].*/
UINT8 type; /**< Mutex type. The value range is [0, 2].*/
UINT8 reserved; /**< Reserved.*/
} pthread_mutexattr_t;
typedef struct pthread_mutex {
pthread_mutexattr_t stAttr; /**< Mutex attributes object*/
MUX_CB_P stLock; /**< Mutex operation object*/
} pthread_mutex_t;
typedef struct {
clockid_t clock;
} pthread_condattr_t;
typedef struct pthread_cond {
volatile int count; /**< The number of tasks blocked by condition */
EVENT_CB_S event; /**< Event object*/
pthread_mutex_t* mutex; /**< Mutex locker for condition variable protection */
volatile int value; /**< Condition variable state value*/
} pthread_cond_t;
#endif
#define PTHREAD_CREATE_JOINABLE 0
#define PTHREAD_CREATE_DETACHED 1
#define PTHREAD_MUTEX_NORMAL 0
#define PTHREAD_MUTEX_DEFAULT 0
#define PTHREAD_MUTEX_RECURSIVE 1
#define PTHREAD_MUTEX_ERRORCHECK 2
#ifdef __LITEOS__
#define PTHREAD_MUTEX_RECURSIVE_NP 1
#define PTHREAD_MUTEX_ERRORCHECK_NP 2
#endif
#define PTHREAD_MUTEX_STALLED 0
#define PTHREAD_MUTEX_ROBUST 1
#define PTHREAD_PRIO_NONE 0
#define PTHREAD_PRIO_INHERIT 1
#define PTHREAD_PRIO_PROTECT 2
#define PTHREAD_INHERIT_SCHED 0
#define PTHREAD_EXPLICIT_SCHED 1
#define PTHREAD_SCOPE_SYSTEM 0
#define PTHREAD_SCOPE_PROCESS 1
/**
* @ingroup pthread
* Define a condition variable to be shared between threads within the same process.
*/
#define PTHREAD_PROCESS_PRIVATE 0
/**
* @ingroup pthread
* Define a condition variable to be shared among multiple processes.
*/
#define PTHREAD_PROCESS_SHARED 1
#ifdef __LITEOS__
#define PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP \
{ { PTHREAD_PRIO_INHERIT, OS_TASK_PRIORITY_LOWEST, PTHREAD_MUTEX_RECURSIVE_NP, 0 }, \
{ { (struct LOS_DL_LIST *)NULL, (struct LOS_DL_LIST *)NULL }, \
(LosTaskCB *)NULL, 0 } }
#define PTHREAD_MUTEX_INITIALIZER \
{ { PTHREAD_PRIO_INHERIT, OS_TASK_PRIORITY_LOWEST, 0, 0 }, \
{ { (struct LOS_DL_LIST *)NULL, (struct LOS_DL_LIST *)NULL }, \
(LosTaskCB *)NULL, 0 } }
#define PTHREAD_COND_INITIALIZER { -1, { 0, { NULL, NULL } }, NULL, -1 }
#endif
#define PTHREAD_RWLOCK_INITIALIZER {{{0}}}
#define PTHREAD_ONCE_INIT 0
#define PTHREAD_CANCEL_ENABLE 0
#define PTHREAD_CANCEL_DISABLE 1
#define PTHREAD_CANCEL_MASKED 2
#define PTHREAD_CANCEL_DEFERRED 0
#define PTHREAD_CANCEL_ASYNCHRONOUS 1
#define PTHREAD_CANCELED ((void *)-1)
#define PTHREAD_BARRIER_SERIAL_THREAD (-1)
int pthread_create(pthread_t *__restrict, const pthread_attr_t *__restrict, void *(*)(void *), void *__restrict);
/**
* @ingroup pthread
*
* @par Description:
* This API is used to mark a thread as detached. When a detached thread terminates, its resources are automatically released back to Huawei LiteOS without the need for another thread to join with the terminated thread.
*
* @param pthread [IN] ID of the thread to be marked as detached.
*
* @attention
* <ul>
* <li>None.</li>
* </ul>
*
* @retval #int If the call succeeds, pthread_detach() shall return 0; otherwise, an error number shall be returned to indicate the error.
*
* @retval #ESRCH The target thread cannot be marked (the thread does not exist or has exited).
* @retval #EINVAL The target thread is already marked as detached.
* @retval #ENOERR The thread is successfully marked.
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
* @see pthread_join
*/
int pthread_detach(pthread_t);
#ifndef __LITEOS__
_Noreturn void pthread_exit(void *);
#else
/**
* @ingroup pthread
*
* @par Description:
* This API is used to terminate the current thread, and the return value contains only one parameter.
*
* @param retval [OUT] Pointer to the thread return value.
*
* @attention
* <ul>
* <li>Thread termination does not release any application visible process resources, including, but not limited to,
* mutexes and file descriptors.</li>
* </ul>
*
* @retval #void None.
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
* @see pthread_create | pthread_join
*/
void pthread_exit(void *);
#endif
/* Wait for the thread to terminate. If thread_return is not NULL then
* the retval from the thread's call to pthread_exit() is stored at thread_return.
*/
/**
* @ingroup pthread
*
* @par Description:
* This API is used to wait for a thread to terminate and reclaim its resources.
*
* @param pthread [IN] ID of the target thread (the waited thread).
* @param thread_return [OUT] Return value sent to the waiting thread.
*
* @attention
* <ul>
* <li>A thread cannot be waited for by multiple threads. If a thread is waited for by multiple threads, ESRCH will be returned.</li>
* </ul>
*
* @retval #int If successful, the pthread_join() function shall return zero; otherwise, an error number shall be returned to indicate the error.
*
* @retval #ESRCH The target thread is not joinable (the thread does not exist, or has exited, or is waited for by another thread).
* @retval #EDEADLK A deadlock results because a thread is waiting for itself to terminate.
* @retval #EINVAL The target thread is not joinable.
* @retval #ENOERR The target thread is successfully joined with.
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
* @see pthread_detach
*/
int pthread_join(pthread_t, void **);
#ifdef __GNUC__
__attribute__((const))
#endif
/**
* @ingroup pthread
*
* @par Description:
* This API is used to acquire the thread identifier of the calling thread.
*
* @attention
* <ul>
* <li>None.</li>
* </ul>
*
* @retval pthread_t Thread ID [0,LOSCFG_BASE_CORE_TSK_LIMIT].
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
* @see None
*/
pthread_t pthread_self(void);
/* Compare two thread identifiers. */
/**
* @ingroup pthread
*
* @par Description:
* This API is used to compare whether two thread IDs belong to the same thread.
*
* @param thread1 [IN] ID of the thread 1 being compared.
* @param thread2 [IN] ID of the thread 2 being compared.
*
* @attention
* <ul>
* <li>Just compare the thread ID, not judge the validity of the thread ID.</li>
* </ul>
*
* @retval #int Any value other than 0 mean that two threads are equal.
* @retval #0 The two threads are unequal.
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
* @see None
*/
int pthread_equal(pthread_t, pthread_t);
#ifndef __cplusplus
#define pthread_equal(x,y) ((x)==(y))
#endif
int pthread_setcancelstate(int, int *);
int pthread_setcanceltype(int, int *);
void pthread_testcancel(void);
int pthread_cancel(pthread_t);
/* Get scheduling policy and parameters for the thread */
/**
* @ingroup pthread
*
* @par Description:
* This API is used to acquire the scheduling policy and priority of a thread.
*
* @param pthread [IN] ID of the thread whose scheduling policy is to be read.
* @param policy [OUT] Acquired scheduling policy.
* @param param [OUT] Acquired scheduling priority.
*
* @attention
* <ul>
* <li>None.</li>
* </ul>
*
* @retval #int If successful, the pthread_getschedparam() function shall return zero; otherwise, an error number shall be returned to indicate the error.
*
* @retval #EINVAL invalid parameter.
* @retval #ENOERR The scheduling policy and priority of the thread is successfully acquired.
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
* @see pthread_setschedparam
*/
int pthread_getschedparam(pthread_t, int *__restrict, struct sched_param *__restrict);
/* Set scheduling policy and parameters for the thread */
/**
* @ingroup pthread
*
* @par Description:
* This API is used to set the scheduling policy and priority of a thread.
*
* @param pthread [IN] ID of the thread whose scheduling policy is to be set.
* @param policy [IN] Specified scheduling policy.
* @param param [IN] Pointer to the scheduling priority.
*
* @attention
* <ul>
* <li>The scheduling policy must be SCHED_OTHER, SCHED_FIFO, or SCHED_RR.</li>
* <li>Only SCHED_RR is supported now. An error code will be returned if the value is set to the other two scheduling policies.</li>
* <li>The content priority specified by the param parameter must fall within the OS priority range[0,31].</li>
* <li>A smaller priority value indicates a higher priority.</li>
* </ul>
*
* @retval #int If successful, the pthread_setschedparam() function shall return zero; otherwise, an error number shall be returned to indicate the error.
*
* @retval #EINVAL invalid parameter.
* @retval #ENOERR The scheduling policy and priority of the thread is successfully set.
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
* @see pthread_getschedparam
*/
int pthread_setschedparam(pthread_t, int, const struct sched_param *);
int pthread_setschedprio(pthread_t, int);
/* Call init_routine just the once per control variable. */
/**
* @ingroup pthread
*
* @par Decription:
* This API is used to call the initialization routine at most once.
*
* @param once_control [IN/OUT] Once-control parameter.
* @param init_routine [IN] Initialization routine function.
*
* @attention
* <ul>
* <li>The control variable once_control must be statically initialized using PTHREAD_ONCE_INIT. Otherwise, this API will not work as expected.</li>
* </ul>
*
* @retval #int Upon successful completion, pthread_once() shall return zero; otherwise, an error number shall be returned to indicate the error.
* @retval #EINVAL One or more parameters are invalid.
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
* @see None
*/
int pthread_once(pthread_once_t *, void (*)(void));
int pthread_mutex_init(pthread_mutex_t *__restrict, const pthread_mutexattr_t *__restrict);
int pthread_mutex_lock(pthread_mutex_t *);
int pthread_mutex_unlock(pthread_mutex_t *);
int pthread_mutex_trylock(pthread_mutex_t *);
int pthread_mutex_timedlock(pthread_mutex_t *__restrict, const struct timespec *__restrict);
int pthread_mutex_destroy(pthread_mutex_t *);
int pthread_mutex_consistent(pthread_mutex_t *);
int pthread_mutex_getprioceiling(const pthread_mutex_t *__restrict, int *__restrict);
int pthread_mutex_setprioceiling(pthread_mutex_t *__restrict, int, int *__restrict);
/**
* @ingroup pthread
* @par Description:
* This API is used to initialize a condition variable.
*
* @param cond [OUT] Condition variable object.
* @param attr [IN] Condition variable attribute. The passed value and the default value of this parameter can be only set to PTHREAD_PROCESS_PRIVATE.
*
* @attention
* <ul>
* <li>A condition variable cannot be initialized by multiple threads. When a condition variable needs to be reinitialized, it must not have been used.</li>
* </ul>
*
* @retval #EINVAL One or more parameters are invalid.
* @retval #ENOERR The condition variable is successfully initialized.
* @retval #ENOMEM Failed to allocate in-memory resources for the operation.
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
*
* @see pthread_cond_destroy
*
*/
int pthread_cond_init(pthread_cond_t *__restrict, const pthread_condattr_t *__restrict);
/**
* @ingroup pthread
* @par Description:
* This API is used to destroy a condition variable.
*
* @param cond [IN] Condition variable object.
*
* @attention
* <ul>
* <li>The condition variable is using memory and not destroyed.</li>
* </ul>
*
* @retval #ENVAIL The parameter is invalid.
* @retval #EBUSY The condition variable is being in use.
* @retval #ENOERR The condition variable is successfully destroyed.
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
*
* @see pthread_cond_init
*
*/
int pthread_cond_destroy(pthread_cond_t *);
/**
* @ingroup pthread
* @par Description:
* A thread has been being blocked on a condition variable and waits to be awoken by the condition variable.
*
* @param cond [IN] Condition variable object.
* @param mutex [IN] Mutex object.
* @attention
* <ul>
* <li>None.</li>
* </ul>
*
* @retval #ENVAIL One or more parameters are invalid.
* @retval #ENOERR The thread is successfully awoken.
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
*
* @see pthread_cond_signal | pthread_cond_broadcast
*
*/
int pthread_cond_wait(pthread_cond_t *__restrict, pthread_mutex_t *__restrict);
/**
* @ingroup pthread
* @par Description:
* A thread has been being blocked on a condition variable and is awoken until the set relative time has passed or the thread obtains a condition variable.
*
* @param cond [IN] Condition variable object.
* @param mutex [IN] Mutex object.
* @param abstime [IN] Time object.
*
* @attention
* <ul>
* <li>The waiting time is a relative time.</li>
* <li> Setting the timeout interval to a past time period is not supported.</li>
* </ul>
*
* @retval #ENOERR The thread receives a signal and is successfully awoken.
* @retval #ENVAIL One or more parameters are invalid.
* @retval #ETIMEDOUT The waiting time has passed.
* @retval #ENOMEM Failed to allocate in-memory resources for the operation.
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
*
* @see pthread_cond_wait
*
*/
int pthread_cond_timedwait(pthread_cond_t *__restrict, pthread_mutex_t *__restrict, const struct timespec *__restrict);
/**
* @ingroup pthread
* @par Description:
* This API is used to unblock all threads blocked on a condition variable and wake all these threads.
*
* @param cond [IN] Condition variable object.
*
* @attention
* <ul>
* <li>None.</li>
* </ul>
*
* @retval #ENVAIL The parameter is invalid.
* @retval #ENOERR All threads blocked on this condition variable are successfully unblocked.
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
*
* @see pthread_cond_wait
*
*/
int pthread_cond_broadcast(pthread_cond_t *);
/**
* @ingroup pthread
* @par Description:
* This API is used to unblock a thread blocked on a condition variable and wakes this thread.
*
* @param cond [IN] Condition variable object.
*
* @attention
* <ul>
* <li>None.</li>
* </ul>
*
* @retval #ENVAIL The parameter is invalid.
* @retval #ENOERR The thread is successfully unlocked.
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
*
* @see pthread_cond_wait
*
*/
int pthread_cond_signal(pthread_cond_t *);
int pthread_rwlock_init(pthread_rwlock_t *__restrict, const pthread_rwlockattr_t *__restrict);
int pthread_rwlock_destroy(pthread_rwlock_t *);
int pthread_rwlock_rdlock(pthread_rwlock_t *);
int pthread_rwlock_tryrdlock(pthread_rwlock_t *);
int pthread_rwlock_timedrdlock(pthread_rwlock_t *__restrict, const struct timespec *__restrict);
int pthread_rwlock_wrlock(pthread_rwlock_t *);
int pthread_rwlock_trywrlock(pthread_rwlock_t *);
int pthread_rwlock_timedwrlock(pthread_rwlock_t *__restrict, const struct timespec *__restrict);
int pthread_rwlock_unlock(pthread_rwlock_t *);
int pthread_spin_init(pthread_spinlock_t *, int);
int pthread_spin_destroy(pthread_spinlock_t *);
int pthread_spin_lock(pthread_spinlock_t *);
int pthread_spin_trylock(pthread_spinlock_t *);
int pthread_spin_unlock(pthread_spinlock_t *);
int pthread_barrier_init(pthread_barrier_t *__restrict, const pthread_barrierattr_t *__restrict, unsigned);
int pthread_barrier_destroy(pthread_barrier_t *);
int pthread_barrier_wait(pthread_barrier_t *);
int pthread_key_create(pthread_key_t *, void (*)(void *));
int pthread_key_delete(pthread_key_t);
void *pthread_getspecific(pthread_key_t);
int pthread_setspecific(pthread_key_t, const void *);
/* Thread attribute handling. */
/**
* @ingroup pthread
*
* @par Description:
* This API is used to initialize a thread attributes object into default attributes.
*
* @param attr [IN] Pointer to the thread attributes object to be initialized.
*
* @attention
* <ul>
* <li>Default thread attributes</li>
* <li>detachstate = PTHREAD_CREATE_JOINABLE</li>
* <li>schedpolicy = SCHED_RR</li>
* <li>schedparam.sched_priority = LOSCFG_BASE_CORE_TSK_DEFAULT_PRIO</li>
* <li>inheritsched = PTHREAD_INHERIT_SCHED</li>
* <li>scope = PTHREAD_SCOPE_SYSTEM</li>
* <li>stackaddr_set = 0</li>
* <li>stackaddr = NULL</li>
* <li>stacksize_set = 1</li>
* <li>stacksize = LOSCFG_BASE_CORE_TSK_DEFAULT_STACK_SIZE</li>
* </ul>
*
* @retval #int Upon successful completion, pthread_attr_init() shall return a value of 0; otherwise, an error number shall be returned to indicate the error.
*
* @retval #EINVAL The input parameter is NULL.
* @retval #ENOERR The thread attributes object is successfully initialized.
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
* @see pthread_attr_destroy
*/
int pthread_attr_init(pthread_attr_t *);
/* Destroy thread attributes object */
/**
* @ingroup pthread
*
* @par Dependency:
* This API is used to destroy a thread attributes object.
*
* @param attr [IN] Pointer to the thread attributes object to be destroyed.
*
* @attention
* <ul>
* <li>This API does not take effect on Huawei LiteOS. In fact, nothing has been done in this API.</li>
* </ul>
*
* @retval #int Upon successful completion, pthread_attr_destroy() shall return a value of 0; otherwise, an error number shall be returned to indicate the error.
*
* @retval #EINVAL The input parameter is NULL.
* @retval #ENOERR The thread attributes object is successfully destroyed.
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
* @see pthread_attr_init
*/
int pthread_attr_destroy(pthread_attr_t *);
int pthread_attr_getguardsize(const pthread_attr_t *__restrict, size_t *__restrict);
int pthread_attr_setguardsize(pthread_attr_t *, size_t);
/* Get current minimal stack size. */
/**
* @ingroup pthread
*
* @par Description:
* This API is used to acquire the stack size attribute of a thread attribute object.
*
* @param attr [IN] Pointer to the thread attributes object to be read.
* @param stacksize [OUT] Pointer to the acquired stack size.
*
* @attention
* <ul>
* <li>None.</li>
* </ul>
*
* @retval #int Upon successful completion, pthread_attr_getstacksize() shall return a value of 0; otherwise, an error number shall be returned to indicate the error.
* The pthread_attr_getstacksize() function stores the stacksize attribute value in stacksize if successful.
*
* @retval #EINVAL invalid parameter, or the stack size left unspecified.
* @retval #ENOERR The stack size attribute is successfully acquired.
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
* @see pthread_attr_setstacksize
*/
int pthread_attr_getstacksize(const pthread_attr_t *__restrict, size_t *__restrict);
/* Set minimum creation stack size. */
/**
* @ingroup pthread
*
* @par Description:
* This API is used to set the stack size attribute of a thread attribute object.
*
* @param attr [OUT] Pointer to the thread attributes object to be set.
* @param stacksize [IN] Specified stack size.
*
* @attention
* <ul>
* <li>The stack size must fall within an appropriate range and be greater than PTHREAD_STACK_MIN.
* If the stack size attribute is left unspecified, the default stack size will be used.</li>
* </ul>
*
* @retval #int Upon successful completion, pthread_attr_setstacksize() shall return a value of 0; otherwise, an error number shall be returned to indicate the error.
*
* @retval #EINVAL invalid parameter.
* @retval #ENOERR The stack size attribute is successfully set.
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
* @see pthread_attr_getstacksize
*/
int pthread_attr_setstacksize(pthread_attr_t *, size_t);
/* Get the detachstate attribute */
/**
* @ingroup pthread
*
* @par Description:
* This API is used to acquire the detach state attribute of a thread attributes object.
*
* @param attr [IN] Pointer to the thread attributes object to be read.
* @param detachstate [OUT] Pointer to the acquired detach state attribute.
*
* @attention
* <ul>
* <li>Detachstate shall be set to either PTHREAD_CREATE_DETACHED or PTHREAD_CREATE_JOINABLE.</li>
* </ul>
*
* @retval int Upon successful completion, pthread_attr_getdetachstate() shall return a value of 0; otherwise, an error number shall be returned to indicate the error.
* The pthread_attr_getdetachstate() function stores the value of the detachstate attribute in detachstate if successful.
*
* @retval #EINVAL invalid parameter.
* @retval #ENOERR The detach state attribute is successfully acquired.
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
* @see pthread_attr_setdetachstate
*/
int pthread_attr_getdetachstate(const pthread_attr_t *, int *);
/* Set the detachstate attribute */
/**
* @ingroup pthread
*
* @par Description:
* This API is used to set the detach state attribute of a thread attributes object.
*
* @param attr [OUT] Pointer to the thread attributes object to be set.
* @param detachstate [IN] Detach state attribute.
*
* @attention
* <ul>
* <li>The detach state attribute must be either PTHREAD_CREATE_JOINABLE or PTHREAD_CREATE_DETACHED. Otherwise, the attempt to set the detach state attribute will fail.</li>
* </ul>
*
* @retval #int Upon successful completion, pthread_attr_setdetachstate() shall return a value of 0; otherwise, an error number shall be returned to indicate the error.
*
* @retval #EINVAL invalid parameter.
* @retval #ENOERR The detach state attribute is successfully set.
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
* @see pthread_attr_getdetachstate
*/
int pthread_attr_setdetachstate(pthread_attr_t *, int);
int pthread_attr_getstack(const pthread_attr_t *__restrict, void **__restrict, size_t *__restrict);
int pthread_attr_setstack(pthread_attr_t *, void *, size_t);
#ifdef __LITEOS__
/* Set starting address of stack. Whether this is at the start or end of
* the memory block allocated for the stack depends on whether the stack
* grows up or down.
*/
/**
* @ingroup pthread
*
* @par Description:
* This API is used to set the stack address attribute of a thread attributes object. This attribute specifies the start address of a stack.
*
* @param attr [OUT] Pointer to the thread attributes object to be set.
* @param stackaddr [IN] Specified stack address.
*
* @attention
* <ul>
* <li>This API does not take effect on Huawei LiteOS Kernel.</li>
* </ul>
*
* @retval #int Upon successful completion, pthread_attr_setstackaddr() shall return a value of 0; otherwise, an error number shall be returned to indicate the error.
*
* @retval #EINVAL invalid parameter.
* @retval #ENOERR The stack address attribute is successfully set.
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
* @see pthread_attr_getstackaddr
*/
int pthread_attr_setstackaddr(pthread_attr_t *, void *);
/* Get any previously set stack address. */
/**
* @ingroup pthread
*
* @par Description:
* This API is used to acquire the stack address attribute of a thread attributes object. This attribute specifies the starting address of a stack.
*
* @param attr [IN] Pointer to the thread attributes object to be read.
* @param stackaddr [OUT] Pointer to the acquired starting address of stack.
*
* @attention
* <ul>
* <li>This API does not take effect on Huawei LiteOS Kernel.</li>
* </ul>
*
* @retval #int Upon successful completion, pthread_attr_getstackaddr() shall return a value of 0; otherwise, an error number shall be returned to indicate the error.
*
* @retval #EINVAL invalid parameter.
* @retval #ENOERR The stack address attribute is successfully acquired.
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
* @see pthread_attr_setstackaddr
*/
int pthread_attr_getstackaddr(const pthread_attr_t *, void **);
#endif
/* Get scheduling contention scope */
/**
* @ingroup pthread
*
* @par Description:
* This API is used to acquire the contention scope attribute of a thread attributes object.
*
* @param attr [IN] Pointer to the thread attributes object to be read.
* @param scope [OUT] Pointer to the acquired contention scope attribute.
*
* @attention
* <ul>
* <li>None.</li>
* </ul>
*
* @retval #int If successful, the pthread_attr_getscope() function shall return zero; otherwise, an error number shall be returned to indicate the error.
*
* @retval #EINVAL invalid parameter.
* @retval #ENOERR The contention scope attribute is successfully acquired.
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
* @see pthread_attr_setscope
*/
int pthread_attr_getscope(const pthread_attr_t *__restrict, int *__restrict);
/* Set scheduling contention scope */
/**
* @ingroup pthread
*
* @par Description:
* This API is used to set the contention scope attribute of a thread attributes object.
*
* @param attr [OUT] Pointer to the thread attributes object to be set.
* @param scope [IN] Contention scope attribute.
*
* @attention
* <ul>
* <li>The contention scope attribute can only be PTHREAD_SCOPE_SYSTEM. PTHREAD_SCOPE_PROCES is not supported.</li>
* </ul>
*
* @retval #int If successful, the pthread_attr_setscope() function shall return zero; otherwise, an error number shall be returned to indicate the error.
*
* @retval #EINVAL invalid parameter.
* @retval #ENOTSUP The specified contention scope attribute value is not supported.
* @retval #ENOERR The contention scope attribute is successfully set.
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
* @see pthread_attr_getscope
*/
int pthread_attr_setscope(pthread_attr_t *, int);
/* Get scheduling policy */
/**
* @ingroup pthread
*
* @par Description:
* This API is used to acquire the scheduling policy attribute of a thread attributes object.
*
* @param attr [IN] Pointer to the thread attributes object to be read.
* @param policy [OUT] Pointer to the acquired scheduling policy attribute.
*
* @attention
* <ul>
* <li>None.</li>
* </ul>
*
* @retval #int If successful, the pthread_attr_getschedpolicy() function shall return zero; otherwise, an error number shall be returned to indicate the error.
*
* @retval #EINVAL invalid parameter.
* @retval #ENOERR The scheduling policy attribute is successfully obtained.
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
* @see pthread_attr_setschedpolicy
*/
int pthread_attr_getschedpolicy(const pthread_attr_t *__restrict, int *__restrict);
/* Set scheduling policy */
/**
* @ingroup pthread
*
* @par Description:
* This API is used to set the scheduling policy attribute of a thread attributes object.
*
* @param attr [OUT] Pointer to the thread attributes object to be set.
* @param policy [IN] Scheduling policy attribute.
*
* @attention
* <ul>
* <li>The scheduling policy attribute is SCHED_OTHER, SCHED_FIFO, or SCHED_RR.</li>
* <li>Only SCHED_RR is supported now. An error code will be returned if the value is set to the other two scheduling policies.</li>
* </ul>
*
* @retval #int If successful, the pthread_attr_setschedpolicy() function shall return zero; otherwise, an error number shall be returned to indicate the error.
*
* @retval #EINVAL invalid parameter.
* @retval #ENOERR The scheduling policy attribute is successfully set.
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
* @see pthread_attr_getschedpolicy
*/
int pthread_attr_setschedpolicy(pthread_attr_t *, int);
/* Get scheduling parameters */
/**
* @ingroup pthread
*
* @par Description:
* This API is used to acquire the scheduling parameter attributes of a thread attributes object. The scheduling parameter attributes indicate the thread priorities.
*
* @param attr [IN] Pointer to the thread attributes object to be read.
* @param param [OUT] Pointer to the acquired scheduling parameter attributes object.
*
* @attention
* <ul>
* <li>None.</li>
* </ul>
*
* @retval #int If successful, the pthread_attr_getschedparam() function shall return zero; otherwise, an error number shall be returned to indicate the error.
*
* @retval #EINVAL invalid parameter.
* @retval #ENOERR The scheduling parameter attributes are successfully acquired.
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
* @see pthread_attr_setschedparam
*/
int pthread_attr_getschedparam(const pthread_attr_t *__restrict, struct sched_param *__restrict);
/* Set scheduling parameters */
/**
* @ingroup pthread
*
* @par Description:
* This API is used to set the scheduling parameter attributes of a thread attributes object. The scheduling parameter attributes indicate thread priorities.
*
* @param attr [OUT] Pointer to the thread attributes object to be set.
* @param param [IN] Pointer to the scheduling parameter attributes object.
*
*@attention
* <ul>
* <li>The priority of the scheduling parameter attributes must be in the range of [0, 31].</li>
* </ul>
*
* @retval #int If successful, the pthread_attr_setschedparam() function shall return zero; otherwise, an error number shall be returned to indicate the error.
*
* @retval #EINVAL invalid parameter.
* @retval #ENOTSUP made to set the attribute to an unsupported value.
* @retval #ENOERR The scheduling parameter attributes are successfully set.
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
* @see pthread_attr_getschedparam
*/
int pthread_attr_setschedparam(pthread_attr_t *__restrict, const struct sched_param *__restrict);
/* Get scheduling inheritance attribute */
/**
* @ingroup pthread
*
* @par Description:
* This API is used to acquire the inherit scheduler attribute of a thread attributes object.
*
* @param attr [IN] Pointer to the thread attributes object to be read.
* @param inherit [OUT] Pointer to the acquired inherit scheduler attribute.
*
* @attention
* <ul>
* <li>None.</li>
* </ul>
*
* @retval #int If successful, the pthread_attr_getinheritsched() function shall return zero; otherwise, an error number shall be returned to indicate the error.
*
* @retval #EINVAL invalid parameter.
* @retval #ENOERR The inherit scheduler attribute is successfully acquired.
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
* @see pthread_attr_setinheritsched
*/
int pthread_attr_getinheritsched(const pthread_attr_t *__restrict, int *__restrict);
/* Set scheduling inheritance attribute */
/**
* @ingroup pthread
*
* @par Description:
* This API is used to set the inherit scheduler attribute of a thread attributes object.
*
* @param attr [OUT] Pointer to the thread attributes object to be set.
* @param inherit [IN] Inherit scheduler attribute.
*
* @attention
* <ul>
* <li>The inherit scheduler attribute must be either PTHREAD_INHERIT_SCHED or PTHREAD_EXPLICIT_SCHED.</li>
* </ul>
*
* @retval #int If successful, the pthread_attr_setinheritsched() function shall return zero; otherwise, an error number shall be returned to indicate the error.
* @retval #EINVAL invalid parameter.
* @retval #ENOERR The inherit scheduler attribute is successfully set.
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
* @see pthread_attr_getinheritsched
*/
int pthread_attr_setinheritsched(pthread_attr_t *, int);
int pthread_mutexattr_destroy(pthread_mutexattr_t *);
int pthread_mutexattr_getprioceiling(const pthread_mutexattr_t *__restrict, int *__restrict);
int pthread_mutexattr_getprotocol(const pthread_mutexattr_t *__restrict, int *__restrict);
int pthread_mutexattr_getpshared(const pthread_mutexattr_t *__restrict, int *__restrict);
int pthread_mutexattr_getrobust(const pthread_mutexattr_t *__restrict, int *__restrict);
int pthread_mutexattr_gettype(const pthread_mutexattr_t *__restrict, int *__restrict);
int pthread_mutexattr_init(pthread_mutexattr_t *);
int pthread_mutexattr_setprioceiling(pthread_mutexattr_t *, int);
int pthread_mutexattr_setprotocol(pthread_mutexattr_t *, int);
int pthread_mutexattr_setpshared(pthread_mutexattr_t *, int);
int pthread_mutexattr_setrobust(pthread_mutexattr_t *, int);
int pthread_mutexattr_settype(pthread_mutexattr_t *, int);
/**
* @ingroup pthread
* @par Description:
* This API is used to initialize the condition variable attribute.
* This API does not task effect on Huawei LiteOS Kernel.
*
* @param attr [OUT] Condition variable attribute.
*
* @attention
* <ul>
* <li>The condition variable attribute can be only set to PTHREAD_PROCESS_PRIVATE.</li>
* </ul>
*
* @retval #ENVAIL The parameter is invalid.
* @retval #ENOERR The condition variable attribute is successfully initialized.
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
*
* @see pthread_condattr_setpshared | pthread_condattr_getpshared
*
*/
int pthread_condattr_init(pthread_condattr_t *);
/**
* @ingroup pthread
* @par Description:
* This API is used to destroy the condition variable attribute.
*
* @param attr [IN] Condition variable attribute.
*
* @attention
* <ul>
* <li>The condition variable attribute can be only set to PTHREAD_PROCESS_PRIVATE.</li>
* <li>This API does not task effect on Huawei LiteOS Kernel.</li>
* </ul>
*
* @retval #ENVAIL The parameter is invalid.
* @retval #ENOERR The condition variable attribute is successfully destroied.
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
*
* @see pthread_condattr_init
*
*/
int pthread_condattr_destroy(pthread_condattr_t *);
int pthread_condattr_setclock(pthread_condattr_t *, clockid_t);
/**
* @ingroup pthread
* @par Description:
* This API is used to set the condition variable attribute.
*
* @param attr [IN] Condition variable attribute.
* @param pshared [OUT] Condition variable attribute, which is always PTHREAD_PROCESS_PRIVATE.
*
* @attention
* <ul>
* <li>The condition variable attribute can be only set to PTHREAD_PROCESS_PRIVATE.</li>
* <li>This API does not task effect on Huawei LiteOS Kernel.</li>
* </ul>
*
* @retval #ENVAIL One or more parameters are invalid.
* @retval #ENOERR The condition variable attribute is successfully set.
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
*
* @see pthread_condattr_getpshared
*
*/
int pthread_condattr_setpshared(pthread_condattr_t *, int);
int pthread_condattr_getclock(const pthread_condattr_t *__restrict, clockid_t *__restrict);
/**
* @ingroup pthread
* @par Description:
* This API is used to obtain the condition variable attribute.
*
* @param attr [IN] Condition variable attribute.
* @param pshared [OUT] Obtained condition variable attribute, which is always PTHREAD_PROCESS_PRIVATE.
*
* @attention
* <ul>
* <li>The condition variable attribute can be only set to PTHREAD_PROCESS_PRIVATE.</li>
* <li>This API does not task effect on Huawei LiteOS Kernel.</li>
* </ul>
*
* @retval #ENVAIL One or more parameters are invalid.
* @retval #ENOERR The condition variable attribute is successfully obtained.
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
*
* @see pthread_condattr_setpshared
*
*/
int pthread_condattr_getpshared(const pthread_condattr_t *__restrict, int *__restrict);
int pthread_rwlockattr_init(pthread_rwlockattr_t *);
int pthread_rwlockattr_destroy(pthread_rwlockattr_t *);
int pthread_rwlockattr_setpshared(pthread_rwlockattr_t *, int);
int pthread_rwlockattr_getpshared(const pthread_rwlockattr_t *__restrict, int *__restrict);
int pthread_barrierattr_destroy(pthread_barrierattr_t *);
int pthread_barrierattr_getpshared(const pthread_barrierattr_t *__restrict, int *__restrict);
int pthread_barrierattr_init(pthread_barrierattr_t *);
int pthread_barrierattr_setpshared(pthread_barrierattr_t *, int);
/**
* @ingroup pthread
* @par Description:
* The function is not supported.
*
* @attention
* <ul>
* <li>The function is not supported.</li>
* </ul>
*
* @retval #int zero.
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
*
* @see None
*
*/
int pthread_atfork(void (*)(void), void (*)(void), void (*)(void));
int pthread_getconcurrency(void);
int pthread_setconcurrency(int);
int pthread_getcpuclockid(pthread_t, clockid_t *);
#ifndef __LITEOS__
struct __ptcb {
void (*__f)(void *);
void *__x;
struct __ptcb *__next;
};
void _pthread_cleanup_push(struct __ptcb *, void (*)(void *), void *);
void _pthread_cleanup_pop(struct __ptcb *, int);
#endif
struct pthread_cleanup_buffer {
void (*routine)(void *);
void *arg;
struct pthread_cleanup_buffer *next;
};
#define pthread_cleanup_push(routine, arg) do { struct pthread_cleanup_buffer cb; pthread_cleanup_push_inner(&cb, routine, arg);
#define pthread_cleanup_pop(arg) pthread_cleanup_pop_inner(&cb, (arg)); } while(0)
#ifdef _GNU_SOURCE
struct cpu_set_t;
/**
* @ingroup pthread
*
* @par Description:
* This API is used to get the cpu affinity mask from the thread.
*
* @param pthread [IN] ID of the thread whose affinity mask is to be read.
* @param cpusetsize [IN] Size of cpuset in bytes.
* @param cpuset [OUT] Pointer to the cpu affinity mask.
*
* @attention
* <ul>
* <li>None.</li>
* </ul>
*
* @retval #EINVAL Invalid parameter.
* @retval #ENOERR The cpu affinity mask of the thread is successfully acquired.
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
*
* @see pthread_setaffinity_np
*
*/
int pthread_getaffinity_np(pthread_t, size_t, struct cpu_set_t *);
/**
* @ingroup pthread
*
* @par Description:
* This API is used to set the cpu affinity mask for the thread.
*
* @param pthread [IN] ID of the thread whose affinity mask is to be set.
* @param cpusetsize [IN] Size of cpuset in bytes.
* @param cpuset [IN] Pointer to the cpu affinity mask.
*
* @attention
* <ul>
* <li>The cpu affinity mask attributes must be in the range of [1, LOSCFG_KERNEL_CPU_MASK].</li>
* </ul>
*
* @retval #EINVAL Invalid parameter.
* @retval #ENOERR The cpu affinity mask of the thread is successfully set.
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
*
* @see pthread_getaffinity_np
*
*/
int pthread_setaffinity_np(pthread_t, size_t, const struct cpu_set_t *);
#ifdef __LITEOS__
/**
* @ingroup pthread
*
* @par Description:
* This API is used to set the cpu affinity mask attributes of a thread attributes object.
*
* @param attr [OUT] Pointer to the thread attributes object to be set.
* @param cpusetsize [IN] Size of cpuset in bytes.
* @param cpuset [IN] Pointer to the cpu affinity mask.
*
* @attention
* <ul>
* <li>The cpu affinity mask attributes must be in the range of [1, LOSCFG_KERNEL_CPU_MASK].</li>
* </ul>
*
* @retval #EINVAL Invalid parameter.
* @retval #ENOERR The cpu affinity mask attributes are successfully set.
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
*
* @see pthread_attr_getaffinity_np
*
*/
int pthread_attr_setaffinity_np(pthread_attr_t *attr, size_t cpusetsize, const cpu_set_t *cpuset);
/**
* @ingroup pthread
*
* @par Description:
* This API is used to get the cpu affinity mask attributes of a thread attributes object.
*
* @param attr [IN] Pointer to the thread attributes object to be read.
* @param cpusetsize [IN] Size of cpuset in bytes.
* @param cpuset [OUT] Pointer to the cpu affinity mask.
*
* @attention
* <ul>
* <li>None.</li>
* </ul>
*
* @retval #EINVAL Invalid parameter.
* @retval #ENOERR The cpu affinity mask attributes are successfully acquired.
*
* @par Dependency:
* <ul><li>pthread.h</li></ul>
*
* @see pthread_attr_setaffinity_np
*
*/
int pthread_attr_getaffinity_np(const pthread_attr_t *attr, size_t cpusetsize, cpu_set_t *cpuset);
#endif
int pthread_getattr_np(pthread_t, pthread_attr_t *);
int pthread_setname_np(pthread_t, const char *);
int pthread_getattr_default_np(pthread_attr_t *);
int pthread_setattr_default_np(const pthread_attr_t *);
int pthread_tryjoin_np(pthread_t, void **);
int pthread_timedjoin_np(pthread_t, void **, const struct timespec *);
#endif
#if _REDIR_TIME64
__REDIR(pthread_mutex_timedlock, __pthread_mutex_timedlock_time64);
__REDIR(pthread_cond_timedwait, __pthread_cond_timedwait_time64);
__REDIR(pthread_rwlock_timedrdlock, __pthread_rwlock_timedrdlock_time64);
__REDIR(pthread_rwlock_timedwrlock, __pthread_rwlock_timedwrlock_time64);
#ifdef _GNU_SOURCE
__REDIR(pthread_timedjoin_np, __pthread_timedjoin_np_time64);
#endif
#endif
#ifdef __cplusplus
}
#endif
#endif
| 32.50624 | 219 | 0.724354 | [
"object"
] |
04e383dc2c03d52ebab55afd150e6ae3b8ded0d3 | 614 | h | C | MarioBaseProject/CharacterKoopa.h | kyleweir/mario | d645734fe33507225e1e2bf55c13af7b0e0c62ac | [
"MIT"
] | 1 | 2020-10-16T00:15:28.000Z | 2020-10-16T00:15:28.000Z | MarioBaseProject/CharacterKoopa.h | kyle-robinson/mario | d645734fe33507225e1e2bf55c13af7b0e0c62ac | [
"MIT"
] | null | null | null | MarioBaseProject/CharacterKoopa.h | kyle-robinson/mario | d645734fe33507225e1e2bf55c13af7b0e0c62ac | [
"MIT"
] | null | null | null | #pragma once
#include "Character.h"
class CharacterKoopa : public Character
{
public:
CharacterKoopa(SDL_Renderer* renderer, string imagePath, LevelMap* map, Vector2D startPosition, FACING startFacing);
~CharacterKoopa();
void Render();
void Update(float deltaTime, SDL_Event e);
void TakeDamage();
void Jump();
bool GetInjured() { return mInjured; }
private:
float mSingleSpriteWidth;
float mSingleSpriteHeight;
bool mInjured;
float mInjuredTime;
float mFrameDelay;
int mCurrentFrame;
void AnimateKoopa(float deltaTime, SDL_Event e);
void FlipRightWayUp();
}; | 19.806452 | 118 | 0.726384 | [
"render"
] |
04e7ad42cd1dc46dabeec5b2c692fa4936c0b4bc | 3,053 | h | C | src/header/command.h | Program0/rshell | 54f661dbc04309f9018991b3a9f1d29a744e5319 | [
"BSD-3-Clause"
] | null | null | null | src/header/command.h | Program0/rshell | 54f661dbc04309f9018991b3a9f1d29a744e5319 | [
"BSD-3-Clause"
] | null | null | null | src/header/command.h | Program0/rshell | 54f661dbc04309f9018991b3a9f1d29a744e5319 | [
"BSD-3-Clause"
] | null | null | null | //Marlo Zeroth mzero001@ucr.edu 861309346
//Emmilio Segovia esego001@ucr.edu 861305177
#ifndef COMMAND_H
#define COMMAND_H
// System libraries
#include <stdexcept>
#include <iostream> // For printing to the command line
#include <cstring> // For dealing with c-strings
#include <iostream> // For printing to command line
#include <cstdlib> // Basic c functions
#include <stdlib.h> // For MACRO use
#include <cstddef> // For NULL
#include <unistd.h> // For calling fork() and running commands as child
#include <sys/types.h> // For making a process wait until child finishes
#include <sys/wait.h> // For waitpid function
#include <stdio.h> // For using perror() and catching errors if sys call failed
#include <errno.h> // For outputting error after system call
#include <fcntl.h> // For testing a pipe between child and parent process
#include <sysexits.h> // For testing exit status of process
#include <sys/stat.h> // For the stat function used in test commands
#include <sys/param.h>//for accessing environment variables
#include <time.h>
#include <limits.h> // For the realpath() function and PATHMAX macro
#include <dirent.h> // For getting a directory stream
// User libraries
#include "base.h"
// Stores commands in null terminated array. The command to execute is
// stored at index 0 and the parameters are stored subsequent elements
// of the array.
class Command : public Base {
private:
/* Member variables */
// Stores command file at index 0, flags at index 1,
// and parameters are stored in subsequent indeces.
char ** cmd; // Null terminated array.
pid_t pid; // Process ID of the command.
int exit_status; // Stores the errno of the command after execution.
// Stores the size of the Null terminated array,
// not include the NULL.
unsigned int size;
/* Utility functions */
// Functions that execute built in commands. Note, this will
// grow as we add built-in commands.
int exit_command();
int test_command();
int system_call();
int cd_command();
public:
// Main constructor
Command(std::vector<std::string> input);
// Destructor
virtual ~Command();
// Overridden functions.
/* For use in a command tree */
// Returns NULL.
virtual Base * get_left();
virtual Base * get_right();
// Does nothing.
virtual void set_left(Base * left);
virtual void set_right(Base * right);
// Always returns true. Commands are leafs in a command tree.
virtual bool isLeaf();
/* Accessor functions */
// Prints the command and parameters.
virtual void print();
// Returns a string of the command and parameters.
virtual std::string to_string();
// Returns a vector with the command and parameters.
virtual std::vector<std::string> to_vector();
// Overrides Base execute function.
virtual int execute();
};
#endif //COMMAND_H
| 31.153061 | 80 | 0.662627 | [
"vector"
] |
04eb92a362632f7d542e64b0f016282c7db7ae41 | 11,905 | h | C | SDK/P2P/Peer.h | heropan/Elastos.ELA.SPV.Cpp | 9b7fe0de47d3213ed175e28e20905120bfb80a23 | [
"MIT"
] | null | null | null | SDK/P2P/Peer.h | heropan/Elastos.ELA.SPV.Cpp | 9b7fe0de47d3213ed175e28e20905120bfb80a23 | [
"MIT"
] | null | null | null | SDK/P2P/Peer.h | heropan/Elastos.ELA.SPV.Cpp | 9b7fe0de47d3213ed175e28e20905120bfb80a23 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2019 Elastos Foundation
*
* 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 __ELASTOS_SDK_PEER_H__
#define __ELASTOS_SDK_PEER_H__
#include "PeerInfo.h"
#include "Message/Message.h"
#include <Common/Log.h>
#include <Common/ElementSet.h>
#include <Common/uint256.h>
#include <deque>
#include <boost/shared_ptr.hpp>
#include <boost/enable_shared_from_this.hpp>
#include <boost/function.hpp>
#include <sys/types.h>
#include <sys/socket.h>
#define REJECT_INVALID 0x10 // transaction is invalid for some reason (invalid signature, output value > input, etc)
#define REJECT_SPENT 0x12 // an input is already spent
#define REJECT_NONSTANDARD 0x40 // not mined/relayed because it is "non-standard" (type or version unknown by server)
#define REJECT_DUST 0x41 // one or more output amounts are below the 'dust' threshold
#define REJECT_LOWFEE 0x42 // transaction does not have enough fee/priority to be relayed or mined
#ifndef MSG_NOSIGNAL // linux based systems have a MSG_NOSIGNAL send flag, useful for supressing SIGPIPE signals
#define MSG_NOSIGNAL 0 // set to 0 if undefined (BSD has the SO_NOSIGPIPE sockopt, and windows has no signals at all)
#endif
namespace Elastos {
namespace ElaWallet {
class Peer;
class PeerManager;
typedef boost::shared_ptr<Peer> PeerPtr;
#define time_after(a,b) ((long)(b) - (long)(a) < 0)
#define PEER_DEBUG(p, ...) SPVLOG_DEBUG("{} {}:{} " __va_first(__VA_ARGS__, NULL), (p)->GetPeerManager()->GetID(), (p)->GetHost(), (p)->GetPort(), __va_rest(__VA_ARGS__, NULL))
#define PEER_INFO(p, ...) SPVLOG_INFO("{} {}:{} " __va_first(__VA_ARGS__, NULL), (p)->GetPeerManager()->GetID(), (p)->GetHost(), (p)->GetPort(), __va_rest(__VA_ARGS__, NULL))
class Peer : public boost::enable_shared_from_this<Peer> {
public:
enum ConnectStatus {
Disconnected = 0,
Connecting = 1,
Connected = 2,
};
class Listener {
public:
virtual void OnConnected(const PeerPtr &peer) = 0;
virtual void OnDisconnected(const PeerPtr &peer, int error) = 0;
virtual void
OnRelayedPeers(const PeerPtr &peer, const std::vector<PeerInfo> &peers) = 0;
virtual void OnRelayedTx(const PeerPtr &peer, const TransactionPtr &tx) = 0;
virtual void OnHasTx(const PeerPtr &peer, const uint256 &txHash) = 0;
virtual void OnRejectedTx(const PeerPtr &peer, const uint256 &txHash, uint8_t code, const std::string &reason) = 0;
virtual void OnRelayedBlock(const PeerPtr &peer, const MerkleBlockPtr &block) = 0;
virtual void OnRelayedPing(const PeerPtr &peer) = 0;
virtual void
OnNotfound(const PeerPtr &peer, const std::vector<uint256> &txHashes,
const std::vector<uint256> &blockHashes) = 0;
virtual void OnSetFeePerKb(const PeerPtr &peer, uint64_t feePerKb) = 0;
virtual TransactionPtr OnRequestedTx(const PeerPtr &peer, const uint256 &txHash) = 0;
virtual bool OnNetworkIsReachable(const PeerPtr &peer) = 0;
virtual void OnThreadCleanup(const PeerPtr &peer) = 0;
};
typedef boost::function<void(int)> PeerCallback;
typedef boost::function<void(const uint256 &, int, const std::string &)> PeerPubTxCallback;
public:
Peer(PeerManager *manager, uint32_t magicNumber);
void InitDefaultMessages();
~Peer();
void RegisterListner(Listener *listener);
void UnRegisterListener();
void SendMessage(const std::string &msgType, const SendMessageParameter ¶meter);
const uint128 &getAddress() const;
void setAddress(const uint128 &addr);
uint16_t GetPort() const;
void SetPort(uint16_t port);
uint64_t GetTimestamp() const;
void SetTimestamp(uint64_t timestamp);
int GetDownloadSpeed() const;
int CalculateDownloadSpeed();
void ScheduleDownloadStartTime();
uint32_t GetDownloadBytes() const;
void SetDownloadBytes(uint32_t bytes);
uint64_t GetServices() const;
void SetServices(uint64_t services);
uint64_t GetNonce() const;
void SetNonce(uint64_t nonce);
uint32_t GetEarliestKeyTime() const;
void setEarliestKeyTime(uint32_t earliestKeyTime);
uint32_t GetCurrentBlockHeight() const;
void SetCurrentBlockHeight(uint32_t currentBlockHeight);
ConnectStatus GetConnectStatus() const;
void SetConnectStatus(ConnectStatus status);
void Connect();
void Disconnect();
void SendMessage(const bytes_t &message, const std::string &type);
void RerequestBlocks(const uint256 &fromBlock);
void ScheduleDisconnect(double time);
bool NeedsFilterUpdate() const;
void SetNeedsFilterUpdate(bool needsFilterUpdate);
const std::string &GetHost() const;
uint32_t GetVersion() const;
void SetVersion(uint32_t version);
const std::string &GetUserAgent() const;
uint32_t GetLastBlock() const;
void SetLastBlock(uint32_t height);
uint64_t GetFeePerKb() const;
bool IsEqual(const Peer *peer) const;
bool SentVerack();
void SetSentVerack(bool sent);
bool GotVerack();
void SetGotVerack(bool got);
bool SentGetaddr();
void SetSentGetaddr(bool sent);
bool SentFilter();
void SetSentFilter(bool sent);
bool SentGetdata();
void SetSentGetdata(bool sent);
bool WaitingBlocks() const;
void SetWaitingBlocks(bool wait);
bool SentMempool();
void SetSentMempool(bool sent);
bool SentGetblocks();
void SetSentGetblocks(bool sent);
const std::vector<uint256> &CurrentBlockTxHashes() const;
void AddCurrentBlockTxHash(const uint256 &hash);
void CurrentBlockTxHashesRemove(const uint256 &hash);
const std::vector<uint256> &GetKnownBlockHashes() const;
void KnownBlockHashesRemoveRange(size_t index, size_t len);
void AddKnownBlockHash(const uint256 &hash);
const std::vector<uint256> &KnownTxHashes() const;
const uint256 &LastBlockHash() const;
void SetLastBlockHash(const uint256 &hash);
const std::set<uint256> &KnownTxHashSet() const;
void AddKnownTxHashes(const std::vector<uint256> &txHashes);
void RemoveKnownTxHashes(const std::vector<uint256> &txHashes);
bool IsIPv4() const;
double GetStartTime() const;
void SetStartTime(double time);
double GetPingTime() const;
void SetPingTime(double time);
double GetDisconnectTime() const;
void SetDisconnectTime(double time);
void AddPongCallback(const PeerCallback &callback);
PeerCallback PopPongCallback();
const std::deque<PeerCallback> &GetPongCallbacks() const;
const PeerCallback &GetMemPoolCallback() const;
void SetMempoolCallback(const PeerCallback &callback);
void SetMempoolTime(double time);
void ResetMemPool();
PeerManager *GetPeerManager() const;
uint8_t GetFlags() const;
void SetFlags(uint8_t flags);
const PeerInfo &GetPeerInfo() const;
void SetPeerInfo(const PeerInfo &info);
void SetCurrentBlock(const MerkleBlockPtr &block);
const MerkleBlockPtr &CurrentBlock() const;
std::string FormatError(int errnum);
template<typename Arg1, typename... Args>
inline void trace(const std::string &fmt, const Arg1 &arg1, const Args &... args) {
std::string peerFmt = "{} {}:{} ";
peerFmt += fmt;
Log::trace(peerFmt.c_str(), _managerID, GetHost(), GetPort(), arg1, args...);
}
template<typename Arg1, typename... Args>
inline void debug(const std::string &fmt, const Arg1 &arg1, const Args &... args) {
std::string peerFmt = "{} {}:{} ";
peerFmt += fmt;
Log::debug(peerFmt.c_str(), _managerID, GetHost(), GetPort(), arg1, args...);
}
template<typename Arg1, typename... Args>
inline void info(const std::string &fmt, const Arg1 &arg1, const Args &... args) {
std::string peerFmt = "{} {}:{} ";
peerFmt += fmt;
Log::info(peerFmt.c_str(), _managerID, GetHost(), GetPort(), arg1, args...);
}
template<typename Arg1, typename... Args>
inline void warn(const std::string &fmt, const Arg1 &arg1, const Args &... args) {
std::string peerFmt = "{} {}:{} ";
peerFmt += fmt;
Log::warn(peerFmt.c_str(), _managerID, GetHost(), GetPort(), arg1, args...);
}
template<typename Arg1, typename... Args>
inline void error(const std::string &fmt, const Arg1 &arg1, const Args &... args) {
std::string peerFmt = "{} {}:{} ";
peerFmt += fmt;
Log::error(peerFmt.c_str(), _managerID, GetHost(), GetPort(), arg1, args...);
}
template<typename Arg1, typename... Args>
inline void critical(const std::string &fmt, const Arg1 &arg1, const Args &... args) {
std::string peerFmt = "{} {}:{} ";
peerFmt += fmt;
Log::critical(peerFmt.c_str(), _managerID, GetHost(), GetPort(), arg1, args...);
}
template<typename T>
inline void trace(const T &msg) {
Log::trace("{} {}:{} {}", _managerID, GetHost(), GetPort(), msg);
}
template<typename T>
inline void debug(const T &msg) {
Log::debug("{} {}:{} {}", _managerID, GetHost(), GetPort(), msg);
}
template<typename T>
inline void info(const T &msg) {
Log::info("{} {}:{} {}", _managerID, GetHost(), GetPort(), msg);
}
template<typename T>
inline void warn(const T &msg) {
Log::warn("{} {}:{} {}", _managerID, GetHost(), GetPort(), msg);
}
template<typename T>
inline void error(const T &msg) {
Log::error("{} {}:{} {}", _managerID, GetHost(), GetPort(), msg);
}
template<typename T>
inline void critical(const T &msg) {
Log::critical("{} {}:{} {}", _managerID, GetHost(), GetPort(), msg);
}
private:
void InitSingleMessage(Message *message);
bool NetworkIsReachable() const;
bool AcceptMessage(const bytes_t &msg, const std::string &type);
int OpenSocket(int domain, double timeout, int *error);
void PeerThreadRoutine();
private:
friend class Message;
PeerInfo _info;
std::vector<int> _recentSpeed;
std::string _managerID;
uint32_t _magicNumber;
mutable std::string _host;
ConnectStatus _status;
int _waitingForNetwork;
volatile bool _needsFilterUpdate;
uint64_t _nonce, _feePerKb;
std::string _useragent;
uint32_t _version, _lastblock, _earliestKeyTime, _currentBlockHeight;
double _startTime, _pingTime;
uint64_t _downloadStartTime; // millisecond
uint64_t _downloadBytes;
volatile double _disconnectTime, _mempoolTime;
bool _sentVerack, _gotVerack, _sentGetaddr, _sentFilter, _sentGetdata, _sentMempool, _sentGetblocks, _waitingBlocks;
uint256 _lastBlockHash;
MerkleBlockPtr _currentBlock;
std::vector<uint256> _currentBlockTxHashes, _knownBlockHashes, _knownTxHashes;
std::set<uint256> _knownTxHashSet;
volatile int _socket;
PeerCallback _mempoolCallback;
std::deque<PeerCallback> _pongCallbackList;
typedef boost::shared_ptr<Message> MessagePtr;
std::map<std::string, MessagePtr> _messages;
PeerManager *_manager;
Listener *_listener;
};
}
}
#endif //__ELASTOS_SDK_PEER_H__
| 28.617788 | 177 | 0.703738 | [
"vector"
] |
04eb95fdbb96c6bb7c9028163394e4a51b65df6b | 2,769 | h | C | src/Base/GL1SceneRenderer.h | orikuma/choreonoid-org | d63dff5fa2249a586ffb2dbdbfa0aef0081bad66 | [
"MIT"
] | 66 | 2020-03-11T14:06:01.000Z | 2022-03-23T23:18:27.000Z | src/Base/GL1SceneRenderer.h | orikuma/choreonoid-org | d63dff5fa2249a586ffb2dbdbfa0aef0081bad66 | [
"MIT"
] | 12 | 2020-07-23T06:13:11.000Z | 2022-01-13T14:25:01.000Z | src/Base/GL1SceneRenderer.h | orikuma/choreonoid-org | d63dff5fa2249a586ffb2dbdbfa0aef0081bad66 | [
"MIT"
] | 18 | 2020-07-17T15:57:54.000Z | 2022-03-29T13:18:59.000Z | /*!
@file
@author Shin'ichiro Nakaoka
*/
#ifndef CNOID_BASE_GL1_SCENE_RENDERER_H
#define CNOID_BASE_GL1_SCENE_RENDERER_H
#include <cnoid/GLSceneRenderer>
#include "exportdecl.h"
namespace cnoid {
class CNOID_EXPORT GL1SceneRenderer : public GLSceneRenderer
{
public:
GL1SceneRenderer(SgGroup* root = nullptr);
virtual ~GL1SceneRenderer();
virtual void setOutputStream(std::ostream& os) override;
virtual PolymorphicSceneNodeFunctionSet* renderingFunctions() override;
virtual void renderCustomGroup(SgGroup* transform, std::function<void()> traverseFunction) override;
virtual void renderCustomTransform(SgTransform* transform, std::function<void()> traverseFunction) override;
virtual void renderNode(SgNode* node) override;
virtual void addNodeDecoration(SgNode* targetNode, NodeDecorationFunction func, int id) override;
virtual void clearNodeDecorations(int id) override;
virtual const Affine3& currentModelTransform() const override;
virtual const Matrix4& projectionMatrix() const override;
virtual double projectedPixelSizeRatio(const Vector3& position) const override;
virtual bool initializeGL() override;
virtual void flushGL() override;
virtual const std::string& glVendor() const override;
virtual void setViewport(int x, int y, int width, int height) override;
virtual const Vector3& pickedPoint() const override;
virtual const SgNodePath& pickedNodePath() const override;
virtual bool isRenderingPickingImage() const override;
virtual void setLightingMode(LightingMode mode) override;
virtual LightingMode lightingMode() const override;
void setHeadLightLightingFromBackEnabled(bool on);
virtual void setDefaultSmoothShading(bool on) override;
virtual SgMaterial* defaultMaterial() override;
virtual void enableTexture(bool on) override;
virtual void setDefaultPointSize(double size) override;
virtual void setDefaultLineWidth(double width) override;
virtual void showNormalVectors(double length) override;
virtual void requestToClearResources() override;
/**
If this is enabled, OpenGL resources such as display lists, vertex buffer objects
are checked if they are still used or not, and the unused resources are released
when finalizeRendering() is called. The default value is true.
*/
virtual void enableUnusedResourceCheck(bool on) override;
virtual void setColor(const Vector3f& color) override;
virtual void setBackFaceCullingMode(int mode) override;
virtual int backFaceCullingMode() const override;
protected:
virtual void doRender() override;
virtual bool doPick(int x, int y) override;
private:
class Impl;
Impl* impl;
};
}
#endif
| 36.434211 | 112 | 0.760925 | [
"transform"
] |
04f268cdace15ab2b73558edaf4d7180241cbcec | 31,524 | h | C | src/TrackPanel.h | DavidBailes/audacity | d7ffab7825f2d306f88e6f2d0b960030a206b20b | [
"CC-BY-3.0"
] | null | null | null | src/TrackPanel.h | DavidBailes/audacity | d7ffab7825f2d306f88e6f2d0b960030a206b20b | [
"CC-BY-3.0"
] | null | null | null | src/TrackPanel.h | DavidBailes/audacity | d7ffab7825f2d306f88e6f2d0b960030a206b20b | [
"CC-BY-3.0"
] | null | null | null | /**********************************************************************
Audacity: A Digital Audio Editor
TrackPanel.h
Dominic Mazzoni
**********************************************************************/
#ifndef __AUDACITY_TRACK_PANEL__
#define __AUDACITY_TRACK_PANEL__
#include <memory>
#include <vector>
#include <wx/dcmemory.h>
#include <wx/dynarray.h>
#include <wx/panel.h>
#include <wx/timer.h>
#include <wx/window.h>
#include "Experimental.h"
#include "Sequence.h" //Stm: included for the sampleCount declaration
#include "WaveClip.h"
#include "WaveTrack.h"
#include "UndoManager.h" //JKC: Included for PUSH_XXX definitions.
#include "widgets/NumericTextCtrl.h"
class wxMenu;
class wxRect;
class LabelTrack;
class SpectrumAnalyst;
class TrackPanel;
class TrackArtist;
class Ruler;
class SnapManager;
class AdornedRulerPanel;
class LWSlider;
class ControlToolBar; //Needed because state of controls can affect what gets drawn.
class ToolsToolBar; //Needed because state of controls can affect what gets drawn.
class MixerBoard;
class AudacityProject;
class TrackPanelAx;
struct ViewInfo;
WX_DEFINE_ARRAY(LWSlider *, LWSliderArray);
class AUDACITY_DLL_API TrackClip
{
public:
TrackClip(Track *t, WaveClip *c) { track = t; clip = c; }
Track *track;
WaveClip *clip;
};
WX_DECLARE_OBJARRAY(TrackClip, TrackClipArray);
// Declared elsewhere, to reduce compilation dependencies
class TrackPanelListener;
//
// TrackInfo sliders: we keep a pool of sliders, and attach them to tracks as
// they come on screen (this helps deal with very large numbers of tracks, esp.
// on MSW).
//
// With the initial set of sliders smaller than the page size, a new slider is
// created at track-creation time for tracks between 16 and when 80 goes past
// the top of the screen. After that, existing sliders are re-used for new
// tracks.
//
const unsigned int kInitialSliders = 16;
const unsigned int kSliderPageFlip = 80;
// JKC Nov 2011: Disabled warning C4251 which is to do with DLL linkage
// and only a worry when there are DLLs using the structures.
// LWSliderArray and TrackClipArray are private in TrackInfo, so we will not
// access them directly from the DLL.
// TrackClipArray in TrackPanel needs to be handled with care in the derived
// class, but the C4251 warning is no worry in core Audacity.
// wxWidgets doesn't cater to the exact details we need in
// WX_DECLARE_EXPORTED_OBJARRAY to be able to use that for these two arrays.
#ifdef _MSC_VER
#pragma warning( push )
#pragma warning( disable: 4251 )
#endif
class AUDACITY_DLL_API TrackInfo
{
public:
TrackInfo(wxWindow * pParentIn);
~TrackInfo();
int GetTrackInfoWidth() const;
void UpdateSliderOffset(Track *t);
private:
void MakeMoreSliders();
void EnsureSufficientSliders(int index);
void SetTrackInfoFont(wxDC *dc);
void DrawBackground(wxDC * dc, const wxRect & r, bool bSelected, bool bHasMuteSolo, const int labelw, const int vrul);
void DrawBordersWithin(wxDC * dc, const wxRect & r, bool bHasMuteSolo );
void DrawCloseBox(wxDC * dc, const wxRect & r, bool down);
void DrawTitleBar(wxDC * dc, const wxRect & r, Track * t, bool down);
void DrawMuteSolo(wxDC * dc, const wxRect & r, Track * t, bool down, bool solo, bool bHasSoloButton);
void DrawVRuler(wxDC * dc, const wxRect & r, Track * t);
#ifdef EXPERIMENTAL_MIDI_OUT
void DrawVelocitySlider(wxDC * dc, NoteTrack *t, wxRect r);
#endif
void DrawSliders(wxDC * dc, WaveTrack *t, wxRect r);
// Draw the minimize button *and* the sync-lock track icon, if necessary.
void DrawMinimize(wxDC * dc, const wxRect & r, Track * t, bool down);
void GetTrackControlsRect(const wxRect & r, wxRect &dest) const;
void GetCloseBoxRect(const wxRect & r, wxRect &dest) const;
void GetTitleBarRect(const wxRect & r, wxRect &dest) const;
void GetMuteSoloRect(const wxRect & r, wxRect &dest, bool solo, bool bHasSoloButton) const;
void GetGainRect(const wxRect & r, wxRect &dest) const;
void GetPanRect(const wxRect & r, wxRect &dest) const;
void GetMinimizeRect(const wxRect & r, wxRect &dest) const;
void GetSyncLockIconRect(const wxRect & r, wxRect &dest) const;
// These arrays are always kept the same size.
LWSliderArray mGains;
LWSliderArray mPans;
// index of track whose pan/gain sliders are at index 0 in the above arrays
unsigned int mSliderOffset;
public:
// Slider access by track index
LWSlider * GainSlider(int trackIndex);
LWSlider * PanSlider(int trackIndex);
wxWindow * pParent;
wxFont mFont;
friend class TrackPanel;
};
const int DragThreshold = 3;// Anything over 3 pixels is a drag, else a click.
class AUDACITY_DLL_API TrackPanel:public wxPanel {
public:
TrackPanel(wxWindow * parent,
wxWindowID id,
const wxPoint & pos,
const wxSize & size,
TrackList * tracks,
ViewInfo * viewInfo,
TrackPanelListener * listener,
AdornedRulerPanel * ruler );
virtual ~ TrackPanel();
virtual void BuildMenus(void);
virtual void DeleteMenus(void);
virtual void UpdatePrefs();
virtual void OnSize(wxSizeEvent & event);
virtual void OnErase(wxEraseEvent & event);
virtual void OnPaint(wxPaintEvent & event);
virtual void OnMouseEvent(wxMouseEvent & event);
virtual void OnCaptureLost(wxMouseCaptureLostEvent & event);
virtual void OnCaptureKey(wxCommandEvent & event);
virtual void OnKeyDown(wxKeyEvent & event);
virtual void OnChar(wxKeyEvent & event);
virtual void OnSetFocus(wxFocusEvent & event);
virtual void OnKillFocus(wxFocusEvent & event);
virtual void OnContextMenu(wxContextMenuEvent & event);
virtual void OnTrackListResized(wxCommandEvent & event);
virtual void OnTrackListUpdated(wxCommandEvent & event);
virtual void UpdateViewIfNoTracks(); // Call this to update mViewInfo, etc, after track(s) removal, before Refresh().
virtual double GetMostRecentXPos();
virtual void OnTimer();
virtual int GetLeftOffset() const { return GetLabelWidth() + 1;}
virtual void GetTracksUsableArea(int *width, int *height) const;
virtual void SelectNone();
virtual void SetStop(bool bStopped);
virtual void Refresh(bool eraseBackground = true,
const wxRect *rect = (const wxRect *) NULL);
virtual void RefreshTrack(Track *trk, bool refreshbacking = true);
virtual void DisplaySelection();
// These two are neither used nor defined as of Nov-2011
//virtual void SetSelectionFormat(int iformat)
//virtual void SetSnapTo(int snapto)
void HandleEscapeKey();
virtual void HandleAltKey(bool down);
virtual void HandleShiftKey(bool down);
virtual void HandleControlKey(bool down);
virtual void HandlePageUpKey();
virtual void HandlePageDownKey();
virtual AudacityProject * GetProject() const;
virtual void OnPrevTrack(bool shift = false);
virtual void OnNextTrack(bool shift = false);
virtual void OnFirstTrack();
virtual void OnLastTrack();
virtual void OnToggle();
virtual void OnCursorLeft(bool shift, bool ctrl, bool keyup = false);
virtual void OnCursorRight(bool shift, bool ctrl, bool keyup = false);
virtual void OnCursorMove(bool forward, bool jump, bool longjump);
virtual void OnBoundaryMove(bool left, bool boundaryContract);
virtual void ScrollIntoView(double pos);
virtual void ScrollIntoView(int x);
virtual void OnTrackPan();
virtual void OnTrackPanLeft();
virtual void OnTrackPanRight();
virtual void OnTrackGain();
virtual void OnTrackGainDec();
virtual void OnTrackGainInc();
virtual void OnTrackMenu(Track *t = NULL);
virtual void OnTrackMute(bool shiftdown, Track *t = NULL);
virtual void OnTrackSolo(bool shiftdown, Track *t = NULL);
virtual void OnTrackClose();
virtual void OnTrackMoveUp();
virtual void OnTrackMoveDown();
virtual void OnTrackMoveTop();
virtual void OnTrackMoveBottom();
virtual Track * GetFirstSelectedTrack();
virtual bool IsMouseCaptured();
virtual void EnsureVisible(Track * t);
virtual Track *GetFocusedTrack();
virtual void SetFocusedTrack(Track *t);
virtual void HandleCursorForLastMouseEvent();
virtual void UpdateVRulers();
virtual void UpdateVRuler(Track *t);
virtual void UpdateTrackVRuler(Track *t);
virtual void UpdateVRulerSize();
virtual void DrawQuickPlayIndicator(wxDC & dc, double pos);
protected:
virtual MixerBoard* GetMixerBoard();
/** @brief Populates the track pop-down menu with the common set of
* initial items.
*
* Ensures that all pop-down menus start with Name, and the commands for moving
* the track around, via a single set of code.
* @param menu the menu to add the commands to.
*/
virtual void BuildCommonDropMenuItems(wxMenu * menu);
virtual bool IsUnsafe();
virtual bool HandleLabelTrackMouseEvent(LabelTrack * lTrack, wxRect &r, wxMouseEvent & event);
virtual bool HandleTrackLocationMouseEvent(WaveTrack * track, wxRect &r, wxMouseEvent &event);
virtual void HandleTrackSpecificMouseEvent(wxMouseEvent & event);
virtual void DrawIndicator();
/// draws the green line on the tracks to show playback position
/// @param repairOld if true the playback position is not updated/erased, and simply redrawn
/// @param indicator if nonnegative, overrides the indicator value obtainable from AudioIO
virtual void DoDrawIndicator(wxDC & dc, bool repairOld = false, double indicator = -1);
virtual void DrawCursor();
virtual void DoDrawCursor(wxDC & dc);
virtual void ScrollDuringDrag();
// Working out where to dispatch the event to.
virtual int DetermineToolToUse( ToolsToolBar * pTtb, wxMouseEvent & event);
virtual bool HitTestEnvelope(Track *track, wxRect &r, wxMouseEvent & event);
virtual bool HitTestSamples(Track *track, wxRect &r, wxMouseEvent & event);
virtual bool HitTestSlide(Track *track, wxRect &r, wxMouseEvent & event);
#ifdef USE_MIDI
// data for NoteTrack interactive stretch operations:
// Stretching applies to a selected region after quantizing the
// region to beat boundaries (subbeat stretching is not supported,
// but maybe it should be enabled with shift or ctrl or something)
// Stretching can drag the left boundary (the right stays fixed),
// the right boundary (the left stays fixed), or the center (splits
// the selection into two parts: when left part grows, the right
// part shrinks, keeping the leftmost and rightmost boundaries
// fixed.
enum StretchEnum {
stretchLeft,
stretchCenter,
stretchRight
};
StretchEnum mStretchMode; // remembers what to drag
bool mStretching; // true between mouse down and mouse up
bool mStretched; // true after drag has pushed state
double mStretchStart; // time of initial mouse position, quantized
// to the nearest beat
double mStretchSel0; // initial sel0 (left) quantized to nearest beat
double mStretchSel1; // initial sel1 (left) quantized to nearest beat
double mStretchLeftBeats; // how many beats from left to cursor
double mStretchRightBeats; // how many beats from cursor to right
virtual bool HitTestStretch(Track *track, wxRect &r, wxMouseEvent & event);
virtual void Stretch(int mouseXCoordinate, int trackLeftEdge, Track *pTrack);
#endif
// AS: Selection handling
virtual void HandleSelect(wxMouseEvent & event);
virtual void SelectionHandleDrag(wxMouseEvent &event, Track *pTrack);
// Made obsolete by scrubbing:
#ifndef EXPERIMENTAL_SCRUBBING_BASIC
void StartOrJumpPlayback(wxMouseEvent &event);
#endif
#ifdef EXPERIMENTAL_SCRUBBING_SMOOTH_SCROLL
double FindScrubSpeed(double timeAtMouse) const;
#endif
#ifdef EXPERIMENTAL_SCRUBBING_BASIC
bool IsScrubbing();
void ToggleScrubbing(
wxCoord xx
#ifdef EXPERIMENTAL_SCRUBBING_SMOOTH_SCROLL
, bool smoothScrolling
#endif
);
bool MaybeStartScrubbing(wxMouseEvent &event);
bool ContinueScrubbing(wxCoord position, bool maySkip);
bool StopScrubbing();
#endif
virtual void SelectionHandleClick(wxMouseEvent &event,
Track* pTrack, wxRect r);
virtual void StartSelection (int mouseXCoordinate, int trackLeftEdge);
virtual void ExtendSelection(int mouseXCoordinate, int trackLeftEdge,
Track *pTrack);
virtual void UpdateSelectionDisplay();
// Handle small cursor and play head movements
void SeekLeftOrRight
(bool left, bool shift, bool ctrl, bool keyup,
int snapToTime, bool mayAccelerateQuiet, bool mayAccelerateAudio,
double quietSeekStepPositive, double audioSeekStepPositive);
#ifdef EXPERIMENTAL_SPECTRAL_EDITING
public:
void SnapCenterOnce (WaveTrack *pTrack, bool up);
protected:
void StartSnappingFreqSelection (WaveTrack *pTrack);
void MoveSnappingFreqSelection (int mouseYCoordinate,
int trackTopEdge,
int trackHeight, Track *pTrack);
void StartFreqSelection (int mouseYCoordinate, int trackTopEdge,
int trackHeight, Track *pTrack);
void ExtendFreqSelection(int mouseYCoordinate, int trackTopEdge,
int trackHeight);
void ResetFreqSelectionPin(double hintFrequency, bool logF);
#endif
virtual void SelectTracksByLabel( LabelTrack *t );
virtual void SelectTrackLength(Track *t);
// Helper for moving by keyboard with snap-to-grid enabled
virtual double GridMove(double t, int minPix);
// AS: Cursor handling
virtual bool SetCursorByActivity( );
virtual void SetCursorAndTipWhenInLabel( Track * t, wxMouseEvent &event, const wxChar ** ppTip );
virtual void SetCursorAndTipWhenInVResizeArea( Track * label, bool blinked, const wxChar ** ppTip );
virtual void SetCursorAndTipWhenInLabelTrack( LabelTrack * pLT, wxMouseEvent & event, const wxChar ** ppTip );
virtual void SetCursorAndTipWhenSelectTool
( Track * t, wxMouseEvent & event, wxRect &r, bool bMultiToolMode, const wxChar ** ppTip, const wxCursor ** ppCursor );
virtual void SetCursorAndTipByTool( int tool, wxMouseEvent & event, const wxChar **ppTip );
virtual void HandleCursor(wxMouseEvent & event);
virtual void MaySetOnDemandTip( Track * t, const wxChar ** ppTip );
// AS: Envelope editing handlers
virtual void HandleEnvelope(wxMouseEvent & event);
virtual void ForwardEventToTimeTrackEnvelope(wxMouseEvent & event);
virtual void ForwardEventToWaveTrackEnvelope(wxMouseEvent & event);
virtual void ForwardEventToEnvelope(wxMouseEvent &event);
// AS: Track sliding handlers
virtual void HandleSlide(wxMouseEvent & event);
virtual void StartSlide(wxMouseEvent &event);
virtual void DoSlide(wxMouseEvent &event);
virtual void AddClipsToCaptured(Track *t, bool withinSelection);
virtual void AddClipsToCaptured(Track *t, double t0, double t1);
// AS: Handle zooming into tracks
virtual void HandleZoom(wxMouseEvent & event);
virtual void HandleZoomClick(wxMouseEvent & event);
virtual void HandleZoomDrag(wxMouseEvent & event);
virtual void HandleZoomButtonUp(wxMouseEvent & event);
virtual bool IsDragZooming();
virtual void DragZoom(wxMouseEvent &event, int x);
virtual void DoZoomInOut(wxMouseEvent &event, int x);
virtual void HandleVZoom(wxMouseEvent & event);
virtual void HandleVZoomClick(wxMouseEvent & event);
virtual void HandleVZoomDrag(wxMouseEvent & event);
virtual void HandleVZoomButtonUp(wxMouseEvent & event);
// Handle sample editing using the 'draw' tool.
virtual bool IsSampleEditingPossible( wxMouseEvent & event, Track * t );
virtual void HandleSampleEditing(wxMouseEvent & event);
virtual void HandleSampleEditingClick( wxMouseEvent & event );
virtual void HandleSampleEditingDrag( wxMouseEvent & event );
virtual void HandleSampleEditingButtonUp( wxMouseEvent & event );
// MM: Handle mouse wheel rotation
virtual void HandleWheelRotation(wxMouseEvent & event);
// Handle resizing.
virtual void HandleResizeClick(wxMouseEvent & event);
virtual void HandleResizeDrag(wxMouseEvent & event);
virtual void HandleResizeButtonUp(wxMouseEvent & event);
virtual void HandleResize(wxMouseEvent & event);
virtual void HandleLabelClick(wxMouseEvent & event);
virtual void HandleRearrange(wxMouseEvent & event);
virtual void CalculateRearrangingThresholds(wxMouseEvent & event);
virtual void HandleClosing(wxMouseEvent & event);
virtual void HandlePopping(wxMouseEvent & event);
virtual void HandleMutingSoloing(wxMouseEvent & event, bool solo);
virtual void HandleMinimizing(wxMouseEvent & event);
virtual void HandleSliders(wxMouseEvent &event, bool pan);
// These *Func methods are used in TrackPanel::HandleLabelClick to set up
// for actual handling in methods called by TrackPanel::OnMouseEvent, and
// to draw button-down states, etc.
virtual bool CloseFunc(Track * t, wxRect r, int x, int y);
virtual bool PopupFunc(Track * t, wxRect r, int x, int y);
// TrackSelFunc, unlike the other *Func methods, returns true if the click is not
// set up to be handled, but click is on the sync-lock icon or the blank area to
// the left of the minimize button, and we want to pass it forward to be a track select.
virtual bool TrackSelFunc(Track * t, wxRect r, int x, int y);
virtual bool MuteSoloFunc(Track *t, wxRect r, int x, int f, bool solo);
virtual bool MinimizeFunc(Track *t, wxRect r, int x, int f);
virtual bool GainFunc(Track * t, wxRect r, wxMouseEvent &event,
int x, int y);
virtual bool PanFunc(Track * t, wxRect r, wxMouseEvent &event,
int x, int y);
virtual void MakeParentRedrawScrollbars();
// AS: Pushing the state preserves state for Undo operations.
virtual void MakeParentPushState(wxString desc, wxString shortDesc,
int flags = PUSH_AUTOSAVE);
virtual void MakeParentModifyState(bool bWantsAutoSave); // if true, writes auto-save file. Should set only if you really want the state change restored after
// a crash, as it can take many seconds for large (eg. 10 track-hours) projects
virtual void MakeParentResize();
virtual void OnSetName(wxCommandEvent &event);
virtual void OnSetFont(wxCommandEvent &event);
virtual void OnMoveTrack (wxCommandEvent &event);
virtual void MoveTrack(Track* target, int eventId);
virtual void OnChangeOctave (wxCommandEvent &event);
virtual void OnChannelChange(wxCommandEvent &event);
virtual void OnSetDisplay (wxCommandEvent &event);
virtual void OnSetTimeTrackRange (wxCommandEvent &event);
virtual void OnTimeTrackLin(wxCommandEvent &event);
virtual void OnTimeTrackLog(wxCommandEvent &event);
virtual void OnTimeTrackLogInt(wxCommandEvent &event);
virtual void SetMenuCheck( wxMenu & menu, int newId );
virtual void SetRate(Track *pTrack, double rate);
virtual void OnRateChange(wxCommandEvent &event);
virtual void OnRateOther(wxCommandEvent &event);
virtual void OnFormatChange(wxCommandEvent &event);
virtual void OnSwapChannels(wxCommandEvent &event);
virtual void OnSplitStereo(wxCommandEvent &event);
virtual void OnSplitStereoMono(wxCommandEvent &event);
virtual void SplitStereo(bool stereo);
virtual void OnMergeStereo(wxCommandEvent &event);
virtual void OnCutSelectedText(wxCommandEvent &event);
virtual void OnCopySelectedText(wxCommandEvent &event);
virtual void OnPasteSelectedText(wxCommandEvent &event);
virtual void OnDeleteSelectedLabel(wxCommandEvent &event);
virtual void SetTrackPan(Track * t, LWSlider * s);
virtual void SetTrackGain(Track * t, LWSlider * s);
virtual void RemoveTrack(Track * toRemove);
// Find track info by coordinate
virtual Track *FindTrack(int mouseX, int mouseY, bool label, bool link,
wxRect * trackRect = NULL);
virtual wxRect FindTrackRect(Track * target, bool label);
virtual int GetVRulerWidth() const;
virtual int GetVRulerOffset() const { return mTrackInfo.GetTrackInfoWidth(); };
virtual int GetLabelWidth() const { return mTrackInfo.GetTrackInfoWidth() + GetVRulerWidth(); };
// JKC Nov-2011: These four functions only used from within a dll such as mod-track-panel
// They work around some messy problems with constructors.
public:
TrackList * GetTracks(){ return mTracks;};
ViewInfo * GetViewInfo(){ return mViewInfo;};
TrackPanelListener * GetListener(){ return mListener;};
AdornedRulerPanel * GetRuler(){ return mRuler;};
// JKC and here is a factory function which just does 'new' in standard Audacity.
static TrackPanel *(*FactoryFunction)(wxWindow * parent,
wxWindowID id,
const wxPoint & pos,
const wxSize & size,
TrackList * tracks,
ViewInfo * viewInfo,
TrackPanelListener * listener,
AdornedRulerPanel * ruler);
protected:
virtual void DrawTracks(wxDC * dc);
virtual void DrawEverythingElse(wxDC *dc, const wxRegion & region,
const wxRect & clip);
virtual void DrawOutside(Track *t, wxDC *dc, const wxRect & rec,
const wxRect &trackRect);
#ifdef EXPERIMENTAL_SCRUBBING_BASIC
void DrawScrubSpeed(wxDC &dc);
#endif
virtual void DrawZooming(wxDC* dc, const wxRect & clip);
virtual void HighlightFocusedTrack (wxDC* dc, const wxRect &r);
virtual void DrawShadow (Track *t, wxDC* dc, const wxRect & r);
virtual void DrawBordersAroundTrack(Track *t, wxDC* dc, const wxRect & r, const int labelw, const int vrul);
virtual void DrawOutsideOfTrack (Track *t, wxDC* dc, const wxRect & r);
virtual int IdOfRate( int rate );
virtual int IdOfFormat( int format );
#ifdef EXPERIMENTAL_OUTPUT_DISPLAY
void UpdateVirtualStereoOrder();
#endif
// Accessors...
virtual bool HasSoloButton(){ return mSoloPref!=wxT("None");};
//JKC: These two belong in the label track.
int mLabelTrackStartXPos;
int mLabelTrackStartYPos;
virtual wxString TrackSubText(Track *t);
virtual bool MoveClipToTrack(WaveClip *clip, WaveTrack* dst);
TrackInfo mTrackInfo;
TrackPanelListener *mListener;
TrackList *mTracks;
ViewInfo *mViewInfo;
AdornedRulerPanel *mRuler;
double mSeekShort;
double mSeekLong;
TrackArtist *mTrackArtist;
class AUDACITY_DLL_API AudacityTimer:public wxTimer {
public:
virtual void Notify() { parent->OnTimer(); }
TrackPanel *parent;
} mTimer;
// This stores the parts of the screen that get overwritten by the indicator
// and cursor
double mLastIndicator;
double mLastCursor;
// Quick-Play indicator postion
double mOldQPIndicatorPos;
int mTimeCount;
wxMemoryDC mBackingDC;
wxBitmap *mBacking;
bool mRefreshBacking;
int mPrevWidth;
int mPrevHeight;
wxLongLong mLastSelectionAdjustment;
SelectedRegion mInitialSelection;
// Extra indirection to avoid the stupid MSW compiler warnings! Rrrr!
std::vector<bool> *mInitialTrackSelection;
bool mSelStartValid;
double mSelStart;
#ifdef EXPERIMENTAL_SPECTRAL_EDITING
enum eFreqSelMode {
FREQ_SEL_INVALID,
FREQ_SEL_SNAPPING_CENTER,
FREQ_SEL_PINNED_CENTER,
FREQ_SEL_DRAG_CENTER,
FREQ_SEL_FREE,
FREQ_SEL_TOP_FREE,
FREQ_SEL_BOTTOM_FREE,
} mFreqSelMode;
// Following holds:
// the center for FREQ_SEL_PINNED_CENTER,
// the ratio of top to center (== center to bottom) for FREQ_SEL_DRAG_CENTER,
// a frequency boundary for FREQ_SEL_FREE, FREQ_SEL_TOP_FREE, or
// FREQ_SEL_BOTTOM_FREE,
// and is ignored otherwise.
double mFreqSelPin;
const WaveTrack *mFreqSelTrack;
std::auto_ptr<SpectrumAnalyst> mFrequencySnapper;
// For toggling of spectral seletion
double mLastF0;
double mLastF1;
public:
void ToggleSpectralSelection();
protected:
#endif
Track *mCapturedTrack;
Envelope *mCapturedEnvelope;
WaveClip *mCapturedClip;
TrackClipArray mCapturedClipArray;
bool mCapturedClipIsSelection;
WaveTrack::Location mCapturedTrackLocation;
wxRect mCapturedTrackLocationRect;
wxRect mCapturedRect;
// When sliding horizontally, the moving clip may automatically
// snap to the beginning and ending of other clips, or to label
// starts and stops. When you start sliding, SlideSnapFromPoints
// gets populated with the start and stop times of selected clips,
// and SlideSnapToPoints gets populated with the start and stop times
// of other clips. In both cases, times that are within 3 pixels
// of another at the same zoom level are eliminated; you can't snap
// when there are two things arbitrarily close at that zoom level.
wxBaseArrayDouble mSlideSnapFromPoints;
wxBaseArrayDouble mSlideSnapToPoints;
wxArrayInt mSlideSnapLinePixels;
// The amount that clips are sliding horizontally; this allows
// us to undo the slide and then slide it by another amount
double mHSlideAmount;
bool mDidSlideVertically;
bool mRedrawAfterStop;
bool mIndicatorShowing;
wxMouseEvent mLastMouseEvent;
int mMouseClickX;
int mMouseClickY;
int mMouseMostRecentX;
int mMouseMostRecentY;
int mZoomStart;
int mZoomEnd;
// Handles snapping the selection boundaries or track boundaries to
// line up with existing tracks or labels. mSnapLeft and mSnapRight
// are the horizontal index of pixels to display user feedback
// guidelines so the user knows when such snapping is taking place.
SnapManager *mSnapManager;
wxInt64 mSnapLeft;
wxInt64 mSnapRight;
bool mSnapPreferRightEdge;
NumericConverter mConverter;
Track * mDrawingTrack; // Keeps track of which track you are drawing on between events cf. HandleDraw()
int mDrawingTrackTop; // Keeps track of the top position of the drawing track.
sampleCount mDrawingStartSample; // sample of last click-down
float mDrawingStartSampleValue; // value of last click-down
sampleCount mDrawingLastDragSample; // sample of last drag-over
float mDrawingLastDragSampleValue; // value of last drag-over
#ifdef EXPERIMENTAL_SPECTRAL_EDITING
void HandleCenterFrequencyCursor
(bool shiftDown, const wxChar ** ppTip, const wxCursor ** ppCursor);
void HandleCenterFrequencyClick
(bool shiftDown, Track *pTrack, double value);
#endif
double PositionToTime(wxInt64 mouseXCoordinate,
wxInt64 trackLeftEdge) const;
wxInt64 TimeToPosition(double time,
wxInt64 trackLeftEdge) const;
#ifdef EXPERIMENTAL_SPECTRAL_EDITING
double PositionToFrequency(bool maySnap,
wxInt64 mouseYCoordinate,
wxInt64 trackTopEdge,
int trackHeight,
double rate,
bool logF) const;
wxInt64 FrequencyToPosition(double frequency,
wxInt64 trackTopEdge,
int trackHeight,
double rate,
bool logF) const;
#endif
enum SelectionBoundary {
SBNone,
SBLeft, SBRight,
#ifdef EXPERIMENTAL_SPECTRAL_EDITING
SBBottom, SBTop, SBCenter, SBWidth,
#endif
};
SelectionBoundary ChooseTimeBoundary
(double selend, bool onlyWithinSnapDistance,
wxInt64 *pPixelDist = NULL, double *pPinValue = NULL) const;
SelectionBoundary ChooseBoundary
(wxMouseEvent & event, const Track *pTrack,
const wxRect &rect,
bool mayDragWidth,
bool onlyWithinSnapDistance,
double *pPinValue = NULL) const;
bool mInitialMinimized;
int mInitialTrackHeight;
int mInitialActualHeight;
int mInitialUpperTrackHeight;
int mInitialUpperActualHeight;
bool mAutoScrolling;
enum MouseCaptureEnum
{
IsUncaptured=0, // This is the normal state for the mouse
IsVZooming,
IsClosing,
IsSelecting,
IsAdjustingLabel,
IsAdjustingSample,
IsResizing,
IsResizingBetweenLinkedTracks,
IsResizingBelowLinkedTracks,
IsRearranging,
IsSliding,
IsEnveloping,
IsMuting,
IsSoloing,
IsGainSliding,
IsPanSliding,
IsMinimizing,
IsOverCutLine,
WasOverCutLine,
IsPopping,
#ifdef USE_MIDI
IsStretching,
#endif
IsZooming,
};
enum MouseCaptureEnum mMouseCapture;
virtual void SetCapturedTrack( Track * t, enum MouseCaptureEnum MouseCapture=IsUncaptured );
bool mAdjustSelectionEdges;
bool mSlideUpDownOnly;
bool mCircularTrackNavigation;
float mdBr;
// JH: if the user is dragging a track, at what y
// coordinate should the dragging track move up or down?
int mMoveUpThreshold;
int mMoveDownThreshold;
#ifdef EXPERIMENTAL_SCRUBBING_BASIC
int mScrubToken;
wxLongLong mScrubStartClockTimeMillis;
wxCoord mScrubStartPosition;
double mMaxScrubSpeed;
int mScrubSpeedDisplayCountdown;
#endif
#ifdef EXPERIMENTAL_SCRUBBING_SMOOTH_SCROLL
bool mSmoothScrollingScrub;
#endif
#ifdef EXPERIMENTAL_SCRUBBING_SCROLL_WHEEL
int mLogMaxScrubSpeed;
#endif
wxCursor *mArrowCursor;
wxCursor *mPencilCursor;
wxCursor *mSelectCursor;
wxCursor *mResizeCursor;
wxCursor *mSlideCursor;
wxCursor *mEnvelopeCursor; // doubles as the center frequency cursor
// for spectral selection
wxCursor *mSmoothCursor;
wxCursor *mZoomInCursor;
wxCursor *mZoomOutCursor;
wxCursor *mLabelCursorLeft;
wxCursor *mLabelCursorRight;
wxCursor *mRearrangeCursor;
wxCursor *mDisabledCursor;
wxCursor *mAdjustLeftSelectionCursor;
wxCursor *mAdjustRightSelectionCursor;
#ifdef EXPERIMENTAL_SPECTRAL_EDITING
wxCursor *mBottomFrequencyCursor;
wxCursor *mTopFrequencyCursor;
wxCursor *mBandWidthCursor;
#endif
#if USE_MIDI
wxCursor *mStretchCursor;
wxCursor *mStretchLeftCursor;
wxCursor *mStretchRightCursor;
#endif
wxMenu *mWaveTrackMenu;
wxMenu *mNoteTrackMenu;
wxMenu *mTimeTrackMenu;
wxMenu *mLabelTrackMenu;
wxMenu *mRateMenu;
wxMenu *mFormatMenu;
wxMenu *mLabelTrackInfoMenu;
Track *mPopupMenuTarget;
friend class TrackPanelAx;
TrackPanelAx *mAx;
wxString mSoloPref;
// Keeps track of extra fractional vertical scroll steps
double mVertScrollRemainder;
protected:
// The screenshot class needs to access internals
friend class ScreenshotCommand;
public:
wxSize vrulerSize;
DECLARE_EVENT_TABLE()
};
#ifdef _MSC_VER
#pragma warning( pop )
#endif
//This constant determines the size of the vertical region (in pixels) around
//the bottom of a track that can be used for vertical track resizing.
#define TRACK_RESIZE_REGION 5
//This constant determines the size of the horizontal region (in pixels) around
//the right and left selection bounds that can be used for horizontal selection adjusting
//(or, vertical distance around top and bottom bounds in spectrograms,
// for vertical selection adjusting)
#define SELECTION_RESIZE_REGION 3
#define SMOOTHING_KERNEL_RADIUS 3
#define SMOOTHING_BRUSH_RADIUS 5
#define SMOOTHING_PROPORTION_MAX 0.7
#define SMOOTHING_PROPORTION_MIN 0.0
#endif
| 35.065628 | 164 | 0.72199 | [
"vector"
] |
04f41c28e88834a9697e72ed5748c01ec9a5ba9e | 19,917 | h | C | graphics/vnc/server/vnc_server.h | huahang/incubator-nuttx | 10c4aff6ca6d77da9cde42d4e72e60e843a27aca | [
"MIT"
] | 51 | 2019-04-16T15:11:10.000Z | 2022-03-30T11:58:53.000Z | graphics/vnc/server/vnc_server.h | huahang/incubator-nuttx | 10c4aff6ca6d77da9cde42d4e72e60e843a27aca | [
"MIT"
] | 18 | 2019-04-17T05:42:38.000Z | 2022-03-04T06:51:46.000Z | graphics/vnc/server/vnc_server.h | huahang/incubator-nuttx | 10c4aff6ca6d77da9cde42d4e72e60e843a27aca | [
"MIT"
] | 26 | 2019-04-15T19:26:37.000Z | 2022-01-29T19:45:00.000Z | /****************************************************************************
* graphics/vnc/server/vnc_server.h
*
* Copyright (C) 2016 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.
*
****************************************************************************/
#ifndef __GRAPHICS_VNC_SERVER_VNC_SERVER_H
#define __GRAPHICS_VNC_SERVER_VNC_SERVER_H
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <stdint.h>
#include <semaphore.h>
#include <pthread.h>
#include <queue.h>
#include <nuttx/video/fb.h>
#include <nuttx/video/rfb.h>
#include <nuttx/video/vnc.h>
#include <nuttx/nx/nxglib.h>
#include <nuttx/nx/nx.h>
#include <nuttx/net/net.h>
/****************************************************************************
* Pre-processor Definitions
****************************************************************************/
/* Configuration */
#ifndef CONFIG_NET_TCP_READAHEAD
# error CONFIG_NET_TCP_READAHEAD must be set to use VNC
#endif
#ifndef CONFIG_NX_UPDATE
# error CONFIG_NX_UPDATE must be set to use VNC
#endif
#if !defined(CONFIG_VNCSERVER_PROTO3p3) && !defined(CONFIG_VNCSERVER_PROTO3p8)
# error No VNC protocol selected
#endif
#if defined(CONFIG_VNCSERVER_PROTO3p3) && defined(CONFIG_VNCSERVER_PROTO3p8)
# error Too many VNC protocols selected
#endif
#ifndef CONFIG_VNCSERVER_NDISPLAYS
# define CONFIG_VNCSERVER_NDISPLAYS 1
#endif
#if defined(CONFIG_VNCSERVER_COLORFMT_RGB8)
# define RFB_COLORFMT FB_FMT_RGB8_332
# define RFB_BITSPERPIXEL 8
# define RFB_PIXELDEPTH 8
# define RFB_TRUECOLOR 1
# define RFB_RMAX 0x07
# define RFB_GMAX 0x07
# define RFB_BMAX 0x03
# define RFB_RSHIFT 5
# define RFB_GSHIFT 2
# define RFB_BSHIFT 0
#elif defined(CONFIG_VNCSERVER_COLORFMT_RGB16)
# define RFB_COLORFMT FB_FMT_RGB16_565
# define RFB_BITSPERPIXEL 16
# define RFB_PIXELDEPTH 16
# define RFB_TRUECOLOR 1
# define RFB_RMAX 0x001f
# define RFB_GMAX 0x003f
# define RFB_BMAX 0x001f
# define RFB_RSHIFT 11
# define RFB_GSHIFT 5
# define RFB_BSHIFT 0
#elif defined(CONFIG_VNCSERVER_COLORFMT_RGB32)
# define RFB_COLORFMT FB_FMT_RGB32
# define RFB_BITSPERPIXEL 32
# define RFB_PIXELDEPTH 24
# define RFB_TRUECOLOR 1
# define RFB_RMAX 0x000000ff
# define RFB_GMAX 0x000000ff
# define RFB_BMAX 0x000000ff
# define RFB_RSHIFT 16
# define RFB_GSHIFT 8
# define RFB_BSHIFT 0
#else
# error Unspecified/unsupported color format
#endif
#ifndef CONFIG_VNCSERVER_SCREENWIDTH
# define CONFIG_VNCSERVER_SCREENWIDTH 320
#endif
#ifndef CONFIG_VNCSERVER_SCREENHEIGHT
# define CONFIG_VNCSERVER_SCREENHEIGHT 240
#endif
#ifndef CONFIG_VNCSERVER_NAME
# define CONFIG_VNCSERVER_NAME "NuttX"
#endif
#ifndef CONFIG_VNCSERVER_PRIO
# define CONFIG_VNCSERVER_PRIO 100
#endif
#ifndef CONFIG_VNCSERVER_STACKSIZE
# define CONFIG_VNCSERVER_STACKSIZE 2048
#endif
#ifndef CONFIG_VNCSERVER_UPDATER_PRIO
# define CONFIG_VNCSERVER_UPDATER_PRIO 100
#endif
#ifndef CONFIG_VNCSERVER_UPDATER_STACKSIZE
# define CONFIG_VNCSERVER_UPDATER_STACKSIZE 2048
#endif
#ifndef CONFIG_VNCSERVER_INBUFFER_SIZE
# define CONFIG_VNCSERVER_INBUFFER_SIZE 80
#endif
#ifndef CONFIG_VNCSERVER_NUPDATES
# define CONFIG_VNCSERVER_NUPDATES 48
#endif
#ifndef CONFIG_VNCSERVER_UPDATE_BUFSIZE
# define CONFIG_VNCSERVER_UPDATE_BUFSIZE 4096
#endif
#define VNCSERVER_UPDATE_BUFSIZE \
(CONFIG_VNCSERVER_UPDATE_BUFSIZE + SIZEOF_RFB_FRAMEBUFFERUPDATE_S(0))
/* Local framebuffer characteristics in bytes */
#define RFB_BYTESPERPIXEL ((RFB_BITSPERPIXEL + 7) >> 3)
#define RFB_STRIDE (RFB_BYTESPERPIXEL * CONFIG_VNCSERVER_SCREENWIDTH)
#define RFB_SIZE (RFB_STRIDE * CONFIG_VNCSERVER_SCREENHEIGHT)
/* RFB Port Number */
#define RFB_PORT_BASE 5900
#define RFB_MAX_DISPLAYS CONFIG_VNCSERVER_NDISPLAYS
#define RFB_DISPLAY_PORT(d) (RFB_PORT_BASE + (d))
/* Miscellaneous */
#ifndef MIN
# define MIN(a,b) (((a) < (b)) ? (a) : (b))
#endif
#ifndef MAX
# define MAX(a,b) (((a) > (b)) ? (a) : (b))
#endif
/* Debug */
#ifdef CONFIG_VNCSERVER_UPDATE_DEBUG
# ifdef CONFIG_CPP_HAVE_VARARGS
# define upderr(format, ...) _err(format, ##__VA_ARGS__)
# define updinfo(format, ...) _info(format, ##__VA_ARGS__)
# define updinfo(format, ...) _info(format, ##__VA_ARGS__)
# else
# define upderr _err
# define updwarn _warn
# define updinfo _info
# endif
#else
# ifdef CONFIG_CPP_HAVE_VARARGS
# define upderr(x...)
# define updwarn(x...)
# define updinfo(x...)
# else
# define upderr (void)
# define updwarn (void)
# define updinfo (void)
# endif
#endif
/****************************************************************************
* Public Types
****************************************************************************/
/* This enumeration indicates the state of the VNC server */
enum vnc_server_e
{
VNCSERVER_UNINITIALIZED = 0, /* Initial state */
VNCSERVER_INITIALIZED, /* State structured initialized, but not connected */
VNCSERVER_CONNECTED, /* Connect to a client, but not yet configured */
VNCSERVER_CONFIGURED, /* Configured and ready to transfer graphics */
VNCSERVER_RUNNING, /* Running and activly transferring graphics */
VNCSERVER_STOPPING, /* The updater has been asked to stop */
VNCSERVER_STOPPED /* The updater has stopped */
};
/* This structure is used to queue FrameBufferUpdate event. It includes a
* pointer to support singly linked list.
*/
struct vnc_fbupdate_s
{
FAR struct vnc_fbupdate_s *flink;
bool whupd; /* True: whole screen update */
struct nxgl_rect_s rect; /* The enqueued update rectangle */
};
struct vnc_session_s
{
/* Connection data */
struct socket listen; /* Listen socket */
struct socket connect; /* Connected socket */
volatile uint8_t state; /* See enum vnc_server_e */
volatile uint8_t nwhupd; /* Number of whole screen updates queued */
volatile bool change; /* True: Frambebuffer data change since last whole screen update */
/* Display geometry and color characteristics */
uint8_t display; /* Display number (for debug) */
volatile uint8_t colorfmt; /* Remote color format (See include/nuttx/fb.h) */
volatile uint8_t bpp; /* Remote bits per pixel */
volatile bool bigendian; /* True: Remote expect data in big-endian format */
volatile bool rre; /* True: Remote supports RRE encoding */
FAR uint8_t *fb; /* Allocated local frame buffer */
/* VNC client input support */
vnc_kbdout_t kbdout; /* Callout when keyboard input is received */
vnc_mouseout_t mouseout; /* Callout when keyboard input is received */
FAR void *arg; /* Argument that accompanies the callouts */
/* Updater information */
pthread_t updater; /* Updater thread ID */
/* Update list information */
struct vnc_fbupdate_s updpool[CONFIG_VNCSERVER_NUPDATES];
sq_queue_t updfree;
sq_queue_t updqueue;
sem_t freesem;
sem_t queuesem;
/* I/O buffers for misc network send/receive */
uint8_t inbuf[CONFIG_VNCSERVER_INBUFFER_SIZE];
uint8_t outbuf[VNCSERVER_UPDATE_BUFSIZE];
};
/* This structure is used to communicate start-up status between the server
* the framebuffer driver.
*/
struct fb_startup_s
{
sem_t fbinit; /* Wait for session creation */
sem_t fbconnect; /* Wait for client connection */
int16_t result; /* OK: successfully initialized */
};
/* The size of the color type in the local framebuffer */
#if defined(CONFIG_VNCSERVER_COLORFMT_RGB8)
typedef uint8_t lfb_color_t;
#elif defined(CONFIG_VNCSERVER_COLORFMT_RGB16)
typedef uint16_t lfb_color_t;
#elif defined(CONFIG_VNCSERVER_COLORFMT_RGB32)
typedef uint32_t lfb_color_t;
#else
# error Unspecified/unsupported color format
#endif
/* Color conversion function pointer types */
typedef CODE uint8_t (*vnc_convert8_t) (lfb_color_t rgb);
typedef CODE uint16_t (*vnc_convert16_t)(lfb_color_t rgb);
typedef CODE uint32_t (*vnc_convert32_t)(lfb_color_t rgb);
/****************************************************************************
* Public Data
****************************************************************************/
#ifdef __cplusplus
#define EXTERN extern "C"
extern "C"
{
#else
#define EXTERN extern
#endif
/* Given a display number as an index, the following array can be used to
* look-up the session structure for that display.
*/
EXTERN FAR struct vnc_session_s *g_vnc_sessions[RFB_MAX_DISPLAYS];
/* Used to synchronize the server thread with the framebuffer driver. */
EXTERN struct fb_startup_s g_fbstartup[RFB_MAX_DISPLAYS];
/****************************************************************************
* Public Function Prototypes
****************************************************************************/
/****************************************************************************
* Name: vnc_server
*
* Description:
* The VNC server daemon. This daemon is implemented as a kernel thread.
*
* Input Parameters:
* Standard kernel thread arguments (all ignored)
*
* Returned Value:
* This function does not return.
*
****************************************************************************/
int vnc_server(int argc, FAR char *argv[]);
/****************************************************************************
* Name: vnc_negotiate
*
* Description:
* Perform the VNC initialization sequence after the client has successfully
* connected to the server. Negotiate security, framebuffer and color
* properties.
*
* Input Parameters:
* session - An instance of the session structure.
*
* Returned Value:
* Returns zero (OK) on success; a negated errno value on failure.
*
****************************************************************************/
int vnc_negotiate(FAR struct vnc_session_s *session);
/****************************************************************************
* Name: vnc_client_pixelformat
*
* Description:
* A Client-to-Sever SetPixelFormat message has been received. We need to
* immediately switch the output color format that we generate.
*
* Input Parameters:
* session - An instance of the session structure.
* pixelfmt - The pixel from from the received SetPixelFormat message
*
* Returned Value:
* Returns zero (OK) on success; a negated errno value on failure.
*
****************************************************************************/
int vnc_client_pixelformat(FAR struct vnc_session_s *session,
FAR struct rfb_pixelfmt_s *pixelfmt);
/****************************************************************************
* Name: vnc_client_encodings
*
* Description:
* Pick out any mutually supported encodings from the Client-to-Server
* SetEncodings message
*
* Input Parameters:
* session - An instance of the session structure.
* encodings - The received SetEncodings message
*
* Returned Value:
* At present, always returns OK
*
****************************************************************************/
int vnc_client_encodings(FAR struct vnc_session_s *session,
FAR struct rfb_setencodings_s *encodings);
/****************************************************************************
* Name: vnc_start_updater
*
* Description:
* Start the updater thread
*
* Input Parameters:
* session - An instance of the session structure.
*
* Returned Value:
* Zero (OK) is returned on success; a negated errno value is returned on
* any failure.
*
****************************************************************************/
int vnc_start_updater(FAR struct vnc_session_s *session);
/****************************************************************************
* Name: vnc_stop_updater
*
* Description:
* Stop the updater thread
*
* Input Parameters:
* session - An instance of the session structure.
*
* Returned Value:
* Zero (OK) is returned on success; a negated errno value is returned on
* any failure.
*
****************************************************************************/
int vnc_stop_updater(FAR struct vnc_session_s *session);
/****************************************************************************
* Name: vnc_update_rectangle
*
* Description:
* Queue an update of the specified rectangular region on the display.
*
* Input Parameters:
* session - An instance of the session structure.
* rect - The rectanglular region to be updated.
* change - True: Frame buffer data has changed
*
* Returned Value:
* Zero (OK) is returned on success; a negated errno value is returned on
* any failure.
*
****************************************************************************/
int vnc_update_rectangle(FAR struct vnc_session_s *session,
FAR const struct nxgl_rect_s *rect,
bool change);
/****************************************************************************
* Name: vnc_receiver
*
* Description:
* This function handles all Client-to-Server messages.
*
* Input Parameters:
* session - An instance of the session structure.
*
* Returned Value:
* At present, always returns OK
*
****************************************************************************/
int vnc_receiver(FAR struct vnc_session_s *session);
/****************************************************************************
* Name: vnc_rre
*
* Description:
* This function does not really do RRE encoding. It just checks if the
* update region is one color then uses the RRE encoding format to send
* the constant color rectangle.
*
* Input Parameters:
* session - An instance of the session structure.
* rect - Describes the rectangle in the local framebuffer.
*
* Returned Value:
* Zero is returned if RRE coding was not performed (but not error was)
* encountered. Otherwise, the size of the framebuffer update message
* is returned on success or a negated errno value is returned on failure
* that indicates the nature of the failure. A failure is only
* returned in cases of a network failure and unexpected internal failures.
*
****************************************************************************/
int vnc_rre(FAR struct vnc_session_s *session, FAR struct nxgl_rect_s *rect);
/****************************************************************************
* Name: vnc_raw
*
* Description:
* As a fallback, send the framebuffer update using the RAW encoding which
* must be supported by all VNC clients.
*
* Input Parameters:
* session - An instance of the session structure.
* rect - Describes the rectangle in the local framebuffer.
*
* Returned Value:
* Zero (OK) on success; A negated errno value is returned on failure that
* indicates the nature of the failure. A failure is only returned
* in cases of a network failure and unexpected internal failures.
*
****************************************************************************/
int vnc_raw(FAR struct vnc_session_s *session, FAR struct nxgl_rect_s *rect);
/****************************************************************************
* Name: vnc_key_map
*
* Description:
* Map the receive X11 keysym into something understood by NuttX and route
* that through NX to the appropriate window.
*
* Input Parameters:
* session - An instance of the session structure.
* keysym - The X11 keysym value (see include/nuttx/inputx11_keysymdef)
* keydown - True: Key pressed; False: Key released
*
* Returned Value:
* None
*
****************************************************************************/
#ifdef CONFIG_NX_KBD
void vnc_key_map(FAR struct vnc_session_s *session, uint16_t keysym,
bool keydown);
#endif
/****************************************************************************
* Name: vnc_convert_rgbNN
*
* Description:
* Convert the native framebuffer color format (either RGB8 3:3:2,
* RGB16 5:6:5, or RGB32 8:8:8) to the remote framebuffer color format
* (either RGB8 2:2:2, RGB8 3:3:2, RGB16 5:5:5, RGB16 5:6:5, or RGB32
* 8:8:8)
*
* Input Parameters:
* pixel - The src color in local framebuffer format.
*
* Returned Value:
* The pixel in the remote framebuffer color format.
*
****************************************************************************/
uint8_t vnc_convert_rgb8_222(lfb_color_t rgb);
uint8_t vnc_convert_rgb8_332(lfb_color_t rgb);
uint16_t vnc_convert_rgb16_555(lfb_color_t rgb);
uint16_t vnc_convert_rgb16_565(lfb_color_t rgb);
uint32_t vnc_convert_rgb32_888(lfb_color_t rgb);
/****************************************************************************
* Name: vnc_colors
*
* Description:
* Test the update rectangle to see if it contains complex colors. If it
* contains only a few colors, then it may be a candidate for some type
* run-length encoding.
*
* Input Parameters:
* session - An instance of the session structure.
* rect - The update region in the local frame buffer.
* maxcolors - The maximum number of colors that should be returned. This
* currently cannot exceed eight.
* colors - The top 'maxcolors' most frequency colors are returned.
*
* Returned Value:
* The number of valid colors in the colors[] array are returned, the
* first entry being the most frequent. A negated errno value is returned
* if the colors cannot be determined. This would be the case if the color
* depth is > 8 and there are more than 'maxcolors' colors in the update
* rectangle.
*
****************************************************************************/
int vnc_colors(FAR struct vnc_session_s *session, FAR struct nxgl_rect_s *rect,
unsigned int maxcolors, FAR lfb_color_t *colors);
#undef EXTERN
#ifdef __cplusplus
}
#endif
#endif /* __GRAPHICS_VNC_SERVER_VNC_SERVER_H */
| 33.250417 | 98 | 0.610132 | [
"geometry"
] |
04f5c06c5ee6ee4340c6e175d8bc18ce6c7afa8b | 28,735 | c | C | libs/iovm/source/IoList.c | Titousensei/io | 828f8236c08ed53e9b8506cd4e60d5dd6d1ee18a | [
"BSD-3-Clause"
] | 1 | 2016-05-03T02:45:42.000Z | 2016-05-03T02:45:42.000Z | libs/iovm/source/IoList.c | mistydemeo/io | ebc0c53a89fe720c6cf77f2ef7a72767d799c057 | [
"BSD-3-Clause"
] | null | null | null | libs/iovm/source/IoList.c | mistydemeo/io | ebc0c53a89fe720c6cf77f2ef7a72767d799c057 | [
"BSD-3-Clause"
] | null | null | null |
//metadoc List category Core
//metadoc List copyright Steve Dekorte 2002
//metadoc List license BSD revised
/*metadoc List description
A mutable array of values. The first index is 0.
*/
#include "IoList.h"
#include "IoObject.h"
#include "IoState.h"
#include "IoCFunction.h"
#include "IoSeq.h"
#include "IoState.h"
#include "IoNumber.h"
#include "IoBlock.h"
#include <math.h>
static const char *protoId = "List";
#define DATA(self) ((List *)(IoObject_dataPointer(self)))
IoTag *IoList_newTag(void *state)
{
IoTag *tag = IoTag_newWithName_(protoId);
IoTag_state_(tag, state);
IoTag_freeFunc_(tag, (IoTagFreeFunc *)IoList_free);
IoTag_cloneFunc_(tag, (IoTagCloneFunc *)IoList_rawClone);
IoTag_markFunc_(tag, (IoTagMarkFunc *)IoList_mark);
IoTag_compareFunc_(tag, (IoTagCompareFunc *)IoList_compare);
//IoTag_writeToStreamFunc_(tag, (IoTagWriteToStreamFunc *)IoList_writeToStream_);
//IoTag_readFromStreamFunc_(tag, (IoTagReadFromStreamFunc *)IoList_readFromStream_);
return tag;
}
/*
void IoList_writeToStream_(IoList *self, BStream *stream)
{
List *list = DATA(self);
BStream_writeTaggedInt32_(stream, List_size(list));
LIST_FOREACH(list, i, v,
BStream_writeTaggedInt32_(stream, IoObject_pid((IoObject *)v));
);
}
void IoList_readFromStream_(IoList *self, BStream *stream)
{
List *list = DATA(self);
int i, max = BStream_readTaggedInt32(stream);
for (i = 0; i < max; i ++)
{
int pid = BStream_readTaggedInt32(stream);
IoObject *v = IoState_objectWithPid_(IOSTATE, pid);
List_append_(list, v);
}
}
*/
IoList *IoList_proto(void *state)
{
IoMethodTable methodTable[] = {
{"with", IoList_with},
// access
{"indexOf", IoList_indexOf},
{"contains", IoList_contains},
{"containsIdenticalTo", IoList_containsIdenticalTo},
{"capacity", IoList_capacity},
{"size", IoList_size},
// mutation
{"setSize", IoList_setSize},
{"removeAll", IoList_removeAll},
{"appendSeq", IoList_appendSeq},
{"append", IoList_append},
{"prepend", IoList_prepend},
{"push", IoList_append},
{"appendIfAbsent", IoList_appendIfAbsent},
{"remove", IoList_remove},
{"pop", IoList_pop},
{"atInsert", IoList_atInsert},
{"at", IoList_at},
{"atPut", IoList_atPut},
{"removeAt", IoList_removeAt},
{"swapIndices", IoList_swapIndices},
{"preallocateToSize", IoList_preallocateToSize},
{"first", IoList_first},
{"last", IoList_last},
{"slice", IoList_slice},
{"sliceInPlace", IoList_sliceInPlace},
{"sortInPlace", IoList_sortInPlace},
{"sortInPlaceBy", IoList_sortInPlaceBy},
{"foreach", IoList_foreach},
{"reverseInPlace", IoList_reverseInPlace},
{"reverseForeach", IoList_reverseForeach},
{"asEncodedList", IoList_asEncodedList},
{"fromEncodedList", IoList_fromEncodedList},
{"join", IoList_join},
{NULL, NULL},
};
IoObject *self = IoObject_new(state);
IoObject_tag_(self, IoList_newTag(state));
IoObject_setDataPointer_(self, List_new());
IoState_registerProtoWithId_((IoState *)state, self, protoId);
IoObject_addMethodTable_(self, methodTable);
return self;
}
IoList *IoList_rawClone(IoList *proto)
{
IoObject *self = IoObject_rawClonePrimitive(proto);
IoObject_tag_(self, IoObject_tag(proto));
IoObject_setDataPointer_(self, List_clone(DATA(proto)));
return self;
}
IoList *IoList_new(void *state)
{
IoObject *proto = IoState_protoWithId_((IoState *)state, protoId);
return IOCLONE(proto);
}
IoList *IoList_newWithList_(void *state, List *list)
{
IoList *self = IoList_new(state);
//printf("IoList_newWithList_ %p %p\n", (void *)self, (void *)list);
List_free(IoObject_dataPointer(self));
IoObject_setDataPointer_(self, list);
return self;
}
void IoList_free(IoList *self)
{
if (NULL == DATA(self))
{
printf("IoList_free(%p) already freed\n", (void *)self);
exit(1);
}
//printf("IoList_free(%p) List_free(%p)\n", (void *)self, (void *)DATA(self));
List_free(DATA(self));
IoObject_setDataPointer_(self, NULL);
}
void IoList_mark(IoList *self)
{
LIST_FOREACH(DATA(self), i, item, IoObject_shouldMark(item));
}
int IoList_compare(IoList *self, IoList *otherList)
{
if (!ISLIST(otherList))
{
return IoObject_defaultCompare(self, otherList);
}
else
{
size_t s1 = List_size(DATA(self));
size_t s2 = List_size(DATA(otherList));
size_t i;
if (s1 != s2)
{
return s1 > s2 ? 1 : -1;
}
for (i = 0; i < s1; i ++)
{
IoObject *v1 = LIST_AT_(DATA(self), i);
IoObject *v2 = LIST_AT_(DATA(otherList), i);
int c = IoObject_compare(v1, v2);
if (c)
{
return c;
}
}
}
return 0;
}
List *IoList_rawList(IoList *self)
{
return DATA(self);
}
IoObject *IoList_rawAt_(IoList *self, int i)
{
return List_at_(DATA(self), i);
}
void IoList_rawAt_put_(IoList *self, int i, IoObject *v)
{
List_at_put_(DATA(self), i, IOREF(v));
IoObject_isDirty_(self, 1);
}
void IoList_rawAppend_(IoList *self, IoObject *v)
{
List_append_(DATA(self), IOREF(v));
IoObject_isDirty_(self, 1);
}
void IoList_rawRemove_(IoList *self, IoObject *v)
{
List_remove_(DATA(self), IOREF(v));
IoObject_isDirty_(self, 1);
}
void IoList_rawAddBaseList_(IoList *self, List *otherList)
{
List *list = DATA(self);
LIST_FOREACH(otherList, i, v, List_append_(list, IOREF((IoObject *)v)); );
IoObject_isDirty_(self, 1);
}
void IoList_rawAddIoList_(IoList *self, IoList *other)
{
IoList_rawAddBaseList_(self, DATA(other));
IoObject_isDirty_(self, 1);
}
size_t IoList_rawSize(IoList *self)
{
return List_size(DATA(self));
}
long IoList_rawIndexOf_(IoList *self, IoObject *v)
{
List *list = DATA(self);
LIST_FOREACH(list, i, item,
if (IoObject_compare(v, (IoObject *)item) == 0)
{
return i;
}
);
return -1;
}
void IoList_checkIndex(IoList *self, IoMessage *m, char allowsExtending, int index, const char *methodName)
{
size_t max = List_size(DATA(self));
if (allowsExtending)
{
max += 1;
}
if (index < 0 || index >= max)
{
IoState_error_(IOSTATE, m, "index out of bounds\n");
}
}
// immutable --------------------------------------------------------
IO_METHOD(IoList, with)
{
/*doc List with(anObject, ...)
Returns a new List containing the arguments.
*/
int n, argCount = (int)IoMessage_argCount(m);
IoList *ioList = IOCLONE(self);
for (n = 0; n < argCount; n ++)
{
IoObject *v = IoMessage_locals_valueArgAt_(m, locals, n);
IoList_rawAppend_(ioList, v);
}
return ioList;
}
IO_METHOD(IoList, indexOf)
{
/*doc List indexOf(anObject)
Returns the index of the first occurrence of anObject
in the receiver. Returns Nil if the receiver doesn't contain anObject.
*/
int count = IoMessage_argCount(m);
IOASSERT(count, "remove requires at least one argument");
{
IoObject *v = IoMessage_locals_valueArgAt_(m, locals, 0);
size_t i = IoList_rawIndexOf_(self, v);
return i == -1 ? IONIL(self) :
(IoObject *)IONUMBER(IoList_rawIndexOf_(self, v));
}
}
IO_METHOD(IoList, contains)
{
/*doc List contains(anObject)
Returns true if the receiver contains anObject, otherwise returns false.
*/
IoObject *v = IoMessage_locals_valueArgAt_(m, locals, 0);
return IOBOOL(self, IoList_rawIndexOf_(self, v) != -1);
}
IO_METHOD(IoList, containsIdenticalTo)
{
/*doc List containsIdenticalTo(anObject)
Returns true if the receiver contains a value identical to anObject, otherwise returns false.
*/
IoObject *v = IoMessage_locals_valueArgAt_(m, locals, 0);
return IOBOOL(self, List_contains_(DATA(self), v) != 0);
}
IO_METHOD(IoList, capacity)
{
/*doc List capacity
Returns the number of potential elements the receiver can hold before it needs to grow.
*/
return IONUMBER(DATA(self)->memSize / sizeof(void *));
}
IO_METHOD(IoList, size)
{
/*doc List size
Returns the number of items in the receiver.
*/
return IONUMBER(List_size(DATA(self)));
}
IO_METHOD(IoList, at)
{
/*doc List at(index)
Returns the value at index. Returns Nil if the index is out of bounds.
*/
int index = IoMessage_locals_intArgAt_(m, locals, 0);
IoObject *v;
/*IoList_checkIndex(self, m, 0, index, "Io List at");*/
v = List_at_(DATA(self), index);
return (v) ? v : IONIL(self);
}
IO_METHOD(IoList, first)
{
/*doc List first(optionalSize)
Returns the first item or Nil if the list is empty.
If optionalSize is provided, that number of the first items in the list are returned.
*/
IoObject *result = List_at_(DATA(self), 0);
return result ? result : IONIL(self);
}
IO_METHOD(IoList, last)
{
/*doc List last(optionalSize)
Returns the last item or Nil if the list is empty.
If optionalSize is provided, that number of the last items in the list are returned.
*/
IoObject *result = List_at_(DATA(self), List_size(DATA(self)) - 1);
return result ? result : IONIL(self);
}
void IoList_sliceIndex(int *index, int step, int size)
{
/* The following code mimics Python's slicing behaviour. */
if (*index < 0)
{
*index += size;
if (*index < 0)
{
*index = (step < 0) ? -1 : 0;
}
}
else if (*index >= size)
{
*index = (step < 0) ? size - 1 : size;
}
}
void IoList_sliceArguments(IoList *self, IoObject *locals, IoMessage *m, int *start, int *end, int *step)
{
size_t size = IoList_rawSize(self);
/* Checking step, before any other arguments. */
*step = (IoMessage_argCount(m) == 3) ? IoMessage_locals_intArgAt_(m, locals, 2) : 1;
IOASSERT(step != 0, "step cannot be equal to zero");
*start = IoMessage_locals_intArgAt_(m, locals, 0);
*end = (IoMessage_argCount(m) >= 2) ? IoMessage_locals_intArgAt_(m, locals, 1) : (int)size;
/* Fixing slice index values. */
IoList_sliceIndex(start, *step, (int)size);
IoList_sliceIndex(end, *step, (int)size);
}
IO_METHOD(IoList, slice)
{
/*doc List slice(startIndex, endIndex, step)
Returns a new string containing the subset of the receiver
from the startIndex to the endIndex. The endIndex argument
is optional. If not given, it is assumed to be the end of the string.
Step argument is also optional and defaults to 1, if not given.
However, since Io supports positional arguments only, you need to
explicitly specify endIndex, if you need a custom step.
*/
List *list;
int start, end, step;
IoList_sliceArguments(self, locals, m, &start, &end, &step);
if ((step > 0 && end < start) ||
(step < 0 && end > start))
{
return IoList_new(IOSTATE);
}
else
{
list = List_cloneSlice(DATA(self), start, end, step);
return IoList_newWithList_(IOSTATE, list);
}
}
IO_METHOD(IoList, sliceInPlace)
{
/*doc List sliceInPlace(startIndex, endIndex, step)
Returns the receiver containing the subset of the
receiver from the startIndex to the endIndex. The endIndex argument
is optional. If not given, it is assumed to be the end of the string.
Step argument is also optional and defaults to 1.
*/
int start, end, step;
IoList_sliceArguments(self, locals, m, &start, &end, &step);
if ((step > 0 && end < start) ||
(step < 0 && end > start))
{
return IoList_new(IOSTATE);
}
else
{
List_sliceInPlace(DATA(self), start, end, step);
}
IoObject_isDirty_(self, 1);
return self;
}
IO_METHOD(IoList, each)
{
IoState *state = IOSTATE;
IoObject *result = IONIL(self);
IoMessage *doMessage = IoMessage_rawArgAt_(m, 0);
List *list = DATA(self);
IoState_pushRetainPool(state);
LIST_SAFEFOREACH(list, i, v,
IoState_clearTopPool(state);
result = IoMessage_locals_performOn_(doMessage, locals, (IoObject *)v);
if (IoState_handleStatus(IOSTATE)) goto done;
);
done:
IoState_popRetainPoolExceptFor_(state, result);
return result;
}
IO_METHOD(IoList, foreach)
{
/*doc List foreach(optionalIndex, value, message)
Loops over the list values setting the specified index and
value slots and executing the message. Returns the result of the last
execution of the message. Example:
<p>
<pre>
list(1, 2, 3) foreach(i, v, writeln(i, " = ", v))
list(1, 2, 3) foreach(v, writeln(v))</pre>
*/
IoState *state = IOSTATE;
IoObject *result = IONIL(self);
IoSymbol *slotName = NULL;
IoSymbol *valueName;
IoMessage *doMessage;
List *list = DATA(self);
if (IoMessage_argCount(m) == 1)
{
return IoList_each(self, locals, m);
}
IoMessage_foreachArgs(m, self, &slotName, &valueName, &doMessage);
IoState_pushRetainPool(state);
if (slotName)
{
LIST_SAFEFOREACH(list, i, value,
IoState_clearTopPool(state);
IoObject_setSlot_to_(locals, slotName, IONUMBER(i));
IoObject_setSlot_to_(locals, valueName, (IoObject *)value);
result = IoMessage_locals_performOn_(doMessage, locals, locals);
if (IoState_handleStatus(IOSTATE)) goto done;
);
}
else
{
LIST_SAFEFOREACH(list, i, value,
IoState_clearTopPool(state);
IoObject_setSlot_to_(locals, valueName, (IoObject *)value);
result = IoMessage_locals_performOn_(doMessage, locals, locals);
if (IoState_handleStatus(IOSTATE)) goto done;
);
}
done:
IoState_popRetainPoolExceptFor_(state, result);
return result;
}
IO_METHOD(IoList, reverseForeach)
{
/*doc List reverseForeach(index, value, message)
Same as foreach, but in reverse order.
*/
IoState *state = IOSTATE;
IoObject *result = IONIL(self);
IoSymbol *slotName, *valueName;
IoMessage *doMessage;
long i;
IoMessage_foreachArgs(m, self, &slotName, &valueName, &doMessage);
IoState_pushRetainPool(state);
for (i = List_size(DATA(self)) - 1; i >= 0; i --)
{
IoState_clearTopPool(state);
{
IoObject *value = (IoObject *)LIST_AT_(DATA(self), i);
if (slotName)
{
IoObject_setSlot_to_(locals, slotName, IONUMBER(i));
}
IoObject_setSlot_to_(locals, valueName, value);
result = IoMessage_locals_performOn_(doMessage, locals, locals);
if (IoState_handleStatus(IOSTATE))
{
goto done;
}
}
if(i > List_size(DATA(self)) - 1) { i = List_size(DATA(self)) - 1; }
}
done:
IoState_popRetainPoolExceptFor_(state, result);
return result;
}
// mutable --------------------------------------------------------
IO_METHOD(IoList, appendIfAbsent)
{
/*doc List appendIfAbsent(anObject)
Adds each value not already contained by the receiver, returns self.
*/
int n;
for (n = 0; n < IoMessage_argCount(m); n ++)
{
IoObject *v = IoMessage_locals_valueArgAt_(m, locals, n);
if (IoList_rawIndexOf_(self, v) == -1)
{
IoState_stackRetain_(IOSTATE, v);
List_append_(DATA(self), IOREF(v));
IoObject_isDirty_(self, 1);
}
}
return self;
}
IO_METHOD(IoList, appendSeq)
{
/*doc List appendSeq(aList1, aList2, ...)
Add the items in the lists to the receiver. Returns self.
*/
int i;
for (i = 0; i < IoMessage_argCount(m); i ++)
{
IoObject *other = IoMessage_locals_valueArgAt_(m, locals, i);
IOASSERT(ISLIST(other), "requires List objects as arguments");
if (other == self)
{
IoState_error_(IOSTATE, m, "can't add a list to itself\n");
}
else
{
List *selfList = DATA(self);
List *otherList = DATA(other);
size_t i, max = List_size(otherList);
for (i = 0; i < max; i ++)
{
IoObject *v = List_at_(otherList, i);
List_append_(selfList, IOREF(v));
}
IoObject_isDirty_(self, 1);
}
}
return self;
}
IO_METHOD(IoList, append)
{
/*doc List append(anObject1, anObject2, ...)
Appends the arguments to the end of the list. Returns self.
*/
/*doc List push(anObject1, anObject2, ...)
Same as add(anObject1, anObject2, ...).
*/
int n;
IOASSERT(IoMessage_argCount(m), "requires at least one argument");
for (n = 0; n < IoMessage_argCount(m); n ++)
{
IoObject *v = IoMessage_locals_valueArgAt_(m, locals, n);
List_append_(DATA(self), IOREF(v));
}
IoObject_isDirty_(self, 1);
return self;
}
IO_METHOD(IoList, prepend)
{
/*doc List prepend(anObject1, anObject2, ...)
Inserts the values at the beginning of the list. Returns self.
*/
int n;
IOASSERT(IoMessage_argCount(m), "requires at least one argument");
for (n = 0; n < IoMessage_argCount(m); n ++)
{
IoObject *v = IoMessage_locals_valueArgAt_(m, locals, n);
List_at_insert_(DATA(self), 0, IOREF(v));
}
IoObject_isDirty_(self, 1);
return self;
}
IO_METHOD(IoList, remove)
{
/*doc List remove(anObject, ...)
Removes all occurrences of the arguments from the receiver. Returns self.
*/
int count = IoMessage_argCount(m);
int j;
IOASSERT(count, "requires at least one argument");
for (j = 0; j < count; j++)
{
IoObject *v = IoMessage_locals_valueArgAt_(m, locals, j);
// a quick pass to remove values with equal pointers
List_remove_(DATA(self), v);
// slow pass to remove values that match comparision test
for (;;)
{
long i = IoList_rawIndexOf_(self, v);
if (i == -1)
{
break;
}
List_removeIndex_(DATA(self), i);
}
}
IoObject_isDirty_(self, 1);
return self;
}
IO_METHOD(IoList, pop)
{
/*doc List pop
Returns the last item in the list and removes it
from the receiver. Returns nil if the receiver is empty.
*/
IoObject *v = List_pop(DATA(self));
return (v) ? v : IONIL(self);
}
IO_METHOD(IoList, atInsert)
{
/*doc List atInsert(index, anObject)
Inserts anObject at the index specified by index.
Adds anObject if the index equals the current count of the receiver.
Raises an exception if the index is out of bounds. Returns self.
*/
int index = IoMessage_locals_intArgAt_(m, locals, 0);
IoObject *v = IoMessage_locals_valueArgAt_(m, locals, 1);
IoList_checkIndex(self, m, 1, index, "List atInsert");
List_at_insert_(DATA(self), index, IOREF(v));
IoObject_isDirty_(self, 1);
return self;
}
IO_METHOD(IoList, removeAt)
{
/*doc List removeAt(index)
Removes the item at the specified index and returns the value removed.
Raises an exception if the index is out of bounds.
*/
int index = IoMessage_locals_intArgAt_(m, locals, 0);
IoObject *v = List_at_(DATA(self), index);
IoList_checkIndex(self, m, 0, index, "Io List atInsert");
List_removeIndex_(DATA(self), index);
IoObject_isDirty_(self, 1);
return (v) ? v : IONIL(self);
}
void IoList_rawAtPut(IoList *self, int i, IoObject *v)
{
while (List_size(DATA(self)) < i) /* not efficient */
{
List_append_(DATA(self), IONIL(self));
}
List_at_put_(DATA(self), i, IOREF(v));
IoObject_isDirty_(self, 1);
}
IO_METHOD(IoList, atPut)
{
/*doc List atPut(index, anObject)
Replaces the existing value at index with anObject.
Raises an exception if the index is out of bounds. Returns self.
*/
int index = IoMessage_locals_intArgAt_(m, locals, 0);
IoObject *v = IoMessage_locals_valueArgAt_(m, locals, 1);
IoList_checkIndex(self, m, 0, index, "Io List atPut");
IoList_rawAtPut(self, index, v);
IoObject_isDirty_(self, 1);
return self;
}
IO_METHOD(IoList, setSize)
{
/*doc List setSize
Sets the size of the receiver by either removing excess items or adding nils as needed.
*/
List *list = DATA(self);
size_t newSize = IoMessage_locals_sizetArgAt_(m, locals, 0);
size_t oldSize = List_size(list);
if(newSize < oldSize)
{
List_setSize_(list, newSize);
}
else
{
size_t i, max = newSize - oldSize;
IoObject *nilObject = IONIL(self);
for(i = 0; i < max; i ++)
{
List_append_(list, nilObject);
}
}
IoObject_isDirty_(self, 1);
return self;
}
IO_METHOD(IoList, removeAll)
{
/*doc List empty
Removes all items from the receiver.
*/
List_removeAll(DATA(self));
IoObject_isDirty_(self, 1);
return self;
}
IO_METHOD(IoList, swapIndices)
{
/*doc List swapIndices(index1, index2)
Exchanges the object at index1 with the object at index2.
Raises an exception if either index is out of bounds. Returns self.
*/
int i = IoMessage_locals_intArgAt_(m, locals, 0);
int j = IoMessage_locals_intArgAt_(m, locals, 1);
IoList_checkIndex(self, m, 0, i, "List swapIndices");
IoList_checkIndex(self, m, 0, j, "List swapIndices");
List_swap_with_(DATA(self), i, j);
IoObject_isDirty_(self, 1);
return self;
}
IO_METHOD(IoList, reverseInPlace)
{
/*doc List reverseInPlace
Reverses the ordering of all the items in the receiver. Returns self.
*/
List_reverseInPlace(DATA(self));
IoObject_isDirty_(self, 1);
return self;
}
IO_METHOD(IoList, preallocateToSize)
{
/*doc List preallocateToSize(aNumber)
Preallocates array memory to hold aNumber number of items.
*/
int newSize = IoMessage_locals_intArgAt_(m, locals, 0);
List_preallocateToSize_(DATA(self), newSize);
return self;
}
// sorting -----------------------------------------------
typedef struct
{
IoState *state;
IoObject *locals;
IoMessage *exp;
List *list;
} MSortContext;
int MSortContext_compareForSort(MSortContext *self, void *ap, void *bp)
{
IoObject *a = *(void **)ap;
IoObject *b = *(void **)bp;
int r;
IoState_pushRetainPool(self->state);
a = IoMessage_locals_performOn_(self->exp, self->locals, a);
b = IoMessage_locals_performOn_(self->exp, self->locals, b);
r = IoObject_compare(a, b);
IoState_popRetainPool(self->state);
return r;
}
IO_METHOD(IoList, sortInPlace)
{
/*doc List sortInPlace(optionalExpression)
Sorts the list using the compare method on the items. Returns self.
If an optionalExpression is provided, the sort is done on the result of the evaluation
of the optionalExpression on each value.
*/
if (IoMessage_argCount(m) == 0)
{
List_qsort(DATA(self), (ListSortCallback *)IoObject_sortCompare);
}
else
{
MSortContext sc;
MSortContext *sortContext = ≻
sortContext->state = IOSTATE;
sortContext->locals = locals;
sortContext->exp = IoMessage_rawArgAt_(m, 0);
List_qsort_r(DATA(self), sortContext, (ListSortRCallback *)MSortContext_compareForSort);
}
IoObject_isDirty_(self, 1);
return self;
}
typedef struct
{
IoState *state;
IoObject *locals;
IoBlock *block;
IoMessage *blockMsg;
IoMessage *argMsg1;
IoMessage *argMsg2;
List *list;
} SortContext;
int SortContext_compareForSort(SortContext *self, void *ap, void *bp)
{
IoObject *a = *(void **)ap;
IoObject *b = *(void **)bp;
IoObject *cr;
IoState_pushRetainPool(self->state);
IoMessage_rawSetCachedResult_(self->argMsg1, a);
IoMessage_rawSetCachedResult_(self->argMsg2, b);
cr = IoBlock_activate(self->block, self->locals, self->locals, self->blockMsg, self->locals);
IoState_popRetainPool(self->state);
return ISFALSE(cr) ? 1 : -1;
}
IO_METHOD(IoList, sortInPlaceBy)
{
/*doc List sortInPlaceBy(aBlock)
Sort the list using aBlock as the compare function. Returns self.
*/
SortContext sc;
SortContext *sortContext = ≻
sc.state = IOSTATE;
sc.locals = locals;
sc.block = IoMessage_locals_blockArgAt_(m, locals, 0);
sc.blockMsg = IoMessage_new(IOSTATE);
sc.argMsg1 = IoMessage_new(IOSTATE);
sc.argMsg2 = IoMessage_new(IOSTATE);
IoMessage_addArg_(sortContext->blockMsg, sortContext->argMsg1);
IoMessage_addArg_(sortContext->blockMsg, sortContext->argMsg2);
List_qsort_r(DATA(self), &sc, (ListSortRCallback *)SortContext_compareForSort);
IoObject_isDirty_(self, 1);
return self;
}
typedef enum
{
IOLIST_ENCODING_TYPE_NIL,
IOLIST_ENCODING_TYPE_NUMBER,
IOLIST_ENCODING_TYPE_SYMBOL,
IOLIST_ENCODING_TYPE_REFERENCE,
} IOLIST_ENCODING_TYPE;
IO_METHOD(IoList, asEncodedList)
{
/*doc List asEncodedList
Returns a Sequence with an encoding of the list.
Nil, Number and Symbol objects are copied into the encoding, for other object
types, referenceIdForObject(item) will be called to request a reference id for
the object.
Also see: List fromEncodedList.
*/
UArray *u = UArray_new();
List *list = IoList_rawList(self);
size_t i, max = List_size(list);
IoMessage *rm = IOSTATE->referenceIdForObjectMessage;
UArray_setItemType_(u, CTYPE_uint8_t);
UArray_setEncoding_(u, CENCODING_NUMBER);
//UArray_appendBytes_size_(u, " ", 4); // placeholder until we know the size
for(i = 0; i < max; i ++)
{
IoObject *item = List_at_(list, i);
if(ISNIL(item))
{
UArray_appendLong_(u, IOLIST_ENCODING_TYPE_NIL);
UArray_appendLong_(u, 0);
UArray_appendLong_(u, 0);
}
else if(ISNUMBER(item))
{
float32_t f = CNUMBER(item);
UArray_appendLong_(u, IOLIST_ENCODING_TYPE_NUMBER);
UArray_appendLong_(u, CENCODING_NUMBER);
UArray_appendLong_(u, CTYPE_float32_t);
UArray_appendBytes_size_(u, (const uint8_t *)(&f), sizeof(float32_t));
}
else if(ISSEQ(item))
{
UArray *s = IoSeq_rawUArray(item);
uint32_t size = (uint32_t)UArray_size(s);
UArray_appendLong_(u, IOLIST_ENCODING_TYPE_SYMBOL);
UArray_appendLong_(u, UArray_encoding(s));
UArray_appendLong_(u, UArray_itemType(s));
UArray_appendBytes_size_(u, (const uint8_t *)(&size), sizeof(uint32_t));
UArray_appendBytes_size_(u, (const uint8_t *)UArray_bytes(s), UArray_sizeInBytes(s));
}
else
{
IoObject *result;
IoMessage_setCachedArg_to_(rm, 0, item);
result = IoObject_perform(locals, locals, rm);
IoMessage_setCachedArg_to_(rm, 0, IONIL(self));
IOASSERT(ISNUMBER(result), "referenceIdForObject() must return a Number");
{
uint32_t id = CNUMBER(result);
UArray_appendLong_(u, IOLIST_ENCODING_TYPE_REFERENCE);
UArray_appendLong_(u, 0);
UArray_appendLong_(u, 0);
UArray_appendBytes_size_(u, (const uint8_t *)(&id), sizeof(uint32_t));
}
}
}
return IoSeq_newWithUArray_copy_(IOSTATE, u, 0);
}
IO_METHOD(IoList, fromEncodedList)
{
/*doc List fromEncodedList(aSeq)
Returns a List with the decoded Nils, Symbols and Numbers from the input raw array.
For each object reference encounters, objectForReferenceId(id) will be called to
allow the reference to be resolved.
Also see: List asEncodedList.
*/
IoMessage *rm = IOSTATE->objectForReferenceIdMessage;
IoSeq *s = IoMessage_locals_seqArgAt_(m, locals, 0);
UArray *u = IoSeq_rawUArray(s);
List *list = List_new();
const uint8_t *d = UArray_bytes(u);
size_t uSize = UArray_sizeInBytes(u);
size_t index = 0;
// add bounds checks
while (index <= uSize - 7)
{
uint8_t type = d[index + 0];
uint8_t encoding = d[index + 1];
uint8_t itemType = d[index + 2];
index += 3;
if(type == IOLIST_ENCODING_TYPE_NIL)
{
List_append_(list, IONIL(self));
}
else if(type == IOLIST_ENCODING_TYPE_NUMBER)
{
float32_t f = *((float32_t *)(d + index));
index += sizeof(float32_t);
List_append_(list, IONUMBER(f));
}
else if(type == IOLIST_ENCODING_TYPE_SYMBOL)
{
uint32_t size = *((uint32_t *)(d + index));
UArray *o;
index += sizeof(uint32_t);
if (index + size > uSize)
{
List_free(list);
return IONIL(self);
}
o = UArray_newWithData_type_size_copy_((void *)(d + index), itemType, size, 1);
UArray_setEncoding_(o, encoding);
List_append_(list, IoSeq_newWithUArray_copy_(IOSTATE, o, 0));
index += size;
}
else if(type == IOLIST_ENCODING_TYPE_REFERENCE)
{
// should we have a Number reference encoding?
uint32_t id = *((uint32_t *)(d + index));
IoMessage_setCachedArg_to_(rm, 0, IONUMBER(id));
IoMessage_setCachedArg_to_(rm, 0, IONIL(self));
index += sizeof(uint32_t);
{
IoObject *result = IoObject_perform(locals, locals, rm);
List_append_(list, result);
}
}
else
{
IOASSERT(0, "unrecognized encoded type");
}
}
return IoList_newWithList_(IOSTATE, list);
}
IO_METHOD(IoList, join)
{
/*doc List join(optionalSeparator)
Returns a String with the elements of the receiver concatenated into one String.
If optionalSeparator is provided, it is used to separate the concatenated strings.
This operation does not respect string encodings.
*/
List *items = IoList_rawList(self);
size_t itemCount = List_size(items);
IoSeq *separator = IoMessage_locals_seqArgAt_(m, locals, 0);
UArray *out = UArray_new();
int totalSize = 0;
int hasSeparator = !ISNIL(separator);
size_t separatorSize = hasSeparator ? IOSEQ_LENGTH(separator) : 0;
uint8_t *bytes;
IOASSERT(ISSEQ(separator), "separator must be of type Sequence");
LIST_FOREACH(items, i, v,
if(!ISSEQ(v))
{
//printf("type: %s\n", IoObject_name(v));
IOASSERT(ISSEQ(v), "values must be of type Sequence");
}
totalSize += IoSeq_rawSizeInBytes(v);
//printf("UArray_sizeInBytes(v): %i\n", (int) IoSeq_rawSizeInBytes(v));
if(hasSeparator) totalSize += separatorSize;
)
if(hasSeparator) totalSize -= separatorSize;
//printf("separatorSize: %i\n", (int) separatorSize);
//printf("totalSize: %i\n", (int) totalSize);
UArray_sizeTo_(out, totalSize+1);
bytes = UArray_mutableBytes(out);
LIST_FOREACH(items, i, v,
size_t vsize = IoSeq_rawSizeInBytes(v);
memcpy((char *)bytes, (char *)IoSeq_rawBytes(v), (int)vsize);
bytes += vsize;
if(hasSeparator && i != itemCount-1)
{
memcpy(bytes, (char *)IoSeq_rawBytes(separator), separatorSize);
bytes += separatorSize;
}
)
return IoSeq_newWithUArray_copy_(IOSTATE, out, 0);
}
| 23.806959 | 107 | 0.693788 | [
"object"
] |
04f89caef9c4926c40092aed725db848adc2379e | 6,604 | c | C | datasets/linux-4.11-rc3/arch/x86/kernel/espfix_64.c | yijunyu/demo-fast | 11c0c84081a3181494b9c469bda42a313c457ad2 | [
"BSD-2-Clause"
] | 55 | 2019-12-20T03:25:14.000Z | 2022-01-16T07:19:47.000Z | datasets/linux-4.11-rc3/arch/x86/kernel/espfix_64.c | yijunyu/demo-vscode-fast | 11c0c84081a3181494b9c469bda42a313c457ad2 | [
"BSD-2-Clause"
] | 2 | 2020-11-02T08:01:00.000Z | 2022-03-27T02:59:18.000Z | datasets/linux-4.11-rc3/arch/x86/kernel/espfix_64.c | yijunyu/demo-vscode-fast | 11c0c84081a3181494b9c469bda42a313c457ad2 | [
"BSD-2-Clause"
] | 11 | 2020-08-06T03:59:45.000Z | 2022-02-25T02:31:59.000Z | /* ----------------------------------------------------------------------- *
*
* Copyright 2014 Intel Corporation; author: H. Peter Anvin
*
* This program is free software; you can redistribute it and/or modify it
* under the terms and conditions of the GNU General Public License,
* version 2, as published by the Free Software Foundation.
*
* This program is distributed in the hope 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.
*
* ----------------------------------------------------------------------- */
/*
* The IRET instruction, when returning to a 16-bit segment, only
* restores the bottom 16 bits of the user space stack pointer. This
* causes some 16-bit software to break, but it also leaks kernel state
* to user space.
*
* This works around this by creating percpu "ministacks", each of which
* is mapped 2^16 times 64K apart. When we detect that the return SS is
* on the LDT, we copy the IRET frame to the ministack and use the
* relevant alias to return to userspace. The ministacks are mapped
* readonly, so if the IRET fault we promote #GP to #DF which is an IST
* vector and thus has its own stack; we then do the fixup in the #DF
* handler.
*
* This file sets up the ministacks and the related page tables. The
* actual ministack invocation is in entry_64.S.
*/
#include <linux/init.h>
#include <linux/init_task.h>
#include <linux/kernel.h>
#include <linux/percpu.h>
#include <linux/gfp.h>
#include <linux/random.h>
#include <asm/pgtable.h>
#include <asm/pgalloc.h>
#include <asm/setup.h>
#include <asm/espfix.h>
/*
* Note: we only need 6*8 = 48 bytes for the espfix stack, but round
* it up to a cache line to avoid unnecessary sharing.
*/
#define ESPFIX_STACK_SIZE (8*8UL)
#define ESPFIX_STACKS_PER_PAGE (PAGE_SIZE/ESPFIX_STACK_SIZE)
/* There is address space for how many espfix pages? */
#define ESPFIX_PAGE_SPACE (1UL << (PGDIR_SHIFT-PAGE_SHIFT-16))
#define ESPFIX_MAX_CPUS (ESPFIX_STACKS_PER_PAGE * ESPFIX_PAGE_SPACE)
#if CONFIG_NR_CPUS > ESPFIX_MAX_CPUS
# error "Need more than one PGD for the ESPFIX hack"
#endif
#define PGALLOC_GFP (GFP_KERNEL | __GFP_NOTRACK | __GFP_ZERO)
/* This contains the *bottom* address of the espfix stack */
DEFINE_PER_CPU_READ_MOSTLY(unsigned long, espfix_stack);
DEFINE_PER_CPU_READ_MOSTLY(unsigned long, espfix_waddr);
/* Initialization mutex - should this be a spinlock? */
static DEFINE_MUTEX(espfix_init_mutex);
/* Page allocation bitmap - each page serves ESPFIX_STACKS_PER_PAGE CPUs */
#define ESPFIX_MAX_PAGES DIV_ROUND_UP(CONFIG_NR_CPUS, ESPFIX_STACKS_PER_PAGE)
static void *espfix_pages[ESPFIX_MAX_PAGES];
static __page_aligned_bss pud_t espfix_pud_page[PTRS_PER_PUD]
__aligned(PAGE_SIZE);
static unsigned int page_random, slot_random;
/*
* This returns the bottom address of the espfix stack for a specific CPU.
* The math allows for a non-power-of-two ESPFIX_STACK_SIZE, in which case
* we have to account for some amount of padding at the end of each page.
*/
static inline unsigned long espfix_base_addr(unsigned int cpu)
{
unsigned long page, slot;
unsigned long addr;
page = (cpu / ESPFIX_STACKS_PER_PAGE) ^ page_random;
slot = (cpu + slot_random) % ESPFIX_STACKS_PER_PAGE;
addr = (page << PAGE_SHIFT) + (slot * ESPFIX_STACK_SIZE);
addr = (addr & 0xffffUL) | ((addr & ~0xffffUL) << 16);
addr += ESPFIX_BASE_ADDR;
return addr;
}
#define PTE_STRIDE (65536/PAGE_SIZE)
#define ESPFIX_PTE_CLONES (PTRS_PER_PTE/PTE_STRIDE)
#define ESPFIX_PMD_CLONES PTRS_PER_PMD
#define ESPFIX_PUD_CLONES (65536/(ESPFIX_PTE_CLONES*ESPFIX_PMD_CLONES))
#define PGTABLE_PROT ((_KERNPG_TABLE & ~_PAGE_RW) | _PAGE_NX)
static void init_espfix_random(void)
{
unsigned long rand;
/*
* This is run before the entropy pools are initialized,
* but this is hopefully better than nothing.
*/
if (!arch_get_random_long(&rand)) {
/* The constant is an arbitrary large prime */
rand = rdtsc();
rand *= 0xc345c6b72fd16123UL;
}
slot_random = rand % ESPFIX_STACKS_PER_PAGE;
page_random = (rand / ESPFIX_STACKS_PER_PAGE)
& (ESPFIX_PAGE_SPACE - 1);
}
void __init init_espfix_bsp(void)
{
pgd_t *pgd_p;
/* Install the espfix pud into the kernel page directory */
pgd_p = &init_level4_pgt[pgd_index(ESPFIX_BASE_ADDR)];
pgd_populate(&init_mm, pgd_p, (pud_t *)espfix_pud_page);
/* Randomize the locations */
init_espfix_random();
/* The rest is the same as for any other processor */
init_espfix_ap(0);
}
void init_espfix_ap(int cpu)
{
unsigned int page;
unsigned long addr;
pud_t pud, *pud_p;
pmd_t pmd, *pmd_p;
pte_t pte, *pte_p;
int n, node;
void *stack_page;
pteval_t ptemask;
/* We only have to do this once... */
if (likely(per_cpu(espfix_stack, cpu)))
return; /* Already initialized */
addr = espfix_base_addr(cpu);
page = cpu/ESPFIX_STACKS_PER_PAGE;
/* Did another CPU already set this up? */
stack_page = ACCESS_ONCE(espfix_pages[page]);
if (likely(stack_page))
goto done;
mutex_lock(&espfix_init_mutex);
/* Did we race on the lock? */
stack_page = ACCESS_ONCE(espfix_pages[page]);
if (stack_page)
goto unlock_done;
node = cpu_to_node(cpu);
ptemask = __supported_pte_mask;
pud_p = &espfix_pud_page[pud_index(addr)];
pud = *pud_p;
if (!pud_present(pud)) {
struct page *page = alloc_pages_node(node, PGALLOC_GFP, 0);
pmd_p = (pmd_t *)page_address(page);
pud = __pud(__pa(pmd_p) | (PGTABLE_PROT & ptemask));
paravirt_alloc_pmd(&init_mm, __pa(pmd_p) >> PAGE_SHIFT);
for (n = 0; n < ESPFIX_PUD_CLONES; n++)
set_pud(&pud_p[n], pud);
}
pmd_p = pmd_offset(&pud, addr);
pmd = *pmd_p;
if (!pmd_present(pmd)) {
struct page *page = alloc_pages_node(node, PGALLOC_GFP, 0);
pte_p = (pte_t *)page_address(page);
pmd = __pmd(__pa(pte_p) | (PGTABLE_PROT & ptemask));
paravirt_alloc_pte(&init_mm, __pa(pte_p) >> PAGE_SHIFT);
for (n = 0; n < ESPFIX_PMD_CLONES; n++)
set_pmd(&pmd_p[n], pmd);
}
pte_p = pte_offset_kernel(&pmd, addr);
stack_page = page_address(alloc_pages_node(node, GFP_KERNEL, 0));
pte = __pte(__pa(stack_page) | (__PAGE_KERNEL_RO & ptemask));
for (n = 0; n < ESPFIX_PTE_CLONES; n++)
set_pte(&pte_p[n*PTE_STRIDE], pte);
/* Job is done for this CPU and any CPU which shares this page */
ACCESS_ONCE(espfix_pages[page]) = stack_page;
unlock_done:
mutex_unlock(&espfix_init_mutex);
done:
per_cpu(espfix_stack, cpu) = addr;
per_cpu(espfix_waddr, cpu) = (unsigned long)stack_page
+ (addr & ~PAGE_MASK);
}
| 31.447619 | 78 | 0.713507 | [
"vector"
] |
04fdcb1012d25295d7d83f9ce220398fb1f69fe4 | 3,823 | h | C | aws-cpp-sdk-gamelift/include/aws/gamelift/model/CreateScriptResult.h | irods/aws-sdk-cpp | ea5a4d61a26c1eac41443fb9829e969ebac6e09b | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-gamelift/include/aws/gamelift/model/CreateScriptResult.h | irods/aws-sdk-cpp | ea5a4d61a26c1eac41443fb9829e969ebac6e09b | [
"Apache-2.0"
] | 1 | 2021-10-14T16:57:00.000Z | 2021-10-18T10:47:24.000Z | aws-cpp-sdk-gamelift/include/aws/gamelift/model/CreateScriptResult.h | irods/aws-sdk-cpp | ea5a4d61a26c1eac41443fb9829e969ebac6e09b | [
"Apache-2.0"
] | null | null | null | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/gamelift/GameLift_EXPORTS.h>
#include <aws/gamelift/model/Script.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace GameLift
{
namespace Model
{
class AWS_GAMELIFT_API CreateScriptResult
{
public:
CreateScriptResult();
CreateScriptResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
CreateScriptResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>The newly created script record with a unique script ID and ARN. The new
* script's storage location reflects an Amazon S3 location: (1) If the script was
* uploaded from an S3 bucket under your account, the storage location reflects the
* information that was provided in the <i>CreateScript</i> request; (2) If the
* script file was uploaded from a local zip file, the storage location reflects an
* S3 location controls by the Amazon Web Services service.</p>
*/
inline const Script& GetScript() const{ return m_script; }
/**
* <p>The newly created script record with a unique script ID and ARN. The new
* script's storage location reflects an Amazon S3 location: (1) If the script was
* uploaded from an S3 bucket under your account, the storage location reflects the
* information that was provided in the <i>CreateScript</i> request; (2) If the
* script file was uploaded from a local zip file, the storage location reflects an
* S3 location controls by the Amazon Web Services service.</p>
*/
inline void SetScript(const Script& value) { m_script = value; }
/**
* <p>The newly created script record with a unique script ID and ARN. The new
* script's storage location reflects an Amazon S3 location: (1) If the script was
* uploaded from an S3 bucket under your account, the storage location reflects the
* information that was provided in the <i>CreateScript</i> request; (2) If the
* script file was uploaded from a local zip file, the storage location reflects an
* S3 location controls by the Amazon Web Services service.</p>
*/
inline void SetScript(Script&& value) { m_script = std::move(value); }
/**
* <p>The newly created script record with a unique script ID and ARN. The new
* script's storage location reflects an Amazon S3 location: (1) If the script was
* uploaded from an S3 bucket under your account, the storage location reflects the
* information that was provided in the <i>CreateScript</i> request; (2) If the
* script file was uploaded from a local zip file, the storage location reflects an
* S3 location controls by the Amazon Web Services service.</p>
*/
inline CreateScriptResult& WithScript(const Script& value) { SetScript(value); return *this;}
/**
* <p>The newly created script record with a unique script ID and ARN. The new
* script's storage location reflects an Amazon S3 location: (1) If the script was
* uploaded from an S3 bucket under your account, the storage location reflects the
* information that was provided in the <i>CreateScript</i> request; (2) If the
* script file was uploaded from a local zip file, the storage location reflects an
* S3 location controls by the Amazon Web Services service.</p>
*/
inline CreateScriptResult& WithScript(Script&& value) { SetScript(std::move(value)); return *this;}
private:
Script m_script;
};
} // namespace Model
} // namespace GameLift
} // namespace Aws
| 41.107527 | 106 | 0.711222 | [
"model"
] |
ca01838810a7c61ae6f0638195acd17debc82dfc | 32,694 | h | C | include/Zydis/Internal/SharedData.h | ryan-johnson2/zydis | 92c65f3333b7b1892a25725ea8e9abd1c8ad44ac | [
"MIT"
] | 56 | 2020-11-11T03:07:16.000Z | 2022-03-04T02:56:33.000Z | include/Zydis/Internal/SharedData.h | ryan-johnson2/zydis | 92c65f3333b7b1892a25725ea8e9abd1c8ad44ac | [
"MIT"
] | 3 | 2020-11-12T14:43:03.000Z | 2020-12-13T17:43:48.000Z | include/Zydis/Internal/SharedData.h | ryan-johnson2/zydis | 92c65f3333b7b1892a25725ea8e9abd1c8ad44ac | [
"MIT"
] | 37 | 2020-11-08T00:10:34.000Z | 2022-03-14T21:56:01.000Z | /***************************************************************************************************
Zyan Disassembler Library (Zydis)
Original Author : Florian Bernd
* 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 ZYDIS_INTERNAL_SHAREDDATA_H
#define ZYDIS_INTERNAL_SHAREDDATA_H
#include <Zycore/Defines.h>
#include <Zydis/Mnemonic.h>
#include <Zydis/Register.h>
#include <Zydis/SharedTypes.h>
#include <Zydis/DecoderTypes.h>
#ifdef __cplusplus
extern "C" {
#endif
/* ============================================================================================== */
/* Enums and types */
/* ============================================================================================== */
// MSVC does not like types other than (un-)signed int for bit-fields
#ifdef ZYAN_MSVC
# pragma warning(push)
# pragma warning(disable:4214)
#endif
#pragma pack(push, 1)
/* ---------------------------------------------------------------------------------------------- */
/* Operand definition */
/* ---------------------------------------------------------------------------------------------- */
/**
* Defines the `ZydisSemanticOperandType` enum.
*/
typedef enum ZydisSemanticOperandType_
{
ZYDIS_SEMANTIC_OPTYPE_UNUSED,
ZYDIS_SEMANTIC_OPTYPE_IMPLICIT_REG,
ZYDIS_SEMANTIC_OPTYPE_IMPLICIT_MEM,
ZYDIS_SEMANTIC_OPTYPE_IMPLICIT_IMM1,
ZYDIS_SEMANTIC_OPTYPE_GPR8,
ZYDIS_SEMANTIC_OPTYPE_GPR16,
ZYDIS_SEMANTIC_OPTYPE_GPR32,
ZYDIS_SEMANTIC_OPTYPE_GPR64,
ZYDIS_SEMANTIC_OPTYPE_GPR16_32_64,
ZYDIS_SEMANTIC_OPTYPE_GPR32_32_64,
ZYDIS_SEMANTIC_OPTYPE_GPR16_32_32,
ZYDIS_SEMANTIC_OPTYPE_GPR_ASZ,
ZYDIS_SEMANTIC_OPTYPE_FPR,
ZYDIS_SEMANTIC_OPTYPE_MMX,
ZYDIS_SEMANTIC_OPTYPE_XMM,
ZYDIS_SEMANTIC_OPTYPE_YMM,
ZYDIS_SEMANTIC_OPTYPE_ZMM,
ZYDIS_SEMANTIC_OPTYPE_BND,
ZYDIS_SEMANTIC_OPTYPE_SREG,
ZYDIS_SEMANTIC_OPTYPE_CR,
ZYDIS_SEMANTIC_OPTYPE_DR,
ZYDIS_SEMANTIC_OPTYPE_MASK,
ZYDIS_SEMANTIC_OPTYPE_MEM,
ZYDIS_SEMANTIC_OPTYPE_MEM_VSIBX,
ZYDIS_SEMANTIC_OPTYPE_MEM_VSIBY,
ZYDIS_SEMANTIC_OPTYPE_MEM_VSIBZ,
ZYDIS_SEMANTIC_OPTYPE_IMM,
ZYDIS_SEMANTIC_OPTYPE_REL,
ZYDIS_SEMANTIC_OPTYPE_PTR,
ZYDIS_SEMANTIC_OPTYPE_AGEN,
ZYDIS_SEMANTIC_OPTYPE_MOFFS,
ZYDIS_SEMANTIC_OPTYPE_MIB,
/**
* Maximum value of this enum.
*/
ZYDIS_SEMANTIC_OPTYPE_MAX_VALUE = ZYDIS_SEMANTIC_OPTYPE_MIB,
/**
* The minimum number of bits required to represent all values of this enum.
*/
ZYDIS_SEMANTIC_OPTYPE_REQUIRED_BITS = ZYAN_BITS_TO_REPRESENT(ZYDIS_SEMANTIC_OPTYPE_MAX_VALUE)
} ZydisSemanticOperandType;
/* ---------------------------------------------------------------------------------------------- */
/**
* Defines the `ZydisInternalElementType` enum.
*/
typedef enum ZydisInternalElementType_
{
ZYDIS_IELEMENT_TYPE_INVALID,
ZYDIS_IELEMENT_TYPE_VARIABLE,
ZYDIS_IELEMENT_TYPE_STRUCT,
ZYDIS_IELEMENT_TYPE_INT,
ZYDIS_IELEMENT_TYPE_UINT,
ZYDIS_IELEMENT_TYPE_INT1,
ZYDIS_IELEMENT_TYPE_INT8,
ZYDIS_IELEMENT_TYPE_INT16,
ZYDIS_IELEMENT_TYPE_INT32,
ZYDIS_IELEMENT_TYPE_INT64,
ZYDIS_IELEMENT_TYPE_UINT8,
ZYDIS_IELEMENT_TYPE_UINT16,
ZYDIS_IELEMENT_TYPE_UINT32,
ZYDIS_IELEMENT_TYPE_UINT64,
ZYDIS_IELEMENT_TYPE_UINT128,
ZYDIS_IELEMENT_TYPE_UINT256,
ZYDIS_IELEMENT_TYPE_FLOAT16,
ZYDIS_IELEMENT_TYPE_FLOAT32,
ZYDIS_IELEMENT_TYPE_FLOAT64,
ZYDIS_IELEMENT_TYPE_FLOAT80,
ZYDIS_IELEMENT_TYPE_BCD80,
ZYDIS_IELEMENT_TYPE_CC3,
ZYDIS_IELEMENT_TYPE_CC5,
/**
* Maximum value of this enum.
*/
ZYDIS_IELEMENT_TYPE_MAX_VALUE = ZYDIS_IELEMENT_TYPE_CC5,
/**
* The minimum number of bits required to represent all values of this enum.
*/
ZYDIS_IELEMENT_TYPE_REQUIRED_BITS = ZYAN_BITS_TO_REPRESENT(ZYDIS_IELEMENT_TYPE_MAX_VALUE)
} ZydisInternalElementType;
/* ---------------------------------------------------------------------------------------------- */
/**
* Defines the `ZydisImplicitRegisterType` enum.
*/
typedef enum ZydisImplicitRegisterType_
{
ZYDIS_IMPLREG_TYPE_STATIC,
ZYDIS_IMPLREG_TYPE_GPR_OSZ,
ZYDIS_IMPLREG_TYPE_GPR_ASZ,
ZYDIS_IMPLREG_TYPE_GPR_SSZ,
ZYDIS_IMPLREG_TYPE_IP_ASZ,
ZYDIS_IMPLREG_TYPE_IP_SSZ,
ZYDIS_IMPLREG_TYPE_FLAGS_SSZ,
/**
* Maximum value of this enum.
*/
ZYDIS_IMPLREG_TYPE_MAX_VALUE = ZYDIS_IMPLREG_TYPE_FLAGS_SSZ,
/**
* The minimum number of bits required to represent all values of this enum.
*/
ZYDIS_IMPLREG_TYPE_REQUIRED_BITS = ZYAN_BITS_TO_REPRESENT(ZYDIS_IMPLREG_TYPE_MAX_VALUE)
} ZydisImplicitRegisterType;
/* ---------------------------------------------------------------------------------------------- */
/**
* Defines the `ZydisImplicitMemBase` enum.
*/
typedef enum ZydisImplicitMemBase_
{
ZYDIS_IMPLMEM_BASE_AGPR_REG,
ZYDIS_IMPLMEM_BASE_AGPR_RM,
ZYDIS_IMPLMEM_BASE_AAX,
ZYDIS_IMPLMEM_BASE_ADX,
ZYDIS_IMPLMEM_BASE_ABX,
ZYDIS_IMPLMEM_BASE_ASP,
ZYDIS_IMPLMEM_BASE_ABP,
ZYDIS_IMPLMEM_BASE_ASI,
ZYDIS_IMPLMEM_BASE_ADI,
/**
* Maximum value of this enum.
*/
ZYDIS_IMPLMEM_BASE_MAX_VALUE = ZYDIS_IMPLMEM_BASE_ADI,
/**
* The minimum number of bits required to represent all values of this enum.
*/
ZYDIS_IMPLMEM_BASE_REQUIRED_BITS = ZYAN_BITS_TO_REPRESENT(ZYDIS_IMPLMEM_BASE_MAX_VALUE)
} ZydisImplicitMemBase;
/* ---------------------------------------------------------------------------------------------- */
// MSVC does not correctly execute the `pragma pack(1)` compiler-directive, if we use the correct
// enum types
ZYAN_STATIC_ASSERT(ZYDIS_SEMANTIC_OPTYPE_REQUIRED_BITS <= 8);
ZYAN_STATIC_ASSERT(ZYDIS_OPERAND_VISIBILITY_REQUIRED_BITS <= 8);
ZYAN_STATIC_ASSERT(ZYDIS_OPERAND_ACTION_REQUIRED_BITS <= 8);
ZYAN_STATIC_ASSERT(ZYDIS_IELEMENT_TYPE_REQUIRED_BITS <= 8);
ZYAN_STATIC_ASSERT(ZYDIS_OPERAND_ENCODING_REQUIRED_BITS <= 8);
ZYAN_STATIC_ASSERT(ZYDIS_IMPLREG_TYPE_REQUIRED_BITS <= 8);
ZYAN_STATIC_ASSERT(ZYDIS_REGISTER_REQUIRED_BITS <= 16);
ZYAN_STATIC_ASSERT(ZYDIS_IMPLMEM_BASE_REQUIRED_BITS <= 8);
/**
* Defines the `ZydisOperandDefinition` struct.
*/
typedef struct ZydisOperandDefinition_
{
ZyanU8 type ZYAN_BITFIELD(ZYDIS_SEMANTIC_OPTYPE_REQUIRED_BITS);
ZyanU8 visibility ZYAN_BITFIELD(ZYDIS_OPERAND_VISIBILITY_REQUIRED_BITS);
ZyanU8 actions ZYAN_BITFIELD(ZYDIS_OPERAND_ACTION_REQUIRED_BITS);
ZyanU16 size[3];
ZyanU8 element_type ZYAN_BITFIELD(ZYDIS_IELEMENT_TYPE_REQUIRED_BITS);
union
{
ZyanU8 encoding ZYAN_BITFIELD(ZYDIS_OPERAND_ENCODING_REQUIRED_BITS);
struct
{
ZyanU8 type ZYAN_BITFIELD(ZYDIS_IMPLREG_TYPE_REQUIRED_BITS);
union
{
ZyanU16 reg ZYAN_BITFIELD(ZYDIS_REGISTER_REQUIRED_BITS);
ZyanU8 id ZYAN_BITFIELD(6);
} reg;
} reg;
struct
{
ZyanU8 seg ZYAN_BITFIELD(3);
ZyanU8 base ZYAN_BITFIELD(ZYDIS_IMPLMEM_BASE_REQUIRED_BITS);
} mem;
} op;
} ZydisOperandDefinition;
/* ---------------------------------------------------------------------------------------------- */
/* Instruction definition */
/* ---------------------------------------------------------------------------------------------- */
/**
* Defines the `ZydisReadWriteAction` enum.
*/
typedef enum ZydisReadWriteAction_
{
ZYDIS_RW_ACTION_NONE,
ZYDIS_RW_ACTION_READ,
ZYDIS_RW_ACTION_WRITE,
ZYDIS_RW_ACTION_READWRITE,
/**
* Maximum value of this enum.
*/
ZYDIS_RW_ACTION_MAX_VALUE = ZYDIS_RW_ACTION_READWRITE,
/**
* The minimum number of bits required to represent all values of this enum.
*/
ZYDIS_RW_ACTION_REQUIRED_BITS = ZYAN_BITS_TO_REPRESENT(ZYDIS_RW_ACTION_MAX_VALUE)
} ZydisReadWriteAction;
/* ---------------------------------------------------------------------------------------------- */
/**
* Defines the `ZydisRegisterConstraint` enum.
*/
typedef enum ZydisRegisterConstraint_
{
ZYDIS_REG_CONSTRAINTS_UNUSED,
ZYDIS_REG_CONSTRAINTS_NONE,
ZYDIS_REG_CONSTRAINTS_GPR,
ZYDIS_REG_CONSTRAINTS_SR_DEST,
ZYDIS_REG_CONSTRAINTS_SR,
ZYDIS_REG_CONSTRAINTS_CR,
ZYDIS_REG_CONSTRAINTS_DR,
ZYDIS_REG_CONSTRAINTS_MASK,
ZYDIS_REG_CONSTRAINTS_BND,
ZYDIS_REG_CONSTRAINTS_VSIB,
ZYDIS_REG_CONSTRAINTS_NO_REL,
/**
* Maximum value of this enum.
*/
ZYDIS_REG_CONSTRAINTS_MAX_VALUE = ZYDIS_REG_CONSTRAINTS_NO_REL,
/**
* The minimum number of bits required to represent all values of this enum.
*/
ZYDIS_REG_CONSTRAINTS_REQUIRED_BITS = ZYAN_BITS_TO_REPRESENT(ZYDIS_REG_CONSTRAINTS_MAX_VALUE)
} ZydisRegisterConstraint;
/* ---------------------------------------------------------------------------------------------- */
/**
* Defines the `ZydisInternalVectorLength` enum.
*/
typedef enum ZydisInternalVectorLength_
{
ZYDIS_IVECTOR_LENGTH_DEFAULT,
ZYDIS_IVECTOR_LENGTH_FIXED_128,
ZYDIS_IVECTOR_LENGTH_FIXED_256,
ZYDIS_IVECTOR_LENGTH_FIXED_512,
/**
* Maximum value of this enum.
*/
ZYDIS_IVECTOR_LENGTH_MAX_VALUE = ZYDIS_IVECTOR_LENGTH_FIXED_512,
/**
* The minimum number of bits required to represent all values of this enum.
*/
ZYDIS_IVECTOR_LENGTH_REQUIRED_BITS = ZYAN_BITS_TO_REPRESENT(ZYDIS_IVECTOR_LENGTH_MAX_VALUE)
} ZydisInternalVectorLength;
/* ---------------------------------------------------------------------------------------------- */
/**
* Defines the `ZydisInternalElementSize` enum.
*/
typedef enum ZydisInternalElementSize_
{
ZYDIS_IELEMENT_SIZE_INVALID,
ZYDIS_IELEMENT_SIZE_8,
ZYDIS_IELEMENT_SIZE_16,
ZYDIS_IELEMENT_SIZE_32,
ZYDIS_IELEMENT_SIZE_64,
ZYDIS_IELEMENT_SIZE_128,
/**
* Maximum value of this enum.
*/
ZYDIS_IELEMENT_SIZE_MAX_VALUE = ZYDIS_IELEMENT_SIZE_128,
/**
* The minimum number of bits required to represent all values of this enum.
*/
ZYDIS_IELEMENT_SIZE_REQUIRED_BITS = ZYAN_BITS_TO_REPRESENT(ZYDIS_IELEMENT_SIZE_MAX_VALUE)
} ZydisInternalElementSize;
/* ---------------------------------------------------------------------------------------------- */
/**
* Defines the `ZydisEVEXFunctionality` enum.
*/
typedef enum ZydisEVEXFunctionality_
{
ZYDIS_EVEX_FUNC_INVALID,
/**
* `EVEX.b` enables broadcast functionality.
*/
ZYDIS_EVEX_FUNC_BC,
/**
* `EVEX.b` enables embedded-rounding functionality.
*/
ZYDIS_EVEX_FUNC_RC,
/**
* `EVEX.b` enables sae functionality.
*/
ZYDIS_EVEX_FUNC_SAE,
/**
* Maximum value of this enum.
*/
ZYDIS_EVEX_FUNC_MAX_VALUE = ZYDIS_EVEX_FUNC_SAE,
/**
* The minimum number of bits required to represent all values of this enum.
*/
ZYDIS_EVEX_FUNC_REQUIRED_BITS = ZYAN_BITS_TO_REPRESENT(ZYDIS_EVEX_FUNC_MAX_VALUE)
} ZydisEVEXFunctionality;
/* ---------------------------------------------------------------------------------------------- */
/**
* Defines the `ZydisEVEXTupleType` enum.
*/
typedef enum ZydisEVEXTupleType_
{
ZYDIS_TUPLETYPE_INVALID,
/**
* Full Vector
*/
ZYDIS_TUPLETYPE_FV,
/**
* Half Vector
*/
ZYDIS_TUPLETYPE_HV,
/**
* Full Vector Mem
*/
ZYDIS_TUPLETYPE_FVM,
/**
* Tuple1 Scalar
*/
ZYDIS_TUPLETYPE_T1S,
/**
* Tuple1 Fixed
*/
ZYDIS_TUPLETYPE_T1F,
/**
* Tuple1 4x32
*/
ZYDIS_TUPLETYPE_T1_4X,
/**
* Gather / Scatter
*/
ZYDIS_TUPLETYPE_GSCAT,
/**
* Tuple2
*/
ZYDIS_TUPLETYPE_T2,
/**
* Tuple4
*/
ZYDIS_TUPLETYPE_T4,
/**
* Tuple8
*/
ZYDIS_TUPLETYPE_T8,
/**
* Half Mem
*/
ZYDIS_TUPLETYPE_HVM,
/**
* QuarterMem
*/
ZYDIS_TUPLETYPE_QVM,
/**
* OctMem
*/
ZYDIS_TUPLETYPE_OVM,
/**
* Mem128
*/
ZYDIS_TUPLETYPE_M128,
/**
* MOVDDUP
*/
ZYDIS_TUPLETYPE_DUP,
/**
* Maximum value of this enum.
*/
ZYDIS_TUPLETYPE_MAX_VALUE = ZYDIS_TUPLETYPE_DUP,
/**
* The minimum number of bits required to represent all values of this enum.
*/
ZYDIS_TUPLETYPE_REQUIRED_BITS = ZYAN_BITS_TO_REPRESENT(ZYDIS_TUPLETYPE_MAX_VALUE)
} ZydisEVEXTupleType;
/* ---------------------------------------------------------------------------------------------- */
/**
* Defines the `ZydisMVEXFunctionality` enum.
*/
typedef enum ZydisMVEXFunctionality_
{
/**
* The `MVEX.SSS` value is ignored.
*/
ZYDIS_MVEX_FUNC_IGNORED,
/**
* `MVEX.SSS` must be `000b`.
*/
ZYDIS_MVEX_FUNC_INVALID,
/**
* `MVEX.SSS` controls embedded-rounding functionality.
*/
ZYDIS_MVEX_FUNC_RC,
/**
* `MVEX.SSS` controls sae functionality.
*/
ZYDIS_MVEX_FUNC_SAE,
/**
* No special operation (32bit float elements).
*/
ZYDIS_MVEX_FUNC_F_32,
/**
* No special operation (32bit uint elements).
*/
ZYDIS_MVEX_FUNC_I_32,
/**
* No special operation (64bit float elements).
*/
ZYDIS_MVEX_FUNC_F_64,
/**
* No special operation (64bit uint elements).
*/
ZYDIS_MVEX_FUNC_I_64,
/**
* Sf32(reg) or Si32(reg).
*/
ZYDIS_MVEX_FUNC_SWIZZLE_32,
/**
* Sf64(reg) or Si64(reg).
*/
ZYDIS_MVEX_FUNC_SWIZZLE_64,
/**
* Sf32(mem).
*/
ZYDIS_MVEX_FUNC_SF_32,
/**
* Sf32(mem) broadcast only.
*/
ZYDIS_MVEX_FUNC_SF_32_BCST,
/**
* Sf32(mem) broadcast 4to16 only.
*/
ZYDIS_MVEX_FUNC_SF_32_BCST_4TO16,
/**
* Sf64(mem).
*/
ZYDIS_MVEX_FUNC_SF_64,
/**
* Si32(mem).
*/
ZYDIS_MVEX_FUNC_SI_32,
/**
* Si32(mem) broadcast only.
*/
ZYDIS_MVEX_FUNC_SI_32_BCST,
/**
* Si32(mem) broadcast 4to16 only.
*/
ZYDIS_MVEX_FUNC_SI_32_BCST_4TO16,
/**
* Si64(mem).
*/
ZYDIS_MVEX_FUNC_SI_64,
/**
* Uf32.
*/
ZYDIS_MVEX_FUNC_UF_32,
/**
* Uf64.
*/
ZYDIS_MVEX_FUNC_UF_64,
/**
* Ui32.
*/
ZYDIS_MVEX_FUNC_UI_32,
/**
* Ui64.
*/
ZYDIS_MVEX_FUNC_UI_64,
/**
* Df32.
*/
ZYDIS_MVEX_FUNC_DF_32,
/**
* Df64.
*/
ZYDIS_MVEX_FUNC_DF_64,
/**
* Di32.
*/
ZYDIS_MVEX_FUNC_DI_32,
/**
* Di64.
*/
ZYDIS_MVEX_FUNC_DI_64,
/**
* Maximum value of this enum.
*/
ZYDIS_MVEX_FUNC_MAX_VALUE = ZYDIS_MVEX_FUNC_DI_64,
/**
* The minimum number of bits required to represent all values of this enum.
*/
ZYDIS_MVEX_FUNC_REQUIRED_BITS = ZYAN_BITS_TO_REPRESENT(ZYDIS_MVEX_FUNC_MAX_VALUE)
} ZydisMVEXFunctionality;
/* ---------------------------------------------------------------------------------------------- */
/**
* Defines the `ZydisVEXStaticBroadcast` enum.
*/
typedef enum ZydisVEXStaticBroadcast
{
ZYDIS_VEX_STATIC_BROADCAST_NONE,
ZYDIS_VEX_STATIC_BROADCAST_1_TO_2,
ZYDIS_VEX_STATIC_BROADCAST_1_TO_4,
ZYDIS_VEX_STATIC_BROADCAST_1_TO_8,
ZYDIS_VEX_STATIC_BROADCAST_1_TO_16,
ZYDIS_VEX_STATIC_BROADCAST_1_TO_32,
ZYDIS_VEX_STATIC_BROADCAST_2_TO_4,
/**
* Maximum value of this enum.
*/
ZYDIS_VEX_STATIC_BROADCAST_MAX_VALUE = ZYDIS_VEX_STATIC_BROADCAST_2_TO_4,
/**
* The minimum number of bits required to represent all values of this enum.
*/
ZYDIS_VEX_STATIC_BROADCAST_REQUIRED_BITS =
ZYAN_BITS_TO_REPRESENT(ZYDIS_VEX_STATIC_BROADCAST_MAX_VALUE)
} ZydisVEXStaticBroadcast;
/* ---------------------------------------------------------------------------------------------- */
/**
* Defines the `ZydisEVEXStaticBroadcast` enum.
*/
typedef enum ZydisEVEXStaticBroadcast_
{
ZYDIS_EVEX_STATIC_BROADCAST_NONE,
ZYDIS_EVEX_STATIC_BROADCAST_1_TO_2,
ZYDIS_EVEX_STATIC_BROADCAST_1_TO_4,
ZYDIS_EVEX_STATIC_BROADCAST_1_TO_8,
ZYDIS_EVEX_STATIC_BROADCAST_1_TO_16,
ZYDIS_EVEX_STATIC_BROADCAST_1_TO_32,
ZYDIS_EVEX_STATIC_BROADCAST_1_TO_64,
ZYDIS_EVEX_STATIC_BROADCAST_2_TO_4,
ZYDIS_EVEX_STATIC_BROADCAST_2_TO_8,
ZYDIS_EVEX_STATIC_BROADCAST_2_TO_16,
ZYDIS_EVEX_STATIC_BROADCAST_4_TO_8,
ZYDIS_EVEX_STATIC_BROADCAST_4_TO_16,
ZYDIS_EVEX_STATIC_BROADCAST_8_TO_16,
/**
* Maximum value of this enum.
*/
ZYDIS_EVEX_STATIC_BROADCAST_MAX_VALUE = ZYDIS_EVEX_STATIC_BROADCAST_8_TO_16,
/**
* The minimum number of bits required to represent all values of this enum.
*/
ZYDIS_EVEX_STATIC_BROADCAST_REQUIRED_BITS =
ZYAN_BITS_TO_REPRESENT(ZYDIS_EVEX_STATIC_BROADCAST_MAX_VALUE)
} ZydisEVEXStaticBroadcast;
/* ---------------------------------------------------------------------------------------------- */
/**
* Defines the `ZydisMVEXStaticBroadcast` enum.
*/
typedef enum ZydisMVEXStaticBroadcast_
{
ZYDIS_MVEX_STATIC_BROADCAST_NONE,
ZYDIS_MVEX_STATIC_BROADCAST_1_TO_8,
ZYDIS_MVEX_STATIC_BROADCAST_1_TO_16,
ZYDIS_MVEX_STATIC_BROADCAST_4_TO_8,
ZYDIS_MVEX_STATIC_BROADCAST_4_TO_16,
/**
* Maximum value of this enum.
*/
ZYDIS_MVEX_STATIC_BROADCAST_MAX_VALUE = ZYDIS_MVEX_STATIC_BROADCAST_4_TO_16,
/**
* The minimum number of bits required to represent all values of this enum.
*/
ZYDIS_MVEX_STATIC_BROADCAST_REQUIRED_BITS =
ZYAN_BITS_TO_REPRESENT(ZYDIS_MVEX_STATIC_BROADCAST_MAX_VALUE)
} ZydisMVEXStaticBroadcast;
/* ---------------------------------------------------------------------------------------------- */
/**
* Defines the `ZydisMaskPolicy` enum.
*/
typedef enum ZydisMaskPolicy_
{
ZYDIS_MASK_POLICY_INVALID,
/**
* The instruction accepts mask-registers other than the default-mask (K0), but
* does not require them.
*/
ZYDIS_MASK_POLICY_ALLOWED,
/**
* The instruction requires a mask-register other than the default-mask (K0).
*/
ZYDIS_MASK_POLICY_REQUIRED,
/**
* The instruction does not allow a mask-register other than the default-mask (K0).
*/
ZYDIS_MASK_POLICY_FORBIDDEN,
/**
* Maximum value of this enum.
*/
ZYDIS_MASK_POLICY_MAX_VALUE = ZYDIS_MASK_POLICY_FORBIDDEN,
/**
* The minimum number of bits required to represent all values of this enum.
*/
ZYDIS_MASK_POLICY_REQUIRED_BITS = ZYAN_BITS_TO_REPRESENT(ZYDIS_MASK_POLICY_MAX_VALUE)
} ZydisMaskPolicy;
/* ---------------------------------------------------------------------------------------------- */
/**
* Defines the `ZydisMaskOverride` enum.
*/
typedef enum ZydisMaskOverride_
{
ZYDIS_MASK_OVERRIDE_DEFAULT,
ZYDIS_MASK_OVERRIDE_ZEROING,
ZYDIS_MASK_OVERRIDE_CONTROL,
/**
* Maximum value of this enum.
*/
ZYDIS_MASK_OVERRIDE_MAX_VALUE = ZYDIS_MASK_OVERRIDE_CONTROL,
/**
* The minimum number of bits required to represent all values of this enum.
*/
ZYDIS_MASK_OVERRIDE_REQUIRED_BITS = ZYAN_BITS_TO_REPRESENT(ZYDIS_MASK_OVERRIDE_MAX_VALUE)
} ZydisMaskOverride;
/* ---------------------------------------------------------------------------------------------- */
// MSVC does not correctly execute the `pragma pack(1)` compiler-directive, if we use the correct
// enum types
ZYAN_STATIC_ASSERT(ZYDIS_MNEMONIC_REQUIRED_BITS <= 16);
ZYAN_STATIC_ASSERT(ZYDIS_CATEGORY_REQUIRED_BITS <= 8);
ZYAN_STATIC_ASSERT(ZYDIS_ISA_SET_REQUIRED_BITS <= 8);
ZYAN_STATIC_ASSERT(ZYDIS_ISA_EXT_REQUIRED_BITS <= 8);
ZYAN_STATIC_ASSERT(ZYDIS_BRANCH_TYPE_REQUIRED_BITS <= 8);
ZYAN_STATIC_ASSERT(ZYDIS_EXCEPTION_CLASS_REQUIRED_BITS <= 8);
ZYAN_STATIC_ASSERT(ZYDIS_REG_CONSTRAINTS_REQUIRED_BITS <= 8);
ZYAN_STATIC_ASSERT(ZYDIS_RW_ACTION_REQUIRED_BITS <= 8);
#ifndef ZYDIS_MINIMAL_MODE
# define ZYDIS_INSTRUCTION_DEFINITION_BASE \
ZyanU16 mnemonic ZYAN_BITFIELD(ZYDIS_MNEMONIC_REQUIRED_BITS); \
ZyanU8 operand_count ZYAN_BITFIELD( 4); \
ZyanU16 operand_reference ZYAN_BITFIELD(15); \
ZyanU8 operand_size_map ZYAN_BITFIELD( 3); \
ZyanU8 address_size_map ZYAN_BITFIELD( 2); \
ZyanU8 flags_reference ZYAN_BITFIELD( 7); \
ZyanBool requires_protected_mode ZYAN_BITFIELD( 1); \
ZyanU8 category ZYAN_BITFIELD(ZYDIS_CATEGORY_REQUIRED_BITS); \
ZyanU8 isa_set ZYAN_BITFIELD(ZYDIS_ISA_SET_REQUIRED_BITS); \
ZyanU8 isa_ext ZYAN_BITFIELD(ZYDIS_ISA_EXT_REQUIRED_BITS); \
ZyanU8 branch_type ZYAN_BITFIELD(ZYDIS_BRANCH_TYPE_REQUIRED_BITS); \
ZyanU8 exception_class ZYAN_BITFIELD(ZYDIS_EXCEPTION_CLASS_REQUIRED_BITS); \
ZyanU8 constr_REG ZYAN_BITFIELD(ZYDIS_REG_CONSTRAINTS_REQUIRED_BITS); \
ZyanU8 constr_RM ZYAN_BITFIELD(ZYDIS_REG_CONSTRAINTS_REQUIRED_BITS); \
ZyanU8 cpu_state ZYAN_BITFIELD(ZYDIS_RW_ACTION_REQUIRED_BITS); \
ZyanU8 fpu_state ZYAN_BITFIELD(ZYDIS_RW_ACTION_REQUIRED_BITS); \
ZyanU8 xmm_state ZYAN_BITFIELD(ZYDIS_RW_ACTION_REQUIRED_BITS)
#else
# define ZYDIS_INSTRUCTION_DEFINITION_BASE \
ZyanU16 mnemonic ZYAN_BITFIELD(ZYDIS_MNEMONIC_REQUIRED_BITS); \
ZyanU8 operand_size_map ZYAN_BITFIELD( 3); \
ZyanU8 address_size_map ZYAN_BITFIELD( 2); \
ZyanBool requires_protected_mode ZYAN_BITFIELD( 1); \
ZyanU8 constr_REG ZYAN_BITFIELD(ZYDIS_REG_CONSTRAINTS_REQUIRED_BITS); \
ZyanU8 constr_RM ZYAN_BITFIELD(ZYDIS_REG_CONSTRAINTS_REQUIRED_BITS)
#endif
#define ZYDIS_INSTRUCTION_DEFINITION_BASE_VECTOR \
ZYDIS_INSTRUCTION_DEFINITION_BASE; \
ZyanU8 constr_NDSNDD ZYAN_BITFIELD(ZYDIS_REG_CONSTRAINTS_REQUIRED_BITS)
#define ZYDIS_INSTRUCTION_DEFINITION_BASE_VECTOR_INTEL \
ZYDIS_INSTRUCTION_DEFINITION_BASE_VECTOR; \
ZyanBool is_gather ZYAN_BITFIELD( 1)
/**
* Defines the `ZydisInstructionDefinition` struct.
*/
typedef struct ZydisInstructionDefinition_
{
ZYDIS_INSTRUCTION_DEFINITION_BASE;
} ZydisInstructionDefinition;
/**
* Defines the `ZydisInstructionDefinitionLEGACY` struct.
*/
typedef struct ZydisInstructionDefinitionLEGACY_
{
ZYDIS_INSTRUCTION_DEFINITION_BASE;
#ifndef ZYDIS_MINIMAL_MODE
ZyanBool is_privileged ZYAN_BITFIELD( 1);
#endif
ZyanBool accepts_LOCK ZYAN_BITFIELD( 1);
#ifndef ZYDIS_MINIMAL_MODE
ZyanBool accepts_REP ZYAN_BITFIELD( 1);
ZyanBool accepts_REPEREPZ ZYAN_BITFIELD( 1);
ZyanBool accepts_REPNEREPNZ ZYAN_BITFIELD( 1);
ZyanBool accepts_BOUND ZYAN_BITFIELD( 1);
ZyanBool accepts_XACQUIRE ZYAN_BITFIELD( 1);
ZyanBool accepts_XRELEASE ZYAN_BITFIELD( 1);
ZyanBool accepts_hle_without_lock ZYAN_BITFIELD( 1);
ZyanBool accepts_branch_hints ZYAN_BITFIELD( 1);
ZyanBool accepts_segment ZYAN_BITFIELD( 1);
#endif
} ZydisInstructionDefinitionLEGACY;
/**
* Defines the `ZydisInstructionDefinition3DNOW` struct.
*/
typedef struct ZydisInstructionDefinition3DNOW_
{
ZYDIS_INSTRUCTION_DEFINITION_BASE;
} ZydisInstructionDefinition3DNOW;
/**
* Defines the `ZydisInstructionDefinitionXOP` struct.
*/
typedef struct ZydisInstructionDefinitionXOP_
{
ZYDIS_INSTRUCTION_DEFINITION_BASE_VECTOR;
} ZydisInstructionDefinitionXOP;
// MSVC does not correctly execute the `pragma pack(1)` compiler-directive, if we use the correct
// enum types
ZYAN_STATIC_ASSERT(ZYDIS_VEX_STATIC_BROADCAST_REQUIRED_BITS <= 8);
/**
* Defines the `ZydisInstructionDefinitionVEX` struct.
*/
typedef struct ZydisInstructionDefinitionVEX_
{
ZYDIS_INSTRUCTION_DEFINITION_BASE_VECTOR_INTEL;
#ifndef ZYDIS_MINIMAL_MODE
ZyanU8 broadcast ZYAN_BITFIELD(ZYDIS_VEX_STATIC_BROADCAST_REQUIRED_BITS);
#endif
} ZydisInstructionDefinitionVEX;
#ifndef ZYDIS_DISABLE_AVX512
// MSVC does not correctly execute the `pragma pack(1)` compiler-directive, if we use the correct
// enum types
ZYAN_STATIC_ASSERT(ZYDIS_IVECTOR_LENGTH_REQUIRED_BITS <= 8);
ZYAN_STATIC_ASSERT(ZYDIS_TUPLETYPE_REQUIRED_BITS <= 8);
ZYAN_STATIC_ASSERT(ZYDIS_IELEMENT_SIZE_REQUIRED_BITS <= 8);
ZYAN_STATIC_ASSERT(ZYDIS_EVEX_FUNC_REQUIRED_BITS <= 8);
ZYAN_STATIC_ASSERT(ZYDIS_MASK_POLICY_REQUIRED_BITS <= 8);
ZYAN_STATIC_ASSERT(ZYDIS_MASK_OVERRIDE_REQUIRED_BITS <= 8);
ZYAN_STATIC_ASSERT(ZYDIS_EVEX_STATIC_BROADCAST_REQUIRED_BITS <= 8);
/**
* Defines the `ZydisInstructionDefinitionEVEX` struct.
*/
typedef struct ZydisInstructionDefinitionEVEX_
{
ZYDIS_INSTRUCTION_DEFINITION_BASE_VECTOR_INTEL;
#ifndef ZYDIS_MINIMAL_MODE
ZyanU8 vector_length ZYAN_BITFIELD(ZYDIS_IVECTOR_LENGTH_REQUIRED_BITS);
ZyanU8 tuple_type ZYAN_BITFIELD(ZYDIS_TUPLETYPE_REQUIRED_BITS);
ZyanU8 element_size ZYAN_BITFIELD(ZYDIS_IELEMENT_SIZE_REQUIRED_BITS);
ZyanU8 functionality ZYAN_BITFIELD(ZYDIS_EVEX_FUNC_REQUIRED_BITS);
#endif
ZyanU8 mask_policy ZYAN_BITFIELD(ZYDIS_MASK_POLICY_REQUIRED_BITS);
ZyanBool accepts_zero_mask ZYAN_BITFIELD( 1);
#ifndef ZYDIS_MINIMAL_MODE
ZyanU8 mask_override ZYAN_BITFIELD(ZYDIS_MASK_OVERRIDE_REQUIRED_BITS);
ZyanU8 broadcast ZYAN_BITFIELD(ZYDIS_EVEX_STATIC_BROADCAST_REQUIRED_BITS);
#endif
} ZydisInstructionDefinitionEVEX;
#endif
#ifndef ZYDIS_DISABLE_KNC
// MSVC does not correctly execute the `pragma pack(1)` compiler-directive, if we use the correct
// enum types
ZYAN_STATIC_ASSERT(ZYDIS_MVEX_FUNC_REQUIRED_BITS <= 8);
ZYAN_STATIC_ASSERT(ZYDIS_MASK_POLICY_REQUIRED_BITS <= 8);
ZYAN_STATIC_ASSERT(ZYDIS_MVEX_STATIC_BROADCAST_REQUIRED_BITS <= 8);
/**
* Defines the `ZydisInstructionDefinitionMVEX` struct.
*/
typedef struct ZydisInstructionDefinitionMVEX_
{
ZYDIS_INSTRUCTION_DEFINITION_BASE_VECTOR_INTEL;
ZyanU8 functionality ZYAN_BITFIELD(ZYDIS_MVEX_FUNC_REQUIRED_BITS);
ZyanU8 mask_policy ZYAN_BITFIELD(ZYDIS_MASK_POLICY_REQUIRED_BITS);
#ifndef ZYDIS_MINIMAL_MODE
ZyanBool has_element_granularity ZYAN_BITFIELD( 1);
ZyanU8 broadcast ZYAN_BITFIELD(ZYDIS_MVEX_STATIC_BROADCAST_REQUIRED_BITS);
#endif
} ZydisInstructionDefinitionMVEX;
#endif
/* ---------------------------------------------------------------------------------------------- */
/* Accessed CPU flags */
/* ---------------------------------------------------------------------------------------------- */
typedef struct ZydisAccessedFlags_
{
ZydisCPUFlagAction action[ZYDIS_CPUFLAG_MAX_VALUE + 1];
} ZydisAccessedFlags;
/* ---------------------------------------------------------------------------------------------- */
#pragma pack(pop)
#ifdef ZYAN_MSVC
# pragma warning(pop)
#endif
/* ============================================================================================== */
/* Functions */
/* ============================================================================================== */
/* ---------------------------------------------------------------------------------------------- */
/* Instruction definition */
/* ---------------------------------------------------------------------------------------------- */
/**
* Returns the instruction-definition with the given `encoding` and `id`.
*
* @param encoding The instruction-encoding.
* @param id The definition-id.
* @param definition A pointer to the variable that receives a pointer to the instruction-
* definition.
*/
ZYDIS_NO_EXPORT void ZydisGetInstructionDefinition(ZydisInstructionEncoding encoding,
ZyanU16 id, const ZydisInstructionDefinition** definition);
/* ---------------------------------------------------------------------------------------------- */
/* Operand definition */
/* ---------------------------------------------------------------------------------------------- */
#ifndef ZYDIS_MINIMAL_MODE
/**
* Returns the the operand-definitions for the given instruction-`definition`.
*
* @param definition A pointer to the instruction-definition.
* @param operand A pointer to the variable that receives a pointer to the first operand-
* definition of the instruction.
*
* @return The number of operands for the given instruction-definition.
*/
ZYDIS_NO_EXPORT ZyanU8 ZydisGetOperandDefinitions(const ZydisInstructionDefinition* definition,
const ZydisOperandDefinition** operand);
#endif
/* ---------------------------------------------------------------------------------------------- */
/* Element info */
/* ---------------------------------------------------------------------------------------------- */
#ifndef ZYDIS_MINIMAL_MODE
/**
* Returns the actual type and size of an internal element-type.
*
* @param element The internal element type.
* @param type The actual element type.
* @param size The element size.
*/
ZYDIS_NO_EXPORT void ZydisGetElementInfo(ZydisInternalElementType element, ZydisElementType* type,
ZydisElementSize* size);
#endif
/* ---------------------------------------------------------------------------------------------- */
/* Accessed CPU flags */
/* ---------------------------------------------------------------------------------------------- */
#ifndef ZYDIS_MINIMAL_MODE
/**
* Returns the the operand-definitions for the given instruction-`definition`.
*
* @param definition A pointer to the instruction-definition.
* @param flags A pointer to the variable that receives the `ZydisAccessedFlags` struct.
*
* @return `ZYAN_TRUE`, if the instruction accesses any flags, or `ZYAN_FALSE`, if not.
*/
ZYDIS_NO_EXPORT ZyanBool ZydisGetAccessedFlags(const ZydisInstructionDefinition* definition,
const ZydisAccessedFlags** flags);
#endif
/* ---------------------------------------------------------------------------------------------- */
/* ============================================================================================== */
#ifdef __cplusplus
}
#endif
#endif /* ZYDIS_INTERNAL_SHAREDDATA_H */
| 33.705155 | 100 | 0.609256 | [
"vector"
] |
ca02ff9ad3ca98563a1a75a3d6a4eed8857c8cb2 | 45,985 | h | C | include/opcbuiltins.h | consorzio-rfx/mdsplus | 81cdbfc759d92b101d84328e6eb7b3a6e6e22103 | [
"BSD-2-Clause"
] | null | null | null | include/opcbuiltins.h | consorzio-rfx/mdsplus | 81cdbfc759d92b101d84328e6eb7b3a6e6e22103 | [
"BSD-2-Clause"
] | null | null | null | include/opcbuiltins.h | consorzio-rfx/mdsplus | 81cdbfc759d92b101d84328e6eb7b3a6e6e22103 | [
"BSD-2-Clause"
] | null | null | null | COM/* <opcbuiltins.h>
.macro OpcBUILTINS ;*/
COM/* <WARNING: This code is used by both MACRO and C.>*/
COM/* <Check TDISHR$SHARE.MAR and TDI$$DEF_FUNCTION.C >*/
COM/* <Included by opcopcodes.h >*/
COM/* <For the OPC macro to avoid argument mismatch: >*/
COM/* <MACRO needs white space between it and (". >*/
COM/* <CC requires a / *, MACRO requires a semicolon. >*/
COM/* <Tokens are used by LEX and DECOMPILE_R. >*/
COM/* <+I=immediate (for all VMS arguments, evaluate. Machine-indep types, _OF.) >*/
COM/* < Especially VECTOR and SET_RANGE to make arrays and BUILD_ for class-R. >*/
COM/* <+N=named (is operator or keyword in the language.) >*/
COM/* <+S=symbolic (decompiles to symbolic form.) >*/
COM/* <+U=unusual (defer evaluation: system calls and array generators.) >*/
COM/* <CC omissions: % (casts) declarations initializers auto const static struct * & >*/
COM/* <F90 omissions: !-comments defined-operators defined-types common declarations >*/
COM/* <types%components identify much-I/O modules entry contains named-arguments >*/
COM/* <F90==CC: select case==switch do==for dowhile==while exit==break cycle==continue>*/
COM/* <CC==TDI: case x:==case(x) default:==case default >*/
COM/* <CC==TDI: do s while(x)==do {s}while(x) return==return() >*/
COM/* <IDL omissions: a#b TOTAL >*/
COM/* <name, f1, f2, f3, i1,i2, o1,o2, m1,m2, token Language, args>*/
OPC ( dollar, $ , Else, undef, undef, XX,YY, XX,YY, 0,0, ARG )/*; argument for put*/
OPC ( A0, $A0 , Constant, undef, A0, F,HC, F,HC, 0,0, CONST )/*; Bohr radius */
OPC ( Alpha, $ALPHA , Constant, undef, Alpha, F,HC, F,HC, 0,0, CONST )/*; 1/137 */
OPC ( Amu, $AMU , Constant, undef, Amu, F,HC, F,HC, 0,0, CONST )/*; atomic mass unit*/
OPC ( C, $C , Constant, undef, C, F,HC, F,HC, 0,0, CONST )/*; light speed */
OPC ( Cal, $CAL , Constant, undef, Cal, F,HC, F,HC, 0,0, CONST )/*; calorie to J */
OPC ( Degree, $DEGREE , Constant, undef, Degree, F,HC, F,HC, 0,0, CONST )/*; degree to rad */
OPC ( Ev, $EV , Constant, undef, Ev, F,HC, F,HC, 0,0, CONST )/*; electron volt */
OPC ( False, $FALSE , Constant, undef, False, VV,VV, VV,VV, 0,0, CONST )/*; 0bu */
OPC ( Faraday, $FARADAY , Constant, undef, Faraday, F,HC, F,HC, 0,0, CONST )/*; Faraday constant*/
OPC ( G, $G , Constant, undef, G, F,HC, F,HC, 0,0, CONST )/*; gravity */
OPC ( Gas, $GAS , Constant, undef, Gas, F,HC, F,HC, 0,0, CONST )/*; gas */
OPC ( H, $H , Constant, undef, H, F,HC, F,HC, 0,0, CONST )/*; Planck */
OPC ( Hbar, $HBAR , Constant, undef, Hbar, F,HC, F,HC, 0,0, CONST )/*; */
OPC ( I, $I , Constant, undef, I, F,HC, FC,HC, 0,0, CONST )/*; imaginary */
OPC ( K, $K , Constant, undef, K, F,HC, F,HC, 0,0, CONST )/*; Boltzmann */
OPC ( Me, $ME , Constant, undef, Me, F,HC, F,HC, 0,0, CONST )/*; mass electron */
OPC ( Missing, $MISSING , Constant, undef, Missing, XX,YY, XX,YY, 0,0, CONST+I )/*; missing arg */
OPC ( Mp, $MP , Constant, undef, Mp, F,HC, F,HC, 0,0, CONST )/*; mass proton */
OPC ( N0, $N0 , Constant, undef, N0, F,HC, F,HC, 0,0, CONST )/*; Loschmidt's numb*/
OPC ( Na, $NA , Constant, undef, Na, F,HC, F,HC, 0,0, CONST )/*; Avogadro number */
OPC ( P0, $P0 , Constant, undef, P0, F,HC, F,HC, 0,0, CONST )/*; atmospheric pres*/
OPC ( Pi, $PI , Constant, undef, Pi, F,HC, F,HC, 0,0, CONST )/*; */
OPC ( Qe, $QE , Constant, undef, Qe, F,HC, F,HC, 0,0, CONST )/*; charge electron */
OPC ( Re, $RE , Constant, undef, Re, F,HC, F,HC, 0,0, CONST )/*; classical el.rad*/
OPC ( Roprand, $ROPRAND , Constant, undef, Roprand, F,HC, F,HC, 0,0, CONST+I )/*;vax bad floating */
OPC ( Rydberg, $RYDBERG , Constant, undef, Rydberg, F,HC, F,HC, 0,0, CONST )/*; Rydberg constant*/
OPC ( T0, $T0 , Constant, undef, T0, F,HC, F,HC, 0,0, CONST )/*; standard temp. */
OPC ( Torr, $TORR , Constant, undef, Torr, F,HC, F,HC, 0,0, CONST )/*; 1mm Hg pressure */
OPC ( True, $TRUE , Constant, undef, True, VV,VV, VV,VV, 0,0, CONST )/*; 1bu */
OPC ( Value, $VALUE , Value, undef, undef, XX,YY, XX,YY, 0,0, CONST )/*; raw value in sig*/
OPC ( Abort, ABORT , Abort, undef, undef, XX,YY, XX,YY, 0,255, OK+U )/*; () */
OPC ( Abs, ABS , Same, Abs, Abs, BU,HC, BU,H, 1,1, OK )/*;f9 (a) */
OPC ( Abs1, ABS1 , Same, Abs, Abs1, BU,HC, BU,H, 1,1, OK )/*; (a) 1-norm */
OPC ( AbsSq, ABSSQ , Same, Square, AbsSq, BU,HC, BU,H, 1,1, OK )/*; (a) abs(a)**2 */
OPC ( Achar, ACHAR , Same, Char, Char, BU,O, T,T, 1,2, OK )/*;f9 (i,[dummy_kind])*/
OPC ( Acos, ACOS , Same, None, Acos, F,HC, F,HC, 1,1, OK )/*;f9 (x) */
OPC ( Acosd, ACOSD , Same, None, Acosd, F,HC, F,HC, 1,1, OK )/*;vax (x) */
OPC ( Add, ADD , Same, Add, Add, BU,HC, BU,HC, 2,2, ADD+S )/*;% a+b */
OPC ( Adjustl, ADJUSTL , Same, Adjust, Adjustl, BU,T, T,T, 1,1, OK )/*;f9 (string) */
OPC ( Adjustr, ADJUSTR , Same, Adjust, Adjustr, BU,T, T,T, 1,1, OK )/*;f9 (string) */
OPC ( Aimag, AIMAG , Same, Keep, Aimag, BU,HC, BU,H, 1,1, OK )/*;f9 (z) */
OPC ( Aint, AINT , Same, Aint, Aint, F,HC, F,HC, 1,2, OK )/*;f9 (a,[kind]) */
OPC ( All, ALL , Trans, Mask1, All, BU,O, VV,VV, 1,2, OK )/*;f9 (mask,[dim]) */
OPC ( Allocated, ALLOCATED , Allocated, undef, undef, XX,YY, VV,VV, 1,1, OK+U )/*;f9 (array) */
OPC ( And, AND , Same, Land, And, BU,O, VV,VV, 2,2, LAND+N+S )/*;% v&&w v.AND.w */
OPC ( AndNot, AND_NOT , Same, Land, AndNot, BU,O, VV,VV, 2,2, LAND+N )/*;% (v,w) v.AND..NOT.w */
OPC ( Anint, ANINT , Same, Aint, Anint, F,HC, F,HC, 1,2, OK )/*;f9 (a,kind) */
OPC ( Any, ANY , Trans, Mask1, Any, BU,O, VV,VV, 1,2, OK )/*;f9 (mask,[dim]) */
OPC ( Arg, ARG , Same, None, Arg, FC,HC, F,H, 1,1, OK )/*; (z) atan2(imag,real) */
OPC ( Argd, ARGD , Same, None, Argd, FC,HC, F,H, 1,1, OK )/*; (z) atan2d(imag,real) */
OPC ( ArgOf, ARG_OF , ArgOf, undef, undef, FUNCTION,CONDITION,XX,YY,1,2, OK+I )/*;mds (ext_fun other ,[n]) */
OPC ( Array, ARRAY , Array, undef, Zero, XX,YY, FLOAT,F, 0,2, OK+U )/*; ([size],[kind]) */
OPC ( Asin, ASIN , Same, None, Asin, F,HC, F,HC, 1,1, OK )/*;f9 (x) */
OPC ( Asind, ASIND , Same, None, Asind, F,HC, F,HC, 1,1, OK )/*;vax (x) */
OPC ( AsIs, AS_IS , AsIs, undef, undef, XX,YY, XX,YY, 1,1, MODIF+N )/*;mds (any) unevaluated */
OPC ( Atan, ATAN , Same, None, Atan, F,HC, F,HC, 1,1, OK )/*;f9 (x) */
OPC ( Atan2, ATAN2 , Same, Atan2, Atan2, F,HC, F,HC, 2,2, OK )/*;f9 (y,x) */
OPC ( Atan2d, ATAN2D , Same, Atan2, Atan2d, F,HC, F,HC, 2,2, OK )/*;vax (y,x) */
OPC ( Atand, ATAND , Same, None, Atand, F,HC, F,HC, 1,1, OK )/*;vax (x) */
OPC ( Atanh, ATANH , Same, None, Atanh, F,HC, F,HC, 1,1, OK )/*;vax (x) */
OPC ( AxisOf, AXIS_OF , AxisOf, undef, undef, DIMENSION,DIMENSION,SLOPE,SLOPE,1,1, OK+I )/*;mds (dimension) */
OPC ( Backspace, BACKSPACE , Backspace, undef, undef, L,L, L,L, 1,1, OK+U )/*;f9 (unit) */
OPC ( Ibclr, IBCLR , Same, Long2, Ibclr, XX,YY, XX,YY, 2,2, OK )/*;f9 (i,pos) */
OPC ( BeginOf, BEGIN_OF , BeginOf, undef, undef, WINDOW,RANGE, XX,YY, 1,2, OK+I )/*;mds (window or range)*/
OPC ( Ibits, IBITS , Same, Long2, Ibits, BU,L, BU,L, 3,3, OK )/*;f9 (i,pos,len) */
OPC ( Break, BREAK , Break, undef, undef, XX,YY, XX,YY, 0,0, BREAK+N+U )/*;%cc BREAK;for,switch,while*/
OPC ( Bsearch, BSEARCH , Bsearch, undef, undef, T,HC, T,HC, 2,4, OK )/*; (a,table,[mode],[upcas])*/
OPC ( Ibset, IBSET , Same, Long2, Ibset, XX,YY, XX,YY, 2,2, OK )/*;f9 (i,pos) */
OPC ( Btest, BTEST , Same, Btest, Btest, XX,YY, VV,VV, 2,2, OK )/*;f9 (i,pos) */
OPC ( BuildAction, BUILD_ACTION , Build, undef, undef, XX,YY,ACTION,ACTION, 2,5, OK+I )/*;mds (dis,task,err,comp,perf)*/
OPC ( BuildCondition, BUILD_CONDITION ,Build, undef, undef, XX,YY,CONDITION,WU, 2,2, OK+I )/*;mds (opcode,condition) */
OPC ( BuildConglom, BUILD_CONGLOM , Build, undef, undef, XX,YY,CONGLOM,CONGLOM, 4,4, OK+I )/*;mds (image,model,name,qual) */
OPC ( BuildDependency, BUILD_DEPENDENCY ,Build, undef, undef, XX,YY,DEPENDENCY,WU, 3,3, OK+I )/*;mds (opcode,arg1,arg2) */
OPC ( BuildDim, BUILD_DIM , Build, undef, undef, XX,YY,DIMENSION,DIMENSION,2,2, OK+I )/*;mds (window,axis) */
OPC ( BuildDispatch, BUILD_DISPATCH , Build, undef, undef, XX,YY,DISPATCH,BU, 5,5, OK+I )/*;mds (type,id,phase,when,com)*/
OPC ( BuildEvent, BUILD_EVENT , BuildPath, undef, undef, T,T,EVENT,EVENT, 1,1, OK+I )/*;mds (string) */
OPC ( BuildFunction, BUILD_FUNCTION , Build, undef, undef, XX,YY,FUNCTION,WU, 1,254, OK+I )/*;mds (opcode,[arguments...]) */
OPC ( BuildMethod, BUILD_METHOD , Build, undef, undef, XX,YY,METHOD,METHOD, 3,254, OK+I )/*;mds (timeout,method,obj,...)*/
OPC ( BuildParam, BUILD_PARAM , Build, undef, undef, XX,YY,PARAM,PARAM, 3,3, OK+I )/*;mds (value,help,validation) */
OPC ( BuildPath, BUILD_PATH , BuildPath, undef, undef, T,T,PATH,PATH, 1,1, OK+I )/*;mds (string) */
OPC ( BuildProcedure, BUILD_PROCEDURE ,Build, undef, undef, XX,YY,PROCEDURE,PROCEDURE,3,254, OK+I )/*;mds (timeout,lang,proc,...) */
OPC ( BuildProgram, BUILD_PROGRAM , Build, undef, undef, XX,YY,PROGRAM,PROGRAM, 2,2, OK+I )/*;mds (timeout,program) */
OPC ( BuildRange, BUILD_RANGE , Build, undef, undef, XX,YY,RANGE,RANGE, 2,3, OK+I )/*;mds ([low],[high],[step]) */
OPC ( BuildRoutine, BUILD_ROUTINE , Build, undef, undef, XX,YY,ROUTINE,ROUTINE, 3,254, OK+I )/*;mds (timeout,image,rout,..) */
OPC ( BuildSignal, BUILD_SIGNAL , Build, undef, undef, XX,YY,SIGNAL,SIGNAL, 2,2+MAXDIM,OK+I )/*;mds (data,raw,[dim...]) */
OPC ( BuildSlope, BUILD_SLOPE , Build, undef, undef, XX,YY,SLOPE,SLOPE, 1,254, OK+I )/*;mds (slope,[begin,end]...) */
OPC ( BuildWindow, BUILD_WINDOW , Build, undef, undef, XX,YY,WINDOW,WINDOW, 3,3, OK+I )/*;mds (istart,iend,x_at_0) */
OPC ( BuildWithUnits, BUILD_WITH_UNITS ,Build, undef, undef, XX,YY,WITH_UNITS,WITH_UNITS,2,2, OK+I )/*;mds (data,units) */
OPC ( BuiltinOpcode, BUILTIN_OPCODE , Same, None, StringOpcode, T,T, W,W, 1,1, OK )/*;mds (string) */
OPC ( Byte, BYTE , Same, Keep, undef, B,B, B,B, 1,1, CAST+N+I )/*;%cc (a) (signed char) */
OPC ( ByteUnsigned, BYTE_UNSIGNED , Same, Keep, undef, BU,BU, BU,BU, 1,1, CAST+N+I )/*;%cc (a) (unsigned char) */
OPC ( Case, CASE , Case, undef, undef, XX,YY, XX,YY, 2,254, CASE+N+U )/*;%cc CASE(n)stmt switch_opt */
OPC ( Ceiling, CEILING , Same, Aint, Ceiling, BU,HC, BU,HC, 1,1, OK )/*;f9 (a) */
OPC ( Char, CHAR , Same, Char, Char, BU,O, T,T, 1,2, OK )/*;f9 (i,[kind]) */
OPC ( Class, CLASS , Class, undef, undef, XX,YY, BU,BU, 1,1, OK )/*;vms (any) */
OPC ( Fclose, FCLOSE , Fclose, undef, undef, L,L, L,L, 1,1, OK+U )/*;cc (unit) */
OPC ( Cmplx, CMPLX , Same, Cmplx, Cmplx, FC,HC, FC,HC, 1,3, CAST+N+I )/*;f9 (x,[y],[kind]) */
OPC ( Comma, COMMA , Comma, undef, undef, XX,YY, XX,YY, 2,254, OK+S )/*;%cc a,b.. eval&keep last */
OPC ( Compile, COMPILE , Compile, undef, undef, T,T, FUNCTION,FUNCTION,1,254,OK )/*;mds (string,[arguments...]) */
OPC ( CompletionOf, COMPLETION_OF , CompletionOf, undef, undef, ACTION,DISPATCH, XX,YY, 1,1, OK+I )/*;mds (dispatch) */
OPC ( Concat, CONCAT , MinMax,Concat, Concat, T,T, T,T, 2,254, CONCAT+I )/*;%f9 a//b... */
OPC ( Conditional, CONDITIONAL , Conditional,Merge, Merge, XX,YY, XX,YY, 3,3, COND+S )/*;%cc (t,f,c) c ? t : f */
OPC ( Conjg, CONJG , Same, Keep, Conjg, BU,HC, BU,HC, 1,1, OK )/*;f9 (z) */
OPC ( Continue, CONTINUE , Continue, undef, undef, XX,YY, XX,YY, 0,0, BREAK+N+U )/*;%cc CONTINUE; for,while */
OPC ( Convolve, CONVOLVE , Convolve, undef, undef, BU,HC, BU,HC, 2,2, OK )/*; (z,z) */
OPC ( Cos, COS , Same, NoHc, Cos, F,HC, F,HC, 1,1, OK )/*;f9 (z) */
OPC ( Cosd, COSD , Same, None, Cosd, F,HC, F,HC, 1,1, OK )/*;vax (x) */
OPC ( Cosh, COSH , Same, None, Cosh, F,HC, F,HC, 1,1, OK )/*;f9 (x) */
OPC ( Count, COUNT , Trans, Mask1, Count, BU,O, L,L, 1,2, OK )/*;f9 (mask,[dim]) */
OPC ( Cshift, CSHIFT , Shift, undef, Cshift, XX,YY, XX,YY, 2,3, OK )/*;f9 (array,shift,dim) */
OPC ( Cvt, CVT , Same, Cvt, undef, XX,YY, XX,YY, 2,2, OK+I )/*; (a,mold) */
OPC ( Data, DATA , Data, undef, undef, XX,YY, XX,YY, 1,1, OK+I )/*;mds (any) */
OPC ( DateAndTime, DATE_AND_TIME , DateAndTime, undef, undef, T,T, T,L, 0,1, OK+U )/*;f9variant ([string]) */
OPC ( DateTime, DATE_TIME , DateTime, undef, undef, XX,YY, T,T, 0,1, OK+U )/*; ([quad]) */
OPC ( Dble, DBLE , Same, Dble, undef, BU,HC, WU,HC, 1,1, OK )/*;f9variant (a) */
OPC ( Deallocate, DEALLOCATE , Deallocate, undef, undef, XX,YY, L,L, 0,254, OK+U )/*; (a...) */
OPC ( Debug, DEBUG , Debug, undef, undef, L,L, L,L, 0,1, OK+U )/*; (option) */
OPC ( Decode, DECODE , Decode, undef, undef, T,T, XX,YY, 1,2, OK )/*;f? (fmt|*,text) */
OPC ( Decompile, DECOMPILE , Decompile, undef, undef, XX,YY, T,T, 1,2, OK )/*;mds (expression,[max_array])*/
OPC ( Decompress, DECOMPRESS , Decompress, undef, undef, XX,YY, XX,YY, 4,4, OK )/*;mds ([ima],[rou],shape,dat) */
OPC ( Default, DEFAULT , Default, undef, undef, XX,YY, XX,YY, 1,254, DEFAULT+N+U )/*;%cc CASE DEFAULT stmt */
OPC ( Derivative, DERIVATIVE , Trans, Sign, Derivative, XX,YY, XX,YY, 2,3, OK )/*; (z,dim,[dt]) axis diff */
OPC ( Descr, DESCR , Else, undef, undef, XX,YY, XX,YY, 1,1, OK )/*;vax (any) */
OPC ( Diagonal, DIAGONAL , Diagonal, undef, undef, XX,YY, XX,YY, 1,2, OK )/*; (vector,[fill]) */
OPC ( Digits, DIGITS , Scalar,Any, Digits, BU,HC, L,L, 1,1, OK )/*;f9 (model) */
OPC ( Dim, DIM , Same, Add, Dim, BU,HC, BU,HC, 2,2, OK )/*;f9 (x,y) */
OPC ( DimOf, DIM_OF , DimOf, undef, undef, XX,YY,DIMENSION,DIMENSION,1,2, OK )/*;mds (signal or VMS,[num]) */
OPC ( DispatchOf, DISPATCH_OF , DispatchOf, undef, undef, ACTION,DISPATCH,DISPATCH,DISPATCH,1,1,OK+I)/*;mds (action) */
OPC ( Divide, DIVIDE , Same, Divide, Divide, BU,HC, BU,HC, 2,2, MUL+S )/*;% a/b */
OPC ( Lbound, LBOUND , Bound, undef, Lbound, XX,YY, L,L, 1,2, OK )/*;f9 (array,[dim]) */
OPC ( Do, DO , Do, undef, undef, XX,YY, XX,YY, 2,254, DO+N )/*;%cc DO stmt WHILE(expr) */
OPC ( DotProduct, DOT_PRODUCT , Scalar,Multiply, DotProduct, BU,HC, BU,HC, 2,2, OK )/*;f9variant (vec_a,vec_b) */
OPC ( Dprod, DPROD , Same, Dprod, Multiply, BU,HC, WU,HC, 2,2, OK )/*;f9variant (x,y) */
OPC ( Dscptr, DSCPTR , Dscptr, undef, undef, XX,YY, XX,YY, 1,2, OK+I )/*;mds (any_class_R,[num]) */
OPC ( Shape, SHAPE , Bound, undef, Shape, XX,YY, L,L, 1,2, OK )/*;f9 (array,[dim]) */
OPC ( Size, SIZE , Bound, undef, Size, XX,YY, L,L, 1,2, OK )/*;f9 (array,[dim]) */
OPC ( Kind, KIND , Kind, undef, undef, XX,YY, BU,BU, 1,1, OK )/*;f9 (any) */
OPC ( Ubound, UBOUND , Bound, undef, Ubound, XX,YY, L,L, 1,2, OK )/*;f9 (array,[dim]) */
OPC ( DComplex, D_COMPLEX , Same, Cmplx, Complex, D,D, DC,DC, 1,2, CAST+N+I )/*;% (x,y) */
OPC ( DFloat, D_FLOAT , Same, Keep, undef, D,D, D,D, 1,1, CAST+N+I )/*;% (a) */
OPC ( Range, RANGE , Scalar,Any, Range, F,HC, L,L, 1,1, OK )/*;f9 (model) */
OPC ( Precision, PRECISION , Scalar,Any, Precision, F,HC, L,L, 1,1, OK )/*;f9 (model) */
OPC ( Elbound, ELBOUND , Ebound, undef, Elbound, XX,YY, BU,H, 1,2, OK )/*; (array,[dim]) */
OPC ( Else, ELSE , Else, undef, undef, XX,YY, XX,YY, 0,0, ELSE+N+I )/*;%cc placeholder IF */
OPC ( Elsewhere, ELSEWHERE , Else, undef, undef, XX,YY, XX,YY, 0,0, ELSEW+N+I )/*;%f9 placeholder WHERE */
OPC ( Encode, ENCODE , Encode, undef, undef, XX,YY, T,T, 1,254, OK )/*;% (fmt|*,arg...) */
OPC ( Endfile, ENDFILE , Endfile, undef, undef, L,L, L,L, 1,1, OK+U )/*;f9 (unit) */
OPC ( EndOf, END_OF , EndOf, undef, undef, WINDOW,RANGE, XX,YY, 1,2, OK+I )/*;mds (window slope,[n] range)*/
OPC ( Eoshift, EOSHIFT , Shift, undef, Eoshift, XX,YY, XX,YY, 3,4, OK )/*;f9 (arr,dim,shift,[bndry]) */
OPC ( Epsilon, EPSILON , Scalar, Keep, Epsilon, F,HC, F,HC, 1,1, OK )/*;f9 (model) */
OPC ( Eq, EQ , Same, Eq, Eq, XX,YY, VV,VV, 2,2, LEQ+N+S )/*;% a==b a.EQ.b */
OPC ( Equals, EQUALS , Equals, undef, undef, XX,YY, XX,YY, 2,2, OK+S+U )/*;% a = b */
OPC ( EqualsFirst, EQUALS_FIRST , EqualsFirst, undef, undef, XX,YY, XX,YY, 1,1, OK+S+U )/*;% a binop = b */
OPC ( Eqv, EQV , Same, Land, Eqv, BU,O, VV,VV, 2,2, LEQV+N )/*;% (v,w) v.EQV.w */
OPC ( Eshape, ESHAPE , Ebound, undef, Eshape, XX,YY, BU,H, 1,2, OK )/*; (array,[dim]) */
OPC ( Esize, ESIZE , Ebound, undef, Esize, XX,YY, BU,H, 1,2, OK )/*; (array,[dim]) */
OPC ( Eubound, EUBOUND , Ebound, undef, Eubound, XX,YY, BU,H, 1,2, OK )/*; (array,[dim]) */
OPC ( Evaluate, EVALUATE , Evaluate, undef, undef, XX,YY, XX,YY, 1,1, OK )/*; (reeval_expression) */
OPC ( Execute, EXECUTE , Execute, undef, undef, T,T, XX,YY, 1,254, OK )/*; (string,[arguments...]) */
OPC ( Exp, EXP , Same, NoHc, Exp, F,HC, F,HC, 1,1, OK )/*;f9 (z) */
OPC ( Exponent, EXPONENT , Same, Keep, Exponent, F,HC, L,L, 1,1, OK )/*;f9 (x) */
OPC ( ExtFunction, EXT_FUNCTION , ExtFunction, undef, undef, XX,YY, XX,YY, 2,254, OK+S+U )/*;mds (image,routine,a...) */
OPC ( Fft, FFT , Fft, undef, undef, FC,HC, FC,HC, 2,2, OK )/*; (array,direction) */
OPC ( FirstLoc, FIRSTLOC , Trans, Mask1, FirstLoc, BU,O, VV,VV, 1,2, OK )/*; (mask,[dim]) */
OPC ( Fit, FIT , Fit, undef, undef, F,HC, F,HC, 2,2, OK )/*; (X_guess,residuals(X)) */
OPC ( FixRoprand, FIX_ROPRAND , Same, Fix, FixRoprand, BU,HC, BU,HC, 2,2, OK )/*; (a,replacement) */
OPC ( Float, FLOAT , Same, Real, undef, F,H, F,H, 1,2, CAST+N+I )/*; (a,[kind]) */
OPC ( Floor, FLOOR , Same, Aint, Floor, F,HC, F,HC, 1,1, OK )/*;f9 (x) */
OPC ( For, FOR , For, undef, undef, XX,YY, XX,YY, 4,254, FOR+N )/*;%cc FOR(expr;expr;expr)stmt */
OPC ( Fraction, FRACTION , Same, Keep, Fraction, F,HC, F,HC, 1,1, OK )/*;f9 (x) */
OPC ( Fun, FUN , Fun, undef, undef, XX,YY, YY,YY, 2,254, FUN+N+U )/*;[public] fun name(a...)stmt */
OPC ( FComplex, F_COMPLEX , Same, Cmplx, Complex, F,F, FC,FC, 1,2, CAST+N+I )/*;% (x,y) */
OPC ( FFloat, F_FLOAT , Same, Keep, undef, F,F, F,F, 1,1, CAST+N+I )/*;% (a) */
OPC ( Ge, GE , Same, Eq, Ge, XX,YY, VV,VV, 2,2, LGE+N+S )/*;% a>=b a.GE.b */
OPC ( GetNci, GETNCI , GetNci, undef, undef, NID,NID,XX,YY, 2,3, OK+U )/*;mds (nid,item_str,[usage]) */
OPC ( Goto, GOTO , Goto, undef, undef, XX,YY, XX,YY, 1,1, GOTO+N+U )/*;%cc GOTO label; */
OPC ( Gt, GT , Same, Eq, Gt, XX,YY, VV,VV, 2,2, LGE+N+S )/*;% a>b a.GT.b */
OPC ( GComplex, G_COMPLEX , Same, Cmplx, Complex, G,G, GC,GC, 1,2, CAST+N+I )/*;% (x,y) */
OPC ( GFloat, G_FLOAT , Same, Keep, undef, G,G, G,G, 1,1, CAST+N+I )/*;% (a) */
OPC ( HelpOf, HELP_OF , HelpOf, undef, undef, PARAM,PARAM, T,T, 1,1, OK+I )/*;mds (param) */
OPC ( Huge, HUGE , Scalar, Keep, Huge, BU,HC, BU,H, 1,1, OK )/*;f9 (model) */
OPC ( HComplex, H_COMPLEX , Same, Cmplx, Complex, HC,HC, HC,HC, 1,2, CAST+N+I )/*;% (x,y) */
OPC ( HFloat, H_FLOAT , Same, Keep, undef, H,H, H,H, 1,1, CAST+N+I )/*;% (a) */
OPC ( Iachar, IACHAR , Same, Keep, Ichar, T,T, BU,BU, 1,1, OK )/*;f9 (character) */
OPC ( Iand, IAND , Same, Iand, Iand, BU,O, BU,OU, 2,2, IAND+S )/*;f9 i&j iand(i,j) */
OPC ( IandNot, IAND_NOT , Same, Iand, IandNot, BU,O, BU,OU, 2,2, IAND )/*; (i,j) */
OPC ( Ichar, ICHAR , Same, Keep, Ichar, T,T, BU,BU, 1,1, OK )/*;f9 (character) */
OPC ( IdentOf, IDENT_OF , IdentOf, undef, undef, ACTION,DISPATCH, T,T, 1,1, OK+I )/*;mds (dispatch) */
OPC ( If, IF , If, undef, undef, XX,YY, XX,YY, 2,3, IF+N )/*;%cc IF(expr)stmt */
OPC ( IfError, IF_ERROR , IfError, undef, undef, XX,YY, XX,YY, 1,254, OK )/*; (a..) a, if (error) b.. */
OPC ( ImageOf, IMAGE_OF , ImageOf, undef, undef, FUNCTION,ROUTINE,T,T, 1,1, OK+I )/*;mds (ext_f conglom routine) */
OPC ( In, IN , Else, undef, undef, XX,YY, XX,YY, 1,1, MODIF+N )/*; IN a read only */
OPC ( Inand, INAND , Same, Iand, Inand, BU,O, BU,OU, 2,2, IAND )/*; (i,j) */
OPC ( InandNot, INAND_NOT , Same, Iand, InandNot, BU,O, BU,OU, 2,2, IAND )/*; (i,j) */
OPC ( Index, INDEX , Same, Ttb, Index, T,T,SUBSCRIPT,SUBSCRIPT,2,3, OK )/*;f9 (string,substr,[back]) */
OPC ( Inor, INOR , Same, Iand, Inor, BU,O, BU,OU, 2,2, IOR )/*; (i,j) */
OPC ( InorNot, INOR_NOT , Same, Iand, InorNot, BU,O, BU,OU, 2,2, IOR )/*; (i,j) */
OPC ( Inot, INOT , Same, Keep, Inot, BU,O, BU,OU, 1,1, UNARY+S )/*;%cc ~a \\not(a)\\ */
OPC ( InOut, INOUT , Else, undef, undef, XX,YY, XX,YY, 1,1, MODIF+N )/*; INOUT a read/write */
OPC ( Inquire, INQUIRE , Inquire, undef, undef, XX,YY, XX,YY, 2,2, OK+U )/*;%f9 (unit|file,select) */
OPC ( Int, INT , Same, Real, undef, B,O, B,O, 1,2, CAST+N+I )/*;f9 (a,[kind]) */
OPC ( Integral, INTEGRAL , Trans, Sign, Integral, BU,HC, BU,HC, 2,3, OK )/*; (a,dim,[dt]) axis sum */
OPC ( Interpol, INTERPOL , Interpol, undef, undef, BU,HC, BU,HC, 2,3, OK )/*; (a,n) or (a,xin,xout) */
OPC ( Intersect, INTERSECT , Intersect, undef, undef, XX,YY, XX,YY, 0,254, OK )/*; (a,...) */
OPC ( IntUnsigned, INT_UNSIGNED , Same, Keep, undef, BU,OU, BU,OU, 1,1, CAST+N+I )/*;% (a) (unsigned int) zext */
OPC ( Inverse, INVERSE , Same, Inverse, Inverse, F,HC, F,HC, 1,1, OK )/*; (matrix) */
OPC ( Ior, IOR , Same, Iand, Ior, BU,O, BU,OU, 2,2, IOR+S )/*;f9 i|j ior(i,j) */
OPC ( IorNot, IOR_NOT , Same, Iand, IorNot, BU,O, BU,OU, 2,2, IOR )/*; (i,j) */
OPC ( IsIn, IS_IN , IsIn, undef, undef, T,HC, VV,VV, 2,3, IN+N )/*;% a IS_IN b rng/lst upcase*/
OPC ( Ieor, IEOR , Same, Iand, Ieor, BU,O, BU,OU, 2,2, IXOR )/*; (i,j) */
OPC ( IeorNot, IEOR_NOT , Same, Iand, IeorNot, BU,O, BU,OU, 2,2, IXOR )/*; (i,j) */
OPC ( Label, LABEL , Label, undef, undef, XX,YY, XX,YY, 2,254, LABEL+N+U )/*;% LABEL label: stmt */
OPC ( Laminate, LAMINATE , Laminate, undef, undef, XX,YY, XX,YY, 2,254, OK+S )/*;% {{a1,a2},...{z1,z2}} */
OPC ( LanguageOf, LANGUAGE_OF , LanguageOf, undef, undef, PROCEDURE,PROCEDURE, XX,YY, 1,1, OK+I )/*;mds (procedure) */
OPC ( LastLoc, LASTLOC , Trans, Mask1, LastLoc, BU,O, VV,VV, 1,2, OK )/*; (mask,[dim]) */
OPC ( Le, LE , Same, Eq, Le, XX,YY, VV,VV, 2,2, LGE+N+S )/*;% a<=b a.LE.b */
OPC ( Len, LEN , Scalar, Any, Len, XX,YY, L,L, 1,1, OK )/*;f9+ (string or other) */
OPC ( LenTrim, LEN_TRIM , Same, Any, LenTrim, BU,T, L,L, 1,1, OK )/*;f9 (string) */
OPC ( Lge, LGE , Same, Eq, Ge, T,T, VV,VV, 2,2, OK )/*;f9 (string_a,string_b) */
OPC ( Lgt, LGT , Same, Eq, Gt, T,T, VV,VV, 2,2, OK )/*;f9 (string_a,string_b) */
OPC ( Lle, LLE , Same, Eq, Le, T,T, VV,VV, 2,2, OK )/*;f9 (string_a,string_b) */
OPC ( Llt, LLT , Same, Eq, Lt, T,T, VV,VV, 2,2, OK )/*;f9 (string_a,string_b) */
OPC ( Log, LOG , Same, NoHc, Log, F,HC, F,HC, 1,1, OK )/*;f9 (z) */
OPC ( Log10, LOG10 , Same, None, Log10, F,HC, F,HC, 1,1, OK )/*;f9 (x) */
OPC ( Log2, LOG2 , Same, None, Log2, F,HC, F,HC, 1,1, OK )/*;vax (x) */
OPC ( Logical, LOGICAL , Same, Not, Logical, BU,O, VV,VV, 1,2, OK )/*;f9 (a,[kind]) */
OPC ( Long, LONG , Same, Keep, undef, L,L, L,L, 1,1, CAST+N+I )/*;% (a) (signed long) */
OPC ( LongUnsigned, LONG_UNSIGNED , Same, Keep, undef, LU,LU, LU,LU, 1,1, CAST+N+I )/*;% (a) (unsigned long) */
OPC ( Lt, LT , Same, Eq, Lt, XX,YY, VV,VV, 2,2, LGE+N+S )/*;% a<b a.LT.b */
OPC ( Matmul, MATMUL , Matmul, undef, undef, BU,HC, BU,HC, 2,2, OK )/*;f9 (matrix_a,matrix_b) */
OPC ( MatRot, MAT_ROT , Matrix, undef, MatRot, F,HC, F,HC, 2,5, OK )/*; (mat,angle,mag,x0,y0) */
OPC ( MatRotInt, MAT_ROT_INT , Matrix, undef, MatRotInt, F,HC, F,HC, 2,5, OK )/*; (mat,angle,mag,x0,y0) */
OPC ( Max, MAX , MinMax, Add, Max, BU,HC, BU,HC, 2,254, OK )/*;f9 (x,y..) */
OPC ( MaxExponent, MAXEXPONENT , Scalar,Any, MaxExponent, F,HC, L,L, 1,1, OK )/*;f9 (model) */
OPC ( MaxLoc, MAXLOC , Trans, Mask3, MaxLoc, T,HC,SUBSCRIPT,SUBSCRIPT,1,3, OK )/*;f9 (x,[dim],[mask]) */
OPC ( MaxVal, MAXVAL , Trans, Mask3, MaxVal, T,HC, T,HC, 1,3, OK )/*;f9 (x,[dim],[mask]) */
OPC ( Mean, MEAN , Trans, Mask3, Mean, BU,HC, F,HC, 1,3, OK )/*; (x,[dim],[mask]) */
OPC ( Median, MEDIAN , Same, Long2, Median, BU,HC, BU,HC, 2,2, OK )/*; (a,width) */
OPC ( Merge, MERGE , Same, Merge, Merge, XX,YY, XX,YY, 3,3, OK )/*;f9 (tsource,fsource,mask) */
OPC ( MethodOf, METHOD_OF , MethodOf, undef, undef, METHOD,METHOD, XX,YY, 1,1, OK+I )/*;mds (method) */
OPC ( Min, MIN , MinMax,Add, Min, BU,HC, BU,HC, 2,254, OK )/*;f9 (x,y..) */
OPC ( MinExponent, MINEXPONENT , Scalar,Any, MinExponent, F,HC, L,L, 1,1, OK )/*;f9 (model) */
OPC ( MinLoc, MINLOC , Trans, Mask3, MinLoc, T,HC,SUBSCRIPT,SUBSCRIPT,1,3, OK )/*;f9 (x,[dim], [mask]) */
OPC ( MinVal, MINVAL , Trans, Mask3, MinVal, T,HC, T,HC, 1,3, OK )/*;f9 (x,[dim],[mask]) */
OPC ( Mod, MOD , Same, Add, Mod, BU,HC, BU,HC, 2,2, MUL+N )/*;f9 (a,p) */
OPC ( ModelOf, MODEL_OF , ModelOf, undef, undef, CONGLOM,CONGLOM, XX,YY, 1,1, OK+I )/*;mds (conglom) */
OPC ( Multiply, MULTIPLY , Same, Multiply, Multiply, BU,HC, BU,HC, 2,2, MUL+S )/*;% a*b */
OPC ( NameOf, NAME_OF , NameOf, undef, undef, CONGLOM,CONGLOM, T,T, 1,1, OK+I )/*;mds (conglom) */
OPC ( Nand, NAND , Same, Land, Nand, BU,O, VV,VV, 2,2, LAND+N )/*;% (v,w) .NOT.(v.AND.w) */
OPC ( NandNot, NAND_NOT , Same, Land, NandNot, BU,O, VV,VV, 2,2, LAND+N )/*;% (v,w) .NOT.v.OR.w */
OPC ( Ndesc, NDESC , Ndesc, undef, undef, PARAM,WITH_UNITS,BU,BU, 1,1, OK )/*;mds (class_R) */
OPC ( Ne, NE , Same, Eq, Ne, XX,YY, VV,VV, 2,2, LEQ+N+S )/*;% a!=b a/=b a<>b a.NE.b */
OPC ( Nearest, NEAREST , Same, Sign, Nearest, F,HC, F,HC, 2,2, OK )/*;f9 (x,s) */
OPC ( Neqv, NEQV , Same, Land, Neqv, BU,O, VV,VV, 2,2, LEQV+N )/*;% (v,w) v.NEQV.w */
OPC ( Nint, NINT , Same, Aint, Nint, BU,HC, L,L, 1,2, OK )/*;f9 (x,[kind]) */
OPC ( Nor, NOR , Same, Land, Nor, BU,O, VV,VV, 2,2, LOR+N )/*;% (v,w) .NOT.(v.OR.w) */
OPC ( NorNot, NOR_NOT , Same, Land, NorNot, BU,O, VV,VV, 2,2, LOR+N )/*;% (v,w) .NOT.v.AND.w */
OPC ( Not, NOT , Same, Not, Not, BU,O, VV,VV, 1,1, UNARY+N+S )/*;% !a .NOT.a */
OPC ( ObjectOf, OBJECT_OF , ObjectOf, undef, undef, METHOD,METHOD, XX,YY, 1,1, OK+I )/*;mds (method) */
OPC ( Octaword, OCTAWORD , Same, Keep, undef, O,O, O,O, 1,1, CAST+N+I )/*;% (a) */
OPC ( OctawordUnsigned, OCTAWORD_UNSIGNED ,Same,Keep, undef, OU,OU, OU,OU, 1,1, CAST+N+I )/*;% (a) */
OPC ( OnError, ON_ERROR , OnError, undef, undef, XX,YY, XX,YY, 1,1, OK )/*; (a,b..) a, on (error) b */
OPC ( OpcodeBuiltin, OPCODE_BUILTIN , Trim, undef, OpcodeBuiltin, WU,L, T,T, 1,1, OK )/*; (opcode) */
OPC ( OpcodeString, OPCODE_STRING , Trim, undef, OpcodeString, WU,L, T,T, 1,1, OK )/*; (opcode) */
OPC ( Fopen, FOPEN , Fopen, undef, undef, T,T, L,L, 2,254, OK+U )/*;%cc unit=(file,mode,[arg..])*/
OPC ( Optional, OPTIONAL , Else, undef, undef, XX,YY, XX,YY, 1,1, MODIF+N )/*; OPTIONAL a */
OPC ( Or, OR , Same, Land, Or, BU,O, VV,VV, 2,2, LOR+N )/*;% (v,w) v||w v.OR.w */
OPC ( OrNot, OR_NOT , Same, Land, OrNot, BU,O, VV,VV, 2,2, LOR+N )/*;% (v,w) v.OR..NOT.w */
OPC ( Out, OUT , Else, undef, undef, XX,YY, XX,YY, 1,1, MODIF+N )/*; OUT a write only */
OPC ( Pack, PACK , Pack, undef, undef, XX,YY, XX,YY, 2,3, OK )/*;f9 (a,mask,[vector]) */
OPC ( PhaseOf, PHASE_OF , PhaseOf, undef, undef, ACTION,DISPATCH, T,T, 1,1, OK+I )/*;mds (dispatch) */
OPC ( PostDec, POST_DEC , PostDec, undef, undef, BU,HC, BU,HC, 1,1, INC+S+U )/*;%cc a-- */
OPC ( PostInc, POST_INC , PostInc, undef, undef, BU,HC, BU,HC, 1,1, INC+S+U )/*;%cc a++ */
OPC ( Power, POWER , Same, Power, Power, BU,HC, BU,HC, 2,2, POWER+S )/*;% a^b a**b */
OPC ( Present, PRESENT , Present, undef, undef, XX,YY, VV,VV, 1,1, OK )/*;f9 (a) */
OPC ( PreDec, PRE_DEC , PreDec, undef, undef, BU,HC, BU,HC, 1,1, INC+S+U )/*;%cc --a */
OPC ( PreInc, PRE_INC , PreInc, undef, undef, BU,HC, BU,HC, 1,1, INC+S+U )/*;%cc ++a */
OPC ( Private, PRIVATE , Private, undef, undef, T,T, XX,YY, 1,1, MODIF+N )/*; PRIVATE a */
OPC ( ProcedureOf, PROCEDURE_OF , ProcedureOf, undef, undef, PROCEDURE,PROCEDURE,XX,YY,1,1, OK+I )/*;mds (procedure) */
OPC ( Product, PRODUCT , Trans, Mask3, Product, BU,HC, BU,HC, 1,3, OK )/*;f9 (array,[dim],[mask]) */
OPC ( ProgramOf, PROGRAM_OF , ProgramOf, undef, undef, PROGRAM,PROGRAM, XX,YY, 1,1, OK+I )/*;mds (program) */
OPC ( Project, PROJECT , Project, undef, undef, XX,YY, XX,YY, 3,4, OK )/*; (arr,mask,field,[dim]) */
OPC ( Promote, PROMOTE , Promote, undef, undef, XX,YY, XX,YY, 2,2, PROMO+S+U )/*; ncopies@b */
OPC ( Public, PUBLIC , Public, undef, undef, T,T, XX,YY, 1,1, MODIF+N )/*; PUBLIC a */
OPC ( Quadword, QUADWORD , Same, Keep, undef, Q,Q, Q,Q, 1,1, CAST+N+I )/*;% (a) */
OPC ( QuadwordUnsigned, QUADWORD_UNSIGNED ,Same,Keep, undef, QU,QU, QU,QU, 1,1, CAST+N+I )/*;% (a) */
OPC ( QualifiersOf, QUALIFIERS_OF , QualifiersOf, undef, undef, CONGLOM,CONGLOM, XX,YY, 1,1, OK+I )/*;mds (conglom) */
OPC ( Radix, RADIX , Scalar,Any, Radix, BU,HC, L,L, 1,1, OK )/*;f9 (model) */
OPC ( Ramp, RAMP , Array, undef, Ramp, XX,YY, L,L, 0,2, OK+U )/*; ([size],[kind]) */
OPC ( Random, RANDOM , Array, undef, Random, XX,YY, FLOAT,F, 0,2, OK+U )/*;f9var ([size],[kind]) */
OPC ( RandomSeed, RANDOM_SEED , RandomSeed, undef, undef, L,L, L,L, 0,1, OK+U )/*;f9var ([put]) */
OPC ( DtypeRange, DTYPE_RANGE , DtypeRange, undef, undef, BU,HC, BU,HC, 2,3, RANGE+S+U )/*;% a:b:[c] a..b..[c] */
OPC ( Rank, RANK , Scalar,Any, Rank, XX,YY, L,L, 1,1, OK )/*;fex (a) */
OPC ( RawOf, RAW_OF , RawOf, undef, undef, SIGNAL,SIGNAL, XX,YY, 1,1, OK+I )/*;mds (signal) */
OPC ( Read, READ , Read, undef, undef, XX,YY, T,T, 1,1, OK )/*;% (unit|*,fmt|*,arg...) */
OPC ( Real, REAL , Same, Real, undef, F,H, F,H, 1,2, OK+I )/*;f9 (a,[kind]) */
OPC ( Rebin, REBIN , Rebin, undef, undef, BU,HC, BU,HC, 2,4, OK )/*; (a,size1,...) */
OPC ( Ref, REF , Else, undef, undef, XX,YY, XX,YY, 1,1, OK )/*;vax (any) */
OPC ( Repeat, REPEAT , Same, Repeat, Repeat, T,T, T,T, 2,2, OK+U )/*;f9 (string,ncopies) */
OPC ( Replicate, REPLICATE , Trans, Sign, Replicate, XX,YY, XX,YY, 3,3, OK+U )/*;fex (array,dim,ncopies) */
OPC ( Reshape, RESHAPE , Reshape, undef, undef, XX,YY, XX,YY, 2,4, OK )/*;f9 (dimvec,a,[pad],[order])*/
OPC ( Return, RETURN , Return, undef, undef, XX,YY, XX,YY, 0,1, RETURN+N+U )/*;%cc (expr); */
OPC ( Rewind, REWIND , Rewind, undef, undef, L,L, L,L, 1,1, OK+U )/*;%f9 (unit) */
OPC ( Rms, RMS , Trans, Mask3, Rms, F,HC, F,H, 1,3, OK )/*; (array,[dim],[mask]) */
OPC ( RoutineOf, ROUTINE_OF , RoutineOf, undef, undef, FUNCTION,ROUTINE,T,T, 1,1, OK+I )/*;mds (ext_fun routine) */
OPC ( RrSpacing, RRSPACING , Same, Keep, RrSpacing, F,HC, F,HC, 1,1, OK )/*;f9 (x) */
OPC ( Scale, SCALE , Same, Long2, Scale, F,HC, F,HC, 2,2, OK )/*;f9 (r,i) */
OPC ( Scan, SCAN , Same, Ttb, Scan, T,T,SUBSCRIPT,SUBSCRIPT,2,3, OK )/*;f9 (string,set,[back]) */
OPC ( Fseek, FSEEK , Fseek, undef, undef, L,L, L,L, 1,3, OK+U )/*;%cc (unit,[offset],[origin])*/
OPC ( SetExponent, SET_EXPONENT , Same, Long2, SetExponent, F,HC, F,HC, 2,2, OK )/*;f9 (x,i) */
OPC ( SetRange, SET_RANGE , SetRange, undef, undef, XX,YY, XX,YY, 2,1+MAXDIM,OK+I )/*;% (range...,name) */
OPC ( Ishft, ISHFT , Same, Shft, Ishft, BU,O, BU,O, 2,2, OK )/*;f9 (a,shift) */
OPC ( Ishftc, ISHFTC , Same, Shft, Ishftc, BU,O, BU,O, 3,3, OK )/*;f9 (a,shift,size) */
OPC ( ShiftLeft, SHIFT_LEFT , Same, Shft, ShiftLeft, BU,O, BU,O, 2,2, SHIFT+S )/*;%cc i<<j */
OPC ( ShiftRight, SHIFT_RIGHT , Same, Shft, ShiftRight, BU,O, BU,O, 2,2, SHIFT+S )/*;%cc i>>j sign=signed */
OPC ( Sign, SIGN , Same, Sign, Sign, BU,HC, BU,HC, 2,2, OK )/*;f9 (a,b) */
OPC ( Signed, SIGNED , Same, Keep, undef, B,O, B,O, 1,1, CAST+N+I )/*;% (a) */
OPC ( Sin, SIN , Same, NoHc, Sin, F,HC, F,HC, 1,1, OK )/*;f9 (x) */
OPC ( Sind, SIND , Same, None, Sind, F,HC, F,HC, 1,1, OK )/*;vax (x) */
OPC ( Sinh, SINH , Same, None, Sinh, F,HC, F,HC, 1,1, OK )/*;f9 (x) */
OPC ( SizeOf, SIZEOF , Scalar,Any, SizeOf, XX,YY, L,L, 1,1, SIZEOF+N )/*;%ccmod (expr) */
OPC ( SlopeOf, SLOPE_OF , SlopeOf, undef, undef, SLOPE,RANGE, BU,HC, 1,2, OK+I )/*;mds (slope range,[n]) */
OPC ( Smooth, SMOOTH , Same, Long2, Smooth, BU,HC, BU,HC, 2,2, OK )/*; (a,width) */
OPC ( Solve, SOLVE , Matrix,Divide, Solve, F,HC, F,HC, 2,2, OK )/*; (right,matrix) */
OPC ( SortVal, SORTVAL , SortVal, undef, undef, T,HC, T,HC, 1,2, OK )/*; (array,[upcase]) */
OPC ( Spacing, SPACING , Same, Keep, Spacing, F,HC, F,HC, 1,1, OK )/*;f9 (x) */
OPC ( Spawn, SPAWN , Spawn, undef, undef, T,T, L,L, 0,3, OK+U )/*;vax (cmd,input,output) */
OPC ( Spread, SPREAD , Trans, Sign, Spread, XX,YY, XX,YY, 3,3, OK )/*;f9 (a,dim,ncopies) */
OPC ( Sqrt, SQRT , Same, NoHc, Sqrt, F,HC, F,HC, 1,1, OK )/*;f9 (z) */
OPC ( Square, SQUARE , Same, Square, Square, BU,HC, BU,HC, 1,1, OK )/*; (z) a**2 */
OPC ( Statement, STATEMENT , Statement, undef, undef, XX,YY, XX,YY, 0,254, OK+S )/*;%cc {a;..} evl&forget..null */
OPC ( StdDev, STD_DEV , Trans, Mask3, StdDev, F,HC, F,HC, 1,3, OK )/*; (array,[dim],[mask]) */
OPC ( String, STRING , String, undef, undef, XX,YY, T,T, 1,254, OK )/*; (a,...[format]) */
OPC ( StringOpcode, STRING_OPCODE , Same, None, StringOpcode, T,T, W,W, 1,1, OK )/*;mds (string) */
OPC ( Subscript, SUBSCRIPT , Subscript, undef, undef, XX,YY, XX,YY, 1,1+MAXDIM,OK+S )/*;%cc a[b..] range list sig */
OPC ( Subtract, SUBTRACT , Same, Add, Subtract, BU,HC, BU,HC, 2,2, ADD+S )/*;% a-b */
OPC ( Sum, SUM , Trans, Mask3, Sum, BU,HC, BU,HC, 1,3, OK )/*;f9 (array,[dim],[mask]) */
OPC ( Switch, SWITCH , Switch, undef, undef, XX,YY, XX,YY, 2,254, SWITCH+N )/*;%cc SWITCH(expr)stmt */
OPC ( SystemClock, SYSTEM_CLOCK , Same, None, SystemClock, XX,YY, L,L, 1,1, OK+U )/*;f9variant (string) */
OPC ( Tan, TAN , Same, None, Tan, F,HC, F,HC, 1,1, OK )/*; (x) */
OPC ( Tand, TAND , Same, None, Tand, F,HC, F,HC, 1,1, OK )/*;vax (x) */
OPC ( Tanh, TANH , Same, None, Tanh, F,HC, F,HC, 1,1, OK )/*;f9 (x) */
OPC ( TaskOf, TASK_OF , TaskOf, undef, undef, ACTION,ACTION,PROGRAM,METHOD, 1,1, OK+I )/*;mds (action) */
OPC ( Text, TEXT , Same, Text, undef, BU,T, T,T, 1,2, OK )/*; (a,[length]) */
OPC ( TimeoutOf, TIME_OUT_OF , TimeoutOf, undef, undef, PROGRAM,METHOD, XX,YY, 1,1, OK+I )/*;mds (prog rout proc meth) */
OPC ( Tiny, TINY , Scalar,Keep, Tiny, F,HC, F,H, 1,1, OK )/*;f9 (model) */
OPC ( Transfer, TRANSFER , Transfer, undef, undef, XX,YY, XX,YY, 2,3, OK )/*;f9 (a,mold,[size]) */
OPC ( Transpose_, TRANSPOSE_ , Matrix, undef, Transpose, XX,YY, XX,YY, 1,1, OK )/*;f9 (matrix) 2D */
OPC ( Trim, TRIM , Trim, undef, Trim, T,T, T,T, 1,1, OK )/*;f9 (string) */
OPC ( UnaryMinus, UNARY_MINUS , Same, Keep, UnaryMinus, BU,HC, B,HC, 1,1, UNARY+I+S )/*;% -a */
OPC ( UnaryPlus, UNARY_PLUS , Same, Keep, undef, BU,HC, B,HC, 1,1, UNARY+I+S )/*;% +a */
OPC ( Union, UNION , Union, undef, undef, XX,YY, XX,YY, 0,254, OK )/*; (a,b) */
OPC ( Units, UNITS , Units, undef, undef, XX,YY, T,T, 1,1, OK )/*;mds (with_units none) */
OPC ( UnitsOf, UNITS_OF , UnitsOf, undef, undef, WITH_UNITS,WITH_UNITS,UNITS,UNITS,1,1,OK+I )/*;mds (with_units) */
OPC ( Unpack, UNPACK , Unpack, undef, undef, XX,YY, XX,YY, 3,3, OK )/*;f9 (vector,mask,field) */
OPC ( Unsigned, UNSIGNED , Same, Keep, undef, BU,OU, BU,OU, 1,1, CAST+N+I )/*;% (a) */
OPC ( Val, VAL , Else, undef, undef, L,L, XX,YY, 1,1, OK )/*;vax (long) */
OPC ( ValidationOf, VALIDATION_OF , ValidationOf, undef, undef, PARAM,PARAM, XX,YY, 1,1, OK+I )/*;mds (param) */
OPC ( ValueOf, VALUE_OF , ValueOf, undef, undef, XX,YY, XX,YY, 1,1, OK+I )/*;mds (param signal wind VMS) */
OPC ( Var, VAR , Var, undef, undef, T,T, XX,YY, 1,2, OK+U )/*; (string,[exp]) variable */
OPC ( Vector, VECTOR , Vector, undef, undef, XX,YY, XX,YY, 0,254, OK+I+S )/*;%f9+ [a..z1:z2:dz..n@[this]]*/
OPC ( Verify, VERIFY , Same, Ttb, Verify, BU,T,SUBSCRIPT,SUBSCRIPT,2,3, OK )/*;f9 (string,set,[back]) */
OPC ( Wait, WAIT , Wait, undef, undef, F,F, F,F, 1,1, OK+U )/*; (seconds) */
OPC ( WhenOf, WHEN_OF , WhenOf, undef, undef, ACTION,DISPATCH, XX,YY, 1,1, OK+I )/*;mds (dispatch) */
OPC ( Where, WHERE , Where, undef, undef, XX,YY, XX,YY, 2,3, WHERE+N )/*;%f9 WHERE(expr)stmtELSEWHERE*/
OPC ( While, WHILE , While, undef, undef, XX,YY, XX,YY, 2,254, WHILE+N )/*;%cc WHILE(expr)stmt */
OPC ( WindowOf, WINDOW_OF , WindowOf, undef, undef, DIMENSION,DIMENSION,WINDOW,WINDOW,1,1,OK+I )/*;mds (dimension) */
OPC ( Word, WORD , Same, Keep, undef, W,W, W,W, 1,1, CAST+N+I )/*;% (a) (signed short) */
OPC ( WordUnsigned, WORD_UNSIGNED , Same, Keep, undef, WU,WU, WU,WU, 1,1, CAST+N+I )/*;% (a) (unsigned short) */
OPC ( Write, WRITE , Write, undef, undef, XX,YY, L,L, 1,254, OK+U )/*;% (unit|*,arg...) */
OPC ( Zero, ZERO , Array, undef, Zero, XX,YY, FLOAT,F, 0,2, OK+U )/*; ([size],[kind]) */
OPC ( 2Pi, $2PI , Constant, undef, 2Pi, F,HC, F,HC, 0,0, CONST )/*; twice pi */
OPC ( Narg, $NARG , Constant, undef, Narg, L,L, L,L, 0,0, CONST )/*; FUN number of arguments */
OPC ( Element, ELEMENT , Same, Element, Element, BU,T, T,T, 3,3, OK )/*;dcl (position,delim,string) */
OPC ( RcDroop, RC_DROOP , Trans, Sign, RcDroop, F,HC, F,HC, 3,3, OK )/*; (x,dim,rc-time) */
OPC ( ResetPrivate, RESET_PRIVATE , ResetPrivate, undef, undef, XX,YY, XX,YY, 0,0, OK+U )/*;mds () */
OPC ( ResetPublic, RESET_PUBLIC , ResetPublic, undef, undef, XX,YY, XX,YY, 0,0, OK+U )/*;mds () */
OPC ( ShowPrivate, SHOW_PRIVATE , ShowPrivate, undef, undef, XX,YY, XX,YY, 0,254, OK+U )/*;mds ([list...]) */
OPC ( ShowPublic, SHOW_PUBLIC , ShowPublic, undef, undef, XX,YY, XX,YY, 0,254, OK+U )/*;mds ([list...]) */
OPC ( ShowVm, SHOW_VM , ShowVm, undef, undef, L,L, XX,YY, 0,2, OK+U )/*;vax (print_option, mask) */
OPC ( Translate, TRANSLATE , Same, Adjust, Translate, T,T, T,T, 3,3, OK )/*;vax (string,translat,match) */
OPC ( TransposeMul, TRANSPOSE_MUL , Matrix, undef, TransposeMul, BU,FC, BU,FC, 2,2, OK )/*; (a,b) (a+)*b */
OPC ( Upcase, UPCASE , Same, Adjust, Upcase, T,T, T,T, 1,1, OK )/*; (string) */
OPC ( Using, USING , Using, undef, undef, XX,YY, XX,YY, 2,4, USING+N )/*;mds (exp,[def],[sht],[expt])*/
OPC ( Validation, VALIDATION , Validation, undef, undef, PARAM,PARAM,XX,YY,1,1, OK )/*;mds (param) data(val_of()) */
OPC ( MdsDefault, $DEFAULT , Trim, undef, MdsDefault, XX,YY, T,T, 0,0, CONST )/*;mds tree path */
OPC ( Expt, $EXPT , Trim, undef, Expt, XX,YY, T,T, 0,0, CONST )/*;mds experiment name */
OPC ( Shot, $SHOT , Trim, undef, Shot, L,L, L,L, 0,0, CONST )/*;mds shot number */
OPC ( GetDbi, GETDBI , GetDbi, undef, undef, T,T, T,BU, 1,2, OK )/*;mds (string,[index]) */
OPC ( Cull, CULL , Cull, undef, undef, XX,YY, XX,YY, 1,4, OK )/*;mds (arr dim,[dim],[sub],upc)*/
OPC ( Extend, EXTEND , Extend, undef, undef, XX,YY, XX,YY, 1,4, OK )/*;mds (arr dim,[dim],[sub],upc)*/
OPC ( ItoX, I_TO_X , ItoX, undef, undef, T,HC, T,HC, 1,2, OK )/*;mds (dimension,[indices]) */
OPC ( XtoI, X_TO_I , ItoX, undef, undef, T,HC, T,HC, 1,2, OK )/*;mds (dimension,[axis_pts]) */
OPC ( Map, MAP , Map, undef, undef, SUBSCRIPT,SUBSCRIPT,XX,YY,2,2, OK )/*;mds (array,indices) */
OPC ( CompileDependency, COMPILE_DEPENDENCY ,CompileDependency, undef, undef,T,T,DEPENDENCY,DEPENDENCY,1,1,OK+I )/*;mds (text) */
OPC ( DecompileDependency, DECOMPILE_DEPENDENCY ,DecompileDependency, undef, undef,DEPENDENCY,DEPENDENCY,T,T,1,1,OK+I)/*;mds (dependency) */
OPC ( BuildCall, BUILD_CALL , Build, undef, undef, XX,YY,CALL,BU, 3,254, OK+I )/*;mds (type,imag,rout,[arg]..)*/
OPC ( ErrorlogsOf, ERRORLOGS_OF , ErrorlogsOf, undef, undef, ACTION,ACTION, XX,YY, 1,1, OK+I )/*;mds (action) */
OPC ( PerformanceOf, PERFORMANCE_OF , PerformanceOf, undef, undef, ACTION,ACTION, XX,YY, 1,1, OK+I )/*;mds (action) */
OPC ( Xd, XD , Else, undef, undef, XX,YY, DSC,DSC,1,1, OK )/*;mds (any) */
OPC ( ConditionOf, CONDITION_OF , ConditionOf, undef, undef, CONDITION,CONDITION,XX,YY,1,1, OK+I )/*;mds (condition) */
OPC ( Sort, SORT , Sort, undef, undef, T,HC,SUBSCRIPT,SUBSCRIPT,1,2, OK )/*; (array,[upcase]) */
OPC ( This, $THIS , This, undef, undef, XX,YY, XX,YY, 0,0, CONST )/*;mds signal param or dimen */
OPC ( DataWithUnits, DATA_WITH_UNITS ,DataWithUnits, undef, undef, XX,YY, XX,YY, 1,1, OK+I )/*;mds (any) */
OPC ( Atm, $ATM , Constant, undef, P0, F,HC, F,HC, 0,0, CONST )/*;atmospheric pressure */
OPC ( Epsilon0, $EPSILON0 , Constant, undef, Epsilon0, F,HC, F,HC, 0,0, CONST )/*;permitivity of vacuum */
OPC ( Gn, $GN , Constant, undef, Gn, F,HC, F,HC, 0,0, CONST )/*;acceleration of gravity */
OPC ( Mu0, $MU0 , Constant, undef, Mu0, F,HC, F,HC, 0,0, CONST )/*;permeability of vacuum */
OPC ( Extract, EXTRACT , Same, Extract, Extract, BU,T, T,T, 3,3, OK )/*;dcl (start,length,string) */
OPC ( Finite, FINITE , Same, Any, Finite, T,HC, VV,VV, 1,1, OK )/*;idl (a) */
OPC ( BitSize, BIT_SIZE , Scalar,Keep, BitSize, BU,HC, L,L, 1,1, OK )/*;f9+ (i) */
OPC ( Modulo, MODULO , Same, Add, Modulo, BU,HC, BU,HC, 2,2, MUL+N )/*;f9 (a,p) */
OPC ( SelectedIntKind, SELECTED_INT_KIND ,Scalar,Any, SelectedIntKind,BU,HC,L,L, 1,1, OK )/*;f9 (r) */
OPC ( SelectedRealKind, SELECTED_REAL_KIND ,Scalar,Any, SelectedRealKind,BU,HC,L,L, 1,2, OK )/*;f9 (p,r) */
OPC ( Dsql, DSQL , Dsql, undef, undef, XX,YY, L,L, 1,254, OK+U )/*; (string,in,...outs,...) */
OPC ( Isql, ISQL , Isql, undef, undef, T,T, L,L, 1,1, OK+U )/*; (string) */
OPC ( Ftell, FTELL , Ftell, undef, undef, L,L, L,L, 1,1, OK+U )/*;%cc pos=(unit) */
OPC ( MakeAction, MAKE_ACTION , Make, undef, undef, XX,YY,ACTION,ACTION, 2,5, OK+I )/*;mds (dis,task,err,comp,perf)*/
OPC ( MakeCondition, MAKE_CONDITION , Make, undef, undef, XX,YY,CONDITION,WU, 2,2, OK+I )/*;mds (opcode,condition) */
OPC ( MakeConglom, MAKE_CONGLOM , Make, undef, undef, XX,YY,CONGLOM,CONGLOM, 4,4, OK+I )/*;mds (image,model,name,qual) */
OPC ( MakeDependency, MAKE_DEPENDENCY ,Make, undef, undef, XX,YY,DEPENDENCY,WU, 3,3, OK+I )/*;mds (opcode,arg1,arg2) */
OPC ( MakeDim, MAKE_DIM , Make, undef, undef, XX,YY,DIMENSION,DIMENSION,2,2, OK+I )/*;mds (window,axis) */
OPC ( MakeDispatch, MAKE_DISPATCH , Make, undef, undef, XX,YY,DISPATCH,BU, 5,5, OK+I )/*;mds (type,id,phase,when,com)*/
OPC ( MakeFunction, MAKE_FUNCTION , Make, undef, undef, XX,YY,FUNCTION,WU, 1,254, OK+I )/*;mds (opcode,[arguments...]) */
OPC ( MakeMethod, MAKE_METHOD , Make, undef, undef, XX,YY,METHOD,METHOD, 3,254, OK+I )/*;mds (timeout,method,obj,...)*/
OPC ( MakeParam, MAKE_PARAM , Make, undef, undef, XX,YY,PARAM,PARAM, 3,3, OK+I )/*;mds (value,help,validation) */
OPC ( MakeProcedure, MAKE_PROCEDURE , Make, undef, undef, XX,YY,PROCEDURE,PROCEDURE,3,254, OK+I )/*;mds (timeout,lang,proc,...) */
OPC ( MakeProgram, MAKE_PROGRAM , Make, undef, undef, XX,YY,PROGRAM,PROGRAM, 2,2, OK+I )/*;mds (timeout,program) */
OPC ( MakeRange, MAKE_RANGE , Make, undef, undef, XX,YY,RANGE,RANGE, 2,3, OK+I )/*;mds ([low],[high],[step]) */
OPC ( MakeRoutine, MAKE_ROUTINE , Make, undef, undef, XX,YY,ROUTINE,ROUTINE, 3,254, OK+I )/*;mds (timeout,image,rout,..) */
OPC ( MakeSignal, MAKE_SIGNAL , Make, undef, undef, XX,YY,SIGNAL,SIGNAL, 2,2+MAXDIM,OK+I )/*;mds (data,raw,[dim...]) */
OPC ( MakeWindow, MAKE_WINDOW , Make, undef, undef, XX,YY,WINDOW,WINDOW, 3,3, OK+I )/*;mds (istart,iend,x_at_0) */
OPC ( MakeWithUnits, MAKE_WITH_UNITS ,Make, undef, undef, XX,YY,WITH_UNITS,WITH_UNITS, 2,2,OK+I)/*;mds (data,units) */
OPC ( MakeCall, MAKE_CALL , Make, undef, undef, XX,YY,CALL,BU, 3,254, OK+I )/*;mds (type,imag,rout,[arg]..)*/
OPC ( ClassOf, CLASS_OF , ClassOf, undef, undef, XX,YY, BU,BU, 1,1, OK )/*;vms (any) */
OPC ( DscptrOf, DSCPTR_OF , DscptrOf, undef, undef, XX,YY, XX,YY, 1,2, OK+I )/*;mds (any_class_R,[num]) */
OPC ( KindOf, KIND_OF , KindOf, undef, undef, XX,YY, BU,BU, 1,1, OK )/*;mds (any) */
OPC ( NdescOf, NDESC_OF , NdescOf, undef, undef, PARAM,WITH_ERROR,BU,BU, 1,1, OK )/*;mds (class_R) */
OPC ( Accumulate, ACCUMULATE , Trans, Mask3, Accumulate, BU,HC, BU,HC, 1,3, OK )/*; (x,[dim],[mask]) */
OPC ( MakeSlope, MAKE_SLOPE , Make, undef, undef, XX,YY,SLOPE,SLOPE, 1,254, OK+I )/*;mds (slope,[begin,end]...) */
OPC ( Rem, REM , Rem, undef, undef, XX,YY, XX,YY, 1,254, OK+U )/*; (any,...) */
OPC ( CompletionMessageOf, COMPLETION_MESSAGE_OF ,CompletionMessageOf, undef, undef,ACTION,ACTION,XX,YY,1,1,OK+I )/*;mds (dispatch) */
OPC ( InterruptOf, INTERRUPT_OF , InterruptOf, undef, undef, ACTION,DISPATCH, T,T, 1,1, OK+I )/*;mds (dispatch) */
OPC ( Shotname, $SHOTNAME , Trim, undef, Shotname, T,T, T,T, 0,0, CONST )/*;mds shot number */
OPC ( BuildWithError, BUILD_WITH_ERROR ,Build, undef, undef, XX,YY,WITH_ERROR,WITH_ERROR,2,2, OK+I )/*;mds (data,error) */
OPC ( ErrorOf, ERROR_OF , ErrorOf, undef, undef, WITH_ERROR,WITH_ERROR,XX,YY, 1,1,OK+I)/*;mds (with_error) */
OPC ( MakeWithError, MAKE_WITH_ERROR ,Make, undef, undef, XX,YY,WITH_ERROR,WITH_ERROR, 2,2,OK+I)/*;mds (data,error) */
OPC ( DoTask, DO_TASK , DoTask, undef, undef, ACTION,METHOD, XX,XX, 1,1, OK )/*;mds (routine/method) */
OPC ( IsqlSet, ISQL_SET , IsqlSet, undef, undef, L,L, XX,YY, 1,3, OK+U )/*; (width,head) */
OPC ( FS_float, FS_FLOAT , Same, Keep, undef, FS,FS, FS,FS, 1,1, CAST+N+I )/*;% (a) */
OPC ( FS_complex, FS_COMPLEX , Same, Cmplx, Complex, FS,FS, FSC,FSC, 1,2, CAST+N+I )/*;% (x,y) */
OPC ( FT_float, FT_FLOAT , Same, Keep, undef, FT,FT, FT,FT, 1,1, CAST+N+I )/*;% (a) */
OPC ( FT_complex, FT_COMPLEX , Same, Cmplx, Complex, FT,FT, FTC,FTC, 1,2, CAST+N+I )/*;% (x,y) */
OPC ( BuildOpaque, BUILD_OPAQUE ,Build, undef, undef, XX,YY,OPAQUE,OPAQUE,2,2, OK+I )/*;mds (data,type_string) */
OPC ( MakeOpaque, MAKE_OPAQUE , Make, undef, undef, XX,YY,OPAQUE,OPAQUE, 2,2,OK+I )/*;mds (data,type_string) */
OPC ( Dict, DICT , Dict, undef, undef, XX,YY, XX,YY, 0,254, OK+I+S )/*;%f9+ [a..z1:z2:dz..n@[this]]*/
OPC ( Tuple, TUPLE , Tuple, undef, undef, XX,YY, XX,YY, 0,254, OK+I+S )/*;%f9+ [a..z1:z2:dz..n@[this]]*/
OPC ( List, LIST , List, undef, undef, XX,YY, XX,YY, 0,254, OK+I+S )/*;%f9+ [a..z1:z2:dz..n@[this]]*/
COM/*
.endm ;*/
| 94.619342 | 141 | 0.583908 | [
"shape",
"vector",
"model"
] |
ca0611f3c5b3db12204c43c65dbd6594f66c773c | 1,821 | h | C | Tests/Headers/PackingSerializerTests.h | MINATILO/packing-generation | 4d4f5d037e0687b57178602b989431e82a5c8b96 | [
"MIT"
] | 79 | 2015-08-23T12:05:30.000Z | 2022-03-31T16:39:56.000Z | Tests/Headers/PackingSerializerTests.h | MINATILO/packing-generation | 4d4f5d037e0687b57178602b989431e82a5c8b96 | [
"MIT"
] | 31 | 2015-07-20T17:57:08.000Z | 2022-03-02T10:31:50.000Z | Tests/Headers/PackingSerializerTests.h | MINATILO/packing-generation | 4d4f5d037e0687b57178602b989431e82a5c8b96 | [
"MIT"
] | 36 | 2015-10-14T02:43:16.000Z | 2022-03-18T12:51:03.000Z | // Copyright (c) 2013 Vasili Baranau
// Distributed under the MIT software license
// See the accompanying file License.txt or http://opensource.org/licenses/MIT
#ifndef Headers_PackingSerializerTests_h
#define Headers_PackingSerializerTests_h
#include <boost/shared_ptr.hpp>
#include "Generation/Model/Headers/Types.h"
namespace PackingServices { class PackingSerializer; }
namespace Tests { class EndiannessProviderStub; }
namespace Tests
{
class PackingSerializerTests
{
private:
static Model::Packing particles;
static boost::shared_ptr<PackingServices::PackingSerializer> packingSerializer;
static boost::shared_ptr<EndiannessProviderStub> endiannessProvider;
static const int particlesCount = 4;
public:
static void RunTests();
private:
static void SetUp();
static void TearDown();
static void SavePacking_InBigEndian_PackingIsDifferentWhenLoadingInLittleEndian();
static void SavePacking_InLittleEndian_PackingIsDifferentWhenLoadingInBigEndian();
static void SavePacking_InBigEndian_PackingIsNotChanged();
static void SavePacking_InBigEndian_PackingIsCorrectWhenLoadedInBigEndian();
static void SavePacking_InLittleEndian_PackingIsCorrectWhenLoadedInLittleEndian();
static void SerializeInsertionRadii_InBigEndian_DataIsDifferentWhenLoadingInLittleEndian();
static void SerializeInsertionRadii_InLittleEndian_DataIsDifferentWhenLoadingInBigEndian();
static void SerializeInsertionRadii_InBigEndian_DataIsNotChanged();
static void SerializeInsertionRadii_InBigEndian_DataIsCorrectWhenLoadedInBigEndian();
static void SerializeInsertionRadii_InLittleEndian_DataIsCorrectWhenLoadedInLittleEndian();
};
}
#endif /* Headers_PackingSerializerTests_h */
| 41.386364 | 99 | 0.790774 | [
"model"
] |
ca077b43058e25adecc11a2d75a5dc0a5394a2da | 14,731 | c | C | iraf.v2161/vendor/x11iraf/xgterm/scrollbar.c | ysBach/irafdocgen | b11fcd75cc44b01ae69c9c399e650ec100167a54 | [
"MIT"
] | 2 | 2019-12-01T15:19:09.000Z | 2019-12-02T16:48:42.000Z | iraf.v2161/vendor/x11iraf/xgterm/scrollbar.c | ysBach/irafdocgen | b11fcd75cc44b01ae69c9c399e650ec100167a54 | [
"MIT"
] | 1 | 2019-11-30T13:48:50.000Z | 2019-12-02T19:40:25.000Z | iraf.v2161/vendor/x11iraf/xgterm/scrollbar.c | ysBach/irafdocgen | b11fcd75cc44b01ae69c9c399e650ec100167a54 | [
"MIT"
] | null | null | null | /*
* $XConsortium: scrollbar.c,v 1.44 94/04/02 12:42:01 gildea Exp $
*/
/*
* Copyright 1987 by Digital Equipment Corporation, Maynard, Massachusetts.
*
* All Rights Reserved
*
* Permission to use, copy, modify, and distribute this software and its
* documentation for any purpose and without fee is hereby granted,
* provided that the above copyright notice appear in all copies and that
* both that copyright notice and this permission notice appear in
* supporting documentation, and that the name of Digital Equipment
* Corporation not be used in advertising or publicity pertaining to
* distribution of the software without specific, written prior permission.
*
*
* DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
* ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
* DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
* ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
* WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
* ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
* SOFTWARE.
*/
#include "ptyx.h" /* gets Xt headers, too */
#include <stdio.h>
#include <ctype.h>
#include <X11/Xatom.h>
#include <X11/StringDefs.h>
#include <X11/Shell.h>
#include <X11/Xaw/Scrollbar.h>
#include "data.h"
#include "error.h"
#include "menu.h"
/* Event handlers */
static void ScrollTextTo();
static void ScrollTextUpDownBy();
/* resize the text window for a terminal screen, modifying the
* appropriate WM_SIZE_HINTS and taking advantage of bit gravity.
*/
static void ResizeScreen(xw, min_width, min_height )
register XgtermWidget xw;
int min_width, min_height;
{
register TScreen *screen = &xw->screen;
#ifndef nothack
XSizeHints sizehints;
long supp;
#endif
XtGeometryResult geomreqresult;
Dimension reqWidth, reqHeight, repWidth, repHeight;
/*
* I'm going to try to explain, as I understand it, why we
* have to do XGetWMNormalHints and XSetWMNormalHints here,
* although I can't guarantee that I've got it right.
*
* In a correctly written toolkit program, the Shell widget
* parses the user supplied geometry argument. However,
* because of the way xgterm does things, the VT100 widget does
* the parsing of the geometry option, not the Shell widget.
* The result of this is that the Shell widget doesn't set the
* correct window manager hints, and doesn't know that the
* user has specified a geometry.
*
* The XtVaSetValues call below tells the Shell widget to
* change its hints. However, since it's confused about the
* hints to begin with, it doesn't get them all right when it
* does the SetValues -- it undoes some of what the VT100
* widget did when it originally set the hints.
*
* To fix this, we do the following:
*
* 1. Get the sizehints directly from the window, going around
* the (confused) shell widget.
* 2. Call XtVaSetValues to let the shell widget know which
* hints have changed. Note that this may not even be
* necessary, since we're going to right ahead after that
* and set the hints ourselves, but it's good to put it
* here anyway, so that when we finally do fix the code so
* that the Shell does the right thing with hints, we
* already have the XtVaSetValues in place.
* 3. We set the sizehints directly, this fixing up whatever
* damage was done by the Shell widget during the
* XtVaSetValues.
*
* Gross, huh?
*
* The correct fix is to redo VTRealize, VTInitialize and
* VTSetValues so that font processing happens early enough to
* give back responsibility for the size hints to the Shell.
*
* Someday, we hope to have time to do this. Someday, we hope
* to have time to completely rewrite xgterm.
*/
#ifndef nothack
/*
* NOTE: If you change the way any of the hints are calculated
* below, make sure you change the calculation both in the
* sizehints assignments and in the XtVaSetValues.
*/
if (! XGetWMNormalHints(screen->display, XtWindow(XtParent(xw)),
&sizehints, &supp))
sizehints.flags = 0;
sizehints.base_width = min_width;
sizehints.base_height = min_height;
sizehints.width_inc = FontWidth(screen);
sizehints.height_inc = FontHeight(screen);
sizehints.min_width = sizehints.base_width + sizehints.width_inc;
sizehints.min_height = sizehints.base_height + sizehints.height_inc;
sizehints.flags |= (PBaseSize|PMinSize|PResizeInc);
/* These are obsolete, but old clients may use them */
sizehints.width = (screen->max_col + 1) * FontWidth(screen)
+ min_width;
sizehints.height = (screen->max_row + 1) * FontHeight(screen)
+ min_height;
#endif
/*
* Note: width and height are not set here because they are
* obsolete.
*/
XtVaSetValues(XtParent(xw),
XtNbaseWidth, min_width,
XtNbaseHeight, min_height,
XtNwidthInc, FontWidth(screen),
XtNheightInc, FontHeight(screen),
XtNminWidth, min_width + FontWidth(screen),
XtNminHeight, min_height + FontHeight(screen),
NULL);
reqWidth = (screen->max_col + 1) * FontWidth(screen) + min_width;
reqHeight = FontHeight(screen) * (screen->max_row + 1) + min_height;
geomreqresult = XtMakeResizeRequest ((Widget)xw, reqWidth, reqHeight,
&repWidth, &repHeight);
if (geomreqresult == XtGeometryAlmost) {
geomreqresult = XtMakeResizeRequest ((Widget)xw, repWidth,
repHeight, NULL, NULL);
}
#ifndef nothack
XSetWMNormalHints(screen->display, XtWindow(XtParent(xw)), &sizehints);
#endif
}
void DoResizeScreen (xw)
register XgtermWidget xw;
{
int border = 2 * xw->screen.border;
ResizeScreen (xw, border + xw->screen.scrollbar, border);
}
static Widget CreateScrollBar(xw, x, y, height)
XgtermWidget xw;
int x, y, height;
{
Widget scrollWidget;
static Arg argList[] = {
{XtNx, (XtArgVal) 0},
{XtNy, (XtArgVal) 0},
{XtNheight, (XtArgVal) 0},
{XtNreverseVideo, (XtArgVal) 0},
{XtNorientation, (XtArgVal) XtorientVertical},
{XtNborderWidth, (XtArgVal) 1},
};
argList[0].value = (XtArgVal) x;
argList[1].value = (XtArgVal) y;
argList[2].value = (XtArgVal) height;
argList[3].value = (XtArgVal) xw->misc.re_verse;
scrollWidget = XtCreateWidget("scrollbar", scrollbarWidgetClass,
(Widget)xw, argList, XtNumber(argList));
XtAddCallback (scrollWidget, XtNscrollProc, ScrollTextUpDownBy, 0);
XtAddCallback (scrollWidget, XtNjumpProc, ScrollTextTo, 0);
return (scrollWidget);
}
static void RealizeScrollBar (sbw, screen)
Widget sbw;
TScreen *screen;
{
XtRealizeWidget (sbw);
}
ScrollBarReverseVideo(scrollWidget)
register Widget scrollWidget;
{
Arg args[4];
int nargs = XtNumber(args);
unsigned long bg, fg, bdr;
Pixmap bdpix;
XtSetArg(args[0], XtNbackground, &bg);
XtSetArg(args[1], XtNforeground, &fg);
XtSetArg(args[2], XtNborderColor, &bdr);
XtSetArg(args[3], XtNborderPixmap, &bdpix);
XtGetValues (scrollWidget, args, nargs);
args[0].value = (XtArgVal) fg;
args[1].value = (XtArgVal) bg;
nargs--; /* don't set border_pixmap */
if (bdpix == XtUnspecifiedPixmap) { /* if not pixmap then pixel */
args[2].value = args[1].value; /* set border to new fg */
} else { /* ignore since pixmap */
nargs--; /* don't set border pixel */
}
XtSetValues (scrollWidget, args, nargs);
}
ScrollBarDrawThumb(scrollWidget)
register Widget scrollWidget;
{
register TScreen *screen = &term->screen;
register int thumbTop, thumbHeight, totalHeight;
thumbTop = screen->topline + screen->savedlines;
thumbHeight = screen->max_row + 1;
totalHeight = thumbHeight + screen->savedlines;
XawScrollbarSetThumb(scrollWidget,
((float)thumbTop) / totalHeight,
((float)thumbHeight) / totalHeight);
}
ResizeScrollBar(scrollWidget, x, y, height)
register Widget scrollWidget;
int x, y;
unsigned height;
{
XtConfigureWidget(scrollWidget, x, y, scrollWidget->core.width,
height, scrollWidget->core.border_width);
if (term->misc.sb_right)
XtMoveWidget(scrollWidget, x,y);
ScrollBarDrawThumb(scrollWidget);
}
WindowScroll(screen, top)
register TScreen *screen;
int top;
{
register int i, lines;
register int scrolltop, scrollheight, refreshtop;
register int x = 0;
if (top < -screen->savedlines)
top = -screen->savedlines;
else if (top > 0)
top = 0;
if((i = screen->topline - top) == 0) {
ScrollBarDrawThumb(screen->scrollWidget);
return;
}
if(screen->cursor_state)
HideCursor();
lines = i > 0 ? i : -i;
if(lines > screen->max_row + 1)
lines = screen->max_row + 1;
scrollheight = screen->max_row - lines + 1;
if(i > 0)
refreshtop = scrolltop = 0;
else {
scrolltop = lines;
refreshtop = scrollheight;
}
x = (term->misc.sb_right? screen->border : screen->scrollbar+screen->border);
scrolling_copy_area(screen, scrolltop, scrollheight, -i);
screen->topline = top;
ScrollSelection(screen, i);
XClearArea(
screen->display,
TextWindow(screen),
(int) x,
(int) refreshtop * FontHeight(screen) + screen->border,
(unsigned) Width(screen),
(unsigned) lines * FontHeight(screen),
FALSE);
ScrnRefresh(screen, refreshtop, 0, lines, screen->max_col + 1, False);
ScrollBarDrawThumb(screen->scrollWidget);
}
ScrollBarOn (xw, init, doalloc)
XgtermWidget xw;
int init, doalloc;
{
register TScreen *screen = &xw->screen;
register int border = 2 * screen->border;
register int i;
if(screen->scrollbar)
return;
if (init) { /* then create it only */
if (screen->scrollWidget) return;
/* make it a dummy size and resize later */
if ((screen->scrollWidget = CreateScrollBar (xw, -1, - 1, 5))
== NULL) {
Bell();
return;
}
return;
}
if (!screen->scrollWidget) {
Bell ();
Bell ();
return;
}
if (doalloc && screen->allbuf) {
if((screen->allbuf =
(ScrnBuf) realloc((char *) screen->buf,
(unsigned) 4*(screen->max_row + 2 +
screen->savelines) *
sizeof(char *)))
== NULL)
Error (ERROR_SBRALLOC);
screen->buf = &screen->allbuf[4 * screen->savelines];
memmove( (char *)screen->buf, (char *)screen->allbuf,
4 * (screen->max_row + 2) * sizeof (char *));
for(i = 4 * screen->savelines - 1 ; i >= 0 ; i--)
if((screen->allbuf[i] =
(Char *)calloc((unsigned) screen->max_col+1, sizeof(char))) ==
NULL)
Error (ERROR_SBRALLOC2);
}
if (term->misc.sb_right) {
ResizeScrollBar (screen->scrollWidget,
screen->fullVwin.fullwidth -
screen->scrollWidget->core.width -
screen->scrollWidget->core.border_width,
0,
Height (screen) + border -1);
} else {
ResizeScrollBar (screen->scrollWidget, -1, -1,
Height (screen) + border);
}
RealizeScrollBar (screen->scrollWidget, screen);
screen->scrollbar = screen->scrollWidget->core.width +
screen->scrollWidget->core.border_width;
ScrollBarDrawThumb(screen->scrollWidget);
DoResizeScreen (xw);
XtMapWidget(screen->scrollWidget);
update_scrollbar ();
if (screen->buf) {
XClearWindow (screen->display, XtWindow (term));
Redraw ();
}
}
ScrollBarOff(screen)
register TScreen *screen;
{
if(!screen->scrollbar)
return;
XtUnmapWidget(screen->scrollWidget);
screen->scrollbar = 0;
DoResizeScreen (term);
update_scrollbar ();
if (screen->buf) {
XClearWindow (screen->display, XtWindow (term));
Redraw ();
}
}
/*ARGSUSED*/
static void ScrollTextTo(scrollbarWidget, client_data, call_data)
Widget scrollbarWidget;
XtPointer client_data;
XtPointer call_data;
{
float *topPercent = (float *) call_data;
register TScreen *screen = &term->screen;
int thumbTop; /* relative to first saved line */
int newTopLine;
/*
screen->savedlines : Number of offscreen text lines,
screen->maxrow + 1 : Number of onscreen text lines,
screen->topline : -Number of lines above the last screen->max_row+1 lines
*/
thumbTop = *topPercent * (screen->savedlines + screen->max_row+1);
newTopLine = thumbTop - screen->savedlines;
WindowScroll(screen, newTopLine);
}
/*ARGSUSED*/
static void ScrollTextUpDownBy(scrollbarWidget, client_data, call_data)
Widget scrollbarWidget;
XtPointer client_data;
XtPointer call_data;
{
int pixels = (int) call_data;
register TScreen *screen = &term->screen;
register int rowOnScreen, newTopLine;
rowOnScreen = pixels / FontHeight(screen);
if (rowOnScreen == 0) {
if (pixels < 0)
rowOnScreen = -1;
else if (pixels > 0)
rowOnScreen = 1;
}
newTopLine = screen->topline + rowOnScreen;
WindowScroll(screen, newTopLine);
}
/*
* assume that b is lower case and allow plural
*/
static int specialcmplowerwiths (a, b)
char *a, *b;
{
register char ca, cb;
if (!a || !b) return 0;
while (1) {
ca = *a;
cb = *b;
if (isascii(ca) && isupper(ca)) { /* lowercasify */
#ifdef _tolower
ca = _tolower (ca);
#else
ca = tolower (ca);
#endif
}
if (ca != cb || ca == '\0') break; /* if not eq else both nul */
a++, b++;
}
if (cb == '\0' && (ca == '\0' || (ca == 's' && a[1] == '\0')))
return 1;
return 0;
}
static int params_to_pixels (screen, params, n)
TScreen *screen;
String *params;
int n;
{
register mult = 1;
register char *s;
switch (n > 2 ? 2 : n) {
case 2:
s = params[1];
if (specialcmplowerwiths (s, "page")) {
mult = (screen->max_row + 1) * FontHeight(screen);
} else if (specialcmplowerwiths (s, "halfpage")) {
mult = ((screen->max_row + 1) * FontHeight(screen)) >> 1;
} else if (specialcmplowerwiths (s, "pixel")) {
mult = 1;
} /* else assume that it is Line */
mult *= atoi (params[0]);
break;
case 1:
mult = atoi (params[0]) * FontHeight(screen); /* lines */
break;
default:
mult = screen->scrolllines * FontHeight(screen);
break;
}
return mult;
}
/*ARGSUSED*/
void HandleScrollForward (gw, event, params, nparams)
Widget gw;
XEvent *event;
String *params;
Cardinal *nparams;
{
XgtermWidget w = (XgtermWidget) gw;
register TScreen *screen = &w->screen;
ScrollTextUpDownBy (gw, (XtPointer) NULL,
(XtPointer)params_to_pixels (screen, params, (int) *nparams));
return;
}
/*ARGSUSED*/
void HandleScrollBack (gw, event, params, nparams)
Widget gw;
XEvent *event;
String *params;
Cardinal *nparams;
{
XgtermWidget w = (XgtermWidget) gw;
register TScreen *screen = &w->screen;
ScrollTextUpDownBy (gw, (XtPointer) NULL,
(XtPointer)-params_to_pixels (screen, params, (int) *nparams));
return;
}
| 27.68985 | 85 | 0.673478 | [
"geometry"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.