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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
7fb6c9213e9cba6de171cd6efd835db36998b326 | 4,575 | h | C | dispatcher/windows/mfx_dxva2_device.h | xhaihao/oneVPL | ce99bf9039ce50e756b70a86a03098ab14970532 | [
"MIT"
] | null | null | null | dispatcher/windows/mfx_dxva2_device.h | xhaihao/oneVPL | ce99bf9039ce50e756b70a86a03098ab14970532 | [
"MIT"
] | null | null | null | dispatcher/windows/mfx_dxva2_device.h | xhaihao/oneVPL | ce99bf9039ce50e756b70a86a03098ab14970532 | [
"MIT"
] | null | null | null | /*############################################################################
# Copyright (C) 2012-2020 Intel Corporation
#
# SPDX-License-Identifier: MIT
############################################################################*/
#ifndef DISPATCHER_WINDOWS_MFX_DXVA2_DEVICE_H_
#define DISPATCHER_WINDOWS_MFX_DXVA2_DEVICE_H_
#include <windows.h>
#define TOSTRING(L) #L
#define STRINGIFY(L) TOSTRING(L)
#if defined(MEDIASDK_UWP_DISPATCHER)
#if defined(MFX_D3D9_ENABLED) && !defined(MFX_FORCE_D3D9_ENABLED)
#undef MFX_D3D9_ENABLED
#pragma message("\n\nATTENTION:\nin file\n\t" __FILE__ \
" (" STRINGIFY(__LINE__) "):\nUsing of D3D9 disabled for UWP!\n\n")
#endif
#if defined(MFX_FORCE_D3D9_ENABLED)
#define MFX_D3D9_ENABLED
#endif
#else
#define MFX_D3D9_ENABLED
#pragma message("\n\nATTENTION:\nin file\n\t" __FILE__ \
" (" STRINGIFY(__LINE__) "):\nUsing of D3D9 enabled!\n\n")
#endif
#include <vpl/mfxdefs.h>
#ifdef DXVA2DEVICE_LOG
#include <stdio.h>
#define DXVA2DEVICE_TRACE(expr) printf expr;
#define DXVA2DEVICE_TRACE_OPERATION(expr) expr;
#else
#define DXVA2DEVICE_TRACE(expr)
#define DXVA2DEVICE_TRACE_OPERATION(expr)
#endif
namespace MFX {
class DXDevice {
public:
// Default constructor
DXDevice(void);
// Destructor
virtual ~DXDevice(void) = 0;
// Initialize device using DXGI 1.1 or VAAPI interface
virtual bool Init(const mfxU32 adapterNum) = 0;
// Obtain graphic card's parameter
mfxU32 GetVendorID(void) const;
mfxU32 GetDeviceID(void) const;
mfxU64 GetDriverVersion(void) const;
mfxU64 GetLUID(void) const;
// Provide the number of available adapters
mfxU32 GetAdapterCount(void) const;
// Close the object
virtual void Close(void);
// Load the required DLL module
void LoadDLLModule(const wchar_t *pModuleName);
protected:
// Free DLL module
void UnloadDLLModule(void);
// Handle to the DLL library
HMODULE m_hModule;
// Number of adapters available
mfxU32 m_numAdapters;
// Vendor ID
mfxU32 m_vendorID;
// Device ID
mfxU32 m_deviceID;
// x.x.x.x each x of two bytes
mfxU64 m_driverVersion;
// LUID
mfxU64 m_luid;
private:
// unimplemented by intent to make this class and its descendants non-copyable
DXDevice(const DXDevice &);
void operator=(const DXDevice &);
};
#ifdef MFX_D3D9_ENABLED
class D3D9Device : public DXDevice {
public:
// Default constructor
D3D9Device(void);
// Destructor
virtual ~D3D9Device(void);
// Initialize device using D3D v9 interface
virtual bool Init(const mfxU32 adapterNum);
// Close the object
virtual void Close(void);
protected:
// Pointer to the D3D v9 interface
void *m_pD3D9;
// Pointer to the D3D v9 extended interface
void *m_pD3D9Ex;
};
#endif // MFX_D3D9_ENABLED
class DXGI1Device : public DXDevice {
public:
// Default constructor
DXGI1Device(void);
// Destructor
virtual ~DXGI1Device(void);
// Initialize device
virtual bool Init(const mfxU32 adapterNum);
// Close the object
virtual void Close(void);
protected:
// Pointer to the DXGI1 factory
void *m_pDXGIFactory1;
// Pointer to the current DXGI1 adapter
void *m_pDXGIAdapter1;
};
class DXVA2Device {
public:
// Default constructor
DXVA2Device(void);
// Destructor
~DXVA2Device(void);
// Initialize device using D3D v9 interface
bool InitD3D9(const mfxU32 adapterNum);
// Initialize device using DXGI 1.1 interface
bool InitDXGI1(const mfxU32 adapterNum);
// Obtain graphic card's parameter
mfxU32 GetVendorID(void) const;
mfxU32 GetDeviceID(void) const;
mfxU64 GetDriverVersion(void) const;
// Provide the number of available adapters
mfxU32 GetAdapterCount(void) const;
void Close(void);
protected:
#ifdef MFX_D3D9_ENABLED
// Get vendor & device IDs by alternative way (D3D9 in Remote Desktop sessions)
void UseAlternativeWay(const D3D9Device *pD3D9Device);
#endif // MFX_D3D9_ENABLED
// Number of adapters available
mfxU32 m_numAdapters;
// Vendor ID
mfxU32 m_vendorID;
// Device ID
mfxU32 m_deviceID;
//x.x.x.x
mfxU64 m_driverVersion;
private:
// unimplemented by intent to make this class non-copyable
DXVA2Device(const DXVA2Device &);
void operator=(const DXVA2Device &);
};
} // namespace MFX
#endif // DISPATCHER_WINDOWS_MFX_DXVA2_DEVICE_H_
| 25.137363 | 91 | 0.667978 | [
"object"
] |
7fb70b23ab4087769f0527c619fb25a6a6817c39 | 1,270 | h | C | plugin/accountssortfilterproxymodel.h | meego-tablet-ux/meego-app-im | af526f024f5ed5897e0178452d12dcb0e004b41d | [
"Apache-2.0"
] | null | null | null | plugin/accountssortfilterproxymodel.h | meego-tablet-ux/meego-app-im | af526f024f5ed5897e0178452d12dcb0e004b41d | [
"Apache-2.0"
] | null | null | null | plugin/accountssortfilterproxymodel.h | meego-tablet-ux/meego-app-im | af526f024f5ed5897e0178452d12dcb0e004b41d | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2011 Intel Corporation.
*
* This program is licensed under the terms and conditions of the
* Apache License, version 2.0. The full text of the Apache License is at
* http://www.apache.org/licenses/LICENSE-2.0
*/
#ifndef ACCOUNTSSORTFILTERPROXYMODEL_H
#define ACCOUNTSSORTFILTERPROXYMODEL_H
#include "imaccountsmodel.h"
#include <QObject>
#include <QSortFilterProxyModel>
class AccountsSortFilterProxyModel : public QSortFilterProxyModel
{
Q_OBJECT
// we need this so that the filter menu in QML can tell the size of the account switcher menu
Q_PROPERTY(int length READ length NOTIFY lengthChanged)
public:
AccountsSortFilterProxyModel(IMAccountsModel *model, QObject *parent = 0);
~AccountsSortFilterProxyModel();
int length() const;
/**
* This allows to access account data by row number
*/
Q_INVOKABLE QVariant dataByRow(const int row, const int role);
Q_SIGNALS:
void lengthChanged();
protected:
bool filterAcceptsColumn(int sourceColumn, const QModelIndex &sourceParent) const;
bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const;
bool lessThan(const QModelIndex &left, const QModelIndex &right) const;
};
#endif // ACCOUNTSSORTFILTERPROXYMODEL_H
| 27.608696 | 97 | 0.755118 | [
"model"
] |
7fba53179fc94e2f4fd9866a34ff38a62fe62648 | 2,139 | h | C | content/browser/background_fetch/storage/get_settled_fetches_task.h | zipated/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 2,151 | 2020-04-18T07:31:17.000Z | 2022-03-31T08:39:18.000Z | content/browser/background_fetch/storage/get_settled_fetches_task.h | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 395 | 2020-04-18T08:22:18.000Z | 2021-12-08T13:04:49.000Z | content/browser/background_fetch/storage/get_settled_fetches_task.h | cangulcan/src | 2b8388091c71e442910a21ada3d97ae8bc1845d3 | [
"BSD-3-Clause"
] | 338 | 2020-04-18T08:03:10.000Z | 2022-03-29T12:33:22.000Z | // 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 CONTENT_BROWSER_BACKGROUND_FETCH_STORAGE_GET_SETTLED_FETCHES_TASK_H_
#define CONTENT_BROWSER_BACKGROUND_FETCH_STORAGE_GET_SETTLED_FETCHES_TASK_H_
#include "base/callback_forward.h"
#include "content/browser/background_fetch/storage/database_task.h"
#include "content/common/service_worker/service_worker_status_code.h"
#include "storage/browser/blob/blob_data_handle.h"
namespace content {
namespace background_fetch {
class GetSettledFetchesTask : public DatabaseTask {
public:
using SettledFetchesCallback = base::OnceCallback<void(
blink::mojom::BackgroundFetchError,
bool,
std::vector<BackgroundFetchSettledFetch>,
std::vector<std::unique_ptr<storage::BlobDataHandle>>)>;
GetSettledFetchesTask(BackgroundFetchDataManager* data_manager,
BackgroundFetchRegistrationId registration_id,
SettledFetchesCallback callback);
~GetSettledFetchesTask() override;
// DatabaseTask implementation:
void Start() override;
private:
void DidGetCompletedRequests(const std::vector<std::string>& data,
ServiceWorkerStatusCode status);
void FillFailedResponse(ServiceWorkerResponse* response,
const base::RepeatingClosure& callback);
void FillSuccessfulResponse(ServiceWorkerResponse* response,
const base::RepeatingClosure& callback);
void FinishTaskWithErrorCode(blink::mojom::BackgroundFetchError error);
BackgroundFetchRegistrationId registration_id_;
SettledFetchesCallback settled_fetches_callback_;
std::vector<BackgroundFetchSettledFetch> settled_fetches_;
bool background_fetch_succeeded_ = true;
base::WeakPtrFactory<GetSettledFetchesTask> weak_factory_; // Keep as last.
DISALLOW_COPY_AND_ASSIGN(GetSettledFetchesTask);
};
} // namespace background_fetch
} // namespace content
#endif // CONTENT_BROWSER_BACKGROUND_FETCH_STORAGE_GET_SETTLED_FETCHES_TASK_H_
| 34.5 | 79 | 0.767648 | [
"vector"
] |
7fbba4fb73f65f0a14ba6b083b50eb771d40658d | 18,369 | h | C | EasyFramework3d/managed/gl/model/ModelManager.h | sizilium/FlexChess | f12b94e800ddcb00535067eca3b560519c9122e0 | [
"MIT"
] | null | null | null | EasyFramework3d/managed/gl/model/ModelManager.h | sizilium/FlexChess | f12b94e800ddcb00535067eca3b560519c9122e0 | [
"MIT"
] | null | null | null | EasyFramework3d/managed/gl/model/ModelManager.h | sizilium/FlexChess | f12b94e800ddcb00535067eca3b560519c9122e0 | [
"MIT"
] | null | null | null | /**
* @file ModelManager.h
* @author maccesch
* @date 28.09.2007
* @brief This file is part of the Vision Synthesis Easy Framework.\n
* This file has no copyright; you can change everything.
* Visit www.vision-synthesis.de or www.easy-framework.de for further informations.\n
* If there is a bug please send a mail to bug@vision-synthesis.de. No warranty is given!
*/
#ifndef MODELMANAGER_H_
#define MODELMANAGER_H_
#define DEFAULT_CLICK_REGION 3
#define DEFAULT_FOV_Y 45
#define DEFAULT_Z_NEAR 0.1
#define DEFAULT_Z_FAR 1000
#define DEFAULT_BUFFER_SIZE 512
// includes
#include <vs/Build.hpp>
#include <string>
#include <vector>
#include <map>
#include <set>
#include <list>
#include <GL/gl.h>
#include <vs/base/interfaces/AbstractManager.hpp>
#include <vs/managed/gl/model/ModelManager.h>
#include <vs/base/util/IDGenerator.hpp>
#include <vs/core/gl/Color.h>
// #include <vs/core/gl/Camera.h>
#include <vs/base/math/DoubleVector.h>
#include <vs/base/cont/List.hpp>
#include <vs/base/interfaces/MsgObservable.hpp>
namespace vs {
// predeclarations
namespace core {
namespace gl {
class Camera;
}
}
namespace managed {
namespace gl {
namespace model {
// predeclarations
class ManagedModel;
class ManagedModelBinder;
using namespace std;
// TODO document default parameter for ModelManager
class VS_EXPORT ModelManager : public base::interfaces::AbstractManager<ModelManager>,
public base::interfaces::MsgObservable<unsigned int> {
private:
friend class ManagedModel;
friend class ManagedModelBinder;
friend class ModelFactory;
typedef list<GLuint> uilist;
/**
* Operation constant in the renderQueue.
* It tells the renderQueue traverser that the successing data should be interpreted as rotation.
* For details see the code of printRenderQueue().
*/
static const int ROTATION;
/**
* Operation constant in the renderQueue.
* It tells the renderQueue traverser that the successing data should be interpreted as translation.
* For details see the code of printRenderQueue().
*/
static const int TRANSLATION;
/**
* Operation constant in the renderQueue.
* It tells the renderQueue traverser that the successing data should be interpreted as scalation.
* For details see the code of printRenderQueue().
*/
static const int SCALATION;
/**
* Operation constant in the renderQueue.
* It tells the renderQueue traverser that glPushMatrix() has to be called.
* For details see the code of printRenderQueue().
*/
static const int PUSH;
/**
* Operation constant in the renderQueue.
* It tells the renderQueue traverser that glPopMatrix() has to be called.
* For details see the code of printRenderQueue().
*/
static const int POP;
/**
* Operation constant in the renderQueue.
* It tells the renderQueue traverser that the successing data should be interpreted as model data
* until DRAW_END is found. For details see the code of printRenderQueue().
*/
static const int DRAW;
/**
* Operation constant in the renderQueue.
* It tells the renderQueue traverser that the model data ends. To every DRAW belongs one DRAW_END.
* For details see the code of printRenderQueue().
*/
static const int DRAW_END;
/**
* Operation constant in the renderQueue.
* It tells the renderQueue traverser that the successing data should be interpreted as color.
* For details see the code of printRenderQueue().
*/
static const int COLOR;
/**
* Operation constant in the renderQueue.
* It tells the renderQueue traverser that the successing data should be interpreted as euler.
* For details see the code of printRenderQueue().
*/
static const int EULER;
// only opaque model are handled so far
// all the unsigned ints here refer to ids (= indices)
map<unsigned int, uilist> models2textures; // model -> textures
// TODO : is there only one display list per (model, texture)-pair ?
map<pair<unsigned int, GLuint>, uilist> modelsTex2displayLists; // model, textures -> display lists
map<unsigned int, uilist> models2untexturedDLists; // model -> untextured display lists
// textures -> last occurence in the renderQueue
map< unsigned int, list<double>::iterator> textures2lastOccur;
// variables for loading purposes only
// unsigned int displayListNumber; // number of display lists
map<string, list<unsigned int> > textureNames2models; // texture names -> model
map<string, unsigned int> texNames2texIds;
map<string, vector<unsigned int> > filenames2models;
map<pair<string, string>, unsigned int> objNamesFilenames2models;
map<unsigned int, base::math::DoubleVector> models2centers;
map<unsigned int, base::math::DoubleVector> models2rotations;
map<unsigned int, base::math::DoubleVector> models2sizes;
map<unsigned int, core::gl::Color> models2colors;
/// In this field translations, rotations, pushs, pops, draws, etc are queued
/// for drawing. It is traversed and drawn by drawQueue().
/// For the structure of the renderQueue see the source code of printRenderQueue()
list<double> renderQueue;
/// When a texture in the renderQueue has been drawn its directly successing value
/// is set to the same value as this field. It is flipping 0 and 1
/// every time drawQueue() is called.
char renderedFlag;
base::util::IDGenerator<unsigned int> modelIdGen;
base::cont::List<base::interfaces::AbstractManaged *> managedModels;
bool texturedEnabled; ///< true, when textured geometry is to be drawn
bool untexturedEnabled; ///< true, when untextured geometry is to be drawn
/// Its value is flipped every time update() is called to minimize OpenGL
/// state changes. See the source code of update() for details.
bool texturedFlip;
/**
* Draws all geometry in the render queue.
* @param[in] textured If true only textured geometry is drawn, only untextured otherwise.
* @param[in] drawingModes Only models that are activated for the drawing modes specified by this
* parameter are drawn. The modes are specified as bit flags. Possible values are:
* DRAWING_MODE_DEFAULT, DRAWING_MODE_PICKING
* @param[in] texImportant If false the parameter textured isn't considered.
* So textured and untextured geometry is drawn, but both without texture.
* This is useful for example when drawing for Picking.
*/
void drawQueue(bool textured,
unsigned int drawingModes = DRAWING_MODE_DEFAULT,
bool texImportant = true);
/**
* Enqueues a value to the end of renderQueue
* @param[in] value The value to enqueue.
*/
void enqueue(double value);
/**
* See AbstracManager::addManaged()
*/
void addManaged(base::interfaces::AbstractManaged *managed) {
managedModels.add(managed);
}
/**
* Take care of internal texturedFlip initialization.
* When textured and untextured geometry gets enabled update() begins to take
* care of the textured state of OpenGL. This method ensures that this state
* is correctly initialised.
*/
inline void bothEnabled();
/**
* Does the actual work for removeManaged(const string &name).
* @param[in] name See removeManaged(const string &name)
* @param[in] deleteTextured If true is passed the ManagedModel object
* will be deleted from the heap. Otherwise it won't.
* @see base::interfaces::ManagerInterface::removeManaged()
*/
void removeManaged(const string &name, bool deleteTextured);
/**
* Removes all textures for an model object.
* @param[in] objId The id of the object to be removed.
*/
void removeTextures(unsigned int objId);
/**
* Draws all untextured display lists for the model object.
* @param[in] model Id of the model object to be drawn.
*/
inline void drawUntexturedDLists(unsigned int model);
/**
* Draws all textured display lists for the model object with the given texture.
* @param[in] model Id of the model object to be drawn.
* @param[in] texture Id of the texture.
*/
inline void drawTexturedDLists(unsigned int model, int texture);
/**
* Processes the picking hit records. The model object id with has the hit record
* with the nearest z value is considered to be clicked. Observers are notified with
* this model object id.
* @param[in] hits Number of hit records.
* @param[in] selectionBuffer Buffer where the hit records are stored in.
*/
void processPickingHits(GLint hits, GLuint selectionBuffer[]);
public:
// TODO! : documents these right:
/// This flag is passed to drawQueue() as the default drawing mode (to screen).
static const unsigned int DRAWING_MODE_DEFAULT;
/// this flag is passed to drawQueue() when models activated for picking are to be drawn
static const unsigned int DRAWING_MODE_PICKING;
ModelManager();
virtual ~ModelManager();
// TODO implements ManagerInterface interfacess ...
/**
* Draws all models that are managed by this manager and are activated.
* @warning If textured and untextured models are both disabled, nothing will
* be displayed.
* @see disableTextured(), disableUntextured()
*/
void update(double time = 0);
/**
* Draws all for picking activated geometry and notifies picking observers
* (by calling processPickingHits()).
* @param[in] mouseX X-coordinate of the mouse cursor (in window coordinates).
* @param[in] mouseY Y-coordinate of the mouse cursor (in window coordinates).
* @param[in] pov Point of view. Passed as the first three arguments to gluLookAt().
* @param[in] lookAt Point to look at. Passed as the fourth to sixth argument to gluLookAt().
* @param[in] up Vector that points up. Passed as the seventh to nineth argument to gluLookAt().
* @param[in] clickRegion Number of pixels of the side length of the picking area
* around the mouse cursor. The larger it is the less accurate one must aim to
* hit an object and the more objects will be hit (slowing down hit processing).
* @param[in] fovy Angle of the field of view in y direction.
* @param[in] zNear Minimum distance from the point of view to start drawing
* (i.e. considering objects for picking). It has to be larger than zero.
* @param[in] zFar Maximum distance from the point of view to start drawing
* (i.e. considering objects for picking).
* @param[in] bufferSize Size of the buffer (in GLuints) where the hit records are to be stored in.
* @note Before you call this method you have to activate picking (ManagedModel::activatePicking())
* for the model objects you want to be pickable.
*/
void performPicking(int mouseX, int mouseY,
const base::math::DoubleVector &pov,
const base::math::DoubleVector &lookAt,
const base::math::DoubleVector &up,
short clickRegion = DEFAULT_CLICK_REGION,
GLdouble fovy = DEFAULT_FOV_Y, GLdouble zNear = DEFAULT_Z_NEAR,
GLdouble zFar = DEFAULT_Z_FAR,
unsigned int bufferSize = DEFAULT_BUFFER_SIZE);
/**
* Draws all for picking activated geometry and notifies picking observers
* (by calling processPickingHits()). This is a convenience method.
* @param[in] mouseX X-coordinate of the mouse cursor (in window coordinates).
* @param[in] mouseY Y-coordinate of the mouse cursor (in window coordinates).
* @param[in] clickRegion Number of pixels of the side length of the picking area
* around the mouse cursor. The larger it is the less accurate one must aim to
* hit an object and the more objects will be hit (slowing down hit processing).
* @param[in] bufferSize Size of the buffer (in GLuints) where the hit records are to be stored in.
* @note Before you call this method you have to activate picking (ManagedModel::activatePicking())
* for the model objects you want to be pickable.
* @see performPicking(int mouseX, int mouseY, const base::math::DoubleVector &pov,
* const base::math::DoubleVector &lookAt,
* const base::math::DoubleVector &up,
* short clickRegion = DEFAULT_CLICK_REGION,
* GLdouble fovy = DEFAULT_FOV_Y, GLdouble zNear = DEFAULT_Z_NEAR,
* GLdouble zFar = DEFAULT_Z_FAR,
* unsigned int bufferSize = DEFAULT_BUFFER_SIZE)
*/
void performPicking(int mouseX, int mouseY, core::gl::Camera *camera,
short clickRegion = DEFAULT_CLICK_REGION,
unsigned int bufferSize = DEFAULT_BUFFER_SIZE);
/**
* Enables drawing of textured geometry.
*/
void enableTextured() {
texturedEnabled = true;
bothEnabled();
}
/**
* Disables drawing of textured geometry.
*/
void disableTextured() {
texturedEnabled = false;
}
/**
* Enables drawing of untextured geometry.
*/
void enableUntextured() {
untexturedEnabled = true;
bothEnabled();
}
/**
* Disables drawing of untextured geometry.
*/
void disableUntextured() {
untexturedEnabled = false;
}
/**
* See base::interfaces::ManagerInterface::getManagedNames()
*/
void getManagedNames(base::cont::JavaStyleContainer<string> * names) const;
/**
* See base::interfaces::ManagerInterface::getManaged()
*/
base::interfaces::AbstractManaged* getManaged(const string &name) const;
/**
* Only calls removeManaged(name, true)
* @see base::interfaces::ManagerInterface::removeManaged()
* @see removeManaged(const string &name, bool deleteManaged)
*/
void removeManaged(const string &name);
/**
* Returns the name of the manager.
* @return The managers name.
*/
std::string getName() const {
return "ModelManager";
}
/**
* This method clears all managed from the manager.
*/
void clear();
/**
* Prints some information about the manager to std console.
*/
void outDebug() const;
// TODO! : add optional parameter: iterator to renderQueue where the values are to be enqueued.
void enqueueTranslation(double x, double y, double z);
void enqueueRotation(double angle, double x, double y, double z);
void enqueueEuler(double angle_x, double angle_y, double angle_z);
// TODO : either only size or only scale
void enqueueScalation(double x, double y, double z);
void enqueueColor(double r, double g, double b, double a);
inline void enqueuePush();
inline void enqueuePop();
inline void enqueueDraw(unsigned int modelId);
inline void emptyQueue();
// comfort methods
inline void enqueueTranslation(const base::math::DoubleVector &v);
inline void
enqueueRotation(double angle, const base::math::DoubleVector &v);
inline void enqueueEuler(const base::math::DoubleVector &euler);
inline void enqueueScalation(const base::math::DoubleVector &s);
inline void enqueueColor(const core::gl::Color &c);
// TODO! : use either only model id or only object id!
base::math::DoubleVector &getModelCenter(unsigned int model) {
return models2centers[model];
}
base::math::DoubleVector &getModelEuler(unsigned int model) {
return models2rotations[model];
}
base::math::DoubleVector &getModelSize(unsigned int model) {
return models2sizes[model];
}
core::gl::Color &getModelColor(unsigned int model) {
return models2colors[model];
}
#ifndef NDEBUG
void printRenderQueue() const;
#endif
};
inline void ModelManager::enqueueColor(double r, double g, double b, double a) {
enqueue(COLOR);
enqueue(r);
enqueue(g);
enqueue(b);
enqueue(a);
}
inline void ModelManager::enqueueTranslation(double x, double y, double z) {
enqueue(TRANSLATION);
enqueue(x);
enqueue(y);
enqueue(z);
}
inline void ModelManager::enqueueRotation(double angle, double x, double y,
double z) {
enqueue(ROTATION);
enqueue(angle);
enqueue(x);
enqueue(y);
enqueue(z);
}
inline void ModelManager::enqueueScalation(double x, double y, double z) {
enqueue(SCALATION);
enqueue(x);
enqueue(y);
enqueue(z);
}
inline void ModelManager::enqueueEuler(double angle_x, double angle_y,
double angle_z) {
enqueue(EULER);
enqueue(angle_x);
enqueue(angle_y);
enqueue(angle_z);
}
inline void ModelManager::enqueuePush() {
enqueue(PUSH);
}
inline void ModelManager::enqueuePop() {
enqueue(POP);
}
inline void ModelManager::enqueueDraw(unsigned int model) {
enqueue(DRAW);
// add drawing flags (default is default)
enqueue(DRAWING_MODE_DEFAULT);
enqueue(model);
// TODO : das hier nach drawQueue verschieben?
uilist &modelTextures = models2textures[model];
for (uilist::iterator texIt = modelTextures.begin(); texIt
!= modelTextures.end(); ++texIt) {
enqueue(*texIt);
enqueue(1 - renderedFlag); // add the drawn flag (initially false of course)
textures2lastOccur[*texIt] = --renderQueue.end();
}
enqueue(DRAW_END);
}
inline void ModelManager::emptyQueue() {
// TODO optimize
renderQueue.clear();
}
inline void ModelManager::enqueue(double value) {
// TODO optimize
renderQueue.push_back(value);
}
inline void ModelManager::bothEnabled() {
if (texturedEnabled && untexturedEnabled) {
texturedFlip = true;
glEnable(GL_TEXTURE_2D);
}
}
inline void ModelManager::enqueueTranslation(const base::math::DoubleVector &v) {
enqueueTranslation(const_cast<base::math::DoubleVector &>(v)[0], const_cast<base::math::DoubleVector &>(v)[1], const_cast<base::math::DoubleVector &>(v)[2]);
}
inline void ModelManager::enqueueRotation(double angle,
const base::math::DoubleVector &v) {
enqueueRotation(angle, const_cast<base::math::DoubleVector &>(v)[0], const_cast<base::math::DoubleVector &>(v)[1], const_cast<base::math::DoubleVector &>(v)[2]);
}
inline void ModelManager::enqueueScalation(const base::math::DoubleVector &s) {
enqueueScalation(const_cast<base::math::DoubleVector &>(s)[0], const_cast<base::math::DoubleVector &>(s)[1], const_cast<base::math::DoubleVector &>(s)[2]);
}
inline void ModelManager::enqueueColor(const core::gl::Color &c) {
enqueueColor(const_cast<core::gl::Color &>(c)[0], const_cast<core::gl::Color &>(c)[1], const_cast<core::gl::Color &>(c)[2], const_cast<core::gl::Color &>(c)[3]);
}
// rotate first around z, then y, then x
inline void ModelManager::enqueueEuler(const base::math::DoubleVector &euler) {
enqueueEuler(const_cast<base::math::DoubleVector &>(euler)[0], const_cast<base::math::DoubleVector &>(euler)[1], const_cast<base::math::DoubleVector &>(euler)[2]);
}
inline void ModelManager::drawUntexturedDLists(unsigned int model) {
uilist & dLists = models2untexturedDLists[model];
for (uilist::iterator dlIt = dLists.begin(); dlIt != dLists.end(); ++dlIt) {
glCallList(*dlIt);
}
}
inline void ModelManager::drawTexturedDLists(unsigned int model, int texture) {
uilist & dLists = modelsTex2displayLists[make_pair(model, texture)];
for (uilist::iterator dlIt = dLists.begin(); dlIt != dLists.end(); ++dlIt) {
glCallList(*dlIt);
}
}
} // model
} // gl
} // managed
} // vs
#endif /*MODELMANAGER_H_*/
| 34.789773 | 164 | 0.734988 | [
"geometry",
"render",
"object",
"vector",
"model"
] |
7fc1b26ea304993dd18ee681b4e7ad398c7b7f5a | 4,151 | h | C | chrome/browser/apps/drive/drive_app_provider.h | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2019-11-28T10:46:52.000Z | 2019-11-28T10:46:52.000Z | chrome/browser/apps/drive/drive_app_provider.h | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | chrome/browser/apps/drive/drive_app_provider.h | kjthegod/chromium | cf940f7f418436b77e15b1ea23e6fa100ca1c91a | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 2 | 2015-03-27T11:15:39.000Z | 2016-08-17T14:19:56.000Z | // Copyright 2014 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_APPS_DRIVE_DRIVE_APP_PROVIDER_H_
#define CHROME_BROWSER_APPS_DRIVE_DRIVE_APP_PROVIDER_H_
#include <set>
#include <string>
#include <vector>
#include "base/macros.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/scoped_vector.h"
#include "base/memory/weak_ptr.h"
#include "chrome/browser/drive/drive_app_registry_observer.h"
#include "extensions/browser/extension_registry_observer.h"
namespace drive {
struct DriveAppInfo;
}
class BrowserContextKeyedServiceFactory;
class DriveAppConverter;
class DriveAppMapping;
class DriveAppUninstallSyncService;
class DriveServiceBridge;
class ExtensionService;
class Profile;
// DriveAppProvider is the integration point for Drive apps. It ensures each
// Drive app has a corresponding Chrome app in the extension system. If there
// is no matching Chrome app, a local URL app would be created. The class
// processes app changes from both DriveAppRegistry and extension system to
// keep the two in sync.
class DriveAppProvider : public drive::DriveAppRegistryObserver,
public extensions::ExtensionRegistryObserver {
public:
DriveAppProvider(Profile* profile,
DriveAppUninstallSyncService* uninstall_sync_service);
~DriveAppProvider() override;
// Appends PKS factories this class depends on.
static void AppendDependsOnFactories(
std::set<BrowserContextKeyedServiceFactory*>* factories);
void SetDriveServiceBridgeForTest(scoped_ptr<DriveServiceBridge> test_bridge);
// Adds/removes uninstalled Drive app id from DriveAppUninstallSyncService.
// If a Drive app id is added as uninstalled Drive app, DriveAppProvider
// would not auto create the local URL app for it until the uninstall record
// is removed.
void AddUninstalledDriveAppFromSync(const std::string& drive_app_id);
void RemoveUninstalledDriveAppFromSync(const std::string& drive_app_id);
private:
friend class DriveAppProviderTest;
typedef std::set<std::string> IdSet;
typedef std::vector<drive::DriveAppInfo> DriveAppInfos;
// Maps |drive_app_id| to |new_app|'s id in mapping. Auto uninstall existing
// mapped app if it is an URL app.
void UpdateMappingAndExtensionSystem(const std::string& drive_app_id,
const extensions::Extension* new_app,
bool is_new_app_generated);
// Deferred processing of relevant extension installed message.
void ProcessDeferredOnExtensionInstalled(const std::string drive_app_id,
const std::string chrome_app_id);
void SchedulePendingConverters();
void OnLocalAppConverted(const DriveAppConverter* converter, bool success);
bool IsMappedUrlAppUpToDate(const drive::DriveAppInfo& drive_app) const;
void AddOrUpdateDriveApp(const drive::DriveAppInfo& drive_app);
void ProcessRemovedDriveApp(const std::string& drive_app_id);
void UpdateDriveApps();
// drive::DriveAppRegistryObserver overrides:
void OnDriveAppRegistryUpdated() override;
// extensions::ExtensionRegistryObserver overrides:
void OnExtensionInstalled(content::BrowserContext* browser_context,
const extensions::Extension* extension,
bool is_update) override;
void OnExtensionUninstalled(content::BrowserContext* browser_context,
const extensions::Extension* extension,
extensions::UninstallReason reason) override;
Profile* profile_;
DriveAppUninstallSyncService* uninstall_sync_service_;
scoped_ptr<DriveServiceBridge> service_bridge_;
scoped_ptr<DriveAppMapping> mapping_;
DriveAppInfos drive_apps_;
// Tracks the pending web app convertions.
ScopedVector<DriveAppConverter> pending_converters_;
base::WeakPtrFactory<DriveAppProvider> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(DriveAppProvider);
};
#endif // CHROME_BROWSER_APPS_DRIVE_DRIVE_APP_PROVIDER_H_
| 38.082569 | 80 | 0.754999 | [
"vector"
] |
7fc4f6123b2d13682d888bcb58eaf64077cdafab | 14,612 | h | C | addons/ofxPango/src/includes/glib/gobject/gparam.h | HellicarAndLewis/ProjectDonk | 96fde869c469f8312843333e51c862bd3b143222 | [
"MIT"
] | 1 | 2015-12-05T04:53:15.000Z | 2015-12-05T04:53:15.000Z | addons/ofxPango/src/includes/glib/gobject/gparam.h | HellicarAndLewis/ProjectDonk | 96fde869c469f8312843333e51c862bd3b143222 | [
"MIT"
] | null | null | null | addons/ofxPango/src/includes/glib/gobject/gparam.h | HellicarAndLewis/ProjectDonk | 96fde869c469f8312843333e51c862bd3b143222 | [
"MIT"
] | null | null | null | /* GObject - GLib Type, Object, Parameter and Signal Library
* Copyright (C) 1997-1999, 2000-2001 Tim Janik and Red Hat, Inc.
*
* 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 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., 59 Temple Place, Suite 330,
* Boston, MA 02111-1307, USA.
*
* gparam.h: GParamSpec base class implementation
*/
#if !defined (__GLIB_GOBJECT_H_INSIDE__) && !defined (GOBJECT_COMPILATION)
#error "Only <glib-object.h> can be included directly."
#endif
#ifndef __G_PARAM_H__
#define __G_PARAM_H__
#include <gobject/gvalue.h>
G_BEGIN_DECLS
/* --- standard type macros --- */
/**
* G_TYPE_IS_PARAM:
* @type: a #GType ID
*
* Checks whether @type "is a" %G_TYPE_PARAM.
*/
#define G_TYPE_IS_PARAM(type) (G_TYPE_FUNDAMENTAL (type) == G_TYPE_PARAM)
/**
* G_PARAM_SPEC:
* @pspec: a valid #GParamSpec
*
* Casts a derived #GParamSpec object (e.g. of type #GParamSpecInt) into
* a #GParamSpec object.
*/
#define G_PARAM_SPEC(pspec) (G_TYPE_CHECK_INSTANCE_CAST ((pspec), G_TYPE_PARAM, GParamSpec))
/**
* G_IS_PARAM_SPEC:
* @pspec: a #GParamSpec
*
* Checks whether @pspec "is a" valid #GParamSpec structure of type %G_TYPE_PARAM
* or derived.
*/
#define G_IS_PARAM_SPEC(pspec) (G_TYPE_CHECK_INSTANCE_TYPE ((pspec), G_TYPE_PARAM))
/**
* G_PARAM_SPEC_CLASS:
* @pclass: a valid #GParamSpecClass
*
* Casts a derived #GParamSpecClass structure into a #GParamSpecClass structure.
*/
#define G_PARAM_SPEC_CLASS(pclass) (G_TYPE_CHECK_CLASS_CAST ((pclass), G_TYPE_PARAM, GParamSpecClass))
/**
* G_IS_PARAM_SPEC_CLASS:
* @pclass: a #GParamSpecClass
*
* Checks whether @pclass "is a" valid #GParamSpecClass structure of type
* %G_TYPE_PARAM or derived.
*/
#define G_IS_PARAM_SPEC_CLASS(pclass) (G_TYPE_CHECK_CLASS_TYPE ((pclass), G_TYPE_PARAM))
/**
* G_PARAM_SPEC_GET_CLASS:
* @pspec: a valid #GParamSpec
*
* Retrieves the #GParamSpecClass of a #GParamSpec.
*/
#define G_PARAM_SPEC_GET_CLASS(pspec) (G_TYPE_INSTANCE_GET_CLASS ((pspec), G_TYPE_PARAM, GParamSpecClass))
/* --- convenience macros --- */
/**
* G_PARAM_SPEC_TYPE:
* @pspec: a valid #GParamSpec
*
* Retrieves the #GType of this @pspec.
*/
#define G_PARAM_SPEC_TYPE(pspec) (G_TYPE_FROM_INSTANCE (pspec))
/**
* G_PARAM_SPEC_TYPE_NAME:
* @pspec: a valid #GParamSpec
*
* Retrieves the #GType name of this @pspec.
*/
#define G_PARAM_SPEC_TYPE_NAME(pspec) (g_type_name (G_PARAM_SPEC_TYPE (pspec)))
/**
* G_PARAM_SPEC_VALUE_TYPE:
* @pspec: a valid #GParamSpec
*
* Retrieves the #GType to initialize a #GValue for this parameter.
*/
#define G_PARAM_SPEC_VALUE_TYPE(pspec) (G_PARAM_SPEC (pspec)->value_type)
/**
* G_VALUE_HOLDS_PARAM:
* @value: a valid #GValue structure
*
* Checks whether the given #GValue can hold values derived from type %G_TYPE_PARAM.
*
* Returns: %TRUE on success.
*/
#define G_VALUE_HOLDS_PARAM(value) (G_TYPE_CHECK_VALUE_TYPE ((value), G_TYPE_PARAM))
/* --- flags --- */
/**
* GParamFlags:
* @G_PARAM_READABLE: the parameter is readable
* @G_PARAM_WRITABLE: the parameter is writable
* @G_PARAM_CONSTRUCT: the parameter will be set upon object construction
* @G_PARAM_CONSTRUCT_ONLY: the parameter will only be set upon object construction
* @G_PARAM_LAX_VALIDATION: upon parameter conversion (see g_param_value_convert())
* strict validation is not required
* @G_PARAM_STATIC_NAME: the string used as name when constructing the
* parameter is guaranteed to remain valid and
* unmodified for the lifetime of the parameter.
* Since 2.8
* @G_PARAM_STATIC_NICK: the string used as nick when constructing the
* parameter is guaranteed to remain valid and
* unmmodified for the lifetime of the parameter.
* Since 2.8
* @G_PARAM_STATIC_BLURB: the string used as blurb when constructing the
* parameter is guaranteed to remain valid and
* unmodified for the lifetime of the parameter.
* Since 2.8
* @G_PARAM_PRIVATE: internal
*
* Through the #GParamFlags flag values, certain aspects of parameters
* can be configured.
*/
typedef enum
{
G_PARAM_READABLE = 1 << 0,
G_PARAM_WRITABLE = 1 << 1,
G_PARAM_CONSTRUCT = 1 << 2,
G_PARAM_CONSTRUCT_ONLY = 1 << 3,
G_PARAM_LAX_VALIDATION = 1 << 4,
G_PARAM_STATIC_NAME = 1 << 5,
#ifndef G_DISABLE_DEPRECATED
G_PARAM_PRIVATE = G_PARAM_STATIC_NAME,
#endif
G_PARAM_STATIC_NICK = 1 << 6,
G_PARAM_STATIC_BLURB = 1 << 7
} GParamFlags;
/**
* G_PARAM_READWRITE:
*
* #GParamFlags value alias for %G_PARAM_READABLE | %G_PARAM_WRITABLE.
*/
#define G_PARAM_READWRITE (G_PARAM_READABLE | G_PARAM_WRITABLE)
/**
* G_PARAM_STATIC_STRINGS:
*
* #GParamFlags value alias for %G_PARAM_STATIC_NAME | %G_PARAM_STATIC_NICK | %G_PARAM_STATIC_BLURB.
*
* Since 2.13.0
*/
#define G_PARAM_STATIC_STRINGS (G_PARAM_STATIC_NAME | G_PARAM_STATIC_NICK | G_PARAM_STATIC_BLURB)
/* bits in the range 0xffffff00 are reserved for 3rd party usage */
/**
* G_PARAM_MASK:
*
* Mask containing the bits of #GParamSpec.flags which are reserved for GLib.
*/
#define G_PARAM_MASK (0x000000ff)
/**
* G_PARAM_USER_SHIFT:
*
* Minimum shift count to be used for user defined flags, to be stored in
* #GParamSpec.flags.
*/
#define G_PARAM_USER_SHIFT (8)
/* --- typedefs & structures --- */
typedef struct _GParamSpec GParamSpec;
typedef struct _GParamSpecClass GParamSpecClass;
typedef struct _GParameter GParameter;
typedef struct _GParamSpecPool GParamSpecPool;
/**
* GParamSpec:
* @g_type_instance: private #GTypeInstance portion
* @name: name of this parameter
* @flags: #GParamFlags flags for this parameter
* @value_type: the #GValue type for this parameter
* @owner_type: #GType type that uses (introduces) this parameter
*
* All other fields of the <structname>GParamSpec</structname> struct are private and
* should not be used directly.
*/
struct _GParamSpec
{
GTypeInstance g_type_instance;
gchar *name;
GParamFlags flags;
GType value_type;
GType owner_type; /* class or interface using this property */
/*< private >*/
gchar *_nick;
gchar *_blurb;
GData *qdata;
guint ref_count;
guint param_id; /* sort-criteria */
};
/**
* GParamSpecClass:
* @g_type_class: the parent class
* @value_type: the #GValue type for this parameter
* @finalize: The instance finalization function (optional), should chain
* up to the finalize method of the parent class.
* @value_set_default: Resets a @value to the default value for this type
* (recommended, the default is g_value_reset()), see
* g_param_value_set_default().
* @value_validate: Ensures that the contents of @value comply with the
* specifications set out by this type (optional), see
* g_param_value_set_validate().
* @values_cmp: Compares @value1 with @value2 according to this type
* (recommended, the default is memcmp()), see g_param_values_cmp().
*
* The class structure for the <structname>GParamSpec</structname> type.
* Normally, <structname>GParamSpec</structname> classes are filled by
* g_param_type_register_static().
*/
struct _GParamSpecClass
{
GTypeClass g_type_class;
GType value_type;
void (*finalize) (GParamSpec *pspec);
/* GParam methods */
void (*value_set_default) (GParamSpec *pspec,
GValue *value);
gboolean (*value_validate) (GParamSpec *pspec,
GValue *value);
gint (*values_cmp) (GParamSpec *pspec,
const GValue *value1,
const GValue *value2);
/*< private >*/
gpointer dummy[4];
};
/**
* GParameter:
* @name: the parameter name
* @value: the parameter value
*
* The <structname>GParameter</structname> struct is an auxiliary structure used
* to hand parameter name/value pairs to g_object_newv().
*/
struct _GParameter /* auxillary structure for _setv() variants */
{
const gchar *name;
GValue value;
};
/* --- prototypes --- */
GParamSpec* g_param_spec_ref (GParamSpec *pspec);
void g_param_spec_unref (GParamSpec *pspec);
void g_param_spec_sink (GParamSpec *pspec);
GParamSpec* g_param_spec_ref_sink (GParamSpec *pspec);
gpointer g_param_spec_get_qdata (GParamSpec *pspec,
GQuark quark);
void g_param_spec_set_qdata (GParamSpec *pspec,
GQuark quark,
gpointer data);
void g_param_spec_set_qdata_full (GParamSpec *pspec,
GQuark quark,
gpointer data,
GDestroyNotify destroy);
gpointer g_param_spec_steal_qdata (GParamSpec *pspec,
GQuark quark);
GParamSpec* g_param_spec_get_redirect_target (GParamSpec *pspec);
void g_param_value_set_default (GParamSpec *pspec,
GValue *value);
gboolean g_param_value_defaults (GParamSpec *pspec,
GValue *value);
gboolean g_param_value_validate (GParamSpec *pspec,
GValue *value);
gboolean g_param_value_convert (GParamSpec *pspec,
const GValue *src_value,
GValue *dest_value,
gboolean strict_validation);
gint g_param_values_cmp (GParamSpec *pspec,
const GValue *value1,
const GValue *value2);
G_CONST_RETURN gchar* g_param_spec_get_name (GParamSpec *pspec);
G_CONST_RETURN gchar* g_param_spec_get_nick (GParamSpec *pspec);
G_CONST_RETURN gchar* g_param_spec_get_blurb (GParamSpec *pspec);
void g_value_set_param (GValue *value,
GParamSpec *param);
GParamSpec* g_value_get_param (const GValue *value);
GParamSpec* g_value_dup_param (const GValue *value);
void g_value_take_param (GValue *value,
GParamSpec *param);
#ifndef G_DISABLE_DEPRECATED
void g_value_set_param_take_ownership (GValue *value,
GParamSpec *param);
#endif
/* --- convenience functions --- */
typedef struct _GParamSpecTypeInfo GParamSpecTypeInfo;
/**
* GParamSpecTypeInfo:
* @instance_size: Size of the instance (object) structure.
* @n_preallocs: Prior to GLib 2.10, it specified the number of pre-allocated (cached) instances to reserve memory for (0 indicates no caching). Since GLib 2.10, it is ignored, since instances are allocated with the <link linkend="glib-Memory-Slices">slice allocator</link> now.
* @instance_init: Location of the instance initialization function (optional).
* @value_type: The #GType of values conforming to this #GParamSpec
* @finalize: The instance finalization function (optional).
* @value_set_default: Resets a @value to the default value for @pspec
* (recommended, the default is g_value_reset()), see
* g_param_value_set_default().
* @value_validate: Ensures that the contents of @value comply with the
* specifications set out by @pspec (optional), see
* g_param_value_set_validate().
* @values_cmp: Compares @value1 with @value2 according to @pspec
* (recommended, the default is memcmp()), see g_param_values_cmp().
*
* This structure is used to provide the type system with the information
* required to initialize and destruct (finalize) a parameter's class and
* instances thereof.
* The initialized structure is passed to the g_param_type_register_static()
* The type system will perform a deep copy of this structure, so its memory
* does not need to be persistent across invocation of
* g_param_type_register_static().
*/
struct _GParamSpecTypeInfo
{
/* type system portion */
guint16 instance_size; /* obligatory */
guint16 n_preallocs; /* optional */
void (*instance_init) (GParamSpec *pspec); /* optional */
/* class portion */
GType value_type; /* obligatory */
void (*finalize) (GParamSpec *pspec); /* optional */
void (*value_set_default) (GParamSpec *pspec, /* recommended */
GValue *value);
gboolean (*value_validate) (GParamSpec *pspec, /* optional */
GValue *value);
gint (*values_cmp) (GParamSpec *pspec, /* recommended */
const GValue *value1,
const GValue *value2);
};
GType g_param_type_register_static (const gchar *name,
const GParamSpecTypeInfo *pspec_info);
/* For registering builting types */
GType _g_param_type_register_static_constant (const gchar *name,
const GParamSpecTypeInfo *pspec_info,
GType opt_type);
/* --- protected --- */
gpointer g_param_spec_internal (GType param_type,
const gchar *name,
const gchar *nick,
const gchar *blurb,
GParamFlags flags);
GParamSpecPool* g_param_spec_pool_new (gboolean type_prefixing);
void g_param_spec_pool_insert (GParamSpecPool *pool,
GParamSpec *pspec,
GType owner_type);
void g_param_spec_pool_remove (GParamSpecPool *pool,
GParamSpec *pspec);
GParamSpec* g_param_spec_pool_lookup (GParamSpecPool *pool,
const gchar *param_name,
GType owner_type,
gboolean walk_ancestors);
GList* g_param_spec_pool_list_owned (GParamSpecPool *pool,
GType owner_type);
GParamSpec** g_param_spec_pool_list (GParamSpecPool *pool,
GType owner_type,
guint *n_pspecs_p);
/* contracts:
*
* gboolean value_validate (GParamSpec *pspec,
* GValue *value):
* modify value contents in the least destructive way, so
* that it complies with pspec's requirements (i.e.
* according to minimum/maximum ranges etc...). return
* whether modification was necessary.
*
* gint values_cmp (GParamSpec *pspec,
* const GValue *value1,
* const GValue *value2):
* return value1 - value2, i.e. (-1) if value1 < value2,
* (+1) if value1 > value2, and (0) otherwise (equality)
*/
G_END_DECLS
#endif /* __G_PARAM_H__ */
| 35.552311 | 278 | 0.690186 | [
"object"
] |
7fc5a18634857333709373e592f4d883496983cb | 1,930 | h | C | ext/phalcon/mvc/model/behavior.zep.h | ufoproger/cphalcon | 3763e7e770afd0b5869f44c96000da1b5b609ca0 | [
"PHP-3.01",
"Zend-2.0",
"BSD-3-Clause"
] | null | null | null | ext/phalcon/mvc/model/behavior.zep.h | ufoproger/cphalcon | 3763e7e770afd0b5869f44c96000da1b5b609ca0 | [
"PHP-3.01",
"Zend-2.0",
"BSD-3-Clause"
] | null | null | null | ext/phalcon/mvc/model/behavior.zep.h | ufoproger/cphalcon | 3763e7e770afd0b5869f44c96000da1b5b609ca0 | [
"PHP-3.01",
"Zend-2.0",
"BSD-3-Clause"
] | null | null | null |
extern zend_class_entry *phalcon_mvc_model_behavior_ce;
ZEPHIR_INIT_CLASS(Phalcon_Mvc_Model_Behavior);
PHP_METHOD(Phalcon_Mvc_Model_Behavior, __construct);
PHP_METHOD(Phalcon_Mvc_Model_Behavior, mustTakeAction);
PHP_METHOD(Phalcon_Mvc_Model_Behavior, getOptions);
PHP_METHOD(Phalcon_Mvc_Model_Behavior, notify);
PHP_METHOD(Phalcon_Mvc_Model_Behavior, missingMethod);
ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_behavior___construct, 0, 0, 0)
ZEND_ARG_INFO(0, options)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_WITH_RETURN_TYPE_INFO_EX(arginfo_phalcon_mvc_model_behavior_musttakeaction, 0, 1, _IS_BOOL, 0)
ZEND_ARG_TYPE_INFO(0, eventName, IS_STRING, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_behavior_getoptions, 0, 0, 0)
ZEND_ARG_TYPE_INFO(0, eventName, IS_STRING, 1)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_behavior_notify, 0, 0, 2)
ZEND_ARG_TYPE_INFO(0, type, IS_STRING, 0)
ZEND_ARG_OBJ_INFO(0, model, Phalcon\\Mvc\\ModelInterface, 0)
ZEND_END_ARG_INFO()
ZEND_BEGIN_ARG_INFO_EX(arginfo_phalcon_mvc_model_behavior_missingmethod, 0, 0, 2)
ZEND_ARG_OBJ_INFO(0, model, Phalcon\\Mvc\\ModelInterface, 0)
ZEND_ARG_TYPE_INFO(0, method, IS_STRING, 0)
ZEND_ARG_INFO(0, arguments)
ZEND_END_ARG_INFO()
ZEPHIR_INIT_FUNCS(phalcon_mvc_model_behavior_method_entry) {
PHP_ME(Phalcon_Mvc_Model_Behavior, __construct, arginfo_phalcon_mvc_model_behavior___construct, ZEND_ACC_PUBLIC|ZEND_ACC_CTOR)
PHP_ME(Phalcon_Mvc_Model_Behavior, mustTakeAction, arginfo_phalcon_mvc_model_behavior_musttakeaction, ZEND_ACC_PROTECTED)
PHP_ME(Phalcon_Mvc_Model_Behavior, getOptions, arginfo_phalcon_mvc_model_behavior_getoptions, ZEND_ACC_PROTECTED)
PHP_ME(Phalcon_Mvc_Model_Behavior, notify, arginfo_phalcon_mvc_model_behavior_notify, ZEND_ACC_PUBLIC)
PHP_ME(Phalcon_Mvc_Model_Behavior, missingMethod, arginfo_phalcon_mvc_model_behavior_missingmethod, ZEND_ACC_PUBLIC)
PHP_FE_END
};
| 44.883721 | 127 | 0.869948 | [
"model"
] |
7fc7b7095bcda1d86080d8d5b57b459ea8ab9ec0 | 2,552 | h | C | release/src-ra-4300/lib/include/bits/dlfcn.h | zhoutao0712/rtn11pb1 | 09e6b6c7ef4b91be0a9374daeacc3ac9f2fa3a05 | [
"Apache-2.0"
] | null | null | null | release/src-ra-4300/lib/include/bits/dlfcn.h | zhoutao0712/rtn11pb1 | 09e6b6c7ef4b91be0a9374daeacc3ac9f2fa3a05 | [
"Apache-2.0"
] | null | null | null | release/src-ra-4300/lib/include/bits/dlfcn.h | zhoutao0712/rtn11pb1 | 09e6b6c7ef4b91be0a9374daeacc3ac9f2fa3a05 | [
"Apache-2.0"
] | null | null | null | /* System dependent definitions for run-time dynamic loading.
Copyright (C) 1996, 1997, 1999, 2000, 2001 Free Software Foundation, Inc.
This file is part of the GNU C Library.
The GNU C 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.
The GNU C 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 the GNU C Library; if not, write to the Free
Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA. */
#ifndef _DLFCN_H
# error "Never use <bits/dlfcn.h> directly; include <dlfcn.h> instead."
#endif
/* The MODE argument to `dlopen' contains one of the following: */
#define RTLD_LAZY 0x0001 /* Lazy function call binding. */
#define RTLD_NOW 0x0002 /* Immediate function call binding. */
#define RTLD_BINDING_MASK 0x3 /* Mask of binding time value. */
#define RTLD_NOLOAD 0x00008 /* Do not load the object. */
/* If the following bit is set in the MODE argument to `dlopen',
the symbols of the loaded object and its dependencies are made
visible as if the object were linked directly into the program. */
#define RTLD_GLOBAL 0x0004
/* Unix98 demands the following flag which is the inverse to RTLD_GLOBAL.
The implementation does this by default and so we can define the
value to zero. */
#define RTLD_LOCAL 0
/* Do not delete object when closed. */
#define RTLD_NODELETE 0x01000
#ifdef __USE_GNU
/* To support profiling of shared objects it is a good idea to call
the function found using `dlsym' using the following macro since
these calls do not use the PLT. But this would mean the dynamic
loader has no chance to find out when the function is called. The
macro applies the necessary magic so that profiling is possible.
Rewrite
foo = (*fctp) (arg1, arg2);
into
foo = DL_CALL_FCT (fctp, (arg1, arg2));
*/
# define DL_CALL_FCT(fctp, args) \
(_dl_mcount_wrapper_check ((void *) (fctp)), (*(fctp)) args)
__BEGIN_DECLS
/* This function calls the profiling functions. */
extern void _dl_mcount_wrapper_check (void *__selfpc) __THROW;
__END_DECLS
#endif
| 39.261538 | 76 | 0.736677 | [
"object"
] |
7fd13d1f37ad8ff328b32a7b10f9e05f534ab77f | 37,314 | h | C | src/kv/store.h | wintersteiger/CCF | 27febea56ff6923fbc02231de06e432b4f6b2511 | [
"Apache-2.0"
] | null | null | null | src/kv/store.h | wintersteiger/CCF | 27febea56ff6923fbc02231de06e432b4f6b2511 | [
"Apache-2.0"
] | 47 | 2021-11-15T06:19:01.000Z | 2022-03-30T06:24:22.000Z | src/kv/store.h | beejones/CCF | 335fc3613c2dd4a3bda38e10e8e8196dba52465e | [
"Apache-2.0"
] | 1 | 2021-11-08T09:33:34.000Z | 2021-11-08T09:33:34.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the Apache 2.0 License.
#pragma once
#include "apply_changes.h"
#include "deserialise.h"
#include "ds/ccf_exception.h"
#include "kv/committable_tx.h"
#include "kv_serialiser.h"
#include "kv_types.h"
#include "node/entities.h"
#include "node/progress_tracker.h"
#include "node/signatures.h"
#include "snapshot.h"
#define FMT_HEADER_ONLY
#include <fmt/format.h>
namespace kv
{
class StoreState
{
protected:
// All collections of Map must be ordered so that we lock their contained
// maps in a stable order. The order here is by map name. The version
// indicates the version at which the Map was created.
using Maps = std::
map<std::string, std::pair<kv::Version, std::shared_ptr<untyped::Map>>>;
std::mutex maps_lock;
Maps maps;
std::mutex version_lock;
Version version = 0;
Version last_new_map = kv::NoVersion;
Version compacted = 0;
// Calls to Store::commit are made atomic by taking this lock.
std::mutex commit_lock;
// Term at which write future transactions should be committed.
Term term_of_next_version = 0;
// Term at which the last entry was committed. Further transactions
// should read in that term. Note that it is assumed that the history of
// terms of past transactions is kept track of by and specified by the
// caller on rollback
Term term_of_last_version = 0;
Version last_replicated = 0;
Version last_committable = 0;
Version rollback_count = 0;
std::unordered_map<Version, std::pair<std::unique_ptr<PendingTx>, bool>>
pending_txs;
public:
void clear()
{
std::lock_guard<std::mutex> mguard(maps_lock);
std::lock_guard<std::mutex> vguard(version_lock);
maps.clear();
pending_txs.clear();
version = 0;
last_new_map = kv::NoVersion;
compacted = 0;
term_of_next_version = 0;
term_of_last_version = 0;
last_replicated = 0;
last_committable = 0;
rollback_count = 0;
}
};
class Store : public AbstractStore,
public StoreState,
public ExecutionWrapperStore
{
private:
using Hooks = std::map<std::string, kv::untyped::Map::CommitHook>;
using MapHooks = std::map<std::string, kv::untyped::Map::MapHook>;
Hooks global_hooks;
MapHooks map_hooks;
std::shared_ptr<Consensus> consensus = nullptr;
std::shared_ptr<TxHistory> history = nullptr;
std::shared_ptr<ccf::ProgressTracker> progress_tracker = nullptr;
EncryptorPtr encryptor = nullptr;
kv::ReplicateType replicate_type = kv::ReplicateType::ALL;
std::unordered_set<std::string> replicated_tables;
// Generally we will only accept deserialised views if they are contiguous -
// at Version N we reject everything but N+1. The exception is when a Store
// is used for historical queries, where it may deserialise arbitrary
// transactions. In this case the Store is a useful container for a set of
// Tables, but its versioning invariants are ignored.
const bool strict_versions = true;
// If true, use historical ledger secrets to deserialise entries
const bool is_historical = false;
bool commit_deserialised(
OrderedChanges& changes,
Version v,
Term term,
const MapCollection& new_maps,
kv::ConsensusHookPtrs& hooks) override
{
auto c = apply_changes(
changes,
[v](bool) { return std::make_tuple(v, v - 1); },
hooks,
new_maps);
if (!c.has_value())
{
LOG_FAIL_FMT("Failed to commit deserialised Tx at version {}", v);
return false;
}
{
std::lock_guard<std::mutex> vguard(version_lock);
version = v;
last_replicated = version;
term_of_last_version = term;
}
return true;
}
bool has_map_internal(const std::string& name)
{
auto search = maps.find(name);
if (search != maps.end())
return true;
return false;
}
Version next_version_unsafe()
{
// Get the next global version
++version;
// If the version becomes too large to represent in a DeletableVersion,
// wrap to 0
if (version > std::numeric_limits<DeletableVersion>::max())
{
LOG_FAIL_FMT("KV version too large - wrapping to 0");
version = 0;
}
// Further transactions should read in the commit term
term_of_last_version = term_of_next_version;
return version;
}
TxID current_txid_unsafe()
{
// version_lock should be first acquired
return {term_of_last_version, version};
}
public:
Store(bool strict_versions_ = true, bool is_historical_ = false) :
strict_versions(strict_versions_),
is_historical(is_historical_)
{}
Store(
const ReplicateType& replicate_type_,
const std::unordered_set<std::string>& replicated_tables_) :
replicate_type(replicate_type_),
replicated_tables(replicated_tables_)
{}
Store(std::shared_ptr<Consensus> consensus_) : consensus(consensus_) {}
Store(const Store& that) = delete;
std::shared_ptr<Consensus> get_consensus() override
{
return consensus;
}
void set_consensus(std::shared_ptr<Consensus> consensus_)
{
consensus = consensus_;
}
std::shared_ptr<TxHistory> get_history() override
{
return history;
}
void set_history(std::shared_ptr<TxHistory> history_)
{
history = history_;
}
std::shared_ptr<ccf::ProgressTracker> get_progress_tracker()
{
return progress_tracker;
}
void set_progress_tracker(
std::shared_ptr<ccf::ProgressTracker> progress_tracker_)
{
progress_tracker = progress_tracker_;
}
void set_encryptor(const EncryptorPtr& encryptor_)
{
encryptor = encryptor_;
}
EncryptorPtr get_encryptor() override
{
return encryptor;
}
/** Get a map by name, iff it exists at the given version.
*
* This means a prior transaction must have created the map, and
* successfully committed at a version <= v. If this has not happened (the
* map has never been created, or never been committed, or committed at a
* later version) this will return nullptr.
*
* @param v Version at which the map must exist
* @param map_name Name of requested map
*
* @return Abstract shared-owning pointer to requested map, or nullptr if no
* such map exists
*/
std::shared_ptr<AbstractMap> get_map(
kv::Version v, const std::string& map_name) override
{
return get_map_internal(v, map_name);
}
std::shared_ptr<kv::untyped::Map> get_map_internal(
kv::Version v, const std::string& map_name)
{
auto search = maps.find(map_name);
if (search != maps.end())
{
const auto& [map_creation_version, map_ptr] = search->second;
if (v >= map_creation_version || map_creation_version == NoVersion)
{
return map_ptr;
}
}
return nullptr;
}
/** Transfer ownership of a dynamically created map to this Store.
*
* Should be called as part of the commit process, once a transaction is
* known to be conflict-free and has been assigned a unique Version. This
* publishes dynamically created Maps so they can be retrieved via get_map
* in future transactions.
*
* @param v Version at which map is being committed/created
* @param map_ Map to add
*/
void add_dynamic_map(
kv::Version v, const std::shared_ptr<AbstractMap>& map_) override
{
auto map = std::dynamic_pointer_cast<kv::untyped::Map>(map_);
if (map == nullptr)
{
throw std::logic_error(fmt::format(
"Can't add dynamic map - {} is not of expected type",
map_->get_name()));
}
const auto map_name = map->get_name();
if (get_map(v, map_name) != nullptr)
{
throw std::logic_error(fmt::format(
"Can't add dynamic map - already have a map named {}", map_name));
}
LOG_DEBUG_FMT("Adding newly created map '{}' at version {}", map_name, v);
maps[map_name] = std::make_pair(v, map);
{
// If we have any hooks for the given map name, set them on this new map
const auto global_it = global_hooks.find(map_name);
if (global_it != global_hooks.end())
{
map->set_global_hook(global_it->second);
}
const auto map_it = map_hooks.find(map_name);
if (map_it != map_hooks.end())
{
map->set_map_hook(map_it->second);
}
}
}
bool is_map_replicated(const std::string& name) override
{
switch (replicate_type)
{
case (kv::ReplicateType::ALL):
{
return true;
}
case (kv::ReplicateType::NONE):
{
return false;
}
case (kv::ReplicateType::SOME):
{
return replicated_tables.find(name) != replicated_tables.end();
}
default:
{
throw std::logic_error("Unhandled ReplicateType value");
}
}
}
bool should_track_dependencies(const std::string& name) override
{
return name.compare(ccf::Tables::AFT_REQUESTS) != 0;
}
std::unique_ptr<AbstractSnapshot> snapshot(Version v) override
{
auto cv = compacted_version();
if (v < cv)
{
throw std::logic_error(fmt::format(
"Cannot snapshot at version {} which is earlier than last "
"compacted version {} ",
v,
cv));
}
if (v > current_version())
{
throw std::logic_error(fmt::format(
"Cannot snapshot at version {} which is later than current "
"version {} ",
v,
current_version()));
}
auto snapshot = std::make_unique<StoreSnapshot>(v);
{
std::lock_guard<std::mutex> mguard(maps_lock);
for (auto& it : maps)
{
auto& [_, map] = it.second;
map->lock();
}
for (auto& it : maps)
{
auto& [_, map] = it.second;
snapshot->add_map_snapshot(map->snapshot(v));
}
auto h = get_history();
if (h)
{
snapshot->add_hash_at_snapshot(h->get_raw_leaf(v));
}
auto c = get_consensus();
if (c)
{
snapshot->add_view_history(c->get_view_history(v));
}
for (auto& it : maps)
{
auto& [_, map] = it.second;
map->unlock();
}
}
return snapshot;
}
std::vector<uint8_t> serialise_snapshot(
std::unique_ptr<AbstractSnapshot> snapshot) override
{
auto e = get_encryptor();
return snapshot->serialise(e);
}
ApplyResult deserialise_snapshot(
const uint8_t* data,
size_t size,
kv::ConsensusHookPtrs& hooks,
std::vector<Version>* view_history = nullptr,
bool public_only = false) override
{
auto e = get_encryptor();
auto d = KvStoreDeserialiser(
e,
public_only ? kv::SecurityDomain::PUBLIC :
std::optional<kv::SecurityDomain>());
kv::Term term;
auto v_ = d.init(data, size, term, is_historical);
if (!v_.has_value())
{
LOG_FAIL_FMT("Initialisation of deserialise object failed");
return ApplyResult::FAIL;
}
auto [v, _] = v_.value();
std::lock_guard<std::mutex> mguard(maps_lock);
for (auto& it : maps)
{
auto& [_, map] = it.second;
map->lock();
}
std::vector<uint8_t> hash_at_snapshot;
auto h = get_history();
if (h)
{
hash_at_snapshot = d.deserialise_raw();
}
std::vector<Version> view_history_;
if (view_history)
{
view_history_ = d.deserialise_view_history();
}
OrderedChanges changes;
MapCollection new_maps;
for (auto r = d.start_map(); r.has_value(); r = d.start_map())
{
const auto map_name = r.value();
std::shared_ptr<kv::untyped::Map> map = nullptr;
auto search = maps.find(map_name);
if (search == maps.end())
{
map = std::make_shared<kv::untyped::Map>(
this,
map_name,
get_security_domain(map_name),
is_map_replicated(map_name),
should_track_dependencies(map_name));
new_maps[map_name] = map;
LOG_DEBUG_FMT(
"Creating map {} while deserialising snapshot at version {}",
map_name,
v);
}
else
{
map = search->second.second;
}
auto changes_search = changes.find(map_name);
if (changes_search != changes.end())
{
LOG_FAIL_FMT("Failed to deserialise snapshot at version {}", v);
LOG_DEBUG_FMT("Multiple writes on map {}", map_name);
return ApplyResult::FAIL;
}
auto deserialised_snapshot_changes =
map->deserialise_snapshot_changes(d);
// Take ownership of the produced change set, store it to be committed
// later
changes[map_name] = {map, std::move(deserialised_snapshot_changes)};
}
for (auto& it : maps)
{
auto& [_, map] = it.second;
map->unlock();
}
if (!d.end())
{
LOG_FAIL_FMT("Unexpected content in snapshot at version {}", v);
return ApplyResult::FAIL;
}
// Each map is committed at a different version, independently of the
// overall snapshot version. The commit versions for each map are
// contained in the snapshot and applied when the snapshot is committed.
auto r = apply_changes(
changes,
[](bool) { return std::make_tuple(NoVersion, NoVersion); },
hooks,
new_maps);
if (!r.has_value())
{
LOG_FAIL_FMT("Failed to commit deserialised snapshot at version {}", v);
return ApplyResult::FAIL;
}
{
std::lock_guard<std::mutex> vguard(version_lock);
version = v;
last_replicated = v;
last_committable = v;
}
if (h)
{
if (!h->init_from_snapshot(hash_at_snapshot))
{
return ApplyResult::FAIL;
}
}
if (view_history)
{
*view_history = std::move(view_history_);
}
return ApplyResult::PASS;
}
void compact(Version v) override
{
// This is called when the store will never be rolled back to any
// state before the specified version.
// No transactions can be prepared or committed during compaction.
std::lock_guard<std::mutex> mguard(maps_lock);
if (v > current_version())
{
return;
}
for (auto& it : maps)
{
auto& [_, map] = it.second;
map->lock();
}
for (auto& it : maps)
{
auto& [_, map] = it.second;
map->compact(v);
}
for (auto& it : maps)
{
auto& [_, map] = it.second;
map->unlock();
}
{
std::lock_guard<std::mutex> vguard(version_lock);
compacted = v;
auto h = get_history();
if (h)
{
h->compact(v);
}
}
for (auto& it : maps)
{
auto& [_, map] = it.second;
map->post_compact();
}
}
void rollback(const TxID& tx_id, Term term_of_next_version_) override
{
// This is called to roll the store back to the state it was in
// at the specified version.
// No transactions can be prepared or committed during rollback.
std::lock_guard<std::mutex> mguard(maps_lock);
{
std::lock_guard<std::mutex> vguard(version_lock);
if (tx_id.version < compacted)
{
throw std::logic_error(fmt::format(
"Attempting rollback to {}, earlier than commit version {}",
tx_id.version,
compacted));
}
// The term should always be updated on rollback() when passed
// regardless of whether version needs to be updated or not
term_of_next_version = term_of_next_version_;
term_of_last_version = tx_id.term;
// History must be informed of the term_of_last_version change, even if
// no actual rollback is required
auto h = get_history();
if (h)
{
h->rollback(tx_id, term_of_next_version);
}
if (tx_id.version >= version)
{
return;
}
version = tx_id.version;
last_replicated = tx_id.version;
last_committable = tx_id.version;
rollback_count++;
pending_txs.clear();
auto e = get_encryptor();
if (e)
{
e->rollback(tx_id.version);
}
}
for (auto& it : maps)
{
auto& [_, map] = it.second;
map->lock();
}
auto it = maps.begin();
while (it != maps.end())
{
auto& [map_creation_version, map] = it->second;
// Rollback this map whether we're forgetting about it or not. Anyone
// else still holding it should see it has rolled back
map->rollback(tx_id.version);
if (map_creation_version > tx_id.version)
{
// Map was created more recently; its creation is being forgotten.
// Erase our knowledge of it
map->unlock();
it = maps.erase(it);
}
else
{
++it;
}
}
for (auto& it : maps)
{
auto& [_, map] = it.second;
map->unlock();
}
}
void initialise_term(Term t) override
{
// Note: This should only be called once, when the store is first
// initialised. term_of_next_version is later updated via rollback.
std::lock_guard<std::mutex> vguard(version_lock);
if (term_of_next_version != 0)
{
throw std::logic_error("term_of_next_version is already initialised");
}
term_of_next_version = t;
auto h = get_history();
if (h)
{
h->set_term(term_of_next_version);
}
}
bool fill_maps(
const std::vector<uint8_t>& data,
bool public_only,
kv::Version& v,
kv::Version& max_conflict_version,
kv::Term& view,
OrderedChanges& changes,
MapCollection& new_maps,
bool ignore_strict_versions = false) override
{
// This will return FAILED if the serialised transaction is being
// applied out of order.
// Processing transactions locally and also deserialising to the
// same store will result in a store version mismatch and
// deserialisation will then fail.
auto e = get_encryptor();
auto d = KvStoreDeserialiser(
e,
public_only ? kv::SecurityDomain::PUBLIC :
std::optional<kv::SecurityDomain>());
auto v_ = d.init(data.data(), data.size(), view, is_historical);
if (!v_.has_value())
{
LOG_FAIL_FMT("Initialisation of deserialise object failed");
return false;
}
std::tie(v, max_conflict_version) = v_.value();
// Throw away any local commits that have not propagated via the
// consensus.
rollback({term_of_last_version, v - 1}, term_of_next_version);
if (strict_versions && !ignore_strict_versions)
{
// Make sure this is the next transaction.
auto cv = current_version();
if (cv != (v - 1))
{
LOG_FAIL_FMT(
"Tried to deserialise {} but current_version is {}", v, cv);
return false;
}
}
// Deserialised transactions express read dependencies as versions,
// rather than with the actual value read. As a result, they don't
// need snapshot isolation on the map state, and so do not need to
// lock each of the maps before creating the transaction.
std::lock_guard<std::mutex> mguard(maps_lock);
for (auto r = d.start_map(); r.has_value(); r = d.start_map())
{
const auto map_name = r.value();
auto map = get_map_internal(v, map_name);
if (map == nullptr)
{
auto new_map = std::make_shared<kv::untyped::Map>(
this,
map_name,
get_security_domain(map_name),
is_map_replicated(map_name),
should_track_dependencies(map_name));
map = new_map;
new_maps[map_name] = new_map;
LOG_DEBUG_FMT(
"Creating map '{}' while deserialising transaction at version {}",
map_name,
v);
}
auto change_search = changes.find(map_name);
if (change_search != changes.end())
{
LOG_FAIL_FMT("Failed to deserialise transaction at version {}", v);
LOG_DEBUG_FMT("Multiple writes on map {}", map_name);
return false;
}
auto deserialised_changes = map->deserialise_changes(d, v);
// Take ownership of the produced change set, store it to be applied
// later
changes[map_name] =
kv::MapChanges{map, std::move(deserialised_changes)};
}
if (!d.end())
{
LOG_FAIL_FMT("Unexpected content in transaction at version {}", v);
return false;
}
return true;
}
std::unique_ptr<kv::AbstractExecutionWrapper> deserialize(
const std::vector<uint8_t>& data,
ConsensusType consensus_type,
bool public_only = false,
const std::optional<TxID>& expected_txid = std::nullopt) override
{
if (consensus_type == ConsensusType::CFT)
{
auto exec = std::make_unique<CFTExecutionWrapper>(
this, get_history(), std::move(data), public_only, expected_txid);
return exec;
}
else
{
kv::Version v;
kv::Term view;
kv::Version max_conflict_version;
OrderedChanges changes;
MapCollection new_maps;
if (!fill_maps(
data,
public_only,
v,
max_conflict_version,
view,
changes,
new_maps,
true))
{
return nullptr;
}
std::unique_ptr<BFTExecutionWrapper> exec;
if (changes.find(ccf::Tables::SIGNATURES) != changes.end())
{
exec = std::make_unique<SignatureBFTExec>(
this,
get_history(),
get_consensus(),
std::move(data),
public_only,
v,
view,
std::move(changes),
std::move(new_maps));
}
else if (changes.find(ccf::Tables::BACKUP_SIGNATURES) != changes.end())
{
exec = std::make_unique<BackupSignatureBFTExec>(
this,
get_history(),
get_progress_tracker(),
get_consensus(),
std::move(data),
public_only,
v,
view,
std::move(changes),
std::move(new_maps));
}
else if (changes.find(ccf::Tables::NONCES) != changes.end())
{
exec = std::make_unique<NoncesBFTExec>(
this,
get_history(),
get_progress_tracker(),
std::move(data),
public_only,
v,
view,
std::move(changes),
std::move(new_maps));
}
else if (changes.find(ccf::Tables::NEW_VIEWS) != changes.end())
{
exec = std::make_unique<NewViewBFTExec>(
this,
get_history(),
get_progress_tracker(),
get_consensus(),
std::move(data),
public_only,
v,
view,
std::move(changes),
std::move(new_maps));
}
else if (
changes.find(ccf::Tables::SHARES) != changes.end() || public_only)
{
// The currently logic for creating shares uses entropy. This needs to
// be fixed to use this in a proper BFT way.
// https://github.com/microsoft/CCF/issues/2679
exec = std::make_unique<TxBFTApply>(
this,
get_history(),
std::move(data),
public_only,
std::make_unique<CommittableTx>(this),
v,
max_conflict_version,
view,
std::move(changes),
std::move(new_maps));
}
else if (changes.find(ccf::Tables::AFT_REQUESTS) != changes.end())
{
exec = std::make_unique<TxBFTExec>(
this,
get_history(),
std::move(data),
public_only,
std::make_unique<CommittableTx>(this),
v,
max_conflict_version,
view,
std::move(changes),
std::move(new_maps));
}
else
{
// we have deserialised an entry that didn't belong to the bft
// requests nor the signatures table
for (const auto& it : changes)
{
LOG_FAIL_FMT("Request contains unexpected table - {}", it.first);
}
CCF_ASSERT_FMT_FAIL(
"Request contains unexpected table - {}", changes.begin()->first);
}
return exec;
}
}
bool operator==(const Store& that) const
{
// Only used for debugging, not thread safe.
if (version != that.version)
return false;
if (maps.size() != that.maps.size())
return false;
for (auto it = maps.begin(); it != maps.end(); ++it)
{
auto search = that.maps.find(it->first);
if (search == that.maps.end())
return false;
auto& [this_v, this_map] = it->second;
auto& [that_v, that_map] = search->second;
if (this_v != that_v)
return false;
if (*this_map != *that_map)
return false;
}
return true;
}
Version current_version() override
{
// Must lock in case the version is being incremented.
std::lock_guard<std::mutex> vguard(version_lock);
return version;
}
TxID current_txid() override
{
// Must lock in case the version or read term is being incremented.
std::lock_guard<std::mutex> vguard(version_lock);
return current_txid_unsafe();
}
std::pair<TxID, Term> current_txid_and_commit_term() override
{
// Must lock in case the version or commit term is being incremented.
std::lock_guard<std::mutex> vguard(version_lock);
return {current_txid_unsafe(), term_of_next_version};
}
Version compacted_version() override
{
// Must lock in case the store is being compacted.
std::lock_guard<std::mutex> vguard(version_lock);
return compacted;
}
Term commit_view() override
{
// Must lock in case the commit_view is being incremented.
std::lock_guard<std::mutex> vguard(version_lock);
return term_of_next_version;
}
CommitResult commit(
const TxID& txid,
std::unique_ptr<PendingTx> pending_tx,
bool globally_committable) override
{
auto c = get_consensus();
if (!c)
{
return CommitResult::SUCCESS;
}
std::lock_guard<std::mutex> cguard(commit_lock);
LOG_DEBUG_FMT(
"Store::commit {}{}",
txid.version,
(globally_committable ? " globally_committable" : ""));
BatchVector batch;
Version previous_last_replicated = 0;
Version next_last_replicated = 0;
Version previous_rollback_count = 0;
ccf::View replication_view = 0;
{
std::lock_guard<std::mutex> vguard(version_lock);
if (txid.term != term_of_next_version && consensus->is_primary())
{
// This can happen when a transaction started before a view change,
// but tries to commit after the view change is complete.
LOG_DEBUG_FMT(
"Want to commit for term {} but term is {}",
txid.term,
term_of_next_version);
return CommitResult::FAIL_NO_REPLICATE;
}
if (globally_committable && txid.version > last_committable)
{
last_committable = txid.version;
}
pending_txs.insert(
{txid.version,
std::make_pair(std::move(pending_tx), globally_committable)});
LOG_TRACE_FMT("Inserting pending tx at {}", txid.version);
auto h = get_history();
auto c = get_consensus();
for (Version offset = 1; true; ++offset)
{
auto search = pending_txs.find(last_replicated + offset);
if (search == pending_txs.end())
{
LOG_TRACE_FMT(
"Couldn't find {} = {} + {}, giving up on batch while committing "
"{}.{}",
last_replicated + offset,
last_replicated,
offset,
txid.term,
txid.version);
break;
}
auto& [pending_tx_, committable_] = search->second;
auto [success_, data_, hooks_] = pending_tx_->call();
auto data_shared =
std::make_shared<std::vector<uint8_t>>(std::move(data_));
auto hooks_shared =
std::make_shared<kv::ConsensusHookPtrs>(std::move(hooks_));
// NB: this cannot happen currently. Regular Tx only make it here if
// they did succeed, and signatures cannot conflict because they
// execute in order with a read_version that's version - 1, so even
// two contiguous signatures are fine
if (success_ != CommitResult::SUCCESS)
{
LOG_DEBUG_FMT("Failed Tx commit {}", last_replicated + offset);
}
if (h)
{
h->append(*data_shared);
}
LOG_DEBUG_FMT(
"Batching {} ({}) during commit of {}.{}",
last_replicated + offset,
data_shared->size(),
txid.term,
txid.version);
batch.emplace_back(
last_replicated + offset, data_shared, committable_, hooks_shared);
pending_txs.erase(search);
}
if (batch.size() == 0)
{
return CommitResult::SUCCESS;
}
previous_rollback_count = rollback_count;
previous_last_replicated = last_replicated;
next_last_replicated = last_replicated + batch.size();
replication_view = term_of_next_version;
if (consensus->type() == ConsensusType::BFT && consensus->is_backup())
{
last_replicated = next_last_replicated;
}
}
if (c->replicate(batch, replication_view))
{
std::lock_guard<std::mutex> vguard(version_lock);
if (
last_replicated == previous_last_replicated &&
previous_rollback_count == rollback_count &&
!(consensus->type() == ConsensusType::BFT && consensus->is_backup()))
{
last_replicated = next_last_replicated;
}
return CommitResult::SUCCESS;
}
else
{
LOG_DEBUG_FMT("Failed to replicate");
return CommitResult::FAIL_NO_REPLICATE;
}
}
void lock() override
{
maps_lock.lock();
}
void unlock() override
{
maps_lock.unlock();
}
std::tuple<Version, Version> next_version(bool commit_new_map) override
{
std::lock_guard<std::mutex> vguard(version_lock);
Version v = next_version_unsafe();
auto previous_last_new_map = last_new_map;
if (commit_new_map)
{
last_new_map = v;
}
return std::make_tuple(v, previous_last_new_map);
}
Version next_version() override
{
std::lock_guard<std::mutex> vguard(version_lock);
return next_version_unsafe();
}
TxID next_txid() override
{
std::lock_guard<std::mutex> vguard(version_lock);
next_version_unsafe();
return {term_of_next_version, version};
}
size_t commit_gap() override
{
std::lock_guard<std::mutex> vguard(version_lock);
return version - last_committable;
}
/** This is only safe in very restricted circumstances, and is only
* meant to be used during catastrophic recovery, between a KV
* with public-state only and a KV with full state, to swap in the
* private state from the latter into the former.
*
* It's also important to note that swapping in private state
* may result in previously uncompacted writes becoming effectively
* compacted, from a user's perspective (they would not be internally
* compacted until the next compact() however). So it is important to
* make sure that the private state being swapped in is fully compacted
* before the swap.
**/
void swap_private_maps(Store& store)
{
{
const auto source_version = store.current_version();
const auto target_version = current_version();
if (source_version > target_version)
{
throw std::runtime_error(fmt::format(
"Invalid call to swap_private_maps. Source is at version {} while "
"target is at {}",
source_version,
target_version));
}
}
std::lock_guard<std::mutex> this_maps_guard(maps_lock);
std::lock_guard<std::mutex> other_maps_guard(store.maps_lock);
// Each entry is (Name, MyMap, TheirMap)
using MapEntry = std::tuple<std::string, AbstractMap*, AbstractMap*>;
std::vector<MapEntry> entries;
// Get the list of private maps from the source store
for (auto& [name, pair] : store.maps)
{
auto& [_, map] = pair;
if (map->get_security_domain() == SecurityDomain::PRIVATE)
{
map->lock();
entries.emplace_back(name, nullptr, map.get());
}
}
// For each source map, either create it or, where it already exists,
// confirm it is PRIVATE. Lock it and store it in entries
auto entry = entries.begin();
while (entry != entries.end())
{
const auto& [name, _, their_map] = *entry;
std::shared_ptr<AbstractMap> map = nullptr;
const auto it = maps.find(name);
if (it == maps.end())
{
// NB: We lose the creation version from the original map, but assume
// it is irrelevant - its creation should no longer be at risk of
// rollback
auto new_map = std::make_pair(
NoVersion,
std::make_shared<kv::untyped::Map>(
this,
name,
SecurityDomain::PRIVATE,
is_map_replicated(name),
should_track_dependencies(name)));
maps[name] = new_map;
map = new_map.second;
}
else
{
map = it->second.second;
if (map->get_security_domain() != SecurityDomain::PRIVATE)
{
throw std::logic_error(fmt::format(
"Swap mismatch - map {} is private in source but not in target",
name));
}
}
std::get<1>(*entry) = map.get();
map->lock();
++entry;
}
for (auto& [name, lhs, rhs] : entries)
{
lhs->swap(rhs);
}
for (auto& [name, lhs, rhs] : entries)
{
lhs->unlock();
rhs->unlock();
}
}
void set_map_hook(
const std::string& map_name, const kv::untyped::Map::MapHook& hook)
{
map_hooks[map_name] = hook;
const auto it = maps.find(map_name);
if (it != maps.end())
{
it->second.second->set_map_hook(hook);
}
}
void unset_map_hook(const std::string& map_name)
{
map_hooks.erase(map_name);
const auto it = maps.find(map_name);
if (it != maps.end())
{
it->second.second->unset_map_hook();
}
}
void set_global_hook(
const std::string& map_name, const kv::untyped::Map::CommitHook& hook)
{
global_hooks[map_name] = hook;
const auto it = maps.find(map_name);
if (it != maps.end())
{
it->second.second->set_global_hook(hook);
}
}
void unset_global_hook(const std::string& map_name)
{
global_hooks.erase(map_name);
const auto it = maps.find(map_name);
if (it != maps.end())
{
it->second.second->unset_global_hook();
}
}
ReadOnlyTx create_read_only_tx()
{
return ReadOnlyTx(this);
}
CommittableTx create_tx()
{
return CommittableTx(this);
}
ReservedTx create_reserved_tx(const TxID& tx_id)
{
// version_lock should already been acquired in case term_of_last_version
// is incremented.
return ReservedTx(this, term_of_last_version, tx_id);
}
};
}
| 28.161509 | 80 | 0.574369 | [
"object",
"vector"
] |
7fd20980b37cf69a4df63056e4fa2de0e7f20904 | 609 | h | C | 7_ofAppsInsideQtWindowsWithImgui/src/mainwindow.h | kissinger31/ofxQt | 13f506336414ec189e44f3b0e74d97f3b6cc7178 | [
"MIT"
] | 25 | 2017-05-30T05:58:08.000Z | 2021-04-15T00:44:38.000Z | 7_ofAppsInsideQtWindowsWithImgui/src/mainwindow.h | kissinger31/ofxQt | 13f506336414ec189e44f3b0e74d97f3b6cc7178 | [
"MIT"
] | 1 | 2018-03-04T08:05:12.000Z | 2018-03-12T11:29:26.000Z | 7_ofAppsInsideQtWindowsWithImgui/src/mainwindow.h | jordiexvision/ofxQt | 13f506336414ec189e44f3b0e74d97f3b6cc7178 | [
"MIT"
] | 4 | 2017-10-27T17:29:16.000Z | 2020-03-05T06:41:57.000Z | #ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include "ofMain.h"
#include "ui_mainwindow.h"
#include "device.h"
// include Qt always at the end or face glew error
#include <vector>
#include <QMainWindow>
#include <QMdiSubWindow>
#include <QWidget>
namespace Ui {
class MainWindow;
}
class ofApp;
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
public slots:
void on_actionAdd_OF_app_triggered() {
loadSubWindow(new device(this));
}
private:
Ui::MainWindow *ui;
void loadSubWindow(QWidget* widget);
};
#endif // MAINWINDOW_H
| 15.225 | 50 | 0.738916 | [
"vector"
] |
7fd731be67024ac7099f7119ec4ea29e47384829 | 5,055 | h | C | retro/cores/gba/include/mgba/internal/gb/video.h | MatPoliquin/retro | c70c174a9818d1e97bc36e61abb4694d28fc68e1 | [
"MIT-0",
"MIT"
] | 2,706 | 2018-04-05T18:28:50.000Z | 2022-03-29T16:56:59.000Z | retro/cores/gba/include/mgba/internal/gb/video.h | MatPoliquin/retro | c70c174a9818d1e97bc36e61abb4694d28fc68e1 | [
"MIT-0",
"MIT"
] | 242 | 2018-04-05T22:30:42.000Z | 2022-03-19T01:55:11.000Z | retro/cores/gba/include/mgba/internal/gb/video.h | MatPoliquin/retro | c70c174a9818d1e97bc36e61abb4694d28fc68e1 | [
"MIT-0",
"MIT"
] | 464 | 2018-04-05T19:10:34.000Z | 2022-03-28T13:33:32.000Z | /* Copyright (c) 2013-2016 Jeffrey Pfau
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
#ifndef GB_VIDEO_H
#define GB_VIDEO_H
#include <mgba-util/common.h>
CXX_GUARD_START
#include <mgba/core/timing.h>
#include <mgba/gb/interface.h>
enum {
GB_VIDEO_HORIZONTAL_PIXELS = 160,
GB_VIDEO_VERTICAL_PIXELS = 144,
GB_VIDEO_VBLANK_PIXELS = 10,
GB_VIDEO_VERTICAL_TOTAL_PIXELS = 154,
// TODO: Figure out exact lengths
GB_VIDEO_MODE_2_LENGTH = 80,
GB_VIDEO_MODE_3_LENGTH_BASE = 172,
GB_VIDEO_MODE_0_LENGTH_BASE = 204,
GB_VIDEO_HORIZONTAL_LENGTH = 456,
GB_VIDEO_TOTAL_LENGTH = 70224,
GB_BASE_MAP = 0x1800,
GB_SIZE_MAP = 0x0400,
SGB_SIZE_CHAR_RAM = 0x2000,
SGB_SIZE_MAP_RAM = 0x1000,
SGB_SIZE_PAL_RAM = 0x1000,
SGB_SIZE_ATF_RAM = 0x1000
};
DECL_BITFIELD(GBObjAttributes, uint8_t);
DECL_BITS(GBObjAttributes, CGBPalette, 0, 3);
DECL_BIT(GBObjAttributes, Bank, 3);
DECL_BIT(GBObjAttributes, Palette, 4);
DECL_BIT(GBObjAttributes, XFlip, 5);
DECL_BIT(GBObjAttributes, YFlip, 6);
DECL_BIT(GBObjAttributes, Priority, 7);
DECL_BITFIELD(SGBBgAttributes, uint16_t);
DECL_BITS(SGBBgAttributes, Tile, 0, 10);
DECL_BITS(SGBBgAttributes, Palette, 10, 3);
DECL_BIT(SGBBgAttributes, Priority, 13);
DECL_BIT(SGBBgAttributes, XFlip, 14);
DECL_BIT(SGBBgAttributes, YFlip, 15);
struct GBObj {
uint8_t y;
uint8_t x;
uint8_t tile;
GBObjAttributes attr;
};
union GBOAM {
struct GBObj obj[40];
uint8_t raw[160];
};
struct mCacheSet;
struct GBVideoRenderer {
void (*init)(struct GBVideoRenderer* renderer, enum GBModel model, bool borders);
void (*deinit)(struct GBVideoRenderer* renderer);
uint8_t (*writeVideoRegister)(struct GBVideoRenderer* renderer, uint16_t address, uint8_t value);
void (*writeSGBPacket)(struct GBVideoRenderer* renderer, uint8_t* data);
void (*writeVRAM)(struct GBVideoRenderer* renderer, uint16_t address);
void (*writePalette)(struct GBVideoRenderer* renderer, int index, uint16_t value);
void (*writeOAM)(struct GBVideoRenderer* renderer, uint16_t oam);
void (*drawRange)(struct GBVideoRenderer* renderer, int startX, int endX, int y, struct GBObj* objOnLine, size_t nObj);
void (*finishScanline)(struct GBVideoRenderer* renderer, int y);
void (*finishFrame)(struct GBVideoRenderer* renderer);
void (*getPixels)(struct GBVideoRenderer* renderer, size_t* stride, const void** pixels);
void (*putPixels)(struct GBVideoRenderer* renderer, size_t stride, const void* pixels);
uint8_t* vram;
union GBOAM* oam;
struct mCacheSet* cache;
uint8_t* sgbCharRam;
uint8_t* sgbMapRam;
uint8_t* sgbPalRam;
int sgbRenderMode;
uint8_t* sgbAttributes;
uint8_t* sgbAttributeFiles;
bool disableBG;
bool disableOBJ;
bool disableWIN;
};
DECL_BITFIELD(GBRegisterLCDC, uint8_t);
DECL_BIT(GBRegisterLCDC, BgEnable, 0);
DECL_BIT(GBRegisterLCDC, ObjEnable, 1);
DECL_BIT(GBRegisterLCDC, ObjSize, 2);
DECL_BIT(GBRegisterLCDC, TileMap, 3);
DECL_BIT(GBRegisterLCDC, TileData, 4);
DECL_BIT(GBRegisterLCDC, Window, 5);
DECL_BIT(GBRegisterLCDC, WindowTileMap, 6);
DECL_BIT(GBRegisterLCDC, Enable, 7);
DECL_BITFIELD(GBRegisterSTAT, uint8_t);
DECL_BITS(GBRegisterSTAT, Mode, 0, 2);
DECL_BIT(GBRegisterSTAT, LYC, 2);
DECL_BIT(GBRegisterSTAT, HblankIRQ, 3);
DECL_BIT(GBRegisterSTAT, VblankIRQ, 4);
DECL_BIT(GBRegisterSTAT, OAMIRQ, 5);
DECL_BIT(GBRegisterSTAT, LYCIRQ, 6);
struct GBVideo {
struct GB* p;
struct GBVideoRenderer* renderer;
int x;
int ly;
GBRegisterSTAT stat;
int mode;
struct mTimingEvent modeEvent;
struct mTimingEvent frameEvent;
uint32_t dotClock;
uint8_t* vram;
uint8_t* vramBank;
int vramCurrentBank;
union GBOAM oam;
struct GBObj objThisLine[10];
int objMax;
int bcpIndex;
bool bcpIncrement;
int ocpIndex;
bool ocpIncrement;
uint8_t sgbCommandHeader;
uint16_t dmgPalette[12];
uint16_t palette[64];
bool sgbBorders;
int32_t frameCounter;
int frameskip;
int frameskipCounter;
};
void GBVideoInit(struct GBVideo* video);
void GBVideoReset(struct GBVideo* video);
void GBVideoDeinit(struct GBVideo* video);
void GBVideoAssociateRenderer(struct GBVideo* video, struct GBVideoRenderer* renderer);
void GBVideoProcessDots(struct GBVideo* video, uint32_t cyclesLate);
void GBVideoWriteLCDC(struct GBVideo* video, GBRegisterLCDC value);
void GBVideoWriteSTAT(struct GBVideo* video, GBRegisterSTAT value);
void GBVideoWriteLYC(struct GBVideo* video, uint8_t value);
void GBVideoWritePalette(struct GBVideo* video, uint16_t address, uint8_t value);
void GBVideoSwitchBank(struct GBVideo* video, uint8_t value);
void GBVideoDisableCGB(struct GBVideo* video);
void GBVideoSetPalette(struct GBVideo* video, unsigned index, uint32_t color);
void GBVideoWriteSGBPacket(struct GBVideo* video, uint8_t* data);
struct GBSerializedState;
void GBVideoSerialize(const struct GBVideo* video, struct GBSerializedState* state);
void GBVideoDeserialize(struct GBVideo* video, const struct GBSerializedState* state);
CXX_GUARD_END
#endif
| 27.928177 | 120 | 0.781602 | [
"model"
] |
7fdb2e91d361e7b0f9664caf1d91f9402f9a3094 | 347 | h | C | MyLayout/AllTest2TableViewCell.h | ShanJiJi/MyLinearLayoutDemo | 6d9d1c2286b2eb06c325b81562da08665f51fa56 | [
"MIT"
] | 4,591 | 2015-06-14T02:23:24.000Z | 2022-03-30T06:46:10.000Z | MyLayout/AllTest2TableViewCell.h | ShanJiJi/MyLinearLayoutDemo | 6d9d1c2286b2eb06c325b81562da08665f51fa56 | [
"MIT"
] | 136 | 2015-08-18T05:58:36.000Z | 2022-03-17T11:25:22.000Z | MyLayout/AllTest2TableViewCell.h | ShanJiJi/MyLinearLayoutDemo | 6d9d1c2286b2eb06c325b81562da08665f51fa56 | [
"MIT"
] | 967 | 2015-06-15T01:59:11.000Z | 2022-03-14T08:19:40.000Z | //
// AllTest2TableViewCell.h
// MyLayout
//
// Created by apple on 16/5/25.
// Copyright © 2016年 YoungSoft. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "MyLayout.h"
#import "AllTestDataModel.h"
/**
* 静态高度UITableViewCell
*/
@interface AllTest2TableViewCell : UITableViewCell
-(void)setModel:(AllTest2DataModel*)model;
@end
| 15.086957 | 53 | 0.711816 | [
"model"
] |
7fdefaaad582ca4eee5fbf3aa623b4112dba4ffc | 6,007 | h | C | engine/include/reflection/property.h | ilopit/agea | 9825b661a5e34bb8efe858e52d35656a396bc925 | [
"MIT"
] | null | null | null | engine/include/reflection/property.h | ilopit/agea | 9825b661a5e34bb8efe858e52d35656a396bc925 | [
"MIT"
] | null | null | null | engine/include/reflection/property.h | ilopit/agea | 9825b661a5e34bb8efe858e52d35656a396bc925 | [
"MIT"
] | null | null | null | #pragma once
#include "core/agea_minimal.h"
#include "reflection/types.h"
#include "reflection/property_utils.h"
#include <string>
#include <vector>
#include <unordered_map>
#include <functional>
namespace agea
{
namespace reflection
{
class entry
{
public:
static bool
set_up();
};
class property
{
public:
bool static save_to_string(property& from_property, blob_ptr ptr, std::string& buf);
bool
load_from_string(blob_ptr ptr, const std::string& str);
bool
save_to_string_with_hint(blob_ptr ptr, const std::string& hint, std::string& buf);
bool
load_from_string_with_hint(blob_ptr ptr, const std::string& hint, const std::string& str);
static bool
serialize(reflection::property& p,
blob_ptr ptr,
serialization::json_conteiner& jc,
model::object_constructor_context& occ);
static bool
deserialize(reflection::property& p,
model::smart_object& obj,
serialization::json_conteiner& jc,
model::object_constructor_context& occ);
static bool
deserialize_update(reflection::property& p,
blob_ptr ptr,
serialization::json_conteiner& jc,
model::object_constructor_context& occ);
static bool
copy(property& from_property,
property& to_property,
model::smart_object& src_obj,
model::smart_object& dst_obj,
model::object_constructor_context& occ);
private:
static bool
deserialize_collection(reflection::property& p,
model::smart_object& obj,
serialization::json_conteiner& jc,
model::object_constructor_context& occ);
static bool
deserialize_item(reflection::property& p,
model::smart_object& obj,
serialization::json_conteiner& jc,
model::object_constructor_context& occ);
static bool
deserialize_update_collection(reflection::property& p,
blob_ptr ptr,
serialization::json_conteiner& jc,
model::object_constructor_context& occ);
static bool
deserialize_update_item(reflection::property& p,
blob_ptr ptr,
serialization::json_conteiner& jc,
model::object_constructor_context& occ);
public:
std::string name;
size_t offset;
property_type_description type;
std::string category;
std::vector<std::string> hints;
access_mode access = access_mode::ro;
bool serializable = false;
bool visible = false;
// clang-format off
property_copy_handler copy_handler = nullptr;
property_serialization_handler serialization_handler = nullptr;
property_serialization_update_handler update_handler = nullptr;
// clang-format on
};
struct class_reflection_table
{
class_reflection_table(class_reflection_table* p)
: parent(p)
{
}
class_reflection_table* parent;
};
struct property_convertes
{
using read_from_property = std::function<bool(blob_ptr, std::string&)>;
using write_to_property = std::function<bool(blob_ptr, const std::string&)>;
static std::vector<read_from_property>&
readers()
{
static std::vector<read_from_property> s_readers;
return s_readers;
}
static std::vector<write_to_property>&
writers()
{
static std::vector<write_to_property> s_writers;
return s_writers;
}
static bool
init();
// STR
static bool
read_t_str(blob_ptr ptr, std::string& str);
static bool
write_t_str(blob_ptr ptr, const std::string& str);
// Bool
static bool
read_t_bool(blob_ptr ptr, std::string& str);
static bool
write_t_bool(blob_ptr ptr, const std::string& str);
// I8
static bool
read_t_i8(blob_ptr ptr, std::string& str);
static bool
write_t_i8(blob_ptr ptr, const std::string& str);
// I16
static bool
read_t_i16(blob_ptr ptr, std::string& str);
static bool
write_t_i16(blob_ptr ptr, const std::string& str);
// I32
static bool
read_t_i32(blob_ptr ptr, std::string& str);
static bool
write_t_i32(blob_ptr ptr, const std::string& str);
// I64
static bool
read_t_i64(blob_ptr ptr, std::string& str);
static bool
write_t_i64(blob_ptr ptr, const std::string& str);
// U8
static bool
read_t_u8(blob_ptr ptr, std::string& str);
static bool
write_t_u8(blob_ptr ptr, const std::string& str);
// U16
static bool
read_t_u16(blob_ptr ptr, std::string& str);
static bool
write_t_u16(blob_ptr ptr, const std::string& str);
// U32
static bool
read_t_u32(blob_ptr ptr, std::string& str);
static bool
write_t_u32(blob_ptr ptr, const std::string& str);
// U64
static bool
read_t_u64(blob_ptr ptr, std::string& str);
static bool
write_t_u64(blob_ptr ptr, const std::string& str);
// Float
static bool
read_t_f(blob_ptr ptr, std::string& str);
static bool
write_t_f(blob_ptr ptr, const std::string& str);
// Double
static bool
read_t_d(blob_ptr ptr, std::string& str);
static bool
write_t_d(blob_ptr ptr, const std::string& str);
// Vec3
static bool
read_t_vec3(blob_ptr ptr, std::string& str);
static bool
write_t_vec3(blob_ptr ptr, const std::string& str);
// Material
static bool
read_t_mat(blob_ptr ptr, std::string& str);
static bool
write_t_mat(blob_ptr ptr, const std::string& str);
// Mesh
static bool
read_t_msh(blob_ptr ptr, std::string& str);
static bool
write_t_msh(blob_ptr ptr, const std::string& str);
};
} // namespace reflection
} // namespace agea
#define AGEA_property(...) | 25.892241 | 94 | 0.631929 | [
"mesh",
"vector",
"model"
] |
7fe290b674961e7df86d32e1fcf0ad3388303003 | 21,585 | h | C | icing/legacy/index/icing-dynamic-trie.h | PixelPlusUI-SnowCone/external_icing | 206a7d6b4ab83c6acdb8b14565e2431751c9e4cf | [
"Apache-2.0"
] | null | null | null | icing/legacy/index/icing-dynamic-trie.h | PixelPlusUI-SnowCone/external_icing | 206a7d6b4ab83c6acdb8b14565e2431751c9e4cf | [
"Apache-2.0"
] | null | null | null | icing/legacy/index/icing-dynamic-trie.h | PixelPlusUI-SnowCone/external_icing | 206a7d6b4ab83c6acdb8b14565e2431751c9e4cf | [
"Apache-2.0"
] | null | null | null | // Copyright (C) 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.
// Copyright 2011 Google Inc. All Rights Reserved.
// Author: ulas@google.com (Ulas Kirazci)
//
// Trie for word prefix lookups. Features:
//
// - Dynamic additions (but not deletions)
// - Low memory usage
// - Reasonable latency but not QPS
// - Revive from persistence is a disk read
// - Stores a 4-byte value associated with every key
//
// Associated with each value in the trie is a set of property ids. For
// efficiency, property ids should start at 0 and be densely packed. A value
// may have more than one id set. There is an additional deleted property
// for each value, which is set only when all the property ids associated with a
// value have been cleared. In the flash_index, property ids are used to track
// corpus ids.
//
// Not thread-safe.
#ifndef ICING_LEGACY_INDEX_ICING_DYNAMIC_TRIE_H_
#define ICING_LEGACY_INDEX_ICING_DYNAMIC_TRIE_H_
#include <stdint.h>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include "icing/legacy/core/icing-compat.h"
#include "icing/legacy/core/icing-packed-pod.h"
#include "icing/legacy/index/icing-filesystem.h"
#include "icing/legacy/index/icing-mmapper.h"
#include "icing/legacy/index/icing-storage.h"
#include "icing/legacy/index/proto/icing-dynamic-trie-header.pb.h"
#include "icing/util/i18n-utils.h"
#include "unicode/utf8.h"
namespace icing {
namespace lib {
class IcingFlashBitmap;
class IcingDynamicTrie : public IIcingStorage {
class Dumper;
class IcingDynamicTrieStorage;
public:
// Adjacent bit fields are usually packed automatically. However, that is
// implementation specific:
// http://en.cppreference.com/w/cpp/language/bit_field
// So we'll set packed to be explicit.
class Node {
public:
// This object is only ever used by an ArrayStorage, which allocates
// sizeof(Node) bytes, zeroes them out and then casts to a Node.
Node() = delete;
uint32_t next_index() const { return next_index_; }
void set_next_index(uint32_t next_index) { next_index_ = next_index; }
bool is_leaf() const { return is_leaf_; }
void set_is_leaf(bool is_leaf) { is_leaf_ = is_leaf; }
uint8_t log2_num_children() const { return log2_num_children_; }
void set_log2_num_children(uint8_t log2_num_children) {
log2_num_children_ = log2_num_children;
}
private:
uint32_t next_index_ : 27;
uint32_t is_leaf_ : 1;
uint32_t log2_num_children_ : 4;
} __attribute__((packed));
static_assert(sizeof(Node) == 4, "");
static_assert(icing_is_packed_pod<Node>::value, "go/icing-ubsan");
// Adjacent bit fields are usually packed automatically. However, that is
// implementation specific:
// http://en.cppreference.com/w/cpp/language/bit_field.
// So we'll set packed to be explicit.
union Next {
Next(uint8_t val, uint32_t node_index) {
used.val = val;
used.node_index = node_index;
}
uint8_t val() const { return used.val; }
void set_val(uint8_t val) { used.val = val; }
uint32_t node_index() const { return used.node_index; }
void set_node_index(uint32_t node_index) { used.node_index = node_index; }
uint32_t next_index() const { return freelink.next_index; }
void set_next_index(uint32_t next_index) {
freelink.next_index = next_index;
}
bool operator<(const Next &next2) const {
if (val() == next2.val()) {
return node_index() < next2.node_index();
}
return val() < next2.val();
}
private:
// This object is only ever used by an ArrayStorage, which allocates
// sizeof(Node) bytes, zeroes them out and then casts to a Node.
Next() = default;
struct {
uint32_t val : 8;
uint32_t node_index : 24;
} used;
struct {
uint32_t next_index : 32;
} freelink;
} __attribute__((packed));
static_assert(sizeof(Next) == 4, "");
static_assert(sizeof(Next) % alignof(Next) == 0, "");
static_assert(icing_is_packed_pod<Next>::value, "go/icing-ubsan");
static const int kMaxNextArraySize = 256;
static const int kNumNextAllocationBuckets = 9; // [log2(1), log2(256)]
static const uint32_t kMaxPropertyId = (1 << 16) - 1;
static const uint32_t kInvalidValueIndex = 0;
static const uint32_t kNoCrc = 0;
struct Stats {
uint32_t num_keys;
// Node stats
uint32_t num_nodes;
uint32_t max_nodes;
// Count of intermediate nodes.
uint32_t num_intermediates;
// Count of leaf nodes.
uint32_t num_leaves;
// Next stats
uint32_t num_nexts;
uint32_t max_nexts;
// Count of next arrays by size.
uint32_t child_counts[kMaxNextArraySize];
// Wasted next array space per allocation bucket (in Nexts, not
// bytes).
uint32_t wasted[kNumNextAllocationBuckets];
// Sum of wasted array.
uint32_t total_wasted;
// Suffix stats
uint32_t suffixes_size;
uint32_t max_suffixes_size;
// Bytes actually used by suffixes.
uint32_t suffixes_used;
// Number of suffixes that are just empty strings.
uint32_t null_suffixes;
// Next free-list stats
uint32_t num_free[kNumNextAllocationBuckets];
// Total Next nodes free (weighted sum of the above).
uint32_t total_free;
// Dirty pages.
uint32_t dirty_pages_nodes;
uint32_t dirty_pages_nexts;
uint32_t dirty_pages_suffixes;
std::string DumpStats(int verbosity) const;
};
// Options when creating the trie. Maximums for the node/next/suffix
// arrays must be specified in advance.
struct Options {
// Absolute maximums.
static const uint32_t kMaxNodes, kMaxNexts, kMaxSuffixesSize, kMaxValueSize;
// The default takes 13MB of memory and can take about 1M English
// words.
Options()
: max_nodes(1U << 20),
max_nexts(1U << 20),
max_suffixes_size(5U << 20),
value_size(sizeof(uint32_t)) {}
Options(uint32_t max_nodes_in, uint32_t max_nexts_in,
uint32_t max_suffixes_size_in, uint32_t value_size_in)
: max_nodes(max_nodes_in),
max_nexts(max_nexts_in),
max_suffixes_size(max_suffixes_size_in),
value_size(value_size_in) {}
uint32_t max_nodes;
uint32_t max_nexts;
uint32_t max_suffixes_size;
uint32_t value_size;
// True if options do not exceed absolute maximums.
bool is_valid() const;
};
// These can be supplied during runtime, as opposed to the persisted
// Options above.
struct RuntimeOptions {
enum StoragePolicy {
// Changes are reflected in the underlying file immediately but
// more vulnerable to corruption.
kMapSharedWithCrc,
// Changes only applied during Flush. Smaller window of
// vulnerability to corruption.
kExplicitFlush,
};
RuntimeOptions &set_storage_policy(StoragePolicy sp) {
storage_policy = sp;
return *this;
}
StoragePolicy storage_policy = kExplicitFlush;
};
static uint32_t max_value_index(const Options &options) {
return options.max_suffixes_size;
}
// Light-weight constructor. Real work happens in Create or Init.
IcingDynamicTrie(const std::string &filename_base,
const RuntimeOptions &runtime_options,
const IcingFilesystem *filesystem);
~IcingDynamicTrie() override;
bool is_initialized() const { return is_initialized_; }
// Create, but do not Init, a new trie with options if the file does
// not already exist.
//
// Returns true if successfully created all files or files already
// exist. Does not do a complete sanity check for when files seem to
// exist. Cleans up files if creation fails midstream.
bool CreateIfNotExist(const Options &options);
bool UpgradeTo(int new_version) override { return true; }
bool Init() override;
void Close() override;
bool Remove() override;
uint64_t GetDiskUsage() const override;
// Returns the size of the elements held in the trie. This excludes the size
// of any internal metadata of the trie, e.g. the trie's header.
uint64_t GetElementsSize() const;
// REQUIRED: For all functions below is_initialized() == true.
// Number of keys in trie.
uint32_t size() const;
// Collecting stats.
void CollectStats(Stats *stats) const;
// Gets all of the contents of the trie for debugging purposes. Note: this
// stores the entire set of terms in memory.
// pretty_print - The tree structure of the trie will be written to this.
// keys - All keys in the trie are appended to this vector.
void DumpTrie(std::ostream *pretty_print,
std::vector<std::string> *keys) const;
// Empty out the trie without closing or removing.
void Clear();
// Clears the suffix and value at the given index. Returns true on success.
bool ClearSuffixAndValue(uint32_t suffix_value_index);
// Resets the next at the given index so that it points to no node.
// Returns true on success.
bool ResetNext(uint32_t next_index);
// Sorts the next array of the node. Returns true on success.
bool SortNextArray(const Node *node);
// Sync to disk.
bool Sync() override;
// Tell kernel we will access the memory shortly.
void Warm() const;
// Potentially about to get nuked.
void OnSleep() override;
// Compact trie into out for value indices present in old_tvi_to_new_value.
class NewValueMap {
public:
virtual ~NewValueMap();
// Returns the new value we want to assign to the entry at old
// value index. We don't take ownership of the pointer.
virtual const void *GetNewValue(uint32_t old_value_index) const = 0;
};
// Compacts this trie. This drops all deleted keys, drops all keys for which
// old_tvi_to_new_value returns nullptr, updates values to be the values
// returned by old_tvi_to_new_value, rewrites tvis, and saves the results into
// the trie given in 'out'. 'old_to_new_tvi' is be populated with a mapping of
// old value_index to new value_index.
bool Compact(const NewValueMap &old_tvi_to_new_value, IcingDynamicTrie *out,
std::unordered_map<uint32_t, uint32_t> *old_to_new_tvi) const;
// Insert value at key. If key already exists and replace == true,
// replaces old value with value. We take a copy of value.
//
// If value_index is not NULL, returns a pointer to value in
// value_index. This can then be used with SetValueAtIndex
// below. value_index is not valid past a Clear/Read/Write.
//
// Returns false if there is no space left in the trie.
//
// REQUIRES: value a buffer of size value_size()
bool Insert(const char *key, const void *value) {
return Insert(key, value, nullptr, true, nullptr);
}
bool Insert(const char *key, const void *value, uint32_t *value_index,
bool replace) {
return Insert(key, value, value_index, replace, nullptr);
}
bool Insert(const char *key, const void *value, uint32_t *value_index,
bool replace, bool *pnew_key);
// Get a value returned by Insert value_index. This points to the
// value in the trie. The pointer is immutable and always valid
// while the trie is alive.
const void *GetValueAtIndex(uint32_t value_index) const;
// Set a value returned by Insert value_index. We take a copy of
// value.
//
// REQUIRES: value a buffer of size value_size()
void SetValueAtIndex(uint32_t value_index, const void *value);
// Returns true if key is found and sets value. If value_index is
// not NULL, returns value_index (see Insert discussion above).
// If the key is not found, returns false and neither value nor
// value_index is modified.
//
// REQUIRES: value a buffer of size value_size()
bool Find(const char *key, void *value) const {
return Find(key, value, nullptr);
}
bool Find(const char *key, void *value, uint32_t *value_index) const;
// Find the input key and all keys that are a variant of the input
// key according to a variant map. Currently supports
// transliteration. For example "a" is a variant for "à" or "á" so
// an "a" in the input key can match those characters in the trie in
// addition to itself.
//
// If prefix is set, also returns any prefix matches (so value_index
// will be invalid).
//
// REQUIRES: all terms in the lexicon to be valid utf8.
struct OriginalMatch {
uint32_t value_index;
std::string orig;
OriginalMatch() : value_index(kInvalidValueIndex) {}
bool is_full_match() const { return value_index != kInvalidValueIndex; }
};
static constexpr int kNoBranchFound = -1;
// Return prefix of any new branches created if key were inserted. If utf8 is
// true, does not cut key mid-utf8. Returns kNoBranchFound if no branches
// would be created.
int FindNewBranchingPrefixLength(const char *key, bool utf8) const;
// Find all prefixes of key where the trie branches. Excludes the key
// itself. If utf8 is true, does not cut key mid-utf8.
std::vector<int> FindBranchingPrefixLengths(const char *key, bool utf8) const;
void GetDebugInfo(int verbosity, std::string *out) const override;
double min_free_fraction() const;
uint32_t value_size() const;
uint32_t max_value_index() const;
// If in kMapSharedWithCrc mode, update crcs and return the master
// crc, else return kNoCrc. This crc includes both the trie files
// and property bitmaps.
uint32_t UpdateCrc();
// Store dynamic properties for each value. When a property is added to
// a value, the deleted flag is cleared for it (if it was previously set).
bool SetProperty(uint32_t value_index, uint32_t property_id);
bool ClearProperty(uint32_t value_index, uint32_t property_id);
// Store deleted property for each value.
// This method is not the only way the deleted property can be set; the trie
// may set this property itself during other operations if it can determine a
// value becomes superfluous.
bool SetDeleted(uint32_t value_index);
// Clears the deleted property for each value.
bool ClearDeleted(uint32_t value_index);
// Deletes the entry associated with the key. Data can not be recovered after
// the deletion. Returns true on success.
bool Delete(std::string_view key);
// Clear a specific property id from all values. For each value that has this
// property cleared, also check to see if it was the only property set; if
// so, set the deleted property for the value to indicate it no longer has any
// properties associated with it.
bool ClearPropertyForAllValues(uint32_t property_id);
// Access properties. Usage:
//
// IcingDynamicTrie::PropertyReader reader(trie, 10);
// char value[SIZE];
// uint32_t value_index;
// if (trie.Find("abc", value, &value_index) &&
// reader.HasProperty(value_index)) {
// ...
// }
//
// Readers are valid as long as the underlying trie is open.
class PropertyReaderBase {
public:
// Whether underlying file exists.
bool Exists() const;
// Returns false for all values if underlying file is missing.
bool HasProperty(uint32_t value_index) const;
protected:
PropertyReaderBase(const IcingDynamicTrie &trie, bool deleted,
uint32_t property_id);
// Does not own.
const IcingFlashBitmap *bitmap_;
const IcingDynamicTrie &trie_;
};
// Reader for a given property. It is invalidated when the underlying property
// is deleted, or the trie is closed.
class PropertyReader : public PropertyReaderBase {
public:
PropertyReader(const IcingDynamicTrie &trie, uint32_t property_id)
: PropertyReaderBase(trie, false, property_id) {}
};
// Reader for the deleted property. It is invalidated when the trie is closed.
class PropertyDeletedReader : public PropertyReaderBase {
public:
explicit PropertyDeletedReader(const IcingDynamicTrie &trie)
: PropertyReaderBase(trie, true, 0) {}
};
// Reader for all properties (but not the deleted one). It is invalidated when
// the trie is closed.
class PropertyReadersAll {
public:
explicit PropertyReadersAll(const IcingDynamicTrie &trie);
// Whether underlying file for property_id exists.
bool Exists(uint32_t property_id) const;
// Returns false if underlying file or property doesn't exist.
bool HasProperty(uint32_t property_id, uint32_t value_index) const;
// Returns true if the value at value_index is set for the only the supplied
// property_id, and none of the other properties.
bool IsPropertyUnique(uint32_t property_id, uint32_t value_index) const;
// For iterating.
size_t size() const;
private:
const IcingDynamicTrie &trie_;
};
// Iterate through trie in lexicographic order.
//
// Not thread-safe.
//
// Change in underlying trie invalidates iterator.
class Iterator {
public:
Iterator(const IcingDynamicTrie &trie, const char *prefix);
void Reset();
bool Advance();
// If !IsValid(), GetKey() will return NULL and GetValue() will
// return 0.
bool IsValid() const;
const char *GetKey() const;
// This points directly to the underlying data and is valid while
// the trie is alive. We keep ownership of the pointer.
const void *GetValue() const;
uint32_t GetValueIndex() const;
private:
Iterator();
// Copy is ok.
// Helper function that takes the left-most branch down
// intermediate nodes to a leaf.
void LeftBranchToLeaf(uint32_t node_index);
std::string cur_key_;
const char *cur_suffix_;
int cur_suffix_len_;
struct Branch {
uint32_t node_idx;
int child_idx;
explicit Branch(uint32_t ni) : node_idx(ni), child_idx(0) {}
};
std::vector<Branch> branch_stack_;
bool single_leaf_match_;
const IcingDynamicTrie &trie_;
};
// Represents a non-leaf node or a "virtual" trie node in the suffix
// region.
struct LogicalNode {
const Node *node;
int suffix_offset;
LogicalNode() : node(nullptr), suffix_offset(0) {}
LogicalNode(const Node *node_in, int suffix_offset_in)
: node(node_in), suffix_offset(suffix_offset_in) {}
};
// Iterate over all utf8 chars in the trie anchored at prefix (or
// node). If trie has invalid utf8 chars, behavior is undefined (but
// won't crash).
class Utf8Iterator {
public:
void Reset();
bool Advance();
bool IsValid() const;
private:
struct Branch {
const Node *node;
const Next *child;
const Next *child_end;
bool IsFinished();
};
Utf8Iterator();
// Copy is ok.
void LeftBranchToUtf8End();
void InitBranch(Branch *branch, const Node *start, char key_char);
void GoIntoSuffix(const Node *node);
char cur_[U8_MAX_LENGTH + 1]; // NULL-terminated
int cur_len_;
LogicalNode cur_logical_node_;
Branch branch_stack_[U8_MAX_LENGTH];
Branch *branch_end_;
const IcingDynamicTrie &trie_;
const Node *start_node_;
};
private:
class CandidateSet;
// For testing only.
friend class IcingDynamicTrieTest_TrieShouldRespectLimits_Test;
friend class IcingDynamicTrieTest_SyncErrorRecovery_Test;
friend class IcingDynamicTrieTest_BitmapsClosedWhenInitFails_Test;
void GetHeader(IcingDynamicTrieHeader *hdr) const;
void SetHeader(const IcingDynamicTrieHeader &new_hdr);
static const uint32_t kInvalidSuffixIndex;
// Stats helpers.
void CollectStatsRecursive(const Node &node, Stats *stats) const;
// Helpers for Find and Insert.
const Next *GetNextByChar(const Node *node, uint8_t key_char) const;
const Next *LowerBound(const Next *start, const Next *end,
uint8_t key_char) const;
void FindBestNode(const char *key, uint32_t *best_node_index, int *key_offset,
bool prefix, bool utf8 = false) const;
// For value properties. This truncates the data by clearing it, but leaving
// the storage intact.
bool InitPropertyBitmaps();
// Returns a pointer to a bitmap that is successfully opened.
static std::unique_ptr<IcingFlashBitmap> OpenAndInitBitmap(
const std::string &filename, bool verify,
const IcingFilesystem *filesystem);
// Returns a pointer to a writable bitmap, creating it if necessary. Returned
// pointer should not be freed, it will be maintained by property_bitmaps_.
// Returns null if bitmap failed to load.
IcingFlashBitmap *OpenOrCreatePropertyBitmap(uint32_t property_id);
uint64_t ValueIndexToPropertyBitmapIndex(uint32_t value_index) const;
const std::string filename_base_;
bool is_initialized_;
const RuntimeOptions runtime_options_;
std::unique_ptr<IcingDynamicTrieStorage> storage_;
const std::string property_bitmaps_prefix_;
std::vector<std::unique_ptr<IcingFlashBitmap>> property_bitmaps_;
const std::string deleted_bitmap_filename_;
std::unique_ptr<IcingFlashBitmap> deleted_bitmap_;
const IcingFilesystem *const filesystem_;
};
} // namespace lib
} // namespace icing
#endif // ICING_LEGACY_INDEX_ICING_DYNAMIC_TRIE_H_
| 33.465116 | 80 | 0.708826 | [
"object",
"vector"
] |
7fe395c5b09c01e7e5ab9d017c4a526858d869ac | 7,223 | h | C | src/runtime/crt/graph_runtime.h | yongfeng-nv/incubator-tvm | a6cb4b8d3778db5341f991db9adf76ff735b72ea | [
"Apache-2.0"
] | 2 | 2020-06-28T18:39:18.000Z | 2021-08-23T01:18:52.000Z | src/runtime/crt/graph_runtime.h | yongfeng-nv/incubator-tvm | a6cb4b8d3778db5341f991db9adf76ff735b72ea | [
"Apache-2.0"
] | null | null | null | src/runtime/crt/graph_runtime.h | yongfeng-nv/incubator-tvm | a6cb4b8d3778db5341f991db9adf76ff735b72ea | [
"Apache-2.0"
] | 1 | 2021-08-06T01:23:33.000Z | 2021-08-06T01:23:33.000Z | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 graph_runtime.h
* \brief Tiny graph runtime that can run graph containing only tvm PackedFunc.
*/
#ifndef TVM_RUNTIME_CRT_GRAPH_RUNTIME_H_
#define TVM_RUNTIME_CRT_GRAPH_RUNTIME_H_
#include <dlpack/dlpack.h>
#include "load_json.h"
#include "ndarray.h"
#include "packed_func.h"
#include "module.h"
/*! \brief operator attributes about tvm op */
typedef struct TVMOpParam {
char func_name[120];
uint32_t num_inputs;
uint32_t num_outputs;
uint32_t flatten_data;
} TVMOpParam;
// Memory pool entry.
typedef struct TVMGraphRuntimePoolEntry {
size_t size;
int device_type;
} TVMGraphRuntimePoolEntry;
// Node entry
typedef struct TVMGraphRuntimeNodeEntry {
uint32_t node_id;
uint32_t index;
uint32_t version;
// JSON Loader
void (*Load)(JSONReader *reader);
} TVMGraphRuntimeNodeEntry;
// Node
typedef struct TVMGraphRuntimeNode {
// operator type in string
char op_type[16];
// name of the op
char name[120];
// parameters
TVMOpParam param;
// inputs
TVMGraphRuntimeNodeEntry inputs[GRAPH_RUNTIME_NODE_MAX_INPUTS];
size_t inputs_count;
// control deps
uint32_t control_deps[200];
// JSON Loader
void (*LoadAttrs)(struct TVMGraphRuntimeNode * node, JSONReader *reader, TVMOpParam* param);
// JSON Loader
int (*Load)(struct TVMGraphRuntimeNode * node, JSONReader *reader);
} TVMGraphRuntimeNode;
// Graph attribute
typedef struct TVMGraphRuntimeGraphAttr {
uint32_t storage_num_not_alloctaed;
uint32_t storage_id[GRAPH_RUNTIME_MAX_NODES];
uint32_t device_index[GRAPH_RUNTIME_MAX_NODES];
char dltype[GRAPH_RUNTIME_MAX_NODES][10]; // "int8", "int16", "float32"
uint32_t dltype_count;
int64_t shape[GRAPH_RUNTIME_MAX_NODES][TVM_CRT_MAX_NDIM];
uint32_t ndim[GRAPH_RUNTIME_MAX_NODES];
uint32_t shape_count;
} TVMGraphRuntimeGraphAttr;
typedef DLTensor* DLTensorPtr;
/*!
* \brief Tiny graph runtime.
*
* This runtime can be acccesibly in various language via
* TVM runtime PackedFunc API.
*/
/* class GraphRuntime : public ModuleNode { */
typedef struct TVMGraphRuntime {
void (*Run)(struct TVMGraphRuntime * runtime);
/*!
* \brief Initialize the graph executor with graph and context.
* \param graph_json The execution graph.
* \param module The module containing the compiled functions for the host
* processor.
* \param ctxs The context of the host and devices where graph nodes will be
* executed on.
*/
void (*Init)(struct TVMGraphRuntime * runtime,
const char * graph_json,
const TVMModule * module,
const TVMContext * ctxs);
/*!
* \brief Get the input index given the name of input.
* \param name The name of the input.
* \return The index of input.
*/
int (*GetInputIndex)(struct TVMGraphRuntime * runtime, const char * name);
/*!
* \brief set index-th input to the graph.
* \param index The input index.
* \param data_in The input data.
*/
void (*SetInput)(struct TVMGraphRuntime * runtime, const char * name, DLTensor* data_in);
/*!
* \brief Return NDArray for given output index.
* \param index The output index.
*
* \return NDArray corresponding to given output node index.
*/
int (*GetOutput)(struct TVMGraphRuntime * runtime, const int32_t index, DLTensor * out);
/*!
* \brief Load parameters from parameter blob.
* \param param_blob A binary blob of parameter.
*/
int (*LoadParams)(struct TVMGraphRuntime * runtime, const char * param_blob,
const uint32_t param_size);
// The graph attribute fields.
int (*Load)(struct TVMGraphRuntime * runtime, JSONReader *reader);
/*! \brief Setup the temporal storage */
void (*SetupStorage)(struct TVMGraphRuntime * runtime);
/*! \brief Setup the executors. */
int (*SetupOpExecs)(struct TVMGraphRuntime * runtime);
/*!
* \brief Create an execution function given input.
* \param attrs The node attributes.
* \param args The arguments to the functor, including inputs and outputs.
* \param num_inputs Number of inputs.
* \return The created executor.
*/
int32_t (*CreateTVMOp)(struct TVMGraphRuntime * runtime, const TVMOpParam * attrs,
DLTensorPtr * args, const uint32_t args_count,
uint32_t num_inputs, TVMPackedFunc * pf);
// Get node entry index.
uint32_t (*GetEntryId)(struct TVMGraphRuntime * runtime, uint32_t nid, uint32_t index);
// /*! \brief The graph nodes. */
/* GraphRuntimeNode nodes_[GRAPH_RUNTIME_MAX_NODES]; */
TVMGraphRuntimeNode nodes[GRAPH_RUNTIME_MAX_NODES];
uint32_t nodes_count;
/*! \brief The argument nodes. */
uint32_t input_nodes[GRAPH_RUNTIME_MAX_INPUT_NODES];
uint32_t input_nodes_count;
/*! \brief Used for quick entry indexing. */
uint32_t node_row_ptr[GRAPH_RUNTIME_MAX_NODE_ROW_PTR];
uint32_t node_row_ptr_count;
/*! \brief Output entries. */
TVMGraphRuntimeNodeEntry outputs[GRAPH_RUNTIME_MAX_OUTPUTS];
uint32_t outputs_count;
/*! \brief Additional graph attributes. */
TVMGraphRuntimeGraphAttr attrs;
/*! \brief The code module that contains both host and device code. */
TVMModule module;
/*! \brief Execution context of all devices including the host. */
TVMContext ctxs[GRAPH_RUNTIME_MAX_CONTEXTS];
uint32_t ctxs_count;
/*! \brief Common storage pool for all devices. */
TVMNDArray storage_pool[GRAPH_RUNTIME_MAX_NODES];
uint32_t storage_pool_count;
/*! \brief Data entry of each node. */
TVMNDArray data_entry[GRAPH_RUNTIME_MAX_NODES];
uint32_t data_entry_count;
/*! \brief Operator on each node. */
TVMPackedFunc op_execs[GRAPH_RUNTIME_MAX_NODES];
uint32_t op_execs_count;
} TVMGraphRuntime;
// public functions
TVMGraphRuntime * TVMGraphRuntimeCreate(const char * sym_json, const TVMModule * m,
const TVMContext * ctxs);
void TVMGraphRuntimeRelease(TVMGraphRuntime ** runtime);
// private functions
void TVMGraphRuntime_SetInput(TVMGraphRuntime * runtime, const char * name, DLTensor* data_in);
int TVMGraphRuntime_LoadParams(TVMGraphRuntime * runtime, const char * param_blob,
const uint32_t param_size);
void TVMGraphRuntime_Run(TVMGraphRuntime * runtime);
int TVMGraphRuntime_GetOutput(TVMGraphRuntime * runtime, const int32_t idx, DLTensor * out);
#endif // TVM_RUNTIME_CRT_GRAPH_RUNTIME_H_
| 35.234146 | 95 | 0.721722 | [
"shape"
] |
7fe6ed52bdd9d7c1a50dcfa0d0d21acc0de6d464 | 1,763 | h | C | j2objc/include/com/google/common/collect/ForwardingSet.h | benf1977/j2objc-serialization-example | bc356a2fa4a1f4da680a0f6cfe33985220be74f3 | [
"MIT"
] | null | null | null | j2objc/include/com/google/common/collect/ForwardingSet.h | benf1977/j2objc-serialization-example | bc356a2fa4a1f4da680a0f6cfe33985220be74f3 | [
"MIT"
] | null | null | null | j2objc/include/com/google/common/collect/ForwardingSet.h | benf1977/j2objc-serialization-example | bc356a2fa4a1f4da680a0f6cfe33985220be74f3 | [
"MIT"
] | null | null | null | //
// Generated by the J2ObjC translator. DO NOT EDIT!
// source: /Users/tball/tmp/j2objc/guava/sources/com/google/common/collect/ForwardingSet.java
//
#include "J2ObjC_header.h"
#pragma push_macro("ComGoogleCommonCollectForwardingSet_INCLUDE_ALL")
#if ComGoogleCommonCollectForwardingSet_RESTRICT
#define ComGoogleCommonCollectForwardingSet_INCLUDE_ALL 0
#else
#define ComGoogleCommonCollectForwardingSet_INCLUDE_ALL 1
#endif
#undef ComGoogleCommonCollectForwardingSet_RESTRICT
#if !defined (_ComGoogleCommonCollectForwardingSet_) && (ComGoogleCommonCollectForwardingSet_INCLUDE_ALL || ComGoogleCommonCollectForwardingSet_INCLUDE)
#define _ComGoogleCommonCollectForwardingSet_
#define ComGoogleCommonCollectForwardingCollection_RESTRICT 1
#define ComGoogleCommonCollectForwardingCollection_INCLUDE 1
#include "com/google/common/collect/ForwardingCollection.h"
#define JavaUtilSet_RESTRICT 1
#define JavaUtilSet_INCLUDE 1
#include "java/util/Set.h"
@protocol JavaUtilCollection;
@interface ComGoogleCommonCollectForwardingSet : ComGoogleCommonCollectForwardingCollection < JavaUtilSet >
#pragma mark Public
- (jboolean)isEqual:(id)object;
- (NSUInteger)hash;
#pragma mark Protected
- (instancetype)init;
- (id<JavaUtilSet>)delegate;
- (jboolean)standardEqualsWithId:(id)object;
- (jint)standardHashCode;
- (jboolean)standardRemoveAllWithJavaUtilCollection:(id<JavaUtilCollection>)collection;
#pragma mark Package-Private
@end
J2OBJC_EMPTY_STATIC_INIT(ComGoogleCommonCollectForwardingSet)
FOUNDATION_EXPORT void ComGoogleCommonCollectForwardingSet_init(ComGoogleCommonCollectForwardingSet *self);
J2OBJC_TYPE_LITERAL_HEADER(ComGoogleCommonCollectForwardingSet)
#endif
#pragma pop_macro("ComGoogleCommonCollectForwardingSet_INCLUDE_ALL")
| 27.984127 | 152 | 0.854226 | [
"object"
] |
7fe96ff60c581c324a4eaecbf79d8c2e083bf7f8 | 85,827 | c | C | linsched-linsched-alpha/drivers/scsi/3w-xxxx.c | usenixatc2021/SoftRefresh_Scheduling | 589ba06c8ae59538973c22edf28f74a59d63aa14 | [
"MIT"
] | 47 | 2015-03-10T23:21:52.000Z | 2022-02-17T01:04:14.000Z | linsched-linsched-alpha/drivers/scsi/3w-xxxx.c | usenixatc2021/SoftRefresh_Scheduling | 589ba06c8ae59538973c22edf28f74a59d63aa14 | [
"MIT"
] | 1 | 2020-06-30T18:01:37.000Z | 2020-06-30T18:01:37.000Z | linsched-linsched-alpha/drivers/scsi/3w-xxxx.c | usenixatc2021/SoftRefresh_Scheduling | 589ba06c8ae59538973c22edf28f74a59d63aa14 | [
"MIT"
] | 19 | 2015-02-25T19:50:05.000Z | 2021-10-05T14:35:54.000Z | /*
3w-xxxx.c -- 3ware Storage Controller device driver for Linux.
Written By: Adam Radford <linuxraid@lsi.com>
Modifications By: Joel Jacobson <linux@3ware.com>
Arnaldo Carvalho de Melo <acme@conectiva.com.br>
Brad Strand <linux@3ware.com>
Copyright (C) 1999-2010 3ware Inc.
Kernel compatibility By: Andre Hedrick <andre@suse.com>
Non-Copyright (C) 2000 Andre Hedrick <andre@suse.com>
Further tiny build fixes and trivial hoovering Alan Cox
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; version 2 of the License.
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.
NO WARRANTY
THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT
LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT,
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is
solely responsible for determining the appropriateness of using and
distributing the Program and assumes all risks associated with its
exercise of rights under this Agreement, including but not limited to
the risks and costs of program errors, damage to or loss of data,
programs or equipment, and unavailability or interruption of operations.
DISCLAIMER OF LIABILITY
NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), 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 OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED
HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES
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
Bugs/Comments/Suggestions should be mailed to:
linuxraid@lsi.com
For more information, goto:
http://www.lsi.com
History
-------
0.1.000 - Initial release.
0.4.000 - Added support for Asynchronous Event Notification through
ioctls for 3DM.
1.0.000 - Added DPO & FUA bit support for WRITE_10 & WRITE_6 cdb
to disable drive write-cache before writes.
1.1.000 - Fixed performance bug with DPO & FUA not existing for WRITE_6.
1.2.000 - Added support for clean shutdown notification/feature table.
1.02.00.001 - Added support for full command packet posts through ioctls
for 3DM.
Bug fix so hot spare drives don't show up.
1.02.00.002 - Fix bug with tw_setfeature() call that caused oops on some
systems.
08/21/00 - release previously allocated resources on failure at
tw_allocate_memory (acme)
1.02.00.003 - Fix tw_interrupt() to report error to scsi layer when
controller status is non-zero.
Added handling of request_sense opcode.
Fix possible null pointer dereference in
tw_reset_device_extension()
1.02.00.004 - Add support for device id of 3ware 7000 series controllers.
Make tw_setfeature() call with interrupts disabled.
Register interrupt handler before enabling interrupts.
Clear attention interrupt before draining aen queue.
1.02.00.005 - Allocate bounce buffers and custom queue depth for raid5 for
6000 and 5000 series controllers.
Reduce polling mdelays causing problems on some systems.
Fix use_sg = 1 calculation bug.
Check for scsi_register returning NULL.
Add aen count to /proc/scsi/3w-xxxx.
Remove aen code unit masking in tw_aen_complete().
1.02.00.006 - Remove unit from printk in tw_scsi_eh_abort(), causing
possible oops.
Fix possible null pointer dereference in tw_scsi_queue()
if done function pointer was invalid.
1.02.00.007 - Fix possible null pointer dereferences in tw_ioctl().
Remove check for invalid done function pointer from
tw_scsi_queue().
1.02.00.008 - Set max sectors per io to TW_MAX_SECTORS in tw_findcards().
Add tw_decode_error() for printing readable error messages.
Print some useful information on certain aen codes.
Add tw_decode_bits() for interpreting status register output.
Make scsi_set_pci_device() for kernels >= 2.4.4
Fix bug where aen's could be lost before a reset.
Re-add spinlocks in tw_scsi_detect().
Fix possible null pointer dereference in tw_aen_drain_queue()
during initialization.
Clear pci parity errors during initialization and during io.
1.02.00.009 - Remove redundant increment in tw_state_request_start().
Add ioctl support for direct ATA command passthru.
Add entire aen code string list.
1.02.00.010 - Cleanup queueing code, fix jbod thoughput.
Fix get_param for specific units.
1.02.00.011 - Fix bug in tw_aen_complete() where aen's could be lost.
Fix tw_aen_drain_queue() to display useful info at init.
Set tw_host->max_id for 12 port cards.
Add ioctl support for raw command packet post from userspace
with sglist fragments (parameter and io).
1.02.00.012 - Fix read capacity to under report by 1 sector to fix get
last sector ioctl.
1.02.00.013 - Fix bug where more AEN codes weren't coming out during
driver initialization.
Improved handling of PCI aborts.
1.02.00.014 - Fix bug in tw_findcards() where AEN code could be lost.
Increase timeout in tw_aen_drain_queue() to 30 seconds.
1.02.00.015 - Re-write raw command post with data ioctl method.
Remove raid5 bounce buffers for raid5 for 6XXX for kernel 2.5
Add tw_map/unmap_scsi_sg/single_data() for kernel 2.5
Replace io_request_lock with host_lock for kernel 2.5
Set max_cmd_len to 16 for 3dm for kernel 2.5
1.02.00.016 - Set host->max_sectors back up to 256.
1.02.00.017 - Modified pci parity error handling/clearing from config space
during initialization.
1.02.00.018 - Better handling of request sense opcode and sense information
for failed commands. Add tw_decode_sense().
Replace all mdelay()'s with scsi_sleep().
1.02.00.019 - Revert mdelay's and scsi_sleep's, this caused problems on
some SMP systems.
1.02.00.020 - Add pci_set_dma_mask(), rewrite kmalloc()/virt_to_bus() to
pci_alloc/free_consistent().
Better alignment checking in tw_allocate_memory().
Cleanup tw_initialize_device_extension().
1.02.00.021 - Bump cmd_per_lun in SHT to 255 for better jbod performance.
Improve handling of errors in tw_interrupt().
Add handling/clearing of controller queue error.
Empty stale responses before draining aen queue.
Fix tw_scsi_eh_abort() to not reset on every io abort.
Set can_queue in SHT to 255 to prevent hang from AEN.
1.02.00.022 - Fix possible null pointer dereference in tw_scsi_release().
1.02.00.023 - Fix bug in tw_aen_drain_queue() where unit # was always zero.
1.02.00.024 - Add severity levels to AEN strings.
1.02.00.025 - Fix command interrupt spurious error messages.
Fix bug in raw command post with data ioctl method.
Fix bug where rollcall sometimes failed with cable errors.
Print unit # on all command timeouts.
1.02.00.026 - Fix possible infinite retry bug with power glitch induced
drive timeouts.
Cleanup some AEN severity levels.
1.02.00.027 - Add drive not supported AEN code for SATA controllers.
Remove spurious unknown ioctl error message.
1.02.00.028 - Fix bug where multiple controllers with no units were the
same card number.
Fix bug where cards were being shut down more than once.
1.02.00.029 - Add missing pci_free_consistent() in tw_allocate_memory().
Replace pci_map_single() with pci_map_page() for highmem.
Check for tw_setfeature() failure.
1.02.00.030 - Make driver 64-bit clean.
1.02.00.031 - Cleanup polling timeouts/routines in several places.
Add support for mode sense opcode.
Add support for cache mode page.
Add support for synchronize cache opcode.
1.02.00.032 - Fix small multicard rollcall bug.
Make driver stay loaded with no units for hot add/swap.
Add support for "twe" character device for ioctls.
Clean up request_id queueing code.
Fix tw_scsi_queue() spinlocks.
1.02.00.033 - Fix tw_aen_complete() to not queue 'queue empty' AEN's.
Initialize queues correctly when loading with no valid units.
1.02.00.034 - Fix tw_decode_bits() to handle multiple errors.
Add support for user configurable cmd_per_lun.
Add support for sht->slave_configure().
1.02.00.035 - Improve tw_allocate_memory() memory allocation.
Fix tw_chrdev_ioctl() to sleep correctly.
1.02.00.036 - Increase character ioctl timeout to 60 seconds.
1.02.00.037 - Fix tw_ioctl() to handle all non-data ATA passthru cmds
for 'smartmontools' support.
1.26.00.038 - Roll driver minor version to 26 to denote kernel 2.6.
Add support for cmds_per_lun module parameter.
1.26.00.039 - Fix bug in tw_chrdev_ioctl() polling code.
Fix data_buffer_length usage in tw_chrdev_ioctl().
Update contact information.
1.26.02.000 - Convert driver to pci_driver format.
1.26.02.001 - Increase max ioctl buffer size to 512 sectors.
Make tw_scsi_queue() return 0 for 'Unknown scsi opcode'.
Fix tw_remove() to free irq handler/unregister_chrdev()
before shutting down card.
Change to new 'change_queue_depth' api.
Fix 'handled=1' ISR usage, remove bogus IRQ check.
1.26.02.002 - Free irq handler in __tw_shutdown().
Turn on RCD bit for caching mode page.
Serialize reset code.
1.26.02.003 - Force 60 second timeout default.
*/
#include <linux/module.h>
#include <linux/reboot.h>
#include <linux/spinlock.h>
#include <linux/interrupt.h>
#include <linux/moduleparam.h>
#include <linux/errno.h>
#include <linux/types.h>
#include <linux/delay.h>
#include <linux/gfp.h>
#include <linux/pci.h>
#include <linux/time.h>
#include <linux/mutex.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <asm/uaccess.h>
#include <scsi/scsi.h>
#include <scsi/scsi_host.h>
#include <scsi/scsi_tcq.h>
#include <scsi/scsi_cmnd.h>
#include "3w-xxxx.h"
/* Globals */
#define TW_DRIVER_VERSION "1.26.02.003"
static DEFINE_MUTEX(tw_mutex);
static TW_Device_Extension *tw_device_extension_list[TW_MAX_SLOT];
static int tw_device_extension_count = 0;
static int twe_major = -1;
/* Module parameters */
MODULE_AUTHOR("LSI");
MODULE_DESCRIPTION("3ware Storage Controller Linux Driver");
MODULE_LICENSE("GPL");
MODULE_VERSION(TW_DRIVER_VERSION);
/* Function prototypes */
static int tw_reset_device_extension(TW_Device_Extension *tw_dev);
/* Functions */
/* This function will check the status register for unexpected bits */
static int tw_check_bits(u32 status_reg_value)
{
if ((status_reg_value & TW_STATUS_EXPECTED_BITS) != TW_STATUS_EXPECTED_BITS) {
dprintk(KERN_WARNING "3w-xxxx: tw_check_bits(): No expected bits (0x%x).\n", status_reg_value);
return 1;
}
if ((status_reg_value & TW_STATUS_UNEXPECTED_BITS) != 0) {
dprintk(KERN_WARNING "3w-xxxx: tw_check_bits(): Found unexpected bits (0x%x).\n", status_reg_value);
return 1;
}
return 0;
} /* End tw_check_bits() */
/* This function will print readable messages from status register errors */
static int tw_decode_bits(TW_Device_Extension *tw_dev, u32 status_reg_value, int print_host)
{
char host[16];
dprintk(KERN_WARNING "3w-xxxx: tw_decode_bits()\n");
if (print_host)
sprintf(host, " scsi%d:", tw_dev->host->host_no);
else
host[0] = '\0';
if (status_reg_value & TW_STATUS_PCI_PARITY_ERROR) {
printk(KERN_WARNING "3w-xxxx:%s PCI Parity Error: clearing.\n", host);
outl(TW_CONTROL_CLEAR_PARITY_ERROR, TW_CONTROL_REG_ADDR(tw_dev));
}
if (status_reg_value & TW_STATUS_PCI_ABORT) {
printk(KERN_WARNING "3w-xxxx:%s PCI Abort: clearing.\n", host);
outl(TW_CONTROL_CLEAR_PCI_ABORT, TW_CONTROL_REG_ADDR(tw_dev));
pci_write_config_word(tw_dev->tw_pci_dev, PCI_STATUS, TW_PCI_CLEAR_PCI_ABORT);
}
if (status_reg_value & TW_STATUS_QUEUE_ERROR) {
printk(KERN_WARNING "3w-xxxx:%s Controller Queue Error: clearing.\n", host);
outl(TW_CONTROL_CLEAR_QUEUE_ERROR, TW_CONTROL_REG_ADDR(tw_dev));
}
if (status_reg_value & TW_STATUS_SBUF_WRITE_ERROR) {
printk(KERN_WARNING "3w-xxxx:%s SBUF Write Error: clearing.\n", host);
outl(TW_CONTROL_CLEAR_SBUF_WRITE_ERROR, TW_CONTROL_REG_ADDR(tw_dev));
}
if (status_reg_value & TW_STATUS_MICROCONTROLLER_ERROR) {
if (tw_dev->reset_print == 0) {
printk(KERN_WARNING "3w-xxxx:%s Microcontroller Error: clearing.\n", host);
tw_dev->reset_print = 1;
}
return 1;
}
return 0;
} /* End tw_decode_bits() */
/* This function will poll the status register for a flag */
static int tw_poll_status(TW_Device_Extension *tw_dev, u32 flag, int seconds)
{
u32 status_reg_value;
unsigned long before;
int retval = 1;
status_reg_value = inl(TW_STATUS_REG_ADDR(tw_dev));
before = jiffies;
if (tw_check_bits(status_reg_value))
tw_decode_bits(tw_dev, status_reg_value, 0);
while ((status_reg_value & flag) != flag) {
status_reg_value = inl(TW_STATUS_REG_ADDR(tw_dev));
if (tw_check_bits(status_reg_value))
tw_decode_bits(tw_dev, status_reg_value, 0);
if (time_after(jiffies, before + HZ * seconds))
goto out;
msleep(50);
}
retval = 0;
out:
return retval;
} /* End tw_poll_status() */
/* This function will poll the status register for disappearance of a flag */
static int tw_poll_status_gone(TW_Device_Extension *tw_dev, u32 flag, int seconds)
{
u32 status_reg_value;
unsigned long before;
int retval = 1;
status_reg_value = inl(TW_STATUS_REG_ADDR(tw_dev));
before = jiffies;
if (tw_check_bits(status_reg_value))
tw_decode_bits(tw_dev, status_reg_value, 0);
while ((status_reg_value & flag) != 0) {
status_reg_value = inl(TW_STATUS_REG_ADDR(tw_dev));
if (tw_check_bits(status_reg_value))
tw_decode_bits(tw_dev, status_reg_value, 0);
if (time_after(jiffies, before + HZ * seconds))
goto out;
msleep(50);
}
retval = 0;
out:
return retval;
} /* End tw_poll_status_gone() */
/* This function will attempt to post a command packet to the board */
static int tw_post_command_packet(TW_Device_Extension *tw_dev, int request_id)
{
u32 status_reg_value;
unsigned long command_que_value;
dprintk(KERN_NOTICE "3w-xxxx: tw_post_command_packet()\n");
command_que_value = tw_dev->command_packet_physical_address[request_id];
status_reg_value = inl(TW_STATUS_REG_ADDR(tw_dev));
if (tw_check_bits(status_reg_value)) {
dprintk(KERN_WARNING "3w-xxxx: tw_post_command_packet(): Unexpected bits.\n");
tw_decode_bits(tw_dev, status_reg_value, 1);
}
if ((status_reg_value & TW_STATUS_COMMAND_QUEUE_FULL) == 0) {
/* We successfully posted the command packet */
outl(command_que_value, TW_COMMAND_QUEUE_REG_ADDR(tw_dev));
tw_dev->state[request_id] = TW_S_POSTED;
tw_dev->posted_request_count++;
if (tw_dev->posted_request_count > tw_dev->max_posted_request_count) {
tw_dev->max_posted_request_count = tw_dev->posted_request_count;
}
} else {
/* Couldn't post the command packet, so we do it in the isr */
if (tw_dev->state[request_id] != TW_S_PENDING) {
tw_dev->state[request_id] = TW_S_PENDING;
tw_dev->pending_request_count++;
if (tw_dev->pending_request_count > tw_dev->max_pending_request_count) {
tw_dev->max_pending_request_count = tw_dev->pending_request_count;
}
tw_dev->pending_queue[tw_dev->pending_tail] = request_id;
if (tw_dev->pending_tail == TW_Q_LENGTH-1) {
tw_dev->pending_tail = TW_Q_START;
} else {
tw_dev->pending_tail = tw_dev->pending_tail + 1;
}
}
TW_UNMASK_COMMAND_INTERRUPT(tw_dev);
return 1;
}
return 0;
} /* End tw_post_command_packet() */
/* This function will return valid sense buffer information for failed cmds */
static int tw_decode_sense(TW_Device_Extension *tw_dev, int request_id, int fill_sense)
{
int i;
TW_Command *command;
dprintk(KERN_WARNING "3w-xxxx: tw_decode_sense()\n");
command = (TW_Command *)tw_dev->command_packet_virtual_address[request_id];
printk(KERN_WARNING "3w-xxxx: scsi%d: Command failed: status = 0x%x, flags = 0x%x, unit #%d.\n", tw_dev->host->host_no, command->status, command->flags, TW_UNIT_OUT(command->unit__hostid));
/* Attempt to return intelligent sense information */
if (fill_sense) {
if ((command->status == 0xc7) || (command->status == 0xcb)) {
for (i = 0; i < ARRAY_SIZE(tw_sense_table); i++) {
if (command->flags == tw_sense_table[i][0]) {
/* Valid bit and 'current errors' */
tw_dev->srb[request_id]->sense_buffer[0] = (0x1 << 7 | 0x70);
/* Sense key */
tw_dev->srb[request_id]->sense_buffer[2] = tw_sense_table[i][1];
/* Additional sense length */
tw_dev->srb[request_id]->sense_buffer[7] = 0xa; /* 10 bytes */
/* Additional sense code */
tw_dev->srb[request_id]->sense_buffer[12] = tw_sense_table[i][2];
/* Additional sense code qualifier */
tw_dev->srb[request_id]->sense_buffer[13] = tw_sense_table[i][3];
tw_dev->srb[request_id]->result = (DID_OK << 16) | (CHECK_CONDITION << 1);
return TW_ISR_DONT_RESULT; /* Special case for isr to not over-write result */
}
}
}
/* If no table match, error so we get a reset */
return 1;
}
return 0;
} /* End tw_decode_sense() */
/* This function will report controller error status */
static int tw_check_errors(TW_Device_Extension *tw_dev)
{
u32 status_reg_value;
status_reg_value = inl(TW_STATUS_REG_ADDR(tw_dev));
if (TW_STATUS_ERRORS(status_reg_value) || tw_check_bits(status_reg_value)) {
tw_decode_bits(tw_dev, status_reg_value, 0);
return 1;
}
return 0;
} /* End tw_check_errors() */
/* This function will empty the response que */
static void tw_empty_response_que(TW_Device_Extension *tw_dev)
{
u32 status_reg_value, response_que_value;
status_reg_value = inl(TW_STATUS_REG_ADDR(tw_dev));
while ((status_reg_value & TW_STATUS_RESPONSE_QUEUE_EMPTY) == 0) {
response_que_value = inl(TW_RESPONSE_QUEUE_REG_ADDR(tw_dev));
status_reg_value = inl(TW_STATUS_REG_ADDR(tw_dev));
}
} /* End tw_empty_response_que() */
/* This function will free a request_id */
static void tw_state_request_finish(TW_Device_Extension *tw_dev, int request_id)
{
tw_dev->free_queue[tw_dev->free_tail] = request_id;
tw_dev->state[request_id] = TW_S_FINISHED;
tw_dev->free_tail = (tw_dev->free_tail + 1) % TW_Q_LENGTH;
} /* End tw_state_request_finish() */
/* This function will assign an available request_id */
static void tw_state_request_start(TW_Device_Extension *tw_dev, int *request_id)
{
*request_id = tw_dev->free_queue[tw_dev->free_head];
tw_dev->free_head = (tw_dev->free_head + 1) % TW_Q_LENGTH;
tw_dev->state[*request_id] = TW_S_STARTED;
} /* End tw_state_request_start() */
/* Show some statistics about the card */
static ssize_t tw_show_stats(struct device *dev, struct device_attribute *attr,
char *buf)
{
struct Scsi_Host *host = class_to_shost(dev);
TW_Device_Extension *tw_dev = (TW_Device_Extension *)host->hostdata;
unsigned long flags = 0;
ssize_t len;
spin_lock_irqsave(tw_dev->host->host_lock, flags);
len = snprintf(buf, PAGE_SIZE, "3w-xxxx Driver version: %s\n"
"Current commands posted: %4d\n"
"Max commands posted: %4d\n"
"Current pending commands: %4d\n"
"Max pending commands: %4d\n"
"Last sgl length: %4d\n"
"Max sgl length: %4d\n"
"Last sector count: %4d\n"
"Max sector count: %4d\n"
"SCSI Host Resets: %4d\n"
"AEN's: %4d\n",
TW_DRIVER_VERSION,
tw_dev->posted_request_count,
tw_dev->max_posted_request_count,
tw_dev->pending_request_count,
tw_dev->max_pending_request_count,
tw_dev->sgl_entries,
tw_dev->max_sgl_entries,
tw_dev->sector_count,
tw_dev->max_sector_count,
tw_dev->num_resets,
tw_dev->aen_count);
spin_unlock_irqrestore(tw_dev->host->host_lock, flags);
return len;
} /* End tw_show_stats() */
/* This function will set a devices queue depth */
static int tw_change_queue_depth(struct scsi_device *sdev, int queue_depth,
int reason)
{
if (reason != SCSI_QDEPTH_DEFAULT)
return -EOPNOTSUPP;
if (queue_depth > TW_Q_LENGTH-2)
queue_depth = TW_Q_LENGTH-2;
scsi_adjust_queue_depth(sdev, MSG_ORDERED_TAG, queue_depth);
return queue_depth;
} /* End tw_change_queue_depth() */
/* Create sysfs 'stats' entry */
static struct device_attribute tw_host_stats_attr = {
.attr = {
.name = "stats",
.mode = S_IRUGO,
},
.show = tw_show_stats
};
/* Host attributes initializer */
static struct device_attribute *tw_host_attrs[] = {
&tw_host_stats_attr,
NULL,
};
/* This function will read the aen queue from the isr */
static int tw_aen_read_queue(TW_Device_Extension *tw_dev, int request_id)
{
TW_Command *command_packet;
TW_Param *param;
unsigned long command_que_value;
u32 status_reg_value;
unsigned long param_value = 0;
dprintk(KERN_NOTICE "3w-xxxx: tw_aen_read_queue()\n");
status_reg_value = inl(TW_STATUS_REG_ADDR(tw_dev));
if (tw_check_bits(status_reg_value)) {
dprintk(KERN_WARNING "3w-xxxx: tw_aen_read_queue(): Unexpected bits.\n");
tw_decode_bits(tw_dev, status_reg_value, 1);
return 1;
}
if (tw_dev->command_packet_virtual_address[request_id] == NULL) {
printk(KERN_WARNING "3w-xxxx: tw_aen_read_queue(): Bad command packet virtual address.\n");
return 1;
}
command_packet = (TW_Command *)tw_dev->command_packet_virtual_address[request_id];
memset(command_packet, 0, sizeof(TW_Sector));
command_packet->opcode__sgloffset = TW_OPSGL_IN(2, TW_OP_GET_PARAM);
command_packet->size = 4;
command_packet->request_id = request_id;
command_packet->status = 0;
command_packet->flags = 0;
command_packet->byte6.parameter_count = 1;
command_que_value = tw_dev->command_packet_physical_address[request_id];
if (command_que_value == 0) {
printk(KERN_WARNING "3w-xxxx: tw_aen_read_queue(): Bad command packet physical address.\n");
return 1;
}
/* Now setup the param */
if (tw_dev->alignment_virtual_address[request_id] == NULL) {
printk(KERN_WARNING "3w-xxxx: tw_aen_read_queue(): Bad alignment virtual address.\n");
return 1;
}
param = (TW_Param *)tw_dev->alignment_virtual_address[request_id];
memset(param, 0, sizeof(TW_Sector));
param->table_id = 0x401; /* AEN table */
param->parameter_id = 2; /* Unit code */
param->parameter_size_bytes = 2;
param_value = tw_dev->alignment_physical_address[request_id];
if (param_value == 0) {
printk(KERN_WARNING "3w-xxxx: tw_aen_read_queue(): Bad alignment physical address.\n");
return 1;
}
command_packet->byte8.param.sgl[0].address = param_value;
command_packet->byte8.param.sgl[0].length = sizeof(TW_Sector);
/* Now post the command packet */
if ((status_reg_value & TW_STATUS_COMMAND_QUEUE_FULL) == 0) {
dprintk(KERN_WARNING "3w-xxxx: tw_aen_read_queue(): Post succeeded.\n");
tw_dev->srb[request_id] = NULL; /* Flag internal command */
tw_dev->state[request_id] = TW_S_POSTED;
outl(command_que_value, TW_COMMAND_QUEUE_REG_ADDR(tw_dev));
} else {
printk(KERN_WARNING "3w-xxxx: tw_aen_read_queue(): Post failed, will retry.\n");
return 1;
}
return 0;
} /* End tw_aen_read_queue() */
/* This function will complete an aen request from the isr */
static int tw_aen_complete(TW_Device_Extension *tw_dev, int request_id)
{
TW_Param *param;
unsigned short aen;
int error = 0, table_max = 0;
dprintk(KERN_WARNING "3w-xxxx: tw_aen_complete()\n");
if (tw_dev->alignment_virtual_address[request_id] == NULL) {
printk(KERN_WARNING "3w-xxxx: tw_aen_complete(): Bad alignment virtual address.\n");
return 1;
}
param = (TW_Param *)tw_dev->alignment_virtual_address[request_id];
aen = *(unsigned short *)(param->data);
dprintk(KERN_NOTICE "3w-xxxx: tw_aen_complete(): Queue'd code 0x%x\n", aen);
/* Print some useful info when certain aen codes come out */
if (aen == 0x0ff) {
printk(KERN_WARNING "3w-xxxx: scsi%d: AEN: INFO: AEN queue overflow.\n", tw_dev->host->host_no);
} else {
table_max = ARRAY_SIZE(tw_aen_string);
if ((aen & 0x0ff) < table_max) {
if ((tw_aen_string[aen & 0xff][strlen(tw_aen_string[aen & 0xff])-1]) == '#') {
printk(KERN_WARNING "3w-xxxx: scsi%d: AEN: %s%d.\n", tw_dev->host->host_no, tw_aen_string[aen & 0xff], aen >> 8);
} else {
if (aen != 0x0)
printk(KERN_WARNING "3w-xxxx: scsi%d: AEN: %s.\n", tw_dev->host->host_no, tw_aen_string[aen & 0xff]);
}
} else {
printk(KERN_WARNING "3w-xxxx: scsi%d: Received AEN %d.\n", tw_dev->host->host_no, aen);
}
}
if (aen != TW_AEN_QUEUE_EMPTY) {
tw_dev->aen_count++;
/* Now queue the code */
tw_dev->aen_queue[tw_dev->aen_tail] = aen;
if (tw_dev->aen_tail == TW_Q_LENGTH - 1) {
tw_dev->aen_tail = TW_Q_START;
} else {
tw_dev->aen_tail = tw_dev->aen_tail + 1;
}
if (tw_dev->aen_head == tw_dev->aen_tail) {
if (tw_dev->aen_head == TW_Q_LENGTH - 1) {
tw_dev->aen_head = TW_Q_START;
} else {
tw_dev->aen_head = tw_dev->aen_head + 1;
}
}
error = tw_aen_read_queue(tw_dev, request_id);
if (error) {
printk(KERN_WARNING "3w-xxxx: scsi%d: Error completing AEN.\n", tw_dev->host->host_no);
tw_dev->state[request_id] = TW_S_COMPLETED;
tw_state_request_finish(tw_dev, request_id);
}
} else {
tw_dev->state[request_id] = TW_S_COMPLETED;
tw_state_request_finish(tw_dev, request_id);
}
return 0;
} /* End tw_aen_complete() */
/* This function will drain the aen queue after a soft reset */
static int tw_aen_drain_queue(TW_Device_Extension *tw_dev)
{
TW_Command *command_packet;
TW_Param *param;
int request_id = 0;
unsigned long command_que_value;
unsigned long param_value;
TW_Response_Queue response_queue;
unsigned short aen;
unsigned short aen_code;
int finished = 0;
int first_reset = 0;
int queue = 0;
int found = 0, table_max = 0;
dprintk(KERN_NOTICE "3w-xxxx: tw_aen_drain_queue()\n");
if (tw_poll_status(tw_dev, TW_STATUS_ATTENTION_INTERRUPT | TW_STATUS_MICROCONTROLLER_READY, 30)) {
dprintk(KERN_WARNING "3w-xxxx: tw_aen_drain_queue(): No attention interrupt for card %d.\n", tw_device_extension_count);
return 1;
}
TW_CLEAR_ATTENTION_INTERRUPT(tw_dev);
/* Empty response queue */
tw_empty_response_que(tw_dev);
/* Initialize command packet */
if (tw_dev->command_packet_virtual_address[request_id] == NULL) {
printk(KERN_WARNING "3w-xxxx: tw_aen_drain_queue(): Bad command packet virtual address.\n");
return 1;
}
command_packet = (TW_Command *)tw_dev->command_packet_virtual_address[request_id];
memset(command_packet, 0, sizeof(TW_Sector));
command_packet->opcode__sgloffset = TW_OPSGL_IN(2, TW_OP_GET_PARAM);
command_packet->size = 4;
command_packet->request_id = request_id;
command_packet->status = 0;
command_packet->flags = 0;
command_packet->byte6.parameter_count = 1;
command_que_value = tw_dev->command_packet_physical_address[request_id];
if (command_que_value == 0) {
printk(KERN_WARNING "3w-xxxx: tw_aen_drain_queue(): Bad command packet physical address.\n");
return 1;
}
/* Now setup the param */
if (tw_dev->alignment_virtual_address[request_id] == NULL) {
printk(KERN_WARNING "3w-xxxx: tw_aen_drain_queue(): Bad alignment virtual address.\n");
return 1;
}
param = (TW_Param *)tw_dev->alignment_virtual_address[request_id];
memset(param, 0, sizeof(TW_Sector));
param->table_id = 0x401; /* AEN table */
param->parameter_id = 2; /* Unit code */
param->parameter_size_bytes = 2;
param_value = tw_dev->alignment_physical_address[request_id];
if (param_value == 0) {
printk(KERN_WARNING "3w-xxxx: tw_aen_drain_queue(): Bad alignment physical address.\n");
return 1;
}
command_packet->byte8.param.sgl[0].address = param_value;
command_packet->byte8.param.sgl[0].length = sizeof(TW_Sector);
/* Now drain the controller's aen queue */
do {
/* Post command packet */
outl(command_que_value, TW_COMMAND_QUEUE_REG_ADDR(tw_dev));
/* Now poll for completion */
if (tw_poll_status_gone(tw_dev, TW_STATUS_RESPONSE_QUEUE_EMPTY, 30) == 0) {
response_queue.value = inl(TW_RESPONSE_QUEUE_REG_ADDR(tw_dev));
request_id = TW_RESID_OUT(response_queue.response_id);
if (request_id != 0) {
/* Unexpected request id */
printk(KERN_WARNING "3w-xxxx: tw_aen_drain_queue(): Unexpected request id.\n");
return 1;
}
if (command_packet->status != 0) {
if (command_packet->flags != TW_AEN_TABLE_UNDEFINED) {
/* Bad response */
tw_decode_sense(tw_dev, request_id, 0);
return 1;
} else {
/* We know this is a 3w-1x00, and doesn't support aen's */
return 0;
}
}
/* Now check the aen */
aen = *(unsigned short *)(param->data);
aen_code = (aen & 0x0ff);
queue = 0;
switch (aen_code) {
case TW_AEN_QUEUE_EMPTY:
dprintk(KERN_WARNING "3w-xxxx: AEN: %s.\n", tw_aen_string[aen & 0xff]);
if (first_reset != 1) {
return 1;
} else {
finished = 1;
}
break;
case TW_AEN_SOFT_RESET:
if (first_reset == 0) {
first_reset = 1;
} else {
printk(KERN_WARNING "3w-xxxx: AEN: %s.\n", tw_aen_string[aen & 0xff]);
tw_dev->aen_count++;
queue = 1;
}
break;
default:
if (aen == 0x0ff) {
printk(KERN_WARNING "3w-xxxx: AEN: INFO: AEN queue overflow.\n");
} else {
table_max = ARRAY_SIZE(tw_aen_string);
if ((aen & 0x0ff) < table_max) {
if ((tw_aen_string[aen & 0xff][strlen(tw_aen_string[aen & 0xff])-1]) == '#') {
printk(KERN_WARNING "3w-xxxx: AEN: %s%d.\n", tw_aen_string[aen & 0xff], aen >> 8);
} else {
printk(KERN_WARNING "3w-xxxx: AEN: %s.\n", tw_aen_string[aen & 0xff]);
}
} else
printk(KERN_WARNING "3w-xxxx: Received AEN %d.\n", aen);
}
tw_dev->aen_count++;
queue = 1;
}
/* Now put the aen on the aen_queue */
if (queue == 1) {
tw_dev->aen_queue[tw_dev->aen_tail] = aen;
if (tw_dev->aen_tail == TW_Q_LENGTH - 1) {
tw_dev->aen_tail = TW_Q_START;
} else {
tw_dev->aen_tail = tw_dev->aen_tail + 1;
}
if (tw_dev->aen_head == tw_dev->aen_tail) {
if (tw_dev->aen_head == TW_Q_LENGTH - 1) {
tw_dev->aen_head = TW_Q_START;
} else {
tw_dev->aen_head = tw_dev->aen_head + 1;
}
}
}
found = 1;
}
if (found == 0) {
printk(KERN_WARNING "3w-xxxx: tw_aen_drain_queue(): Response never received.\n");
return 1;
}
} while (finished == 0);
return 0;
} /* End tw_aen_drain_queue() */
/* This function will allocate memory */
static int tw_allocate_memory(TW_Device_Extension *tw_dev, int size, int which)
{
int i;
dma_addr_t dma_handle;
unsigned long *cpu_addr = NULL;
dprintk(KERN_NOTICE "3w-xxxx: tw_allocate_memory()\n");
cpu_addr = pci_alloc_consistent(tw_dev->tw_pci_dev, size*TW_Q_LENGTH, &dma_handle);
if (cpu_addr == NULL) {
printk(KERN_WARNING "3w-xxxx: pci_alloc_consistent() failed.\n");
return 1;
}
if ((unsigned long)cpu_addr % (tw_dev->tw_pci_dev->device == TW_DEVICE_ID ? TW_ALIGNMENT_6000 : TW_ALIGNMENT_7000)) {
printk(KERN_WARNING "3w-xxxx: Couldn't allocate correctly aligned memory.\n");
pci_free_consistent(tw_dev->tw_pci_dev, size*TW_Q_LENGTH, cpu_addr, dma_handle);
return 1;
}
memset(cpu_addr, 0, size*TW_Q_LENGTH);
for (i=0;i<TW_Q_LENGTH;i++) {
switch(which) {
case 0:
tw_dev->command_packet_physical_address[i] = dma_handle+(i*size);
tw_dev->command_packet_virtual_address[i] = (unsigned long *)((unsigned char *)cpu_addr + (i*size));
break;
case 1:
tw_dev->alignment_physical_address[i] = dma_handle+(i*size);
tw_dev->alignment_virtual_address[i] = (unsigned long *)((unsigned char *)cpu_addr + (i*size));
break;
default:
printk(KERN_WARNING "3w-xxxx: tw_allocate_memory(): case slip in tw_allocate_memory()\n");
return 1;
}
}
return 0;
} /* End tw_allocate_memory() */
/* This function handles ioctl for the character device */
static long tw_chrdev_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
int request_id;
dma_addr_t dma_handle;
unsigned short tw_aen_code;
unsigned long flags;
unsigned int data_buffer_length = 0;
unsigned long data_buffer_length_adjusted = 0;
struct inode *inode = file->f_dentry->d_inode;
unsigned long *cpu_addr;
long timeout;
TW_New_Ioctl *tw_ioctl;
TW_Passthru *passthru;
TW_Device_Extension *tw_dev = tw_device_extension_list[iminor(inode)];
int retval = -EFAULT;
void __user *argp = (void __user *)arg;
dprintk(KERN_WARNING "3w-xxxx: tw_chrdev_ioctl()\n");
mutex_lock(&tw_mutex);
/* Only let one of these through at a time */
if (mutex_lock_interruptible(&tw_dev->ioctl_lock)) {
mutex_unlock(&tw_mutex);
return -EINTR;
}
/* First copy down the buffer length */
if (copy_from_user(&data_buffer_length, argp, sizeof(unsigned int)))
goto out;
/* Check size */
if (data_buffer_length > TW_MAX_IOCTL_SECTORS * 512) {
retval = -EINVAL;
goto out;
}
/* Hardware can only do multiple of 512 byte transfers */
data_buffer_length_adjusted = (data_buffer_length + 511) & ~511;
/* Now allocate ioctl buf memory */
cpu_addr = dma_alloc_coherent(&tw_dev->tw_pci_dev->dev, data_buffer_length_adjusted+sizeof(TW_New_Ioctl) - 1, &dma_handle, GFP_KERNEL);
if (cpu_addr == NULL) {
retval = -ENOMEM;
goto out;
}
tw_ioctl = (TW_New_Ioctl *)cpu_addr;
/* Now copy down the entire ioctl */
if (copy_from_user(tw_ioctl, argp, data_buffer_length + sizeof(TW_New_Ioctl) - 1))
goto out2;
passthru = (TW_Passthru *)&tw_ioctl->firmware_command;
/* See which ioctl we are doing */
switch (cmd) {
case TW_OP_NOP:
dprintk(KERN_WARNING "3w-xxxx: tw_chrdev_ioctl(): caught TW_OP_NOP.\n");
break;
case TW_OP_AEN_LISTEN:
dprintk(KERN_WARNING "3w-xxxx: tw_chrdev_ioctl(): caught TW_AEN_LISTEN.\n");
memset(tw_ioctl->data_buffer, 0, data_buffer_length);
spin_lock_irqsave(tw_dev->host->host_lock, flags);
if (tw_dev->aen_head == tw_dev->aen_tail) {
tw_aen_code = TW_AEN_QUEUE_EMPTY;
} else {
tw_aen_code = tw_dev->aen_queue[tw_dev->aen_head];
if (tw_dev->aen_head == TW_Q_LENGTH - 1) {
tw_dev->aen_head = TW_Q_START;
} else {
tw_dev->aen_head = tw_dev->aen_head + 1;
}
}
spin_unlock_irqrestore(tw_dev->host->host_lock, flags);
memcpy(tw_ioctl->data_buffer, &tw_aen_code, sizeof(tw_aen_code));
break;
case TW_CMD_PACKET_WITH_DATA:
dprintk(KERN_WARNING "3w-xxxx: tw_chrdev_ioctl(): caught TW_CMD_PACKET_WITH_DATA.\n");
spin_lock_irqsave(tw_dev->host->host_lock, flags);
tw_state_request_start(tw_dev, &request_id);
/* Flag internal command */
tw_dev->srb[request_id] = NULL;
/* Flag chrdev ioctl */
tw_dev->chrdev_request_id = request_id;
tw_ioctl->firmware_command.request_id = request_id;
/* Load the sg list */
switch (TW_SGL_OUT(tw_ioctl->firmware_command.opcode__sgloffset)) {
case 2:
tw_ioctl->firmware_command.byte8.param.sgl[0].address = dma_handle + sizeof(TW_New_Ioctl) - 1;
tw_ioctl->firmware_command.byte8.param.sgl[0].length = data_buffer_length_adjusted;
break;
case 3:
tw_ioctl->firmware_command.byte8.io.sgl[0].address = dma_handle + sizeof(TW_New_Ioctl) - 1;
tw_ioctl->firmware_command.byte8.io.sgl[0].length = data_buffer_length_adjusted;
break;
case 5:
passthru->sg_list[0].address = dma_handle + sizeof(TW_New_Ioctl) - 1;
passthru->sg_list[0].length = data_buffer_length_adjusted;
break;
}
memcpy(tw_dev->command_packet_virtual_address[request_id], &(tw_ioctl->firmware_command), sizeof(TW_Command));
/* Now post the command packet to the controller */
tw_post_command_packet(tw_dev, request_id);
spin_unlock_irqrestore(tw_dev->host->host_lock, flags);
timeout = TW_IOCTL_CHRDEV_TIMEOUT*HZ;
/* Now wait for the command to complete */
timeout = wait_event_timeout(tw_dev->ioctl_wqueue, tw_dev->chrdev_request_id == TW_IOCTL_CHRDEV_FREE, timeout);
/* We timed out, and didn't get an interrupt */
if (tw_dev->chrdev_request_id != TW_IOCTL_CHRDEV_FREE) {
/* Now we need to reset the board */
printk(KERN_WARNING "3w-xxxx: scsi%d: Character ioctl (0x%x) timed out, resetting card.\n", tw_dev->host->host_no, cmd);
retval = -EIO;
if (tw_reset_device_extension(tw_dev)) {
printk(KERN_WARNING "3w-xxxx: tw_chrdev_ioctl(): Reset failed for card %d.\n", tw_dev->host->host_no);
}
goto out2;
}
/* Now copy in the command packet response */
memcpy(&(tw_ioctl->firmware_command), tw_dev->command_packet_virtual_address[request_id], sizeof(TW_Command));
/* Now complete the io */
spin_lock_irqsave(tw_dev->host->host_lock, flags);
tw_dev->posted_request_count--;
tw_dev->state[request_id] = TW_S_COMPLETED;
tw_state_request_finish(tw_dev, request_id);
spin_unlock_irqrestore(tw_dev->host->host_lock, flags);
break;
default:
retval = -ENOTTY;
goto out2;
}
/* Now copy the response to userspace */
if (copy_to_user(argp, tw_ioctl, sizeof(TW_New_Ioctl) + data_buffer_length - 1))
goto out2;
retval = 0;
out2:
/* Now free ioctl buf memory */
dma_free_coherent(&tw_dev->tw_pci_dev->dev, data_buffer_length_adjusted+sizeof(TW_New_Ioctl) - 1, cpu_addr, dma_handle);
out:
mutex_unlock(&tw_dev->ioctl_lock);
mutex_unlock(&tw_mutex);
return retval;
} /* End tw_chrdev_ioctl() */
/* This function handles open for the character device */
/* NOTE that this function races with remove. */
static int tw_chrdev_open(struct inode *inode, struct file *file)
{
unsigned int minor_number;
dprintk(KERN_WARNING "3w-xxxx: tw_ioctl_open()\n");
minor_number = iminor(inode);
if (minor_number >= tw_device_extension_count)
return -ENODEV;
return 0;
} /* End tw_chrdev_open() */
/* File operations struct for character device */
static const struct file_operations tw_fops = {
.owner = THIS_MODULE,
.unlocked_ioctl = tw_chrdev_ioctl,
.open = tw_chrdev_open,
.release = NULL,
.llseek = noop_llseek,
};
/* This function will free up device extension resources */
static void tw_free_device_extension(TW_Device_Extension *tw_dev)
{
dprintk(KERN_NOTICE "3w-xxxx: tw_free_device_extension()\n");
/* Free command packet and generic buffer memory */
if (tw_dev->command_packet_virtual_address[0])
pci_free_consistent(tw_dev->tw_pci_dev, sizeof(TW_Command)*TW_Q_LENGTH, tw_dev->command_packet_virtual_address[0], tw_dev->command_packet_physical_address[0]);
if (tw_dev->alignment_virtual_address[0])
pci_free_consistent(tw_dev->tw_pci_dev, sizeof(TW_Sector)*TW_Q_LENGTH, tw_dev->alignment_virtual_address[0], tw_dev->alignment_physical_address[0]);
} /* End tw_free_device_extension() */
/* This function will send an initconnection command to controller */
static int tw_initconnection(TW_Device_Extension *tw_dev, int message_credits)
{
unsigned long command_que_value;
TW_Command *command_packet;
TW_Response_Queue response_queue;
int request_id = 0;
dprintk(KERN_NOTICE "3w-xxxx: tw_initconnection()\n");
/* Initialize InitConnection command packet */
if (tw_dev->command_packet_virtual_address[request_id] == NULL) {
printk(KERN_WARNING "3w-xxxx: tw_initconnection(): Bad command packet virtual address.\n");
return 1;
}
command_packet = (TW_Command *)tw_dev->command_packet_virtual_address[request_id];
memset(command_packet, 0, sizeof(TW_Sector));
command_packet->opcode__sgloffset = TW_OPSGL_IN(0, TW_OP_INIT_CONNECTION);
command_packet->size = TW_INIT_COMMAND_PACKET_SIZE;
command_packet->request_id = request_id;
command_packet->status = 0x0;
command_packet->flags = 0x0;
command_packet->byte6.message_credits = message_credits;
command_packet->byte8.init_connection.response_queue_pointer = 0x0;
command_que_value = tw_dev->command_packet_physical_address[request_id];
if (command_que_value == 0) {
printk(KERN_WARNING "3w-xxxx: tw_initconnection(): Bad command packet physical address.\n");
return 1;
}
/* Send command packet to the board */
outl(command_que_value, TW_COMMAND_QUEUE_REG_ADDR(tw_dev));
/* Poll for completion */
if (tw_poll_status_gone(tw_dev, TW_STATUS_RESPONSE_QUEUE_EMPTY, 30) == 0) {
response_queue.value = inl(TW_RESPONSE_QUEUE_REG_ADDR(tw_dev));
request_id = TW_RESID_OUT(response_queue.response_id);
if (request_id != 0) {
/* unexpected request id */
printk(KERN_WARNING "3w-xxxx: tw_initconnection(): Unexpected request id.\n");
return 1;
}
if (command_packet->status != 0) {
/* bad response */
tw_decode_sense(tw_dev, request_id, 0);
return 1;
}
}
return 0;
} /* End tw_initconnection() */
/* Set a value in the features table */
static int tw_setfeature(TW_Device_Extension *tw_dev, int parm, int param_size,
unsigned char *val)
{
TW_Param *param;
TW_Command *command_packet;
TW_Response_Queue response_queue;
int request_id = 0;
unsigned long command_que_value;
unsigned long param_value;
/* Initialize SetParam command packet */
if (tw_dev->command_packet_virtual_address[request_id] == NULL) {
printk(KERN_WARNING "3w-xxxx: tw_setfeature(): Bad command packet virtual address.\n");
return 1;
}
command_packet = (TW_Command *)tw_dev->command_packet_virtual_address[request_id];
memset(command_packet, 0, sizeof(TW_Sector));
param = (TW_Param *)tw_dev->alignment_virtual_address[request_id];
command_packet->opcode__sgloffset = TW_OPSGL_IN(2, TW_OP_SET_PARAM);
param->table_id = 0x404; /* Features table */
param->parameter_id = parm;
param->parameter_size_bytes = param_size;
memcpy(param->data, val, param_size);
param_value = tw_dev->alignment_physical_address[request_id];
if (param_value == 0) {
printk(KERN_WARNING "3w-xxxx: tw_setfeature(): Bad alignment physical address.\n");
tw_dev->state[request_id] = TW_S_COMPLETED;
tw_state_request_finish(tw_dev, request_id);
tw_dev->srb[request_id]->result = (DID_OK << 16);
tw_dev->srb[request_id]->scsi_done(tw_dev->srb[request_id]);
}
command_packet->byte8.param.sgl[0].address = param_value;
command_packet->byte8.param.sgl[0].length = sizeof(TW_Sector);
command_packet->size = 4;
command_packet->request_id = request_id;
command_packet->byte6.parameter_count = 1;
command_que_value = tw_dev->command_packet_physical_address[request_id];
if (command_que_value == 0) {
printk(KERN_WARNING "3w-xxxx: tw_setfeature(): Bad command packet physical address.\n");
return 1;
}
/* Send command packet to the board */
outl(command_que_value, TW_COMMAND_QUEUE_REG_ADDR(tw_dev));
/* Poll for completion */
if (tw_poll_status_gone(tw_dev, TW_STATUS_RESPONSE_QUEUE_EMPTY, 30) == 0) {
response_queue.value = inl(TW_RESPONSE_QUEUE_REG_ADDR(tw_dev));
request_id = TW_RESID_OUT(response_queue.response_id);
if (request_id != 0) {
/* unexpected request id */
printk(KERN_WARNING "3w-xxxx: tw_setfeature(): Unexpected request id.\n");
return 1;
}
if (command_packet->status != 0) {
/* bad response */
tw_decode_sense(tw_dev, request_id, 0);
return 1;
}
}
return 0;
} /* End tw_setfeature() */
/* This function will reset a controller */
static int tw_reset_sequence(TW_Device_Extension *tw_dev)
{
int error = 0;
int tries = 0;
unsigned char c = 1;
/* Reset the board */
while (tries < TW_MAX_RESET_TRIES) {
TW_SOFT_RESET(tw_dev);
error = tw_aen_drain_queue(tw_dev);
if (error) {
printk(KERN_WARNING "3w-xxxx: scsi%d: AEN drain failed, retrying.\n", tw_dev->host->host_no);
tries++;
continue;
}
/* Check for controller errors */
if (tw_check_errors(tw_dev)) {
printk(KERN_WARNING "3w-xxxx: scsi%d: Controller errors found, retrying.\n", tw_dev->host->host_no);
tries++;
continue;
}
/* Now the controller is in a good state */
break;
}
if (tries >= TW_MAX_RESET_TRIES) {
printk(KERN_WARNING "3w-xxxx: scsi%d: Controller errors, card not responding, check all cabling.\n", tw_dev->host->host_no);
return 1;
}
error = tw_initconnection(tw_dev, TW_INIT_MESSAGE_CREDITS);
if (error) {
printk(KERN_WARNING "3w-xxxx: scsi%d: Connection initialization failed.\n", tw_dev->host->host_no);
return 1;
}
error = tw_setfeature(tw_dev, 2, 1, &c);
if (error) {
printk(KERN_WARNING "3w-xxxx: Unable to set features for card, probable old firmware or card.\n");
}
return 0;
} /* End tw_reset_sequence() */
/* This function will initialize the fields of a device extension */
static int tw_initialize_device_extension(TW_Device_Extension *tw_dev)
{
int i, error=0;
dprintk(KERN_NOTICE "3w-xxxx: tw_initialize_device_extension()\n");
/* Initialize command packet buffers */
error = tw_allocate_memory(tw_dev, sizeof(TW_Command), 0);
if (error) {
printk(KERN_WARNING "3w-xxxx: Command packet memory allocation failed.\n");
return 1;
}
/* Initialize generic buffer */
error = tw_allocate_memory(tw_dev, sizeof(TW_Sector), 1);
if (error) {
printk(KERN_WARNING "3w-xxxx: Generic memory allocation failed.\n");
return 1;
}
for (i=0;i<TW_Q_LENGTH;i++) {
tw_dev->free_queue[i] = i;
tw_dev->state[i] = TW_S_INITIAL;
}
tw_dev->pending_head = TW_Q_START;
tw_dev->pending_tail = TW_Q_START;
tw_dev->chrdev_request_id = TW_IOCTL_CHRDEV_FREE;
mutex_init(&tw_dev->ioctl_lock);
init_waitqueue_head(&tw_dev->ioctl_wqueue);
return 0;
} /* End tw_initialize_device_extension() */
static int tw_map_scsi_sg_data(struct pci_dev *pdev, struct scsi_cmnd *cmd)
{
int use_sg;
dprintk(KERN_WARNING "3w-xxxx: tw_map_scsi_sg_data()\n");
use_sg = scsi_dma_map(cmd);
if (use_sg < 0) {
printk(KERN_WARNING "3w-xxxx: tw_map_scsi_sg_data(): pci_map_sg() failed.\n");
return 0;
}
cmd->SCp.phase = TW_PHASE_SGLIST;
cmd->SCp.have_data_in = use_sg;
return use_sg;
} /* End tw_map_scsi_sg_data() */
static void tw_unmap_scsi_data(struct pci_dev *pdev, struct scsi_cmnd *cmd)
{
dprintk(KERN_WARNING "3w-xxxx: tw_unmap_scsi_data()\n");
if (cmd->SCp.phase == TW_PHASE_SGLIST)
scsi_dma_unmap(cmd);
} /* End tw_unmap_scsi_data() */
/* This function will reset a device extension */
static int tw_reset_device_extension(TW_Device_Extension *tw_dev)
{
int i = 0;
struct scsi_cmnd *srb;
unsigned long flags = 0;
dprintk(KERN_NOTICE "3w-xxxx: tw_reset_device_extension()\n");
set_bit(TW_IN_RESET, &tw_dev->flags);
TW_DISABLE_INTERRUPTS(tw_dev);
TW_MASK_COMMAND_INTERRUPT(tw_dev);
spin_lock_irqsave(tw_dev->host->host_lock, flags);
/* Abort all requests that are in progress */
for (i=0;i<TW_Q_LENGTH;i++) {
if ((tw_dev->state[i] != TW_S_FINISHED) &&
(tw_dev->state[i] != TW_S_INITIAL) &&
(tw_dev->state[i] != TW_S_COMPLETED)) {
srb = tw_dev->srb[i];
if (srb != NULL) {
srb->result = (DID_RESET << 16);
tw_dev->srb[i]->scsi_done(tw_dev->srb[i]);
tw_unmap_scsi_data(tw_dev->tw_pci_dev, tw_dev->srb[i]);
}
}
}
/* Reset queues and counts */
for (i=0;i<TW_Q_LENGTH;i++) {
tw_dev->free_queue[i] = i;
tw_dev->state[i] = TW_S_INITIAL;
}
tw_dev->free_head = TW_Q_START;
tw_dev->free_tail = TW_Q_START;
tw_dev->posted_request_count = 0;
tw_dev->pending_request_count = 0;
tw_dev->pending_head = TW_Q_START;
tw_dev->pending_tail = TW_Q_START;
tw_dev->reset_print = 0;
spin_unlock_irqrestore(tw_dev->host->host_lock, flags);
if (tw_reset_sequence(tw_dev)) {
printk(KERN_WARNING "3w-xxxx: scsi%d: Reset sequence failed.\n", tw_dev->host->host_no);
return 1;
}
TW_ENABLE_AND_CLEAR_INTERRUPTS(tw_dev);
clear_bit(TW_IN_RESET, &tw_dev->flags);
tw_dev->chrdev_request_id = TW_IOCTL_CHRDEV_FREE;
return 0;
} /* End tw_reset_device_extension() */
/* This funciton returns unit geometry in cylinders/heads/sectors */
static int tw_scsi_biosparam(struct scsi_device *sdev, struct block_device *bdev,
sector_t capacity, int geom[])
{
int heads, sectors, cylinders;
TW_Device_Extension *tw_dev;
dprintk(KERN_NOTICE "3w-xxxx: tw_scsi_biosparam()\n");
tw_dev = (TW_Device_Extension *)sdev->host->hostdata;
heads = 64;
sectors = 32;
cylinders = sector_div(capacity, heads * sectors);
if (capacity >= 0x200000) {
heads = 255;
sectors = 63;
cylinders = sector_div(capacity, heads * sectors);
}
dprintk(KERN_NOTICE "3w-xxxx: tw_scsi_biosparam(): heads = %d, sectors = %d, cylinders = %d\n", heads, sectors, cylinders);
geom[0] = heads;
geom[1] = sectors;
geom[2] = cylinders;
return 0;
} /* End tw_scsi_biosparam() */
/* This is the new scsi eh reset function */
static int tw_scsi_eh_reset(struct scsi_cmnd *SCpnt)
{
TW_Device_Extension *tw_dev=NULL;
int retval = FAILED;
tw_dev = (TW_Device_Extension *)SCpnt->device->host->hostdata;
tw_dev->num_resets++;
sdev_printk(KERN_WARNING, SCpnt->device,
"WARNING: Command (0x%x) timed out, resetting card.\n",
SCpnt->cmnd[0]);
/* Make sure we are not issuing an ioctl or resetting from ioctl */
mutex_lock(&tw_dev->ioctl_lock);
/* Now reset the card and some of the device extension data */
if (tw_reset_device_extension(tw_dev)) {
printk(KERN_WARNING "3w-xxxx: scsi%d: Reset failed.\n", tw_dev->host->host_no);
goto out;
}
retval = SUCCESS;
out:
mutex_unlock(&tw_dev->ioctl_lock);
return retval;
} /* End tw_scsi_eh_reset() */
/* This function handles scsi inquiry commands */
static int tw_scsiop_inquiry(TW_Device_Extension *tw_dev, int request_id)
{
TW_Param *param;
TW_Command *command_packet;
unsigned long command_que_value;
unsigned long param_value;
dprintk(KERN_NOTICE "3w-xxxx: tw_scsiop_inquiry()\n");
/* Initialize command packet */
command_packet = (TW_Command *)tw_dev->command_packet_virtual_address[request_id];
if (command_packet == NULL) {
printk(KERN_WARNING "3w-xxxx: tw_scsiop_inquiry(): Bad command packet virtual address.\n");
return 1;
}
memset(command_packet, 0, sizeof(TW_Sector));
command_packet->opcode__sgloffset = TW_OPSGL_IN(2, TW_OP_GET_PARAM);
command_packet->size = 4;
command_packet->request_id = request_id;
command_packet->status = 0;
command_packet->flags = 0;
command_packet->byte6.parameter_count = 1;
/* Now setup the param */
if (tw_dev->alignment_virtual_address[request_id] == NULL) {
printk(KERN_WARNING "3w-xxxx: tw_scsiop_inquiry(): Bad alignment virtual address.\n");
return 1;
}
param = (TW_Param *)tw_dev->alignment_virtual_address[request_id];
memset(param, 0, sizeof(TW_Sector));
param->table_id = 3; /* unit summary table */
param->parameter_id = 3; /* unitsstatus parameter */
param->parameter_size_bytes = TW_MAX_UNITS;
param_value = tw_dev->alignment_physical_address[request_id];
if (param_value == 0) {
printk(KERN_WARNING "3w-xxxx: tw_scsiop_inquiry(): Bad alignment physical address.\n");
return 1;
}
command_packet->byte8.param.sgl[0].address = param_value;
command_packet->byte8.param.sgl[0].length = sizeof(TW_Sector);
command_que_value = tw_dev->command_packet_physical_address[request_id];
if (command_que_value == 0) {
printk(KERN_WARNING "3w-xxxx: tw_scsiop_inquiry(): Bad command packet physical address.\n");
return 1;
}
/* Now try to post the command packet */
tw_post_command_packet(tw_dev, request_id);
return 0;
} /* End tw_scsiop_inquiry() */
static void tw_transfer_internal(TW_Device_Extension *tw_dev, int request_id,
void *data, unsigned int len)
{
scsi_sg_copy_from_buffer(tw_dev->srb[request_id], data, len);
}
/* This function is called by the isr to complete an inquiry command */
static int tw_scsiop_inquiry_complete(TW_Device_Extension *tw_dev, int request_id)
{
unsigned char *is_unit_present;
unsigned char request_buffer[36];
TW_Param *param;
dprintk(KERN_NOTICE "3w-xxxx: tw_scsiop_inquiry_complete()\n");
memset(request_buffer, 0, sizeof(request_buffer));
request_buffer[0] = TYPE_DISK; /* Peripheral device type */
request_buffer[1] = 0; /* Device type modifier */
request_buffer[2] = 0; /* No ansi/iso compliance */
request_buffer[4] = 31; /* Additional length */
memcpy(&request_buffer[8], "3ware ", 8); /* Vendor ID */
sprintf(&request_buffer[16], "Logical Disk %-2d ", tw_dev->srb[request_id]->device->id);
memcpy(&request_buffer[32], TW_DRIVER_VERSION, 3);
tw_transfer_internal(tw_dev, request_id, request_buffer,
sizeof(request_buffer));
param = (TW_Param *)tw_dev->alignment_virtual_address[request_id];
if (param == NULL) {
printk(KERN_WARNING "3w-xxxx: tw_scsiop_inquiry_complete(): Bad alignment virtual address.\n");
return 1;
}
is_unit_present = &(param->data[0]);
if (is_unit_present[tw_dev->srb[request_id]->device->id] & TW_UNIT_ONLINE) {
tw_dev->is_unit_present[tw_dev->srb[request_id]->device->id] = 1;
} else {
tw_dev->is_unit_present[tw_dev->srb[request_id]->device->id] = 0;
tw_dev->srb[request_id]->result = (DID_BAD_TARGET << 16);
return TW_ISR_DONT_RESULT;
}
return 0;
} /* End tw_scsiop_inquiry_complete() */
/* This function handles scsi mode_sense commands */
static int tw_scsiop_mode_sense(TW_Device_Extension *tw_dev, int request_id)
{
TW_Param *param;
TW_Command *command_packet;
unsigned long command_que_value;
unsigned long param_value;
dprintk(KERN_NOTICE "3w-xxxx: tw_scsiop_mode_sense()\n");
/* Only page control = 0, page code = 0x8 (cache page) supported */
if (tw_dev->srb[request_id]->cmnd[2] != 0x8) {
tw_dev->state[request_id] = TW_S_COMPLETED;
tw_state_request_finish(tw_dev, request_id);
tw_dev->srb[request_id]->result = (DID_OK << 16);
tw_dev->srb[request_id]->scsi_done(tw_dev->srb[request_id]);
return 0;
}
/* Now read firmware cache setting for this unit */
command_packet = (TW_Command *)tw_dev->command_packet_virtual_address[request_id];
if (command_packet == NULL) {
printk(KERN_WARNING "3w-xxxx: tw_scsiop_mode_sense(): Bad command packet virtual address.\n");
return 1;
}
/* Setup the command packet */
memset(command_packet, 0, sizeof(TW_Sector));
command_packet->opcode__sgloffset = TW_OPSGL_IN(2, TW_OP_GET_PARAM);
command_packet->size = 4;
command_packet->request_id = request_id;
command_packet->status = 0;
command_packet->flags = 0;
command_packet->byte6.parameter_count = 1;
/* Setup the param */
if (tw_dev->alignment_virtual_address[request_id] == NULL) {
printk(KERN_WARNING "3w-xxxx: tw_scsiop_mode_sense(): Bad alignment virtual address.\n");
return 1;
}
param = (TW_Param *)tw_dev->alignment_virtual_address[request_id];
memset(param, 0, sizeof(TW_Sector));
param->table_id = TW_UNIT_INFORMATION_TABLE_BASE + tw_dev->srb[request_id]->device->id;
param->parameter_id = 7; /* unit flags */
param->parameter_size_bytes = 1;
param_value = tw_dev->alignment_physical_address[request_id];
if (param_value == 0) {
printk(KERN_WARNING "3w-xxxx: tw_scsiop_mode_sense(): Bad alignment physical address.\n");
return 1;
}
command_packet->byte8.param.sgl[0].address = param_value;
command_packet->byte8.param.sgl[0].length = sizeof(TW_Sector);
command_que_value = tw_dev->command_packet_physical_address[request_id];
if (command_que_value == 0) {
printk(KERN_WARNING "3w-xxxx: tw_scsiop_mode_sense(): Bad command packet physical address.\n");
return 1;
}
/* Now try to post the command packet */
tw_post_command_packet(tw_dev, request_id);
return 0;
} /* End tw_scsiop_mode_sense() */
/* This function is called by the isr to complete a mode sense command */
static int tw_scsiop_mode_sense_complete(TW_Device_Extension *tw_dev, int request_id)
{
TW_Param *param;
unsigned char *flags;
unsigned char request_buffer[8];
dprintk(KERN_NOTICE "3w-xxxx: tw_scsiop_mode_sense_complete()\n");
param = (TW_Param *)tw_dev->alignment_virtual_address[request_id];
if (param == NULL) {
printk(KERN_WARNING "3w-xxxx: tw_scsiop_mode_sense_complete(): Bad alignment virtual address.\n");
return 1;
}
flags = (char *)&(param->data[0]);
memset(request_buffer, 0, sizeof(request_buffer));
request_buffer[0] = 0xf; /* mode data length */
request_buffer[1] = 0; /* default medium type */
request_buffer[2] = 0x10; /* dpo/fua support on */
request_buffer[3] = 0; /* no block descriptors */
request_buffer[4] = 0x8; /* caching page */
request_buffer[5] = 0xa; /* page length */
if (*flags & 0x1)
request_buffer[6] = 0x5; /* WCE on, RCD on */
else
request_buffer[6] = 0x1; /* WCE off, RCD on */
tw_transfer_internal(tw_dev, request_id, request_buffer,
sizeof(request_buffer));
return 0;
} /* End tw_scsiop_mode_sense_complete() */
/* This function handles scsi read_capacity commands */
static int tw_scsiop_read_capacity(TW_Device_Extension *tw_dev, int request_id)
{
TW_Param *param;
TW_Command *command_packet;
unsigned long command_que_value;
unsigned long param_value;
dprintk(KERN_NOTICE "3w-xxxx: tw_scsiop_read_capacity()\n");
/* Initialize command packet */
command_packet = (TW_Command *)tw_dev->command_packet_virtual_address[request_id];
if (command_packet == NULL) {
dprintk(KERN_NOTICE "3w-xxxx: tw_scsiop_read_capacity(): Bad command packet virtual address.\n");
return 1;
}
memset(command_packet, 0, sizeof(TW_Sector));
command_packet->opcode__sgloffset = TW_OPSGL_IN(2, TW_OP_GET_PARAM);
command_packet->size = 4;
command_packet->request_id = request_id;
command_packet->unit__hostid = TW_UNITHOST_IN(0, tw_dev->srb[request_id]->device->id);
command_packet->status = 0;
command_packet->flags = 0;
command_packet->byte6.block_count = 1;
/* Now setup the param */
if (tw_dev->alignment_virtual_address[request_id] == NULL) {
dprintk(KERN_NOTICE "3w-xxxx: tw_scsiop_read_capacity(): Bad alignment virtual address.\n");
return 1;
}
param = (TW_Param *)tw_dev->alignment_virtual_address[request_id];
memset(param, 0, sizeof(TW_Sector));
param->table_id = TW_UNIT_INFORMATION_TABLE_BASE +
tw_dev->srb[request_id]->device->id;
param->parameter_id = 4; /* unitcapacity parameter */
param->parameter_size_bytes = 4;
param_value = tw_dev->alignment_physical_address[request_id];
if (param_value == 0) {
dprintk(KERN_NOTICE "3w-xxxx: tw_scsiop_read_capacity(): Bad alignment physical address.\n");
return 1;
}
command_packet->byte8.param.sgl[0].address = param_value;
command_packet->byte8.param.sgl[0].length = sizeof(TW_Sector);
command_que_value = tw_dev->command_packet_physical_address[request_id];
if (command_que_value == 0) {
dprintk(KERN_NOTICE "3w-xxxx: tw_scsiop_read_capacity(): Bad command packet physical address.\n");
return 1;
}
/* Now try to post the command to the board */
tw_post_command_packet(tw_dev, request_id);
return 0;
} /* End tw_scsiop_read_capacity() */
/* This function is called by the isr to complete a readcapacity command */
static int tw_scsiop_read_capacity_complete(TW_Device_Extension *tw_dev, int request_id)
{
unsigned char *param_data;
u32 capacity;
char buff[8];
TW_Param *param;
dprintk(KERN_NOTICE "3w-xxxx: tw_scsiop_read_capacity_complete()\n");
memset(buff, 0, sizeof(buff));
param = (TW_Param *)tw_dev->alignment_virtual_address[request_id];
if (param == NULL) {
printk(KERN_WARNING "3w-xxxx: tw_scsiop_read_capacity_complete(): Bad alignment virtual address.\n");
return 1;
}
param_data = &(param->data[0]);
capacity = (param_data[3] << 24) | (param_data[2] << 16) |
(param_data[1] << 8) | param_data[0];
/* Subtract one sector to fix get last sector ioctl */
capacity -= 1;
dprintk(KERN_NOTICE "3w-xxxx: tw_scsiop_read_capacity_complete(): Capacity = 0x%x.\n", capacity);
/* Number of LBA's */
buff[0] = (capacity >> 24);
buff[1] = (capacity >> 16) & 0xff;
buff[2] = (capacity >> 8) & 0xff;
buff[3] = capacity & 0xff;
/* Block size in bytes (512) */
buff[4] = (TW_BLOCK_SIZE >> 24);
buff[5] = (TW_BLOCK_SIZE >> 16) & 0xff;
buff[6] = (TW_BLOCK_SIZE >> 8) & 0xff;
buff[7] = TW_BLOCK_SIZE & 0xff;
tw_transfer_internal(tw_dev, request_id, buff, sizeof(buff));
return 0;
} /* End tw_scsiop_read_capacity_complete() */
/* This function handles scsi read or write commands */
static int tw_scsiop_read_write(TW_Device_Extension *tw_dev, int request_id)
{
TW_Command *command_packet;
unsigned long command_que_value;
u32 lba = 0x0, num_sectors = 0x0;
int i, use_sg;
struct scsi_cmnd *srb;
struct scatterlist *sglist, *sg;
dprintk(KERN_NOTICE "3w-xxxx: tw_scsiop_read_write()\n");
srb = tw_dev->srb[request_id];
sglist = scsi_sglist(srb);
if (!sglist) {
printk(KERN_WARNING "3w-xxxx: tw_scsiop_read_write(): Request buffer NULL.\n");
return 1;
}
/* Initialize command packet */
command_packet = (TW_Command *)tw_dev->command_packet_virtual_address[request_id];
if (command_packet == NULL) {
dprintk(KERN_NOTICE "3w-xxxx: tw_scsiop_read_write(): Bad command packet virtual address.\n");
return 1;
}
if (srb->cmnd[0] == READ_6 || srb->cmnd[0] == READ_10) {
command_packet->opcode__sgloffset = TW_OPSGL_IN(3, TW_OP_READ);
} else {
command_packet->opcode__sgloffset = TW_OPSGL_IN(3, TW_OP_WRITE);
}
command_packet->size = 3;
command_packet->request_id = request_id;
command_packet->unit__hostid = TW_UNITHOST_IN(0, srb->device->id);
command_packet->status = 0;
command_packet->flags = 0;
if (srb->cmnd[0] == WRITE_10) {
if ((srb->cmnd[1] & 0x8) || (srb->cmnd[1] & 0x10))
command_packet->flags = 1;
}
if (srb->cmnd[0] == READ_6 || srb->cmnd[0] == WRITE_6) {
lba = ((u32)srb->cmnd[1] << 16) | ((u32)srb->cmnd[2] << 8) | (u32)srb->cmnd[3];
num_sectors = (u32)srb->cmnd[4];
} else {
lba = ((u32)srb->cmnd[2] << 24) | ((u32)srb->cmnd[3] << 16) | ((u32)srb->cmnd[4] << 8) | (u32)srb->cmnd[5];
num_sectors = (u32)srb->cmnd[8] | ((u32)srb->cmnd[7] << 8);
}
/* Update sector statistic */
tw_dev->sector_count = num_sectors;
if (tw_dev->sector_count > tw_dev->max_sector_count)
tw_dev->max_sector_count = tw_dev->sector_count;
dprintk(KERN_NOTICE "3w-xxxx: tw_scsiop_read_write(): lba = 0x%x num_sectors = 0x%x\n", lba, num_sectors);
command_packet->byte8.io.lba = lba;
command_packet->byte6.block_count = num_sectors;
use_sg = tw_map_scsi_sg_data(tw_dev->tw_pci_dev, tw_dev->srb[request_id]);
if (!use_sg)
return 1;
scsi_for_each_sg(tw_dev->srb[request_id], sg, use_sg, i) {
command_packet->byte8.io.sgl[i].address = sg_dma_address(sg);
command_packet->byte8.io.sgl[i].length = sg_dma_len(sg);
command_packet->size+=2;
}
/* Update SG statistics */
tw_dev->sgl_entries = scsi_sg_count(tw_dev->srb[request_id]);
if (tw_dev->sgl_entries > tw_dev->max_sgl_entries)
tw_dev->max_sgl_entries = tw_dev->sgl_entries;
command_que_value = tw_dev->command_packet_physical_address[request_id];
if (command_que_value == 0) {
dprintk(KERN_WARNING "3w-xxxx: tw_scsiop_read_write(): Bad command packet physical address.\n");
return 1;
}
/* Now try to post the command to the board */
tw_post_command_packet(tw_dev, request_id);
return 0;
} /* End tw_scsiop_read_write() */
/* This function will handle the request sense scsi command */
static int tw_scsiop_request_sense(TW_Device_Extension *tw_dev, int request_id)
{
char request_buffer[18];
dprintk(KERN_NOTICE "3w-xxxx: tw_scsiop_request_sense()\n");
memset(request_buffer, 0, sizeof(request_buffer));
request_buffer[0] = 0x70; /* Immediate fixed format */
request_buffer[7] = 10; /* minimum size per SPC: 18 bytes */
/* leave all other fields zero, giving effectively NO_SENSE return */
tw_transfer_internal(tw_dev, request_id, request_buffer,
sizeof(request_buffer));
tw_dev->state[request_id] = TW_S_COMPLETED;
tw_state_request_finish(tw_dev, request_id);
/* If we got a request_sense, we probably want a reset, return error */
tw_dev->srb[request_id]->result = (DID_ERROR << 16);
tw_dev->srb[request_id]->scsi_done(tw_dev->srb[request_id]);
return 0;
} /* End tw_scsiop_request_sense() */
/* This function will handle synchronize cache scsi command */
static int tw_scsiop_synchronize_cache(TW_Device_Extension *tw_dev, int request_id)
{
TW_Command *command_packet;
unsigned long command_que_value;
dprintk(KERN_NOTICE "3w-xxxx: tw_scsiop_synchronize_cache()\n");
/* Send firmware flush command for this unit */
command_packet = (TW_Command *)tw_dev->command_packet_virtual_address[request_id];
if (command_packet == NULL) {
printk(KERN_WARNING "3w-xxxx: tw_scsiop_synchronize_cache(): Bad command packet virtual address.\n");
return 1;
}
/* Setup the command packet */
memset(command_packet, 0, sizeof(TW_Sector));
command_packet->opcode__sgloffset = TW_OPSGL_IN(0, TW_OP_FLUSH_CACHE);
command_packet->size = 2;
command_packet->request_id = request_id;
command_packet->unit__hostid = TW_UNITHOST_IN(0, tw_dev->srb[request_id]->device->id);
command_packet->status = 0;
command_packet->flags = 0;
command_packet->byte6.parameter_count = 1;
command_que_value = tw_dev->command_packet_physical_address[request_id];
if (command_que_value == 0) {
printk(KERN_WARNING "3w-xxxx: tw_scsiop_synchronize_cache(): Bad command packet physical address.\n");
return 1;
}
/* Now try to post the command packet */
tw_post_command_packet(tw_dev, request_id);
return 0;
} /* End tw_scsiop_synchronize_cache() */
/* This function will handle test unit ready scsi command */
static int tw_scsiop_test_unit_ready(TW_Device_Extension *tw_dev, int request_id)
{
TW_Param *param;
TW_Command *command_packet;
unsigned long command_que_value;
unsigned long param_value;
dprintk(KERN_NOTICE "3w-xxxx: tw_scsiop_test_unit_ready()\n");
/* Initialize command packet */
command_packet = (TW_Command *)tw_dev->command_packet_virtual_address[request_id];
if (command_packet == NULL) {
printk(KERN_WARNING "3w-xxxx: tw_scsiop_test_unit_ready(): Bad command packet virtual address.\n");
return 1;
}
memset(command_packet, 0, sizeof(TW_Sector));
command_packet->opcode__sgloffset = TW_OPSGL_IN(2, TW_OP_GET_PARAM);
command_packet->size = 4;
command_packet->request_id = request_id;
command_packet->status = 0;
command_packet->flags = 0;
command_packet->byte6.parameter_count = 1;
/* Now setup the param */
if (tw_dev->alignment_virtual_address[request_id] == NULL) {
printk(KERN_WARNING "3w-xxxx: tw_scsiop_test_unit_ready(): Bad alignment virtual address.\n");
return 1;
}
param = (TW_Param *)tw_dev->alignment_virtual_address[request_id];
memset(param, 0, sizeof(TW_Sector));
param->table_id = 3; /* unit summary table */
param->parameter_id = 3; /* unitsstatus parameter */
param->parameter_size_bytes = TW_MAX_UNITS;
param_value = tw_dev->alignment_physical_address[request_id];
if (param_value == 0) {
printk(KERN_WARNING "3w-xxxx: tw_scsiop_test_unit_ready(): Bad alignment physical address.\n");
return 1;
}
command_packet->byte8.param.sgl[0].address = param_value;
command_packet->byte8.param.sgl[0].length = sizeof(TW_Sector);
command_que_value = tw_dev->command_packet_physical_address[request_id];
if (command_que_value == 0) {
printk(KERN_WARNING "3w-xxxx: tw_scsiop_test_unit_ready(): Bad command packet physical address.\n");
return 1;
}
/* Now try to post the command packet */
tw_post_command_packet(tw_dev, request_id);
return 0;
} /* End tw_scsiop_test_unit_ready() */
/* This function is called by the isr to complete a testunitready command */
static int tw_scsiop_test_unit_ready_complete(TW_Device_Extension *tw_dev, int request_id)
{
unsigned char *is_unit_present;
TW_Param *param;
dprintk(KERN_WARNING "3w-xxxx: tw_scsiop_test_unit_ready_complete()\n");
param = (TW_Param *)tw_dev->alignment_virtual_address[request_id];
if (param == NULL) {
printk(KERN_WARNING "3w-xxxx: tw_scsiop_test_unit_ready_complete(): Bad alignment virtual address.\n");
return 1;
}
is_unit_present = &(param->data[0]);
if (is_unit_present[tw_dev->srb[request_id]->device->id] & TW_UNIT_ONLINE) {
tw_dev->is_unit_present[tw_dev->srb[request_id]->device->id] = 1;
} else {
tw_dev->is_unit_present[tw_dev->srb[request_id]->device->id] = 0;
tw_dev->srb[request_id]->result = (DID_BAD_TARGET << 16);
return TW_ISR_DONT_RESULT;
}
return 0;
} /* End tw_scsiop_test_unit_ready_complete() */
/* This is the main scsi queue function to handle scsi opcodes */
static int tw_scsi_queue_lck(struct scsi_cmnd *SCpnt, void (*done)(struct scsi_cmnd *))
{
unsigned char *command = SCpnt->cmnd;
int request_id = 0;
int retval = 1;
TW_Device_Extension *tw_dev = (TW_Device_Extension *)SCpnt->device->host->hostdata;
/* If we are resetting due to timed out ioctl, report as busy */
if (test_bit(TW_IN_RESET, &tw_dev->flags))
return SCSI_MLQUEUE_HOST_BUSY;
/* Save done function into Scsi_Cmnd struct */
SCpnt->scsi_done = done;
/* Queue the command and get a request id */
tw_state_request_start(tw_dev, &request_id);
/* Save the scsi command for use by the ISR */
tw_dev->srb[request_id] = SCpnt;
/* Initialize phase to zero */
SCpnt->SCp.phase = TW_PHASE_INITIAL;
switch (*command) {
case READ_10:
case READ_6:
case WRITE_10:
case WRITE_6:
dprintk(KERN_NOTICE "3w-xxxx: tw_scsi_queue(): caught READ/WRITE.\n");
retval = tw_scsiop_read_write(tw_dev, request_id);
break;
case TEST_UNIT_READY:
dprintk(KERN_NOTICE "3w-xxxx: tw_scsi_queue(): caught TEST_UNIT_READY.\n");
retval = tw_scsiop_test_unit_ready(tw_dev, request_id);
break;
case INQUIRY:
dprintk(KERN_NOTICE "3w-xxxx: tw_scsi_queue(): caught INQUIRY.\n");
retval = tw_scsiop_inquiry(tw_dev, request_id);
break;
case READ_CAPACITY:
dprintk(KERN_NOTICE "3w-xxxx: tw_scsi_queue(): caught READ_CAPACITY.\n");
retval = tw_scsiop_read_capacity(tw_dev, request_id);
break;
case REQUEST_SENSE:
dprintk(KERN_NOTICE "3w-xxxx: tw_scsi_queue(): caught REQUEST_SENSE.\n");
retval = tw_scsiop_request_sense(tw_dev, request_id);
break;
case MODE_SENSE:
dprintk(KERN_NOTICE "3w-xxxx: tw_scsi_queue(): caught MODE_SENSE.\n");
retval = tw_scsiop_mode_sense(tw_dev, request_id);
break;
case SYNCHRONIZE_CACHE:
dprintk(KERN_NOTICE "3w-xxxx: tw_scsi_queue(): caught SYNCHRONIZE_CACHE.\n");
retval = tw_scsiop_synchronize_cache(tw_dev, request_id);
break;
case TW_IOCTL:
printk(KERN_WARNING "3w-xxxx: SCSI_IOCTL_SEND_COMMAND deprecated, please update your 3ware tools.\n");
break;
default:
printk(KERN_NOTICE "3w-xxxx: scsi%d: Unknown scsi opcode: 0x%x\n", tw_dev->host->host_no, *command);
tw_dev->state[request_id] = TW_S_COMPLETED;
tw_state_request_finish(tw_dev, request_id);
SCpnt->result = (DID_BAD_TARGET << 16);
done(SCpnt);
retval = 0;
}
if (retval) {
tw_dev->state[request_id] = TW_S_COMPLETED;
tw_state_request_finish(tw_dev, request_id);
SCpnt->result = (DID_ERROR << 16);
done(SCpnt);
retval = 0;
}
return retval;
} /* End tw_scsi_queue() */
static DEF_SCSI_QCMD(tw_scsi_queue)
/* This function is the interrupt service routine */
static irqreturn_t tw_interrupt(int irq, void *dev_instance)
{
int request_id;
u32 status_reg_value;
TW_Device_Extension *tw_dev = (TW_Device_Extension *)dev_instance;
TW_Response_Queue response_que;
int error = 0, retval = 0;
TW_Command *command_packet;
int handled = 0;
/* Get the host lock for io completions */
spin_lock(tw_dev->host->host_lock);
/* Read the registers */
status_reg_value = inl(TW_STATUS_REG_ADDR(tw_dev));
/* Check if this is our interrupt, otherwise bail */
if (!(status_reg_value & TW_STATUS_VALID_INTERRUPT))
goto tw_interrupt_bail;
handled = 1;
/* If we are resetting, bail */
if (test_bit(TW_IN_RESET, &tw_dev->flags))
goto tw_interrupt_bail;
/* Check controller for errors */
if (tw_check_bits(status_reg_value)) {
dprintk(KERN_WARNING "3w-xxxx: tw_interrupt(): Unexpected bits.\n");
if (tw_decode_bits(tw_dev, status_reg_value, 1)) {
TW_CLEAR_ALL_INTERRUPTS(tw_dev);
goto tw_interrupt_bail;
}
}
/* Handle host interrupt */
if (status_reg_value & TW_STATUS_HOST_INTERRUPT) {
dprintk(KERN_NOTICE "3w-xxxx: tw_interrupt(): Received host interrupt.\n");
TW_CLEAR_HOST_INTERRUPT(tw_dev);
}
/* Handle attention interrupt */
if (status_reg_value & TW_STATUS_ATTENTION_INTERRUPT) {
dprintk(KERN_NOTICE "3w-xxxx: tw_interrupt(): Received attention interrupt.\n");
TW_CLEAR_ATTENTION_INTERRUPT(tw_dev);
tw_state_request_start(tw_dev, &request_id);
error = tw_aen_read_queue(tw_dev, request_id);
if (error) {
printk(KERN_WARNING "3w-xxxx: scsi%d: Error reading aen queue.\n", tw_dev->host->host_no);
tw_dev->state[request_id] = TW_S_COMPLETED;
tw_state_request_finish(tw_dev, request_id);
}
}
/* Handle command interrupt */
if (status_reg_value & TW_STATUS_COMMAND_INTERRUPT) {
/* Drain as many pending commands as we can */
while (tw_dev->pending_request_count > 0) {
request_id = tw_dev->pending_queue[tw_dev->pending_head];
if (tw_dev->state[request_id] != TW_S_PENDING) {
printk(KERN_WARNING "3w-xxxx: scsi%d: Found request id that wasn't pending.\n", tw_dev->host->host_no);
break;
}
if (tw_post_command_packet(tw_dev, request_id)==0) {
if (tw_dev->pending_head == TW_Q_LENGTH-1) {
tw_dev->pending_head = TW_Q_START;
} else {
tw_dev->pending_head = tw_dev->pending_head + 1;
}
tw_dev->pending_request_count--;
} else {
/* If we get here, we will continue re-posting on the next command interrupt */
break;
}
}
/* If there are no more pending requests, we mask command interrupt */
if (tw_dev->pending_request_count == 0)
TW_MASK_COMMAND_INTERRUPT(tw_dev);
}
/* Handle response interrupt */
if (status_reg_value & TW_STATUS_RESPONSE_INTERRUPT) {
/* Drain the response queue from the board */
while ((status_reg_value & TW_STATUS_RESPONSE_QUEUE_EMPTY) == 0) {
/* Read response queue register */
response_que.value = inl(TW_RESPONSE_QUEUE_REG_ADDR(tw_dev));
request_id = TW_RESID_OUT(response_que.response_id);
command_packet = (TW_Command *)tw_dev->command_packet_virtual_address[request_id];
error = 0;
/* Check for bad response */
if (command_packet->status != 0) {
/* If internal command, don't error, don't fill sense */
if (tw_dev->srb[request_id] == NULL) {
tw_decode_sense(tw_dev, request_id, 0);
} else {
error = tw_decode_sense(tw_dev, request_id, 1);
}
}
/* Check for correct state */
if (tw_dev->state[request_id] != TW_S_POSTED) {
if (tw_dev->srb[request_id] != NULL) {
printk(KERN_WARNING "3w-xxxx: scsi%d: Received a request id that wasn't posted.\n", tw_dev->host->host_no);
error = 1;
}
}
dprintk(KERN_NOTICE "3w-xxxx: tw_interrupt(): Response queue request id: %d.\n", request_id);
/* Check for internal command completion */
if (tw_dev->srb[request_id] == NULL) {
dprintk(KERN_WARNING "3w-xxxx: tw_interrupt(): Found internally posted command.\n");
/* Check for chrdev ioctl completion */
if (request_id != tw_dev->chrdev_request_id) {
retval = tw_aen_complete(tw_dev, request_id);
if (retval) {
printk(KERN_WARNING "3w-xxxx: scsi%d: Error completing aen.\n", tw_dev->host->host_no);
}
} else {
tw_dev->chrdev_request_id = TW_IOCTL_CHRDEV_FREE;
wake_up(&tw_dev->ioctl_wqueue);
}
} else {
switch (tw_dev->srb[request_id]->cmnd[0]) {
case READ_10:
case READ_6:
dprintk(KERN_NOTICE "3w-xxxx: tw_interrupt(): caught READ_10/READ_6\n");
break;
case WRITE_10:
case WRITE_6:
dprintk(KERN_NOTICE "3w-xxxx: tw_interrupt(): caught WRITE_10/WRITE_6\n");
break;
case TEST_UNIT_READY:
dprintk(KERN_NOTICE "3w-xxxx: tw_interrupt(): caught TEST_UNIT_READY\n");
error = tw_scsiop_test_unit_ready_complete(tw_dev, request_id);
break;
case INQUIRY:
dprintk(KERN_NOTICE "3w-xxxx: tw_interrupt(): caught INQUIRY\n");
error = tw_scsiop_inquiry_complete(tw_dev, request_id);
break;
case READ_CAPACITY:
dprintk(KERN_NOTICE "3w-xxxx: tw_interrupt(): caught READ_CAPACITY\n");
error = tw_scsiop_read_capacity_complete(tw_dev, request_id);
break;
case MODE_SENSE:
dprintk(KERN_NOTICE "3w-xxxx: tw_interrupt(): caught MODE_SENSE\n");
error = tw_scsiop_mode_sense_complete(tw_dev, request_id);
break;
case SYNCHRONIZE_CACHE:
dprintk(KERN_NOTICE "3w-xxxx: tw_interrupt(): caught SYNCHRONIZE_CACHE\n");
break;
default:
printk(KERN_WARNING "3w-xxxx: case slip in tw_interrupt()\n");
error = 1;
}
/* If no error command was a success */
if (error == 0) {
tw_dev->srb[request_id]->result = (DID_OK << 16);
}
/* If error, command failed */
if (error == 1) {
/* Ask for a host reset */
tw_dev->srb[request_id]->result = (DID_OK << 16) | (CHECK_CONDITION << 1);
}
/* Now complete the io */
if ((error != TW_ISR_DONT_COMPLETE)) {
tw_dev->state[request_id] = TW_S_COMPLETED;
tw_state_request_finish(tw_dev, request_id);
tw_dev->posted_request_count--;
tw_dev->srb[request_id]->scsi_done(tw_dev->srb[request_id]);
tw_unmap_scsi_data(tw_dev->tw_pci_dev, tw_dev->srb[request_id]);
}
}
/* Check for valid status after each drain */
status_reg_value = inl(TW_STATUS_REG_ADDR(tw_dev));
if (tw_check_bits(status_reg_value)) {
dprintk(KERN_WARNING "3w-xxxx: tw_interrupt(): Unexpected bits.\n");
if (tw_decode_bits(tw_dev, status_reg_value, 1)) {
TW_CLEAR_ALL_INTERRUPTS(tw_dev);
goto tw_interrupt_bail;
}
}
}
}
tw_interrupt_bail:
spin_unlock(tw_dev->host->host_lock);
return IRQ_RETVAL(handled);
} /* End tw_interrupt() */
/* This function tells the controller to shut down */
static void __tw_shutdown(TW_Device_Extension *tw_dev)
{
/* Disable interrupts */
TW_DISABLE_INTERRUPTS(tw_dev);
/* Free up the IRQ */
free_irq(tw_dev->tw_pci_dev->irq, tw_dev);
printk(KERN_WARNING "3w-xxxx: Shutting down host %d.\n", tw_dev->host->host_no);
/* Tell the card we are shutting down */
if (tw_initconnection(tw_dev, 1)) {
printk(KERN_WARNING "3w-xxxx: Connection shutdown failed.\n");
} else {
printk(KERN_WARNING "3w-xxxx: Shutdown complete.\n");
}
/* Clear all interrupts just before exit */
TW_ENABLE_AND_CLEAR_INTERRUPTS(tw_dev);
} /* End __tw_shutdown() */
/* Wrapper for __tw_shutdown */
static void tw_shutdown(struct pci_dev *pdev)
{
struct Scsi_Host *host = pci_get_drvdata(pdev);
TW_Device_Extension *tw_dev = (TW_Device_Extension *)host->hostdata;
__tw_shutdown(tw_dev);
} /* End tw_shutdown() */
/* This function gets called when a disk is coming online */
static int tw_slave_configure(struct scsi_device *sdev)
{
/* Force 60 second timeout */
blk_queue_rq_timeout(sdev->request_queue, 60 * HZ);
return 0;
} /* End tw_slave_configure() */
static struct scsi_host_template driver_template = {
.module = THIS_MODULE,
.name = "3ware Storage Controller",
.queuecommand = tw_scsi_queue,
.eh_host_reset_handler = tw_scsi_eh_reset,
.bios_param = tw_scsi_biosparam,
.change_queue_depth = tw_change_queue_depth,
.can_queue = TW_Q_LENGTH-2,
.slave_configure = tw_slave_configure,
.this_id = -1,
.sg_tablesize = TW_MAX_SGL_LENGTH,
.max_sectors = TW_MAX_SECTORS,
.cmd_per_lun = TW_MAX_CMDS_PER_LUN,
.use_clustering = ENABLE_CLUSTERING,
.shost_attrs = tw_host_attrs,
.emulated = 1
};
/* This function will probe and initialize a card */
static int __devinit tw_probe(struct pci_dev *pdev, const struct pci_device_id *dev_id)
{
struct Scsi_Host *host = NULL;
TW_Device_Extension *tw_dev;
int retval = -ENODEV;
retval = pci_enable_device(pdev);
if (retval) {
printk(KERN_WARNING "3w-xxxx: Failed to enable pci device.");
goto out_disable_device;
}
pci_set_master(pdev);
retval = pci_set_dma_mask(pdev, TW_DMA_MASK);
if (retval) {
printk(KERN_WARNING "3w-xxxx: Failed to set dma mask.");
goto out_disable_device;
}
host = scsi_host_alloc(&driver_template, sizeof(TW_Device_Extension));
if (!host) {
printk(KERN_WARNING "3w-xxxx: Failed to allocate memory for device extension.");
retval = -ENOMEM;
goto out_disable_device;
}
tw_dev = (TW_Device_Extension *)host->hostdata;
/* Save values to device extension */
tw_dev->host = host;
tw_dev->tw_pci_dev = pdev;
if (tw_initialize_device_extension(tw_dev)) {
printk(KERN_WARNING "3w-xxxx: Failed to initialize device extension.");
goto out_free_device_extension;
}
/* Request IO regions */
retval = pci_request_regions(pdev, "3w-xxxx");
if (retval) {
printk(KERN_WARNING "3w-xxxx: Failed to get mem region.");
goto out_free_device_extension;
}
/* Save base address */
tw_dev->base_addr = pci_resource_start(pdev, 0);
if (!tw_dev->base_addr) {
printk(KERN_WARNING "3w-xxxx: Failed to get io address.");
goto out_release_mem_region;
}
/* Disable interrupts on the card */
TW_DISABLE_INTERRUPTS(tw_dev);
/* Initialize the card */
if (tw_reset_sequence(tw_dev))
goto out_release_mem_region;
/* Set host specific parameters */
host->max_id = TW_MAX_UNITS;
host->max_cmd_len = TW_MAX_CDB_LEN;
/* Luns and channels aren't supported by adapter */
host->max_lun = 0;
host->max_channel = 0;
/* Register the card with the kernel SCSI layer */
retval = scsi_add_host(host, &pdev->dev);
if (retval) {
printk(KERN_WARNING "3w-xxxx: scsi add host failed");
goto out_release_mem_region;
}
pci_set_drvdata(pdev, host);
printk(KERN_WARNING "3w-xxxx: scsi%d: Found a 3ware Storage Controller at 0x%x, IRQ: %d.\n", host->host_no, tw_dev->base_addr, pdev->irq);
/* Now setup the interrupt handler */
retval = request_irq(pdev->irq, tw_interrupt, IRQF_SHARED, "3w-xxxx", tw_dev);
if (retval) {
printk(KERN_WARNING "3w-xxxx: Error requesting IRQ.");
goto out_remove_host;
}
tw_device_extension_list[tw_device_extension_count] = tw_dev;
tw_device_extension_count++;
/* Re-enable interrupts on the card */
TW_ENABLE_AND_CLEAR_INTERRUPTS(tw_dev);
/* Finally, scan the host */
scsi_scan_host(host);
if (twe_major == -1) {
if ((twe_major = register_chrdev (0, "twe", &tw_fops)) < 0)
printk(KERN_WARNING "3w-xxxx: Failed to register character device.");
}
return 0;
out_remove_host:
scsi_remove_host(host);
out_release_mem_region:
pci_release_regions(pdev);
out_free_device_extension:
tw_free_device_extension(tw_dev);
scsi_host_put(host);
out_disable_device:
pci_disable_device(pdev);
return retval;
} /* End tw_probe() */
/* This function is called to remove a device */
static void tw_remove(struct pci_dev *pdev)
{
struct Scsi_Host *host = pci_get_drvdata(pdev);
TW_Device_Extension *tw_dev = (TW_Device_Extension *)host->hostdata;
scsi_remove_host(tw_dev->host);
/* Unregister character device */
if (twe_major >= 0) {
unregister_chrdev(twe_major, "twe");
twe_major = -1;
}
/* Shutdown the card */
__tw_shutdown(tw_dev);
/* Free up the mem region */
pci_release_regions(pdev);
/* Free up device extension resources */
tw_free_device_extension(tw_dev);
scsi_host_put(tw_dev->host);
pci_disable_device(pdev);
tw_device_extension_count--;
} /* End tw_remove() */
/* PCI Devices supported by this driver */
static struct pci_device_id tw_pci_tbl[] __devinitdata = {
{ PCI_VENDOR_ID_3WARE, PCI_DEVICE_ID_3WARE_1000,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
{ PCI_VENDOR_ID_3WARE, PCI_DEVICE_ID_3WARE_7000,
PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0},
{ }
};
MODULE_DEVICE_TABLE(pci, tw_pci_tbl);
/* pci_driver initializer */
static struct pci_driver tw_driver = {
.name = "3w-xxxx",
.id_table = tw_pci_tbl,
.probe = tw_probe,
.remove = tw_remove,
.shutdown = tw_shutdown,
};
/* This function is called on driver initialization */
static int __init tw_init(void)
{
printk(KERN_WARNING "3ware Storage Controller device driver for Linux v%s.\n", TW_DRIVER_VERSION);
return pci_register_driver(&tw_driver);
} /* End tw_init() */
/* This function is called on driver exit */
static void __exit tw_exit(void)
{
pci_unregister_driver(&tw_driver);
} /* End tw_exit() */
module_init(tw_init);
module_exit(tw_exit);
| 34.889024 | 190 | 0.708367 | [
"geometry"
] |
7fee23b8d00045ce28301ba9728e68c6979cd701 | 25,806 | h | C | onnxruntime/core/providers/dml/OperatorAuthorHelper/MLOperatorAuthorHelper.h | codemzs/onnxruntime | c69194ec4c8c9674368113aa6044d0db708cd813 | [
"MIT"
] | 4 | 2019-06-06T23:48:57.000Z | 2021-06-03T11:51:45.000Z | onnxruntime/core/providers/dml/OperatorAuthorHelper/MLOperatorAuthorHelper.h | Montaer/onnxruntime | 6dc25a60f8b058a556964801d99d5508641dcf69 | [
"MIT"
] | null | null | null | onnxruntime/core/providers/dml/OperatorAuthorHelper/MLOperatorAuthorHelper.h | Montaer/onnxruntime | 6dc25a60f8b058a556964801d99d5508641dcf69 | [
"MIT"
] | 3 | 2019-05-07T01:29:04.000Z | 2020-08-09T08:36:12.000Z | // Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
#pragma once
#include "core/providers/dml/DmlExecutionProvider/inc/MLOperatorAuthor.h"
#include "MLOperatorAuthorPrivate.h"
#define ML_CHECK_BOOL(x) THROW_HR_IF(E_INVALIDARG, !(x))
class MLFloat16;
//
// Traits for numeric attribute types
//
template <typename T>
struct MLTypeTraits
{
};
template <>
struct MLTypeTraits<float>
{
static const MLOperatorAttributeType AttributeType = MLOperatorAttributeType::Float;
static const MLOperatorAttributeType AttributeVectorType = MLOperatorAttributeType::FloatArray;
static const MLOperatorTensorDataType TensorType = MLOperatorTensorDataType::Float;
};
template <>
struct MLTypeTraits<int32_t>
{
static const MLOperatorTensorDataType TensorType = MLOperatorTensorDataType::Int32;
};
template <>
struct MLTypeTraits<uint8_t>
{
static const MLOperatorTensorDataType TensorType = MLOperatorTensorDataType::UInt8;
};
template <>
struct MLTypeTraits<int8_t>
{
static const MLOperatorTensorDataType TensorType = MLOperatorTensorDataType::Int8;
};
template <>
struct MLTypeTraits<uint16_t>
{
static const MLOperatorTensorDataType TensorType = MLOperatorTensorDataType::UInt16;
};
template <>
struct MLTypeTraits<int16_t>
{
static const MLOperatorTensorDataType TensorType = MLOperatorTensorDataType::Int16;
};
template <>
struct MLTypeTraits<int64_t>
{
static const MLOperatorTensorDataType TensorType = MLOperatorTensorDataType::Int64;
static const MLOperatorAttributeType AttributeType = MLOperatorAttributeType::Int;
static const MLOperatorAttributeType AttributeVectorType = MLOperatorAttributeType::IntArray;
};
template <>
struct MLTypeTraits<bool>
{
static const MLOperatorTensorDataType TensorType = MLOperatorTensorDataType::Bool;
};
template <>
struct MLTypeTraits<double>
{
static const MLOperatorTensorDataType TensorType = MLOperatorTensorDataType::Double;
};
template <>
struct MLTypeTraits<uint32_t>
{
static const MLOperatorTensorDataType TensorType = MLOperatorTensorDataType::UInt32;
};
template <>
struct MLTypeTraits<uint64_t>
{
static const MLOperatorTensorDataType TensorType = MLOperatorTensorDataType::UInt64;
};
template <>
struct MLTypeTraits<MLFloat16>
{
static const MLOperatorTensorDataType TensorType = MLOperatorTensorDataType::Float16;
};
inline uint32_t ComputeElementCountFromDimensions(gsl::span<const uint32_t> dimensions)
{
return std::accumulate(dimensions.begin(), dimensions.end(), 1, std::multiplies<uint32_t>());
}
inline size_t GetByteSizeFromMlDataType(MLOperatorTensorDataType tensorDataType)
{
switch (tensorDataType)
{
case MLOperatorTensorDataType::Float: return 4;
case MLOperatorTensorDataType::UInt8: return 1;
case MLOperatorTensorDataType::Int8: return 1;
case MLOperatorTensorDataType::UInt16: return 2;
case MLOperatorTensorDataType::Int16: return 2;
case MLOperatorTensorDataType::Int32: return 4;
case MLOperatorTensorDataType::Int64: return 8;
case MLOperatorTensorDataType::String: THROW_HR(E_INVALIDARG);
case MLOperatorTensorDataType::Bool: return 1;
case MLOperatorTensorDataType::Float16: return 2;
case MLOperatorTensorDataType::Double: return 8;
case MLOperatorTensorDataType::UInt32: return 4;
case MLOperatorTensorDataType::UInt64: return 8;
case MLOperatorTensorDataType::Complex64: return 8;
case MLOperatorTensorDataType::Complex128: return 16;
case MLOperatorTensorDataType::Undefined:
default: THROW_HR(E_INVALIDARG);
};
}
using MLConstStringParam = const char*;
class MLOperatorKernelContext;
//
// Wrappers for ABI objects consumed by kernels.
// These wrappers provide typesafe methods which use STL types and convert
// return values to exceptions.
//
class MLOperatorTensorShapeDescription
{
public:
MLOperatorTensorShapeDescription(IMLOperatorTensorShapeDescription* impl) : m_impl(impl) {}
uint32_t GetInputTensorDimensionCount(uint32_t inputIndex) const
{
uint32_t ret;
THROW_IF_FAILED(m_impl->GetInputTensorDimensionCount(inputIndex, &ret));
return ret;
}
std::vector<uint32_t> GetInputTensorShape(uint32_t inputIndex) const
{
std::vector<uint32_t> ret;
uint32_t dimensionCount = GetInputTensorDimensionCount(inputIndex);
ret.resize(dimensionCount);
THROW_IF_FAILED(m_impl->GetInputTensorShape(inputIndex, dimensionCount, ret.data()));
return ret;
}
bool HasOutputShapeDescription() const noexcept
{
return m_impl->HasOutputShapeDescription();
}
uint32_t GetOutputTensorDimensionCount(uint32_t outputIndex) const
{
uint32_t ret;
THROW_IF_FAILED(m_impl->GetOutputTensorDimensionCount(outputIndex, &ret));
return ret;
}
std::vector<uint32_t> GetOutputTensorShape(uint32_t outputIndex) const
{
std::vector<uint32_t> ret;
uint32_t dimensionCount = GetOutputTensorDimensionCount(outputIndex);
ret.resize(dimensionCount);
THROW_IF_FAILED(m_impl->GetOutputTensorShape(outputIndex, dimensionCount, ret.data()));
return ret;
}
Microsoft::WRL::ComPtr<IMLOperatorTensorShapeDescription> GetInterface() const { return m_impl; }
protected:
Microsoft::WRL::ComPtr<IMLOperatorTensorShapeDescription> m_impl ;
};
class MLOperatorAttributes
{
public:
MLOperatorAttributes(IMLOperatorAttributes* impl) : m_impl(impl)
{
}
uint32_t GetAttributeElementCount(
_In_z_ MLConstStringParam name,
MLOperatorAttributeType type) const
{
uint32_t elementCount;
THROW_IF_FAILED(m_impl->GetAttributeElementCount(name, type, &elementCount));
return elementCount;
}
bool HasAttribute(_In_z_ MLConstStringParam name, MLOperatorAttributeType type) const noexcept
{
return GetAttributeElementCount(name, type) > 0;
}
//
// Templatized methods to query numeric attributes using MLTypeTraits
//
template <typename T>
T GetAttribute(_In_z_ MLConstStringParam name) const
{
T value;
THROW_IF_FAILED(m_impl->GetAttribute(
name,
MLTypeTraits<T>::AttributeType,
1,
sizeof(T),
&value));
return value;
}
template <typename T>
std::vector<T> GetAttributeVector(_In_z_ MLConstStringParam name) const
{
uint32_t count = GetAttributeElementCount(name, MLTypeTraits<T>::AttributeVectorType);
std::vector<T> values(count);
THROW_IF_FAILED(m_impl->GetAttribute(
name,
MLTypeTraits<T>::AttributeVectorType,
count,
sizeof(T),
values.data()));
return values;
}
std::string GetAttribute(_In_z_ MLConstStringParam name) const
{
return GetAttributeElement(name, 0);
}
std::vector<std::string> GetAttributeVector(_In_z_ MLConstStringParam name) const
{
uint32_t count = GetAttributeElementCount(name, MLOperatorAttributeType::StringArray);
std::vector<std::string> values;
values.resize(count);
for (uint32_t i = 0; i < count; ++i)
{
values[i] = GetAttributeElement(name, i);
}
return values;
}
std::string GetAttributeElement(_In_z_ MLConstStringParam name, uint32_t elementIndex) const
{
uint32_t length = 0;
THROW_IF_FAILED(m_impl->GetStringAttributeElementLength(name, elementIndex, &length));
// Construct a string by copying a character array. The copy can be removed with C++17
// using the non-const std::basic_string::data method.
std::vector<char> temp(length);
THROW_IF_FAILED(m_impl->GetStringAttributeElement(name, elementIndex, length, temp.data()));
std::string value(temp.data());
return value;
}
std::vector<int32_t> GetOptionalAttributeVectorInt32(MLConstStringParam attributeName) const
{
std::vector<int32_t> vector32Bit;
if (HasAttribute(attributeName, MLOperatorAttributeType::IntArray))
{
auto vector64Bit = GetAttributeVector<int64_t>(attributeName);
vector32Bit.resize(vector64Bit.size());
std::transform(vector64Bit.begin(), vector64Bit.end(), /*out*/vector32Bit.begin(), [](auto i)
{return gsl::narrow_cast<int32_t>(std::clamp<int64_t>(i, INT32_MIN, INT32_MAX)); });
}
return vector32Bit;
}
std::vector<std::string> GetOptionalStringAttributeVector(MLConstStringParam attributeName) const
{
return HasAttribute(attributeName, MLOperatorAttributeType::StringArray)
? GetAttributeVector(attributeName)
: std::vector<std::string>{}; // Empty vector if attribute absent.
}
// Not implemented
template <typename T> T GetOptionalAttribute(MLConstStringParam attributeName, T defaultValue) const;
template <>
int32_t GetOptionalAttribute<int32_t>(MLConstStringParam attributeName, int32_t defaultValue) const
{
return HasAttribute(attributeName, MLOperatorAttributeType::Int)
? gsl::narrow_cast<int32_t>(GetAttribute<int64_t>(attributeName))
: defaultValue;
}
template <>
uint32_t GetOptionalAttribute<uint32_t>(MLConstStringParam attributeName, uint32_t defaultValue) const
{
return HasAttribute(attributeName, MLOperatorAttributeType::Int)
? gsl::narrow_cast<uint32_t>(GetAttribute<int64_t>(attributeName))
: defaultValue;
}
template <>
int64_t GetOptionalAttribute<int64_t>(MLConstStringParam attributeName, int64_t defaultValue) const
{
return HasAttribute(attributeName, MLOperatorAttributeType::Int)
? GetAttribute<int64_t>(attributeName)
: defaultValue;
}
template <>
float GetOptionalAttribute<float>(MLConstStringParam attributeName, float defaultValue) const
{
return HasAttribute(attributeName, MLOperatorAttributeType::Float)
? GetAttribute<float>(attributeName)
: defaultValue;
}
template <>
std::vector<float> GetOptionalAttribute<std::vector<float>>(MLConstStringParam attributeName, std::vector<float> defaultValue) const
{
return HasAttribute(attributeName, MLOperatorAttributeType::FloatArray)
? GetAttributeVector<float>(attributeName)
: defaultValue;
}
template <>
bool GetOptionalAttribute<bool>(MLConstStringParam attributeName, bool defaultValue) const
{
return HasAttribute(attributeName, MLOperatorAttributeType::Int)
? gsl::narrow_cast<bool>(GetAttribute<int64_t>(attributeName))
: defaultValue;
}
template <>
std::string GetOptionalAttribute<std::string>(MLConstStringParam attributeName, std::string defaultValue) const
{
return HasAttribute(attributeName, MLOperatorAttributeType::String)
? GetAttribute(attributeName)
: defaultValue;
}
private:
Microsoft::WRL::ComPtr<IMLOperatorAttributes> m_impl;
};
class MLOperatorTensor
{
public:
MLOperatorTensor(IMLOperatorTensor* impl) : m_impl(impl) {}
// For cases of interop where the caller needs to pass the unwrapped class across a boundary.
Microsoft::WRL::ComPtr<IMLOperatorTensor> GetInterface() const noexcept
{
return m_impl;
}
// Need default constructor for usage in STL containers.
MLOperatorTensor() = default;
MLOperatorTensor(const MLOperatorTensor&) = default;
MLOperatorTensor(MLOperatorTensor&&) = default;
MLOperatorTensor& operator=(const MLOperatorTensor&) = default;
uint32_t GetDimensionCount() const
{
return m_impl->GetDimensionCount();
}
const std::vector<uint32_t>& GetShape() const
{
if (m_dimensionsCache.empty())
{
uint32_t dimensionCount = GetDimensionCount();
const_cast<MLOperatorTensor*>(this)->m_dimensionsCache.resize(dimensionCount);
THROW_IF_FAILED(m_impl->GetShape(dimensionCount, const_cast<MLOperatorTensor*>(this)->m_dimensionsCache.data()));
}
return m_dimensionsCache;
}
uint32_t GetTotalElementCount() const
{
return ComputeElementCountFromDimensions(GetShape());
}
size_t GetUnalignedTensorByteSize() const
{
return GetTotalElementCount() * GetByteSizeFromMlDataType(GetTensorDataType());
}
MLOperatorTensorDataType GetTensorDataType() const noexcept
{
return m_impl->GetTensorDataType();
}
bool IsCpuData() const noexcept
{
return m_impl->IsCpuData();
}
bool IsDataInterface() const noexcept
{
return m_impl->IsDataInterface();
}
// Return data as an explicitly typed array, verifying the requested type
// is the actual data type in the tensor.
template <typename T>
T* GetData()
{
ML_CHECK_BOOL(GetTensorDataType() == MLTypeTraits<T>::TensorType);
ML_CHECK_BOOL(!IsDataInterface());
return static_cast<T*>(m_impl->GetData());
}
template <typename T>
const T* GetData() const
{
ML_CHECK_BOOL(GetTensorDataType() == MLTypeTraits<T>::TensorType);
ML_CHECK_BOOL(!IsDataInterface());
return static_cast<const T*>(m_impl->GetData());
}
// Return as raw bytes, regardless of underlying type, which is useful when
// needing to agnostically copy memory.
const void* GetByteData() const
{
ML_CHECK_BOOL(!IsDataInterface());
return m_impl->GetData();
}
void* GetByteData()
{
ML_CHECK_BOOL(!IsDataInterface());
return m_impl->GetData();
}
Microsoft::WRL::ComPtr<IUnknown> GetDataInterface()
{
ML_CHECK_BOOL(IsDataInterface());
Microsoft::WRL::ComPtr<IUnknown> ret;
m_impl->GetDataInterface(&ret);
return ret;
}
private:
Microsoft::WRL::ComPtr<IMLOperatorTensor> m_impl;
std::vector<uint32_t> m_dimensionsCache;
};
class MLOperatorKernelCreationContext : public MLOperatorAttributes
{
public:
MLOperatorKernelCreationContext(IMLOperatorKernelCreationContext* impl) : m_impl(impl), MLOperatorAttributes(impl)
{
m_impl.As(&m_implPrivate);
}
// For cases of interop where the caller needs to pass the unwrapped class across a boundary.
Microsoft::WRL::ComPtr<IMLOperatorKernelCreationContext> GetInterface() const noexcept
{
return m_impl;
}
Microsoft::WRL::ComPtr<IUnknown> GetExecutionInterface() const noexcept
{
Microsoft::WRL::ComPtr<IUnknown> ret;
m_impl->GetExecutionInterface(&ret);
return ret;
}
uint32_t GetInputCount() const noexcept
{
return m_impl->GetInputCount();
}
uint32_t GetOutputCount() const noexcept
{
return m_impl->GetOutputCount();
}
bool IsInputValid(uint32_t index) const {
return m_impl->IsInputValid(index);
}
bool IsOutputValid(uint32_t index) const {
return m_impl->IsOutputValid(index);
}
MLOperatorEdgeDescription GetInputEdgeDescription(uint32_t inputIndex) const
{
MLOperatorEdgeDescription ret;
THROW_IF_FAILED(m_impl->GetInputEdgeDescription(inputIndex, &ret));
return ret;
}
MLOperatorEdgeDescription GetOutputEdgeDescription(uint32_t outputIndex) const
{
MLOperatorEdgeDescription ret = {};
THROW_IF_FAILED(m_impl->GetOutputEdgeDescription(outputIndex, &ret));
return ret;
}
bool HasTensorShapeDescription() const noexcept
{
return m_impl->HasTensorShapeDescription();
}
MLOperatorTensorShapeDescription GetTensorShapeDescription() const
{
Microsoft::WRL::ComPtr<IMLOperatorTensorShapeDescription> ret;
THROW_IF_FAILED(m_impl->GetTensorShapeDescription(&ret));
return MLOperatorTensorShapeDescription(ret.Get());
}
MLOperatorTensor GetConstantInputTensor(uint32_t inputIndex) const
{
Microsoft::WRL::ComPtr<IMLOperatorTensor> tensor;
THROW_IF_FAILED(m_implPrivate->GetConstantInputTensor(inputIndex, &tensor));
return MLOperatorTensor(tensor.Get());
}
private:
Microsoft::WRL::ComPtr<IMLOperatorKernelCreationContext> m_impl;
Microsoft::WRL::ComPtr<IMLOperatorKernelCreationContextPrivate> m_implPrivate;
};
class MLShapeInferenceContext : public MLOperatorAttributes
{
public:
MLShapeInferenceContext(IMLOperatorShapeInferenceContext* impl) : MLOperatorAttributes(impl)
{
THROW_IF_FAILED(impl->QueryInterface(m_impl.GetAddressOf()));
}
// For cases of interop where the caller needs to pass the unwrapped class across a boundary.
Microsoft::WRL::ComPtr<IMLOperatorShapeInferenceContextPrivate> GetInterface() const noexcept
{
return m_impl;
}
uint32_t GetInputCount() const noexcept
{
return m_impl->GetInputCount();
}
uint32_t GetOutputCount() const noexcept
{
return m_impl->GetOutputCount();
}
MLOperatorEdgeDescription GetInputEdgeDescription(uint32_t inputIndex) const
{
MLOperatorEdgeDescription ret;
THROW_IF_FAILED(m_impl->GetInputEdgeDescription(inputIndex, &ret));
return ret;
}
uint32_t GetInputTensorDimensionCount(uint32_t inputIndex) const
{
uint32_t ret;
THROW_IF_FAILED(m_impl->GetInputTensorDimensionCount(inputIndex, &ret));
return ret;
}
std::vector<uint32_t> GetInputTensorShape(uint32_t inputIndex) const
{
std::vector<uint32_t> ret;
uint32_t dimensionCount = GetInputTensorDimensionCount(inputIndex);
ret.resize(dimensionCount);
THROW_IF_FAILED(m_impl->GetInputTensorShape(inputIndex, dimensionCount, ret.data()));
return ret;
}
void SetOutputTensorShape(uint32_t outputIndex, const std::vector<uint32_t>& outputDimensions)
{
THROW_IF_FAILED(m_impl->SetOutputTensorShape(outputIndex, static_cast<uint32_t>(outputDimensions.size()), outputDimensions.data()));
}
MLOperatorTensor GetConstantInputTensor(uint32_t inputIndex) const
{
Microsoft::WRL::ComPtr<IMLOperatorTensor> tensor;
THROW_IF_FAILED(m_impl->GetConstantInputTensor(inputIndex, &tensor));
return MLOperatorTensor(tensor.Get());
}
private:
Microsoft::WRL::ComPtr<IMLOperatorShapeInferenceContextPrivate> m_impl;
};
class MLOperatorTypeInferenceContext : public MLOperatorAttributes
{
public:
MLOperatorTypeInferenceContext(IMLOperatorTypeInferenceContext* impl) : m_impl(impl), MLOperatorAttributes(impl) {}
// For cases of interop where the caller needs to pass the unwrapped class across a boundary.
Microsoft::WRL::ComPtr<IMLOperatorTypeInferenceContext> GetInterface() const noexcept
{
return m_impl;
}
uint32_t GetInputCount() const noexcept
{
return m_impl->GetInputCount();
}
uint32_t GetOutputCount() const noexcept
{
return m_impl->GetOutputCount();
}
MLOperatorEdgeDescription GetInputEdgeDescription(uint32_t inputIndex) const
{
MLOperatorEdgeDescription desc;
THROW_IF_FAILED(m_impl->GetInputEdgeDescription(inputIndex, &desc));
return desc;
}
void SetOutputEdgeDescription(uint32_t outputIndex, const MLOperatorEdgeDescription* edgeDesc) const
{
THROW_IF_FAILED(m_impl->SetOutputEdgeDescription(outputIndex, edgeDesc));
}
private:
Microsoft::WRL::ComPtr<IMLOperatorTypeInferenceContext> m_impl;
};
class MLOperatorKernelContext
{
public:
MLOperatorKernelContext(IMLOperatorKernelContext* impl) : m_impl(impl) {}
// Retrieve the underlying ABI compatible interface from the wrapper, for cases of interop
// between components or different DLLs where the caller needs to pass the unwrapped class
// across a boundary. e.g. Operator implementations may use the helper classes so that
// they can use exceptions without checking every return value, but then they need to pass
// results onward to a different component which expects the lower level currency.
Microsoft::WRL::ComPtr<IMLOperatorKernelContext> GetInterface() const noexcept
{
return m_impl;
}
MLOperatorTensor GetInputTensor(uint32_t inputIndex) const
{
Microsoft::WRL::ComPtr<IMLOperatorTensor> tensor;
THROW_IF_FAILED(m_impl->GetInputTensor(inputIndex, &tensor));
return tensor.Get();
}
MLOperatorTensor GetOutputTensor(uint32_t outputIndex) const
{
Microsoft::WRL::ComPtr<IMLOperatorTensor> tensor;
THROW_IF_FAILED(m_impl->GetOutputTensor(outputIndex, &tensor));
return tensor.Get();
}
MLOperatorTensor GetOutputTensor(uint32_t outputIndex, const std::vector<uint32_t> dimensionSizes) const
{
Microsoft::WRL::ComPtr<IMLOperatorTensor> tensor;
THROW_IF_FAILED(m_impl->GetOutputTensor(outputIndex, static_cast<uint32_t>(dimensionSizes.size()), dimensionSizes.data(), &tensor));
return tensor.Get();
}
Microsoft::WRL::ComPtr<IUnknown> AllocateTemporaryData(size_t size) const
{
Microsoft::WRL::ComPtr<IUnknown> ret;
THROW_IF_FAILED(m_impl->AllocateTemporaryData(size, &ret));
return ret;
}
Microsoft::WRL::ComPtr<IUnknown> GetExecutionInterface() const noexcept
{
Microsoft::WRL::ComPtr<IUnknown> ret;
m_impl->GetExecutionInterface(&ret);
return ret;
}
private:
Microsoft::WRL::ComPtr<IMLOperatorKernelContext> m_impl;
};
// Helper class for operator implementations, templatized by the
// implementation type. This class converts ABI types to wrappers,
// supports STL types, and converts exceptions to return values.
template <class T>
class MLOperatorKernel : public Microsoft::WRL::RuntimeClass<
Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::ClassicCom>, IMLOperatorKernel>,
public T
{
public:
static HRESULT STDMETHODCALLTYPE CreateInstance(IMLOperatorKernelCreationContext& info, IMLOperatorKernel** opKernel) noexcept try
{
Microsoft::WRL::ComPtr<MLOperatorKernel> kernel = wil::MakeOrThrow<MLOperatorKernel>(MLOperatorKernelCreationContext(&info));
*opKernel = kernel.Detach();
return S_OK;
}
CATCH_RETURN();
MLOperatorKernel(const MLOperatorKernelCreationContext& info) : T(info)
{
}
virtual ~MLOperatorKernel()
{
}
HRESULT STDMETHODCALLTYPE Compute(IMLOperatorKernelContext* context) noexcept override try
{
T::Compute(MLOperatorKernelContext(context));
return S_OK;
}
CATCH_RETURN();
using T::Compute;
};
using MLOperatorTypeInferenceFunction = void (CALLBACK*)(IMLOperatorTypeInferenceContext*);
using MLOperatorShapeInferenceFunction = void (CALLBACK*)(IMLOperatorShapeInferenceContext*);
using MLOperatorKernelCreateFn = void(CALLBACK*)(IMLOperatorKernelCreationContext*, IMLOperatorKernel**);
using MLOperatorSupportQueryFunction = void (CALLBACK*)(IMLOperatorSupportQueryContextPrivate*, bool*);
class MLOperatorShapeInferrer : public Microsoft::WRL::RuntimeClass<
Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::ClassicCom>, IMLOperatorShapeInferrer>
{
public:
MLOperatorShapeInferrer(MLOperatorShapeInferenceFunction shapeInferenceFn) :
m_shapeInferenceFn(shapeInferenceFn)
{}
HRESULT STDMETHODCALLTYPE InferOutputShapes(IMLOperatorShapeInferenceContext* context) noexcept override try
{
m_shapeInferenceFn(context);
return S_OK;
}
CATCH_RETURN();
private:
MLOperatorShapeInferenceFunction m_shapeInferenceFn = nullptr;
};
class MLOperatorSupportQuery : public Microsoft::WRL::RuntimeClass<
Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::ClassicCom>, IMLOperatorSupportQueryPrivate>
{
public:
MLOperatorSupportQuery(MLOperatorSupportQueryFunction queryFn) :
m_queryFn(queryFn)
{}
HRESULT STDMETHODCALLTYPE QuerySupport(
IMLOperatorSupportQueryContextPrivate* context,
BOOL* isSupported) noexcept override try
{
bool fIsSupported = false;
m_queryFn(context, &fIsSupported);
*isSupported = fIsSupported ? TRUE : FALSE;
return S_OK;
}
CATCH_RETURN();
private:
MLOperatorSupportQueryFunction m_queryFn = nullptr;
};
class MLOperatorTypeInferrer : public Microsoft::WRL::RuntimeClass<
Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::ClassicCom>, IMLOperatorTypeInferrer>
{
public:
MLOperatorTypeInferrer(MLOperatorTypeInferenceFunction typeInferenceFn) :
m_typeInferenceFn(typeInferenceFn)
{}
HRESULT STDMETHODCALLTYPE InferOutputTypes(IMLOperatorTypeInferenceContext* context) noexcept override try
{
m_typeInferenceFn(context);
return S_OK;
}
CATCH_RETURN();
private:
MLOperatorTypeInferenceFunction m_typeInferenceFn = nullptr;
};
class MLOperatorKernelFactory : public Microsoft::WRL::RuntimeClass<
Microsoft::WRL::RuntimeClassFlags<Microsoft::WRL::ClassicCom>, IMLOperatorKernelFactory>
{
public:
MLOperatorKernelFactory(MLOperatorKernelCreateFn createFn) :
m_createFn(createFn)
{}
HRESULT STDMETHODCALLTYPE CreateKernel(
IMLOperatorKernelCreationContext* context,
_COM_Outptr_ IMLOperatorKernel** kernel) noexcept override try
{
m_createFn(context, kernel);
return S_OK;
}
CATCH_RETURN();
private:
MLOperatorKernelCreateFn m_createFn = nullptr;
}; | 31.4324 | 140 | 0.712082 | [
"vector",
"transform"
] |
7feef782a19dfe632df7d330745c09518cca367e | 3,028 | h | C | AdskLogo/DbxEntity.h | MadhukarMoogala/adn_adskLogo | e491636f4e0ff29be5e10a0fd375277b48c6bb83 | [
"MIT"
] | 1 | 2021-07-20T01:13:28.000Z | 2021-07-20T01:13:28.000Z | AdskLogo/DbxEntity.h | MadhukarMoogala/adn_adskLogo | e491636f4e0ff29be5e10a0fd375277b48c6bb83 | [
"MIT"
] | null | null | null | AdskLogo/DbxEntity.h | MadhukarMoogala/adn_adskLogo | e491636f4e0ff29be5e10a0fd375277b48c6bb83 | [
"MIT"
] | 4 | 2019-03-21T13:33:36.000Z | 2020-06-14T03:43:03.000Z | //
//////////////////////////////////////////////////////////////////////////////
//
// Copyright 2018 Autodesk, Inc. All rights reserved.
//
// Use of this software is subject to the terms of the Autodesk license
// agreement provided at the time of installation or download, or which
// otherwise accompanies this software in either electronic or hard copy form.
//
//////////////////////////////////////////////////////////////////////////////
#ifndef ARXDBGDBENTITY_H
#define ARXDBGDBENTITY_H
#include "StdAfx.h"
/****************************************************************************
**
** CLASS ArxDbgDbEntity:
** base class for entities. Used as an example to show how to handle
** basic blockReference-type transformations and how to handle references
** to other entities. See ArxDbgDbAdeskLogo.cpp
** for examples of working derived classes.
**
** **jma
**
*************************************/
class ArxDbgDbEntity : public AcDbEntity {
public:
enum CloneRefType {
kNoClone = 0,
kClone = 1, // Clone reference along with this object
kFakeClone = 2, // Add to IdMap, but don't actually clone
};
ArxDbgDbEntity();
virtual ~ArxDbgDbEntity();
ACRX_DECLARE_MEMBERS(ArxDbgDbEntity);
AcGePoint3d location() const;
Acad::ErrorStatus setLocation(const AcGePoint3d& pt);
double rotation() const;
Acad::ErrorStatus setRotation(double rot);
AcGeVector3d normal() const;
Acad::ErrorStatus setNormal(const AcGeVector3d& nvec);
// overridden from AcDbEntity
virtual Acad::ErrorStatus dwgInFields(AcDbDwgFiler *filer);
virtual Acad::ErrorStatus dwgOutFields(AcDbDwgFiler *filer) const;
virtual Acad::ErrorStatus dxfInFields(AcDbDxfFiler *filer);
virtual Acad::ErrorStatus dxfOutFields(AcDbDxfFiler *filer) const;
virtual void getEcs(AcGeMatrix3d& retVal) const;
virtual Acad::ErrorStatus verifyReferences(int& fixedErrorCount, bool fullCheck);
protected:
virtual void getCloneReferences(AcDb::DeepCloneType type,
AcDbObjectIdArray& objIds,
AcDbIntArray& refTypes) const;
void printForListCmd(LPCTSTR label, LPCTSTR value) const;
virtual Acad::ErrorStatus subTransformBy(const AcGeMatrix3d& xform);
virtual Acad::ErrorStatus subGetGripPoints(AcGePoint3dArray& gripPoints,
AcDbIntArray& osnapModes,
AcDbIntArray& geomIds) const;
virtual Acad::ErrorStatus subMoveGripPointsAt(const AcDbIntArray& indices,
const AcGeVector3d& offset);
virtual void subList() const;
virtual Acad::ErrorStatus subDeepClone(AcDbObject* pOwner,
AcDbObject*& pClonedObject,
AcDbIdMapping& idMap,
Adesk::Boolean isPrimary) const;
virtual Acad::ErrorStatus subWblockClone(AcRxObject* pOwner,
AcDbObject*& pClone,
AcDbIdMapping& idMap,
Adesk::Boolean isPrimary) const;
private:
// data members
AcGePoint3d m_origin;
AcGeVector3d m_xDir;
AcGeVector3d m_zDir;
static Adesk::Int16 m_version;
// Dxf Codes
enum {
kDxfLocation = 10,
kDxfDirection = 15,
kDxfNormal = 210,
};
};
#endif // ARXDBGDBENTITY_H
| 26.103448 | 82 | 0.68395 | [
"object"
] |
7ff5735647efcf1f93f476fc1cd2eac810db606f | 7,964 | c | C | apps/plugins/test_mem.c | Rockbox-Chinese-Community/Rockbox-RCC | a701aefe45f03ca391a8e2f1a6e3da1b8774b2f2 | [
"BSD-3-Clause"
] | 24 | 2015-03-10T08:43:56.000Z | 2022-01-05T14:09:46.000Z | apps/plugins/test_mem.c | Rockbox-Chinese-Community/Rockbox-RCC | a701aefe45f03ca391a8e2f1a6e3da1b8774b2f2 | [
"BSD-3-Clause"
] | 4 | 2015-07-04T18:15:33.000Z | 2018-05-18T05:33:33.000Z | apps/plugins/test_mem.c | Rockbox-Chinese-Community/Rockbox-RCC | a701aefe45f03ca391a8e2f1a6e3da1b8774b2f2 | [
"BSD-3-Clause"
] | 15 | 2015-01-21T13:58:13.000Z | 2020-11-04T04:30:22.000Z | /***************************************************************************
* __________ __ ___.
* Open \______ \ ____ ____ | | _\_ |__ _______ ___
* Source | _// _ \_/ ___\| |/ /| __ \ / _ \ \/ /
* Jukebox | | ( <_> ) \___| < | \_\ ( <_> > < <
* Firmware |____|_ /\____/ \___ >__|_ \|___ /\____/__/\_ \
* \/ \/ \/ \/ \/
* $Id$
*
* Copyright (C) 2010 Thomas Martitz, Andree Buschmann
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This software is distributed on an "AS IS" basis, WITHOUT WARRANTY OF ANY
* KIND, either express or implied.
*
****************************************************************************/
#include "plugin.h"
#if PLUGIN_BUFFER_SIZE <= 0x8000
#define BUF_SIZE (1<<12) /* 16 KB = (1<<12)*sizeof(int) */
#else
#define BUF_SIZE (1<<13) /* 32 KB = (1<<13)*sizeof(int) */
#endif
#define LOOP_REPEAT_DRAM 256
static int loop_repeat_dram = LOOP_REPEAT_DRAM;
static volatile int buf_dram[BUF_SIZE] MEM_ALIGN_ATTR;
#if defined(PLUGIN_USE_IRAM)
#define LOOP_REPEAT_IRAM 256
static int loop_repeat_iram = LOOP_REPEAT_DRAM;
static volatile int buf_iram[BUF_SIZE] IBSS_ATTR MEM_ALIGN_ATTR;
#endif
/* (Byte per loop * loops)>>20 * ticks per s * 10 / ticks = dMB per s */
#define dMB_PER_SEC(buf_size, cnt, delta) ((((buf_size*sizeof(int)*cnt)>>20)*HZ*10)/delta)
static void memset_test(volatile int *buf, int buf_size, int loop_cnt)
{
size_t buf_bytes = buf_size*sizeof(buf[0]);
for(int i = 0; i < loop_cnt; i++)
{
memset((void*)buf, 0xff, buf_bytes);
}
}
static void memcpy_test(volatile int *buf, int buf_size, int loop_cnt)
{
/* half-size memcpy since memory regions must not overlap */
void* half_buf = (void*)(&buf[buf_size/2]);
size_t half_buf_bytes = buf_size * sizeof(buf[0]) / 2;
/* double loop count to compensate for half size memcpy */
for(int i = 0; i < loop_cnt*2; i++)
{
memcpy((void*)&buf[0], half_buf, half_buf_bytes);
}
}
static void write_test(volatile int *buf, int buf_size, int loop_cnt)
{
#if defined(CPU_ARM)
asm volatile (
"mov r0, #0 \n"
"mov r1, #1 \n"
"mov r2, #2 \n"
"mov r3, #3 \n"
"mov r6, %[loops] \n"
".outer_loop_read: \n"
"mov r4, %[buf_p] \n"
"mov r5, %[size] \n"
".inner_loop_read: \n"
"stmia r4!, {r0-r3} \n"
"stmia r4!, {r0-r3} \n"
"subs r5, r5, #8 \n"
"bgt .inner_loop_read \n"
"subs r6, r6, #1 \n"
"bgt .outer_loop_read \n"
:
: [loops] "r" (loop_cnt), [size] "r" (buf_size), [buf_p] "r" (buf)
: "r0", "r1", "r2", "r3", "r4", "r5", "r6", "memory", "cc"
);
#else
for(int i = 0; i < loop_cnt; i++)
{
for(int j = 0; j < buf_size; j+=4)
{
buf[j ] = j;
buf[j+1] = j+1;
buf[j+2] = j+2;
buf[j+3] = j+3;
}
}
#endif
}
static void read_test(volatile int *buf, int buf_size, int loop_cnt)
{
#if defined(CPU_ARM)
asm volatile (
"mov r6, %[loops] \n"
".outer_loop_write: \n"
"mov r4, %[buf_p] \n"
"mov r5, %[size] \n"
".inner_loop_write: \n"
"ldmia r4!, {r0-r3} \n"
"subs r5, r5, #8 \n"
"ldmia r4!, {r0-r3} \n"
"bgt .inner_loop_write \n"
"subs r6, r6, #1 \n"
"bgt .outer_loop_write \n"
:
: [loops] "r" (loop_cnt), [size] "r" (buf_size), [buf_p] "r" (buf)
: "r0", "r1", "r2", "r3", "r4", "r5", "r6", "memory", "cc"
);
#else
int x;
for(int i = 0; i < loop_cnt; i++)
{
for(int j = 0; j < buf_size; j+=4)
{
x = buf[j ];
x = buf[j+2];
x = buf[j+3];
x = buf[j+4];
}
}
(void)x;
#endif
}
enum test_type {
READ,
WRITE,
MEMSET,
MEMCPY,
};
static const char tests[][7] = {
[READ] = "read ",
[WRITE] = "write ",
[MEMSET] = "memset",
[MEMCPY] = "memcpy",
};
static int line;
#define TEST_MEM_PRINTF(...) rb->screens[0]->putsf(0, line++, __VA_ARGS__)
static int test(volatile int *buf, int buf_size, int loop_cnt,
enum test_type type)
{
int delta, dMB;
int last_tick = *rb->current_tick;
int ret = 0;
switch(type)
{
case READ: read_test(buf, buf_size, loop_cnt); break;
case WRITE: write_test(buf, buf_size, loop_cnt); break;
case MEMSET: memset_test(buf, buf_size, loop_cnt); break;
case MEMCPY: memcpy_test(buf, buf_size, loop_cnt); break;
}
delta = *rb->current_tick - last_tick;
if (delta <= 20)
{
/* The loop_cnt will be increased for the next measurement set until
* each measurement at least takes 10 ticks. This is to ensure a
* minimum accuracy. */
ret = 1;
}
delta = delta>0 ? delta : delta+1;
dMB = dMB_PER_SEC(buf_size, loop_cnt, delta);
TEST_MEM_PRINTF("%s: %3d.%d MB/s (%3d ms)",
tests[type], dMB/10, dMB%10, delta*10);
return ret;
}
enum plugin_status plugin_start(const void* parameter)
{
(void)parameter;
bool done = false;
#ifdef HAVE_ADJUSTABLE_CPU_FREQ
bool boost = false;
#endif
int count = 0;
#ifdef HAVE_LCD_BITMAP
rb->lcd_setfont(FONT_SYSFIXED);
#endif
rb->screens[0]->clear_display();
TEST_MEM_PRINTF("patience, may take some seconds...");
rb->screens[0]->update();
while (!done)
{
line = 0;
int ret;
rb->screens[0]->clear_display();
#ifdef HAVE_ADJUSTABLE_CPU_FREQ
TEST_MEM_PRINTF("%s", boost?"boosted":"unboosted");
TEST_MEM_PRINTF("clock: %3d.%d MHz", (*rb->cpu_frequency)/1000000, (*rb->cpu_frequency)%1000000);
#endif
TEST_MEM_PRINTF("loop#: %d", ++count);
TEST_MEM_PRINTF("DRAM cnt: %d size: %d MB", loop_repeat_dram,
(loop_repeat_dram*BUF_SIZE*sizeof(buf_dram[0]))>>20);
ret = 0;
ret |= test(buf_dram, BUF_SIZE, loop_repeat_dram, READ);
ret |= test(buf_dram, BUF_SIZE, loop_repeat_dram, WRITE);
ret |= test(buf_dram, BUF_SIZE, loop_repeat_dram, MEMSET);
ret |= test(buf_dram, BUF_SIZE, loop_repeat_dram, MEMCPY);
if (ret != 0) loop_repeat_dram *= 2;
#if defined(PLUGIN_USE_IRAM)
TEST_MEM_PRINTF("IRAM cnt: %d size: %d MB", loop_repeat_iram,
(loop_repeat_iram*BUF_SIZE*sizeof(buf_iram[0]))>>20);
ret = 0;
ret |= test(buf_iram, BUF_SIZE, loop_repeat_iram, READ);
ret |= test(buf_iram, BUF_SIZE, loop_repeat_iram, WRITE);
ret |= test(buf_iram, BUF_SIZE, loop_repeat_iram, MEMSET);
ret |= test(buf_iram, BUF_SIZE, loop_repeat_iram, MEMCPY);
if (ret != 0) loop_repeat_iram *= 2;
#endif
rb->screens[0]->update();
switch (rb->get_action(CONTEXT_STD, HZ/5))
{
#ifdef HAVE_ADJUSTABLE_CPU_FREQ
case ACTION_STD_PREV:
if (!boost)
{
rb->cpu_boost(true);
boost = true;
}
break;
case ACTION_STD_NEXT:
if (boost)
{
rb->cpu_boost(false);
boost = false;
}
break;
#endif
case ACTION_STD_CANCEL:
done = true;
break;
}
}
return PLUGIN_OK;
}
| 30.05283 | 105 | 0.518332 | [
"3d"
] |
7ff67a147c71996cb5e2e423a3226b7ff809d045 | 17,662 | h | C | Marlin/src/lcd/language/language_jp-kana.h | s3abrz/s3abrz_FLSUN-Kossel-Mini-skr-v1.3 | dddee88d748162ed48fd9dd5351ce8953746325f | [
"MIT"
] | 1 | 2019-07-25T16:09:15.000Z | 2019-07-25T16:09:15.000Z | Marlin/src/lcd/language/language_jp-kana.h | s3abrz/s3abrz_FLSUN-Kossel-Mini-skr-v1.3 | dddee88d748162ed48fd9dd5351ce8953746325f | [
"MIT"
] | null | null | null | Marlin/src/lcd/language/language_jp-kana.h | s3abrz/s3abrz_FLSUN-Kossel-Mini-skr-v1.3 | dddee88d748162ed48fd9dd5351ce8953746325f | [
"MIT"
] | null | null | null | /**
* Marlin 3D Printer Firmware
* Copyright (C) 2019 MarlinFirmware [https://github.com/MarlinFirmware/Marlin]
*
* Based on Sprinter and grbl.
* Copyright (C) 2011 Camiel Gubbels / Erik van der Zalm
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
#pragma once
/**
* Japanese (Kana)
* UTF-8 for Graphical Display
*
* LCD Menu Messages
* See also http://marlinfw.org/docs/development/lcd_language.html
*
*/
#define DISPLAY_CHARSET_ISO10646_KANA
#define CHARSIZE 3
// This just to show the potential benefit of unicode.
// This translation can be improved by using the full charset of unicode codeblock U+30A0 to U+30FF.
// 片仮名表示定義
#define WELCOME_MSG MACHINE_NAME _UxGT(" ready.")
#define MSG_SD_INSERTED _UxGT("カードガソウニュウサレマシタ") // "Card inserted"
#define MSG_SD_REMOVED _UxGT("カードガアリマセン") // "Card removed"
#define MSG_LCD_ENDSTOPS _UxGT("エンドストップ") // "Endstops" // Max length 8 characters
#define MSG_MAIN _UxGT("メイン") // "Main"
#define MSG_AUTOSTART _UxGT("ジドウカイシ") // "Autostart"
#define MSG_DISABLE_STEPPERS _UxGT("モーターデンゲン オフ") // "Disable steppers"
#define MSG_DEBUG_MENU _UxGT("デバッグメニュー") // "Debug Menu"
#define MSG_PROGRESS_BAR_TEST _UxGT("プログレスバー テスト") // "Progress Bar Test"
#define MSG_AUTO_HOME _UxGT("ゲンテンフッキ") // "Auto home"
#define MSG_AUTO_HOME_X _UxGT("Xジク ゲンテンフッキ") // "Home X"
#define MSG_AUTO_HOME_Y _UxGT("Yジク ゲンテンフッキ") // "Home Y"
#define MSG_AUTO_HOME_Z _UxGT("Zジク ゲンテンフッキ") // "Home Z"
#define MSG_LEVEL_BED_HOMING _UxGT("ゲンテンフッキチュウ") // "Homing XYZ"
#define MSG_LEVEL_BED_WAITING _UxGT("レベリングカイシ") // "Click to Begin"
#define MSG_LEVEL_BED_NEXT_POINT _UxGT("ツギノソクテイテンヘ") // "Next Point"
#define MSG_LEVEL_BED_DONE _UxGT("レベリングカンリョウ") // "Leveling Done!"
#define MSG_SET_HOME_OFFSETS _UxGT("キジュンオフセットセッテイ") // "Set home offsets"
#define MSG_HOME_OFFSETS_APPLIED _UxGT("オフセットガテキヨウサレマシタ") // "Offsets applied"
#define MSG_SET_ORIGIN _UxGT("キジュンセット") // "Set origin"
#define MSG_PREHEAT_1 _UxGT(PREHEAT_1_LABEL " ヨネツ") // "Preheat " PREHEAT_1_LABEL
#define MSG_PREHEAT_1_N MSG_PREHEAT_1 _UxGT(" ")
#define MSG_PREHEAT_1_ALL _UxGT(PREHEAT_1_LABEL " スベテヨネツ") // " All"
#define MSG_PREHEAT_1_BEDONLY _UxGT(PREHEAT_1_LABEL " ベッドヨネツ") // " Bed"
#define MSG_PREHEAT_1_SETTINGS MSG_PREHEAT_1 _UxGT("セッテイ") // " conf"
#define MSG_PREHEAT_2 _UxGT(PREHEAT_2_LABEL " ヨネツ") // "Preheat " PREHEAT_2_LABEL
#define MSG_PREHEAT_2_N MSG_PREHEAT_2 _UxGT(" ")
#define MSG_PREHEAT_2_ALL _UxGT(PREHEAT_2_LABEL " スベテヨネツ") // " All"
#define MSG_PREHEAT_2_BEDONLY _UxGT(PREHEAT_2_LABEL " ベッドヨネツ") // " Bed"
#define MSG_PREHEAT_2_SETTINGS MSG_PREHEAT_2 _UxGT("セッテイ") // " conf"
#define MSG_COOLDOWN _UxGT("カネツテイシ") // "Cooldown"
#define MSG_SWITCH_PS_ON _UxGT("デンゲン オン") // "Switch power on"
#define MSG_SWITCH_PS_OFF _UxGT("デンゲン オフ") // "Switch power off"
#define MSG_EXTRUDE _UxGT("オシダシ") // "Extrude"
#define MSG_RETRACT _UxGT("ヒキコミセッテイ") // "Retract"
#define MSG_MOVE_AXIS _UxGT("ジクイドウ") // "Move axis"
#define MSG_BED_LEVELING _UxGT("ベッドレベリング") // "Bed leveling"
#define MSG_LEVEL_BED _UxGT("ベッドレベリング") // "Level bed"
#define MSG_MOVING _UxGT("イドウチュウ") // "Moving..."
#define MSG_FREE_XY _UxGT("XYジク カイホウ") // "Free XY"
#define MSG_MOVE_X _UxGT("Xジク イドウ") // "Move X"
#define MSG_MOVE_Y _UxGT("Yジク イドウ") // "Move Y"
#define MSG_MOVE_Z _UxGT("Zジク イドウ") // "Move Z"
#define MSG_MOVE_E _UxGT("エクストルーダー") // "Extruder"
#define MSG_MOVE_01MM _UxGT("0.1mm イドウ") // "Move 0.1mm"
#define MSG_MOVE_1MM _UxGT(" 1mm イドウ") // "Move 1mm"
#define MSG_MOVE_10MM _UxGT(" 10mm イドウ") // "Move 10mm"
#define MSG_SPEED _UxGT("ソクド") // "Speed"
#define MSG_BED_Z _UxGT("Zオフセット") // "Bed Z"
#define MSG_NOZZLE _UxGT("ノズル") // "Nozzle"
#define MSG_BED _UxGT("ベッド") // "Bed"
#define MSG_FAN_SPEED _UxGT("ファンソクド") // "Fan speed"
#define MSG_FLOW _UxGT("トシュツリョウ") // "Flow"
#define MSG_CONTROL _UxGT("セイギョ") // "Control"
#define MSG_MIN _UxGT(" ") LCD_STR_THERMOMETER _UxGT(" サイテイ") // " Min"
#define MSG_MAX _UxGT(" ") LCD_STR_THERMOMETER _UxGT(" サイコウ") // " Max"
#define MSG_FACTOR _UxGT(" ") LCD_STR_THERMOMETER _UxGT(" ファクター") // " Fact"
#define MSG_AUTOTEMP _UxGT("ジドウオンドセイギョ") // "Autotemp"
#define MSG_LCD_ON _UxGT("オン") // "On"
#define MSG_LCD_OFF _UxGT("オフ") // "Off"
#define MSG_PID_P _UxGT("PID-P")
#define MSG_PID_I _UxGT("PID-I")
#define MSG_PID_D _UxGT("PID-D")
#define MSG_PID_C _UxGT("PID-C")
#define MSG_SELECT _UxGT("センタク") // "Select"
#define MSG_ACC _UxGT("カソクド mm/s2") // "Accel"
#define MSG_JERK _UxGT("ヤクド mm/s") // "Jerk"
#if IS_KINEMATIC
#define MSG_VA_JERK _UxGT("Aジク ヤクド mm/s") // "Va-jerk"
#define MSG_VB_JERK _UxGT("Bジク ヤクド mm/s") // "Vb-jerk"
#define MSG_VC_JERK _UxGT("Cジク ヤクド mm/s") // "Vc-jerk"
#else
#define MSG_VA_JERK _UxGT("Xジク ヤクド mm/s") // "Vx-jerk"
#define MSG_VB_JERK _UxGT("Yジク ヤクド mm/s") // "Vy-jerk"
#define MSG_VC_JERK _UxGT("Zジク ヤクド mm/s") // "Vz-jerk"
#endif
#define MSG_VE_JERK _UxGT("エクストルーダー ヤクド") // "Ve-jerk"
#define MSG_VMAX _UxGT("サイダイオクリソクド ") // "Vmax "
#define MSG_VMIN _UxGT("サイショウオクリソクド") // "Vmin"
#define MSG_VTRAV_MIN _UxGT("サイショウイドウソクド") // "VTrav min"
#define MSG_ACCELERATION MSG_ACC
#define MSG_AMAX _UxGT("サイダイカソクド ") // "Amax "
#define MSG_A_RETRACT _UxGT("ヒキコミカソクド") // "A-retract"
#define MSG_A_TRAVEL _UxGT("イドウカソクド") // "A-travel"
#define MSG_TEMPERATURE _UxGT("オンド") // "Temperature"
#define MSG_MOTION _UxGT("ウゴキセッテイ") // "Motion"
#define MSG_FILAMENT _UxGT("フィラメント") // "Filament"
#define MSG_VOLUMETRIC_ENABLED _UxGT("E in mm3")
#define MSG_FILAMENT_DIAM _UxGT("フィラメントチョッケイ") // "Fil. Dia."
#define MSG_CONTRAST _UxGT("LCDコントラスト") // "LCD contrast"
#define MSG_STORE_EEPROM _UxGT("メモリヘカクノウ") // "Store memory"
#define MSG_LOAD_EEPROM _UxGT("メモリカラヨミコミ") // "Load memory"
#define MSG_RESTORE_FAILSAFE _UxGT("セッテイリセット") // "Restore failsafe"
#define MSG_REFRESH _UxGT("リフレッシュ") // "Refresh"
#define MSG_WATCH _UxGT("ジョウホウガメン") // "Info screen"
#define MSG_PREPARE _UxGT("ジュンビセッテイ") // "Prepare"
#define MSG_TUNE _UxGT("チョウセイ") // "Tune"
#define MSG_PAUSE_PRINT _UxGT("イチジテイシ") // "Pause print"
#define MSG_RESUME_PRINT _UxGT("プリントサイカイ") // "Resume print"
#define MSG_STOP_PRINT _UxGT("プリントテイシ") // "Stop print"
#define MSG_CARD_MENU _UxGT("SDカードカラプリント") // "Print from SD"
#define MSG_NO_CARD _UxGT("SDカードガアリマセン") // "No SD card"
#define MSG_DWELL _UxGT("キュウシ") // "Sleep..."
#define MSG_USERWAIT _UxGT("シバラクオマチクダサイ") // "Wait for user..."
#define MSG_PRINT_ABORTED _UxGT("プリントガチュウシサレマシタ") // "Print aborted"
#define MSG_NO_MOVE _UxGT("ウゴキマセン") // "No move."
#define MSG_KILLED _UxGT("ヒジョウテイシ") // "KILLED. "
#define MSG_STOPPED _UxGT("テイシシマシタ") // "STOPPED. "
#define MSG_CONTROL_RETRACT _UxGT("ヒキコミリョウ mm") // "Retract mm"
#define MSG_CONTROL_RETRACT_SWAP _UxGT("ヒキコミリョウS mm") // "Swap Re.mm"
#define MSG_CONTROL_RETRACTF _UxGT("ヒキコミソクド mm/s") // "Retract V"
#define MSG_CONTROL_RETRACT_ZHOP _UxGT("ノズルタイヒ mm") // "Hop mm"
#define MSG_CONTROL_RETRACT_RECOVER _UxGT("ホショウリョウ mm") // "UnRet mm"
#define MSG_CONTROL_RETRACT_RECOVER_SWAP _UxGT("ホショウリョウS mm") // "S UnRet mm"
#define MSG_CONTROL_RETRACT_RECOVERF _UxGT("ホショウソクド mm/s") // "UnRet V"
#define MSG_AUTORETRACT _UxGT("ジドウヒキコミ") // "AutoRetr."
#define MSG_FILAMENTCHANGE _UxGT("フィラメントコウカン") // "Change filament"
#define MSG_INIT_SDCARD _UxGT("SDカードサイヨミコミ") // "Init. SD card"
#define MSG_CHANGE_SDCARD _UxGT("SDカードコウカン") // "Change SD card"
#define MSG_ZPROBE_OUT _UxGT("Zプローブ ベッドガイ") // "Z probe out. bed"
#define MSG_BLTOUCH_SELFTEST _UxGT("BLTouch ジコシンダン") // "BLTouch Self-Test"
#define MSG_BLTOUCH_RESET _UxGT("BLTouch リセット") // "Reset BLTouch"
#define MSG_HOME _UxGT("サキニ") // "Home" // Used as MSG_HOME " " MSG_X MSG_Y MSG_Z " " MSG_FIRST
#define MSG_FIRST _UxGT("ヲフッキサセテクダサイ") // "first"
#define MSG_ZPROBE_ZOFFSET _UxGT("Zオフセット") // "Z Offset"
#define MSG_BABYSTEP_X _UxGT("Xジク ビドウ") // "Babystep X"
#define MSG_BABYSTEP_Y _UxGT("Yジク ビドウ") // "Babystep Y"
#define MSG_BABYSTEP_Z _UxGT("Zジク ビドウ") // "Babystep Z"
#define MSG_ENDSTOP_ABORT _UxGT("イドウゲンカイケンチキノウ") // "Endstop abort"
#define MSG_HEATING_FAILED_LCD _UxGT("カネツシッパイ") // "Heating failed"
#define MSG_ERR_REDUNDANT_TEMP _UxGT("エラー:ジョウチョウサーミスターキノウ") // "Err: REDUNDANT TEMP"
#define MSG_THERMAL_RUNAWAY _UxGT("ネツボウソウ") // "THERMAL RUNAWAY"
#define MSG_ERR_MAXTEMP _UxGT("エラー:サイコウオンチョウカ") // "Err: MAXTEMP"
#define MSG_ERR_MINTEMP _UxGT("エラー:サイテイオンミマン") // "Err: MINTEMP"
#define MSG_ERR_MAXTEMP_BED _UxGT("エラー:ベッド サイコウオンチョウカ") // "Err: MAXTEMP BED"
#define MSG_ERR_MINTEMP_BED _UxGT("エラー:ベッド サイテイオンミマン") // "Err: MINTEMP BED"
#define MSG_ERR_Z_HOMING MSG_HOME _UxGT(" ") MSG_X MSG_Y _UxGT(" ") MSG_FIRST // "Home XY first"
#define MSG_HALTED _UxGT("プリンターハテイシシマシタ") // "PRINTER HALTED"
#define MSG_PLEASE_RESET _UxGT("リセットシテクダサイ") // "Please reset"
#define MSG_SHORT_DAY _UxGT("d") // One character only
#define MSG_SHORT_HOUR _UxGT("h") // One character only
#define MSG_SHORT_MINUTE _UxGT("m") // One character only
#define MSG_HEATING _UxGT("カネツチュウ") // "Heating..."
#define MSG_BED_HEATING _UxGT("ベッド カネツチュウ") // "Bed Heating..."
#define MSG_DELTA_CALIBRATE _UxGT("デルタ コウセイ") // "Delta Calibration"
#define MSG_DELTA_CALIBRATE_X _UxGT("Xジク コウセイ") // "Calibrate X"
#define MSG_DELTA_CALIBRATE_Y _UxGT("Yジク コウセイ") // "Calibrate Y"
#define MSG_DELTA_CALIBRATE_Z _UxGT("Zジク コウセイ") // "Calibrate Z"
#define MSG_DELTA_CALIBRATE_CENTER _UxGT("チュウシン コウセイ") // "Calibrate Center"
#define MSG_INFO_MENU _UxGT("コノプリンターニツイテ") // "About Printer"
#define MSG_INFO_PRINTER_MENU _UxGT("プリンタージョウホウ") // "Printer Info"
#define MSG_INFO_STATS_MENU _UxGT("プリントジョウキョウ") // "Printer Stats"
#define MSG_INFO_BOARD_MENU _UxGT("セイギョケイジョウホウ") // "Board Info"
#define MSG_INFO_THERMISTOR_MENU _UxGT("サーミスター") // "Thermistors"
#define MSG_INFO_EXTRUDERS _UxGT("エクストルーダースウ") // "Extruders"
#define MSG_INFO_BAUDRATE _UxGT("ボーレート") // "Baud"
#define MSG_INFO_PROTOCOL _UxGT("プロトコル") // "Protocol"
#define MSG_CASE_LIGHT _UxGT("キョウタイナイショウメイ") // "Case light"
#define MSG_INFO_PRINT_COUNT _UxGT("プリントスウ ") // "Print Count"
#define MSG_INFO_COMPLETED_PRINTS _UxGT("カンリョウスウ") // "Completed"
#define MSG_INFO_PRINT_TIME _UxGT("プリントジカンルイケイ") // "Total print time"
#define MSG_INFO_PRINT_LONGEST _UxGT("サイチョウプリントジカン") // "Longest job time"
#define MSG_INFO_PRINT_FILAMENT _UxGT("フィラメントシヨウリョウルイケイ") // "Extruded total"
#define MSG_INFO_MIN_TEMP _UxGT("セッテイサイテイオン") // "Min Temp"
#define MSG_INFO_MAX_TEMP _UxGT("セッテイサイコウオン") // "Max Temp"
#define MSG_INFO_PSU _UxGT("デンゲンシュベツ") // "Power Supply"
#define MSG_DRIVE_STRENGTH _UxGT("モータークドウリョク") // "Drive Strength"
#define MSG_DAC_PERCENT _UxGT("DACシュツリョク %") // "Driver %"
#define MSG_DAC_EEPROM_WRITE MSG_STORE_EEPROM // "DAC EEPROM Write"
#define MSG_FILAMENT_CHANGE_OPTION_RESUME _UxGT("プリントサイカイ") // "Resume print"
#define MSG_FILAMENT_CHANGE_INIT_1 _UxGT("コウカンヲカイシシマス") // "Wait for start"
#define MSG_FILAMENT_CHANGE_INIT_2 _UxGT("シバラクオマチクダサイ") // "of the filament"
#define MSG_FILAMENT_CHANGE_UNLOAD_1 _UxGT("フィラメントヌキダシチュウ") // "Wait for"
#define MSG_FILAMENT_CHANGE_UNLOAD_2 _UxGT("シバラクオマチクダサイ") // "filament unload"
#define MSG_FILAMENT_CHANGE_INSERT_1 _UxGT("フィラメントヲソウニュウシ,") // "Insert filament"
#define MSG_FILAMENT_CHANGE_INSERT_2 _UxGT("クリックスルトゾッコウシマス") // "and press button"
#define MSG_FILAMENT_CHANGE_LOAD_1 _UxGT("フィラメントソウテンチュウ") // "Wait for"
#define MSG_FILAMENT_CHANGE_LOAD_2 _UxGT("シバラクオマチクダサイ") // "filament load"
#define MSG_FILAMENT_CHANGE_RESUME_1 _UxGT("プリントヲサイカイシマス") // "Wait for print"
#define MSG_FILAMENT_CHANGE_RESUME_2 _UxGT("シバラクオマチクダサイ") // "to resume"
| 79.918552 | 143 | 0.503793 | [
"3d"
] |
7ff828e0f38d4c4956964df86843f48511b3b833 | 56,316 | h | C | clang/include/clang/Basic/TargetInfo.h | jazgarewal/llvm-project | f8fb30933d1804a47241a61289ab04a995eabbe7 | [
"Apache-2.0"
] | null | null | null | clang/include/clang/Basic/TargetInfo.h | jazgarewal/llvm-project | f8fb30933d1804a47241a61289ab04a995eabbe7 | [
"Apache-2.0"
] | null | null | null | clang/include/clang/Basic/TargetInfo.h | jazgarewal/llvm-project | f8fb30933d1804a47241a61289ab04a995eabbe7 | [
"Apache-2.0"
] | null | null | null | //===--- TargetInfo.h - Expose information about the target -----*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
///
/// \file
/// Defines the clang::TargetInfo interface.
///
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_BASIC_TARGETINFO_H
#define LLVM_CLANG_BASIC_TARGETINFO_H
#include "clang/Basic/AddressSpaces.h"
#include "clang/Basic/CodeGenOptions.h"
#include "clang/Basic/LLVM.h"
#include "clang/Basic/LangOptions.h"
#include "clang/Basic/Specifiers.h"
#include "clang/Basic/TargetCXXABI.h"
#include "clang/Basic/TargetOptions.h"
#include "llvm/ADT/APFloat.h"
#include "llvm/ADT/APInt.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/IntrusiveRefCntPtr.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/StringMap.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/Triple.h"
#include "llvm/Frontend/OpenMP/OMPGridValues.h"
#include "llvm/Support/DataTypes.h"
#include "llvm/Support/VersionTuple.h"
#include <cassert>
#include <string>
#include <vector>
namespace llvm {
struct fltSemantics;
class DataLayout;
}
namespace clang {
class DiagnosticsEngine;
class LangOptions;
class CodeGenOptions;
class MacroBuilder;
class QualType;
class SourceLocation;
class SourceManager;
namespace Builtin { struct Info; }
/// Fields controlling how types are laid out in memory; these may need to
/// be copied for targets like AMDGPU that base their ABIs on an auxiliary
/// CPU target.
struct TransferrableTargetInfo {
unsigned char PointerWidth, PointerAlign;
unsigned char BoolWidth, BoolAlign;
unsigned char IntWidth, IntAlign;
unsigned char HalfWidth, HalfAlign;
unsigned char BFloat16Width, BFloat16Align;
unsigned char FloatWidth, FloatAlign;
unsigned char DoubleWidth, DoubleAlign;
unsigned char LongDoubleWidth, LongDoubleAlign, Float128Align;
unsigned char LargeArrayMinWidth, LargeArrayAlign;
unsigned char LongWidth, LongAlign;
unsigned char LongLongWidth, LongLongAlign;
// Fixed point bit widths
unsigned char ShortAccumWidth, ShortAccumAlign;
unsigned char AccumWidth, AccumAlign;
unsigned char LongAccumWidth, LongAccumAlign;
unsigned char ShortFractWidth, ShortFractAlign;
unsigned char FractWidth, FractAlign;
unsigned char LongFractWidth, LongFractAlign;
// If true, unsigned fixed point types have the same number of fractional bits
// as their signed counterparts, forcing the unsigned types to have one extra
// bit of padding. Otherwise, unsigned fixed point types have
// one more fractional bit than its corresponding signed type. This is false
// by default.
bool PaddingOnUnsignedFixedPoint;
// Fixed point integral and fractional bit sizes
// Saturated types share the same integral/fractional bits as their
// corresponding unsaturated types.
// For simplicity, the fractional bits in a _Fract type will be one less the
// width of that _Fract type. This leaves all signed _Fract types having no
// padding and unsigned _Fract types will only have 1 bit of padding after the
// sign if PaddingOnUnsignedFixedPoint is set.
unsigned char ShortAccumScale;
unsigned char AccumScale;
unsigned char LongAccumScale;
unsigned char SuitableAlign;
unsigned char DefaultAlignForAttributeAligned;
unsigned char MinGlobalAlign;
unsigned short NewAlign;
unsigned MaxVectorAlign;
unsigned MaxTLSAlign;
const llvm::fltSemantics *HalfFormat, *BFloat16Format, *FloatFormat,
*DoubleFormat, *LongDoubleFormat, *Float128Format;
///===---- Target Data Type Query Methods -------------------------------===//
enum IntType {
NoInt = 0,
SignedChar,
UnsignedChar,
SignedShort,
UnsignedShort,
SignedInt,
UnsignedInt,
SignedLong,
UnsignedLong,
SignedLongLong,
UnsignedLongLong
};
enum RealType {
NoFloat = 255,
Float = 0,
Double,
LongDouble,
Float128
};
protected:
IntType SizeType, IntMaxType, PtrDiffType, IntPtrType, WCharType,
WIntType, Char16Type, Char32Type, Int64Type, SigAtomicType,
ProcessIDType;
/// Whether Objective-C's built-in boolean type should be signed char.
///
/// Otherwise, when this flag is not set, the normal built-in boolean type is
/// used.
unsigned UseSignedCharForObjCBool : 1;
/// Control whether the alignment of bit-field types is respected when laying
/// out structures. If true, then the alignment of the bit-field type will be
/// used to (a) impact the alignment of the containing structure, and (b)
/// ensure that the individual bit-field will not straddle an alignment
/// boundary.
unsigned UseBitFieldTypeAlignment : 1;
/// Whether zero length bitfields (e.g., int : 0;) force alignment of
/// the next bitfield.
///
/// If the alignment of the zero length bitfield is greater than the member
/// that follows it, `bar', `bar' will be aligned as the type of the
/// zero-length bitfield.
unsigned UseZeroLengthBitfieldAlignment : 1;
/// Whether explicit bit field alignment attributes are honored.
unsigned UseExplicitBitFieldAlignment : 1;
/// If non-zero, specifies a fixed alignment value for bitfields that follow
/// zero length bitfield, regardless of the zero length bitfield type.
unsigned ZeroLengthBitfieldBoundary;
};
/// OpenCL type kinds.
enum OpenCLTypeKind : uint8_t {
OCLTK_Default,
OCLTK_ClkEvent,
OCLTK_Event,
OCLTK_Image,
OCLTK_Pipe,
OCLTK_Queue,
OCLTK_ReserveID,
OCLTK_Sampler,
};
/// Exposes information about the current target.
///
class TargetInfo : public virtual TransferrableTargetInfo,
public RefCountedBase<TargetInfo> {
std::shared_ptr<TargetOptions> TargetOpts;
llvm::Triple Triple;
protected:
// Target values set by the ctor of the actual target implementation. Default
// values are specified by the TargetInfo constructor.
bool BigEndian;
bool TLSSupported;
bool VLASupported;
bool NoAsmVariants; // True if {|} are normal characters.
bool HasLegalHalfType; // True if the backend supports operations on the half
// LLVM IR type.
bool HasFloat128;
bool HasFloat16;
bool HasBFloat16;
bool HasStrictFP;
unsigned char MaxAtomicPromoteWidth, MaxAtomicInlineWidth;
unsigned short SimdDefaultAlign;
std::unique_ptr<llvm::DataLayout> DataLayout;
const char *MCountName;
unsigned char RegParmMax, SSERegParmMax;
TargetCXXABI TheCXXABI;
const LangASMap *AddrSpaceMap;
const unsigned *GridValues =
nullptr; // Array of target-specific GPU grid values that must be
// consistent between host RTL (plugin), device RTL, and clang.
mutable StringRef PlatformName;
mutable VersionTuple PlatformMinVersion;
unsigned HasAlignMac68kSupport : 1;
unsigned RealTypeUsesObjCFPRet : 3;
unsigned ComplexLongDoubleUsesFP2Ret : 1;
unsigned HasBuiltinMSVaList : 1;
unsigned IsRenderScriptTarget : 1;
unsigned HasAArch64SVETypes : 1;
unsigned ARMCDECoprocMask : 8;
unsigned PointerAuthSupported : 1;
unsigned MaxOpenCLWorkGroupSize;
// TargetInfo Constructor. Default initializes all fields.
TargetInfo(const llvm::Triple &T);
void resetDataLayout(StringRef DL);
public:
/// Construct a target for the given options.
///
/// \param Opts - The options to use to initialize the target. The target may
/// modify the options to canonicalize the target feature information to match
/// what the backend expects.
static TargetInfo *
CreateTargetInfo(DiagnosticsEngine &Diags,
const std::shared_ptr<TargetOptions> &Opts);
virtual ~TargetInfo();
/// Retrieve the target options.
TargetOptions &getTargetOpts() const {
assert(TargetOpts && "Missing target options");
return *TargetOpts;
}
/// The different kinds of __builtin_va_list types defined by
/// the target implementation.
enum BuiltinVaListKind {
/// typedef char* __builtin_va_list;
CharPtrBuiltinVaList = 0,
/// typedef void* __builtin_va_list;
VoidPtrBuiltinVaList,
/// __builtin_va_list as defined by the AArch64 ABI
/// http://infocenter.arm.com/help/topic/com.arm.doc.ihi0055a/IHI0055A_aapcs64.pdf
AArch64ABIBuiltinVaList,
/// __builtin_va_list as defined by the PNaCl ABI:
/// http://www.chromium.org/nativeclient/pnacl/bitcode-abi#TOC-Machine-Types
PNaClABIBuiltinVaList,
/// __builtin_va_list as defined by the Power ABI:
/// https://www.power.org
/// /resources/downloads/Power-Arch-32-bit-ABI-supp-1.0-Embedded.pdf
PowerABIBuiltinVaList,
/// __builtin_va_list as defined by the x86-64 ABI:
/// http://refspecs.linuxbase.org/elf/x86_64-abi-0.21.pdf
X86_64ABIBuiltinVaList,
/// __builtin_va_list as defined by ARM AAPCS ABI
/// http://infocenter.arm.com
// /help/topic/com.arm.doc.ihi0042d/IHI0042D_aapcs.pdf
AAPCSABIBuiltinVaList,
// typedef struct __va_list_tag
// {
// long __gpr;
// long __fpr;
// void *__overflow_arg_area;
// void *__reg_save_area;
// } va_list[1];
SystemZBuiltinVaList,
// typedef struct __va_list_tag {
// void *__current_saved_reg_area_pointer;
// void *__saved_reg_area_end_pointer;
// void *__overflow_area_pointer;
//} va_list;
HexagonBuiltinVaList
};
protected:
/// Specify if mangling based on address space map should be used or
/// not for language specific address spaces
bool UseAddrSpaceMapMangling;
public:
IntType getSizeType() const { return SizeType; }
IntType getSignedSizeType() const {
switch (SizeType) {
case UnsignedShort:
return SignedShort;
case UnsignedInt:
return SignedInt;
case UnsignedLong:
return SignedLong;
case UnsignedLongLong:
return SignedLongLong;
default:
llvm_unreachable("Invalid SizeType");
}
}
IntType getIntMaxType() const { return IntMaxType; }
IntType getUIntMaxType() const {
return getCorrespondingUnsignedType(IntMaxType);
}
IntType getPtrDiffType(unsigned AddrSpace) const {
return AddrSpace == 0 ? PtrDiffType : getPtrDiffTypeV(AddrSpace);
}
IntType getUnsignedPtrDiffType(unsigned AddrSpace) const {
return getCorrespondingUnsignedType(getPtrDiffType(AddrSpace));
}
IntType getIntPtrType() const { return IntPtrType; }
IntType getUIntPtrType() const {
return getCorrespondingUnsignedType(IntPtrType);
}
IntType getWCharType() const { return WCharType; }
IntType getWIntType() const { return WIntType; }
IntType getChar16Type() const { return Char16Type; }
IntType getChar32Type() const { return Char32Type; }
IntType getInt64Type() const { return Int64Type; }
IntType getUInt64Type() const {
return getCorrespondingUnsignedType(Int64Type);
}
IntType getSigAtomicType() const { return SigAtomicType; }
IntType getProcessIDType() const { return ProcessIDType; }
static IntType getCorrespondingUnsignedType(IntType T) {
switch (T) {
case SignedChar:
return UnsignedChar;
case SignedShort:
return UnsignedShort;
case SignedInt:
return UnsignedInt;
case SignedLong:
return UnsignedLong;
case SignedLongLong:
return UnsignedLongLong;
default:
llvm_unreachable("Unexpected signed integer type");
}
}
/// In the event this target uses the same number of fractional bits for its
/// unsigned types as it does with its signed counterparts, there will be
/// exactly one bit of padding.
/// Return true if unsigned fixed point types have padding for this target.
bool doUnsignedFixedPointTypesHavePadding() const {
return PaddingOnUnsignedFixedPoint;
}
/// Return the width (in bits) of the specified integer type enum.
///
/// For example, SignedInt -> getIntWidth().
unsigned getTypeWidth(IntType T) const;
/// Return integer type with specified width.
virtual IntType getIntTypeByWidth(unsigned BitWidth, bool IsSigned) const;
/// Return the smallest integer type with at least the specified width.
virtual IntType getLeastIntTypeByWidth(unsigned BitWidth,
bool IsSigned) const;
/// Return floating point type with specified width. On PPC, there are
/// three possible types for 128-bit floating point: "PPC double-double",
/// IEEE 754R quad precision, and "long double" (which under the covers
/// is represented as one of those two). At this time, there is no support
/// for an explicit "PPC double-double" type (i.e. __ibm128) so we only
/// need to differentiate between "long double" and IEEE quad precision.
RealType getRealTypeByWidth(unsigned BitWidth, bool ExplicitIEEE) const;
/// Return the alignment (in bits) of the specified integer type enum.
///
/// For example, SignedInt -> getIntAlign().
unsigned getTypeAlign(IntType T) const;
/// Returns true if the type is signed; false otherwise.
static bool isTypeSigned(IntType T);
/// Return the width of pointers on this target, for the
/// specified address space.
uint64_t getPointerWidth(unsigned AddrSpace) const {
return AddrSpace == 0 ? PointerWidth : getPointerWidthV(AddrSpace);
}
uint64_t getPointerAlign(unsigned AddrSpace) const {
return AddrSpace == 0 ? PointerAlign : getPointerAlignV(AddrSpace);
}
/// Return the maximum width of pointers on this target.
virtual uint64_t getMaxPointerWidth() const {
return PointerWidth;
}
/// Get integer value for null pointer.
/// \param AddrSpace address space of pointee in source language.
virtual uint64_t getNullPointerValue(LangAS AddrSpace) const { return 0; }
/// Return the size of '_Bool' and C++ 'bool' for this target, in bits.
unsigned getBoolWidth() const { return BoolWidth; }
/// Return the alignment of '_Bool' and C++ 'bool' for this target.
unsigned getBoolAlign() const { return BoolAlign; }
unsigned getCharWidth() const { return 8; } // FIXME
unsigned getCharAlign() const { return 8; } // FIXME
/// Return the size of 'signed short' and 'unsigned short' for this
/// target, in bits.
unsigned getShortWidth() const { return 16; } // FIXME
/// Return the alignment of 'signed short' and 'unsigned short' for
/// this target.
unsigned getShortAlign() const { return 16; } // FIXME
/// getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for
/// this target, in bits.
unsigned getIntWidth() const { return IntWidth; }
unsigned getIntAlign() const { return IntAlign; }
/// getLongWidth/Align - Return the size of 'signed long' and 'unsigned long'
/// for this target, in bits.
unsigned getLongWidth() const { return LongWidth; }
unsigned getLongAlign() const { return LongAlign; }
/// getLongLongWidth/Align - Return the size of 'signed long long' and
/// 'unsigned long long' for this target, in bits.
unsigned getLongLongWidth() const { return LongLongWidth; }
unsigned getLongLongAlign() const { return LongLongAlign; }
/// getShortAccumWidth/Align - Return the size of 'signed short _Accum' and
/// 'unsigned short _Accum' for this target, in bits.
unsigned getShortAccumWidth() const { return ShortAccumWidth; }
unsigned getShortAccumAlign() const { return ShortAccumAlign; }
/// getAccumWidth/Align - Return the size of 'signed _Accum' and
/// 'unsigned _Accum' for this target, in bits.
unsigned getAccumWidth() const { return AccumWidth; }
unsigned getAccumAlign() const { return AccumAlign; }
/// getLongAccumWidth/Align - Return the size of 'signed long _Accum' and
/// 'unsigned long _Accum' for this target, in bits.
unsigned getLongAccumWidth() const { return LongAccumWidth; }
unsigned getLongAccumAlign() const { return LongAccumAlign; }
/// getShortFractWidth/Align - Return the size of 'signed short _Fract' and
/// 'unsigned short _Fract' for this target, in bits.
unsigned getShortFractWidth() const { return ShortFractWidth; }
unsigned getShortFractAlign() const { return ShortFractAlign; }
/// getFractWidth/Align - Return the size of 'signed _Fract' and
/// 'unsigned _Fract' for this target, in bits.
unsigned getFractWidth() const { return FractWidth; }
unsigned getFractAlign() const { return FractAlign; }
/// getLongFractWidth/Align - Return the size of 'signed long _Fract' and
/// 'unsigned long _Fract' for this target, in bits.
unsigned getLongFractWidth() const { return LongFractWidth; }
unsigned getLongFractAlign() const { return LongFractAlign; }
/// getShortAccumScale/IBits - Return the number of fractional/integral bits
/// in a 'signed short _Accum' type.
unsigned getShortAccumScale() const { return ShortAccumScale; }
unsigned getShortAccumIBits() const {
return ShortAccumWidth - ShortAccumScale - 1;
}
/// getAccumScale/IBits - Return the number of fractional/integral bits
/// in a 'signed _Accum' type.
unsigned getAccumScale() const { return AccumScale; }
unsigned getAccumIBits() const { return AccumWidth - AccumScale - 1; }
/// getLongAccumScale/IBits - Return the number of fractional/integral bits
/// in a 'signed long _Accum' type.
unsigned getLongAccumScale() const { return LongAccumScale; }
unsigned getLongAccumIBits() const {
return LongAccumWidth - LongAccumScale - 1;
}
/// getUnsignedShortAccumScale/IBits - Return the number of
/// fractional/integral bits in a 'unsigned short _Accum' type.
unsigned getUnsignedShortAccumScale() const {
return PaddingOnUnsignedFixedPoint ? ShortAccumScale : ShortAccumScale + 1;
}
unsigned getUnsignedShortAccumIBits() const {
return PaddingOnUnsignedFixedPoint
? getShortAccumIBits()
: ShortAccumWidth - getUnsignedShortAccumScale();
}
/// getUnsignedAccumScale/IBits - Return the number of fractional/integral
/// bits in a 'unsigned _Accum' type.
unsigned getUnsignedAccumScale() const {
return PaddingOnUnsignedFixedPoint ? AccumScale : AccumScale + 1;
}
unsigned getUnsignedAccumIBits() const {
return PaddingOnUnsignedFixedPoint ? getAccumIBits()
: AccumWidth - getUnsignedAccumScale();
}
/// getUnsignedLongAccumScale/IBits - Return the number of fractional/integral
/// bits in a 'unsigned long _Accum' type.
unsigned getUnsignedLongAccumScale() const {
return PaddingOnUnsignedFixedPoint ? LongAccumScale : LongAccumScale + 1;
}
unsigned getUnsignedLongAccumIBits() const {
return PaddingOnUnsignedFixedPoint
? getLongAccumIBits()
: LongAccumWidth - getUnsignedLongAccumScale();
}
/// getShortFractScale - Return the number of fractional bits
/// in a 'signed short _Fract' type.
unsigned getShortFractScale() const { return ShortFractWidth - 1; }
/// getFractScale - Return the number of fractional bits
/// in a 'signed _Fract' type.
unsigned getFractScale() const { return FractWidth - 1; }
/// getLongFractScale - Return the number of fractional bits
/// in a 'signed long _Fract' type.
unsigned getLongFractScale() const { return LongFractWidth - 1; }
/// getUnsignedShortFractScale - Return the number of fractional bits
/// in a 'unsigned short _Fract' type.
unsigned getUnsignedShortFractScale() const {
return PaddingOnUnsignedFixedPoint ? getShortFractScale()
: getShortFractScale() + 1;
}
/// getUnsignedFractScale - Return the number of fractional bits
/// in a 'unsigned _Fract' type.
unsigned getUnsignedFractScale() const {
return PaddingOnUnsignedFixedPoint ? getFractScale() : getFractScale() + 1;
}
/// getUnsignedLongFractScale - Return the number of fractional bits
/// in a 'unsigned long _Fract' type.
unsigned getUnsignedLongFractScale() const {
return PaddingOnUnsignedFixedPoint ? getLongFractScale()
: getLongFractScale() + 1;
}
/// Determine whether the __int128 type is supported on this target.
virtual bool hasInt128Type() const {
return (getPointerWidth(0) >= 64) || getTargetOpts().ForceEnableInt128;
} // FIXME
/// Determine whether the _ExtInt type is supported on this target. This
/// limitation is put into place for ABI reasons.
virtual bool hasExtIntType() const {
return false;
}
/// Determine whether _Float16 is supported on this target.
virtual bool hasLegalHalfType() const { return HasLegalHalfType; }
/// Determine whether the __float128 type is supported on this target.
virtual bool hasFloat128Type() const { return HasFloat128; }
/// Determine whether the _Float16 type is supported on this target.
virtual bool hasFloat16Type() const { return HasFloat16; }
/// Determine whether the _BFloat16 type is supported on this target.
virtual bool hasBFloat16Type() const { return HasBFloat16; }
/// Determine whether constrained floating point is supported on this target.
virtual bool hasStrictFP() const { return HasStrictFP; }
/// Return the alignment that is suitable for storing any
/// object with a fundamental alignment requirement.
unsigned getSuitableAlign() const { return SuitableAlign; }
/// Return the default alignment for __attribute__((aligned)) on
/// this target, to be used if no alignment value is specified.
unsigned getDefaultAlignForAttributeAligned() const {
return DefaultAlignForAttributeAligned;
}
/// getMinGlobalAlign - Return the minimum alignment of a global variable,
/// unless its alignment is explicitly reduced via attributes.
virtual unsigned getMinGlobalAlign (uint64_t) const {
return MinGlobalAlign;
}
/// Return the largest alignment for which a suitably-sized allocation with
/// '::operator new(size_t)' is guaranteed to produce a correctly-aligned
/// pointer.
unsigned getNewAlign() const {
return NewAlign ? NewAlign : std::max(LongDoubleAlign, LongLongAlign);
}
/// getWCharWidth/Align - Return the size of 'wchar_t' for this target, in
/// bits.
unsigned getWCharWidth() const { return getTypeWidth(WCharType); }
unsigned getWCharAlign() const { return getTypeAlign(WCharType); }
/// getChar16Width/Align - Return the size of 'char16_t' for this target, in
/// bits.
unsigned getChar16Width() const { return getTypeWidth(Char16Type); }
unsigned getChar16Align() const { return getTypeAlign(Char16Type); }
/// getChar32Width/Align - Return the size of 'char32_t' for this target, in
/// bits.
unsigned getChar32Width() const { return getTypeWidth(Char32Type); }
unsigned getChar32Align() const { return getTypeAlign(Char32Type); }
/// getHalfWidth/Align/Format - Return the size/align/format of 'half'.
unsigned getHalfWidth() const { return HalfWidth; }
unsigned getHalfAlign() const { return HalfAlign; }
const llvm::fltSemantics &getHalfFormat() const { return *HalfFormat; }
/// getFloatWidth/Align/Format - Return the size/align/format of 'float'.
unsigned getFloatWidth() const { return FloatWidth; }
unsigned getFloatAlign() const { return FloatAlign; }
const llvm::fltSemantics &getFloatFormat() const { return *FloatFormat; }
/// getBFloat16Width/Align/Format - Return the size/align/format of '__bf16'.
unsigned getBFloat16Width() const { return BFloat16Width; }
unsigned getBFloat16Align() const { return BFloat16Align; }
const llvm::fltSemantics &getBFloat16Format() const { return *BFloat16Format; }
/// getDoubleWidth/Align/Format - Return the size/align/format of 'double'.
unsigned getDoubleWidth() const { return DoubleWidth; }
unsigned getDoubleAlign() const { return DoubleAlign; }
const llvm::fltSemantics &getDoubleFormat() const { return *DoubleFormat; }
/// getLongDoubleWidth/Align/Format - Return the size/align/format of 'long
/// double'.
unsigned getLongDoubleWidth() const { return LongDoubleWidth; }
unsigned getLongDoubleAlign() const { return LongDoubleAlign; }
const llvm::fltSemantics &getLongDoubleFormat() const {
return *LongDoubleFormat;
}
/// getFloat128Width/Align/Format - Return the size/align/format of
/// '__float128'.
unsigned getFloat128Width() const { return 128; }
unsigned getFloat128Align() const { return Float128Align; }
const llvm::fltSemantics &getFloat128Format() const {
return *Float128Format;
}
/// Return the mangled code of long double.
virtual const char *getLongDoubleMangling() const { return "e"; }
/// Return the mangled code of __float128.
virtual const char *getFloat128Mangling() const { return "g"; }
/// Return the mangled code of bfloat.
virtual const char *getBFloat16Mangling() const {
llvm_unreachable("bfloat not implemented on this target");
}
/// Return the value for the C99 FLT_EVAL_METHOD macro.
virtual unsigned getFloatEvalMethod() const { return 0; }
// getLargeArrayMinWidth/Align - Return the minimum array size that is
// 'large' and its alignment.
unsigned getLargeArrayMinWidth() const { return LargeArrayMinWidth; }
unsigned getLargeArrayAlign() const { return LargeArrayAlign; }
/// Return the maximum width lock-free atomic operation which will
/// ever be supported for the given target
unsigned getMaxAtomicPromoteWidth() const { return MaxAtomicPromoteWidth; }
/// Return the maximum width lock-free atomic operation which can be
/// inlined given the supported features of the given target.
unsigned getMaxAtomicInlineWidth() const { return MaxAtomicInlineWidth; }
/// Set the maximum inline or promote width lock-free atomic operation
/// for the given target.
virtual void setMaxAtomicWidth() {}
/// Returns true if the given target supports lock-free atomic
/// operations at the specified width and alignment.
virtual bool hasBuiltinAtomic(uint64_t AtomicSizeInBits,
uint64_t AlignmentInBits) const {
return AtomicSizeInBits <= AlignmentInBits &&
AtomicSizeInBits <= getMaxAtomicInlineWidth() &&
(AtomicSizeInBits <= getCharWidth() ||
llvm::isPowerOf2_64(AtomicSizeInBits / getCharWidth()));
}
/// Return the maximum vector alignment supported for the given target.
unsigned getMaxVectorAlign() const { return MaxVectorAlign; }
/// Return default simd alignment for the given target. Generally, this
/// value is type-specific, but this alignment can be used for most of the
/// types for the given target.
unsigned getSimdDefaultAlign() const { return SimdDefaultAlign; }
unsigned getMaxOpenCLWorkGroupSize() const { return MaxOpenCLWorkGroupSize; }
/// Return the alignment (in bits) of the thrown exception object. This is
/// only meaningful for targets that allocate C++ exceptions in a system
/// runtime, such as those using the Itanium C++ ABI.
virtual unsigned getExnObjectAlignment() const {
// Itanium says that an _Unwind_Exception has to be "double-word"
// aligned (and thus the end of it is also so-aligned), meaning 16
// bytes. Of course, that was written for the actual Itanium,
// which is a 64-bit platform. Classically, the ABI doesn't really
// specify the alignment on other platforms, but in practice
// libUnwind declares the struct with __attribute__((aligned)), so
// we assume that alignment here. (It's generally 16 bytes, but
// some targets overwrite it.)
return getDefaultAlignForAttributeAligned();
}
/// Return the size of intmax_t and uintmax_t for this target, in bits.
unsigned getIntMaxTWidth() const {
return getTypeWidth(IntMaxType);
}
// Return the size of unwind_word for this target.
virtual unsigned getUnwindWordWidth() const { return getPointerWidth(0); }
/// Return the "preferred" register width on this target.
virtual unsigned getRegisterWidth() const {
// Currently we assume the register width on the target matches the pointer
// width, we can introduce a new variable for this if/when some target wants
// it.
return PointerWidth;
}
/// Returns the name of the mcount instrumentation function.
const char *getMCountName() const {
return MCountName;
}
/// Check if the Objective-C built-in boolean type should be signed
/// char.
///
/// Otherwise, if this returns false, the normal built-in boolean type
/// should also be used for Objective-C.
bool useSignedCharForObjCBool() const {
return UseSignedCharForObjCBool;
}
void noSignedCharForObjCBool() {
UseSignedCharForObjCBool = false;
}
/// Check whether the alignment of bit-field types is respected
/// when laying out structures.
bool useBitFieldTypeAlignment() const {
return UseBitFieldTypeAlignment;
}
/// Check whether zero length bitfields should force alignment of
/// the next member.
bool useZeroLengthBitfieldAlignment() const {
return UseZeroLengthBitfieldAlignment;
}
/// Get the fixed alignment value in bits for a member that follows
/// a zero length bitfield.
unsigned getZeroLengthBitfieldBoundary() const {
return ZeroLengthBitfieldBoundary;
}
/// Check whether explicit bitfield alignment attributes should be
// honored, as in "__attribute__((aligned(2))) int b : 1;".
bool useExplicitBitFieldAlignment() const {
return UseExplicitBitFieldAlignment;
}
/// Check whether this target support '\#pragma options align=mac68k'.
bool hasAlignMac68kSupport() const {
return HasAlignMac68kSupport;
}
/// Return the user string for the specified integer type enum.
///
/// For example, SignedShort -> "short".
static const char *getTypeName(IntType T);
/// Return the constant suffix for the specified integer type enum.
///
/// For example, SignedLong -> "L".
const char *getTypeConstantSuffix(IntType T) const;
/// Return the printf format modifier for the specified
/// integer type enum.
///
/// For example, SignedLong -> "l".
static const char *getTypeFormatModifier(IntType T);
/// Check whether the given real type should use the "fpret" flavor of
/// Objective-C message passing on this target.
bool useObjCFPRetForRealType(RealType T) const {
return RealTypeUsesObjCFPRet & (1 << T);
}
/// Check whether _Complex long double should use the "fp2ret" flavor
/// of Objective-C message passing on this target.
bool useObjCFP2RetForComplexLongDouble() const {
return ComplexLongDoubleUsesFP2Ret;
}
/// Check whether llvm intrinsics such as llvm.convert.to.fp16 should be used
/// to convert to and from __fp16.
/// FIXME: This function should be removed once all targets stop using the
/// conversion intrinsics.
virtual bool useFP16ConversionIntrinsics() const {
return true;
}
/// Specify if mangling based on address space map should be used or
/// not for language specific address spaces
bool useAddressSpaceMapMangling() const {
return UseAddrSpaceMapMangling;
}
///===---- Other target property query methods --------------------------===//
/// Appends the target-specific \#define values for this
/// target set to the specified buffer.
virtual void getTargetDefines(const LangOptions &Opts,
MacroBuilder &Builder) const = 0;
/// Return information about target-specific builtins for
/// the current primary target, and info about which builtins are non-portable
/// across the current set of primary and secondary targets.
virtual ArrayRef<Builtin::Info> getTargetBuiltins() const = 0;
/// The __builtin_clz* and __builtin_ctz* built-in
/// functions are specified to have undefined results for zero inputs, but
/// on targets that support these operations in a way that provides
/// well-defined results for zero without loss of performance, it is a good
/// idea to avoid optimizing based on that undef behavior.
virtual bool isCLZForZeroUndef() const { return true; }
/// Returns the kind of __builtin_va_list type that should be used
/// with this target.
virtual BuiltinVaListKind getBuiltinVaListKind() const = 0;
/// Returns whether or not type \c __builtin_ms_va_list type is
/// available on this target.
bool hasBuiltinMSVaList() const { return HasBuiltinMSVaList; }
/// Returns true for RenderScript.
bool isRenderScriptTarget() const { return IsRenderScriptTarget; }
/// Returns whether or not the AArch64 SVE built-in types are
/// available on this target.
bool hasAArch64SVETypes() const { return HasAArch64SVETypes; }
/// For ARM targets returns a mask defining which coprocessors are configured
/// as Custom Datapath.
uint32_t getARMCDECoprocMask() const { return ARMCDECoprocMask; }
/// Returns whether the passed in string is a valid clobber in an
/// inline asm statement.
///
/// This is used by Sema.
bool isValidClobber(StringRef Name) const;
/// Returns whether the passed in string is a valid register name
/// according to GCC.
///
/// This is used by Sema for inline asm statements.
virtual bool isValidGCCRegisterName(StringRef Name) const;
/// Returns the "normalized" GCC register name.
///
/// ReturnCannonical true will return the register name without any additions
/// such as "{}" or "%" in it's canonical form, for example:
/// ReturnCanonical = true and Name = "rax", will return "ax".
StringRef getNormalizedGCCRegisterName(StringRef Name,
bool ReturnCanonical = false) const;
virtual bool isSPRegName(StringRef) const { return false; }
/// Extracts a register from the passed constraint (if it is a
/// single-register constraint) and the asm label expression related to a
/// variable in the input or output list of an inline asm statement.
///
/// This function is used by Sema in order to diagnose conflicts between
/// the clobber list and the input/output lists.
virtual StringRef getConstraintRegister(StringRef Constraint,
StringRef Expression) const {
return "";
}
struct ConstraintInfo {
enum {
CI_None = 0x00,
CI_AllowsMemory = 0x01,
CI_AllowsRegister = 0x02,
CI_ReadWrite = 0x04, // "+r" output constraint (read and write).
CI_HasMatchingInput = 0x08, // This output operand has a matching input.
CI_ImmediateConstant = 0x10, // This operand must be an immediate constant
CI_EarlyClobber = 0x20, // "&" output constraint (early clobber).
};
unsigned Flags;
int TiedOperand;
struct {
int Min;
int Max;
bool isConstrained;
} ImmRange;
llvm::SmallSet<int, 4> ImmSet;
std::string ConstraintStr; // constraint: "=rm"
std::string Name; // Operand name: [foo] with no []'s.
public:
ConstraintInfo(StringRef ConstraintStr, StringRef Name)
: Flags(0), TiedOperand(-1), ConstraintStr(ConstraintStr.str()),
Name(Name.str()) {
ImmRange.Min = ImmRange.Max = 0;
ImmRange.isConstrained = false;
}
const std::string &getConstraintStr() const { return ConstraintStr; }
const std::string &getName() const { return Name; }
bool isReadWrite() const { return (Flags & CI_ReadWrite) != 0; }
bool earlyClobber() { return (Flags & CI_EarlyClobber) != 0; }
bool allowsRegister() const { return (Flags & CI_AllowsRegister) != 0; }
bool allowsMemory() const { return (Flags & CI_AllowsMemory) != 0; }
/// Return true if this output operand has a matching
/// (tied) input operand.
bool hasMatchingInput() const { return (Flags & CI_HasMatchingInput) != 0; }
/// Return true if this input operand is a matching
/// constraint that ties it to an output operand.
///
/// If this returns true then getTiedOperand will indicate which output
/// operand this is tied to.
bool hasTiedOperand() const { return TiedOperand != -1; }
unsigned getTiedOperand() const {
assert(hasTiedOperand() && "Has no tied operand!");
return (unsigned)TiedOperand;
}
bool requiresImmediateConstant() const {
return (Flags & CI_ImmediateConstant) != 0;
}
bool isValidAsmImmediate(const llvm::APInt &Value) const {
if (!ImmSet.empty())
return Value.isSignedIntN(32) &&
ImmSet.count(Value.getZExtValue()) != 0;
return !ImmRange.isConstrained ||
(Value.sge(ImmRange.Min) && Value.sle(ImmRange.Max));
}
void setIsReadWrite() { Flags |= CI_ReadWrite; }
void setEarlyClobber() { Flags |= CI_EarlyClobber; }
void setAllowsMemory() { Flags |= CI_AllowsMemory; }
void setAllowsRegister() { Flags |= CI_AllowsRegister; }
void setHasMatchingInput() { Flags |= CI_HasMatchingInput; }
void setRequiresImmediate(int Min, int Max) {
Flags |= CI_ImmediateConstant;
ImmRange.Min = Min;
ImmRange.Max = Max;
ImmRange.isConstrained = true;
}
void setRequiresImmediate(llvm::ArrayRef<int> Exacts) {
Flags |= CI_ImmediateConstant;
for (int Exact : Exacts)
ImmSet.insert(Exact);
}
void setRequiresImmediate(int Exact) {
Flags |= CI_ImmediateConstant;
ImmSet.insert(Exact);
}
void setRequiresImmediate() {
Flags |= CI_ImmediateConstant;
}
/// Indicate that this is an input operand that is tied to
/// the specified output operand.
///
/// Copy over the various constraint information from the output.
void setTiedOperand(unsigned N, ConstraintInfo &Output) {
Output.setHasMatchingInput();
Flags = Output.Flags;
TiedOperand = N;
// Don't copy Name or constraint string.
}
};
/// Validate register name used for global register variables.
///
/// This function returns true if the register passed in RegName can be used
/// for global register variables on this target. In addition, it returns
/// true in HasSizeMismatch if the size of the register doesn't match the
/// variable size passed in RegSize.
virtual bool validateGlobalRegisterVariable(StringRef RegName,
unsigned RegSize,
bool &HasSizeMismatch) const {
HasSizeMismatch = false;
return true;
}
// validateOutputConstraint, validateInputConstraint - Checks that
// a constraint is valid and provides information about it.
// FIXME: These should return a real error instead of just true/false.
bool validateOutputConstraint(ConstraintInfo &Info) const;
bool validateInputConstraint(MutableArrayRef<ConstraintInfo> OutputConstraints,
ConstraintInfo &info) const;
virtual bool validateOutputSize(const llvm::StringMap<bool> &FeatureMap,
StringRef /*Constraint*/,
unsigned /*Size*/) const {
return true;
}
virtual bool validateInputSize(const llvm::StringMap<bool> &FeatureMap,
StringRef /*Constraint*/,
unsigned /*Size*/) const {
return true;
}
virtual bool
validateConstraintModifier(StringRef /*Constraint*/,
char /*Modifier*/,
unsigned /*Size*/,
std::string &/*SuggestedModifier*/) const {
return true;
}
virtual bool
validateAsmConstraint(const char *&Name,
TargetInfo::ConstraintInfo &info) const = 0;
bool resolveSymbolicName(const char *&Name,
ArrayRef<ConstraintInfo> OutputConstraints,
unsigned &Index) const;
// Constraint parm will be left pointing at the last character of
// the constraint. In practice, it won't be changed unless the
// constraint is longer than one character.
virtual std::string convertConstraint(const char *&Constraint) const {
// 'p' defaults to 'r', but can be overridden by targets.
if (*Constraint == 'p')
return std::string("r");
return std::string(1, *Constraint);
}
/// Returns a string of target-specific clobbers, in LLVM format.
virtual const char *getClobbers() const = 0;
/// Returns true if NaN encoding is IEEE 754-2008.
/// Only MIPS allows a different encoding.
virtual bool isNan2008() const {
return true;
}
/// Returns the target triple of the primary target.
const llvm::Triple &getTriple() const {
return Triple;
}
const llvm::DataLayout &getDataLayout() const {
assert(DataLayout && "Uninitialized DataLayout!");
return *DataLayout;
}
struct GCCRegAlias {
const char * const Aliases[5];
const char * const Register;
};
struct AddlRegName {
const char * const Names[5];
const unsigned RegNum;
};
/// Does this target support "protected" visibility?
///
/// Any target which dynamic libraries will naturally support
/// something like "default" (meaning that the symbol is visible
/// outside this shared object) and "hidden" (meaning that it isn't)
/// visibilities, but "protected" is really an ELF-specific concept
/// with weird semantics designed around the convenience of dynamic
/// linker implementations. Which is not to suggest that there's
/// consistent target-independent semantics for "default" visibility
/// either; the entire thing is pretty badly mangled.
virtual bool hasProtectedVisibility() const { return true; }
/// An optional hook that targets can implement to perform semantic
/// checking on attribute((section("foo"))) specifiers.
///
/// In this case, "foo" is passed in to be checked. If the section
/// specifier is invalid, the backend should return a non-empty string
/// that indicates the problem.
///
/// This hook is a simple quality of implementation feature to catch errors
/// and give good diagnostics in cases when the assembler or code generator
/// would otherwise reject the section specifier.
///
virtual std::string isValidSectionSpecifier(StringRef SR) const {
return "";
}
/// Set forced language options.
///
/// Apply changes to the target information with respect to certain
/// language options which change the target configuration and adjust
/// the language based on the target options where applicable.
virtual void adjust(LangOptions &Opts);
/// Adjust target options based on codegen options.
virtual void adjustTargetOptions(const CodeGenOptions &CGOpts,
TargetOptions &TargetOpts) const {}
/// Initialize the map with the default set of target features for the
/// CPU this should include all legal feature strings on the target.
///
/// \return False on error (invalid features).
virtual bool initFeatureMap(llvm::StringMap<bool> &Features,
DiagnosticsEngine &Diags, StringRef CPU,
const std::vector<std::string> &FeatureVec) const;
/// Get the ABI currently in use.
virtual StringRef getABI() const { return StringRef(); }
/// Get the C++ ABI currently in use.
TargetCXXABI getCXXABI() const {
return TheCXXABI;
}
/// Target the specified CPU.
///
/// \return False on error (invalid CPU name).
virtual bool setCPU(const std::string &Name) {
return false;
}
/// Fill a SmallVectorImpl with the valid values to setCPU.
virtual void fillValidCPUList(SmallVectorImpl<StringRef> &Values) const {}
/// brief Determine whether this TargetInfo supports the given CPU name.
virtual bool isValidCPUName(StringRef Name) const {
return true;
}
/// Use the specified ABI.
///
/// \return False on error (invalid ABI name).
virtual bool setABI(const std::string &Name) {
return false;
}
/// Use the specified unit for FP math.
///
/// \return False on error (invalid unit name).
virtual bool setFPMath(StringRef Name) {
return false;
}
/// Enable or disable a specific target feature;
/// the feature name must be valid.
virtual void setFeatureEnabled(llvm::StringMap<bool> &Features,
StringRef Name,
bool Enabled) const {
Features[Name] = Enabled;
}
/// Determine whether this TargetInfo supports the given feature.
virtual bool isValidFeatureName(StringRef Feature) const {
return true;
}
struct BranchProtectionInfo {
LangOptions::SignReturnAddressScopeKind SignReturnAddr =
LangOptions::SignReturnAddressScopeKind::None;
LangOptions::SignReturnAddressKeyKind SignKey =
LangOptions::SignReturnAddressKeyKind::AKey;
bool BranchTargetEnforcement = false;
};
/// Determine if this TargetInfo supports the given branch protection
/// specification
virtual bool validateBranchProtection(StringRef Spec,
BranchProtectionInfo &BPI,
StringRef &Err) const {
Err = "";
return false;
}
/// Perform initialization based on the user configured
/// set of features (e.g., +sse4).
///
/// The list is guaranteed to have at most one entry per feature.
///
/// The target may modify the features list, to change which options are
/// passed onwards to the backend.
/// FIXME: This part should be fixed so that we can change handleTargetFeatures
/// to merely a TargetInfo initialization routine.
///
/// \return False on error.
virtual bool handleTargetFeatures(std::vector<std::string> &Features,
DiagnosticsEngine &Diags) {
return true;
}
/// Determine whether the given target has the given feature.
virtual bool hasFeature(StringRef Feature) const {
return false;
}
/// Identify whether this target supports multiversioning of functions,
/// which requires support for cpu_supports and cpu_is functionality.
bool supportsMultiVersioning() const { return getTriple().isX86(); }
/// Identify whether this target supports IFuncs.
bool supportsIFunc() const { return getTriple().isOSBinFormatELF(); }
// Validate the contents of the __builtin_cpu_supports(const char*)
// argument.
virtual bool validateCpuSupports(StringRef Name) const { return false; }
// Return the target-specific priority for features/cpus/vendors so
// that they can be properly sorted for checking.
virtual unsigned multiVersionSortPriority(StringRef Name) const {
return 0;
}
// Validate the contents of the __builtin_cpu_is(const char*)
// argument.
virtual bool validateCpuIs(StringRef Name) const { return false; }
// Validate a cpu_dispatch/cpu_specific CPU option, which is a different list
// from cpu_is, since it checks via features rather than CPUs directly.
virtual bool validateCPUSpecificCPUDispatch(StringRef Name) const {
return false;
}
// Get the character to be added for mangling purposes for cpu_specific.
virtual char CPUSpecificManglingCharacter(StringRef Name) const {
llvm_unreachable(
"cpu_specific Multiversioning not implemented on this target");
}
// Get a list of the features that make up the CPU option for
// cpu_specific/cpu_dispatch so that it can be passed to llvm as optimization
// options.
virtual void getCPUSpecificCPUDispatchFeatures(
StringRef Name, llvm::SmallVectorImpl<StringRef> &Features) const {
llvm_unreachable(
"cpu_specific Multiversioning not implemented on this target");
}
// Get the cache line size of a given cpu. This method switches over
// the given cpu and returns "None" if the CPU is not found.
virtual Optional<unsigned> getCPUCacheLineSize() const { return None; }
// Returns maximal number of args passed in registers.
unsigned getRegParmMax() const {
assert(RegParmMax < 7 && "RegParmMax value is larger than AST can handle");
return RegParmMax;
}
/// Whether the target supports thread-local storage.
bool isTLSSupported() const {
return TLSSupported;
}
/// \brief Whether the target supports pointer authentication at all.
///
/// Whether pointer authentication is actually being used is determined
/// by the language option.
bool isPointerAuthSupported() const {
return PointerAuthSupported;
}
/// Return the maximum alignment (in bits) of a TLS variable
///
/// Gets the maximum alignment (in bits) of a TLS variable on this target.
/// Returns zero if there is no such constraint.
unsigned getMaxTLSAlign() const { return MaxTLSAlign; }
/// Whether target supports variable-length arrays.
bool isVLASupported() const { return VLASupported; }
/// Whether the target supports SEH __try.
bool isSEHTrySupported() const {
return getTriple().isOSWindows() &&
(getTriple().isX86() ||
getTriple().getArch() == llvm::Triple::aarch64);
}
/// Return true if {|} are normal characters in the asm string.
///
/// If this returns false (the default), then {abc|xyz} is syntax
/// that says that when compiling for asm variant #0, "abc" should be
/// generated, but when compiling for asm variant #1, "xyz" should be
/// generated.
bool hasNoAsmVariants() const {
return NoAsmVariants;
}
/// Return the register number that __builtin_eh_return_regno would
/// return with the specified argument.
/// This corresponds with TargetLowering's getExceptionPointerRegister
/// and getExceptionSelectorRegister in the backend.
virtual int getEHDataRegisterNumber(unsigned RegNo) const {
return -1;
}
/// Return the section to use for C++ static initialization functions.
virtual const char *getStaticInitSectionSpecifier() const {
return nullptr;
}
const LangASMap &getAddressSpaceMap() const { return *AddrSpaceMap; }
/// Determine whether the given pointer-authentication key is valid.
///
/// The value has been coerced to type 'int'.
virtual bool validatePointerAuthKey(const llvm::APSInt &value) const;
/// Map from the address space field in builtin description strings to the
/// language address space.
virtual LangAS getOpenCLBuiltinAddressSpace(unsigned AS) const {
return getLangASFromTargetAS(AS);
}
/// Map from the address space field in builtin description strings to the
/// language address space.
virtual LangAS getCUDABuiltinAddressSpace(unsigned AS) const {
return getLangASFromTargetAS(AS);
}
/// Return an AST address space which can be used opportunistically
/// for constant global memory. It must be possible to convert pointers into
/// this address space to LangAS::Default. If no such address space exists,
/// this may return None, and such optimizations will be disabled.
virtual llvm::Optional<LangAS> getConstantAddressSpace() const {
return LangAS::Default;
}
/// Return a target-specific GPU grid value based on the GVIDX enum \p gv
unsigned getGridValue(llvm::omp::GVIDX gv) const {
assert(GridValues != nullptr && "GridValues not initialized");
return GridValues[gv];
}
/// Retrieve the name of the platform as it is used in the
/// availability attribute.
StringRef getPlatformName() const { return PlatformName; }
/// Retrieve the minimum desired version of the platform, to
/// which the program should be compiled.
VersionTuple getPlatformMinVersion() const { return PlatformMinVersion; }
bool isBigEndian() const { return BigEndian; }
bool isLittleEndian() const { return !BigEndian; }
/// Gets the default calling convention for the given target and
/// declaration context.
virtual CallingConv getDefaultCallingConv() const {
// Not all targets will specify an explicit calling convention that we can
// express. This will always do the right thing, even though it's not
// an explicit calling convention.
return CC_C;
}
enum CallingConvCheckResult {
CCCR_OK,
CCCR_Warning,
CCCR_Ignore,
CCCR_Error,
};
/// Determines whether a given calling convention is valid for the
/// target. A calling convention can either be accepted, produce a warning
/// and be substituted with the default calling convention, or (someday)
/// produce an error (such as using thiscall on a non-instance function).
virtual CallingConvCheckResult checkCallingConvention(CallingConv CC) const {
switch (CC) {
default:
return CCCR_Warning;
case CC_C:
return CCCR_OK;
}
}
enum CallingConvKind {
CCK_Default,
CCK_ClangABI4OrPS4,
CCK_MicrosoftWin64
};
virtual CallingConvKind getCallingConvKind(bool ClangABICompat4) const;
/// Controls if __builtin_longjmp / __builtin_setjmp can be lowered to
/// llvm.eh.sjlj.longjmp / llvm.eh.sjlj.setjmp.
virtual bool hasSjLjLowering() const {
return false;
}
/// Check if the target supports CFProtection branch.
virtual bool
checkCFProtectionBranchSupported(DiagnosticsEngine &Diags) const;
/// Check if the target supports CFProtection branch.
virtual bool
checkCFProtectionReturnSupported(DiagnosticsEngine &Diags) const;
/// Whether target allows to overalign ABI-specified preferred alignment
virtual bool allowsLargerPreferedTypeAlignment() const { return true; }
/// Whether target defaults to the `power` alignment rules of AIX.
virtual bool defaultsToAIXPowerAlignment() const { return false; }
/// Set supported OpenCL extensions and optional core features.
virtual void setSupportedOpenCLOpts() {}
/// Set supported OpenCL extensions as written on command line
virtual void setOpenCLExtensionOpts() {
for (const auto &Ext : getTargetOpts().OpenCLExtensionsAsWritten) {
getTargetOpts().SupportedOpenCLOptions.support(Ext);
}
}
/// Get supported OpenCL extensions and optional core features.
OpenCLOptions &getSupportedOpenCLOpts() {
return getTargetOpts().SupportedOpenCLOptions;
}
/// Get const supported OpenCL extensions and optional core features.
const OpenCLOptions &getSupportedOpenCLOpts() const {
return getTargetOpts().SupportedOpenCLOptions;
}
/// Get address space for OpenCL type.
virtual LangAS getOpenCLTypeAddrSpace(OpenCLTypeKind TK) const;
/// \returns Target specific vtbl ptr address space.
virtual unsigned getVtblPtrAddressSpace() const {
return 0;
}
/// \returns If a target requires an address within a target specific address
/// space \p AddressSpace to be converted in order to be used, then return the
/// corresponding target specific DWARF address space.
///
/// \returns Otherwise return None and no conversion will be emitted in the
/// DWARF.
virtual Optional<unsigned> getDWARFAddressSpace(unsigned AddressSpace) const {
return None;
}
/// \returns The version of the SDK which was used during the compilation if
/// one was specified, or an empty version otherwise.
const llvm::VersionTuple &getSDKVersion() const {
return getTargetOpts().SDKVersion;
}
/// Check the target is valid after it is fully initialized.
virtual bool validateTarget(DiagnosticsEngine &Diags) const {
return true;
}
virtual void setAuxTarget(const TargetInfo *Aux) {}
/// Whether target allows debuginfo types for decl only variables.
virtual bool allowDebugInfoForExternalVar() const { return false; }
protected:
/// Copy type and layout related info.
void copyAuxTarget(const TargetInfo *Aux);
virtual uint64_t getPointerWidthV(unsigned AddrSpace) const {
return PointerWidth;
}
virtual uint64_t getPointerAlignV(unsigned AddrSpace) const {
return PointerAlign;
}
virtual enum IntType getPtrDiffTypeV(unsigned AddrSpace) const {
return PtrDiffType;
}
virtual ArrayRef<const char *> getGCCRegNames() const = 0;
virtual ArrayRef<GCCRegAlias> getGCCRegAliases() const = 0;
virtual ArrayRef<AddlRegName> getGCCAddlRegNames() const {
return None;
}
private:
// Assert the values for the fractional and integral bits for each fixed point
// type follow the restrictions given in clause 6.2.6.3 of N1169.
void CheckFixedPointBits() const;
};
} // end namespace clang
#endif
| 37.518987 | 86 | 0.708058 | [
"object",
"vector"
] |
7ff8a88daad73ecd206ab053815b01297cc0bdd3 | 8,717 | h | C | RadarApi/include/EndpointRadarErrorCodes.h | toschoch/cpp-radar-logger | 4a7f6c255c34384db9589d3f0fd7f1a879d80974 | [
"MIT"
] | 2 | 2021-04-16T06:53:50.000Z | 2022-03-10T19:53:46.000Z | RadarApi/include/EndpointRadarErrorCodes.h | toschoch/cpp-radar-logger | 4a7f6c255c34384db9589d3f0fd7f1a879d80974 | [
"MIT"
] | null | null | null | RadarApi/include/EndpointRadarErrorCodes.h | toschoch/cpp-radar-logger | 4a7f6c255c34384db9589d3f0fd7f1a879d80974 | [
"MIT"
] | 1 | 2021-11-16T06:23:04.000Z | 2021-11-16T06:23:04.000Z | /**
* \file EndpointRadarErrorCodes.h
*
* \brief This file defines the status codes of the radar endpoints.
*
* The modules EndpointRadarXXX share the same status codes. This files lists
* the known error codes.
*/
/* ===========================================================================
** Copyright (C) 2016-2019 Infineon Technologies AG
** All rights reserved.
** ===========================================================================
**
** ===========================================================================
** This document contains proprietary information of Infineon Technologies AG.
** Passing on and copying of this document, and communication of its contents
** is not permitted without Infineon's prior written authorisation.
** ===========================================================================
*/
#ifndef ENDPOINTRADARSTATUSCODES_H_INCLUDED
#define ENDPOINTRADARSTATUSCODES_H_INCLUDED
/*
==============================================================================
1. INCLUDE FILES
==============================================================================
*/
/* Enable C linkage if header is included in C++ files */
#ifdef __cplusplus
extern "C"
{
#endif /* __cplusplus */
/**
* \defgroup EndpointRadarErrorCodes EndpointRadarErrorCodes
*
* \brief An endpoint of radar type can return of these status codes.
*
* @{
*/
/*
==============================================================================
2. DEFINITIONS
==============================================================================
*/
/**
* The requested operation can't be executed. A possible reason is that a
* certain test mode is activated or the automatic trigger is active.
*/
#define EP_RADAR_ERR_BUSY 0x0002
/**
* The requested operation is not supported by the currently active mode of
*operation.
*/
#define EP_RADAR_ERR_INCOMPATIBLE_MODE 0x0003
/**
* A timeout has occurred while waiting for a data frame to be acquired.
*/
#define EP_RADAR_ERR_TIME_OUT 0x0004
/**
* The requested time interval between two frames is out of range.
*/
#define EP_RADAR_ERR_UNSUPPORTED_FRAME_INTERVAL 0x0005
/**
* One or more of the selected RX or TX antennas is not present on the device.
*/
#define EP_RADAR_ERR_ANTENNA_DOES_NOT_EXIST 0x0006
/**
* The requested temperature sensor does not exist.
*/
#define EP_RADAR_ERR_SENSOR_DOES_NOT_EXIST 0x0007
/**
* The combination of chirps per frame, samples per chirp and number of
* antennas is not supported by the driver. A possible reason is the limit of
* the driver internal data memory.
*/
#define EP_RADAR_ERR_UNSUPPORTED_FRAME_FORMAT 0x0008
/**
* The specified RF frequency is not in the supported range of the device.
*/
#define EP_RADAR_ERR_FREQUENCY_OUT_OF_RANGE 0x0009
/**
* The specified transmission power is not in the valid range of
* 0...max_tx_power (see \ref Device_Info_t).
*/
#define EP_RADAR_ERR_POWER_OUT_OF_RANGE 0x000A
/**
* The device is not capable to capture the requested part of the complex
*signal (see \ref Device_Info_t).
*/
#define EP_RADAR_ERR_UNAVAILABLE_SIGNAL_PART 0x000B
/**
* The specified FMCW ramp direction is not supported by the device. */
#define EP_RADAR_ERR_UNSUPPORTED_DIRECTION 0x0020
/**
* The specified sampling rate is out of range.
*/
#define EP_RADAR_ERR_SAMPLERATE_OUT_OF_RANGE 0x0050
/**
* The specified sample resolution is out of range.
*/
#define EP_RADAR_ERR_UNSUPPORTED_RESOLUTION 0x0051
/**
* The specified TX mode is not supported by the device.
*/
#define EP_RADAR_ERR_UNSUPPORTED_TX_MODE 0x0100
/**
* The specified high pass filter gain is not defined.
*/
#define EP_RADAR_ERR_UNSUPPORTED_HP_GAIN 0x0101
/**
* The specified high pass filter cut-off frequency is not defined.
*/
#define EP_RADAR_ERR_UNSUPPORTED_HP_CUTOFF 0x0102
/**
* The specified gain adjustment setting is not defined.
*/
#define EP_RADAR_ERR_UNSUPPORTED_VGA_GAIN 0x0103
/**
* The specified reset timer period is out of range.
*/
#define EP_RADAR_ERR_RESET_TIMER_OUT_OF_RANGE 0x0104
/**
* The specified charge pump current is out of range.
*/
#define EP_RADAR_ERR_INVALID_CHARGE_PUMP_CURRENT 0x0105
/**
* The specified charge pump pulse width is not defined.
*/
#define EP_RADAR_ERR_INVALID_PULSE_WIDTH 0x0106
/**
* The specified modulator order is not defined.
*/
#define EP_RADAR_ERR_INVALID_FRAC_ORDER 0x0107
/**
* The specified dither mode is not defined.
*/
#define EP_RADAR_ERR_INVALID_DITHER_MODE 0x0108
/**
* The specified cycle slip reduction mode is not defined.
*/
#define EP_RADAR_ERR_INVALID_CYCLE_SLIP_MODE 0x0109
/**
* The calibration of phase settings or base band chain did not succeed.
*/
#define EP_RADAR_ERR_CALIBRATION_FAILED 0x010A
/**
* The provided oscillator phase setting is not valid. It's forbidden to
* disable both phase modulators.
*/
#define EP_RADAR_ERR_INVALID_PHASE_SETTING 0x010B
/**
* The specified ADC tracking mode is not supported by the device.
*/
#define EP_RADAR_ERR_UNDEFINED_TRACKING_MODE 0x0110
/**
* The specified ADC sampling time is not supported by the device.
*/
#define EP_RADAR_ERR_UNDEFINED_ADC_SAMPLE_TIME 0x0111
/**
* The specified ADC oversampling factors is not supported by the device.
*/
#define EP_RADAR_ERR_UNDEFINED_ADC_OVERSAMPLING 0x0112
/**
* The specified shape sequence is not supported. There must not be a gap
* between used shapes.
*/
#define EP_RADAR_ERR_NONCONTINUOUS_SHAPE_SEQUENCE 0x0120
/**
* One or more specified number of repetition is not supported. Only powers of
* two are allowed. Total numbers of shape groups must not exceed 4096.
*/
#define EP_RADAR_ERR_UNSUPPORTED_NUM_REPETITIONS 0x0121
/**
* One or more of the specified power modes is not supported.
*/
#define EP_RADAR_ERR_UNSUPPORTED_POWER_MODE 0x0122
/**
* One or more of the specified post shape / post shape set delays is not
* supported.
*/
#define EP_RADAR_ERR_POST_DELAY_OUT_OF_RANGE 0x0123
/**
* The specified number of frames is out of range.
*/
#define EP_RADAR_ERR_NUM_FRAMES_OUT_OF_RANGE 0x0124
/**
* The requested shape does not exist.
*/
#define EP_RADAR_ERR_SHAPE_NUMBER_OUT_OF_RANGE 0x0125
/**
* The specified pre-chirp delay is out of range.
*/
#define EP_RADAR_ERR_PRECHIRPDELAY_OUT_OF_RANGE 0x0126
/**
* The specified post-chirp delay is out of range.
*/
#define EP_RADAR_ERR_POSTCHIRPDELAY_OUT_OF_RANGE 0x0127
/**
* The specified PA delay is out of range.
*/
#define EP_RADAR_ERR_PADELAY_OUT_OF_RANGE 0x0128
/**
* The specified ADC delay is out of range.
*/
#define EP_RADAR_ERR_ADCDELAY_OUT_OF_RANGE 0x0129
/**
* The specified wake up time is out of range.
*/
#define EP_RADAR_ERR_WAKEUPTIME_OUT_OF_RANGE 0x012A
/**
* The specified PLL settle time is out of range.
*/
#define EP_RADAR_ERR_SETTLETIME_OUT_OF_RANGE 0x012B
/**
* The specified FIFO slice size is not supported.
*/
#define EP_RADAR_ERR_UNSUPPORTED_FIFO_SLICE_SIZE 0x012C
/**
* The FIFO slice can't be released. It has not been used.
*/
#define EP_RADAR_ERR_SLICES_NOT_RELEASABLE 0x012D
/**
* A FIFO overflow has occurred. A reset is needed.
*/
#define EP_RADAR_ERR_FIFO_OVERFLOW 0x012E
/**
* No memory buffer has been provided to store the radar data.
*/
#define EP_RADAR_ERR_NO_MEMORY 0x012F
/**
* The received SPI data sequence does not match the expected one.
*/
#define EP_RADAR_ERR_SPI_TEST_FAILED 0x0130
/**
* The chip could not be programmed.
*/
#define EP_RADAR_ERR_CHIP_SETUP_FAILED 0x0131
/**
* The On-Chip FIFO memory test faild.
*/
#define EP_RADAR_ERR_MEMORY_TEST_FAILED 0x0132
/**
* The Device is not supported by the driver.
*/
#define EP_RADAR_ERR_DEVICE_NOT_SUPPORTED 0x0133
/**
* The requested feature is not supported by the connected device.
*/
#define EP_RADAR_ERR_FEATURE_NOT_SUPPORTED 0x0134
/**
* The PA Delay is shorter than the pre chirp delay.
*/
#define EP_RADAR_ERR_PRECHIRP_EXCEEDS_PADELAY 0x0135
/**
* The register selected for override does not exist.
*/
#define EP_RADAR_ERR_REGISTER_OUT_OF_RANGE 0x0136
/** @} */
/* --- Close open blocks -------------------------------------------------- */
/* Disable C linkage for C++ files */
#ifdef __cplusplus
} /* extern "C" */
#endif /* __cplusplus */
/* End of include guard */
#endif /* ENDPOINTRADARSTATUSCODES_H_INCLUDED */
/* --- End of File -------------------------------------------------------- */
| 26.57622 | 78 | 0.667317 | [
"shape"
] |
7ff9c225c6b4ba67446b298580c3dce671fc6ef5 | 666 | c | C | kem/kem_hqc128_1/ref/gf2x.c | scarv/pq-riscv | 7372af824abe4a71ca6745adc21ddcc57527b0b5 | [
"OpenSSL"
] | 1 | 2019-05-02T17:07:19.000Z | 2019-05-02T17:07:19.000Z | kem/kem_hqc128_1/ref/gf2x.c | scarv/pq-riscv | 7372af824abe4a71ca6745adc21ddcc57527b0b5 | [
"OpenSSL"
] | null | null | null | kem/kem_hqc128_1/ref/gf2x.c | scarv/pq-riscv | 7372af824abe4a71ca6745adc21ddcc57527b0b5 | [
"OpenSSL"
] | null | null | null | /**
* \file gf2x.cpp
* \brief Implementation of multiplication of two polynomials
*/
#include <stdint.h>
#include <stdio.h>
/**
* \fn void ntl_cyclic_product(uint8_t*o, const uint8_t* v1, const uint8_t* v2)
* \brief Multiply two vectors
*
* Vector multiplication is defined as polynomial multiplication performed modulo the polynomial \f$ X^n - 1\f$.
*
* \param[out] o Product of <b>v1</b> and <b>v2</b>
* \param[in] v1 Pointer to the first vector
* \param[in] v2 Pointer to the second vector
*/
void ntl_cyclic_product(uint8_t*o, const uint8_t* v1, const uint8_t* v2) {
printf("%s:%d not implemented\n",__FILE__,__LINE__);
}
| 30.272727 | 113 | 0.677177 | [
"vector"
] |
7ffef48b46048dd3c285c4ab3e1c6d510792657a | 7,420 | h | C | chrome/common/net/gaia/google_service_auth_error.h | Scopetta197/chromium | b7bf8e39baadfd9089de2ebdc0c5d982de4a9820 | [
"BSD-3-Clause"
] | 212 | 2015-01-31T11:55:58.000Z | 2022-02-22T06:35:11.000Z | chrome/common/net/gaia/google_service_auth_error.h | Scopetta197/chromium | b7bf8e39baadfd9089de2ebdc0c5d982de4a9820 | [
"BSD-3-Clause"
] | 5 | 2015-03-27T14:29:23.000Z | 2019-09-25T13:23:12.000Z | chrome/common/net/gaia/google_service_auth_error.h | Scopetta197/chromium | b7bf8e39baadfd9089de2ebdc0c5d982de4a9820 | [
"BSD-3-Clause"
] | 221 | 2015-01-07T06:21:24.000Z | 2022-02-11T02:51:12.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.
// A GoogleServiceAuthError is immutable, plain old data representing an
// error from an attempt to authenticate with a Google service.
// It could be from Google Accounts itself, or any service using Google
// Accounts (e.g expired credentials). It may contain additional data such as
// captcha or OTP challenges.
// A GoogleServiceAuthError without additional data is just a State, defined
// below. A case could be made to have this relation implicit, to allow raising
// error events concisely by doing OnAuthError(GoogleServiceAuthError::NONE),
// for example. But the truth is this class is ever so slightly more than a
// transparent wrapper around 'State' due to additional Captcha data
// (e.g consider operator=), and this would violate the style guide. Thus,
// you must explicitly use the constructor when all you have is a State.
// The good news is the implementation nests the enum inside a class, so you
// may forward declare and typedef GoogleServiceAuthError to something shorter
// in the comfort of your own translation unit.
#ifndef CHROME_COMMON_NET_GAIA_GOOGLE_SERVICE_AUTH_ERROR_H_
#define CHROME_COMMON_NET_GAIA_GOOGLE_SERVICE_AUTH_ERROR_H_
#pragma once
#include <string>
#include "googleurl/src/gurl.h"
namespace base {
class DictionaryValue;
}
class GoogleServiceAuthError {
public:
//
// These enumerations are referenced by integer value in HTML login code.
// Do not change the numeric values.
//
enum State {
// The user is authenticated.
NONE = 0,
// The credentials supplied to GAIA were either invalid, or the locally
// cached credentials have expired.
INVALID_GAIA_CREDENTIALS = 1,
// The GAIA user is not authorized to use the service.
USER_NOT_SIGNED_UP = 2,
// Could not connect to server to verify credentials. This could be in
// response to either failure to connect to GAIA or failure to connect to
// the service needing GAIA tokens during authentication.
CONNECTION_FAILED = 3,
// The user needs to satisfy a CAPTCHA challenge to unlock their account.
// If no other information is available, this can be resolved by visiting
// https://www.google.com/accounts/DisplayUnlockCaptcha. Otherwise,
// captcha() will provide details about the associated challenge.
CAPTCHA_REQUIRED = 4,
// The user account has been deleted.
ACCOUNT_DELETED = 5,
// The user account has been disabled.
ACCOUNT_DISABLED = 6,
// The service is not available; try again later.
SERVICE_UNAVAILABLE = 7,
// The password is valid but we need two factor to get a token.
TWO_FACTOR = 8,
// The requestor of the authentication step cancelled the request
// prior to completion.
REQUEST_CANCELED = 9,
// The user has provided a HOSTED account, when this service requires
// a GOOGLE account.
HOSTED_NOT_ALLOWED = 10,
};
// Additional data for CAPTCHA_REQUIRED errors.
struct Captcha {
Captcha();
Captcha(const std::string& token,
const GURL& audio,
const GURL& img,
const GURL& unlock,
int width,
int height);
~Captcha();
// For test only.
bool operator==(const Captcha &b) const;
std::string token; // Globally identifies the specific CAPTCHA challenge.
GURL audio_url; // The CAPTCHA audio to use instead of image.
GURL image_url; // The CAPTCHA image to show the user.
GURL unlock_url; // Pretty unlock page containing above captcha.
int image_width; // Width of captcha image.
int image_height; // Height of capture image.
};
// Additional data for TWO_FACTOR errors.
struct SecondFactor {
SecondFactor();
SecondFactor(const std::string& token,
const std::string& prompt,
const std::string& alternate,
int length);
~SecondFactor();
// For test only.
bool operator==(const SecondFactor &b) const;
// Globally identifies the specific second-factor challenge.
std::string token;
// Localised prompt text, eg Enter the verification code sent to your
// phone number ending in XXX.
std::string prompt_text;
// Localized text describing an alternate option, eg Get a verification
// code in a text message.
std::string alternate_text;
// Character length for the challenge field.
int field_length;
};
// For test only.
bool operator==(const GoogleServiceAuthError &b) const;
// Construct a GoogleServiceAuthError from a State with no additional data.
explicit GoogleServiceAuthError(State s);
// Construct a GoogleServiceAuthError from a network error.
// It will be created with CONNECTION_FAILED set.
static GoogleServiceAuthError FromConnectionError(int error);
// Construct a CAPTCHA_REQUIRED error with CAPTCHA challenge data from the
// the ClientLogin endpoint.
// TODO(rogerta): once ClientLogin is no longer used, may be able to get
// rid of this function.
static GoogleServiceAuthError FromClientLoginCaptchaChallenge(
const std::string& captcha_token,
const GURL& captcha_image_url,
const GURL& captcha_unlock_url);
// Construct a CAPTCHA_REQUIRED error with CAPTCHA challenge data from the
// ClientOAuth endpoint.
static GoogleServiceAuthError FromCaptchaChallenge(
const std::string& captcha_token,
const GURL& captcha_audio_url,
const GURL& captcha_image_url,
int image_width,
int image_height);
// Construct a TWO_FACTOR error with second-factor challenge data.
static GoogleServiceAuthError FromSecondFactorChallenge(
const std::string& captcha_token,
const std::string& prompt_text,
const std::string& alternate_text,
int field_length);
// Provided for convenience for clients needing to reset an instance to NONE.
// (avoids err_ = GoogleServiceAuthError(GoogleServiceAuthError::NONE), due
// to explicit class and State enum relation. Note: shouldn't be inlined!
static GoogleServiceAuthError None();
// The error information.
State state() const;
const Captcha& captcha() const;
const SecondFactor& second_factor() const;
int network_error() const;
const std::string& token() const;
// Returns info about this object in a dictionary. Caller takes
// ownership of returned dictionary.
base::DictionaryValue* ToValue() const;
// Returns a message describing the error.
std::string ToString() const;
private:
GoogleServiceAuthError(State s, int error);
GoogleServiceAuthError(State s, const std::string& captcha_token,
const GURL& captcha_audio_url,
const GURL& captcha_image_url,
const GURL& captcha_unlock_url,
int image_width,
int image_height);
GoogleServiceAuthError(State s, const std::string& captcha_token,
const std::string& prompt_text,
const std::string& alternate_text,
int field_length);
State state_;
Captcha captcha_;
SecondFactor second_factor_;
int network_error_;
};
#endif // CHROME_COMMON_NET_GAIA_GOOGLE_SERVICE_AUTH_ERROR_H_
| 36.551724 | 79 | 0.705391 | [
"object"
] |
3d017d1f5dba2abb60c5da4f514a9435ab892673 | 7,467 | c | C | lib/sw_apps/freertos_lwip_tcp_perf_server/src/freertos_tcp_perf_server.c | erique/embeddedsw | 4b5fd15c71405844e03f2c276daa38cfcbb6459b | [
"BSD-2-Clause",
"MIT"
] | 595 | 2015-02-03T15:07:36.000Z | 2022-03-31T18:21:23.000Z | lib/sw_apps/freertos_lwip_tcp_perf_server/src/freertos_tcp_perf_server.c | Xilinx/embeddedsw-experimental-dt-support | 329bf8fa54110034c8436d0b3b4aa40e8a56b02d | [
"BSD-2-Clause",
"MIT"
] | 144 | 2016-01-08T17:56:37.000Z | 2022-03-31T13:23:52.000Z | lib/sw_apps/freertos_lwip_tcp_perf_server/src/freertos_tcp_perf_server.c | Xilinx/embeddedsw-experimental-dt-support | 329bf8fa54110034c8436d0b3b4aa40e8a56b02d | [
"BSD-2-Clause",
"MIT"
] | 955 | 2015-03-30T00:54:27.000Z | 2022-03-31T11:32:23.000Z | /*
* Copyright (C) 2018 - 2019 Xilinx, Inc.
* 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. 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.
*
*/
#include "freertos_tcp_perf_server.h"
extern struct netif server_netif;
static struct perf_stats server;
/* Interval time in seconds */
#define REPORT_INTERVAL_TIME (INTERIM_REPORT_INTERVAL * 1000)
void print_app_header(void)
{
xil_printf("TCP server listening on port %d\r\n",
TCP_CONN_PORT);
#if LWIP_IPV6==1
xil_printf("On Host: Run $iperf -V -c %s%%<interface> -i %d -t 300 -w 2M\r\n",
inet6_ntoa(server_netif.ip6_addr[0]),
INTERIM_REPORT_INTERVAL);
#else
xil_printf("On Host: Run $iperf -c %s -i %d -t 300 -w 2M\r\n",
inet_ntoa(server_netif.ip_addr),
INTERIM_REPORT_INTERVAL);
#endif /* LWIP_IPV6 */
}
static void print_tcp_conn_stats(int sock)
{
#if LWIP_IPV6==1
struct sockaddr_in6 local, remote;
#else
struct sockaddr_in local, remote;
#endif /* LWIP_IPV6 */
int size;
size = sizeof(local);
getsockname(sock, (struct sockaddr *)&local, (socklen_t *)&size);
getpeername(sock, (struct sockaddr *)&remote, (socklen_t *)&size);
#if LWIP_IPV6==1
xil_printf("[%3d] local %s port %d connected with ", server.client_id,
inet6_ntoa(local.sin6_addr), ntohs(local.sin6_port));
xil_printf("%s port %d\r\n", inet6_ntoa(remote.sin6_addr),
ntohs(local.sin6_port));
#else
xil_printf("[%3d] local %s port %d connected with ", server.client_id,
inet_ntoa(local.sin_addr), ntohs(local.sin_port));
xil_printf("%s port %d\r\n", inet_ntoa(remote.sin_addr),
ntohs(local.sin_port));
#endif /* LWIP_IPV6 */
xil_printf("[ ID] Interval Transfer Bandwidth\n\r");
}
static void stats_buffer(char* outString, double data, enum measure_t type)
{
int conv = KCONV_UNIT;
const char *format;
double unit = 1024.0;
if (type == SPEED)
unit = 1000.0;
while (data >= unit && conv <= KCONV_GIGA) {
data /= unit;
conv++;
}
/* Fit data in 4 places */
if (data < 9.995) { /* 9.995 rounded to 10.0 */
format = "%4.2f %c"; /* #.## */
} else if (data < 99.95) { /* 99.95 rounded to 100 */
format = "%4.1f %c"; /* ##.# */
} else {
format = "%4.0f %c"; /* #### */
}
sprintf(outString, format, data, kLabel[conv]);
}
/* The report function of a TCP server session */
static void tcp_conn_report(u64_t diff, enum report_type report_type)
{
u64_t total_len;
double duration, bandwidth = 0;
char data[16], perf[16], time[64];
if (report_type == INTER_REPORT) {
total_len = server.i_report.total_bytes;
} else {
server.i_report.last_report_time = 0;
total_len = server.total_bytes;
}
/* Converting duration from milliseconds to secs,
* and bandwidth to bits/sec .
*/
duration = diff / 1000.0; /* secs */
if (duration)
bandwidth = (total_len / duration) * 8.0;
stats_buffer(data, total_len, BYTES);
stats_buffer(perf, bandwidth, SPEED);
/* On 32-bit platforms, xil_printf is not able to print
* u64_t values, so converting these values in strings and
* displaying results
*/
sprintf(time, "%4.1f-%4.1f sec",
(double)server.i_report.last_report_time,
(double)(server.i_report.last_report_time + duration));
xil_printf("[%3d] %s %sBytes %sbits/sec\n\r", server.client_id,
time, data, perf);
if (report_type == INTER_REPORT)
server.i_report.last_report_time += duration;
}
/* thread spawned for each connection */
void tcp_recv_perf_traffic(void *p)
{
char recv_buf[RECV_BUF_SIZE];
int read_bytes;
int sock = *((int *)p);
server.start_time = sys_now();
server.client_id++;
server.i_report.last_report_time = 0;
server.i_report.start_time = 0;
server.i_report.total_bytes = 0;
server.total_bytes = 0;
print_tcp_conn_stats(sock);
while (1) {
/* read a max of RECV_BUF_SIZE bytes from socket */
if ((read_bytes = lwip_recvfrom(sock, recv_buf, RECV_BUF_SIZE,
0, NULL, NULL)) < 0) {
u64_t now = sys_now();
u64_t diff_ms = now - server.start_time;
tcp_conn_report(diff_ms, TCP_ABORTED_REMOTE);
break;
}
/* break if client closed connection */
if (read_bytes == 0) {
u64_t now = sys_now();
u64_t diff_ms = now - server.start_time;
tcp_conn_report(diff_ms, TCP_DONE_SERVER);
xil_printf("TCP test passed Successfully\n\r");
break;
}
if (REPORT_INTERVAL_TIME) {
u64_t now = sys_now();
server.i_report.total_bytes += read_bytes;
if (server.i_report.start_time) {
u64_t diff_ms = now - server.i_report.start_time;
if (diff_ms >= REPORT_INTERVAL_TIME) {
tcp_conn_report(diff_ms, INTER_REPORT);
server.i_report.start_time = 0;
server.i_report.total_bytes = 0;
}
} else {
server.i_report.start_time = now;
}
}
/* Record total bytes for final report */
server.total_bytes += read_bytes;
}
/* close connection */
close(sock);
vTaskDelete(NULL);
}
void start_application(void)
{
int sock, new_sd;
#if LWIP_IPV6==1
struct sockaddr_in6 address, remote;
#else
struct sockaddr_in address, remote;
#endif /* LWIP_IPV6 */
int size;
/* set up address to connect to */
memset(&address, 0, sizeof(address));
#if LWIP_IPV6==1
if ((sock = lwip_socket(AF_INET6, SOCK_STREAM, 0)) < 0) {
xil_printf("TCP server: Error creating Socket\r\n");
return;
}
address.sin6_family = AF_INET6;
address.sin6_port = htons(TCP_CONN_PORT);
address.sin6_len = sizeof(address);
#else
if ((sock = lwip_socket(AF_INET, SOCK_STREAM, 0)) < 0) {
xil_printf("TCP server: Error creating Socket\r\n");
return;
}
address.sin_family = AF_INET;
address.sin_port = htons(TCP_CONN_PORT);
address.sin_addr.s_addr = INADDR_ANY;
#endif /* LWIP_IPV6 */
if (bind(sock, (struct sockaddr *)&address, sizeof (address)) < 0) {
xil_printf("TCP server: Unable to bind to port %d\r\n",
TCP_CONN_PORT);
close(sock);
return;
}
if (listen(sock, 1) < 0) {
xil_printf("TCP server: tcp_listen failed\r\n");
close(sock);
return;
}
size = sizeof(remote);
while (1) {
if ((new_sd = accept(sock, (struct sockaddr *)&remote,
(socklen_t *)&size)) > 0)
sys_thread_new("TCP_recv_perf thread",
tcp_recv_perf_traffic, (void*)&new_sd,
TCP_SERVER_THREAD_STACKSIZE,
DEFAULT_THREAD_PRIO);
}
}
| 29.513834 | 83 | 0.699076 | [
"3d"
] |
3d0484252773a9803e44141110347ad774b19178 | 3,765 | h | C | shared_include/image/filter/diffusion/StructureTensorField.h | ahewer/mri-shape-tools | 4268499948f1330b983ffcdb43df62e38ca45079 | [
"MIT"
] | null | null | null | shared_include/image/filter/diffusion/StructureTensorField.h | ahewer/mri-shape-tools | 4268499948f1330b983ffcdb43df62e38ca45079 | [
"MIT"
] | 2 | 2017-05-29T09:43:01.000Z | 2017-05-29T09:50:05.000Z | shared_include/image/filter/diffusion/StructureTensorField.h | ahewer/mri-shape-tools | 4268499948f1330b983ffcdb43df62e38ca45079 | [
"MIT"
] | 4 | 2017-05-17T11:56:02.000Z | 2022-03-05T09:12:24.000Z | #ifndef __STRUCTURE_TENSOR_FIELD_H__
#define __STRUCTURE_TENSOR_FIELD_H__
#include <armadillo>
#include "image/filter/GaussianFilter.h"
#include "image/filter/diffusion/DiffusionSettings.h"
#include "image/ImageAccess.h"
#include "image/ImageCreate.h"
#include "image/ImageCalculus.h"
#include "image/ImageData.h"
#include "image/ImageMirror.h"
class StructureTensorField{
public:
StructureTensorField(
const ImageData& imageData,
const DiffusionSettings& settings
) :
// dimensions
nx(imageData.nx),
ny(imageData.ny),
nz(imageData.nz),
// structure tensor access
J11(this->J11Data),
J22(this->J22Data),
J33(this->J33Data),
J12(this->J12Data),
J13(this->J13Data),
J23(this->J23Data),
// image data
imageData(imageData),
// diffusion settings
settings(settings)
{
init_structure_tensors();
}
const double& get_hx() const {
return
( this->settings.useDifferentSpacings )? settings.hx: this->imageData.hx;
}
const double& get_hy() const {
return
( this->settings.useDifferentSpacings )? settings.hy: this->imageData.hy;
}
const double& get_hz() const {
return
( this->settings.useDifferentSpacings )? settings.hz: this->imageData.hz;
}
void update() {
// create copy
ImageData copyData = this->imageData;
// smooth image
GaussianFilter(copyData, this->settings.presmoothSigma).apply();
// mirror boundaries
ImageMirror(copyData).all();
// create object for performing calculus operations
ImageCalculus copy(copyData);
for(int i = 0; i < this->nx; ++i) {
for(int j = 0; j < this->ny; ++j) {
for(int k = 0; k < this->nz; ++k) {
arma::mat structureTensor = copy.structure_tensor(i, j, k);
J11.at_grid(i, j, k) = structureTensor.at(0, 0);
J22.at_grid(i, j, k) = structureTensor.at(1, 1);
J33.at_grid(i, j, k) = structureTensor.at(2, 2);
J12.at_grid(i, j, k) = structureTensor.at(0, 1);
J13.at_grid(i, j, k) = structureTensor.at(0, 2);
J23.at_grid(i, j, k) = structureTensor.at(1, 2);
} // end for k
} // end for j
} // end for i
// smooth each structure tensor entry
GaussianFilter(this->J11Data, this->settings.integrationRho).apply();
GaussianFilter(this->J22Data, this->settings.integrationRho).apply();
GaussianFilter(this->J33Data, this->settings.integrationRho).apply();
GaussianFilter(this->J12Data, this->settings.integrationRho).apply();
GaussianFilter(this->J13Data, this->settings.integrationRho).apply();
GaussianFilter(this->J23Data, this->settings.integrationRho).apply();
} // end update_structure_tensors
const int& nx;
const int& ny;
const int& nz;
ImageAccess J11;
ImageAccess J22;
ImageAccess J33;
ImageAccess J12;
ImageAccess J13;
ImageAccess J23;
private:
void init_structure_tensors() {
ImageCreate(this->J11Data).with_dimension(this->nx, this->ny, this->nz).empty_image();
ImageCreate(this->J22Data).with_dimension(this->nx, this->ny, this->nz).empty_image();
ImageCreate(this->J33Data).with_dimension(this->nx, this->ny, this->nz).empty_image();
ImageCreate(this->J12Data).with_dimension(this->nx, this->ny, this->nz).empty_image();
ImageCreate(this->J13Data).with_dimension(this->nx, this->ny, this->nz).empty_image();
ImageCreate(this->J23Data).with_dimension(this->nx, this->ny, this->nz).empty_image();
}
const ImageData& imageData;
const DiffusionSettings& settings;
ImageData J11Data;
ImageData J12Data;
ImageData J13Data;
ImageData J22Data;
ImageData J23Data;
ImageData J33Data;
};
#endif
| 26.145833 | 90 | 0.660558 | [
"object"
] |
3d060c9c4e0931edc733e59033ac8af6010953e2 | 10,124 | h | C | Jit/pyjit.h | isabella232/cinder-1 | 428669a9a925287f192ab361226e5a8ca3fb74d9 | [
"CNRI-Python-GPL-Compatible"
] | null | null | null | Jit/pyjit.h | isabella232/cinder-1 | 428669a9a925287f192ab361226e5a8ca3fb74d9 | [
"CNRI-Python-GPL-Compatible"
] | null | null | null | Jit/pyjit.h | isabella232/cinder-1 | 428669a9a925287f192ab361226e5a8ca3fb74d9 | [
"CNRI-Python-GPL-Compatible"
] | null | null | null | // Copyright (c) Facebook, Inc. and its affiliates. (http://www.facebook.com)
#pragma once
#include "Python.h"
#include "frameobject.h"
#include "genobject.h"
#include "Jit/pyjit_result.h"
#include "Jit/pyjit_typeslots.h"
// Offset of the state field in jit::GenFooterData for fast access from C code.
// This value is verified by static_assert in runtime.h.
#define _PY_GEN_JIT_DATA_STATE_OFFSET 24
#ifndef Py_LIMITED_API
#ifdef __cplusplus
extern "C" {
#endif
enum InitStateJitConfig { JIT_NOT_INITIALIZED, JIT_INITIALIZED, JIT_FINALIZED };
enum FrameModeJitConfig { PY_FRAME = 0, SHADOW_FRAME };
/* Accessors for internal jit config */
PyAPI_FUNC(int) _PyJIT_IsJitConfigAllow_jit_list_wildcards(void);
PyAPI_FUNC(int) _PyJIT_IsJitConfigCompile_all_static_functions(void);
PyAPI_FUNC(size_t) _PyJIT_GetJitConfigBatch_compile_workers(void);
PyAPI_FUNC(int) _PyJIT_IsJitConfigMultithreaded_compile_test(void);
/*
* Offset of the code object within a jit::CodeRuntime
*/
PyAPI_DATA(int64_t) __strobe_CodeRuntime_py_code;
/*
* This defines the global public API for the JIT that is consumed by the
* runtime.
*
* These methods assume that the GIL is held unless it is explicitly stated
* otherwise.
*/
/*
* Initialize any global state required by the JIT.
*
* This must be called before attempting to use the JIT.
*
* Returns 0 on success or -1 on error.
*/
PyAPI_FUNC(int) _PyJIT_Initialize(void);
/*
* Enable the global JIT.
*
* _PyJIT_Initialize must be called before calling this.
*
* Returns 1 if the JIT is enabled and 0 otherwise.
*/
PyAPI_FUNC(int) _PyJIT_Enable(void);
/*
* Disable the global JIT.
*/
PyAPI_FUNC(void) _PyJIT_Disable(void);
/*
* Returns 1 if JIT compilation is enabled and 0 otherwise.
*/
PyAPI_FUNC(int) _PyJIT_IsEnabled(void);
/*
* After-fork callback for child processes. Performs any cleanup necessary for
* per-process state, including handling of Linux perf pid maps.
*/
PyAPI_FUNC(void) _PyJIT_AfterFork_Child(void);
/*
* Enable type slot specialization.
*/
PyAPI_FUNC(int) _PyJIT_EnableTypeSlots(void);
/*
* Returns 1 if type slot specialization is enabled and 0 otherwise.
*/
PyAPI_FUNC(int) _PyJIT_AreTypeSlotsEnabled(void);
/*
* JITs slot functions for the type object, and handles setting up
* deoptimization support for the type. The caller provides the type object and
* a struct containing the pointers to the current slot functions.
*
* Returns PYJIT_RESULT_OK if all operations succeed, or one of the error codes
* on failure.
*/
PyAPI_FUNC(_PyJIT_Result)
_PyJIT_SpecializeType(PyTypeObject* type, _PyJIT_TypeSlots* slots);
/*
* JIT compile func and patch its entry point.
*
* On success, positional only calls to func will use the JIT compiled version.
*
* Returns PYJIT_RESULT_OK on success.
*/
PyAPI_FUNC(_PyJIT_Result) _PyJIT_CompileFunction(PyFunctionObject* func);
/*
* Registers a function with the JIT to be compiled in the future.
*
* The JIT will still be informed by _PyJIT_CompileFunction before the
* function executes for the first time. The JIT can choose to compile
* the function at some future point. Currently the JIT will compile
* the function before it shuts down to make sure all eligable functions
* were compiled.
*
* The JIT will not keep the function alive, instead it will be informed
* that the function is being de-allocated via _PyJIT_UnregisterFunction
* before the function goes away.
*
* Returns 1 if the function is registered with JIT or is already compiled,
* and 0 otherwise.
*/
PyAPI_FUNC(int) _PyJIT_RegisterFunction(PyFunctionObject* func);
/*
* Informs the JIT that a type, function, or code object is being created,
* modified, or destroyed.
*/
PyAPI_FUNC(void) _PyJIT_TypeCreated(PyTypeObject* type);
PyAPI_FUNC(void) _PyJIT_TypeModified(PyTypeObject* type);
PyAPI_FUNC(void) _PyJIT_TypeNameModified(PyTypeObject* type);
PyAPI_FUNC(void) _PyJIT_TypeDestroyed(PyTypeObject* type);
PyAPI_FUNC(void) _PyJIT_FuncModified(PyFunctionObject* func);
PyAPI_FUNC(void) _PyJIT_FuncDestroyed(PyFunctionObject* func);
PyAPI_FUNC(void) _PyJIT_CodeDestroyed(PyCodeObject* code);
/*
* Clean up any resources allocated by the JIT.
*
* This is intended to be called at interpreter shutdown in Py_Finalize.
*
* Returns 0 on success or -1 on error.
*/
PyAPI_FUNC(int) _PyJIT_Finalize(void);
/*
* Returns whether the function specified in `func` is on the jit-list.
*
* Returns 0 if the given function is not on the jit-list, and non-zero
* otherwise.
*
* Always returns 1 if the JIT list is not specified.
*/
PyAPI_FUNC(int) _PyJIT_OnJitList(PyFunctionObject* func);
/*
* Returns a boolean indicating whether or not jitted functions should use a
* shadow frame object by default instead of a full PyFrameObject.
*/
PyAPI_FUNC(int) _PyJIT_ShadowFrame(void);
/* Dict-watching callbacks, invoked by dictobject.c when appropriate. */
/*
* Called when the value at a key is modified (value will contain the new
* value) or deleted (value will be NULL).
*/
PyAPI_FUNC(void)
_PyJIT_NotifyDictKey(PyObject* dict, PyObject* key, PyObject* value);
/*
* Called when a dict is cleared, rather than sending individual notifications
* for every key. The dict is still in a watched state, and further callbacks
* for it will be invoked as appropriate.
*/
PyAPI_FUNC(void) _PyJIT_NotifyDictClear(PyObject* dict);
/*
* Called when a dict has changed in a way that is incompatible with watching,
* or is about to be freed. No more callbacks will be invoked for this dict.
*/
PyAPI_FUNC(void) _PyJIT_NotifyDictUnwatch(PyObject* dict);
/*
* Gets the global cache for the given globals dictionary and key. The global
* that is pointed to will automatically be updated as builtins and globals
* change. The value that is pointed to will be NULL if the dictionaries can
* no longer be tracked or if the value is no longer defined, in which case
* the dictionaries need to be consulted. This will return NULL if the required
* tracking cannot be initialized.
*/
PyAPI_FUNC(PyObject**) _PyJIT_GetGlobalCache(PyObject* globals, PyObject* key);
/*
* Gets the cache for the given dictionary and key. The value that is pointed
* to will automatically be updated as the dictionary changes. The value that
* is pointed to will be NULL if the dictionaries can no longer be tracked or if
* the value is no longer defined, in which case the dictionaries need to be
* consulted. This will return NULL if the required tracking cannot be
* initialized.
*/
PyAPI_FUNC(PyObject**) _PyJIT_GetDictCache(PyObject* dict, PyObject* key);
/*
* Clears internal caches associated with the JIT. This may cause a degradation
* of performance and is only intended for use for detecting memory leaks.
*/
PyAPI_FUNC(void) _PyJIT_ClearDictCaches(void);
/*
* Send into/resume a suspended JIT generator and return the result.
*/
PyAPI_FUNC(PyObject*) _PyJIT_GenSend(
PyGenObject* gen,
PyObject* arg,
int exc,
PyFrameObject* f,
PyThreadState* tstate,
int finish_yield_from);
/*
* Materialize the frame for gen. Returns a new reference.
*/
PyAPI_FUNC(PyFrameObject*) _PyJIT_GenMaterializeFrame(PyGenObject* gen);
/*
* Visit owned references in a JIT-backed generator object.
*/
PyAPI_FUNC(int)
_PyJIT_GenVisitRefs(PyGenObject* gen, visitproc visit, void* arg);
/*
* Release any JIT-related data in a PyGenObject.
*/
PyAPI_FUNC(void) _PyJIT_GenDealloc(PyGenObject* gen);
/*
* Extract overall JIT state for generator. Implemented as a macro for perf
* in C code that doesn't have access to C++ types.
*/
#define _PyJIT_GenState(gen) \
((_PyJitGenState)((char*)gen->gi_jit_data)[_PY_GEN_JIT_DATA_STATE_OFFSET])
#define _PYJIT_MarkGenCompleted(gen) \
(*((_PyJitGenState*)((char*)gen->gi_jit_data + _PY_GEN_JIT_DATA_STATE_OFFSET)) = \
_PyJitGenState_Completed)
/*
* Return current sub-iterator from JIT generator or NULL if there is none.
*/
PyAPI_FUNC(PyObject*) _PyJIT_GenYieldFromValue(PyGenObject* gen);
/*
* Specifies the offset from a JITed function entry point where the re-entry
* point for calling with the correct bound args lives */
#define JITRT_CALL_REENTRY_OFFSET (-9)
/*
* Fixes the JITed function entry point up to be the re-entry point after
* binding the args */
#define JITRT_GET_REENTRY(entry) \
((vectorcallfunc)(((char*)entry) + JITRT_CALL_REENTRY_OFFSET))
/*
* Specifies the offset from a JITed function entry point where the static
* entry point lives */
#define JITRT_STATIC_ENTRY_OFFSET (-14)
/*
* Fixes the JITed function entry point up to be the static entry point after
* binding the args */
#define JITRT_GET_STATIC_ENTRY(entry) \
((vectorcallfunc)(((char*)entry) + JITRT_STATIC_ENTRY_OFFSET))
/*
* Checks if the given function is JITed.
* Returns 1 if the function is JITed, 0 if not.
*/
PyAPI_FUNC(int) _PyJIT_IsCompiled(PyObject* func);
/*
* Returns a borrowed reference to the globals for the top-most Python function
* associated with tstate.
*/
PyAPI_FUNC(PyObject*) _PyJIT_GetGlobals(PyThreadState* tstate);
/*
* Indicates whether or not newly-created interpreter threads should have type
* profiling enabled by default.
*/
extern int g_profile_new_interp_threads;
/*
* Record a type profile for the current instruction.
*/
PyAPI_FUNC(void) _PyJIT_ProfileCurrentInstr(
PyFrameObject* frame,
PyObject** stack_top,
int opcode,
int oparg);
/*
* Record profiled instructions for the given code object upon exit from a
* frame, some of which may not have had their types recorded.
*/
PyAPI_FUNC(void)
_PyJIT_CountProfiledInstrs(PyCodeObject* code, Py_ssize_t count);
/*
* Get and clear, or just clear, information about the recorded type profiles.
*/
PyAPI_FUNC(PyObject*) _PyJIT_GetAndClearTypeProfiles(void);
PyAPI_FUNC(void) _PyJIT_ClearTypeProfiles(void);
/*
* Notify the JIT that type has been modified.
*/
PyAPI_FUNC(void) _PyJIT_TypeModified(PyTypeObject* type);
#ifdef __cplusplus
bool _PyJIT_UseHugePages();
} /* extern "C" */
#endif
#endif /* Py_LIMITED_API */
| 31.150769 | 84 | 0.753655 | [
"object"
] |
3d08780ab1b7d68202c56232bfa50116558b5efd | 4,460 | c | C | mud/bldg/farm.c | shentino/simud | 644b7d4f56bf8d4695442b8efcfd56e0a561fe21 | [
"Apache-2.0"
] | 3 | 2015-07-18T00:19:51.000Z | 2016-02-20T17:25:37.000Z | mud/bldg/farm.c | shentino/simud | 644b7d4f56bf8d4695442b8efcfd56e0a561fe21 | [
"Apache-2.0"
] | 2 | 2021-03-04T19:24:03.000Z | 2021-03-08T10:17:34.000Z | mud/bldg/farm.c | shentino/simud | 644b7d4f56bf8d4695442b8efcfd56e0a561fe21 | [
"Apache-2.0"
] | 2 | 2015-12-22T06:16:53.000Z | 2016-11-18T16:32:50.000Z | inherit "/econ/building";
#include <const.h>
#include <const/shapeconst.h>
#include <const/roomconst.h>
// Seconds between vegetable spawns
#define SPAWN_FREQUENCY 600
BGM( "bjorn/bjorn_lynne-homeland_farmland" )
DISTANT( "a farmhouse" )
SPECIFIC( "the farmhouse" )
LOOK( "A small, rural farmhouse, built from logs, with a thatched roof.\n\nOwned by $(OWNER)." )
PLURAL( "farmhouses" )
ALT_PLURAL( ({ "houses", "buildings" }) )
NAME( "farmhouse" )
ALT_NAME( ({ "farm", "house", "farm house" }) )
TYPE( "building" )
PHRASE( "A farmhouse stands ~plac." )
void create() {
::create();
/* OBJEDIT { */
set_position( "here" );
set_preposition( "in" );
/* } OBJEDIT */
}
void on_map_paint( object painter ) {
painter->paint_shape( query_x(), query_y(), "/:::\\", 0x0b, LAYER_WALL );
painter->paint_row( query_x(), query_y()+1, "|_._|", 0x70, LAYER_WALL );
}
mapping query_shape() {
return SHAPE_BOX( 4, 2 );
}
int last_spawn_time;
int kid_spawn_time;
int query_last_spawn_time() {
return last_spawn_time;
}
int query_kid_spawn_time() {
return kid_spawn_time;
}
void set_last_spawn_time(int time) {
last_spawn_time = time;
}
void set_kid_spawn_time(int time) {
kid_spawn_time = time;
}
object get_work_spot() {
return present( "work_spot", find_room("start", this_object()) );
}
object get_silo() {
return present( "veg_silo", find_room("garden", this_object()) );
}
void supply_food() {
object ob, silo = get_silo();
if( silo ) {
foreach( ob : all_inventory(environment()) ) {
// Easy-out; this isn't perfect, it could be a non-food
// item or something.
if( !first_inventory(silo) )
return;
ob->on_supply( silo );
}
}
}
void spawn_vegetables()
{
string veg;
object silo = get_silo();
// Spawn vegetables at a constant rate in the silo.
switch( random(7) ) {
case 0: veg = "carrot"; break;
case 1: veg = "corn"; break;
case 2: veg = "lettuce"; break;
case 3: veg = "onion"; break;
case 4: veg = "potato"; break;
case 5: veg = "tomato"; break;
case 6: veg = "sugar_beet"; break;
}
if( veg ) {
object ob = clone_object( "/econ/crop/" + veg );
ob->move( silo );
}
}
void spawn_kid() {
object kid = clone_object( "/monsters/human" );
kid->move( find_room("start", this_object()) );
kid->set_home( this_object() );
kid->validate_position();
kid->use_ai_module( "farmer_kid" );
command( "walk random", kid );
}
void reset()
{
::reset();
object spot = get_work_spot();
if( !is_clone(this_object()) )
return;
if( spot && !spot->query_num_employees() )
return;
if( !last_spawn_time )
last_spawn_time = time();
while( last_spawn_time < time() ) {
spawn_vegetables();
last_spawn_time += SPAWN_FREQUENCY;
kid_spawn_time++;
}
// It takes about 1,000,000 seconds for a kid to grow up,
// so to keep the rate reasonable, I want it to take about
// a third that for them to spawn. 500 * 600 = 300,000.
while( kid_spawn_time >= 500 ) {
debug("Producing a kid", "gp");
spawn_kid();
kid_spawn_time -= 500;
}
// Spread out any food we have, although only if we have
// employees.
supply_food();
}
void on_build() {
object start_room, spawn;
ROOM_MAP( 3, 4, 1,
"ccc"
"ccc"
"aab"
"aab")
ROOM_KEY( "a", "start", "The Main Room", "This is the farmhouse's cozy living area." )
ROOM_KEY( "b", "pantry", "The Pantry", "A small side room where food is stored." )
ROOM_KEY( "c", "garden", "The Garden", "Behind the farmhouse is a small vegetable garden." )
start_room = find_room("start", this_object());
object silo = clone_object( "/scn/furni/veg_silo" );
silo->move( find_room("garden", this_object()) );
silo->set_coord( MAKE_C(1,1,0) );
make_outside_exit( start_room, MAKE_C(2,1,0) );
link_rooms( "start", "pantry", MAKE_C(11,3,0), "east" );
link_rooms( "pantry", "garden", MAKE_C(3,0,0), "north" );
object ob;
ob = clone_object( "/scn/furni/larder" );
ob->move( find_room("pantry", this_object()) );
ob->set_x(2); ob->set_y(6);
set_larder( ob );
spawn = clone_object( "/obj/work_spot" );
spawn->move( start_room );
spawn->set_work_name( "farmer" );
spawn->set_work_ai( "farmer" );
spawn->set_home( this_object() );
spawn->set_num_positions( 1 );
spawn->set_coord( MAKE_C(5,3,0) );
}
| 26.081871 | 96 | 0.6213 | [
"object"
] |
3d0e18d93682562ba9ece24a8997b6215f33c05b | 1,811 | h | C | src/view/RallyNetView.h | joelseverin/Johannebergsrallyt | 40932fe1b8bca88274d909bc2d5ee78d19560d10 | [
"MIT"
] | null | null | null | src/view/RallyNetView.h | joelseverin/Johannebergsrallyt | 40932fe1b8bca88274d909bc2d5ee78d19560d10 | [
"MIT"
] | null | null | null | src/view/RallyNetView.h | joelseverin/Johannebergsrallyt | 40932fe1b8bca88274d909bc2d5ee78d19560d10 | [
"MIT"
] | null | null | null | #ifndef RALLY_VIEW_RALLYNETVIEW_H_
#define RALLY_VIEW_RALLYNETVIEW_H_
#include "model/Car.h"
#include "util/Timer.h"
#include <map>
namespace Rally { namespace View {
class RallyNetView_NetworkCarListener {
public:
virtual ~RallyNetView_NetworkCarListener() {
}
/** Called when a car is added or updated. */
virtual void carUpdated(unsigned short carId,
Rally::Vector3 position,
Rally::Quaternion orientation,
Rally::Vector3 velocity,
char carType,
Rally::Vector4 tractionVector) = 0;
/** Called when a car is removed due to disconenct/timeout. */
virtual void carRemoved(unsigned short carId) = 0;
};
struct RallyNetView_InternalClient {
RallyNetView_InternalClient() :
lastPacketArrival(0),
lastPositionSequenceId(0) {
}
time_t lastPacketArrival;
unsigned short lastPositionSequenceId;
};
class RallyNetView {
public:
RallyNetView(RallyNetView_NetworkCarListener & listener);
virtual ~RallyNetView();
void initialize(const std::string & server, unsigned short port, const Model::Car* playerCar);
void pullRemoteChanges();
void pushLocalChanges();
private:
int socket;
unsigned short lastSentPacketId;
RallyNetView_NetworkCarListener& listener;
std::map<unsigned short, RallyNetView_InternalClient> clients;
const Model::Car* playerCar;
Rally::Util::Timer rateLimitTimer;
void pushCar();
void pullCars();
void cleanupClients();
};
} }
#endif // RALLY_VIEW_RALLYNETVIEW_H_
| 28.746032 | 106 | 0.605743 | [
"model"
] |
3d10a67269db1605a3bdce5cbb4c975e10ea949c | 2,693 | h | C | Source/NSDictionary+TNLAdditions.h | LaudateCorpus1/ios-twitter-network-layer | fe6a3f89e70cd3dc689a96f37b9f422fc6c4ecd3 | [
"Apache-2.0"
] | 517 | 2018-07-18T19:18:40.000Z | 2022-03-13T15:05:03.000Z | Source/NSDictionary+TNLAdditions.h | twitter/ios-twitter-network-layer | fe6a3f89e70cd3dc689a96f37b9f422fc6c4ecd3 | [
"Apache-2.0"
] | 11 | 2018-07-18T20:54:46.000Z | 2021-01-25T20:10:21.000Z | Source/NSDictionary+TNLAdditions.h | LaudateCorpus1/ios-twitter-network-layer | fe6a3f89e70cd3dc689a96f37b9f422fc6c4ecd3 | [
"Apache-2.0"
] | 24 | 2018-07-18T19:21:56.000Z | 2022-03-21T00:59:27.000Z | //
// NSDictionary+TNLAdditions.h
// TwitterNetworkLayer
//
// Created on 8/24/14.
// Copyright © 2020 Twitter. All rights reserved.
//
#import <Foundation/Foundation.h>
NS_ASSUME_NONNULL_BEGIN
/**
Additional methods for `NSDictionary`
See also `NSMutableDictionary(TNLAdditions)`
*/
@interface NSDictionary (TNLAdditions)
/**
Retrieve all objects who's keys match the provided case-insensitive key.
@param key the key to lookup
@return an array of matching objects or `nil` if none is found.
@note the cost of using this method vs objectForKey: is O(n) vs O(1)
*/
- (nullable NSArray *)tnl_objectsForCaseInsensitiveKey:(NSString *)key;
/**
Return the first matching value for a given case-insensitive _key_.
@param key the key to look up (case-insensitive)
@return the first matching value
@note will try to lookup via the key directly before performing an O(n) lookup.
*/
- (nullable id)tnl_objectForCaseInsensitiveKey:(NSString *)key;
/**
Find all keys in the receiver that match the given case-insensitive `key`
@param key the key to look up
@return a set of the matching keys if found, otherwise `nil`
@note this method runs in O(n) time
*/
- (nullable NSSet<NSString *> *)tnl_keysMatchingCaseInsensitiveKey:(NSString *)key;
/**
Make an immutable copy with all keys being lowercase
@return an NSDictionary
*/
- (id)tnl_copyWithLowercaseKeys;
/**
Make an immutable copy with all keys being uppercase
@return an NSDictionary
*/
- (id)tnl_copyWithUppercaseKeys;
/**
Make a mutable copy with all keys being lowercase
@return an NSMutableDictionary
*/
- (id)tnl_mutableCopyWithLowercaseKeys;
/**
Make a mutable copy with all keys being uppercase
@return an NSMutableDictionary
*/
- (id)tnl_mutableCopyWithUppercaseKeys;
@end
/**
Additional methods for `NSMutableDictionary`
See also `NSDictionary(TNLAdditions)`
*/
@interface NSMutableDictionary (TNLAdditions)
/**
Remove all objects matching the provided case-insensitive 'key'
@param key the key to match against
@note the cost of using this method vs removeObjectForKey: is O(n) vs O(1)
*/
- (void)tnl_removeObjectsForCaseInsensitiveKey:(NSString *)key;
/**
Set an object for a given 'key'. Any existing key-value-pairs that match the provided
key (case-insensitive) will be removed.
@param object the object to set
@param key the key to associate with the object
@note the cost of using this method vs setObject:forKey: is O(n) vs O(1)
*/
- (void)tnl_setObject:(id)object forCaseInsensitiveKey:(NSString *)key;
/**
Make all keys lowercase
*/
- (void)tnl_makeAllKeysLowercase;
/**
Make all keys uppercase
*/
- (void)tnl_makeAllKeysUppercase;
@end
NS_ASSUME_NONNULL_END
| 25.647619 | 87 | 0.749722 | [
"object"
] |
3d12fb70c6f5a142fb7b3b40f8c9c1ac9e30608b | 1,862 | h | C | wpilibc/src/main/native/include/frc/PWMSpeedController.h | gcjurgiel/allwpilib | 99f3a64dff0eba07be9b2e6c53753aafa0c852d8 | [
"BSD-3-Clause"
] | 1 | 2021-04-07T01:51:18.000Z | 2021-04-07T01:51:18.000Z | wpilibc/src/main/native/include/frc/PWMSpeedController.h | gcjurgiel/allwpilib | 99f3a64dff0eba07be9b2e6c53753aafa0c852d8 | [
"BSD-3-Clause"
] | 6 | 2021-02-19T00:40:42.000Z | 2021-04-01T22:15:54.000Z | wpilibc/src/main/native/include/frc/PWMSpeedController.h | gcjurgiel/allwpilib | 99f3a64dff0eba07be9b2e6c53753aafa0c852d8 | [
"BSD-3-Clause"
] | 1 | 2022-02-16T16:13:24.000Z | 2022-02-16T16:13:24.000Z | // Copyright (c) FIRST and other WPILib contributors.
// Open Source Software; you can modify and/or share it under the terms of
// the WPILib BSD license file in the root directory of this project.
#pragma once
#include "frc/PWM.h"
#include "frc/SpeedController.h"
namespace frc {
/**
* Common base class for all PWM Speed Controllers.
*/
class PWMSpeedController : public PWM, public SpeedController {
public:
PWMSpeedController(PWMSpeedController&&) = default;
PWMSpeedController& operator=(PWMSpeedController&&) = default;
/**
* Set the PWM value.
*
* The PWM value is set using a range of -1.0 to 1.0, appropriately scaling
* the value for the FPGA.
*
* @param speed The speed value between -1.0 and 1.0 to set.
*/
void Set(double value) override;
/**
* Get the recently set value of the PWM. This value is affected by the
* inversion property. If you want the value that is sent directly to the
* SpeedController, use {@link PWM#getSpeed()} instead.
*
* @return The most recently set value for the PWM between -1.0 and 1.0.
*/
double Get() const override;
void SetInverted(bool isInverted) override;
bool GetInverted() const override;
void Disable() override;
void StopMotor() override;
/**
* Write out the PID value as seen in the PIDOutput base object.
*
* @param output Write out the PWM value as was found in the PIDController
*/
void PIDWrite(double output) override;
protected:
/**
* Constructor for a PWM Speed Controller connected via PWM.
*
* @param channel The PWM channel that the controller is attached to. 0-9 are
* on-board, 10-19 are on the MXP port
*/
explicit PWMSpeedController(int channel);
void InitSendable(SendableBuilder& builder) override;
private:
bool m_isInverted = false;
};
} // namespace frc
| 26.6 | 79 | 0.695489 | [
"object"
] |
3d141145181ab74809c84f136059507f43704979 | 11,169 | c | C | gear-lib/libdict/libdict.c | zfgong/libraries | 54b2729975686870d986e567e457612b1425bd72 | [
"MIT"
] | 1,191 | 2015-08-16T17:23:22.000Z | 2019-03-01T15:41:02.000Z | gear-lib/libdict/libdict.c | zfgong/libraries | 54b2729975686870d986e567e457612b1425bd72 | [
"MIT"
] | 26 | 2015-08-23T10:56:03.000Z | 2019-02-25T16:29:28.000Z | gear-lib/libdict/libdict.c | zfgong/libraries | 54b2729975686870d986e567e457612b1425bd72 | [
"MIT"
] | 410 | 2015-12-30T08:21:45.000Z | 2019-02-26T19:35:35.000Z | /******************************************************************************
* Copyright (C) 2014-2020 Zhifeng Gong <gozfree@163.com>
*
* 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 <libposix.h>
#include "libdict.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
#include <errno.h>
/** Minimum dictionary size to start with */
#define DICT_MIN_SZ 64
/** Dummy pointer to reference deleted keys */
#define DUMMY_PTR ((void*)-1)
/** Used to hash further when handling collisions */
#define PERTURB_SHIFT 5
/** Beyond this size, a dictionary will not be grown by the same factor */
#define DICT_BIGSZ 64000
/** Define this to:
0 for no debugging
1 for moderate debugging
2 for heavy debugging
*/
#define DEBUG 0
/*
* Specify which hash function to use
* MurmurHash is fast but may not work on all architectures
* Dobbs is a tad bit slower but not by much and works everywhere
*/
#define dict_hash dict_hash_murmur
/* #define dict_hash dict_hash_dobbs */
/* Forward definitions */
static int dict_resize(dict *d);
/** Replacement for strdup() which is not always provided by libc */
static char *xstrdup(char *s)
{
char * t;
if (!s)
return NULL;
t = (char *)malloc(strlen(s) + 1);
if (t) {
strcpy(t, s);
}
return t;
}
/**
This hash function has been taken from an Article in Dr Dobbs Journal.
There are probably better ones out there but this one does the job.
*/
#if 0
static uint32_t dict_hash_dobbs(char *key, size_t len)
{
int len, i;
uint32_t hash;
if (!key || !len) {
printf("%s: invalid paraments!\n", __func__);
return 0;
}
for (hash = 0, i=0; i < len; i++) {
hash += (uint32_t)key[i];
hash += (hash<<10);
hash ^= (hash>>6);
}
hash += (hash <<3);
hash ^= (hash >>11);
hash += (hash <<15);
return hash;
}
#endif
/* Murmurhash */
static uint32_t dict_hash_murmur(char *key, size_t len)
{
uint32_t h, k;
uint8_t *data;
uint32_t seed = 0x0badcafe;//magic number
uint32_t m = 0x5bd1e995;//magic number
uint32_t r = 24;//magic number
if (!key || !len) {
return 0;
}
h = seed ^ len;
data = (uint8_t *)key;
while (len >= 4) {
k = *(uint32_t *)data;
k *= m;
k ^= k >> r;
k *= m;
h *= m;
h ^= k;
data += 4;
len -= 4;
}
switch (len) {
case 3: h ^= data[2] << 16;
case 2: h ^= data[1] << 8;
case 1: h ^= data[0];
h *= m;
};
h ^= h >> 13;
h *= m;
h ^= h >> 15;
return h;
}
/** Lookup an element in a dict
This implementation copied almost verbatim from the Python dictionary
object, without the Pythonisms.
*/
static keypair *dict_lookup(dict *d, char *key, uint32_t hash)
{
keypair * freeslot;
keypair * ep;
uint32_t i;
uint32_t perturb;
if (!d || !key) {
return NULL;
}
i = hash & (d->size-1);
/* Look for empty slot */
ep = d->table + i;
if (ep->key == NULL || ep->key == key) {
return ep ;
}
if (ep->key == DUMMY_PTR) {
freeslot = ep;
} else {
if (ep->hash == hash &&
!strcmp(key, ep->key)) {
return ep;
}
freeslot = NULL;
}
for (perturb = hash; perturb > 0; perturb >>= PERTURB_SHIFT) {
i = (i<<2) + i + perturb + 1;
i &= (d->size-1);
ep = d->table + i;
if (ep->key == NULL) {
return freeslot == NULL ? ep : freeslot;
}
if ((ep->key == key) ||
(ep->hash == hash &&
ep->key != DUMMY_PTR &&
!strcmp(ep->key, key))) {
return ep;
}
if (ep->key == DUMMY_PTR && freeslot == NULL) {
freeslot = ep;
}
}
return NULL;
}
/** Add an item to a dictionary without copying key/val
Used by dict_resize() only.
*/
static int dict_add_p(dict *d, char *key, char *val)
{
uint32_t hash;
keypair * slot;
if (!d || !key) {
return -1;
}
#if DEBUG>2
printf("dict_add_p[%s][%s]\n", key, val ? val : "UNDEF");
#endif
hash = dict_hash(key, strlen(key));
slot = dict_lookup(d, key, hash);
if (slot) {
slot->key = key;
slot->val = val;
slot->hash = hash;
d->used++;
d->fill++;
if ((3*d->fill) >= (d->size*2)) {
if (dict_resize(d) != 0) {
return -1;
}
}
}
return 0;
}
/** Add an item to a dictionary by copying key/val into the dict. */
int dict_add(dict *d, char *key, char *val)
{
uint32_t hash;
keypair *slot;
if (!d || !key) {
return -1;
}
#if DEBUG>2
printf("dict_add[%s][%s]\n", key, val ? val : "UNDEF");
#endif
hash = dict_hash(key, strlen(key));
slot = dict_lookup(d, key, hash);
if (slot) {
slot->key = xstrdup(key);
if (!(slot->key)) {
return -1;
}
#if 0
slot->val = val ? xstrdup(val) : val;
if (val && !(slot->val)) {
free(slot->key);
return -1;
}
#endif
slot->val = val;
slot->hash = hash;
d->used++;
d->fill++;
if ((3*d->fill) >= (d->size*2)) {
if (dict_resize(d) != 0) {
return -1;
}
}
}
return 0;
}
/** Resize a dictionary */
static int dict_resize(dict *d)
{
uint32_t newsize;
keypair *oldtable;
uint32_t i;
uint32_t oldsize;
uint32_t factor;
newsize = d->size;
/*
* Re-sizing factor depends on the current dict size.
* Small dicts will expand 4 times, bigger ones only 2 times
*/
factor = (d->size>DICT_BIGSZ) ? 2 : 4;
while (newsize <= (factor*d->used)) {
newsize *= 2;
}
/* Exit early if no re-sizing needed */
if (newsize == d->size)
return 0;
#if DEBUG>2
printf("resizing %d to %d (used: %d)\n", d->size, newsize, d->used);
#endif
/* Shuffle pointers, re-allocate new table, re-insert data */
oldtable = d->table;
d->table = (keypair *)calloc(newsize, sizeof(keypair));
if (!(d->table)) {
/* Memory allocation failure */
printf("%s: malloc failed %s\n", __func__, strerror(errno));
return -1;
}
oldsize = d->size;
d->size = newsize;
d->used = 0;
d->fill = 0;
for (i = 0; i < oldsize; i++) {
if (oldtable[i].key && (oldtable[i].key!=DUMMY_PTR)) {
dict_add_p(d, oldtable[i].key, oldtable[i].val);
}
}
free(oldtable);
return 0 ;
}
/** Public: allocate a new dict */
dict *dict_new(void)
{
dict * d = (dict *)calloc(1, sizeof(dict));
if (!d) {
printf("%s: malloc failed %s\n", __func__, strerror(errno));
return NULL;
}
d->size = DICT_MIN_SZ;
d->used = 0;
d->fill = 0;
d->table = (keypair *)calloc(DICT_MIN_SZ, sizeof(keypair));
if (!d->table) {
printf("%s: malloc failed %s\n", __func__, strerror(errno));
free(d);
return NULL;
}
memset(d->table, -1, DICT_MIN_SZ*sizeof(keypair));
return d;
}
/** Public: deallocate a dict */
void dict_free(dict *d)
{
int i;
if (!d)
return;
for (i = 0; i < (int)d->size; i++) {
if (d->table[i].key && d->table[i].key != DUMMY_PTR) {
free(d->table[i].key);
#if 0
//val is not copyed, no need to free
if (d->table[i].val)
free(d->table[i].val);
#endif
}
}
free(d->table);
free(d);
return ;
}
/** Public: get an item from a dict */
char *dict_get(dict *d, char *key, char *defval)
{
keypair *kp;
uint32_t hash;
if (!d || !key) {
return defval;
}
hash = dict_hash(key, strlen(key));
kp = dict_lookup(d, key, hash);
if (kp) {
return kp->val;
}
return defval;
}
/** Public: delete an item in a dict */
int dict_del(dict *d, char *key)
{
uint32_t hash;
keypair *kp;
if (!d || !key) {
return -1;
}
hash = dict_hash(key, strlen(key));
kp = dict_lookup(d, key, hash);
if (!kp)
return -1;
if (kp->key && kp->key != DUMMY_PTR)
free(kp->key);
kp->key = (char *)DUMMY_PTR;
#if 0
if (kp->val)
free(kp->val);
#endif
kp->val = NULL;
d->used--;
return 0;
}
/** Public: enumerate a dictionary */
int dict_enumerate(dict * d, int rank, char ** key, char ** val)
{
if (!d || !key || !val || (rank<0)) {
return -1 ;
}
while ((d->table[rank].key == NULL || d->table[rank].key == DUMMY_PTR)
&& (rank < (int)d->size))
rank++;
if (rank >= (int)d->size) {
*key = NULL;
*val = NULL;
rank = -1;
} else {
*key = d->table[rank].key;
*val = d->table[rank].val;
rank++;
}
return rank;
}
/** Public: dump a dict to a file pointer */
void dict_dump(dict * d, FILE * out)
{
char *key;
char *val;
int rank = 0;
if (!d || !out) {
return;
}
while (1) {
rank = dict_enumerate(d, rank, &key, &val);
if (rank < 0)
break;
fprintf(out, "[rank=%d] %20s: %s\n", rank, key, val ? val : "UNDEF");
}
return;
}
void dict_get_key_list(dict *d, key_list **klist)
{
char *key;
char *val;
int rank = 0;
key_list *knode, *ktmp;
if (!d)
return;
*klist = NULL;
knode = NULL;
ktmp = NULL;
while (1) {
rank = dict_enumerate(d, rank, &key, &val);
if (rank<0)
break ;
knode = (key_list *)calloc(1, sizeof(key_list));
knode->key = xstrdup(key);
knode->next = NULL;
if (*klist == NULL) {
*klist = knode;
ktmp = *klist;
} else {
ktmp->next = knode;
ktmp = ktmp->next;
}
//fprintf(stderr, "%20s: %s\n", key, val ? val : "UNDEF");
}
}
| 24.071121 | 81 | 0.523323 | [
"object"
] |
3d15a881702408fd6fe93fe608ee2d30d19f402a | 4,943 | h | C | src/core/RBlockReferenceData.h | ouxianghui/ezcam | 195fb402202442b6d035bd70853f2d8c3f615de1 | [
"MIT"
] | 12 | 2021-03-26T03:23:30.000Z | 2021-12-31T10:05:44.000Z | src/core/RBlockReferenceData.h | 15831944/ezcam | 195fb402202442b6d035bd70853f2d8c3f615de1 | [
"MIT"
] | null | null | null | src/core/RBlockReferenceData.h | 15831944/ezcam | 195fb402202442b6d035bd70853f2d8c3f615de1 | [
"MIT"
] | 9 | 2021-06-23T08:26:40.000Z | 2022-01-20T07:18:10.000Z | /**
* Copyright (c) 2011-2016 by Andrew Mustun. All rights reserved.
*
* This file is part of the QCAD project.
*
* QCAD 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 3 of the License, or
* (at your option) any later version.
*
* QCAD 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 QCAD.
*/
#ifndef RBLOCKREFERENCEDATA_H
#define RBLOCKREFERENCEDATA_H
#include "core_global.h"
#include "RBox.h"
#include "REntity.h"
#include "RVector.h"
#include "RBlock.h"
class RDocument;
/**
* Defines the geometry and appearance of a block reference entity.
*
* \scriptable
* \copyable
* \ingroup core
*/
class QCADCORE_EXPORT RBlockReferenceData: public REntityData {
friend class RBlockReferenceEntity;
friend class RViewportEntity;
protected:
RBlockReferenceData(RDocument* document, const RBlockReferenceData& data);
public:
RBlockReferenceData();
RBlockReferenceData(RBlock::Id referencedBlockId,
const RVector& position, const RVector& scaleFactors,
double angle,
int columnCount=1, int rowCount=1,
double columnSpacing=0, double rowSpacing=0);
virtual QList<RBox> getBoundingBoxes(bool ignoreEmpty=false) const;
virtual RBox getBoundingBox(bool ignoreEmpty=false) const;
virtual QList<RRefPoint> getInternalReferencePoints(RS::ProjectionRenderingHint hint = RS::RenderTop) const;
virtual QList<RRefPoint> getReferencePoints(RS::ProjectionRenderingHint hint = RS::RenderTop) const;
virtual RVector getVectorTo(const RVector& point, bool limited = true, double strictRange = RMAXDOUBLE) const;
virtual double getDistanceTo(const RVector& point, bool limited = true, double range = 0.0,
bool draft = false, double strictRange = RMAXDOUBLE) const;
RBox getQueryBoxInBlockCoordinates(const RBox& box) const;
virtual QList<QSharedPointer<RShape> > getShapes(const RBox& queryBox = RDEFAULT_RBOX, bool ignoreComplex = false) const;
//virtual void setSelected(bool on);
virtual bool moveReferencePoint(const RVector& referencePoint, const RVector& targetPoint);
virtual bool move(const RVector& offset);
virtual bool rotate(double rotation, const RVector& center = RDEFAULT_RVECTOR);
virtual bool mirror(const RLine& axis);
virtual bool scale(const RVector& scaleFactors,
const RVector& center = RDEFAULT_RVECTOR);
void setReferencedBlockId(RBlock::Id blockId);
void groundReferencedBlockId() const {
referencedBlockId = RBlock::INVALID_ID;
}
RBlock::Id getReferencedBlockId() const {
return referencedBlockId;
}
void setReferencedBlockName(const QString& blockName);
QString getReferencedBlockName() const;
RVector getPosition() const {
return position;
}
void setPosition(const RVector& p);
RVector getScaleFactors() const {
return scaleFactors;
}
void setScaleFactors(const RVector& sf);
double getRotation() const {
return rotation;
}
void setRotation(double r);
int getColumnCount() const {
return columnCount;
}
void setColumnCount(int c) {
columnCount = c;
}
int getRowCount() const {
return rowCount;
}
void setRowCount(int c) {
rowCount = c;
}
double getColumnSpacing() const {
return columnSpacing;
}
void setColumnSpacing(double s) {
columnSpacing = s;
}
double getRowSpacing() const {
return rowSpacing;
}
void setRowSpacing(double s) {
rowSpacing = s;
}
virtual void update() const;
virtual void update(RObject::Id entityId) const;
QSharedPointer<REntity> queryEntity(REntity::Id entityId) const;
bool applyTransformationTo(REntity& entity) const;
RVector getColumnRowOffset(int col, int row) const;
void applyColumnRowOffsetTo(REntity& entity, int col, int row) const;
RVector mapToBlock(const RVector& v) const;
private:
mutable RBlock::Id referencedBlockId;
RVector position;
RVector scaleFactors;
double rotation;
int columnCount;
int rowCount;
double columnSpacing;
double rowSpacing;
mutable QList<RBox> boundingBoxes;
mutable QList<RBox> boundingBoxesIgnoreEmpty;
mutable QMap<REntity::Id, QSharedPointer<REntity> > cache;
};
Q_DECLARE_METATYPE(RBlockReferenceData)
Q_DECLARE_METATYPE(RBlockReferenceData*)
Q_DECLARE_METATYPE(const RBlockReferenceData*)
Q_DECLARE_METATYPE(QSharedPointer<RBlockReferenceData>)
#endif
| 30.512346 | 125 | 0.71313 | [
"geometry"
] |
3d15cc47c984b79616e00640b8acd7eb5e74098d | 16,400 | h | C | 2.4/include/org/apache/xpath/compiler/FunctionTable.h | yaohb/J2ObjCAuto | 8b5252896999f367066e3f68226620f78c020923 | [
"MIT"
] | null | null | null | 2.4/include/org/apache/xpath/compiler/FunctionTable.h | yaohb/J2ObjCAuto | 8b5252896999f367066e3f68226620f78c020923 | [
"MIT"
] | null | null | null | 2.4/include/org/apache/xpath/compiler/FunctionTable.h | yaohb/J2ObjCAuto | 8b5252896999f367066e3f68226620f78c020923 | [
"MIT"
] | null | null | null | //
// Generated by the J2ObjC translator. DO NOT EDIT!
// source: /Users/antoniocortes/j2objcprj/relases/j2objc/xalan/third_party/android/platform/external/apache-xml/src/main/java/org/apache/xpath/compiler/FunctionTable.java
//
#include "J2ObjC_header.h"
#pragma push_macro("INCLUDE_ALL_OrgApacheXpathCompilerFunctionTable")
#ifdef RESTRICT_OrgApacheXpathCompilerFunctionTable
#define INCLUDE_ALL_OrgApacheXpathCompilerFunctionTable 0
#else
#define INCLUDE_ALL_OrgApacheXpathCompilerFunctionTable 1
#endif
#undef RESTRICT_OrgApacheXpathCompilerFunctionTable
#pragma clang diagnostic push
#pragma GCC diagnostic ignored "-Wdeprecated-declarations"
#if __has_feature(nullability)
#pragma clang diagnostic push
#pragma GCC diagnostic ignored "-Wnullability"
#pragma GCC diagnostic ignored "-Wnullability-completeness"
#endif
#if !defined (OrgApacheXpathCompilerFunctionTable_) && (INCLUDE_ALL_OrgApacheXpathCompilerFunctionTable || defined(INCLUDE_OrgApacheXpathCompilerFunctionTable))
#define OrgApacheXpathCompilerFunctionTable_
@class IOSClass;
@class OrgApacheXpathFunctionsFunction;
/*!
@brief The function table for XPath.
*/
@interface OrgApacheXpathCompilerFunctionTable : NSObject
@property (readonly, class) jint FUNC_CURRENT NS_SWIFT_NAME(FUNC_CURRENT);
@property (readonly, class) jint FUNC_LAST NS_SWIFT_NAME(FUNC_LAST);
@property (readonly, class) jint FUNC_POSITION NS_SWIFT_NAME(FUNC_POSITION);
@property (readonly, class) jint FUNC_COUNT NS_SWIFT_NAME(FUNC_COUNT);
@property (readonly, class) jint FUNC_ID NS_SWIFT_NAME(FUNC_ID);
@property (readonly, class) jint FUNC_KEY NS_SWIFT_NAME(FUNC_KEY);
@property (readonly, class) jint FUNC_LOCAL_PART NS_SWIFT_NAME(FUNC_LOCAL_PART);
@property (readonly, class) jint FUNC_NAMESPACE NS_SWIFT_NAME(FUNC_NAMESPACE);
@property (readonly, class) jint FUNC_QNAME NS_SWIFT_NAME(FUNC_QNAME);
@property (readonly, class) jint FUNC_GENERATE_ID NS_SWIFT_NAME(FUNC_GENERATE_ID);
@property (readonly, class) jint FUNC_NOT NS_SWIFT_NAME(FUNC_NOT);
@property (readonly, class) jint FUNC_TRUE NS_SWIFT_NAME(FUNC_TRUE);
@property (readonly, class) jint FUNC_FALSE NS_SWIFT_NAME(FUNC_FALSE);
@property (readonly, class) jint FUNC_BOOLEAN NS_SWIFT_NAME(FUNC_BOOLEAN);
@property (readonly, class) jint FUNC_NUMBER NS_SWIFT_NAME(FUNC_NUMBER);
@property (readonly, class) jint FUNC_FLOOR NS_SWIFT_NAME(FUNC_FLOOR);
@property (readonly, class) jint FUNC_CEILING NS_SWIFT_NAME(FUNC_CEILING);
@property (readonly, class) jint FUNC_ROUND NS_SWIFT_NAME(FUNC_ROUND);
@property (readonly, class) jint FUNC_SUM NS_SWIFT_NAME(FUNC_SUM);
@property (readonly, class) jint FUNC_STRING NS_SWIFT_NAME(FUNC_STRING);
@property (readonly, class) jint FUNC_STARTS_WITH NS_SWIFT_NAME(FUNC_STARTS_WITH);
@property (readonly, class) jint FUNC_CONTAINS NS_SWIFT_NAME(FUNC_CONTAINS);
@property (readonly, class) jint FUNC_SUBSTRING_BEFORE NS_SWIFT_NAME(FUNC_SUBSTRING_BEFORE);
@property (readonly, class) jint FUNC_SUBSTRING_AFTER NS_SWIFT_NAME(FUNC_SUBSTRING_AFTER);
@property (readonly, class) jint FUNC_NORMALIZE_SPACE NS_SWIFT_NAME(FUNC_NORMALIZE_SPACE);
@property (readonly, class) jint FUNC_TRANSLATE NS_SWIFT_NAME(FUNC_TRANSLATE);
@property (readonly, class) jint FUNC_CONCAT NS_SWIFT_NAME(FUNC_CONCAT);
@property (readonly, class) jint FUNC_SUBSTRING NS_SWIFT_NAME(FUNC_SUBSTRING);
@property (readonly, class) jint FUNC_STRING_LENGTH NS_SWIFT_NAME(FUNC_STRING_LENGTH);
@property (readonly, class) jint FUNC_SYSTEM_PROPERTY NS_SWIFT_NAME(FUNC_SYSTEM_PROPERTY);
@property (readonly, class) jint FUNC_LANG NS_SWIFT_NAME(FUNC_LANG);
@property (readonly, class) jint FUNC_EXT_FUNCTION_AVAILABLE NS_SWIFT_NAME(FUNC_EXT_FUNCTION_AVAILABLE);
@property (readonly, class) jint FUNC_EXT_ELEM_AVAILABLE NS_SWIFT_NAME(FUNC_EXT_ELEM_AVAILABLE);
@property (readonly, class) jint FUNC_UNPARSED_ENTITY_URI NS_SWIFT_NAME(FUNC_UNPARSED_ENTITY_URI);
@property (readonly, class) jint FUNC_DOCLOCATION NS_SWIFT_NAME(FUNC_DOCLOCATION);
+ (jint)FUNC_CURRENT;
+ (jint)FUNC_LAST;
+ (jint)FUNC_POSITION;
+ (jint)FUNC_COUNT;
+ (jint)FUNC_ID;
+ (jint)FUNC_KEY;
+ (jint)FUNC_LOCAL_PART;
+ (jint)FUNC_NAMESPACE;
+ (jint)FUNC_QNAME;
+ (jint)FUNC_GENERATE_ID;
+ (jint)FUNC_NOT;
+ (jint)FUNC_TRUE;
+ (jint)FUNC_FALSE;
+ (jint)FUNC_BOOLEAN;
+ (jint)FUNC_NUMBER;
+ (jint)FUNC_FLOOR;
+ (jint)FUNC_CEILING;
+ (jint)FUNC_ROUND;
+ (jint)FUNC_SUM;
+ (jint)FUNC_STRING;
+ (jint)FUNC_STARTS_WITH;
+ (jint)FUNC_CONTAINS;
+ (jint)FUNC_SUBSTRING_BEFORE;
+ (jint)FUNC_SUBSTRING_AFTER;
+ (jint)FUNC_NORMALIZE_SPACE;
+ (jint)FUNC_TRANSLATE;
+ (jint)FUNC_CONCAT;
+ (jint)FUNC_SUBSTRING;
+ (jint)FUNC_STRING_LENGTH;
+ (jint)FUNC_SYSTEM_PROPERTY;
+ (jint)FUNC_LANG;
+ (jint)FUNC_EXT_FUNCTION_AVAILABLE;
+ (jint)FUNC_EXT_ELEM_AVAILABLE;
+ (jint)FUNC_UNPARSED_ENTITY_URI;
+ (jint)FUNC_DOCLOCATION;
#pragma mark Public
- (instancetype __nonnull)init;
/*!
@brief Tell if a built-in, non-namespaced function is available.
@param methName The local name of the function.
@return True if the function can be executed.
*/
- (jboolean)functionAvailableWithNSString:(NSString *)methName;
/*!
@brief Install a built-in function.
@param name The unqualified name of the function, must not be null
@param func A Implementation of an XPath Function object.
@return the position of the function in the internal index.
*/
- (jint)installFunctionWithNSString:(NSString *)name
withIOSClass:(IOSClass *)func;
#pragma mark Package-Private
/*!
@brief Obtain a new Function object from a function ID.
@param which The function ID, which may correspond to one of the FUNC_XXX values found in
<code>org.apache.xpath.compiler.FunctionTable</code> , but may be a value installed by an external module.
@return a a new Function instance.
@throw javax.xml.transform.TransformerExceptionif ClassNotFoundException,
IllegalAccessException, or InstantiationException is thrown.
*/
- (OrgApacheXpathFunctionsFunction *)getFunctionWithInt:(jint)which;
/*!
@brief Obtain a function ID from a given function name
@param key the function name in a java.lang.String format.
@return a function ID, which may correspond to one of the FUNC_XXX values
found in <code>org.apache.xpath.compiler.FunctionTable</code>, but may be a
value installed by an external module.
*/
- (id)getFunctionIDWithNSString:(NSString *)key;
/*!
@brief Return the name of the a function in the static table.Needed to avoid
making the table publicly available.
*/
- (NSString *)getFunctionNameWithInt:(jint)funcID;
@end
J2OBJC_STATIC_INIT(OrgApacheXpathCompilerFunctionTable)
/*!
@brief The 'current()' id.
*/
inline jint OrgApacheXpathCompilerFunctionTable_get_FUNC_CURRENT(void);
#define OrgApacheXpathCompilerFunctionTable_FUNC_CURRENT 0
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXpathCompilerFunctionTable, FUNC_CURRENT, jint)
/*!
@brief The 'last()' id.
*/
inline jint OrgApacheXpathCompilerFunctionTable_get_FUNC_LAST(void);
#define OrgApacheXpathCompilerFunctionTable_FUNC_LAST 1
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXpathCompilerFunctionTable, FUNC_LAST, jint)
/*!
@brief The 'position()' id.
*/
inline jint OrgApacheXpathCompilerFunctionTable_get_FUNC_POSITION(void);
#define OrgApacheXpathCompilerFunctionTable_FUNC_POSITION 2
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXpathCompilerFunctionTable, FUNC_POSITION, jint)
/*!
@brief The 'count()' id.
*/
inline jint OrgApacheXpathCompilerFunctionTable_get_FUNC_COUNT(void);
#define OrgApacheXpathCompilerFunctionTable_FUNC_COUNT 3
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXpathCompilerFunctionTable, FUNC_COUNT, jint)
/*!
@brief The 'id()' id.
*/
inline jint OrgApacheXpathCompilerFunctionTable_get_FUNC_ID(void);
#define OrgApacheXpathCompilerFunctionTable_FUNC_ID 4
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXpathCompilerFunctionTable, FUNC_ID, jint)
/*!
@brief The 'key()' id (XSLT).
*/
inline jint OrgApacheXpathCompilerFunctionTable_get_FUNC_KEY(void);
#define OrgApacheXpathCompilerFunctionTable_FUNC_KEY 5
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXpathCompilerFunctionTable, FUNC_KEY, jint)
/*!
@brief The 'local-name()' id.
*/
inline jint OrgApacheXpathCompilerFunctionTable_get_FUNC_LOCAL_PART(void);
#define OrgApacheXpathCompilerFunctionTable_FUNC_LOCAL_PART 7
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXpathCompilerFunctionTable, FUNC_LOCAL_PART, jint)
/*!
@brief The 'namespace-uri()' id.
*/
inline jint OrgApacheXpathCompilerFunctionTable_get_FUNC_NAMESPACE(void);
#define OrgApacheXpathCompilerFunctionTable_FUNC_NAMESPACE 8
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXpathCompilerFunctionTable, FUNC_NAMESPACE, jint)
/*!
@brief The 'name()' id.
*/
inline jint OrgApacheXpathCompilerFunctionTable_get_FUNC_QNAME(void);
#define OrgApacheXpathCompilerFunctionTable_FUNC_QNAME 9
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXpathCompilerFunctionTable, FUNC_QNAME, jint)
/*!
@brief The 'generate-id()' id.
*/
inline jint OrgApacheXpathCompilerFunctionTable_get_FUNC_GENERATE_ID(void);
#define OrgApacheXpathCompilerFunctionTable_FUNC_GENERATE_ID 10
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXpathCompilerFunctionTable, FUNC_GENERATE_ID, jint)
/*!
@brief The 'not()' id.
*/
inline jint OrgApacheXpathCompilerFunctionTable_get_FUNC_NOT(void);
#define OrgApacheXpathCompilerFunctionTable_FUNC_NOT 11
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXpathCompilerFunctionTable, FUNC_NOT, jint)
/*!
@brief The 'true()' id.
*/
inline jint OrgApacheXpathCompilerFunctionTable_get_FUNC_TRUE(void);
#define OrgApacheXpathCompilerFunctionTable_FUNC_TRUE 12
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXpathCompilerFunctionTable, FUNC_TRUE, jint)
/*!
@brief The 'false()' id.
*/
inline jint OrgApacheXpathCompilerFunctionTable_get_FUNC_FALSE(void);
#define OrgApacheXpathCompilerFunctionTable_FUNC_FALSE 13
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXpathCompilerFunctionTable, FUNC_FALSE, jint)
/*!
@brief The 'boolean()' id.
*/
inline jint OrgApacheXpathCompilerFunctionTable_get_FUNC_BOOLEAN(void);
#define OrgApacheXpathCompilerFunctionTable_FUNC_BOOLEAN 14
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXpathCompilerFunctionTable, FUNC_BOOLEAN, jint)
/*!
@brief The 'number()' id.
*/
inline jint OrgApacheXpathCompilerFunctionTable_get_FUNC_NUMBER(void);
#define OrgApacheXpathCompilerFunctionTable_FUNC_NUMBER 15
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXpathCompilerFunctionTable, FUNC_NUMBER, jint)
/*!
@brief The 'floor()' id.
*/
inline jint OrgApacheXpathCompilerFunctionTable_get_FUNC_FLOOR(void);
#define OrgApacheXpathCompilerFunctionTable_FUNC_FLOOR 16
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXpathCompilerFunctionTable, FUNC_FLOOR, jint)
/*!
@brief The 'ceiling()' id.
*/
inline jint OrgApacheXpathCompilerFunctionTable_get_FUNC_CEILING(void);
#define OrgApacheXpathCompilerFunctionTable_FUNC_CEILING 17
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXpathCompilerFunctionTable, FUNC_CEILING, jint)
/*!
@brief The 'round()' id.
*/
inline jint OrgApacheXpathCompilerFunctionTable_get_FUNC_ROUND(void);
#define OrgApacheXpathCompilerFunctionTable_FUNC_ROUND 18
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXpathCompilerFunctionTable, FUNC_ROUND, jint)
/*!
@brief The 'sum()' id.
*/
inline jint OrgApacheXpathCompilerFunctionTable_get_FUNC_SUM(void);
#define OrgApacheXpathCompilerFunctionTable_FUNC_SUM 19
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXpathCompilerFunctionTable, FUNC_SUM, jint)
/*!
@brief The 'string()' id.
*/
inline jint OrgApacheXpathCompilerFunctionTable_get_FUNC_STRING(void);
#define OrgApacheXpathCompilerFunctionTable_FUNC_STRING 20
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXpathCompilerFunctionTable, FUNC_STRING, jint)
/*!
@brief The 'starts-with()' id.
*/
inline jint OrgApacheXpathCompilerFunctionTable_get_FUNC_STARTS_WITH(void);
#define OrgApacheXpathCompilerFunctionTable_FUNC_STARTS_WITH 21
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXpathCompilerFunctionTable, FUNC_STARTS_WITH, jint)
/*!
@brief The 'contains()' id.
*/
inline jint OrgApacheXpathCompilerFunctionTable_get_FUNC_CONTAINS(void);
#define OrgApacheXpathCompilerFunctionTable_FUNC_CONTAINS 22
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXpathCompilerFunctionTable, FUNC_CONTAINS, jint)
/*!
@brief The 'substring-before()' id.
*/
inline jint OrgApacheXpathCompilerFunctionTable_get_FUNC_SUBSTRING_BEFORE(void);
#define OrgApacheXpathCompilerFunctionTable_FUNC_SUBSTRING_BEFORE 23
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXpathCompilerFunctionTable, FUNC_SUBSTRING_BEFORE, jint)
/*!
@brief The 'substring-after()' id.
*/
inline jint OrgApacheXpathCompilerFunctionTable_get_FUNC_SUBSTRING_AFTER(void);
#define OrgApacheXpathCompilerFunctionTable_FUNC_SUBSTRING_AFTER 24
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXpathCompilerFunctionTable, FUNC_SUBSTRING_AFTER, jint)
/*!
@brief The 'normalize-space()' id.
*/
inline jint OrgApacheXpathCompilerFunctionTable_get_FUNC_NORMALIZE_SPACE(void);
#define OrgApacheXpathCompilerFunctionTable_FUNC_NORMALIZE_SPACE 25
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXpathCompilerFunctionTable, FUNC_NORMALIZE_SPACE, jint)
/*!
@brief The 'translate()' id.
*/
inline jint OrgApacheXpathCompilerFunctionTable_get_FUNC_TRANSLATE(void);
#define OrgApacheXpathCompilerFunctionTable_FUNC_TRANSLATE 26
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXpathCompilerFunctionTable, FUNC_TRANSLATE, jint)
/*!
@brief The 'concat()' id.
*/
inline jint OrgApacheXpathCompilerFunctionTable_get_FUNC_CONCAT(void);
#define OrgApacheXpathCompilerFunctionTable_FUNC_CONCAT 27
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXpathCompilerFunctionTable, FUNC_CONCAT, jint)
/*!
@brief The 'substring()' id.
*/
inline jint OrgApacheXpathCompilerFunctionTable_get_FUNC_SUBSTRING(void);
#define OrgApacheXpathCompilerFunctionTable_FUNC_SUBSTRING 29
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXpathCompilerFunctionTable, FUNC_SUBSTRING, jint)
/*!
@brief The 'string-length()' id.
*/
inline jint OrgApacheXpathCompilerFunctionTable_get_FUNC_STRING_LENGTH(void);
#define OrgApacheXpathCompilerFunctionTable_FUNC_STRING_LENGTH 30
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXpathCompilerFunctionTable, FUNC_STRING_LENGTH, jint)
/*!
@brief The 'system-property()' id.
*/
inline jint OrgApacheXpathCompilerFunctionTable_get_FUNC_SYSTEM_PROPERTY(void);
#define OrgApacheXpathCompilerFunctionTable_FUNC_SYSTEM_PROPERTY 31
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXpathCompilerFunctionTable, FUNC_SYSTEM_PROPERTY, jint)
/*!
@brief The 'lang()' id.
*/
inline jint OrgApacheXpathCompilerFunctionTable_get_FUNC_LANG(void);
#define OrgApacheXpathCompilerFunctionTable_FUNC_LANG 32
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXpathCompilerFunctionTable, FUNC_LANG, jint)
/*!
@brief The 'function-available()' id (XSLT).
*/
inline jint OrgApacheXpathCompilerFunctionTable_get_FUNC_EXT_FUNCTION_AVAILABLE(void);
#define OrgApacheXpathCompilerFunctionTable_FUNC_EXT_FUNCTION_AVAILABLE 33
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXpathCompilerFunctionTable, FUNC_EXT_FUNCTION_AVAILABLE, jint)
/*!
@brief The 'element-available()' id (XSLT).
*/
inline jint OrgApacheXpathCompilerFunctionTable_get_FUNC_EXT_ELEM_AVAILABLE(void);
#define OrgApacheXpathCompilerFunctionTable_FUNC_EXT_ELEM_AVAILABLE 34
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXpathCompilerFunctionTable, FUNC_EXT_ELEM_AVAILABLE, jint)
/*!
@brief The 'unparsed-entity-uri()' id (XSLT).
*/
inline jint OrgApacheXpathCompilerFunctionTable_get_FUNC_UNPARSED_ENTITY_URI(void);
#define OrgApacheXpathCompilerFunctionTable_FUNC_UNPARSED_ENTITY_URI 36
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXpathCompilerFunctionTable, FUNC_UNPARSED_ENTITY_URI, jint)
/*!
@brief The 'document-location()' id (Proprietary).
*/
inline jint OrgApacheXpathCompilerFunctionTable_get_FUNC_DOCLOCATION(void);
#define OrgApacheXpathCompilerFunctionTable_FUNC_DOCLOCATION 35
J2OBJC_STATIC_FIELD_CONSTANT(OrgApacheXpathCompilerFunctionTable, FUNC_DOCLOCATION, jint)
FOUNDATION_EXPORT void OrgApacheXpathCompilerFunctionTable_init(OrgApacheXpathCompilerFunctionTable *self);
FOUNDATION_EXPORT OrgApacheXpathCompilerFunctionTable *new_OrgApacheXpathCompilerFunctionTable_init(void) NS_RETURNS_RETAINED;
FOUNDATION_EXPORT OrgApacheXpathCompilerFunctionTable *create_OrgApacheXpathCompilerFunctionTable_init(void);
J2OBJC_TYPE_LITERAL_HEADER(OrgApacheXpathCompilerFunctionTable)
#endif
#if __has_feature(nullability)
#pragma clang diagnostic pop
#endif
#pragma clang diagnostic pop
#pragma pop_macro("INCLUDE_ALL_OrgApacheXpathCompilerFunctionTable")
| 36.123348 | 171 | 0.835061 | [
"object",
"transform"
] |
3d18c0a81e89182ac47e090a94c7d5dbb6cb2e75 | 709 | h | C | CI/rule/pclint/pclint_include/include_linux/c++/4.8.2/java/beans/beancontext/BeanContextProxy.h | chewaiwai/huaweicloud-sdk-c-obs | fbcd3dadd910c22af3a91aeb73ca0fee94d759fb | [
"Apache-2.0"
] | 22 | 2019-06-13T01:16:44.000Z | 2022-03-29T02:42:39.000Z | CI/rule/pclint/pclint_include/include_linux/c++/4.8.2/java/beans/beancontext/BeanContextProxy.h | chewaiwai/huaweicloud-sdk-c-obs | fbcd3dadd910c22af3a91aeb73ca0fee94d759fb | [
"Apache-2.0"
] | 26 | 2019-09-20T06:46:05.000Z | 2022-03-11T08:07:14.000Z | CI/rule/pclint/pclint_include/include_linux/c++/4.8.2/java/beans/beancontext/BeanContextProxy.h | chewaiwai/huaweicloud-sdk-c-obs | fbcd3dadd910c22af3a91aeb73ca0fee94d759fb | [
"Apache-2.0"
] | 14 | 2019-07-15T06:42:39.000Z | 2022-02-15T10:32:28.000Z |
// DO NOT EDIT THIS FILE - it is machine generated -*- c++ -*-
#ifndef __java_beans_beancontext_BeanContextProxy__
#define __java_beans_beancontext_BeanContextProxy__
#pragma interface
#include <java/lang/Object.h>
extern "Java"
{
namespace java
{
namespace beans
{
namespace beancontext
{
class BeanContextChild;
class BeanContextProxy;
}
}
}
}
class java::beans::beancontext::BeanContextProxy : public ::java::lang::Object
{
public:
virtual ::java::beans::beancontext::BeanContextChild * getBeanContextProxy() = 0;
static ::java::lang::Class class$;
} __attribute__ ((java_interface));
#endif // __java_beans_beancontext_BeanContextProxy__
| 20.852941 | 83 | 0.706629 | [
"object"
] |
3d1d49f0a7d29af3f3d71363c86e7b3715aecfde | 8,929 | h | C | tools/vs2010.sdk/Inc/fpstfmt.h | mphome/NBehave | a1b6a14dad058b158ed0ee267f069dc20e49af88 | [
"BSD-3-Clause"
] | null | null | null | tools/vs2010.sdk/Inc/fpstfmt.h | mphome/NBehave | a1b6a14dad058b158ed0ee267f069dc20e49af88 | [
"BSD-3-Clause"
] | null | null | null | tools/vs2010.sdk/Inc/fpstfmt.h | mphome/NBehave | a1b6a14dad058b158ed0ee267f069dc20e49af88 | [
"BSD-3-Clause"
] | null | null | null |
/* this ALWAYS GENERATED file contains the definitions for the interfaces */
/* File created by MIDL compiler version 7.00.0499 */
/* Compiler settings for fpstfmt.idl:
Oicf, W0, Zp8, env=Win32 (32b run)
protocol : dce , ms_ext, c_ext, robust
error checks: allocation ref bounds_check enum stub_data
VC __declspec() decoration level:
__declspec(uuid()), __declspec(selectany), __declspec(novtable)
DECLSPEC_UUID(), MIDL_INTERFACE()
*/
//@@MIDL_FILE_HEADING( )
#pragma warning( disable: 4049 ) /* more than 64k source lines */
/* verify that the <rpcndr.h> version is high enough to compile this file*/
#ifndef __REQUIRED_RPCNDR_H_VERSION__
#define __REQUIRED_RPCNDR_H_VERSION__ 475
#endif
/* verify that the <rpcsal.h> version is high enough to compile this file*/
#ifndef __REQUIRED_RPCSAL_H_VERSION__
#define __REQUIRED_RPCSAL_H_VERSION__ 100
#endif
#include "rpc.h"
#include "rpcndr.h"
#ifndef __RPCNDR_H_VERSION__
#error this stub requires an updated version of <rpcndr.h>
#endif // __RPCNDR_H_VERSION__
#ifndef COM_NO_WINDOWS_H
#include "windows.h"
#include "ole2.h"
#endif /*COM_NO_WINDOWS_H*/
#ifndef __fpstfmt_h__
#define __fpstfmt_h__
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
/* Forward Declarations */
#ifndef __IPersistFileFormat_FWD_DEFINED__
#define __IPersistFileFormat_FWD_DEFINED__
typedef interface IPersistFileFormat IPersistFileFormat;
#endif /* __IPersistFileFormat_FWD_DEFINED__ */
/* header files for imported files */
#include "oleidl.h"
#include "oaidl.h"
#ifdef __cplusplus
extern "C"{
#endif
/* interface __MIDL_itf_fpstfmt_0000_0000 */
/* [local] */
//=--------------------------------------------------------------------------=
// fpstfmt.h
//=--------------------------------------------------------------------------=
// (C) Copyright 1997 Microsoft Corporation. All Rights Reserved.
//
// THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// THE IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
// PARTICULAR PURPOSE.
//=--------------------------------------------------------------------------=
//
// Declarations for Vegas Shell's IPersistFileFormat.
//
////////////////////////////////////////////////////////////////////////////
// CLSID for CLSID_PersistFileFormat {3AFAE241-B530-11d0-8199-00A0C91BBEE3}
// DEFINE_GUID(CLSID_PersistFileFormat,
// 0x3afae241, 0xb530, 0x11d0, 0x81, 0x99, 0x0, 0xa0, 0xc9, 0x1b, 0xbe, 0xe3);
////////////////////////////////////////////////////////////////////////////
// Interface ID for IPersistFileFormat {3AFAE242-B530-11d0-8199-00A0C91BBEE3}
// DEFINE_GUID(IID_IPersistFileFormat,
// 0x3afae242, 0xb530, 0x11d0, 0x81, 0x99, 0x0, 0xa0, 0xc9, 0x1b, 0xbe, 0xe3);
#ifndef ___DEF_FORMAT_INDEX_DECLARATION__
#define ___DEF_FORMAT_INDEX_DECLARATION__
#define DEF_FORMAT_INDEX ((DWORD) 0) // used when caller does not know a specific format to specify
#endif ___DEF_FORMAT_INDEX_DECLARATION__
typedef
enum _PFF_RESULTS
{ STG_E_INVALIDCODEPAGE = ( ( 0x80000000 | ( 3 << 16 ) ) | 0x300 ) ,
STG_E_NOTTEXT = ( ( 0x80000000 | ( 3 << 16 ) ) | 0x302 ) ,
STG_S_DATALOSS = ( ( 0 | ( 3 << 16 ) ) | 0x301 )
} PFF_RESULTS;
extern RPC_IF_HANDLE __MIDL_itf_fpstfmt_0000_0000_v0_0_c_ifspec;
extern RPC_IF_HANDLE __MIDL_itf_fpstfmt_0000_0000_v0_0_s_ifspec;
#ifndef __IPersistFileFormat_INTERFACE_DEFINED__
#define __IPersistFileFormat_INTERFACE_DEFINED__
/* interface IPersistFileFormat */
/* [unique][version][uuid][object] */
EXTERN_C const IID IID_IPersistFileFormat;
#if defined(__cplusplus) && !defined(CINTERFACE)
MIDL_INTERFACE("3AFAE242-B530-11d0-8199-00A0C91BBEE3")
IPersistFileFormat : public IPersist
{
public:
virtual HRESULT STDMETHODCALLTYPE IsDirty(
/* [out] */ __RPC__out BOOL *pfIsDirty) = 0;
virtual HRESULT STDMETHODCALLTYPE InitNew(
/* [in] */ DWORD nFormatIndex) = 0;
virtual HRESULT STDMETHODCALLTYPE Load(
/* [in] */ __RPC__in LPCOLESTR pszFilename,
/* [in] */ DWORD grfMode,
/* [in] */ BOOL fReadOnly) = 0;
virtual HRESULT STDMETHODCALLTYPE Save(
/* [in] */ __RPC__in LPCOLESTR pszFilename,
/* [in] */ BOOL fRemember,
/* [in] */ DWORD nFormatIndex) = 0;
virtual HRESULT STDMETHODCALLTYPE SaveCompleted(
/* [in] */ __RPC__in LPCOLESTR pszFilename) = 0;
virtual HRESULT STDMETHODCALLTYPE GetCurFile(
/* [out] */ __RPC__deref_out_opt LPOLESTR *ppszFilename,
/* [out] */ __RPC__out DWORD *pnFormatIndex) = 0;
virtual HRESULT STDMETHODCALLTYPE GetFormatList(
/* [out] */ __RPC__deref_out_opt LPOLESTR *ppszFormatList) = 0;
};
#else /* C style interface */
typedef struct IPersistFileFormatVtbl
{
BEGIN_INTERFACE
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
IPersistFileFormat * This,
/* [in] */ __RPC__in REFIID riid,
/* [iid_is][out] */
__RPC__deref_out void **ppvObject);
ULONG ( STDMETHODCALLTYPE *AddRef )(
IPersistFileFormat * This);
ULONG ( STDMETHODCALLTYPE *Release )(
IPersistFileFormat * This);
HRESULT ( STDMETHODCALLTYPE *GetClassID )(
IPersistFileFormat * This,
/* [out] */ __RPC__out CLSID *pClassID);
HRESULT ( STDMETHODCALLTYPE *IsDirty )(
IPersistFileFormat * This,
/* [out] */ __RPC__out BOOL *pfIsDirty);
HRESULT ( STDMETHODCALLTYPE *InitNew )(
IPersistFileFormat * This,
/* [in] */ DWORD nFormatIndex);
HRESULT ( STDMETHODCALLTYPE *Load )(
IPersistFileFormat * This,
/* [in] */ __RPC__in LPCOLESTR pszFilename,
/* [in] */ DWORD grfMode,
/* [in] */ BOOL fReadOnly);
HRESULT ( STDMETHODCALLTYPE *Save )(
IPersistFileFormat * This,
/* [in] */ __RPC__in LPCOLESTR pszFilename,
/* [in] */ BOOL fRemember,
/* [in] */ DWORD nFormatIndex);
HRESULT ( STDMETHODCALLTYPE *SaveCompleted )(
IPersistFileFormat * This,
/* [in] */ __RPC__in LPCOLESTR pszFilename);
HRESULT ( STDMETHODCALLTYPE *GetCurFile )(
IPersistFileFormat * This,
/* [out] */ __RPC__deref_out_opt LPOLESTR *ppszFilename,
/* [out] */ __RPC__out DWORD *pnFormatIndex);
HRESULT ( STDMETHODCALLTYPE *GetFormatList )(
IPersistFileFormat * This,
/* [out] */ __RPC__deref_out_opt LPOLESTR *ppszFormatList);
END_INTERFACE
} IPersistFileFormatVtbl;
interface IPersistFileFormat
{
CONST_VTBL struct IPersistFileFormatVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define IPersistFileFormat_QueryInterface(This,riid,ppvObject) \
( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) )
#define IPersistFileFormat_AddRef(This) \
( (This)->lpVtbl -> AddRef(This) )
#define IPersistFileFormat_Release(This) \
( (This)->lpVtbl -> Release(This) )
#define IPersistFileFormat_GetClassID(This,pClassID) \
( (This)->lpVtbl -> GetClassID(This,pClassID) )
#define IPersistFileFormat_IsDirty(This,pfIsDirty) \
( (This)->lpVtbl -> IsDirty(This,pfIsDirty) )
#define IPersistFileFormat_InitNew(This,nFormatIndex) \
( (This)->lpVtbl -> InitNew(This,nFormatIndex) )
#define IPersistFileFormat_Load(This,pszFilename,grfMode,fReadOnly) \
( (This)->lpVtbl -> Load(This,pszFilename,grfMode,fReadOnly) )
#define IPersistFileFormat_Save(This,pszFilename,fRemember,nFormatIndex) \
( (This)->lpVtbl -> Save(This,pszFilename,fRemember,nFormatIndex) )
#define IPersistFileFormat_SaveCompleted(This,pszFilename) \
( (This)->lpVtbl -> SaveCompleted(This,pszFilename) )
#define IPersistFileFormat_GetCurFile(This,ppszFilename,pnFormatIndex) \
( (This)->lpVtbl -> GetCurFile(This,ppszFilename,pnFormatIndex) )
#define IPersistFileFormat_GetFormatList(This,ppszFormatList) \
( (This)->lpVtbl -> GetFormatList(This,ppszFormatList) )
#endif /* COBJMACROS */
#endif /* C style interface */
#endif /* __IPersistFileFormat_INTERFACE_DEFINED__ */
/* Additional Prototypes for ALL interfaces */
/* end of Additional Prototypes */
#ifdef __cplusplus
}
#endif
#endif
| 32.234657 | 104 | 0.616306 | [
"object"
] |
3d1ea717d01a557bf504a21fcb3fa8252d6ff1d0 | 376 | h | C | src/MPC.h | GlinZhu/CarND-MPC-Project | 8ace132b5e1e7e4c0ea59f5037befc480588f161 | [
"MIT"
] | null | null | null | src/MPC.h | GlinZhu/CarND-MPC-Project | 8ace132b5e1e7e4c0ea59f5037befc480588f161 | [
"MIT"
] | null | null | null | src/MPC.h | GlinZhu/CarND-MPC-Project | 8ace132b5e1e7e4c0ea59f5037befc480588f161 | [
"MIT"
] | null | null | null | #ifndef MPC_H
#define MPC_H
#include <vector>
#include "Eigen-3.3/Eigen/Core"
class MPC {
public:
MPC();
virtual ~MPC();
// Solve the model given an initial state and polynomial coefficients.
// Return the first actuations.
std::vector<double> Solve(const Eigen::VectorXd &state,
const Eigen::VectorXd &coeffs);
};
#endif // MPC_H | 19.789474 | 72 | 0.646277 | [
"vector",
"model"
] |
3d21953dcbb47d66c26d8eae5ad94be21ae0ecfa | 3,883 | h | C | Source/core/svg/SVGFitToViewBox.h | scheib/blink | d18c0cc5b4e96ea87c556bfa57955538de498a9f | [
"BSD-3-Clause"
] | 1 | 2017-08-25T05:15:52.000Z | 2017-08-25T05:15:52.000Z | Source/core/svg/SVGFitToViewBox.h | scheib/blink | d18c0cc5b4e96ea87c556bfa57955538de498a9f | [
"BSD-3-Clause"
] | null | null | null | Source/core/svg/SVGFitToViewBox.h | scheib/blink | d18c0cc5b4e96ea87c556bfa57955538de498a9f | [
"BSD-3-Clause"
] | null | null | null | /*
* Copyright (C) 2004, 2005, 2008 Nikolas Zimmermann <zimmermann@kde.org>
* Copyright (C) 2004, 2005, 2006, 2007, 2010 Rob Buis <buis@kde.org>
* Copyright (C) 2014 Samsung Electronics. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#ifndef SVGFitToViewBox_h
#define SVGFitToViewBox_h
#include "core/SVGNames.h"
#include "core/dom/Document.h"
#include "core/dom/QualifiedName.h"
#include "core/svg/SVGAnimatedPreserveAspectRatio.h"
#include "core/svg/SVGAnimatedRect.h"
#include "core/svg/SVGDocumentExtensions.h"
#include "core/svg/SVGParsingError.h"
#include "core/svg/SVGPreserveAspectRatio.h"
#include "core/svg/SVGRect.h"
#include "platform/heap/Handle.h"
#include "wtf/HashSet.h"
namespace blink {
class AffineTransform;
class Document;
class SVGFitToViewBox : public WillBeGarbageCollectedMixin {
public:
enum PropertyMapPolicy {
PropertyMapPolicyAdd,
PropertyMapPolicySkip,
};
static AffineTransform viewBoxToViewTransform(const FloatRect& viewBoxRect, PassRefPtrWillBeRawPtr<SVGPreserveAspectRatio>, float viewWidth, float viewHeight);
static bool isKnownAttribute(const QualifiedName&);
static void addSupportedAttributes(HashSet<QualifiedName>&);
bool parseAttribute(const QualifiedName& name, const AtomicString& value, Document& document, SVGParsingError& parseError)
{
if (name == SVGNames::viewBoxAttr) {
m_viewBox->setBaseValueAsString(value, parseError);
return true;
}
if (name == SVGNames::preserveAspectRatioAttr) {
m_preserveAspectRatio->setBaseValueAsString(value, parseError);
return true;
}
return false;
}
bool hasEmptyViewBox() const { return m_viewBox->currentValue()->isValid() && m_viewBox->currentValue()->value().isEmpty(); }
// JS API
SVGAnimatedRect* viewBox() const { return m_viewBox.get(); }
SVGAnimatedPreserveAspectRatio* preserveAspectRatio() const { return m_preserveAspectRatio.get(); }
virtual void trace(Visitor*);
protected:
SVGFitToViewBox();
// FIXME: Oilpan: the construction of this mixin requires heap allocation,
// which cannot be safely done with Oilpan until the object that include
// this mixin have had its vptr initialized -- so as to be able to
// accurately trace the entire object should a GC strike while constructing
// the mixin.
//
// Try to come up with a more natural alternative and solution that doesn't
// require hoisting the constructor code for mixins into a separate method
// like initialize(). It makes construction of these heap-allocation mixins
// safe in the meantime, however.
//
void initialize(SVGElement* contextElement, PropertyMapPolicy = PropertyMapPolicyAdd);
void updateViewBox(const FloatRect&);
void clearViewBox() { m_viewBox = nullptr; }
void clearPreserveAspectRatio() { m_preserveAspectRatio = nullptr; }
private:
RefPtrWillBeMember<SVGAnimatedRect> m_viewBox;
RefPtrWillBeMember<SVGAnimatedPreserveAspectRatio> m_preserveAspectRatio;
};
} // namespace blink
#endif // SVGFitToViewBox_h
| 37.699029 | 163 | 0.735514 | [
"object"
] |
2cf6e04b08fc5d9eb04d9e0e0673f6ffd77a6bce | 46,903 | h | C | include/linux/jbd2.h | jowoni/Linux | d00f1b4845c3a01e8db47189276a79ff08595dd1 | [
"Apache-2.0"
] | null | null | null | include/linux/jbd2.h | jowoni/Linux | d00f1b4845c3a01e8db47189276a79ff08595dd1 | [
"Apache-2.0"
] | null | null | null | include/linux/jbd2.h | jowoni/Linux | d00f1b4845c3a01e8db47189276a79ff08595dd1 | [
"Apache-2.0"
] | null | null | null | /*
* linux/include/linux/jbd2.h
*
* Written by Stephen C. Tweedie <sct@redhat.com>
*
* Copyright 1998-2000 Red Hat, Inc --- All Rights Reserved
*
* This file is part of the Linux kernel and is made available under
* the terms of the GNU General Public License, version 2, or at your
* option, any later version, incorporated herein by reference.
*
* Definitions for transaction data structures for the buffer cache
* filesystem journaling support.
*/
#ifndef _LINUX_JBD2_H
#define _LINUX_JBD2_H
/* Allow this file to be included directly into e2fsprogs */
#ifndef __KERNEL__
#include "jfs_compat.h"
#define JBD2_DEBUG
#else
#include <linux/types.h>
#include <linux/buffer_head.h>
#include <linux/journal-head.h>
#include <linux/stddef.h>
#include <linux/mutex.h>
#include <linux/timer.h>
#include <linux/slab.h>
#include <linux/bit_spinlock.h>
#include <crypto/hash.h>
#endif
#define journal_oom_retry 1
/*
* Define JBD2_PARANIOD_IOFAIL to cause a kernel BUG() if ext4 finds
* certain classes of error which can occur due to failed IOs. Under
* normal use we want ext4 to continue after such errors, because
* hardware _can_ fail, but for debugging purposes when running tests on
* known-good hardware we may want to trap these errors.
*/
#undef JBD2_PARANOID_IOFAIL
/*
* The default maximum commit age, in seconds.
*/
#define JBD2_DEFAULT_MAX_COMMIT_AGE 5
#ifdef CONFIG_JBD2_DEBUG
/*
* Define JBD2_EXPENSIVE_CHECKING to enable more expensive internal
* consistency checks. By default we don't do this unless
* CONFIG_JBD2_DEBUG is on.
*/
#define JBD2_EXPENSIVE_CHECKING
extern ushort jbd2_journal_enable_debug;
void __jbd2_debug(int level, const char *file, const char *func,
unsigned int line, const char *fmt, ...);
#define jbd_debug(n, fmt, a...) \
__jbd2_debug((n), __FILE__, __func__, __LINE__, (fmt), ##a)
#else
#define jbd_debug(n, fmt, a...) /**/
#endif
extern void *jbd2_alloc(size_t size, gfp_t flags);
extern void jbd2_free(void *ptr, size_t size);
#define JBD2_MIN_JOURNAL_BLOCKS 1024
#ifdef __KERNEL__
/**
* typedef handle_t - The handle_t type represents a single atomic update being performed by some process.
*
* All filesystem modifications made by the process go
* through this handle. Recursive operations (such as quota operations)
* are gathered into a single update.
*
* The buffer credits field is used to account for journaled buffers
* being modified by the running process. To ensure that there is
* enough log space for all outstanding operations, we need to limit the
* number of outstanding buffers possible at any time. When the
* operation completes, any buffer credits not used are credited back to
* the transaction, so that at all times we know how many buffers the
* outstanding updates on a transaction might possibly touch.
*
* This is an opaque datatype.
**/
typedef struct jbd2_journal_handle handle_t; /* Atomic operation type */
/**
* typedef journal_t - The journal_t maintains all of the journaling state information for a single filesystem.
*
* journal_t is linked to from the fs superblock structure.
*
* We use the journal_t to keep track of all outstanding transaction
* activity on the filesystem, and to manage the state of the log
* writing process.
*
* This is an opaque datatype.
**/
typedef struct journal_s journal_t; /* Journal control structure */
#endif
/*
* Internal structures used by the logging mechanism:
*/
#define JBD2_MAGIC_NUMBER 0xc03b3998U /* The first 4 bytes of /dev/random! */
/*
* On-disk structures
*/
/*
* Descriptor block types:
*/
#define JBD2_DESCRIPTOR_BLOCK 1
#define JBD2_COMMIT_BLOCK 2
#define JBD2_SUPERBLOCK_V1 3
#define JBD2_SUPERBLOCK_V2 4
#define JBD2_REVOKE_BLOCK 5
/*
* Standard header for all descriptor blocks:
*/
typedef struct journal_header_s
{
__be32 h_magic;
__be32 h_blocktype;
__be32 h_sequence;
} journal_header_t;
/*
* Checksum types.
*/
#define JBD2_CRC32_CHKSUM 1
#define JBD2_MD5_CHKSUM 2
#define JBD2_SHA1_CHKSUM 3
#define JBD2_CRC32C_CHKSUM 4
#define JBD2_CRC32_CHKSUM_SIZE 4
#define JBD2_CHECKSUM_BYTES (32 / sizeof(u32))
/*
* Commit block header for storing transactional checksums:
*
* NOTE: If FEATURE_COMPAT_CHECKSUM (checksum v1) is set, the h_chksum*
* fields are used to store a checksum of the descriptor and data blocks.
*
* If FEATURE_INCOMPAT_CSUM_V2 (checksum v2) is set, then the h_chksum
* field is used to store crc32c(uuid+commit_block). Each journal metadata
* block gets its own checksum, and data block checksums are stored in
* journal_block_tag (in the descriptor). The other h_chksum* fields are
* not used.
*
* If FEATURE_INCOMPAT_CSUM_V3 is set, the descriptor block uses
* journal_block_tag3_t to store a full 32-bit checksum. Everything else
* is the same as v2.
*
* Checksum v1, v2, and v3 are mutually exclusive features.
*/
struct commit_header {
__be32 h_magic;
__be32 h_blocktype;
__be32 h_sequence;
unsigned char h_chksum_type;
unsigned char h_chksum_size;
unsigned char h_padding[2];
__be32 h_chksum[JBD2_CHECKSUM_BYTES];
__be64 h_commit_sec;
__be32 h_commit_nsec;
};
/*
* The block tag: used to describe a single buffer in the journal.
* t_blocknr_high is only used if INCOMPAT_64BIT is set, so this
* raw struct shouldn't be used for pointer math or sizeof() - use
* journal_tag_bytes(journal) instead to compute this.
*/
typedef struct journal_block_tag3_s
{
__be32 t_blocknr; /* The on-disk block number */
__be32 t_flags; /* See below */
__be32 t_blocknr_high; /* most-significant high 32bits. */
__be32 t_checksum; /* crc32c(uuid+seq+block) */
} journal_block_tag3_t;
typedef struct journal_block_tag_s
{
__be32 t_blocknr; /* The on-disk block number */
__be16 t_checksum; /* truncated crc32c(uuid+seq+block) */
__be16 t_flags; /* See below */
__be32 t_blocknr_high; /* most-significant high 32bits. */
} journal_block_tag_t;
/* Tail of descriptor or revoke block, for checksumming */
struct jbd2_journal_block_tail {
__be32 t_checksum; /* crc32c(uuid+descr_block) */
};
/*
* The revoke descriptor: used on disk to describe a series of blocks to
* be revoked from the log
*/
typedef struct jbd2_journal_revoke_header_s
{
journal_header_t r_header;
__be32 r_count; /* Count of bytes used in the block */
} jbd2_journal_revoke_header_t;
/* Definitions for the journal tag flags word: */
#define JBD2_FLAG_ESCAPE 1 /* on-disk block is escaped */
#define JBD2_FLAG_SAME_UUID 2 /* block has same uuid as previous */
#define JBD2_FLAG_DELETED 4 /* block deleted by this transaction */
#define JBD2_FLAG_LAST_TAG 8 /* last tag in this descriptor block */
/*
* The journal superblock. All fields are in big-endian byte order.
*/
typedef struct journal_superblock_s
{
/* 0x0000 */
journal_header_t s_header;
/* 0x000C */
/* Static information describing the journal */
__be32 s_blocksize; /* journal device blocksize */
__be32 s_maxlen; /* total blocks in journal file */
__be32 s_first; /* first block of log information */
/* 0x0018 */
/* Dynamic information describing the current state of the log */
__be32 s_sequence; /* first commit ID expected in log */
__be32 s_start; /* blocknr of start of log */
/* 0x0020 */
/* Error value, as set by jbd2_journal_abort(). */
__be32 s_errno;
/* 0x0024 */
/* Remaining fields are only valid in a version-2 superblock */
__be32 s_feature_compat; /* compatible feature set */
__be32 s_feature_incompat; /* incompatible feature set */
__be32 s_feature_ro_compat; /* readonly-compatible feature set */
/* 0x0030 */
__u8 s_uuid[16]; /* 128-bit uuid for journal */
/* 0x0040 */
__be32 s_nr_users; /* Nr of filesystems sharing log */
__be32 s_dynsuper; /* Blocknr of dynamic superblock copy*/
/* 0x0048 */
__be32 s_max_transaction; /* Limit of journal blocks per trans.*/
__be32 s_max_trans_data; /* Limit of data blocks per trans. */
/* 0x0050 */
__u8 s_checksum_type; /* checksum type */
__u8 s_padding2[3];
__u32 s_padding[42];
__be32 s_checksum; /* crc32c(superblock) */
/* 0x0100 */
__u8 s_users[16*48]; /* ids of all fs'es sharing the log */
/* 0x0400 */
} journal_superblock_t;
/* Use the jbd2_{has,set,clear}_feature_* helpers; these will be removed */
#define JBD2_HAS_COMPAT_FEATURE(j,mask) \
((j)->j_format_version >= 2 && \
((j)->j_superblock->s_feature_compat & cpu_to_be32((mask))))
#define JBD2_HAS_RO_COMPAT_FEATURE(j,mask) \
((j)->j_format_version >= 2 && \
((j)->j_superblock->s_feature_ro_compat & cpu_to_be32((mask))))
#define JBD2_HAS_INCOMPAT_FEATURE(j,mask) \
((j)->j_format_version >= 2 && \
((j)->j_superblock->s_feature_incompat & cpu_to_be32((mask))))
#define JBD2_FEATURE_COMPAT_CHECKSUM 0x00000001
#define JBD2_FEATURE_INCOMPAT_REVOKE 0x00000001
#define JBD2_FEATURE_INCOMPAT_64BIT 0x00000002
#define JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT 0x00000004
#define JBD2_FEATURE_INCOMPAT_CSUM_V2 0x00000008
#define JBD2_FEATURE_INCOMPAT_CSUM_V3 0x00000010
/* See "journal feature predicate functions" below */
/* Features known to this kernel version: */
#define JBD2_KNOWN_COMPAT_FEATURES JBD2_FEATURE_COMPAT_CHECKSUM
#define JBD2_KNOWN_ROCOMPAT_FEATURES 0
#define JBD2_KNOWN_INCOMPAT_FEATURES (JBD2_FEATURE_INCOMPAT_REVOKE | \
JBD2_FEATURE_INCOMPAT_64BIT | \
JBD2_FEATURE_INCOMPAT_ASYNC_COMMIT | \
JBD2_FEATURE_INCOMPAT_CSUM_V2 | \
JBD2_FEATURE_INCOMPAT_CSUM_V3)
#ifdef __KERNEL__
#include <linux/fs.h>
#include <linux/sched.h>
enum jbd_state_bits {
BH_JBD /* Has an attached ext3 journal_head */
= BH_PrivateStart,
BH_JWrite, /* Being written to log (@@@ DEBUGGING) */
BH_Freed, /* Has been freed (truncated) */
BH_Revoked, /* Has been revoked from the log */
BH_RevokeValid, /* Revoked flag is valid */
BH_JBDDirty, /* Is dirty but journaled */
BH_State, /* Pins most journal_head state */
BH_JournalHead, /* Pins bh->b_private and jh->b_bh */
BH_Shadow, /* IO on shadow buffer is running */
BH_Verified, /* Metadata block has been verified ok */
BH_JBDPrivateStart, /* First bit available for private use by FS */
};
BUFFER_FNS(JBD, jbd)
BUFFER_FNS(JWrite, jwrite)
BUFFER_FNS(JBDDirty, jbddirty)
TAS_BUFFER_FNS(JBDDirty, jbddirty)
BUFFER_FNS(Revoked, revoked)
TAS_BUFFER_FNS(Revoked, revoked)
BUFFER_FNS(RevokeValid, revokevalid)
TAS_BUFFER_FNS(RevokeValid, revokevalid)
BUFFER_FNS(Freed, freed)
BUFFER_FNS(Shadow, shadow)
BUFFER_FNS(Verified, verified)
static inline struct buffer_head *jh2bh(struct journal_head *jh)
{
return jh->b_bh;
}
static inline struct journal_head *bh2jh(struct buffer_head *bh)
{
return bh->b_private;
}
static inline void jbd_lock_bh_state(struct buffer_head *bh)
{
bit_spin_lock(BH_State, &bh->b_state);
}
static inline int jbd_trylock_bh_state(struct buffer_head *bh)
{
return bit_spin_trylock(BH_State, &bh->b_state);
}
static inline int jbd_is_locked_bh_state(struct buffer_head *bh)
{
return bit_spin_is_locked(BH_State, &bh->b_state);
}
static inline void jbd_unlock_bh_state(struct buffer_head *bh)
{
bit_spin_unlock(BH_State, &bh->b_state);
}
static inline void jbd_lock_bh_journal_head(struct buffer_head *bh)
{
bit_spin_lock(BH_JournalHead, &bh->b_state);
}
static inline void jbd_unlock_bh_journal_head(struct buffer_head *bh)
{
bit_spin_unlock(BH_JournalHead, &bh->b_state);
}
#define J_ASSERT(assert) BUG_ON(!(assert))
#define J_ASSERT_BH(bh, expr) J_ASSERT(expr)
#define J_ASSERT_JH(jh, expr) J_ASSERT(expr)
#if defined(JBD2_PARANOID_IOFAIL)
#define J_EXPECT(expr, why...) J_ASSERT(expr)
#define J_EXPECT_BH(bh, expr, why...) J_ASSERT_BH(bh, expr)
#define J_EXPECT_JH(jh, expr, why...) J_ASSERT_JH(jh, expr)
#else
#define __journal_expect(expr, why...) \
({ \
int val = (expr); \
if (!val) { \
printk(KERN_ERR \
"JBD2 unexpected failure: %s: %s;\n", \
__func__, #expr); \
printk(KERN_ERR why "\n"); \
} \
val; \
})
#define J_EXPECT(expr, why...) __journal_expect(expr, ## why)
#define J_EXPECT_BH(bh, expr, why...) __journal_expect(expr, ## why)
#define J_EXPECT_JH(jh, expr, why...) __journal_expect(expr, ## why)
#endif
/* Flags in jbd_inode->i_flags */
#define __JI_COMMIT_RUNNING 0
#define __JI_WRITE_DATA 1
#define __JI_WAIT_DATA 2
/*
* Commit of the inode data in progress. We use this flag to protect us from
* concurrent deletion of inode. We cannot use reference to inode for this
* since we cannot afford doing last iput() on behalf of kjournald
*/
#define JI_COMMIT_RUNNING (1 << __JI_COMMIT_RUNNING)
/* Write allocated dirty buffers in this inode before commit */
#define JI_WRITE_DATA (1 << __JI_WRITE_DATA)
/* Wait for outstanding data writes for this inode before commit */
#define JI_WAIT_DATA (1 << __JI_WAIT_DATA)
/**
* struct jbd_inode - The jbd_inode type is the structure linking inodes in
* ordered mode present in a transaction so that we can sync them during commit.
*/
struct jbd2_inode {
/**
* @i_transaction:
*
* Which transaction does this inode belong to? Either the running
* transaction or the committing one. [j_list_lock]
*/
transaction_t *i_transaction;
/**
* @i_next_transaction:
*
* Pointer to the running transaction modifying inode's data in case
* there is already a committing transaction touching it. [j_list_lock]
*/
transaction_t *i_next_transaction;
/**
* @i_list: List of inodes in the i_transaction [j_list_lock]
*/
struct list_head i_list;
/**
* @i_vfs_inode:
*
* VFS inode this inode belongs to [constant for lifetime of structure]
*/
struct inode *i_vfs_inode;
/**
* @i_flags: Flags of inode [j_list_lock]
*/
unsigned long i_flags;
};
struct jbd2_revoke_table_s;
/**
* struct handle_s - The handle_s type is the concrete type associated with
* handle_t.
* @h_transaction: Which compound transaction is this update a part of?
* @h_journal: Which journal handle belongs to - used iff h_reserved set.
* @h_rsv_handle: Handle reserved for finishing the logical operation.
* @h_buffer_credits: Number of remaining buffers we are allowed to dirty.
* @h_ref: Reference count on this handle.
* @h_err: Field for caller's use to track errors through large fs operations.
* @h_sync: Flag for sync-on-close.
* @h_jdata: Flag to force data journaling.
* @h_reserved: Flag for handle for reserved credits.
* @h_aborted: Flag indicating fatal error on handle.
* @h_type: For handle statistics.
* @h_line_no: For handle statistics.
* @h_start_jiffies: Handle Start time.
* @h_requested_credits: Holds @h_buffer_credits after handle is started.
* @saved_alloc_context: Saved context while transaction is open.
**/
/* Docbook can't yet cope with the bit fields, but will leave the documentation
* in so it can be fixed later.
*/
struct jbd2_journal_handle
{
union {
transaction_t *h_transaction;
/* Which journal handle belongs to - used iff h_reserved set */
journal_t *h_journal;
};
handle_t *h_rsv_handle;
int h_buffer_credits;
int h_ref;
int h_err;
/* Flags [no locking] */
unsigned int h_sync: 1;
unsigned int h_jdata: 1;
unsigned int h_reserved: 1;
unsigned int h_aborted: 1;
unsigned int h_type: 8;
unsigned int h_line_no: 16;
unsigned long h_start_jiffies;
unsigned int h_requested_credits;
unsigned int saved_alloc_context;
};
/*
* Some stats for checkpoint phase
*/
struct transaction_chp_stats_s {
unsigned long cs_chp_time;
__u32 cs_forced_to_close;
__u32 cs_written;
__u32 cs_dropped;
};
/* The transaction_t type is the guts of the journaling mechanism. It
* tracks a compound transaction through its various states:
*
* RUNNING: accepting new updates
* LOCKED: Updates still running but we don't accept new ones
* RUNDOWN: Updates are tidying up but have finished requesting
* new buffers to modify (state not used for now)
* FLUSH: All updates complete, but we are still writing to disk
* COMMIT: All data on disk, writing commit record
* FINISHED: We still have to keep the transaction for checkpointing.
*
* The transaction keeps track of all of the buffers modified by a
* running transaction, and all of the buffers committed but not yet
* flushed to home for finished transactions.
*/
/*
* Lock ranking:
*
* j_list_lock
* ->jbd_lock_bh_journal_head() (This is "innermost")
*
* j_state_lock
* ->jbd_lock_bh_state()
*
* jbd_lock_bh_state()
* ->j_list_lock
*
* j_state_lock
* ->t_handle_lock
*
* j_state_lock
* ->j_list_lock (journal_unmap_buffer)
*
*/
struct transaction_s
{
/* Pointer to the journal for this transaction. [no locking] */
journal_t *t_journal;
/* Sequence number for this transaction [no locking] */
tid_t t_tid;
/*
* Transaction's current state
* [no locking - only kjournald2 alters this]
* [j_list_lock] guards transition of a transaction into T_FINISHED
* state and subsequent call of __jbd2_journal_drop_transaction()
* FIXME: needs barriers
* KLUDGE: [use j_state_lock]
*/
enum {
T_RUNNING,
T_LOCKED,
T_SWITCH,
T_FLUSH,
T_COMMIT,
T_COMMIT_DFLUSH,
T_COMMIT_JFLUSH,
T_COMMIT_CALLBACK,
T_FINISHED
} t_state;
/*
* Where in the log does this transaction's commit start? [no locking]
*/
unsigned long t_log_start;
/* Number of buffers on the t_buffers list [j_list_lock] */
int t_nr_buffers;
/*
* Doubly-linked circular list of all buffers reserved but not yet
* modified by this transaction [j_list_lock]
*/
struct journal_head *t_reserved_list;
/*
* Doubly-linked circular list of all metadata buffers owned by this
* transaction [j_list_lock]
*/
struct journal_head *t_buffers;
/*
* Doubly-linked circular list of all forget buffers (superseded
* buffers which we can un-checkpoint once this transaction commits)
* [j_list_lock]
*/
struct journal_head *t_forget;
/*
* Doubly-linked circular list of all buffers still to be flushed before
* this transaction can be checkpointed. [j_list_lock]
*/
struct journal_head *t_checkpoint_list;
/*
* Doubly-linked circular list of all buffers submitted for IO while
* checkpointing. [j_list_lock]
*/
struct journal_head *t_checkpoint_io_list;
/*
* Doubly-linked circular list of metadata buffers being shadowed by log
* IO. The IO buffers on the iobuf list and the shadow buffers on this
* list match each other one for one at all times. [j_list_lock]
*/
struct journal_head *t_shadow_list;
/*
* List of inodes whose data we've modified in data=ordered mode.
* [j_list_lock]
*/
struct list_head t_inode_list;
/*
* Protects info related to handles
*/
spinlock_t t_handle_lock;
/*
* Longest time some handle had to wait for running transaction
*/
unsigned long t_max_wait;
/*
* When transaction started
*/
unsigned long t_start;
/*
* When commit was requested
*/
unsigned long t_requested;
/*
* Checkpointing stats [j_checkpoint_sem]
*/
struct transaction_chp_stats_s t_chp_stats;
/*
* Number of outstanding updates running on this transaction
* [none]
*/
atomic_t t_updates;
/*
* Number of buffers reserved for use by all handles in this transaction
* handle but not yet modified. [none]
*/
atomic_t t_outstanding_credits;
/*
* Forward and backward links for the circular list of all transactions
* awaiting checkpoint. [j_list_lock]
*/
transaction_t *t_cpnext, *t_cpprev;
/*
* When will the transaction expire (become due for commit), in jiffies?
* [no locking]
*/
unsigned long t_expires;
/*
* When this transaction started, in nanoseconds [no locking]
*/
ktime_t t_start_time;
/*
* How many handles used this transaction? [none]
*/
atomic_t t_handle_count;
/*
* This transaction is being forced and some process is
* waiting for it to finish.
*/
unsigned int t_synchronous_commit:1;
/* Disk flush needs to be sent to fs partition [no locking] */
int t_need_data_flush;
/*
* For use by the filesystem to store fs-specific data
* structures associated with the transaction
*/
struct list_head t_private_list;
};
struct transaction_run_stats_s {
unsigned long rs_wait;
unsigned long rs_request_delay;
unsigned long rs_running;
unsigned long rs_locked;
unsigned long rs_flushing;
unsigned long rs_logging;
__u32 rs_handle_count;
__u32 rs_blocks;
__u32 rs_blocks_logged;
};
struct transaction_stats_s {
unsigned long ts_tid;
unsigned long ts_requested;
struct transaction_run_stats_s run;
};
static inline unsigned long
jbd2_time_diff(unsigned long start, unsigned long end)
{
if (end >= start)
return end - start;
return end + (MAX_JIFFY_OFFSET - start);
}
#define JBD2_NR_BATCH 64
/**
* struct journal_s - The journal_s type is the concrete type associated with
* journal_t.
*/
struct journal_s
{
/**
* @j_flags: General journaling state flags [j_state_lock]
*/
unsigned long j_flags;
/**
* @j_errno:
*
* Is there an outstanding uncleared error on the journal (from a prior
* abort)? [j_state_lock]
*/
int j_errno;
/**
* @j_sb_buffer: The first part of the superblock buffer.
*/
struct buffer_head *j_sb_buffer;
/**
* @j_superblock: The second part of the superblock buffer.
*/
journal_superblock_t *j_superblock;
/**
* @j_format_version: Version of the superblock format.
*/
int j_format_version;
/**
* @j_state_lock: Protect the various scalars in the journal.
*/
rwlock_t j_state_lock;
/**
* @j_barrier_count:
*
* Number of processes waiting to create a barrier lock [j_state_lock]
*/
int j_barrier_count;
/**
* @j_barrier: The barrier lock itself.
*/
struct mutex j_barrier;
/**
* @j_running_transaction:
*
* Transactions: The current running transaction...
* [j_state_lock] [caller holding open handle]
*/
transaction_t *j_running_transaction;
/**
* @j_committing_transaction:
*
* the transaction we are pushing to disk
* [j_state_lock] [caller holding open handle]
*/
transaction_t *j_committing_transaction;
/**
* @j_checkpoint_transactions:
*
* ... and a linked circular list of all transactions waiting for
* checkpointing. [j_list_lock]
*/
transaction_t *j_checkpoint_transactions;
/**
* @j_wait_transaction_locked:
*
* Wait queue for waiting for a locked transaction to start committing,
* or for a barrier lock to be released.
*/
wait_queue_head_t j_wait_transaction_locked;
/**
* @j_wait_done_commit: Wait queue for waiting for commit to complete.
*/
wait_queue_head_t j_wait_done_commit;
/**
* @j_wait_commit: Wait queue to trigger commit.
*/
wait_queue_head_t j_wait_commit;
/**
* @j_wait_updates: Wait queue to wait for updates to complete.
*/
wait_queue_head_t j_wait_updates;
/**
* @j_wait_reserved:
*
* Wait queue to wait for reserved buffer credits to drop.
*/
wait_queue_head_t j_wait_reserved;
/**
* @j_checkpoint_mutex:
*
* Semaphore for locking against concurrent checkpoints.
*/
struct mutex j_checkpoint_mutex;
/**
* @j_chkpt_bhs:
*
* List of buffer heads used by the checkpoint routine. This
* was moved from jbd2_log_do_checkpoint() to reduce stack
* usage. Access to this array is controlled by the
* @j_checkpoint_mutex. [j_checkpoint_mutex]
*/
struct buffer_head *j_chkpt_bhs[JBD2_NR_BATCH];
/**
* @j_head:
*
* Journal head: identifies the first unused block in the journal.
* [j_state_lock]
*/
unsigned long j_head;
/**
* @j_tail:
*
* Journal tail: identifies the oldest still-used block in the journal.
* [j_state_lock]
*/
unsigned long j_tail;
/**
* @j_free:
*
* Journal free: how many free blocks are there in the journal?
* [j_state_lock]
*/
unsigned long j_free;
/**
* @j_first:
*
* The block number of the first usable block in the journal
* [j_state_lock].
*/
unsigned long j_first;
/**
* @j_last:
*
* The block number one beyond the last usable block in the journal
* [j_state_lock].
*/
unsigned long j_last;
/**
* @j_dev: Device where we store the journal.
*/
struct block_device *j_dev;
/**
* @j_blocksize: Block size for the location where we store the journal.
*/
int j_blocksize;
/**
* @j_blk_offset:
*
* Starting block offset into the device where we store the journal.
*/
unsigned long long j_blk_offset;
/**
* @j_devname: Journal device name.
*/
char j_devname[BDEVNAME_SIZE+24];
/**
* @j_fs_dev:
*
* Device which holds the client fs. For internal journal this will be
* equal to j_dev.
*/
struct block_device *j_fs_dev;
/**
* @j_maxlen: Total maximum capacity of the journal region on disk.
*/
unsigned int j_maxlen;
/**
* @j_reserved_credits:
*
* Number of buffers reserved from the running transaction.
*/
atomic_t j_reserved_credits;
/**
* @j_list_lock: Protects the buffer lists and internal buffer state.
*/
spinlock_t j_list_lock;
/**
* @j_inode:
*
* Optional inode where we store the journal. If present, all
* journal block numbers are mapped into this inode via bmap().
*/
struct inode *j_inode;
/**
* @j_tail_sequence:
*
* Sequence number of the oldest transaction in the log [j_state_lock]
*/
tid_t j_tail_sequence;
/**
* @j_transaction_sequence:
*
* Sequence number of the next transaction to grant [j_state_lock]
*/
tid_t j_transaction_sequence;
/**
* @j_commit_sequence:
*
* Sequence number of the most recently committed transaction
* [j_state_lock].
*/
tid_t j_commit_sequence;
/**
* @j_commit_request:
*
* Sequence number of the most recent transaction wanting commit
* [j_state_lock]
*/
tid_t j_commit_request;
/**
* @j_uuid:
*
* Journal uuid: identifies the object (filesystem, LVM volume etc)
* backed by this journal. This will eventually be replaced by an array
* of uuids, allowing us to index multiple devices within a single
* journal and to perform atomic updates across them.
*/
__u8 j_uuid[16];
/**
* @j_task: Pointer to the current commit thread for this journal.
*/
struct task_struct *j_task;
/**
* @j_max_transaction_buffers:
*
* Maximum number of metadata buffers to allow in a single compound
* commit transaction.
*/
int j_max_transaction_buffers;
/**
* @j_commit_interval:
*
* What is the maximum transaction lifetime before we begin a commit?
*/
unsigned long j_commit_interval;
/**
* @j_commit_timer: The timer used to wakeup the commit thread.
*/
struct timer_list j_commit_timer;
/**
* @j_revoke_lock: Protect the revoke table.
*/
spinlock_t j_revoke_lock;
/**
* @j_revoke:
*
* The revoke table - maintains the list of revoked blocks in the
* current transaction.
*/
struct jbd2_revoke_table_s *j_revoke;
/**
* @j_revoke_table: Alternate revoke tables for j_revoke.
*/
struct jbd2_revoke_table_s *j_revoke_table[2];
/**
* @j_wbuf: Array of bhs for jbd2_journal_commit_transaction.
*/
struct buffer_head **j_wbuf;
/**
* @j_wbufsize:
*
* Size of @j_wbuf array.
*/
int j_wbufsize;
/**
* @j_last_sync_writer:
*
* The pid of the last person to run a synchronous operation
* through the journal.
*/
pid_t j_last_sync_writer;
/**
* @j_average_commit_time:
*
* The average amount of time in nanoseconds it takes to commit a
* transaction to disk. [j_state_lock]
*/
u64 j_average_commit_time;
/**
* @j_min_batch_time:
*
* Minimum time that we should wait for additional filesystem operations
* to get batched into a synchronous handle in microseconds.
*/
u32 j_min_batch_time;
/**
* @j_max_batch_time:
*
* Maximum time that we should wait for additional filesystem operations
* to get batched into a synchronous handle in microseconds.
*/
u32 j_max_batch_time;
/**
* @j_commit_callback:
*
* This function is called when a transaction is closed.
*/
void (*j_commit_callback)(journal_t *,
transaction_t *);
/*
* Journal statistics
*/
/**
* @j_history_lock: Protect the transactions statistics history.
*/
spinlock_t j_history_lock;
/**
* @j_proc_entry: procfs entry for the jbd statistics directory.
*/
struct proc_dir_entry *j_proc_entry;
/**
* @j_stats: Overall statistics.
*/
struct transaction_stats_s j_stats;
/**
* @j_failed_commit: Failed journal commit ID.
*/
unsigned int j_failed_commit;
/**
* @j_private:
*
* An opaque pointer to fs-private information. ext3 puts its
* superblock pointer here.
*/
void *j_private;
/**
* @j_chksum_driver:
*
* Reference to checksum algorithm driver via cryptoapi.
*/
struct crypto_shash *j_chksum_driver;
/**
* @j_csum_seed:
*
* Precomputed journal UUID checksum for seeding other checksums.
*/
__u32 j_csum_seed;
#ifdef CONFIG_DEBUG_LOCK_ALLOC
/**
* @j_trans_commit_map:
*
* Lockdep entity to track transaction commit dependencies. Handles
* hold this "lock" for read, when we wait for commit, we acquire the
* "lock" for writing. This matches the properties of jbd2 journalling
* where the running transaction has to wait for all handles to be
* dropped to commit that transaction and also acquiring a handle may
* require transaction commit to finish.
*/
struct lockdep_map j_trans_commit_map;
#endif
};
#define jbd2_might_wait_for_commit(j) \
do { \
rwsem_acquire(&j->j_trans_commit_map, 0, 0, _THIS_IP_); \
rwsem_release(&j->j_trans_commit_map, 1, _THIS_IP_); \
} while (0)
/* journal feature predicate functions */
#define JBD2_FEATURE_COMPAT_FUNCS(name, flagname) \
static inline bool jbd2_has_feature_##name(journal_t *j) \
{ \
return ((j)->j_format_version >= 2 && \
((j)->j_superblock->s_feature_compat & \
cpu_to_be32(JBD2_FEATURE_COMPAT_##flagname)) != 0); \
} \
static inline void jbd2_set_feature_##name(journal_t *j) \
{ \
(j)->j_superblock->s_feature_compat |= \
cpu_to_be32(JBD2_FEATURE_COMPAT_##flagname); \
} \
static inline void jbd2_clear_feature_##name(journal_t *j) \
{ \
(j)->j_superblock->s_feature_compat &= \
~cpu_to_be32(JBD2_FEATURE_COMPAT_##flagname); \
}
#define JBD2_FEATURE_RO_COMPAT_FUNCS(name, flagname) \
static inline bool jbd2_has_feature_##name(journal_t *j) \
{ \
return ((j)->j_format_version >= 2 && \
((j)->j_superblock->s_feature_ro_compat & \
cpu_to_be32(JBD2_FEATURE_RO_COMPAT_##flagname)) != 0); \
} \
static inline void jbd2_set_feature_##name(journal_t *j) \
{ \
(j)->j_superblock->s_feature_ro_compat |= \
cpu_to_be32(JBD2_FEATURE_RO_COMPAT_##flagname); \
} \
static inline void jbd2_clear_feature_##name(journal_t *j) \
{ \
(j)->j_superblock->s_feature_ro_compat &= \
~cpu_to_be32(JBD2_FEATURE_RO_COMPAT_##flagname); \
}
#define JBD2_FEATURE_INCOMPAT_FUNCS(name, flagname) \
static inline bool jbd2_has_feature_##name(journal_t *j) \
{ \
return ((j)->j_format_version >= 2 && \
((j)->j_superblock->s_feature_incompat & \
cpu_to_be32(JBD2_FEATURE_INCOMPAT_##flagname)) != 0); \
} \
static inline void jbd2_set_feature_##name(journal_t *j) \
{ \
(j)->j_superblock->s_feature_incompat |= \
cpu_to_be32(JBD2_FEATURE_INCOMPAT_##flagname); \
} \
static inline void jbd2_clear_feature_##name(journal_t *j) \
{ \
(j)->j_superblock->s_feature_incompat &= \
~cpu_to_be32(JBD2_FEATURE_INCOMPAT_##flagname); \
}
JBD2_FEATURE_COMPAT_FUNCS(checksum, CHECKSUM)
JBD2_FEATURE_INCOMPAT_FUNCS(revoke, REVOKE)
JBD2_FEATURE_INCOMPAT_FUNCS(64bit, 64BIT)
JBD2_FEATURE_INCOMPAT_FUNCS(async_commit, ASYNC_COMMIT)
JBD2_FEATURE_INCOMPAT_FUNCS(csum2, CSUM_V2)
JBD2_FEATURE_INCOMPAT_FUNCS(csum3, CSUM_V3)
/*
* Journal flag definitions
*/
#define JBD2_UNMOUNT 0x001 /* Journal thread is being destroyed */
#define JBD2_ABORT 0x002 /* Journaling has been aborted for errors. */
#define JBD2_ACK_ERR 0x004 /* The errno in the sb has been acked */
#define JBD2_FLUSHED 0x008 /* The journal superblock has been flushed */
#define JBD2_LOADED 0x010 /* The journal superblock has been loaded */
#define JBD2_BARRIER 0x020 /* Use IDE barriers */
#define JBD2_ABORT_ON_SYNCDATA_ERR 0x040 /* Abort the journal on file
* data write error in ordered
* mode */
#define JBD2_REC_ERR 0x080 /* The errno in the sb has been recorded */
/*
* Function declarations for the journaling transaction and buffer
* management
*/
/* Filing buffers */
extern void jbd2_journal_unfile_buffer(journal_t *, struct journal_head *);
extern void __jbd2_journal_refile_buffer(struct journal_head *);
extern void jbd2_journal_refile_buffer(journal_t *, struct journal_head *);
extern void __jbd2_journal_file_buffer(struct journal_head *, transaction_t *, int);
extern void __journal_free_buffer(struct journal_head *bh);
extern void jbd2_journal_file_buffer(struct journal_head *, transaction_t *, int);
extern void __journal_clean_data_list(transaction_t *transaction);
static inline void jbd2_file_log_bh(struct list_head *head, struct buffer_head *bh)
{
list_add_tail(&bh->b_assoc_buffers, head);
}
static inline void jbd2_unfile_log_bh(struct buffer_head *bh)
{
list_del_init(&bh->b_assoc_buffers);
}
/* Log buffer allocation */
struct buffer_head *jbd2_journal_get_descriptor_buffer(transaction_t *, int);
void jbd2_descriptor_block_csum_set(journal_t *, struct buffer_head *);
int jbd2_journal_next_log_block(journal_t *, unsigned long long *);
int jbd2_journal_get_log_tail(journal_t *journal, tid_t *tid,
unsigned long *block);
int __jbd2_update_log_tail(journal_t *journal, tid_t tid, unsigned long block);
void jbd2_update_log_tail(journal_t *journal, tid_t tid, unsigned long block);
/* Commit management */
extern void jbd2_journal_commit_transaction(journal_t *);
/* Checkpoint list management */
void __jbd2_journal_clean_checkpoint_list(journal_t *journal, bool destroy);
int __jbd2_journal_remove_checkpoint(struct journal_head *);
void jbd2_journal_destroy_checkpoint(journal_t *journal);
void __jbd2_journal_insert_checkpoint(struct journal_head *, transaction_t *);
/*
* Triggers
*/
struct jbd2_buffer_trigger_type {
/*
* Fired a the moment data to write to the journal are known to be
* stable - so either at the moment b_frozen_data is created or just
* before a buffer is written to the journal. mapped_data is a mapped
* buffer that is the frozen data for commit.
*/
void (*t_frozen)(struct jbd2_buffer_trigger_type *type,
struct buffer_head *bh, void *mapped_data,
size_t size);
/*
* Fired during journal abort for dirty buffers that will not be
* committed.
*/
void (*t_abort)(struct jbd2_buffer_trigger_type *type,
struct buffer_head *bh);
};
extern void jbd2_buffer_frozen_trigger(struct journal_head *jh,
void *mapped_data,
struct jbd2_buffer_trigger_type *triggers);
extern void jbd2_buffer_abort_trigger(struct journal_head *jh,
struct jbd2_buffer_trigger_type *triggers);
/* Buffer IO */
extern int jbd2_journal_write_metadata_buffer(transaction_t *transaction,
struct journal_head *jh_in,
struct buffer_head **bh_out,
sector_t blocknr);
/* Transaction locking */
extern void __wait_on_journal (journal_t *);
/* Transaction cache support */
extern void jbd2_journal_destroy_transaction_cache(void);
extern int __init jbd2_journal_init_transaction_cache(void);
extern void jbd2_journal_free_transaction(transaction_t *);
/*
* Journal locking.
*
* We need to lock the journal during transaction state changes so that nobody
* ever tries to take a handle on the running transaction while we are in the
* middle of moving it to the commit phase. j_state_lock does this.
*
* Note that the locking is completely interrupt unsafe. We never touch
* journal structures from interrupts.
*/
static inline handle_t *journal_current_handle(void)
{
return current->journal_info;
}
/* The journaling code user interface:
*
* Create and destroy handles
* Register buffer modifications against the current transaction.
*/
extern handle_t *jbd2_journal_start(journal_t *, int nblocks);
extern handle_t *jbd2__journal_start(journal_t *, int blocks, int rsv_blocks,
gfp_t gfp_mask, unsigned int type,
unsigned int line_no);
extern int jbd2_journal_restart(handle_t *, int nblocks);
extern int jbd2__journal_restart(handle_t *, int nblocks, gfp_t gfp_mask);
extern int jbd2_journal_start_reserved(handle_t *handle,
unsigned int type, unsigned int line_no);
extern void jbd2_journal_free_reserved(handle_t *handle);
extern int jbd2_journal_extend (handle_t *, int nblocks);
extern int jbd2_journal_get_write_access(handle_t *, struct buffer_head *);
extern int jbd2_journal_get_create_access (handle_t *, struct buffer_head *);
extern int jbd2_journal_get_undo_access(handle_t *, struct buffer_head *);
void jbd2_journal_set_triggers(struct buffer_head *,
struct jbd2_buffer_trigger_type *type);
extern int jbd2_journal_dirty_metadata (handle_t *, struct buffer_head *);
extern int jbd2_journal_forget (handle_t *, struct buffer_head *);
extern void journal_sync_buffer (struct buffer_head *);
extern int jbd2_journal_invalidatepage(journal_t *,
struct page *, unsigned int, unsigned int);
extern int jbd2_journal_try_to_free_buffers(journal_t *, struct page *, gfp_t);
extern int jbd2_journal_stop(handle_t *);
extern int jbd2_journal_flush (journal_t *);
extern void jbd2_journal_lock_updates (journal_t *);
extern void jbd2_journal_unlock_updates (journal_t *);
extern journal_t * jbd2_journal_init_dev(struct block_device *bdev,
struct block_device *fs_dev,
unsigned long long start, int len, int bsize);
extern journal_t * jbd2_journal_init_inode (struct inode *);
extern int jbd2_journal_update_format (journal_t *);
extern int jbd2_journal_check_used_features
(journal_t *, unsigned long, unsigned long, unsigned long);
extern int jbd2_journal_check_available_features
(journal_t *, unsigned long, unsigned long, unsigned long);
extern int jbd2_journal_set_features
(journal_t *, unsigned long, unsigned long, unsigned long);
extern void jbd2_journal_clear_features
(journal_t *, unsigned long, unsigned long, unsigned long);
extern int jbd2_journal_load (journal_t *journal);
extern int jbd2_journal_destroy (journal_t *);
extern int jbd2_journal_recover (journal_t *journal);
extern int jbd2_journal_wipe (journal_t *, int);
extern int jbd2_journal_skip_recovery (journal_t *);
extern void jbd2_journal_update_sb_errno(journal_t *);
extern int jbd2_journal_update_sb_log_tail (journal_t *, tid_t,
unsigned long, int);
extern void __jbd2_journal_abort_hard (journal_t *);
extern void jbd2_journal_abort (journal_t *, int);
extern int jbd2_journal_errno (journal_t *);
extern void jbd2_journal_ack_err (journal_t *);
extern int jbd2_journal_clear_err (journal_t *);
extern int jbd2_journal_bmap(journal_t *, unsigned long, unsigned long long *);
extern int jbd2_journal_force_commit(journal_t *);
extern int jbd2_journal_force_commit_nested(journal_t *);
extern int jbd2_journal_inode_add_write(handle_t *handle, struct jbd2_inode *inode);
extern int jbd2_journal_inode_add_wait(handle_t *handle, struct jbd2_inode *inode);
extern int jbd2_journal_begin_ordered_truncate(journal_t *journal,
struct jbd2_inode *inode, loff_t new_size);
extern void jbd2_journal_init_jbd_inode(struct jbd2_inode *jinode, struct inode *inode);
extern void jbd2_journal_release_jbd_inode(journal_t *journal, struct jbd2_inode *jinode);
/*
* journal_head management
*/
struct journal_head *jbd2_journal_add_journal_head(struct buffer_head *bh);
struct journal_head *jbd2_journal_grab_journal_head(struct buffer_head *bh);
void jbd2_journal_put_journal_head(struct journal_head *jh);
/*
* handle management
*/
extern struct kmem_cache *jbd2_handle_cache;
static inline handle_t *jbd2_alloc_handle(gfp_t gfp_flags)
{
return kmem_cache_zalloc(jbd2_handle_cache, gfp_flags);
}
static inline void jbd2_free_handle(handle_t *handle)
{
kmem_cache_free(jbd2_handle_cache, handle);
}
/*
* jbd2_inode management (optional, for those file systems that want to use
* dynamically allocated jbd2_inode structures)
*/
extern struct kmem_cache *jbd2_inode_cache;
static inline struct jbd2_inode *jbd2_alloc_inode(gfp_t gfp_flags)
{
return kmem_cache_alloc(jbd2_inode_cache, gfp_flags);
}
static inline void jbd2_free_inode(struct jbd2_inode *jinode)
{
kmem_cache_free(jbd2_inode_cache, jinode);
}
/* Primary revoke support */
#define JOURNAL_REVOKE_DEFAULT_HASH 256
extern int jbd2_journal_init_revoke(journal_t *, int);
extern void jbd2_journal_destroy_revoke_record_cache(void);
extern void jbd2_journal_destroy_revoke_table_cache(void);
extern int __init jbd2_journal_init_revoke_record_cache(void);
extern int __init jbd2_journal_init_revoke_table_cache(void);
extern void jbd2_journal_destroy_revoke(journal_t *);
extern int jbd2_journal_revoke (handle_t *, unsigned long long, struct buffer_head *);
extern int jbd2_journal_cancel_revoke(handle_t *, struct journal_head *);
extern void jbd2_journal_write_revoke_records(transaction_t *transaction,
struct list_head *log_bufs);
/* Recovery revoke support */
extern int jbd2_journal_set_revoke(journal_t *, unsigned long long, tid_t);
extern int jbd2_journal_test_revoke(journal_t *, unsigned long long, tid_t);
extern void jbd2_journal_clear_revoke(journal_t *);
extern void jbd2_journal_switch_revoke_table(journal_t *journal);
extern void jbd2_clear_buffer_revoked_flags(journal_t *journal);
/*
* The log thread user interface:
*
* Request space in the current transaction, and force transaction commit
* transitions on demand.
*/
int jbd2_log_start_commit(journal_t *journal, tid_t tid);
int __jbd2_log_start_commit(journal_t *journal, tid_t tid);
int jbd2_journal_start_commit(journal_t *journal, tid_t *tid);
int jbd2_log_wait_commit(journal_t *journal, tid_t tid);
int jbd2_transaction_committed(journal_t *journal, tid_t tid);
int jbd2_complete_transaction(journal_t *journal, tid_t tid);
int jbd2_log_do_checkpoint(journal_t *journal);
int jbd2_trans_will_send_data_barrier(journal_t *journal, tid_t tid);
void __jbd2_log_wait_for_space(journal_t *journal);
extern void __jbd2_journal_drop_transaction(journal_t *, transaction_t *);
extern int jbd2_cleanup_journal_tail(journal_t *);
/*
* is_journal_abort
*
* Simple test wrapper function to test the JBD2_ABORT state flag. This
* bit, when set, indicates that we have had a fatal error somewhere,
* either inside the journaling layer or indicated to us by the client
* (eg. ext3), and that we and should not commit any further
* transactions.
*/
static inline int is_journal_aborted(journal_t *journal)
{
return journal->j_flags & JBD2_ABORT;
}
static inline int is_handle_aborted(handle_t *handle)
{
if (handle->h_aborted || !handle->h_transaction)
return 1;
return is_journal_aborted(handle->h_transaction->t_journal);
}
static inline void jbd2_journal_abort_handle(handle_t *handle)
{
handle->h_aborted = 1;
}
#endif /* __KERNEL__ */
/* Comparison functions for transaction IDs: perform comparisons using
* modulo arithmetic so that they work over sequence number wraps. */
static inline int tid_gt(tid_t x, tid_t y)
{
int difference = (x - y);
return (difference > 0);
}
static inline int tid_geq(tid_t x, tid_t y)
{
int difference = (x - y);
return (difference >= 0);
}
extern int jbd2_journal_blocks_per_page(struct inode *inode);
extern size_t journal_tag_bytes(journal_t *journal);
static inline bool jbd2_journal_has_csum_v2or3_feature(journal_t *j)
{
return jbd2_has_feature_csum2(j) || jbd2_has_feature_csum3(j);
}
static inline int jbd2_journal_has_csum_v2or3(journal_t *journal)
{
WARN_ON_ONCE(jbd2_journal_has_csum_v2or3_feature(journal) &&
journal->j_chksum_driver == NULL);
return journal->j_chksum_driver != NULL;
}
/*
* We reserve t_outstanding_credits >> JBD2_CONTROL_BLOCKS_SHIFT for
* transaction control blocks.
*/
#define JBD2_CONTROL_BLOCKS_SHIFT 5
/*
* Return the minimum number of blocks which must be free in the journal
* before a new transaction may be started. Must be called under j_state_lock.
*/
static inline int jbd2_space_needed(journal_t *journal)
{
int nblocks = journal->j_max_transaction_buffers;
return nblocks + (nblocks >> JBD2_CONTROL_BLOCKS_SHIFT);
}
/*
* Return number of free blocks in the log. Must be called under j_state_lock.
*/
static inline unsigned long jbd2_log_space_left(journal_t *journal)
{
/* Allow for rounding errors */
unsigned long free = journal->j_free - 32;
if (journal->j_committing_transaction) {
unsigned long committing = atomic_read(&journal->
j_committing_transaction->t_outstanding_credits);
/* Transaction + control blocks */
free -= committing + (committing >> JBD2_CONTROL_BLOCKS_SHIFT);
}
return free;
}
/*
* Definitions which augment the buffer_head layer
*/
/* journaling buffer types */
#define BJ_None 0 /* Not journaled */
#define BJ_Metadata 1 /* Normal journaled metadata */
#define BJ_Forget 2 /* Buffer superseded by this transaction */
#define BJ_Shadow 3 /* Buffer contents being shadowed to the log */
#define BJ_Reserved 4 /* Buffer is reserved for access by journal */
#define BJ_Types 5
extern int jbd_blocks_per_page(struct inode *inode);
/* JBD uses a CRC32 checksum */
#define JBD_MAX_CHECKSUM_SIZE 4
static inline u32 jbd2_chksum(journal_t *journal, u32 crc,
const void *address, unsigned int length)
{
struct {
struct shash_desc shash;
char ctx[JBD_MAX_CHECKSUM_SIZE];
} desc;
int err;
BUG_ON(crypto_shash_descsize(journal->j_chksum_driver) >
JBD_MAX_CHECKSUM_SIZE);
desc.shash.tfm = journal->j_chksum_driver;
desc.shash.flags = 0;
*(u32 *)desc.ctx = crc;
err = crypto_shash_update(&desc.shash, address, length);
BUG_ON(err);
return *(u32 *)desc.ctx;
}
/* Return most recent uncommitted transaction */
static inline tid_t jbd2_get_latest_transaction(journal_t *journal)
{
tid_t tid;
read_lock(&journal->j_state_lock);
tid = journal->j_commit_request;
if (journal->j_running_transaction)
tid = journal->j_running_transaction->t_tid;
read_unlock(&journal->j_state_lock);
return tid;
}
#ifdef __KERNEL__
#define buffer_trace_init(bh) do {} while (0)
#define print_buffer_fields(bh) do {} while (0)
#define print_buffer_trace(bh) do {} while (0)
#define BUFFER_TRACE(bh, info) do {} while (0)
#define BUFFER_TRACE2(bh, bh2, info) do {} while (0)
#define JBUFFER_TRACE(jh, info) do {} while (0)
#endif /* __KERNEL__ */
#define EFSBADCRC EBADMSG /* Bad CRC detected */
#define EFSCORRUPTED EUCLEAN /* Filesystem is corrupted */
#endif /* _LINUX_JBD2_H */
| 28.460558 | 111 | 0.737479 | [
"object"
] |
2cf6e7eb2ed3b69082948e96426b725fd33a45b7 | 3,427 | h | C | windows_packages_gpu/torch/include/caffe2/sgd/iter_op.h | codeproject/DeepStack | d96368a3db1bc0266cb500ba3701d130834da0e6 | [
"Apache-2.0"
] | 353 | 2020-12-10T10:47:17.000Z | 2022-03-31T23:08:29.000Z | windows_packages_gpu/torch/include/caffe2/sgd/iter_op.h | codeproject/DeepStack | d96368a3db1bc0266cb500ba3701d130834da0e6 | [
"Apache-2.0"
] | 80 | 2020-12-10T09:54:22.000Z | 2022-03-30T22:08:45.000Z | windows_packages_gpu/torch/include/caffe2/sgd/iter_op.h | codeproject/DeepStack | d96368a3db1bc0266cb500ba3701d130834da0e6 | [
"Apache-2.0"
] | 63 | 2020-12-10T17:10:34.000Z | 2022-03-28T16:27:07.000Z | #ifndef CAFFE2_SGD_ITER_OP_H_
#define CAFFE2_SGD_ITER_OP_H_
#include <limits>
#include <mutex>
#include "caffe2/core/blob_serialization.h"
#include "caffe2/core/context.h"
#include "caffe2/core/operator.h"
#include "caffe2/core/stats.h"
namespace caffe2 {
inline void IncrementIter(TensorCPU* output) {
CAFFE_ENFORCE_EQ(
output->numel(),
1,
"The output of IterOp exists, but not of the right size.");
int64_t* iter = output->template mutable_data<int64_t>();
CAFFE_ENFORCE(*iter >= 0, "Previous iteration number is negative.");
CAFFE_ENFORCE(
*iter < std::numeric_limits<int64_t>::max(), "Overflow will happen!");
(*iter)++;
}
// IterOp runs an iteration counter. I cannot think of a case where we would
// need to access the iter variable on device, so this will always produce a
// tensor on the CPU side. If the blob already exists and is a tensor<int64_t>
// object, we will simply increment it (this emulates the case when we want to
// resume training). Otherwise we will have the iter starting with 0.
template <class Context>
class IterOp final : public Operator<Context> {
public:
USE_OPERATOR_CONTEXT_FUNCTIONS;
IterOp(const OperatorDef& operator_def, Workspace* ws)
: Operator<Context>(operator_def, ws) {}
bool RunOnDevice() override {
if (InputSize() == 0) {
VLOG(1) << "[Input size is zero]";
if (!OperatorBase::OutputIsTensorType(0, CPU)) {
// This is the first run; set the iter to start with 0.
LOG(ERROR) << "You are using an old definition of IterOp that will "
"be deprecated soon. More specifically, IterOp now "
"requires an explicit in-place input and output.";
VLOG(1) << "Initializing iter counter.";
auto* output = OperatorBase::OutputTensor(
0, {1}, at::dtype<int64_t>().device(CPU));
output->template mutable_data<int64_t>()[0] = 0;
}
}
IncrementIter(OperatorBase::Output<Tensor>(0, CPU));
return true;
}
};
template <class Context>
class AtomicIterOp final : public Operator<Context> {
public:
USE_OPERATOR_CONTEXT_FUNCTIONS;
AtomicIterOp(const OperatorDef& operator_def, Workspace* ws)
: Operator<Context>(operator_def, ws),
stats_(std::string("atomic_iter/stats/") + operator_def.input(1)) {}
bool RunOnDevice() override {
auto& mutex = OperatorBase::Input<std::unique_ptr<std::mutex>>(0);
std::lock_guard<std::mutex> lg(*mutex);
IncrementIter(OperatorBase::Output<Tensor>(0, CPU));
CAFFE_EVENT(stats_, num_iter);
return true;
}
private:
struct AtomicIterOpStats {
CAFFE_STAT_CTOR(AtomicIterOpStats);
CAFFE_EXPORTED_STAT(num_iter);
} stats_;
};
class MutexSerializer : public BlobSerializerBase {
public:
/**
* Serializes a std::unique_ptr<std::mutex>. Note that this blob has to
* contain std::unique_ptr<std::mutex>, otherwise this function produces a
* fatal error.
*/
void Serialize(
const void* pointer,
TypeMeta typeMeta,
const string& name,
BlobSerializerBase::SerializationAcceptor acceptor) override;
};
class MutexDeserializer : public BlobDeserializerBase {
public:
void Deserialize(const BlobProto& proto, Blob* blob) override;
};
} // namespace caffe2
#endif // CAFFE2_SGD_ITER_OP_H_
| 32.638095 | 79 | 0.669098 | [
"object"
] |
2cfb006262d621fed46443089e5dade29c40d8ca | 21,328 | h | C | Plugins/nvindex_plugin/include/nv/index/idistributed_data_locality.h | hkroeger/caetool-paraview | 716d3174523674134a93bfe3a3d335c1ed87d7f1 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Plugins/nvindex_plugin/include/nv/index/idistributed_data_locality.h | hkroeger/caetool-paraview | 716d3174523674134a93bfe3a3d335c1ed87d7f1 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | Plugins/nvindex_plugin/include/nv/index/idistributed_data_locality.h | hkroeger/caetool-paraview | 716d3174523674134a93bfe3a3d335c1ed87d7f1 | [
"Apache-2.0",
"BSD-3-Clause"
] | null | null | null | /******************************************************************************
* Copyright 2018 NVIDIA Corporation. All rights reserved.
*****************************************************************************/
/// \file
/// \brief Interfaces for exposing the data distribution scheme.
#ifndef NVIDIA_INDEX_IDATA_DISTRIBUTION_H
#define NVIDIA_INDEX_IDATA_DISTRIBUTION_H
#include <mi/base/interface_declare.h>
#include <mi/dice.h>
#include <mi/neuraylib/iserializer.h>
#include <nv/index/idistributed_data_edit.h>
namespace nv
{
namespace index
{
/// @ingroup nv_index_data_access
/// The interface class exposes data locality information.
///
/// In general, the data representation that corresponds to a large-scale
/// dataset is distributed in the cluster environment to enable
/// scalable rendering and computing (based on a sort-last approach).
/// The distribution scheme relies on a spatial subdivision
/// of the entire scene space.
/// Using the subdivision scheme, the data representation is partitioned
/// into subsets that are distributed to and stored on the nodes in the
/// cluster. Each subset is contained in its local space bounding box.
///
/// The data locality provides the application the means to query where, i.e., on
/// which node in the cluster, a subset of the data representation of the entire
/// distributed dataset is stored. A node stores either none or a set of subsets.
/// Furthermore, the data locality information provides the number of
/// those 3D bounding boxes that correspond to the number of subsets
/// stored on a given cluster node. Each of the bounding boxes can be
/// accessed. The respective index then also corresponds to the distributed
/// data subset.
///
/// A common use case that requires the data locality is the invocation of
/// parallel and distributed compute tasks applied to the distributed data.
/// DiCE provides a fragmented job infrastructure (\c IFragmented_job) that allows
/// invoking operations in the cluster.
/// Each job invocation usually requires information about
/// the number of operations (a.k.a. fragments) that shall be launched and the
/// target cluster nodes to which the launched fragments shall be sent to
/// process or analyse the distributed data.
///
///
/// \deprecated This interface class is subject to change!
///
class IDistributed_data_locality
: public mi::base::Interface_declare<0x64624ed0, 0x6e2a, 0x48c9, 0xb9, 0x73, 0x61, 0x8d, 0x32,
0xd0, 0x5e, 0xf5, mi::neuraylib::ISerializable>
{
public:
/// The data representation is distributed to a number of machines in the cluster.
/// A cluster node hosts none or a subset of the distributed data.
/// The number of nodes that host a subset of the entire
/// dataset allows, for instance, setting up the fragmented job, i.e.,
/// the number of fragments a fragmented job shall be split into.
///
/// \return The number of cluster nodes that host a subset of
/// the entire data representation.
///
virtual mi::Uint32 get_nb_cluster_nodes() const = 0;
/// The data representation is distributed to the given cluster machines.
/// Each of the cluster machines has a unique id. The method returns the unique
/// ids of the cluster machines that store a subset of the data locally.
///
/// \param[in] index The index used to access one of the cluster nodes.
/// The index must be given in the range from 0 to
/// \c get_nb_cluster_nodes().
///
/// \return The indexed unique cluster machines id.
///
virtual mi::Uint32 get_cluster_node(mi::Uint32 index) const = 0;
/// Each cluster node hosts none or a subset of the large-scale data representation.
/// Each subset has its own bounding box in the scene element's local space.
/// The number of subsets stored locally, i.e., the number
/// of bounding boxes per cluster node, allows, for instance, a user-defined
/// compute algorithm to iterate over all subsets on a cluster machines.
///
/// \param[in] cluster_node_id The id that references a cluster machine.
///
/// \return The number of data subsets
/// stored locally on the cluster node.
///
virtual mi::Size get_nb_bounding_box(mi::Uint32 cluster_node_id) const = 0;
/// The data subset stored locally on a cluster node is defined inside its bounding box.
/// The method allows iterating over all the bounding boxes
/// on a cluster machine, e.g., to implement compute techniques.
///
/// \param[in] cluster_node_id The id that references a cluster node.
/// The index must be given in the range
/// from 0 to \c get_nb_bounding_box().
///
/// \param[in] index The index of the bounding box that references
/// the actual subset of the large-scale data
/// representation.
///
/// \return The data subset's bounding
/// box in the scene element's local space.
///
virtual const mi::math::Bbox_struct<mi::Sint32, 3> get_bounding_box(
mi::Uint32 cluster_node_id, mi::Uint32 index) const = 0;
};
/// @ingroup nv_index_data_access
/// The interface class exposes the locality information of a distributed regular volume dataset.
///
/// The interface method \c IData_distribution::retrieve_data_locality()
/// returns the volume data locality.
///
///
/// \deprecated This interface class is subject to change!
///
class IRegular_volume_data_locality
: public mi::base::Interface_declare<0x64624ed9, 0x6e2a, 0x48c9, 0xa9, 0x82, 0x61, 0x8d, 0x32,
0xd0, 0x5e, 0xf9, IDistributed_data_locality>
{
public:
/// Creates means to edit the volume brick stored locally on a cluster node.
/// The method may only be called on the cluster machine that stores the data.
///
/// \param[in] dice_transaction The DiCE transaction used that the tasks operates in.
///
/// \param[in] cluster_node_id The index of the cluster machine that stores
/// a certain brick data.
///
/// \param[in] index The index of the bounding box that references
/// the actual brick of the subset of bricks.
///
/// \return Returns an NVIDIA IndeX instance of
/// the interface class \c IRegular_volume_data_edit
/// to edit the brick data contents.
///
///
virtual IRegular_volume_data_edit* create_data_edit(
mi::neuraylib::IDice_transaction* dice_transaction, mi::Uint32 cluster_node_id,
mi::Uint32 index) const = 0;
/// Creates means to access the volume brick stored locally on a cluster machine.
/// While the interface class \c IRegular_volume_data_access creates of copy of the
/// present interface method exposes direct access to the brick data stored locally
/// on a machine avoiding any data copies.
/// The method may only be called on the cluster node that stores the data.
///
/// \deprecated This call is supposed to be removed soon as
/// it used to be a workaround in the past.
///
/// \param[in] dice_transaction The DiCE transaction used for this operation.
///
/// \param[in] cluster_node_id The index of the cluster machine that stores
/// a brick data.
///
/// \param[in] index The index of the bounding box that references
/// the brick of the subset of bricks.
///
/// \param[out] brick_bounding_box The bounding box of the brick data stored
/// locally. The bounding box may be larger than
/// the bounding box returned by \c get_bounding_box
/// because the raw brick data may be extended by
/// an additional voxel boundary.
///
/// \return Returns a pointer to the amplitude values of the
/// local brick data.
///
virtual mi::Uint8* access_local_data(mi::neuraylib::IDice_transaction* dice_transaction,
mi::Uint32 cluster_node_id, mi::Uint32 index,
mi::math::Bbox_struct<mi::Uint32, 3>& brick_bounding_box) const = 0;
};
/// @ingroup nv_index_data_access
/// The interface class exposes the locality information of a distributed sparse-volume dataset.
///
/// The interface method \c IData_distribution::retrieve_data_locality()
/// returns the volume data locality.
///
/// \deprecated This interface class is subject to change!
///
class ISparse_volume_data_locality
: public mi::base::Interface_declare<0x860724fe, 0x5c07, 0x43b3, 0xaa, 0xc8, 0xbc, 0x3, 0x72,
0xc8, 0x44, 0xf8, IDistributed_data_locality>
{
public:
/// Creates means to edit the sparse-volume subset stored locally on a cluster node.
/// The method may only be called on the cluster machine that stores the data.
///
/// \param[in] dice_transaction The DiCE transaction used that the tasks operates in.
///
/// \param[in] cluster_node_id The index of the cluster machine that stores
/// a certain subset data.
///
/// \param[in] index The index of the bounding box that references
/// the actual sparse-volume subset
///
/// \return Returns an NVIDIA IndeX instance of
/// the interface class \c ISparse_volume_data_edit
/// to edit the sparse-volume subset data contents.
///
virtual ISparse_volume_data_edit* create_data_edit(
mi::neuraylib::IDice_transaction* dice_transaction, mi::Uint32 cluster_node_id,
mi::Uint32 index) const = 0;
};
/// @ingroup nv_index_data_access
/// The interface class exposes the locality information of a distributed regular heightfield
/// dataset.
///
/// The interface method \c IData_distribution::retrieve_data_locality()
/// returns the volume data locality.
///
///
/// \deprecated This interface class is subject to change!
///
class IRegular_heightfield_data_locality
: public mi::base::Interface_declare<0xe40bd2c9, 0x0d82, 0x4e03, 0x9c, 0x46, 0x42, 0x87, 0x86,
0xbb, 0xee, 0xdf, IDistributed_data_locality>
{
public:
/// Creates means to edit the heightfield data stored locally on a cluster machine.
/// The method may only be called on the cluster node that stores the data.
///
/// \param[in] dice_transaction The DiCE transaction used for this operation.
/// \param[in] cluster_node_id The index of the cluster node that stores
/// a certain patch data.
/// \param[in] index The index of the bounding box that references
/// the actual patch of the sub set of patches.
///
/// \return Returns an instance of an implementation of
/// the interface class \c IRegular_heightfield_data_edit.
///
///
virtual IRegular_heightfield_data_edit* create_data_edit(
mi::neuraylib::IDice_transaction* dice_transaction, mi::Uint32 cluster_node_id,
mi::Uint32 index) const = 0;
};
/// @ingroup nv_index_data_access
/// The interface class exposes the locality information of a distributed regular volume dataset.
///
/// The interface method \c IData_distribution::retrieve_data_locality()
/// returns the volume data locality.
///
///
/// \deprecated This interface class is subject to change!
///
class IIrregular_volume_data_locality
: public mi::base::Interface_declare<0x1a783273, 0xea49, 0x4f86, 0x97, 0x44, 0x24, 0x5b, 0xb5,
0xef, 0xe1, 0x9d, IDistributed_data_locality>
{
public:
/// Creates means to edit the volume brick stored locally on a cluster node.
/// The method may only be called on the cluster machine that stores the data.
///
/// \param[in] dice_transaction The DiCE transaction used that the tasks operates in.
///
/// \param[in] cluster_node_id The index of the cluster machine that stores
/// a certain brick data.
///
/// \param[in] index The index of the bounding box that references
/// the actual brick of the subset of bricks.
///
/// \return Returns an NVIDIA IndeX instance of
/// the interface class \c IRegular_volume_data_edit
/// to edit the brick data contents.
///
///
virtual IIrregular_volume_data_edit* create_data_edit(
mi::neuraylib::IDice_transaction* dice_transaction, mi::Uint32 cluster_node_id,
mi::Uint32 index) const = 0;
/// The irregular volume data subset stored locally on a cluster node is
/// defined inside its bounding box.
/// The method allows iterating over all the bounding boxes
/// on a cluster machine, e.g., to implement compute techniques.
///
/// \param[in] cluster_node_id The id that references a cluster node.
/// The index must be given in the range
/// from 0 to \c get_nb_bounding_box().
///
/// \param[in] index The index of the bounding box that references
/// the actual subset of the large-scale data
/// representation.
///
/// \return The data subset's bounding
/// box in the scene element's local space.
///
virtual const mi::math::Bbox_struct<mi::Float32, 3> get_data_subset_bounding_box(
mi::Uint32 cluster_node_id, mi::Uint32 index) const = 0;
};
/// @ingroup nv_index_data_access
/// Interface class that exposes the data distribution in the cluster environment.
///
/// \deprecated This interface class is subject to change!
///
class IData_distribution : public mi::base::Interface_declare<0xc37caf77, 0xe632, 0x46ad, 0x8c,
0x19, 0x6d, 0x57, 0x56, 0x04, 0xda, 0x68, mi::neuraylib::IElement>
{
public:
/// Query the distribution of volume data in the cluster. The returned
/// instance of the class that implements interface \c IRegular_volume_data_locality
/// provides the cluster nodes where parts of the queried data including their
/// respective bounding boxes (brick bounding box) are stored.
///
/// \param[in] scene_element_tag The volume scene element tag that refers to
/// data representation whose distribution shall
/// be returned.
/// \param[in] query_bbox The bounding box in scene element's local space.
/// The data distribution will be exposed for the
/// user-defined bounding box passed to the query.
/// \param[in] dice_transaction The DiCE transaction that the operation runs in.
///
/// \return Returns the data distribution scheme that
/// corresponds to the query parameters.
///
virtual IRegular_volume_data_locality* retrieve_data_locality(
mi::neuraylib::Tag_struct scene_element_tag,
const mi::math::Bbox_struct<mi::Uint32, 3>& query_bbox,
mi::neuraylib::IDice_transaction* dice_transaction) const = 0;
/// Query the distribution of sparse-volume data in the cluster. The returned
/// instance of the class that implements interface \c ISparse_volume_data_locality
/// provides the cluster nodes where parts of the queried data including their
/// respective bounding boxes (subset bounding box) are stored.
///
/// \param[in] scene_element_tag The sparse-volume scene element tag that refers to
/// data representation whose distribution shall
/// be returned.
/// \param[in] query_bbox The bounding box in scene element's local space.
/// The data distribution will be exposed for the
/// user-defined bounding box passed to the query.
/// \param[in] dice_transaction The DiCE transaction that the operation runs in.
///
/// \return Returns the data distribution scheme that
/// corresponds to the query parameters.
///
virtual ISparse_volume_data_locality* retrieve_sparse_volume_data_locality(
mi::neuraylib::Tag_struct scene_element_tag,
const mi::math::Bbox_struct<mi::Sint32, 3>& query_bbox,
mi::neuraylib::IDice_transaction* dice_transaction) const = 0;
/// Query the distribution of heightfield data in the cluster. The returned
/// instance of the class that implements interface \c IRegular_heightfield_data_locality
/// provides the cluster nodes where parts of the queried data including their
/// respective 2D bounding boxes (patch bounding box) are stored.
///
/// \param[in] scene_element_tag The heightfield scene element tag that refers to
/// data representation whose distribution shall be
/// returned.
/// \param[in] query_patch The bounding box in scene element's local space.
/// The data distribution will be exposed for the
/// user-defined bounding box passed to the query.
/// \param[in] dice_transaction The DiCE transaction that the operation runs in.
///
/// \return Returns the data distribution scheme that
/// corresponds to the query parameters.
///
virtual IRegular_heightfield_data_locality* retrieve_data_locality(
mi::neuraylib::Tag_struct scene_element_tag,
const mi::math::Bbox_struct<mi::Uint32, 2>& query_patch,
mi::neuraylib::IDice_transaction* dice_transaction) const = 0;
/// Query the distribution of heightfield data in the cluster. The returned
/// instance of the class that implements interface \c IRegular_heightfield_data_locality
/// provides the cluster nodes where parts of the queried data including their
/// respective 2D bounding boxes (patch bounding box) are stored.
/// Distributed heightfield patches may cover the same heightfield data area and
/// stored on multiple subregions along the z-direction (depth) in the scene.
/// That is, this query in contrast to the previous one returns all heightfield patches
/// in all intersected subregions, e.g., for applying cluster-wide editing
/// operations.
///
/// \param[in] scene_element_tag The heightfield scene element tag that refers to
/// data representation whose distribution shall be
/// returned.
/// \param[in] query_bbox The bounding box in scene element's local space.
/// The data distribution will be exposed for the
/// user-defined bounding box passed to the query.
/// \param[in] dice_transaction The DiCE transaction that the operation runs in.
///
/// \return Returns the data distribution scheme that
/// corresponds to the query parameters.
///
virtual IRegular_heightfield_data_locality* retrieve_data_locality_for_editing(
mi::neuraylib::Tag_struct scene_element_tag,
const mi::math::Bbox_struct<mi::Uint32, 2>& query_bbox,
mi::neuraylib::IDice_transaction* dice_transaction) const = 0;
/// Query the distribution of irregular volume data in the cluster. The returned
/// instance of the class that implements interface \c IRegular_volume_data_locality
/// provides the cluster nodes where parts of the queried data including their
/// respective bounding boxes (brick bounding box) are stored.
///
/// \param[in] scene_element_tag The volume scene element tag that refers to
/// data representation whose distribution shall
/// be returned.
/// \param[in] query_bbox The bounding box in scene element's local space.
/// The data distribution will be exposed for the
/// user-defined bounding box passed to the query.
/// \param[in] dice_transaction The DiCE transaction that the operation runs in.
///
/// \return Returns the data distribution scheme that
/// corresponds to the query parameters.
///
virtual IIrregular_volume_data_locality* retrieve_data_locality(
mi::neuraylib::Tag_struct scene_element_tag,
const mi::math::Bbox_struct<mi::Float32, 3>& query_bbox,
mi::neuraylib::IDice_transaction* dice_transaction) const = 0;
};
}
} // namespace index / nv
#endif // NVIDIA_INDEX_IDATA_DISTRIBUTION_H
| 50.420804 | 97 | 0.640801 | [
"3d"
] |
2cfb53e76f2329d4290a7759a5a8f407c00bac04 | 17,825 | h | C | cpu/z80/code/_code_group_cb.h | paulscottrobson/cerberus-2080 | c6731eab1b77d818bd22480554dd231cb28e2cf0 | [
"MIT"
] | 1 | 2022-01-09T15:19:28.000Z | 2022-01-09T15:19:28.000Z | emulator/cpu/z80/_code_group_cb.h | paulscottrobson/cerberus-2080 | c6731eab1b77d818bd22480554dd231cb28e2cf0 | [
"MIT"
] | 1 | 2021-12-11T07:08:54.000Z | 2021-12-11T19:07:19.000Z | cpu/z80/code/_code_group_cb.h | paulscottrobson/cerberus-2080 | c6731eab1b77d818bd22480554dd231cb28e2cf0 | [
"MIT"
] | 1 | 2021-12-12T14:20:32.000Z | 2021-12-12T14:20:32.000Z | //
// This file is automatically generated
//
case 0x00: /**** $00:rlc b ****/
B = ZSRRLC(B);
CYCLES(8);break;
case 0x01: /**** $01:rlc c ****/
C = ZSRRLC(C);
CYCLES(8);break;
case 0x02: /**** $02:rlc d ****/
D = ZSRRLC(D);
CYCLES(8);break;
case 0x03: /**** $03:rlc e ****/
E = ZSRRLC(E);
CYCLES(8);break;
case 0x04: /**** $04:rlc h ****/
H = ZSRRLC(H);
CYCLES(8);break;
case 0x05: /**** $05:rlc l ****/
L = ZSRRLC(L);
CYCLES(8);break;
case 0x06: /**** $06:rlc (hl) ****/
temp8 = READ8(HL()); temp8 = ZSRRLC(temp8); WRITE8(HL(),temp8);;
CYCLES(15);break;
case 0x07: /**** $07:rlc a ****/
A = ZSRRLC(A);
CYCLES(8);break;
case 0x08: /**** $08:rrc b ****/
B = ZSRRRC(B);
CYCLES(8);break;
case 0x09: /**** $09:rrc c ****/
C = ZSRRRC(C);
CYCLES(8);break;
case 0x0a: /**** $0a:rrc d ****/
D = ZSRRRC(D);
CYCLES(8);break;
case 0x0b: /**** $0b:rrc e ****/
E = ZSRRRC(E);
CYCLES(8);break;
case 0x0c: /**** $0c:rrc h ****/
H = ZSRRRC(H);
CYCLES(8);break;
case 0x0d: /**** $0d:rrc l ****/
L = ZSRRRC(L);
CYCLES(8);break;
case 0x0e: /**** $0e:rrc (hl) ****/
temp8 = READ8(HL()); temp8 = ZSRRRC(temp8); WRITE8(HL(),temp8);;
CYCLES(15);break;
case 0x0f: /**** $0f:rrc a ****/
A = ZSRRRC(A);
CYCLES(8);break;
case 0x10: /**** $10:rl b ****/
B = ZSRRL(B);
CYCLES(8);break;
case 0x11: /**** $11:rl c ****/
C = ZSRRL(C);
CYCLES(8);break;
case 0x12: /**** $12:rl d ****/
D = ZSRRL(D);
CYCLES(8);break;
case 0x13: /**** $13:rl e ****/
E = ZSRRL(E);
CYCLES(8);break;
case 0x14: /**** $14:rl h ****/
H = ZSRRL(H);
CYCLES(8);break;
case 0x15: /**** $15:rl l ****/
L = ZSRRL(L);
CYCLES(8);break;
case 0x16: /**** $16:rl (hl) ****/
temp8 = READ8(HL()); temp8 = ZSRRL(temp8); WRITE8(HL(),temp8);;
CYCLES(15);break;
case 0x17: /**** $17:rl a ****/
A = ZSRRL(A);
CYCLES(8);break;
case 0x18: /**** $18:rr b ****/
B = ZSRRR(B);
CYCLES(8);break;
case 0x19: /**** $19:rr c ****/
C = ZSRRR(C);
CYCLES(8);break;
case 0x1a: /**** $1a:rr d ****/
D = ZSRRR(D);
CYCLES(8);break;
case 0x1b: /**** $1b:rr e ****/
E = ZSRRR(E);
CYCLES(8);break;
case 0x1c: /**** $1c:rr h ****/
H = ZSRRR(H);
CYCLES(8);break;
case 0x1d: /**** $1d:rr l ****/
L = ZSRRR(L);
CYCLES(8);break;
case 0x1e: /**** $1e:rr (hl) ****/
temp8 = READ8(HL()); temp8 = ZSRRR(temp8); WRITE8(HL(),temp8);;
CYCLES(15);break;
case 0x1f: /**** $1f:rr a ****/
A = ZSRRR(A);
CYCLES(8);break;
case 0x20: /**** $20:sla b ****/
B = ZSRSLA(B);
CYCLES(8);break;
case 0x21: /**** $21:sla c ****/
C = ZSRSLA(C);
CYCLES(8);break;
case 0x22: /**** $22:sla d ****/
D = ZSRSLA(D);
CYCLES(8);break;
case 0x23: /**** $23:sla e ****/
E = ZSRSLA(E);
CYCLES(8);break;
case 0x24: /**** $24:sla h ****/
H = ZSRSLA(H);
CYCLES(8);break;
case 0x25: /**** $25:sla l ****/
L = ZSRSLA(L);
CYCLES(8);break;
case 0x26: /**** $26:sla (hl) ****/
temp8 = READ8(HL()); temp8 = ZSRSLA(temp8); WRITE8(HL(),temp8);;
CYCLES(15);break;
case 0x27: /**** $27:sla a ****/
A = ZSRSLA(A);
CYCLES(8);break;
case 0x28: /**** $28:sra b ****/
B = ZSRSRA(B);
CYCLES(8);break;
case 0x29: /**** $29:sra c ****/
C = ZSRSRA(C);
CYCLES(8);break;
case 0x2a: /**** $2a:sra d ****/
D = ZSRSRA(D);
CYCLES(8);break;
case 0x2b: /**** $2b:sra e ****/
E = ZSRSRA(E);
CYCLES(8);break;
case 0x2c: /**** $2c:sra h ****/
H = ZSRSRA(H);
CYCLES(8);break;
case 0x2d: /**** $2d:sra l ****/
L = ZSRSRA(L);
CYCLES(8);break;
case 0x2e: /**** $2e:sra (hl) ****/
temp8 = READ8(HL()); temp8 = ZSRSRA(temp8); WRITE8(HL(),temp8);;
CYCLES(15);break;
case 0x2f: /**** $2f:sra a ****/
A = ZSRSRA(A);
CYCLES(8);break;
case 0x38: /**** $38:srl b ****/
B = ZSRSRL(B);
CYCLES(8);break;
case 0x39: /**** $39:srl c ****/
C = ZSRSRL(C);
CYCLES(8);break;
case 0x3a: /**** $3a:srl d ****/
D = ZSRSRL(D);
CYCLES(8);break;
case 0x3b: /**** $3b:srl e ****/
E = ZSRSRL(E);
CYCLES(8);break;
case 0x3c: /**** $3c:srl h ****/
H = ZSRSRL(H);
CYCLES(8);break;
case 0x3d: /**** $3d:srl l ****/
L = ZSRSRL(L);
CYCLES(8);break;
case 0x3e: /**** $3e:srl (hl) ****/
temp8 = READ8(HL()); temp8 = ZSRSRL(temp8); WRITE8(HL(),temp8);;
CYCLES(15);break;
case 0x3f: /**** $3f:srl a ****/
A = ZSRSRL(A);
CYCLES(8);break;
case 0x40: /**** $40:bit 0,b ****/
zBitOp(B & 1);
CYCLES(8);break;
case 0x41: /**** $41:bit 0,c ****/
zBitOp(C & 1);
CYCLES(8);break;
case 0x42: /**** $42:bit 0,d ****/
zBitOp(D & 1);
CYCLES(8);break;
case 0x43: /**** $43:bit 0,e ****/
zBitOp(E & 1);
CYCLES(8);break;
case 0x44: /**** $44:bit 0,h ****/
zBitOp(H & 1);
CYCLES(8);break;
case 0x45: /**** $45:bit 0,l ****/
zBitOp(L & 1);
CYCLES(8);break;
case 0x46: /**** $46:bit 0,(hl) ****/
zBitOp(READ8(HL()) & 1);
CYCLES(12);break;
case 0x47: /**** $47:bit 0,a ****/
zBitOp(A & 1);
CYCLES(8);break;
case 0x48: /**** $48:bit 1,b ****/
zBitOp(B & 2);
CYCLES(8);break;
case 0x49: /**** $49:bit 1,c ****/
zBitOp(C & 2);
CYCLES(8);break;
case 0x4a: /**** $4a:bit 1,d ****/
zBitOp(D & 2);
CYCLES(8);break;
case 0x4b: /**** $4b:bit 1,e ****/
zBitOp(E & 2);
CYCLES(8);break;
case 0x4c: /**** $4c:bit 1,h ****/
zBitOp(H & 2);
CYCLES(8);break;
case 0x4d: /**** $4d:bit 1,l ****/
zBitOp(L & 2);
CYCLES(8);break;
case 0x4e: /**** $4e:bit 1,(hl) ****/
zBitOp(READ8(HL()) & 2);
CYCLES(12);break;
case 0x4f: /**** $4f:bit 1,a ****/
zBitOp(A & 2);
CYCLES(8);break;
case 0x50: /**** $50:bit 2,b ****/
zBitOp(B & 4);
CYCLES(8);break;
case 0x51: /**** $51:bit 2,c ****/
zBitOp(C & 4);
CYCLES(8);break;
case 0x52: /**** $52:bit 2,d ****/
zBitOp(D & 4);
CYCLES(8);break;
case 0x53: /**** $53:bit 2,e ****/
zBitOp(E & 4);
CYCLES(8);break;
case 0x54: /**** $54:bit 2,h ****/
zBitOp(H & 4);
CYCLES(8);break;
case 0x55: /**** $55:bit 2,l ****/
zBitOp(L & 4);
CYCLES(8);break;
case 0x56: /**** $56:bit 2,(hl) ****/
zBitOp(READ8(HL()) & 4);
CYCLES(12);break;
case 0x57: /**** $57:bit 2,a ****/
zBitOp(A & 4);
CYCLES(8);break;
case 0x58: /**** $58:bit 3,b ****/
zBitOp(B & 8);
CYCLES(8);break;
case 0x59: /**** $59:bit 3,c ****/
zBitOp(C & 8);
CYCLES(8);break;
case 0x5a: /**** $5a:bit 3,d ****/
zBitOp(D & 8);
CYCLES(8);break;
case 0x5b: /**** $5b:bit 3,e ****/
zBitOp(E & 8);
CYCLES(8);break;
case 0x5c: /**** $5c:bit 3,h ****/
zBitOp(H & 8);
CYCLES(8);break;
case 0x5d: /**** $5d:bit 3,l ****/
zBitOp(L & 8);
CYCLES(8);break;
case 0x5e: /**** $5e:bit 3,(hl) ****/
zBitOp(READ8(HL()) & 8);
CYCLES(12);break;
case 0x5f: /**** $5f:bit 3,a ****/
zBitOp(A & 8);
CYCLES(8);break;
case 0x60: /**** $60:bit 4,b ****/
zBitOp(B & 16);
CYCLES(8);break;
case 0x61: /**** $61:bit 4,c ****/
zBitOp(C & 16);
CYCLES(8);break;
case 0x62: /**** $62:bit 4,d ****/
zBitOp(D & 16);
CYCLES(8);break;
case 0x63: /**** $63:bit 4,e ****/
zBitOp(E & 16);
CYCLES(8);break;
case 0x64: /**** $64:bit 4,h ****/
zBitOp(H & 16);
CYCLES(8);break;
case 0x65: /**** $65:bit 4,l ****/
zBitOp(L & 16);
CYCLES(8);break;
case 0x66: /**** $66:bit 4,(hl) ****/
zBitOp(READ8(HL()) & 16);
CYCLES(12);break;
case 0x67: /**** $67:bit 4,a ****/
zBitOp(A & 16);
CYCLES(8);break;
case 0x68: /**** $68:bit 5,b ****/
zBitOp(B & 32);
CYCLES(8);break;
case 0x69: /**** $69:bit 5,c ****/
zBitOp(C & 32);
CYCLES(8);break;
case 0x6a: /**** $6a:bit 5,d ****/
zBitOp(D & 32);
CYCLES(8);break;
case 0x6b: /**** $6b:bit 5,e ****/
zBitOp(E & 32);
CYCLES(8);break;
case 0x6c: /**** $6c:bit 5,h ****/
zBitOp(H & 32);
CYCLES(8);break;
case 0x6d: /**** $6d:bit 5,l ****/
zBitOp(L & 32);
CYCLES(8);break;
case 0x6e: /**** $6e:bit 5,(hl) ****/
zBitOp(READ8(HL()) & 32);
CYCLES(12);break;
case 0x6f: /**** $6f:bit 5,a ****/
zBitOp(A & 32);
CYCLES(8);break;
case 0x70: /**** $70:bit 6,b ****/
zBitOp(B & 64);
CYCLES(8);break;
case 0x71: /**** $71:bit 6,c ****/
zBitOp(C & 64);
CYCLES(8);break;
case 0x72: /**** $72:bit 6,d ****/
zBitOp(D & 64);
CYCLES(8);break;
case 0x73: /**** $73:bit 6,e ****/
zBitOp(E & 64);
CYCLES(8);break;
case 0x74: /**** $74:bit 6,h ****/
zBitOp(H & 64);
CYCLES(8);break;
case 0x75: /**** $75:bit 6,l ****/
zBitOp(L & 64);
CYCLES(8);break;
case 0x76: /**** $76:bit 6,(hl) ****/
zBitOp(READ8(HL()) & 64);
CYCLES(12);break;
case 0x77: /**** $77:bit 6,a ****/
zBitOp(A & 64);
CYCLES(8);break;
case 0x78: /**** $78:bit 7,b ****/
zBitOp(B & 128);
CYCLES(8);break;
case 0x79: /**** $79:bit 7,c ****/
zBitOp(C & 128);
CYCLES(8);break;
case 0x7a: /**** $7a:bit 7,d ****/
zBitOp(D & 128);
CYCLES(8);break;
case 0x7b: /**** $7b:bit 7,e ****/
zBitOp(E & 128);
CYCLES(8);break;
case 0x7c: /**** $7c:bit 7,h ****/
zBitOp(H & 128);
CYCLES(8);break;
case 0x7d: /**** $7d:bit 7,l ****/
zBitOp(L & 128);
CYCLES(8);break;
case 0x7e: /**** $7e:bit 7,(hl) ****/
zBitOp(READ8(HL()) & 128);
CYCLES(12);break;
case 0x7f: /**** $7f:bit 7,a ****/
zBitOp(A & 128);
CYCLES(8);break;
case 0x80: /**** $80:res 0,b ****/
B &= (~1);
CYCLES(8);break;
case 0x81: /**** $81:res 0,c ****/
C &= (~1);
CYCLES(8);break;
case 0x82: /**** $82:res 0,d ****/
D &= (~1);
CYCLES(8);break;
case 0x83: /**** $83:res 0,e ****/
E &= (~1);
CYCLES(8);break;
case 0x84: /**** $84:res 0,h ****/
H &= (~1);
CYCLES(8);break;
case 0x85: /**** $85:res 0,l ****/
L &= (~1);
CYCLES(8);break;
case 0x86: /**** $86:res 0,(hl) ****/
temp8 = READ8(HL()); WRITE8(HL(),temp8 & (~1));;
CYCLES(12);break;
case 0x87: /**** $87:res 0,a ****/
A &= (~1);
CYCLES(8);break;
case 0x88: /**** $88:res 1,b ****/
B &= (~2);
CYCLES(8);break;
case 0x89: /**** $89:res 1,c ****/
C &= (~2);
CYCLES(8);break;
case 0x8a: /**** $8a:res 1,d ****/
D &= (~2);
CYCLES(8);break;
case 0x8b: /**** $8b:res 1,e ****/
E &= (~2);
CYCLES(8);break;
case 0x8c: /**** $8c:res 1,h ****/
H &= (~2);
CYCLES(8);break;
case 0x8d: /**** $8d:res 1,l ****/
L &= (~2);
CYCLES(8);break;
case 0x8e: /**** $8e:res 1,(hl) ****/
temp8 = READ8(HL()); WRITE8(HL(),temp8 & (~2));;
CYCLES(12);break;
case 0x8f: /**** $8f:res 1,a ****/
A &= (~2);
CYCLES(8);break;
case 0x90: /**** $90:res 2,b ****/
B &= (~4);
CYCLES(8);break;
case 0x91: /**** $91:res 2,c ****/
C &= (~4);
CYCLES(8);break;
case 0x92: /**** $92:res 2,d ****/
D &= (~4);
CYCLES(8);break;
case 0x93: /**** $93:res 2,e ****/
E &= (~4);
CYCLES(8);break;
case 0x94: /**** $94:res 2,h ****/
H &= (~4);
CYCLES(8);break;
case 0x95: /**** $95:res 2,l ****/
L &= (~4);
CYCLES(8);break;
case 0x96: /**** $96:res 2,(hl) ****/
temp8 = READ8(HL()); WRITE8(HL(),temp8 & (~4));;
CYCLES(12);break;
case 0x97: /**** $97:res 2,a ****/
A &= (~4);
CYCLES(8);break;
case 0x98: /**** $98:res 3,b ****/
B &= (~8);
CYCLES(8);break;
case 0x99: /**** $99:res 3,c ****/
C &= (~8);
CYCLES(8);break;
case 0x9a: /**** $9a:res 3,d ****/
D &= (~8);
CYCLES(8);break;
case 0x9b: /**** $9b:res 3,e ****/
E &= (~8);
CYCLES(8);break;
case 0x9c: /**** $9c:res 3,h ****/
H &= (~8);
CYCLES(8);break;
case 0x9d: /**** $9d:res 3,l ****/
L &= (~8);
CYCLES(8);break;
case 0x9e: /**** $9e:res 3,(hl) ****/
temp8 = READ8(HL()); WRITE8(HL(),temp8 & (~8));;
CYCLES(12);break;
case 0x9f: /**** $9f:res 3,a ****/
A &= (~8);
CYCLES(8);break;
case 0xa0: /**** $a0:res 4,b ****/
B &= (~16);
CYCLES(8);break;
case 0xa1: /**** $a1:res 4,c ****/
C &= (~16);
CYCLES(8);break;
case 0xa2: /**** $a2:res 4,d ****/
D &= (~16);
CYCLES(8);break;
case 0xa3: /**** $a3:res 4,e ****/
E &= (~16);
CYCLES(8);break;
case 0xa4: /**** $a4:res 4,h ****/
H &= (~16);
CYCLES(8);break;
case 0xa5: /**** $a5:res 4,l ****/
L &= (~16);
CYCLES(8);break;
case 0xa6: /**** $a6:res 4,(hl) ****/
temp8 = READ8(HL()); WRITE8(HL(),temp8 & (~16));;
CYCLES(12);break;
case 0xa7: /**** $a7:res 4,a ****/
A &= (~16);
CYCLES(8);break;
case 0xa8: /**** $a8:res 5,b ****/
B &= (~32);
CYCLES(8);break;
case 0xa9: /**** $a9:res 5,c ****/
C &= (~32);
CYCLES(8);break;
case 0xaa: /**** $aa:res 5,d ****/
D &= (~32);
CYCLES(8);break;
case 0xab: /**** $ab:res 5,e ****/
E &= (~32);
CYCLES(8);break;
case 0xac: /**** $ac:res 5,h ****/
H &= (~32);
CYCLES(8);break;
case 0xad: /**** $ad:res 5,l ****/
L &= (~32);
CYCLES(8);break;
case 0xae: /**** $ae:res 5,(hl) ****/
temp8 = READ8(HL()); WRITE8(HL(),temp8 & (~32));;
CYCLES(12);break;
case 0xaf: /**** $af:res 5,a ****/
A &= (~32);
CYCLES(8);break;
case 0xb0: /**** $b0:res 6,b ****/
B &= (~64);
CYCLES(8);break;
case 0xb1: /**** $b1:res 6,c ****/
C &= (~64);
CYCLES(8);break;
case 0xb2: /**** $b2:res 6,d ****/
D &= (~64);
CYCLES(8);break;
case 0xb3: /**** $b3:res 6,e ****/
E &= (~64);
CYCLES(8);break;
case 0xb4: /**** $b4:res 6,h ****/
H &= (~64);
CYCLES(8);break;
case 0xb5: /**** $b5:res 6,l ****/
L &= (~64);
CYCLES(8);break;
case 0xb6: /**** $b6:res 6,(hl) ****/
temp8 = READ8(HL()); WRITE8(HL(),temp8 & (~64));;
CYCLES(12);break;
case 0xb7: /**** $b7:res 6,a ****/
A &= (~64);
CYCLES(8);break;
case 0xb8: /**** $b8:res 7,b ****/
B &= (~128);
CYCLES(8);break;
case 0xb9: /**** $b9:res 7,c ****/
C &= (~128);
CYCLES(8);break;
case 0xba: /**** $ba:res 7,d ****/
D &= (~128);
CYCLES(8);break;
case 0xbb: /**** $bb:res 7,e ****/
E &= (~128);
CYCLES(8);break;
case 0xbc: /**** $bc:res 7,h ****/
H &= (~128);
CYCLES(8);break;
case 0xbd: /**** $bd:res 7,l ****/
L &= (~128);
CYCLES(8);break;
case 0xbe: /**** $be:res 7,(hl) ****/
temp8 = READ8(HL()); WRITE8(HL(),temp8 & (~128));;
CYCLES(12);break;
case 0xbf: /**** $bf:res 7,a ****/
A &= (~128);
CYCLES(8);break;
case 0xc0: /**** $c0:set 0,b ****/
B |= 1;
CYCLES(8);break;
case 0xc1: /**** $c1:set 0,c ****/
C |= 1;
CYCLES(8);break;
case 0xc2: /**** $c2:set 0,d ****/
D |= 1;
CYCLES(8);break;
case 0xc3: /**** $c3:set 0,e ****/
E |= 1;
CYCLES(8);break;
case 0xc4: /**** $c4:set 0,h ****/
H |= 1;
CYCLES(8);break;
case 0xc5: /**** $c5:set 0,l ****/
L |= 1;
CYCLES(8);break;
case 0xc6: /**** $c6:set 0,(hl) ****/
temp8 = READ8(HL()); WRITE8(HL(),temp8|1);;
CYCLES(12);break;
case 0xc7: /**** $c7:set 0,a ****/
A |= 1;
CYCLES(8);break;
case 0xc8: /**** $c8:set 1,b ****/
B |= 2;
CYCLES(8);break;
case 0xc9: /**** $c9:set 1,c ****/
C |= 2;
CYCLES(8);break;
case 0xca: /**** $ca:set 1,d ****/
D |= 2;
CYCLES(8);break;
case 0xcb: /**** $cb:set 1,e ****/
E |= 2;
CYCLES(8);break;
case 0xcc: /**** $cc:set 1,h ****/
H |= 2;
CYCLES(8);break;
case 0xcd: /**** $cd:set 1,l ****/
L |= 2;
CYCLES(8);break;
case 0xce: /**** $ce:set 1,(hl) ****/
temp8 = READ8(HL()); WRITE8(HL(),temp8|2);;
CYCLES(12);break;
case 0xcf: /**** $cf:set 1,a ****/
A |= 2;
CYCLES(8);break;
case 0xd0: /**** $d0:set 2,b ****/
B |= 4;
CYCLES(8);break;
case 0xd1: /**** $d1:set 2,c ****/
C |= 4;
CYCLES(8);break;
case 0xd2: /**** $d2:set 2,d ****/
D |= 4;
CYCLES(8);break;
case 0xd3: /**** $d3:set 2,e ****/
E |= 4;
CYCLES(8);break;
case 0xd4: /**** $d4:set 2,h ****/
H |= 4;
CYCLES(8);break;
case 0xd5: /**** $d5:set 2,l ****/
L |= 4;
CYCLES(8);break;
case 0xd6: /**** $d6:set 2,(hl) ****/
temp8 = READ8(HL()); WRITE8(HL(),temp8|4);;
CYCLES(12);break;
case 0xd7: /**** $d7:set 2,a ****/
A |= 4;
CYCLES(8);break;
case 0xd8: /**** $d8:set 3,b ****/
B |= 8;
CYCLES(8);break;
case 0xd9: /**** $d9:set 3,c ****/
C |= 8;
CYCLES(8);break;
case 0xda: /**** $da:set 3,d ****/
D |= 8;
CYCLES(8);break;
case 0xdb: /**** $db:set 3,e ****/
E |= 8;
CYCLES(8);break;
case 0xdc: /**** $dc:set 3,h ****/
H |= 8;
CYCLES(8);break;
case 0xdd: /**** $dd:set 3,l ****/
L |= 8;
CYCLES(8);break;
case 0xde: /**** $de:set 3,(hl) ****/
temp8 = READ8(HL()); WRITE8(HL(),temp8|8);;
CYCLES(12);break;
case 0xdf: /**** $df:set 3,a ****/
A |= 8;
CYCLES(8);break;
case 0xe0: /**** $e0:set 4,b ****/
B |= 16;
CYCLES(8);break;
case 0xe1: /**** $e1:set 4,c ****/
C |= 16;
CYCLES(8);break;
case 0xe2: /**** $e2:set 4,d ****/
D |= 16;
CYCLES(8);break;
case 0xe3: /**** $e3:set 4,e ****/
E |= 16;
CYCLES(8);break;
case 0xe4: /**** $e4:set 4,h ****/
H |= 16;
CYCLES(8);break;
case 0xe5: /**** $e5:set 4,l ****/
L |= 16;
CYCLES(8);break;
case 0xe6: /**** $e6:set 4,(hl) ****/
temp8 = READ8(HL()); WRITE8(HL(),temp8|16);;
CYCLES(12);break;
case 0xe7: /**** $e7:set 4,a ****/
A |= 16;
CYCLES(8);break;
case 0xe8: /**** $e8:set 5,b ****/
B |= 32;
CYCLES(8);break;
case 0xe9: /**** $e9:set 5,c ****/
C |= 32;
CYCLES(8);break;
case 0xea: /**** $ea:set 5,d ****/
D |= 32;
CYCLES(8);break;
case 0xeb: /**** $eb:set 5,e ****/
E |= 32;
CYCLES(8);break;
case 0xec: /**** $ec:set 5,h ****/
H |= 32;
CYCLES(8);break;
case 0xed: /**** $ed:set 5,l ****/
L |= 32;
CYCLES(8);break;
case 0xee: /**** $ee:set 5,(hl) ****/
temp8 = READ8(HL()); WRITE8(HL(),temp8|32);;
CYCLES(12);break;
case 0xef: /**** $ef:set 5,a ****/
A |= 32;
CYCLES(8);break;
case 0xf0: /**** $f0:set 6,b ****/
B |= 64;
CYCLES(8);break;
case 0xf1: /**** $f1:set 6,c ****/
C |= 64;
CYCLES(8);break;
case 0xf2: /**** $f2:set 6,d ****/
D |= 64;
CYCLES(8);break;
case 0xf3: /**** $f3:set 6,e ****/
E |= 64;
CYCLES(8);break;
case 0xf4: /**** $f4:set 6,h ****/
H |= 64;
CYCLES(8);break;
case 0xf5: /**** $f5:set 6,l ****/
L |= 64;
CYCLES(8);break;
case 0xf6: /**** $f6:set 6,(hl) ****/
temp8 = READ8(HL()); WRITE8(HL(),temp8|64);;
CYCLES(12);break;
case 0xf7: /**** $f7:set 6,a ****/
A |= 64;
CYCLES(8);break;
case 0xf8: /**** $f8:set 7,b ****/
B |= 128;
CYCLES(8);break;
case 0xf9: /**** $f9:set 7,c ****/
C |= 128;
CYCLES(8);break;
case 0xfa: /**** $fa:set 7,d ****/
D |= 128;
CYCLES(8);break;
case 0xfb: /**** $fb:set 7,e ****/
E |= 128;
CYCLES(8);break;
case 0xfc: /**** $fc:set 7,h ****/
H |= 128;
CYCLES(8);break;
case 0xfd: /**** $fd:set 7,l ****/
L |= 128;
CYCLES(8);break;
case 0xfe: /**** $fe:set 7,(hl) ****/
temp8 = READ8(HL()); WRITE8(HL(),temp8|128);;
CYCLES(12);break;
case 0xff: /**** $ff:set 7,a ****/
A |= 128;
CYCLES(8);break;
| 17.878636 | 65 | 0.488135 | [
"3d"
] |
2cfdfbfbb2edbddd4d441539e468c2ca0fd0d8f3 | 25,004 | c | C | kernel/linux-5.4/net/802/mrp.c | josehu07/SplitFS | d7442fa67a17de7057664f91defbfdbf10dd7f4a | [
"Apache-2.0"
] | 27 | 2021-10-04T18:56:52.000Z | 2022-03-28T08:23:06.000Z | kernel/linux-5.4/net/802/mrp.c | josehu07/SplitFS | d7442fa67a17de7057664f91defbfdbf10dd7f4a | [
"Apache-2.0"
] | 1 | 2022-01-12T04:05:36.000Z | 2022-01-16T15:48:42.000Z | kernel/linux-5.4/net/802/mrp.c | josehu07/SplitFS | d7442fa67a17de7057664f91defbfdbf10dd7f4a | [
"Apache-2.0"
] | 6 | 2021-11-02T10:56:19.000Z | 2022-03-06T11:58:20.000Z | // SPDX-License-Identifier: GPL-2.0-only
/*
* IEEE 802.1Q Multiple Registration Protocol (MRP)
*
* Copyright (c) 2012 Massachusetts Institute of Technology
*
* Adapted from code in net/802/garp.c
* Copyright (c) 2008 Patrick McHardy <kaber@trash.net>
*/
#include <linux/kernel.h>
#include <linux/timer.h>
#include <linux/skbuff.h>
#include <linux/netdevice.h>
#include <linux/etherdevice.h>
#include <linux/rtnetlink.h>
#include <linux/slab.h>
#include <linux/module.h>
#include <net/mrp.h>
#include <asm/unaligned.h>
static unsigned int mrp_join_time __read_mostly = 200;
module_param(mrp_join_time, uint, 0644);
MODULE_PARM_DESC(mrp_join_time, "Join time in ms (default 200ms)");
static unsigned int mrp_periodic_time __read_mostly = 1000;
module_param(mrp_periodic_time, uint, 0644);
MODULE_PARM_DESC(mrp_periodic_time, "Periodic time in ms (default 1s)");
MODULE_LICENSE("GPL");
static const u8
mrp_applicant_state_table[MRP_APPLICANT_MAX + 1][MRP_EVENT_MAX + 1] = {
[MRP_APPLICANT_VO] = {
[MRP_EVENT_NEW] = MRP_APPLICANT_VN,
[MRP_EVENT_JOIN] = MRP_APPLICANT_VP,
[MRP_EVENT_LV] = MRP_APPLICANT_VO,
[MRP_EVENT_TX] = MRP_APPLICANT_VO,
[MRP_EVENT_R_NEW] = MRP_APPLICANT_VO,
[MRP_EVENT_R_JOIN_IN] = MRP_APPLICANT_AO,
[MRP_EVENT_R_IN] = MRP_APPLICANT_VO,
[MRP_EVENT_R_JOIN_MT] = MRP_APPLICANT_VO,
[MRP_EVENT_R_MT] = MRP_APPLICANT_VO,
[MRP_EVENT_R_LV] = MRP_APPLICANT_VO,
[MRP_EVENT_R_LA] = MRP_APPLICANT_VO,
[MRP_EVENT_REDECLARE] = MRP_APPLICANT_VO,
[MRP_EVENT_PERIODIC] = MRP_APPLICANT_VO,
},
[MRP_APPLICANT_VP] = {
[MRP_EVENT_NEW] = MRP_APPLICANT_VN,
[MRP_EVENT_JOIN] = MRP_APPLICANT_VP,
[MRP_EVENT_LV] = MRP_APPLICANT_VO,
[MRP_EVENT_TX] = MRP_APPLICANT_AA,
[MRP_EVENT_R_NEW] = MRP_APPLICANT_VP,
[MRP_EVENT_R_JOIN_IN] = MRP_APPLICANT_AP,
[MRP_EVENT_R_IN] = MRP_APPLICANT_VP,
[MRP_EVENT_R_JOIN_MT] = MRP_APPLICANT_VP,
[MRP_EVENT_R_MT] = MRP_APPLICANT_VP,
[MRP_EVENT_R_LV] = MRP_APPLICANT_VP,
[MRP_EVENT_R_LA] = MRP_APPLICANT_VP,
[MRP_EVENT_REDECLARE] = MRP_APPLICANT_VP,
[MRP_EVENT_PERIODIC] = MRP_APPLICANT_VP,
},
[MRP_APPLICANT_VN] = {
[MRP_EVENT_NEW] = MRP_APPLICANT_VN,
[MRP_EVENT_JOIN] = MRP_APPLICANT_VN,
[MRP_EVENT_LV] = MRP_APPLICANT_LA,
[MRP_EVENT_TX] = MRP_APPLICANT_AN,
[MRP_EVENT_R_NEW] = MRP_APPLICANT_VN,
[MRP_EVENT_R_JOIN_IN] = MRP_APPLICANT_VN,
[MRP_EVENT_R_IN] = MRP_APPLICANT_VN,
[MRP_EVENT_R_JOIN_MT] = MRP_APPLICANT_VN,
[MRP_EVENT_R_MT] = MRP_APPLICANT_VN,
[MRP_EVENT_R_LV] = MRP_APPLICANT_VN,
[MRP_EVENT_R_LA] = MRP_APPLICANT_VN,
[MRP_EVENT_REDECLARE] = MRP_APPLICANT_VN,
[MRP_EVENT_PERIODIC] = MRP_APPLICANT_VN,
},
[MRP_APPLICANT_AN] = {
[MRP_EVENT_NEW] = MRP_APPLICANT_AN,
[MRP_EVENT_JOIN] = MRP_APPLICANT_AN,
[MRP_EVENT_LV] = MRP_APPLICANT_LA,
[MRP_EVENT_TX] = MRP_APPLICANT_QA,
[MRP_EVENT_R_NEW] = MRP_APPLICANT_AN,
[MRP_EVENT_R_JOIN_IN] = MRP_APPLICANT_AN,
[MRP_EVENT_R_IN] = MRP_APPLICANT_AN,
[MRP_EVENT_R_JOIN_MT] = MRP_APPLICANT_AN,
[MRP_EVENT_R_MT] = MRP_APPLICANT_AN,
[MRP_EVENT_R_LV] = MRP_APPLICANT_VN,
[MRP_EVENT_R_LA] = MRP_APPLICANT_VN,
[MRP_EVENT_REDECLARE] = MRP_APPLICANT_VN,
[MRP_EVENT_PERIODIC] = MRP_APPLICANT_AN,
},
[MRP_APPLICANT_AA] = {
[MRP_EVENT_NEW] = MRP_APPLICANT_VN,
[MRP_EVENT_JOIN] = MRP_APPLICANT_AA,
[MRP_EVENT_LV] = MRP_APPLICANT_LA,
[MRP_EVENT_TX] = MRP_APPLICANT_QA,
[MRP_EVENT_R_NEW] = MRP_APPLICANT_AA,
[MRP_EVENT_R_JOIN_IN] = MRP_APPLICANT_QA,
[MRP_EVENT_R_IN] = MRP_APPLICANT_AA,
[MRP_EVENT_R_JOIN_MT] = MRP_APPLICANT_AA,
[MRP_EVENT_R_MT] = MRP_APPLICANT_AA,
[MRP_EVENT_R_LV] = MRP_APPLICANT_VP,
[MRP_EVENT_R_LA] = MRP_APPLICANT_VP,
[MRP_EVENT_REDECLARE] = MRP_APPLICANT_VP,
[MRP_EVENT_PERIODIC] = MRP_APPLICANT_AA,
},
[MRP_APPLICANT_QA] = {
[MRP_EVENT_NEW] = MRP_APPLICANT_VN,
[MRP_EVENT_JOIN] = MRP_APPLICANT_QA,
[MRP_EVENT_LV] = MRP_APPLICANT_LA,
[MRP_EVENT_TX] = MRP_APPLICANT_QA,
[MRP_EVENT_R_NEW] = MRP_APPLICANT_QA,
[MRP_EVENT_R_JOIN_IN] = MRP_APPLICANT_QA,
[MRP_EVENT_R_IN] = MRP_APPLICANT_QA,
[MRP_EVENT_R_JOIN_MT] = MRP_APPLICANT_AA,
[MRP_EVENT_R_MT] = MRP_APPLICANT_AA,
[MRP_EVENT_R_LV] = MRP_APPLICANT_VP,
[MRP_EVENT_R_LA] = MRP_APPLICANT_VP,
[MRP_EVENT_REDECLARE] = MRP_APPLICANT_VP,
[MRP_EVENT_PERIODIC] = MRP_APPLICANT_AA,
},
[MRP_APPLICANT_LA] = {
[MRP_EVENT_NEW] = MRP_APPLICANT_VN,
[MRP_EVENT_JOIN] = MRP_APPLICANT_AA,
[MRP_EVENT_LV] = MRP_APPLICANT_LA,
[MRP_EVENT_TX] = MRP_APPLICANT_VO,
[MRP_EVENT_R_NEW] = MRP_APPLICANT_LA,
[MRP_EVENT_R_JOIN_IN] = MRP_APPLICANT_LA,
[MRP_EVENT_R_IN] = MRP_APPLICANT_LA,
[MRP_EVENT_R_JOIN_MT] = MRP_APPLICANT_LA,
[MRP_EVENT_R_MT] = MRP_APPLICANT_LA,
[MRP_EVENT_R_LV] = MRP_APPLICANT_LA,
[MRP_EVENT_R_LA] = MRP_APPLICANT_LA,
[MRP_EVENT_REDECLARE] = MRP_APPLICANT_LA,
[MRP_EVENT_PERIODIC] = MRP_APPLICANT_LA,
},
[MRP_APPLICANT_AO] = {
[MRP_EVENT_NEW] = MRP_APPLICANT_VN,
[MRP_EVENT_JOIN] = MRP_APPLICANT_AP,
[MRP_EVENT_LV] = MRP_APPLICANT_AO,
[MRP_EVENT_TX] = MRP_APPLICANT_AO,
[MRP_EVENT_R_NEW] = MRP_APPLICANT_AO,
[MRP_EVENT_R_JOIN_IN] = MRP_APPLICANT_QO,
[MRP_EVENT_R_IN] = MRP_APPLICANT_AO,
[MRP_EVENT_R_JOIN_MT] = MRP_APPLICANT_AO,
[MRP_EVENT_R_MT] = MRP_APPLICANT_AO,
[MRP_EVENT_R_LV] = MRP_APPLICANT_VO,
[MRP_EVENT_R_LA] = MRP_APPLICANT_VO,
[MRP_EVENT_REDECLARE] = MRP_APPLICANT_VO,
[MRP_EVENT_PERIODIC] = MRP_APPLICANT_AO,
},
[MRP_APPLICANT_QO] = {
[MRP_EVENT_NEW] = MRP_APPLICANT_VN,
[MRP_EVENT_JOIN] = MRP_APPLICANT_QP,
[MRP_EVENT_LV] = MRP_APPLICANT_QO,
[MRP_EVENT_TX] = MRP_APPLICANT_QO,
[MRP_EVENT_R_NEW] = MRP_APPLICANT_QO,
[MRP_EVENT_R_JOIN_IN] = MRP_APPLICANT_QO,
[MRP_EVENT_R_IN] = MRP_APPLICANT_QO,
[MRP_EVENT_R_JOIN_MT] = MRP_APPLICANT_AO,
[MRP_EVENT_R_MT] = MRP_APPLICANT_AO,
[MRP_EVENT_R_LV] = MRP_APPLICANT_VO,
[MRP_EVENT_R_LA] = MRP_APPLICANT_VO,
[MRP_EVENT_REDECLARE] = MRP_APPLICANT_VO,
[MRP_EVENT_PERIODIC] = MRP_APPLICANT_QO,
},
[MRP_APPLICANT_AP] = {
[MRP_EVENT_NEW] = MRP_APPLICANT_VN,
[MRP_EVENT_JOIN] = MRP_APPLICANT_AP,
[MRP_EVENT_LV] = MRP_APPLICANT_AO,
[MRP_EVENT_TX] = MRP_APPLICANT_QA,
[MRP_EVENT_R_NEW] = MRP_APPLICANT_AP,
[MRP_EVENT_R_JOIN_IN] = MRP_APPLICANT_QP,
[MRP_EVENT_R_IN] = MRP_APPLICANT_AP,
[MRP_EVENT_R_JOIN_MT] = MRP_APPLICANT_AP,
[MRP_EVENT_R_MT] = MRP_APPLICANT_AP,
[MRP_EVENT_R_LV] = MRP_APPLICANT_VP,
[MRP_EVENT_R_LA] = MRP_APPLICANT_VP,
[MRP_EVENT_REDECLARE] = MRP_APPLICANT_VP,
[MRP_EVENT_PERIODIC] = MRP_APPLICANT_AP,
},
[MRP_APPLICANT_QP] = {
[MRP_EVENT_NEW] = MRP_APPLICANT_VN,
[MRP_EVENT_JOIN] = MRP_APPLICANT_QP,
[MRP_EVENT_LV] = MRP_APPLICANT_QO,
[MRP_EVENT_TX] = MRP_APPLICANT_QP,
[MRP_EVENT_R_NEW] = MRP_APPLICANT_QP,
[MRP_EVENT_R_JOIN_IN] = MRP_APPLICANT_QP,
[MRP_EVENT_R_IN] = MRP_APPLICANT_QP,
[MRP_EVENT_R_JOIN_MT] = MRP_APPLICANT_AP,
[MRP_EVENT_R_MT] = MRP_APPLICANT_AP,
[MRP_EVENT_R_LV] = MRP_APPLICANT_VP,
[MRP_EVENT_R_LA] = MRP_APPLICANT_VP,
[MRP_EVENT_REDECLARE] = MRP_APPLICANT_VP,
[MRP_EVENT_PERIODIC] = MRP_APPLICANT_AP,
},
};
static const u8
mrp_tx_action_table[MRP_APPLICANT_MAX + 1] = {
[MRP_APPLICANT_VO] = MRP_TX_ACTION_S_IN_OPTIONAL,
[MRP_APPLICANT_VP] = MRP_TX_ACTION_S_JOIN_IN,
[MRP_APPLICANT_VN] = MRP_TX_ACTION_S_NEW,
[MRP_APPLICANT_AN] = MRP_TX_ACTION_S_NEW,
[MRP_APPLICANT_AA] = MRP_TX_ACTION_S_JOIN_IN,
[MRP_APPLICANT_QA] = MRP_TX_ACTION_S_JOIN_IN_OPTIONAL,
[MRP_APPLICANT_LA] = MRP_TX_ACTION_S_LV,
[MRP_APPLICANT_AO] = MRP_TX_ACTION_S_IN_OPTIONAL,
[MRP_APPLICANT_QO] = MRP_TX_ACTION_S_IN_OPTIONAL,
[MRP_APPLICANT_AP] = MRP_TX_ACTION_S_JOIN_IN,
[MRP_APPLICANT_QP] = MRP_TX_ACTION_S_IN_OPTIONAL,
};
static void mrp_attrvalue_inc(void *value, u8 len)
{
u8 *v = (u8 *)value;
/* Add 1 to the last byte. If it becomes zero,
* go to the previous byte and repeat.
*/
while (len > 0 && !++v[--len])
;
}
static int mrp_attr_cmp(const struct mrp_attr *attr,
const void *value, u8 len, u8 type)
{
if (attr->type != type)
return attr->type - type;
if (attr->len != len)
return attr->len - len;
return memcmp(attr->value, value, len);
}
static struct mrp_attr *mrp_attr_lookup(const struct mrp_applicant *app,
const void *value, u8 len, u8 type)
{
struct rb_node *parent = app->mad.rb_node;
struct mrp_attr *attr;
int d;
while (parent) {
attr = rb_entry(parent, struct mrp_attr, node);
d = mrp_attr_cmp(attr, value, len, type);
if (d > 0)
parent = parent->rb_left;
else if (d < 0)
parent = parent->rb_right;
else
return attr;
}
return NULL;
}
static struct mrp_attr *mrp_attr_create(struct mrp_applicant *app,
const void *value, u8 len, u8 type)
{
struct rb_node *parent = NULL, **p = &app->mad.rb_node;
struct mrp_attr *attr;
int d;
while (*p) {
parent = *p;
attr = rb_entry(parent, struct mrp_attr, node);
d = mrp_attr_cmp(attr, value, len, type);
if (d > 0)
p = &parent->rb_left;
else if (d < 0)
p = &parent->rb_right;
else {
/* The attribute already exists; re-use it. */
return attr;
}
}
attr = kmalloc(sizeof(*attr) + len, GFP_ATOMIC);
if (!attr)
return attr;
attr->state = MRP_APPLICANT_VO;
attr->type = type;
attr->len = len;
memcpy(attr->value, value, len);
rb_link_node(&attr->node, parent, p);
rb_insert_color(&attr->node, &app->mad);
return attr;
}
static void mrp_attr_destroy(struct mrp_applicant *app, struct mrp_attr *attr)
{
rb_erase(&attr->node, &app->mad);
kfree(attr);
}
static int mrp_pdu_init(struct mrp_applicant *app)
{
struct sk_buff *skb;
struct mrp_pdu_hdr *ph;
skb = alloc_skb(app->dev->mtu + LL_RESERVED_SPACE(app->dev),
GFP_ATOMIC);
if (!skb)
return -ENOMEM;
skb->dev = app->dev;
skb->protocol = app->app->pkttype.type;
skb_reserve(skb, LL_RESERVED_SPACE(app->dev));
skb_reset_network_header(skb);
skb_reset_transport_header(skb);
ph = __skb_put(skb, sizeof(*ph));
ph->version = app->app->version;
app->pdu = skb;
return 0;
}
static int mrp_pdu_append_end_mark(struct mrp_applicant *app)
{
__be16 *endmark;
if (skb_tailroom(app->pdu) < sizeof(*endmark))
return -1;
endmark = __skb_put(app->pdu, sizeof(*endmark));
put_unaligned(MRP_END_MARK, endmark);
return 0;
}
static void mrp_pdu_queue(struct mrp_applicant *app)
{
if (!app->pdu)
return;
if (mrp_cb(app->pdu)->mh)
mrp_pdu_append_end_mark(app);
mrp_pdu_append_end_mark(app);
dev_hard_header(app->pdu, app->dev, ntohs(app->app->pkttype.type),
app->app->group_address, app->dev->dev_addr,
app->pdu->len);
skb_queue_tail(&app->queue, app->pdu);
app->pdu = NULL;
}
static void mrp_queue_xmit(struct mrp_applicant *app)
{
struct sk_buff *skb;
while ((skb = skb_dequeue(&app->queue)))
dev_queue_xmit(skb);
}
static int mrp_pdu_append_msg_hdr(struct mrp_applicant *app,
u8 attrtype, u8 attrlen)
{
struct mrp_msg_hdr *mh;
if (mrp_cb(app->pdu)->mh) {
if (mrp_pdu_append_end_mark(app) < 0)
return -1;
mrp_cb(app->pdu)->mh = NULL;
mrp_cb(app->pdu)->vah = NULL;
}
if (skb_tailroom(app->pdu) < sizeof(*mh))
return -1;
mh = __skb_put(app->pdu, sizeof(*mh));
mh->attrtype = attrtype;
mh->attrlen = attrlen;
mrp_cb(app->pdu)->mh = mh;
return 0;
}
static int mrp_pdu_append_vecattr_hdr(struct mrp_applicant *app,
const void *firstattrvalue, u8 attrlen)
{
struct mrp_vecattr_hdr *vah;
if (skb_tailroom(app->pdu) < sizeof(*vah) + attrlen)
return -1;
vah = __skb_put(app->pdu, sizeof(*vah) + attrlen);
put_unaligned(0, &vah->lenflags);
memcpy(vah->firstattrvalue, firstattrvalue, attrlen);
mrp_cb(app->pdu)->vah = vah;
memcpy(mrp_cb(app->pdu)->attrvalue, firstattrvalue, attrlen);
return 0;
}
static int mrp_pdu_append_vecattr_event(struct mrp_applicant *app,
const struct mrp_attr *attr,
enum mrp_vecattr_event vaevent)
{
u16 len, pos;
u8 *vaevents;
int err;
again:
if (!app->pdu) {
err = mrp_pdu_init(app);
if (err < 0)
return err;
}
/* If there is no Message header in the PDU, or the Message header is
* for a different attribute type, add an EndMark (if necessary) and a
* new Message header to the PDU.
*/
if (!mrp_cb(app->pdu)->mh ||
mrp_cb(app->pdu)->mh->attrtype != attr->type ||
mrp_cb(app->pdu)->mh->attrlen != attr->len) {
if (mrp_pdu_append_msg_hdr(app, attr->type, attr->len) < 0)
goto queue;
}
/* If there is no VectorAttribute header for this Message in the PDU,
* or this attribute's value does not sequentially follow the previous
* attribute's value, add a new VectorAttribute header to the PDU.
*/
if (!mrp_cb(app->pdu)->vah ||
memcmp(mrp_cb(app->pdu)->attrvalue, attr->value, attr->len)) {
if (mrp_pdu_append_vecattr_hdr(app, attr->value, attr->len) < 0)
goto queue;
}
len = be16_to_cpu(get_unaligned(&mrp_cb(app->pdu)->vah->lenflags));
pos = len % 3;
/* Events are packed into Vectors in the PDU, three to a byte. Add a
* byte to the end of the Vector if necessary.
*/
if (!pos) {
if (skb_tailroom(app->pdu) < sizeof(u8))
goto queue;
vaevents = __skb_put(app->pdu, sizeof(u8));
} else {
vaevents = (u8 *)(skb_tail_pointer(app->pdu) - sizeof(u8));
}
switch (pos) {
case 0:
*vaevents = vaevent * (__MRP_VECATTR_EVENT_MAX *
__MRP_VECATTR_EVENT_MAX);
break;
case 1:
*vaevents += vaevent * __MRP_VECATTR_EVENT_MAX;
break;
case 2:
*vaevents += vaevent;
break;
default:
WARN_ON(1);
}
/* Increment the length of the VectorAttribute in the PDU, as well as
* the value of the next attribute that would continue its Vector.
*/
put_unaligned(cpu_to_be16(++len), &mrp_cb(app->pdu)->vah->lenflags);
mrp_attrvalue_inc(mrp_cb(app->pdu)->attrvalue, attr->len);
return 0;
queue:
mrp_pdu_queue(app);
goto again;
}
static void mrp_attr_event(struct mrp_applicant *app,
struct mrp_attr *attr, enum mrp_event event)
{
enum mrp_applicant_state state;
state = mrp_applicant_state_table[attr->state][event];
if (state == MRP_APPLICANT_INVALID) {
WARN_ON(1);
return;
}
if (event == MRP_EVENT_TX) {
/* When appending the attribute fails, don't update its state
* in order to retry at the next TX event.
*/
switch (mrp_tx_action_table[attr->state]) {
case MRP_TX_ACTION_NONE:
case MRP_TX_ACTION_S_JOIN_IN_OPTIONAL:
case MRP_TX_ACTION_S_IN_OPTIONAL:
break;
case MRP_TX_ACTION_S_NEW:
if (mrp_pdu_append_vecattr_event(
app, attr, MRP_VECATTR_EVENT_NEW) < 0)
return;
break;
case MRP_TX_ACTION_S_JOIN_IN:
if (mrp_pdu_append_vecattr_event(
app, attr, MRP_VECATTR_EVENT_JOIN_IN) < 0)
return;
break;
case MRP_TX_ACTION_S_LV:
if (mrp_pdu_append_vecattr_event(
app, attr, MRP_VECATTR_EVENT_LV) < 0)
return;
/* As a pure applicant, sending a leave message
* implies that the attribute was unregistered and
* can be destroyed.
*/
mrp_attr_destroy(app, attr);
return;
default:
WARN_ON(1);
}
}
attr->state = state;
}
int mrp_request_join(const struct net_device *dev,
const struct mrp_application *appl,
const void *value, u8 len, u8 type)
{
struct mrp_port *port = rtnl_dereference(dev->mrp_port);
struct mrp_applicant *app = rtnl_dereference(
port->applicants[appl->type]);
struct mrp_attr *attr;
if (sizeof(struct mrp_skb_cb) + len >
FIELD_SIZEOF(struct sk_buff, cb))
return -ENOMEM;
spin_lock_bh(&app->lock);
attr = mrp_attr_create(app, value, len, type);
if (!attr) {
spin_unlock_bh(&app->lock);
return -ENOMEM;
}
mrp_attr_event(app, attr, MRP_EVENT_JOIN);
spin_unlock_bh(&app->lock);
return 0;
}
EXPORT_SYMBOL_GPL(mrp_request_join);
void mrp_request_leave(const struct net_device *dev,
const struct mrp_application *appl,
const void *value, u8 len, u8 type)
{
struct mrp_port *port = rtnl_dereference(dev->mrp_port);
struct mrp_applicant *app = rtnl_dereference(
port->applicants[appl->type]);
struct mrp_attr *attr;
if (sizeof(struct mrp_skb_cb) + len >
FIELD_SIZEOF(struct sk_buff, cb))
return;
spin_lock_bh(&app->lock);
attr = mrp_attr_lookup(app, value, len, type);
if (!attr) {
spin_unlock_bh(&app->lock);
return;
}
mrp_attr_event(app, attr, MRP_EVENT_LV);
spin_unlock_bh(&app->lock);
}
EXPORT_SYMBOL_GPL(mrp_request_leave);
static void mrp_mad_event(struct mrp_applicant *app, enum mrp_event event)
{
struct rb_node *node, *next;
struct mrp_attr *attr;
for (node = rb_first(&app->mad);
next = node ? rb_next(node) : NULL, node != NULL;
node = next) {
attr = rb_entry(node, struct mrp_attr, node);
mrp_attr_event(app, attr, event);
}
}
static void mrp_join_timer_arm(struct mrp_applicant *app)
{
unsigned long delay;
delay = (u64)msecs_to_jiffies(mrp_join_time) * prandom_u32() >> 32;
mod_timer(&app->join_timer, jiffies + delay);
}
static void mrp_join_timer(struct timer_list *t)
{
struct mrp_applicant *app = from_timer(app, t, join_timer);
spin_lock(&app->lock);
mrp_mad_event(app, MRP_EVENT_TX);
mrp_pdu_queue(app);
spin_unlock(&app->lock);
mrp_queue_xmit(app);
mrp_join_timer_arm(app);
}
static void mrp_periodic_timer_arm(struct mrp_applicant *app)
{
mod_timer(&app->periodic_timer,
jiffies + msecs_to_jiffies(mrp_periodic_time));
}
static void mrp_periodic_timer(struct timer_list *t)
{
struct mrp_applicant *app = from_timer(app, t, periodic_timer);
spin_lock(&app->lock);
mrp_mad_event(app, MRP_EVENT_PERIODIC);
mrp_pdu_queue(app);
spin_unlock(&app->lock);
mrp_periodic_timer_arm(app);
}
static int mrp_pdu_parse_end_mark(struct sk_buff *skb, int *offset)
{
__be16 endmark;
if (skb_copy_bits(skb, *offset, &endmark, sizeof(endmark)) < 0)
return -1;
if (endmark == MRP_END_MARK) {
*offset += sizeof(endmark);
return -1;
}
return 0;
}
static void mrp_pdu_parse_vecattr_event(struct mrp_applicant *app,
struct sk_buff *skb,
enum mrp_vecattr_event vaevent)
{
struct mrp_attr *attr;
enum mrp_event event;
attr = mrp_attr_lookup(app, mrp_cb(skb)->attrvalue,
mrp_cb(skb)->mh->attrlen,
mrp_cb(skb)->mh->attrtype);
if (attr == NULL)
return;
switch (vaevent) {
case MRP_VECATTR_EVENT_NEW:
event = MRP_EVENT_R_NEW;
break;
case MRP_VECATTR_EVENT_JOIN_IN:
event = MRP_EVENT_R_JOIN_IN;
break;
case MRP_VECATTR_EVENT_IN:
event = MRP_EVENT_R_IN;
break;
case MRP_VECATTR_EVENT_JOIN_MT:
event = MRP_EVENT_R_JOIN_MT;
break;
case MRP_VECATTR_EVENT_MT:
event = MRP_EVENT_R_MT;
break;
case MRP_VECATTR_EVENT_LV:
event = MRP_EVENT_R_LV;
break;
default:
return;
}
mrp_attr_event(app, attr, event);
}
static int mrp_pdu_parse_vecattr(struct mrp_applicant *app,
struct sk_buff *skb, int *offset)
{
struct mrp_vecattr_hdr _vah;
u16 valen;
u8 vaevents, vaevent;
mrp_cb(skb)->vah = skb_header_pointer(skb, *offset, sizeof(_vah),
&_vah);
if (!mrp_cb(skb)->vah)
return -1;
*offset += sizeof(_vah);
if (get_unaligned(&mrp_cb(skb)->vah->lenflags) &
MRP_VECATTR_HDR_FLAG_LA)
mrp_mad_event(app, MRP_EVENT_R_LA);
valen = be16_to_cpu(get_unaligned(&mrp_cb(skb)->vah->lenflags) &
MRP_VECATTR_HDR_LEN_MASK);
/* The VectorAttribute structure in a PDU carries event information
* about one or more attributes having consecutive values. Only the
* value for the first attribute is contained in the structure. So
* we make a copy of that value, and then increment it each time we
* advance to the next event in its Vector.
*/
if (sizeof(struct mrp_skb_cb) + mrp_cb(skb)->mh->attrlen >
FIELD_SIZEOF(struct sk_buff, cb))
return -1;
if (skb_copy_bits(skb, *offset, mrp_cb(skb)->attrvalue,
mrp_cb(skb)->mh->attrlen) < 0)
return -1;
*offset += mrp_cb(skb)->mh->attrlen;
/* In a VectorAttribute, the Vector contains events which are packed
* three to a byte. We process one byte of the Vector at a time.
*/
while (valen > 0) {
if (skb_copy_bits(skb, *offset, &vaevents,
sizeof(vaevents)) < 0)
return -1;
*offset += sizeof(vaevents);
/* Extract and process the first event. */
vaevent = vaevents / (__MRP_VECATTR_EVENT_MAX *
__MRP_VECATTR_EVENT_MAX);
if (vaevent >= __MRP_VECATTR_EVENT_MAX) {
/* The byte is malformed; stop processing. */
return -1;
}
mrp_pdu_parse_vecattr_event(app, skb, vaevent);
/* If present, extract and process the second event. */
if (!--valen)
break;
mrp_attrvalue_inc(mrp_cb(skb)->attrvalue,
mrp_cb(skb)->mh->attrlen);
vaevents %= (__MRP_VECATTR_EVENT_MAX *
__MRP_VECATTR_EVENT_MAX);
vaevent = vaevents / __MRP_VECATTR_EVENT_MAX;
mrp_pdu_parse_vecattr_event(app, skb, vaevent);
/* If present, extract and process the third event. */
if (!--valen)
break;
mrp_attrvalue_inc(mrp_cb(skb)->attrvalue,
mrp_cb(skb)->mh->attrlen);
vaevents %= __MRP_VECATTR_EVENT_MAX;
vaevent = vaevents;
mrp_pdu_parse_vecattr_event(app, skb, vaevent);
}
return 0;
}
static int mrp_pdu_parse_msg(struct mrp_applicant *app, struct sk_buff *skb,
int *offset)
{
struct mrp_msg_hdr _mh;
mrp_cb(skb)->mh = skb_header_pointer(skb, *offset, sizeof(_mh), &_mh);
if (!mrp_cb(skb)->mh)
return -1;
*offset += sizeof(_mh);
if (mrp_cb(skb)->mh->attrtype == 0 ||
mrp_cb(skb)->mh->attrtype > app->app->maxattr ||
mrp_cb(skb)->mh->attrlen == 0)
return -1;
while (skb->len > *offset) {
if (mrp_pdu_parse_end_mark(skb, offset) < 0)
break;
if (mrp_pdu_parse_vecattr(app, skb, offset) < 0)
return -1;
}
return 0;
}
static int mrp_rcv(struct sk_buff *skb, struct net_device *dev,
struct packet_type *pt, struct net_device *orig_dev)
{
struct mrp_application *appl = container_of(pt, struct mrp_application,
pkttype);
struct mrp_port *port;
struct mrp_applicant *app;
struct mrp_pdu_hdr _ph;
const struct mrp_pdu_hdr *ph;
int offset = skb_network_offset(skb);
/* If the interface is in promiscuous mode, drop the packet if
* it was unicast to another host.
*/
if (unlikely(skb->pkt_type == PACKET_OTHERHOST))
goto out;
skb = skb_share_check(skb, GFP_ATOMIC);
if (unlikely(!skb))
goto out;
port = rcu_dereference(dev->mrp_port);
if (unlikely(!port))
goto out;
app = rcu_dereference(port->applicants[appl->type]);
if (unlikely(!app))
goto out;
ph = skb_header_pointer(skb, offset, sizeof(_ph), &_ph);
if (!ph)
goto out;
offset += sizeof(_ph);
if (ph->version != app->app->version)
goto out;
spin_lock(&app->lock);
while (skb->len > offset) {
if (mrp_pdu_parse_end_mark(skb, &offset) < 0)
break;
if (mrp_pdu_parse_msg(app, skb, &offset) < 0)
break;
}
spin_unlock(&app->lock);
out:
kfree_skb(skb);
return 0;
}
static int mrp_init_port(struct net_device *dev)
{
struct mrp_port *port;
port = kzalloc(sizeof(*port), GFP_KERNEL);
if (!port)
return -ENOMEM;
rcu_assign_pointer(dev->mrp_port, port);
return 0;
}
static void mrp_release_port(struct net_device *dev)
{
struct mrp_port *port = rtnl_dereference(dev->mrp_port);
unsigned int i;
for (i = 0; i <= MRP_APPLICATION_MAX; i++) {
if (rtnl_dereference(port->applicants[i]))
return;
}
RCU_INIT_POINTER(dev->mrp_port, NULL);
kfree_rcu(port, rcu);
}
int mrp_init_applicant(struct net_device *dev, struct mrp_application *appl)
{
struct mrp_applicant *app;
int err;
ASSERT_RTNL();
if (!rtnl_dereference(dev->mrp_port)) {
err = mrp_init_port(dev);
if (err < 0)
goto err1;
}
err = -ENOMEM;
app = kzalloc(sizeof(*app), GFP_KERNEL);
if (!app)
goto err2;
err = dev_mc_add(dev, appl->group_address);
if (err < 0)
goto err3;
app->dev = dev;
app->app = appl;
app->mad = RB_ROOT;
spin_lock_init(&app->lock);
skb_queue_head_init(&app->queue);
rcu_assign_pointer(dev->mrp_port->applicants[appl->type], app);
timer_setup(&app->join_timer, mrp_join_timer, 0);
mrp_join_timer_arm(app);
timer_setup(&app->periodic_timer, mrp_periodic_timer, 0);
mrp_periodic_timer_arm(app);
return 0;
err3:
kfree(app);
err2:
mrp_release_port(dev);
err1:
return err;
}
EXPORT_SYMBOL_GPL(mrp_init_applicant);
void mrp_uninit_applicant(struct net_device *dev, struct mrp_application *appl)
{
struct mrp_port *port = rtnl_dereference(dev->mrp_port);
struct mrp_applicant *app = rtnl_dereference(
port->applicants[appl->type]);
ASSERT_RTNL();
RCU_INIT_POINTER(port->applicants[appl->type], NULL);
/* Delete timer and generate a final TX event to flush out
* all pending messages before the applicant is gone.
*/
del_timer_sync(&app->join_timer);
del_timer_sync(&app->periodic_timer);
spin_lock_bh(&app->lock);
mrp_mad_event(app, MRP_EVENT_TX);
mrp_pdu_queue(app);
spin_unlock_bh(&app->lock);
mrp_queue_xmit(app);
dev_mc_del(dev, appl->group_address);
kfree_rcu(app, rcu);
mrp_release_port(dev);
}
EXPORT_SYMBOL_GPL(mrp_uninit_applicant);
int mrp_register_application(struct mrp_application *appl)
{
appl->pkttype.func = mrp_rcv;
dev_add_pack(&appl->pkttype);
return 0;
}
EXPORT_SYMBOL_GPL(mrp_register_application);
void mrp_unregister_application(struct mrp_application *appl)
{
dev_remove_pack(&appl->pkttype);
}
EXPORT_SYMBOL_GPL(mrp_unregister_application);
| 27.119306 | 79 | 0.718765 | [
"vector"
] |
2cfe0ba61b64f8b279f65bc50faff767110341fe | 2,757 | h | C | sys/arch/amd64/include/intrdefs.h | ArrogantWombatics/openbsd-src | 75721e1d44322953075b7c4b89337b163a395291 | [
"BSD-3-Clause"
] | 1 | 2019-02-16T13:29:23.000Z | 2019-02-16T13:29:23.000Z | sys/arch/amd64/include/intrdefs.h | ArrogantWombatics/openbsd-src | 75721e1d44322953075b7c4b89337b163a395291 | [
"BSD-3-Clause"
] | 1 | 2018-08-21T03:56:33.000Z | 2018-08-21T03:56:33.000Z | sys/arch/amd64/include/intrdefs.h | ArrogantWombatics/openbsd-src | 75721e1d44322953075b7c4b89337b163a395291 | [
"BSD-3-Clause"
] | null | null | null | /* $OpenBSD: intrdefs.h,v 1.16 2016/06/22 01:12:38 mikeb Exp $ */
/* $NetBSD: intrdefs.h,v 1.2 2003/05/04 22:01:56 fvdl Exp $ */
#ifndef _AMD64_INTRDEFS_H
#define _AMD64_INTRDEFS_H
/*
* Interrupt priority levels.
*
* There are tty, network and disk drivers that use free() at interrupt
* time, so imp > (tty | net | bio).
*
* Since run queues may be manipulated by both the statclock and tty,
* network, and disk drivers, clock > imp.
*
* IPL_HIGH must block everything that can manipulate a run queue.
*
* The level numbers are picked to fit into APIC vector priorities.
*
*/
#define IPL_NONE 0x0 /* nothing */
#define IPL_SOFTCLOCK 0x4 /* timeouts */
#define IPL_SOFTNET 0x5 /* protocol stacks */
#define IPL_BIO 0x6 /* block I/O */
#define IPL_NET 0x7 /* network */
#define IPL_SOFTTTY 0x8 /* delayed terminal handling */
#define IPL_TTY 0x9 /* terminal */
#define IPL_VM 0xa /* memory allocation */
#define IPL_AUDIO 0xb /* audio */
#define IPL_CLOCK 0xc /* clock */
#define IPL_SCHED IPL_CLOCK
#define IPL_STATCLOCK IPL_CLOCK
#define IPL_HIGH 0xd /* everything */
#define IPL_IPI 0xe /* inter-processor interrupts */
#define NIPL 16
#define IPL_MPSAFE 0x100
/* Interrupt sharing types. */
#define IST_NONE 0 /* none */
#define IST_PULSE 1 /* pulsed */
#define IST_EDGE 2 /* edge-triggered */
#define IST_LEVEL 3 /* level-triggered */
/*
* Local APIC masks. Must not conflict with SIR_* above, and must
* be >= NUM_LEGACY_IRQs. Note that LIR_IPI must be first.
*/
#define LIR_IPI 63
#define LIR_TIMER 62
/* Soft interrupt masks. */
#define SIR_CLOCK 61
#define SIR_NET 60
#define SIR_TTY 59
#define LIR_XEN 58
#define LIR_HYPERV 57
/*
* Maximum # of interrupt sources per CPU. 64 to fit in one word.
* ioapics can theoretically produce more, but it's not likely to
* happen. For multiple ioapics, things can be routed to different
* CPUs.
*/
#define MAX_INTR_SOURCES 64
#define NUM_LEGACY_IRQS 16
/*
* Low and high boundaries between which interrupt gates will
* be allocated in the IDT.
*/
#define IDT_INTR_LOW (0x20 + NUM_LEGACY_IRQS)
#define IDT_INTR_HIGH 0xef
#define X86_IPI_HALT 0x00000001
#define X86_IPI_NOP 0x00000002
#define X86_IPI_FLUSH_FPU 0x00000004
#define X86_IPI_SYNCH_FPU 0x00000008
#define X86_IPI_TLB 0x00000010
#define X86_IPI_MTRR 0x00000020
#define X86_IPI_SETPERF 0x00000040
#define X86_IPI_DDB 0x00000080
#define X86_IPI_START_VMM 0x00000100
#define X86_IPI_STOP_VMM 0x00000200
#define X86_NIPI 10
#define X86_IPI_NAMES { "halt IPI", "nop IPI", "FPU flush IPI", \
"FPU synch IPI", "TLB shootdown IPI", \
"MTRR update IPI", "setperf IPI", "ddb IPI", \
"VMM start IPI", "VMM stop IPI" }
#define IREENT_MAGIC 0x18041969
#endif /* _AMD64_INTRDEFS_H */
| 28.42268 | 71 | 0.724338 | [
"vector"
] |
fa02ef0529e73f6eeaf299193dc9182ff1681a9a | 6,754 | h | C | difc-kernel/pileus-kernel/drivers/staging/fsl-mc/include/mc.h | SIIS-cloud/pileus | de7546845cf03862cdd2b9884fefb2033d8b11ab | [
"Apache-2.0"
] | 3 | 2017-09-22T15:10:01.000Z | 2018-03-30T02:11:54.000Z | linux-imx6/drivers/staging/fsl-mc/include/mc.h | ub-rms/rushmore | 9e6c06e94420349f94fa9c1529e1817efd547c7d | [
"BSD-2-Clause"
] | null | null | null | linux-imx6/drivers/staging/fsl-mc/include/mc.h | ub-rms/rushmore | 9e6c06e94420349f94fa9c1529e1817efd547c7d | [
"BSD-2-Clause"
] | null | null | null | /*
* Freescale Management Complex (MC) bus public interface
*
* Copyright (C) 2014 Freescale Semiconductor, Inc.
* Author: German Rivera <German.Rivera@freescale.com>
*
* This file is licensed under the terms of the GNU General Public
* License version 2. This program is licensed "as is" without any
* warranty of any kind, whether express or implied.
*/
#ifndef _FSL_MC_H_
#define _FSL_MC_H_
#include <linux/device.h>
#include <linux/mod_devicetable.h>
#include <linux/list.h>
#include "../include/dprc.h"
#define FSL_MC_VENDOR_FREESCALE 0x1957
struct fsl_mc_device;
struct fsl_mc_io;
/**
* struct fsl_mc_driver - MC object device driver object
* @driver: Generic device driver
* @match_id_table: table of supported device matching Ids
* @probe: Function called when a device is added
* @remove: Function called when a device is removed
* @shutdown: Function called at shutdown time to quiesce the device
* @suspend: Function called when a device is stopped
* @resume: Function called when a device is resumed
*
* Generic DPAA device driver object for device drivers that are registered
* with a DPRC bus. This structure is to be embedded in each device-specific
* driver structure.
*/
struct fsl_mc_driver {
struct device_driver driver;
const struct fsl_mc_device_match_id *match_id_table;
int (*probe)(struct fsl_mc_device *dev);
int (*remove)(struct fsl_mc_device *dev);
void (*shutdown)(struct fsl_mc_device *dev);
int (*suspend)(struct fsl_mc_device *dev, pm_message_t state);
int (*resume)(struct fsl_mc_device *dev);
};
#define to_fsl_mc_driver(_drv) \
container_of(_drv, struct fsl_mc_driver, driver)
/**
* struct fsl_mc_device_match_id - MC object device Id entry for driver matching
* @vendor: vendor ID
* @obj_type: MC object type
* @ver_major: MC object version major number
* @ver_minor: MC object version minor number
*
* Type of entries in the "device Id" table for MC object devices supported by
* a MC object device driver. The last entry of the table has vendor set to 0x0
*/
struct fsl_mc_device_match_id {
uint16_t vendor;
const char obj_type[16];
uint32_t ver_major;
uint32_t ver_minor;
};
/**
* enum fsl_mc_pool_type - Types of allocatable MC bus resources
*
* Entries in these enum are used as indices in the array of resource
* pools of an fsl_mc_bus object.
*/
enum fsl_mc_pool_type {
FSL_MC_POOL_DPMCP = 0x0, /* corresponds to "dpmcp" in the MC */
FSL_MC_POOL_DPBP, /* corresponds to "dpbp" in the MC */
FSL_MC_POOL_DPCON, /* corresponds to "dpcon" in the MC */
/*
* NOTE: New resource pool types must be added before this entry
*/
FSL_MC_NUM_POOL_TYPES
};
/**
* struct fsl_mc_resource - MC generic resource
* @type: type of resource
* @id: unique MC resource Id within the resources of the same type
* @data: pointer to resource-specific data if the resource is currently
* allocated, or NULL if the resource is not currently allocated.
* @parent_pool: pointer to the parent resource pool from which this
* resource is allocated from.
* @node: Node in the free list of the corresponding resource pool
*
* NOTE: This structure is to be embedded as a field of specific
* MC resource structures.
*/
struct fsl_mc_resource {
enum fsl_mc_pool_type type;
int32_t id;
void *data;
struct fsl_mc_resource_pool *parent_pool;
struct list_head node;
};
/**
* Bit masks for a MC object device (struct fsl_mc_device) flags
*/
#define FSL_MC_IS_DPRC 0x0001
/**
* Default DMA mask for devices on a fsl-mc bus
*/
#define FSL_MC_DEFAULT_DMA_MASK (~0ULL)
/**
* struct fsl_mc_device - MC object device object
* @dev: Linux driver model device object
* @dma_mask: Default DMA mask
* @flags: MC object device flags
* @icid: Isolation context ID for the device
* @mc_handle: MC handle for the corresponding MC object opened
* @mc_io: Pointer to MC IO object assigned to this device or
* NULL if none.
* @obj_desc: MC description of the DPAA device
* @regions: pointer to array of MMIO region entries
* @resource: generic resource associated with this MC object device, if any.
*
* Generic device object for MC object devices that are "attached" to a
* MC bus.
*
* NOTES:
* - For a non-DPRC object its icid is the same as its parent DPRC's icid.
* - The SMMU notifier callback gets invoked after device_add() has been
* called for an MC object device, but before the device-specific probe
* callback gets called.
* - DP_OBJ_DPRC objects are the only MC objects that have built-in MC
* portals. For all other MC objects, their device drivers are responsible for
* allocating MC portals for them by calling fsl_mc_portal_allocate().
* - Some types of MC objects (e.g., DP_OBJ_DPBP, DP_OBJ_DPCON) are
* treated as resources that can be allocated/deallocated from the
* corresponding resource pool in the object's parent DPRC, using the
* fsl_mc_object_allocate()/fsl_mc_object_free() functions. These MC objects
* are known as "allocatable" objects. For them, the corresponding
* fsl_mc_device's 'resource' points to the associated resource object.
* For MC objects that are not allocatable (e.g., DP_OBJ_DPRC, DP_OBJ_DPNI),
* 'resource' is NULL.
*/
struct fsl_mc_device {
struct device dev;
uint64_t dma_mask;
uint16_t flags;
uint16_t icid;
uint16_t mc_handle;
struct fsl_mc_io *mc_io;
struct dprc_obj_desc obj_desc;
struct resource *regions;
struct fsl_mc_resource *resource;
};
#define to_fsl_mc_device(_dev) \
container_of(_dev, struct fsl_mc_device, dev)
/*
* module_fsl_mc_driver() - Helper macro for drivers that don't do
* anything special in module init/exit. This eliminates a lot of
* boilerplate. Each module may only use this macro once, and
* calling it replaces module_init() and module_exit()
*/
#define module_fsl_mc_driver(__fsl_mc_driver) \
module_driver(__fsl_mc_driver, fsl_mc_driver_register, \
fsl_mc_driver_unregister)
/*
* Macro to avoid include chaining to get THIS_MODULE
*/
#define fsl_mc_driver_register(drv) \
__fsl_mc_driver_register(drv, THIS_MODULE)
int __must_check __fsl_mc_driver_register(struct fsl_mc_driver *fsl_mc_driver,
struct module *owner);
void fsl_mc_driver_unregister(struct fsl_mc_driver *driver);
int __must_check fsl_mc_portal_allocate(struct fsl_mc_device *mc_dev,
uint16_t mc_io_flags,
struct fsl_mc_io **new_mc_io);
void fsl_mc_portal_free(struct fsl_mc_io *mc_io);
int fsl_mc_portal_reset(struct fsl_mc_io *mc_io);
int __must_check fsl_mc_object_allocate(struct fsl_mc_device *mc_dev,
enum fsl_mc_pool_type pool_type,
struct fsl_mc_device **new_mc_adev);
void fsl_mc_object_free(struct fsl_mc_device *mc_adev);
extern struct bus_type fsl_mc_bus_type;
#endif /* _FSL_MC_H_ */
| 33.435644 | 80 | 0.753776 | [
"object",
"model"
] |
fa035a8bc273ff5c99492a2d96927bcc08c6b020 | 1,340 | h | C | guetzli/jpeg_data_encoder.h | pps83/pik | 9747f8dbe9c10079b7473966fc974e4b3bcef034 | [
"Apache-2.0"
] | null | null | null | guetzli/jpeg_data_encoder.h | pps83/pik | 9747f8dbe9c10079b7473966fc974e4b3bcef034 | [
"Apache-2.0"
] | null | null | null | guetzli/jpeg_data_encoder.h | pps83/pik | 9747f8dbe9c10079b7473966fc974e4b3bcef034 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2016 Google 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.
*/
#ifndef GUETZLI_JPEG_DATA_ENCODER_H_
#define GUETZLI_JPEG_DATA_ENCODER_H_
#include <stdint.h>
#include "guetzli/jpeg_data.h"
namespace pik {
namespace guetzli {
// Adds APP0 header data.
void AddApp0Data(JPEGData* jpg);
// Creates a JPEG from the rgb pixel data. Returns true on success.
bool EncodeRGBToJpeg(const std::vector<uint8_t>& rgb, int w, int h,
JPEGData* jpg);
// Creates a JPEG from the rgb pixel data. Returns true on success. The given
// quantization table must have 3 * kDCTBlockSize values.
bool EncodeRGBToJpeg(const std::vector<uint8_t>& rgb, int w, int h,
const uint8_t* quant, JPEGData* jpg);
} // namespace guetzli
} // namespace pik
#endif // GUETZLI_JPEG_DATA_ENCODER_H_
| 31.162791 | 77 | 0.726119 | [
"vector"
] |
fa053e4c7666e41a5afcddbd92f38d6266983b31 | 41,167 | h | C | magrathea/datamodel.h | vreverdy/magrathea | c299bf041f3864cd5c074fe4389d5d233936ae17 | [
"CECILL-B"
] | null | null | null | magrathea/datamodel.h | vreverdy/magrathea | c299bf041f3864cd5c074fe4389d5d233936ae17 | [
"CECILL-B"
] | null | null | null | magrathea/datamodel.h | vreverdy/magrathea | c299bf041f3864cd5c074fe4389d5d233936ae17 | [
"CECILL-B"
] | null | null | null | /* ******************************* DATAMODEL ******************************** */
/*////////////////////////////////////////////////////////////////////////////*/
// PROJECT : MAGRATHEA-PATHFINDER
// TITLE : DataModel
// DESCRIPTION : Management of fundamental types representation
// AUTHOR(S) : Vincent Reverdy (vince.rev@gmail.com)
// CONTRIBUTIONS : [Vincent Reverdy (2012-2013)]
// LICENSE : CECILL-B License
/*////////////////////////////////////////////////////////////////////////////*/
/// \file datamodel.h
/// \brief Management of fundamental types representation
/// \author Vincent Reverdy (vince.rev@gmail.com)
/// \date 2012-2013
/// \copyright CECILL-B License
/*////////////////////////////////////////////////////////////////////////////*/
#ifndef DATAMODEL_H_INCLUDED
#define DATAMODEL_H_INCLUDED
/*////////////////////////////////////////////////////////////////////////////*/
// ------------------------------ PREPROCESSOR ------------------------------ //
// Include C++
#include <iostream>
#include <iomanip>
#include <type_traits>
#include <stdexcept>
#include <limits>
// Include libs
// Include project
// Misc
namespace magrathea {
// -------------------------------------------------------------------------- //
// ---------------------------------- CLASS --------------------------------- //
// Management of fundamental types representation
/// \brief Management of fundamental types representation.
/// \details Class to hold the data representation of fundamental types
/// on a system. The information is encoded in an <tt>unsigned
/// long long int</tt> in the following way where <tt>[BXbY-Z]
/// </tt> means the information starts at the bit <tt>Y</tt> of
/// the byte <tt>X</tt> and its size is <tt>Z</tt> bits : <ul>
/// <li><tt>[B0b0-1]</tt> endianness</li>
/// <li><tt>[B0b1-1]</tt> complement</li>
/// <li><tt>[B1b0-1]</tt> <tt>float</tt> compatibility to the
/// IEEE-754 <tt>binary32</tt> representation</li>
/// <li><tt>[B1b1-1]</tt> <tt>double</tt> compatibility to the
/// IEEE-754 <tt>binary64</tt> representation</li>
/// <li><tt>[B1b2-1]</tt> <tt>long double</tt> compatibility to
/// the IEEE-754 <tt>binary128</tt> representation</li>
/// <li><tt>[B2b0-4]</tt> <tt>void*</tt> size</li>
/// <li><tt>[B2b4-4]</tt> <tt>bool</tt> size</li>
/// <li><tt>[B3b0-4]</tt> <tt>char</tt> size</li>
/// <li><tt>[B3b4-4]</tt> <tt>short int</tt> size</li>
/// <li><tt>[B4b0-4]</tt> <tt>int</tt> size</li>
/// <li><tt>[B4b4-4]</tt> <tt>long int</tt> size</li>
/// <li><tt>[B5b0-4]</tt> <tt>long long int</tt> size</li>
/// <li><tt>[B6b0-4]</tt> <tt>float</tt> size</li>
/// <li><tt>[B6b4-4]</tt> <tt>double</tt> size</li>
/// <li><tt>[B7b0-4]</tt> <tt>long double</tt> size</li></ul>
/// Specified sizes cannot be equal to zero and are defaulted to
/// one. Futhermore, the IEEE-754 compatibility corresponds to
/// correct byte size, IEC-559 compatibility, denormalization,
/// correct radix and correct number of mantissa digits.
class DataModel final
{
// Lifecycle
/// \name Lifecycle
//@{
public:
explicit inline DataModel(const unsigned long long int source = 0);
explicit inline DataModel(const bool big, const bool twos, const bool fieee754, const bool dieee754, const bool ldieee754, const unsigned int psize, const unsigned int bsize, const unsigned int csize, const unsigned int sisize, const unsigned int isize, const unsigned int lisize, const unsigned int llisize, const unsigned int fsize, const unsigned int dsize, const unsigned int ldsize);
//@}
// Operators
/// \name Operators
//@{
public:
inline unsigned long long int operator()();
inline bool operator==(const DataModel& rhs);
inline bool operator!=(const DataModel& rhs);
//@}
// Assignment
/// \name Assignment
//@{
public:
inline DataModel& assign(const DataModel& source);
inline DataModel& assign(const unsigned long long int source = 0);
inline DataModel& assign(const bool big, const bool twos, const bool fieee754, const bool dieee754, const bool ldieee754, const unsigned int psize, const unsigned int bsize, const unsigned int csize, const unsigned int sisize, const unsigned int isize, const unsigned int lisize, const unsigned int llisize, const unsigned int fsize, const unsigned int dsize, const unsigned int ldsize);
//@}
// Management
/// \name Management
//@{
public:
inline unsigned int size() const;
inline const unsigned long long int& data() const;
inline DataModel& clear();
inline DataModel copy() const;
template <typename Type = DataModel> inline Type cast() const;
inline bool check();
//@}
// Getters
/// \name Getters
//@{
public:
inline unsigned long long int get() const;
inline bool endianness() const;
inline bool complement() const;
template <typename Type, class = typename std::enable_if<(!std::is_pointer<Type>::value) && (std::is_floating_point<typename std::decay<Type>::type>::value)>::type> inline bool ieee754() const;
template <typename Type, class = typename std::enable_if<(std::is_pointer<Type>::value) || (std::is_integral<typename std::decay<Type>::type>::value) || (std::is_floating_point<typename std::decay<Type>::type>::value)>::type> inline unsigned int size() const;
//@}
// Setters
/// \name Setters
//@{
public:
inline DataModel& set(const bool big, const bool twos, const bool fieee754, const bool dieee754, const bool ldieee754, const unsigned int psize, const unsigned int bsize, const unsigned int csize, const unsigned int sisize, const unsigned int isize, const unsigned int lisize, const unsigned int llisize, const unsigned int fsize, const unsigned int dsize, const unsigned int ldsize);
inline DataModel& endianness(const bool value);
inline DataModel& complement(const bool value);
template <typename Type, class = typename std::enable_if<(!std::is_pointer<Type>::value) && (std::is_floating_point<typename std::decay<Type>::type>::value)>::type> inline DataModel& ieee754(const bool value);
template <typename Type, class = typename std::enable_if<(std::is_pointer<Type>::value) || (std::is_integral<typename std::decay<Type>::type>::value) || (std::is_floating_point<typename std::decay<Type>::type>::value)>::type> inline DataModel& size(const unsigned int value);
//@}
// Stream
/// \name Stream
//@{
public:
friend std::ostream& operator<<(std::ostream& lhs, const DataModel& rhs);
//@}
// Helpers
/// \name Helpers
//@{
public:
template <typename Type, typename Decayed = typename std::decay<Type>::type, typename Signed = typename std::make_signed<typename std::conditional<(std::is_integral<Decayed>::value) && (!std::is_same<Decayed, bool>::value), Decayed, int>::type>::type, typename Fundamental = typename std::conditional<std::is_pointer<Type>::value, void*, typename std::conditional<(std::is_integral<Decayed>::value) && (!std::is_same<Decayed, bool>::value), typename std::conditional<std::is_same<Signed, signed char>::value, char, Signed>::type, Decayed>::type>::type, class = typename std::enable_if<(std::is_pointer<Fundamental>::value) || (std::is_integral<Fundamental>::value) || (std::is_floating_point<Fundamental>::value)>::type> static constexpr Fundamental fundamental();
template <typename Type, class = typename std::enable_if<(!std::is_pointer<Type>::value) && (std::is_floating_point<typename std::decay<Type>::type>::value)>::type> static constexpr bool control754();
static constexpr bool control();
//@}
// Predefined
/// \name Predefined
//@{
public:
static inline const DataModel& system();
//@}
// Test
/// \name Test
//@{
public:
static int example();
//@}
// Data members
/// \name Data members
//@{
protected:
unsigned long long int _code; ///< Internal encoding of data types.
//@}
};
// -------------------------------------------------------------------------- //
// ------------------------------- LIFECYCLE -------------------------------- //
// Explicit value constructor
/// \brief Explicit value constructor.
/// \details Explicitely constructs the data model from an <tt>unsigned
/// long long int</tt> code.
/// \param[in] source Code to be used for construction.
inline DataModel::DataModel(const unsigned long long int source)
: _code(source)
{
;
}
// Explicit detailed constructor
/// \brief Explicit detailed constructor.
/// \details Explicitely constructs the data model using all the needed
/// values.
/// \param[in] big False for little-endian, true for big-endian.
/// \param[in] twos True for two's complement, false otherwise.
/// \param[in] fieee754 IEEE-754 <tt>binary32</tt> compatibility of
/// <tt>float</tt>.
/// \param[in] dieee754 IEEE-754 <tt>binary64</tt> compatibility of
/// <tt>double</tt>.
/// \param[in] ldieee754 IEEE-754 <tt>binary128</tt> compatibility of
/// <tt>long double</tt>.
/// \param[in] psize Byte size of pointers.
/// \param[in] bsize Byte size of <tt>bool</tt>.
/// \param[in] csize Byte size of <tt>char</tt>.
/// \param[in] sisize Byte size of <tt>short int</tt>.
/// \param[in] isize Byte size of <tt>int</tt>.
/// \param[in] lisize Byte size of <tt>long int</tt>.
/// \param[in] llisize Byte size of <tt>long long int</tt>.
/// \param[in] fsize Byte size of <tt>float</tt>.
/// \param[in] dsize Byte size of <tt>double</tt>.
/// \param[in] ldsize Byte size of <tt>long double</tt>.
inline DataModel::DataModel(const bool big, const bool twos, const bool fieee754, const bool dieee754, const bool ldieee754, const unsigned int psize, const unsigned int bsize, const unsigned int csize, const unsigned int sisize, const unsigned int isize, const unsigned int lisize, const unsigned int llisize, const unsigned int fsize, const unsigned int dsize, const unsigned int ldsize)
: _code(0)
{
set(big, twos, fieee754, dieee754, ldieee754, psize, bsize, csize, sisize, isize, lisize, llisize, fsize, dsize, ldsize);
}
// -------------------------------------------------------------------------- //
// -------------------------------- OPERATORS ------------------------------- //
// Access operator
/// \brief Access operator.
/// \details Returns a copy of the underlying complete code of the data
/// model.
/// \return Copy of the code.
inline unsigned long long int DataModel::operator()()
{
return _code;
}
// Equal to comparison
/// \brief Equal to comparison.
/// \details Compares two data models for equality.
/// \return True if the two data models are equal, false otherwise.
inline bool DataModel::operator==(const DataModel& rhs)
{
return _code == rhs._code;
}
// Not equal to comparison
/// \brief Not equal to comparison.
/// \details Compares two data models for difference.
/// \return True if the two data models are not equal, false otherwise.
inline bool DataModel::operator!=(const DataModel& rhs)
{
return _code != rhs._code;
}
// -------------------------------------------------------------------------- //
// ------------------------------- ASSIGNMENT ------------------------------- //
// Copy assignment
/// \brief Copy assignment.
/// \details Assign the code from another data model.
/// \param[in] source Source of the copy.
/// \return Self reference.
inline DataModel& DataModel::assign(const DataModel& source)
{
_code = source._code;
return *this;
}
// Value assignment
/// \brief Value assignment.
/// \details Assigns a code to the data model.
/// \param[in] source Source of the copy.
/// \return Self reference.
inline DataModel& DataModel::assign(const unsigned long long int source)
{
_code = source;
return *this;
}
// Detailed assignment
/// \brief Detailed assignment.
/// \details Assigns the contents of the data model using all the needed
/// values.
/// \param[in] big False for little-endian, true for big-endian.
/// \param[in] twos True for two's complement, false otherwise.
/// \param[in] fieee754 IEEE-754 <tt>binary32</tt> compatibility of
/// <tt>float</tt>.
/// \param[in] dieee754 IEEE-754 <tt>binary64</tt> compatibility of
/// <tt>double</tt>.
/// \param[in] ldieee754 IEEE-754 <tt>binary128</tt> compatibility of
/// <tt>long double</tt>.
/// \param[in] psize Byte size of pointers.
/// \param[in] bsize Byte size of <tt>bool</tt>.
/// \param[in] csize Byte size of <tt>char</tt>.
/// \param[in] sisize Byte size of <tt>short int</tt>.
/// \param[in] isize Byte size of <tt>int</tt>.
/// \param[in] lisize Byte size of <tt>long int</tt>.
/// \param[in] llisize Byte size of <tt>long long int</tt>.
/// \param[in] fsize Byte size of <tt>float</tt>.
/// \param[in] dsize Byte size of <tt>double</tt>.
/// \param[in] ldsize Byte size of <tt>long double</tt>.
/// \return Self reference.
inline DataModel& DataModel::assign(const bool big, const bool twos, const bool fieee754, const bool dieee754, const bool ldieee754, const unsigned int psize, const unsigned int bsize, const unsigned int csize, const unsigned int sisize, const unsigned int isize, const unsigned int lisize, const unsigned int llisize, const unsigned int fsize, const unsigned int dsize, const unsigned int ldsize)
{
return set(big, twos, fieee754, dieee754, ldieee754, psize, bsize, csize, sisize, isize, lisize, llisize, fsize, dsize, ldsize);
}
// -------------------------------------------------------------------------- //
// ------------------------------- MANAGEMENT ------------------------------- //
// Get the size of the code
/// \brief Get the size of the code.
/// \details Returns the result of the <tt>sizeof</tt> operator on the
/// underlying code.
/// \return Size of the code in bytes.
inline unsigned int DataModel::size() const
{
return sizeof(_code);
}
// Access data
/// \brief Access data.
/// \details Returns a constant reference to the internal underlying data
/// which is the data model code.
/// \return Immutable reference to the code.
inline const unsigned long long int& DataModel::data() const
{
return _code;
}
// Clear code
/// \brief Clear code.
/// \details Clears the whole contents and sets the flags to zero, and
/// the sizes to one.
/// \return Self reference.
inline DataModel& DataModel::clear()
{
_code = 0;
return *this;
}
// Copy
/// \brief Copy.
/// \details Returns a copy of the data model.
/// \return Copy.
inline DataModel DataModel::copy() const
{
return *this;
}
// Cast
/// \brief Cast.
/// \details Returns a copy of the data model casted to the provided
/// type.
/// \tparam Type Data type.
/// \return Casted copy.
template <typename Type>
inline Type DataModel::cast() const
{
return Type(_code);
}
// Check if standard
/// \brief Check if standard.
/// \details Checks whether the data model is a standard one. It means
/// that it has all the following properties : <ul>
/// <li>it uses two's complement</li>
/// <li><tt>float</tt> and <tt>double</tt> are IEEE-754
/// compliant</li>
/// <li>pointer size is 4 or 8</li>
/// <li><tt>bool</tt> size is 1</li>
/// <li><tt>char</tt> size is 1</li>
/// <li><tt>short int</tt> size is 2</li>
/// <li><tt>int</tt> size is 4</li>
/// <li><tt>long int</tt> size is 4 or 8</li>
/// <li><tt>long long int</tt> size is 8</li>
/// <li><tt>float</tt> size is 4</li>
/// <li><tt>double</tt> size is 8</li>
/// <li><tt>long double</tt> size is 8, 10, 12 or 16</li></ul>
/// \return True if the data model is standard, false if not.
inline bool DataModel::check()
{
return ((complement()) && (ieee754<float>()) && (ieee754<double>()) && ((size<void*>() == 4) || (size<void*>() == 8)) && (size<bool>() == 1) && (size<char>() == 1) && (size<short int>() == 2) && (size<int>() == 4) && ((size<long int>() == 4) || (size<long int>() == 8)) && (size<long long int>() == 8) && (size<float>() == 4) && (size<double>() == 8) && ((size<long double>() == 8) || (size<long double>() == 10) || (size<long double>() == 12) || (size<long double>() == 16)));
}
// -------------------------------------------------------------------------- //
// --------------------------------- GETTERS -------------------------------- //
// Global getter
/// \brief Global getter.
/// \details Returns a copy of the underlying complete code of the data
/// model.
/// \return Copy of the code.
inline unsigned long long int DataModel::get() const
{
return _code;
}
// Get endianness
/// \brief Get endianness.
/// \details Returns the endianness from data model.
/// \return False for little-endian, true for big-endian.
inline bool DataModel::endianness() const
{
return (((*(reinterpret_cast<const unsigned char*>(&_code)+0))>>0)&1);
}
// Get complement
/// \brief Get complement.
/// \details Returns whether the system use two's complement encoding or
/// not according to the data model.
/// \return True for two's complement, false otherwise.
inline bool DataModel::complement() const
{
return (((*(reinterpret_cast<const unsigned char*>(&_code)+0))>>1)&1);
}
// Get IEEE-754 compatibility
/// \brief Get IEEE-754 compatibility.
/// \details Returns whether the specified floating-point type is
/// compliant to the IEEE-754 standard according to the
/// data model.
/// \tparam Type Floating-point type.
/// \return True if compliant, false otherwise.
template <typename Type, class>
inline bool DataModel::ieee754() const
{
return ((std::is_same<decltype(fundamental<Type>()), float>::value) ? (((*(reinterpret_cast<const unsigned char*>(&_code)+1))>>0)&1)
: ((std::is_same<decltype(fundamental<Type>()), double>::value) ? (((*(reinterpret_cast<const unsigned char*>(&_code)+1))>>1)&1)
: ((std::is_same<decltype(fundamental<Type>()), long double>::value) ? (((*(reinterpret_cast<const unsigned char*>(&_code)+1))>>2)&1)
: (0))));
}
// Get type size
/// \brief Get type size.
/// \details Returns the size of the provided fundamental type according
/// to the data model.
/// \tparam Type Pointer, integral of floating-point type.
/// \return Type size in bytes.
template <typename Type, class>
inline unsigned int DataModel::size() const
{
return ((std::is_same<decltype(fundamental<Type>()), void*>::value) ? ((((*(reinterpret_cast<const unsigned char*>(&_code)+2))>>0)&((1<<4)-1))+1)
: ((std::is_same<decltype(fundamental<Type>()), bool>::value) ? ((((*(reinterpret_cast<const unsigned char*>(&_code)+2))>>4)&((1<<4)-1))+1)
: ((std::is_same<decltype(fundamental<Type>()), char>::value) ? ((((*(reinterpret_cast<const unsigned char*>(&_code)+3))>>0)&((1<<4)-1))+1)
: ((std::is_same<decltype(fundamental<Type>()), short int>::value) ? ((((*(reinterpret_cast<const unsigned char*>(&_code)+3))>>4)&((1<<4)-1))+1)
: ((std::is_same<decltype(fundamental<Type>()), int>::value) ? ((((*(reinterpret_cast<const unsigned char*>(&_code)+4))>>0)&((1<<4)-1))+1)
: ((std::is_same<decltype(fundamental<Type>()), long int>::value) ? ((((*(reinterpret_cast<const unsigned char*>(&_code)+4))>>4)&((1<<4)-1))+1)
: ((std::is_same<decltype(fundamental<Type>()), long long int>::value) ? ((((*(reinterpret_cast<const unsigned char*>(&_code)+5))>>0)&((1<<4)-1))+1)
: ((std::is_same<decltype(fundamental<Type>()), float>::value) ? ((((*(reinterpret_cast<const unsigned char*>(&_code)+6))>>0)&((1<<4)-1))+1)
: ((std::is_same<decltype(fundamental<Type>()), double>::value) ? ((((*(reinterpret_cast<const unsigned char*>(&_code)+6))>>4)&((1<<4)-1))+1)
: ((std::is_same<decltype(fundamental<Type>()), long double>::value) ? ((((*(reinterpret_cast<const unsigned char*>(&_code)+7))>>0)&((1<<4)-1))+1)
: (0)))))))))));
}
// -------------------------------------------------------------------------- //
// --------------------------------- SETTERS -------------------------------- //
// Global setter
/// \brief Global setter.
/// \details Sets the content using all the needed values.
/// \param[in] big False for little-endian, true for big-endian.
/// \param[in] twos True for two's complement, false otherwise.
/// \param[in] fieee754 IEEE-754 <tt>binary32</tt> compatibility of
/// <tt>float</tt>.
/// \param[in] dieee754 IEEE-754 <tt>binary64</tt> compatibility of
/// <tt>double</tt>.
/// \param[in] ldieee754 IEEE-754 <tt>binary128</tt> compatibility of
/// <tt>long double</tt>.
/// \param[in] psize Byte size of pointers.
/// \param[in] bsize Byte size of <tt>bool</tt>.
/// \param[in] csize Byte size of <tt>char</tt>.
/// \param[in] sisize Byte size of <tt>short int</tt>.
/// \param[in] isize Byte size of <tt>int</tt>.
/// \param[in] lisize Byte size of <tt>long int</tt>.
/// \param[in] llisize Byte size of <tt>long long int</tt>.
/// \param[in] fsize Byte size of <tt>float</tt>.
/// \param[in] dsize Byte size of <tt>double</tt>.
/// \param[in] ldsize Byte size of <tt>long double</tt>.
/// \return Self reference.
inline DataModel& DataModel::set(const bool big, const bool twos, const bool fieee754, const bool dieee754, const bool ldieee754, const unsigned int psize, const unsigned int bsize, const unsigned int csize, const unsigned int sisize, const unsigned int isize, const unsigned int lisize, const unsigned int llisize, const unsigned int fsize, const unsigned int dsize, const unsigned int ldsize)
{
return endianness(big).complement(twos).ieee754<float>(fieee754).ieee754<double>(dieee754).ieee754<long double>(ldieee754).size<void*>(psize).size<bool>(bsize).size<char>(csize).size<short int>(sisize).size<int>(isize).size<long int>(lisize).size<long long int>(llisize).size<float>(fsize).size<double>(dsize).size<long double>(ldsize);
}
// Set endianness
/// \brief Set endianness.
/// \details Sets the endianness of the data model.
/// \param[in] value False for little-endian, true for big-endian.
/// \return Self reference.
inline DataModel& DataModel::endianness(const bool value)
{
((*(reinterpret_cast<unsigned char*>(&_code)+0) &= ~(1<<0)) |= static_cast<unsigned char>(value)<<0);
return *this;
}
// Set complement
/// \brief Set complement.
/// \details Sets the complement of the data model.
/// \param[in] value True for two's complement, false otherwise.
/// \return Self reference.
inline DataModel& DataModel::complement(const bool value)
{
((*(reinterpret_cast<unsigned char*>(&_code)+0) &= ~(1<<1)) |= static_cast<unsigned char>(value)<<1);
return *this;
}
// Set IEEE-754 compatibility
/// \brief Set IEEE-754 compatibility.
/// \details Sets whether the specified floating-point type is
/// compliant to the IEEE-754 standard.
/// \tparam Type Floating-point type.
/// \param[in] value True if compliant, false otherwise.
/// \return Self reference.
template <typename Type, class>
inline DataModel& DataModel::ieee754(const bool value)
{
(void)((std::is_same<decltype(fundamental<Type>()), float>::value) ? ((*(reinterpret_cast<unsigned char*>(&_code)+1) &= ~(1<<0)) |= static_cast<unsigned char>(value)<<0)
: ((std::is_same<decltype(fundamental<Type>()), double>::value) ? ((*(reinterpret_cast<unsigned char*>(&_code)+1) &= ~(1<<1)) |= static_cast<unsigned char>(value)<<1)
: ((std::is_same<decltype(fundamental<Type>()), long double>::value) ? ((*(reinterpret_cast<unsigned char*>(&_code)+1) &= ~(1<<2)) |= static_cast<unsigned char>(value)<<2)
: (0))));
return *this;
}
// Set type size
/// \brief Set type size.
/// \details Sets the size of the provided fundamental type of the data
/// model.
/// \tparam Type Pointer, integral of floating-point type.
/// \param[in] value Type size in bytes.
/// \return Self reference.
template <typename Type, class>
inline DataModel& DataModel::size(const unsigned int value)
{
(void)((std::is_same<decltype(fundamental<Type>()), void*>::value) ? ((*(reinterpret_cast<unsigned char*>(&_code)+2) &= ~(((1<<4)-1)<<0)) |= static_cast<unsigned char>(value-(value > 0))<<0)
: ((std::is_same<decltype(fundamental<Type>()), bool>::value) ? ((*(reinterpret_cast<unsigned char*>(&_code)+2) &= ~(((1<<4)-1)<<4)) |= static_cast<unsigned char>(value-(value > 0))<<4)
: ((std::is_same<decltype(fundamental<Type>()), char>::value) ? ((*(reinterpret_cast<unsigned char*>(&_code)+3) &= ~(((1<<4)-1)<<0)) |= static_cast<unsigned char>(value-(value > 0))<<0)
: ((std::is_same<decltype(fundamental<Type>()), short int>::value) ? ((*(reinterpret_cast<unsigned char*>(&_code)+3) &= ~(((1<<4)-1)<<4)) |= static_cast<unsigned char>(value-(value > 0))<<4)
: ((std::is_same<decltype(fundamental<Type>()), int>::value) ? ((*(reinterpret_cast<unsigned char*>(&_code)+4) &= ~(((1<<4)-1)<<0)) |= static_cast<unsigned char>(value-(value > 0))<<0)
: ((std::is_same<decltype(fundamental<Type>()), long int>::value) ? ((*(reinterpret_cast<unsigned char*>(&_code)+4) &= ~(((1<<4)-1)<<4)) |= static_cast<unsigned char>(value-(value > 0))<<4)
: ((std::is_same<decltype(fundamental<Type>()), long long int>::value) ? ((*(reinterpret_cast<unsigned char*>(&_code)+5) &= ~(((1<<4)-1)<<0)) |= static_cast<unsigned char>(value-(value > 0))<<0)
: ((std::is_same<decltype(fundamental<Type>()), float>::value) ? ((*(reinterpret_cast<unsigned char*>(&_code)+6) &= ~(((1<<4)-1)<<0)) |= static_cast<unsigned char>(value-(value > 0))<<0)
: ((std::is_same<decltype(fundamental<Type>()), double>::value) ? ((*(reinterpret_cast<unsigned char*>(&_code)+6) &= ~(((1<<4)-1)<<4)) |= static_cast<unsigned char>(value-(value > 0))<<4)
: ((std::is_same<decltype(fundamental<Type>()), long double>::value) ? ((*(reinterpret_cast<unsigned char*>(&_code)+7) &= ~(((1<<4)-1)<<0)) |= static_cast<unsigned char>(value-(value > 0))<<0)
: (0)))))))))));
return *this;
}
// -------------------------------------------------------------------------- //
// --------------------------------- STREAM --------------------------------- //
// Output stream operator
/// \brief Output stream operator.
/// \details Prints out the data model.
/// \param[in,out] lhs Left-hand side stream.
/// \param[in] rhs Right-hand side data model.
/// \return Output stream.
std::ostream& operator<<(std::ostream& lhs, const DataModel& rhs)
{
const char separator = lhs.fill();
return lhs<<rhs.endianness()<<separator<<rhs.complement()<<separator<<rhs.ieee754<float>()<<separator<<rhs.ieee754<double>()<<separator<<rhs.ieee754<long double>()<<separator<<rhs.size<void*>()<<separator<<rhs.size<bool>()<<separator<<rhs.size<char>()<<separator<<rhs.size<short int>()<<separator<<rhs.size<int>()<<separator<<rhs.size<long int>()<<separator<<rhs.size<long long int>()<<separator<<rhs.size<float>()<<separator<<rhs.size<double>()<<separator<<rhs.size<long double>();
}
// -------------------------------------------------------------------------- //
// --------------------------------- HELPERS -------------------------------- //
// Get the associated fundamental type
/// \brief Get the associated fundamental type.
/// \details Converts the type passed as first template argument to an
/// associated fundamental type : <ul>
/// <li><tt>void*</tt> if the type is a pointer</li>
/// <li><tt>bool</tt> if the type is a cv-qualified boolean</li>
/// <li><tt>char</tt> if the type is a cv-qualified plain,
/// signed or unsigned character</li>
/// <li>signed decayed type if the type is an integral type</li>
/// <li>decayed type if the type is a floating-point type</li>
/// </ul>.
/// \tparam Type Type to convert.
/// \tparam Decayed (Decayed version of the type.)
/// \tparam Signed (Signed version of the type.)
/// \tparam Fundamental (Fundamental version of the type.)
/// \return Default value of the fundamental type.
template <typename Type, typename Decayed, typename Signed, typename Fundamental, class>
constexpr Fundamental DataModel::fundamental()
{
return Fundamental();
}
// Control IEEE-754 system compatibility
/// \brief Control IEEE-754 system compatibility.
/// \details Control whether the floating-point type is compatible with
/// the IEEE-754 standard on the current architecture : correct
/// byte size, IEC-559 compatibility, denormalization, correct
/// radix and correct number of mantissa digits.
/// \tparam Type Floating-point type.
/// \return True if the type is compliant to IEEE-754, false otherwise.
template <typename Type, class>
constexpr bool DataModel::control754()
{
return (std::numeric_limits<Type>::is_iec559) && (std::numeric_limits<Type>::has_denorm) && (std::numeric_limits<Type>::radix == 2) && (((std::is_same<Type, float>::value) && (sizeof(Type) == 4) && (std::numeric_limits<Type>::digits == 24)) || ((std::is_same<Type, double>::value) && (sizeof(Type) == 8) && (std::numeric_limits<Type>::digits == 53)) || ((std::is_same<Type, long double>::value) && (sizeof(Type) == 16) && (std::numeric_limits<Type>::digits == 113)));
}
// Control if standard
/// \brief Control if standard.
/// \details Controls whether the system data model is a standard one.
/// It means that it has all the following properties : <ul>
/// <li>it uses two's complement</li>
/// <li><tt>float</tt> and <tt>double</tt> are IEEE-754
/// compliant</li>
/// <li><tt>long double</tt> is IEC-559 compliant, can be
/// denormalized and has a binary radix</li>
/// <li>pointer size is 4 or 8</li>
/// <li><tt>bool</tt> size is 1</li>
/// <li><tt>char</tt> size is 1</li>
/// <li><tt>short int</tt> size is 2</li>
/// <li><tt>int</tt> size is 4</li>
/// <li><tt>long int</tt> size is 4 or 8</li>
/// <li><tt>long long int</tt> size is 8</li>
/// <li><tt>float</tt> size is 4</li>
/// <li><tt>double</tt> size is 8</li>
/// <li><tt>long double</tt> size is 8, 10, 12 or 16</li></ul>
/// \return True if the data model is standard, false if not.
constexpr bool DataModel::control()
{
return (-1 == ~0) && ((control754<float>()) && (control754<double>()) && ((std::numeric_limits<long double>::is_iec559) && (std::numeric_limits<long double>::has_denorm) && (std::numeric_limits<long double>::radix == 2))) && ((sizeof(void*) == 4) || (sizeof(void*) == 8)) && (sizeof(bool) == 1) && (sizeof(char) == 1) && (sizeof(short int) == 2) && (sizeof(int) == 4) && ((sizeof(long int) == 4) || (sizeof(long int) == 8)) && (sizeof(long long int) == 8) && (sizeof(float) == 4) && (sizeof(double) == 8) && ((sizeof(long double) == 8) || (sizeof(long double) == 10) || (sizeof(long double) == 12) || (sizeof(long double) == 16));
}
// -------------------------------------------------------------------------- //
// ------------------------------- PREDEFINED ------------------------------- //
// System data model
/// \brief System data model.
/// \details Returns an immutable reference to singleton representing the
/// data model of the current architecture.
/// \return Immutable reference to system data model singleton.
inline const DataModel& DataModel::system()
{
static const union {uint32_t i; char c[4];} x = {0x0000FEFF};
static const DataModel singleton(!(x.c[0]), -1 == ~0, control754<float>(), control754<double>(), control754<long double>(), sizeof(void*), sizeof(bool), sizeof(char), sizeof(short int), sizeof(int), sizeof(long int), sizeof(long long int), sizeof(float), sizeof(double), sizeof(long double));
return singleton;
}
// -------------------------------------------------------------------------- //
// ---------------------------------- TEST ---------------------------------- //
// Example function
/// \brief Example function.
/// \details Tests and demonstrates the use of DataModel.
/// \return 0 if no error.
int DataModel::example()
{
// Initialize
std::cout<<"BEGIN = DataModel::example()"<<std::endl;
std::cout<<std::boolalpha<<std::left;
static const unsigned int width = 40;
// Construction
DataModel model;
// Lifecycle
std::cout<<std::endl;
std::cout<<std::setw(width*2)<<"Lifecycle : " <<std::endl;
std::cout<<std::setw(width*2)<<"DataModel() : " <<DataModel()<<std::endl;
std::cout<<std::setw(width*2)<<"DataModel(0) : " <<DataModel(0)<<std::endl;
std::cout<<std::setw(width*2)<<"DataModel(0, 1, 1, 1, 0, 8, 1, 1, 2, 4, 4, 8, 4, 8, 16) : " <<DataModel(0, 1, 1, 1, 0, 8, 1, 1, 2, 4, 4, 8, 4, 8, 16)<<std::endl;
std::cout<<std::setw(width*2)<<"DataModel(model) : " <<DataModel(model)<<std::endl;
// Operators
std::cout<<std::endl;
std::cout<<std::setw(width)<<"Operators : " <<std::endl;
std::cout<<std::setw(width)<<"model() : " <<model()<<std::endl;
std::cout<<std::setw(width)<<"model == d.system() : " <<(model == model.system())<<std::endl;
std::cout<<std::setw(width)<<"model != d.system() : " <<(model != model.system())<<std::endl;
std::cout<<std::setw(width)<<"(model = model.system()) : " <<(model = model.system())<<std::endl;
// Assignment
std::cout<<std::endl;
std::cout<<std::setw(width*2)<<"Assignment : " <<std::endl;
std::cout<<std::setw(width*2)<<"model.assign(0) : " <<model.assign(0)<<std::endl;
std::cout<<std::setw(width*2)<<"model.assign(model.system()) : " <<model.assign(model.system())<<std::endl;
std::cout<<std::setw(width*2)<<"model.assign(0, 1, 1, 1, 0, 8, 1, 1, 2, 4, 4, 8, 4, 8, 16) : " <<model.assign(0, 1, 1, 1, 0, 8, 1, 1, 2, 4, 4, 8, 4, 8, 16)<<std::endl;
// Management
std::cout<<std::endl;
std::cout<<std::setw(width)<<"Management : " <<std::endl;
std::cout<<std::setw(width)<<"model.size() : " <<model.size()<<std::endl;
std::cout<<std::setw(width)<<"model.data() : " <<model.data()<<std::endl;
std::cout<<std::setw(width)<<"model.clear() : " <<model.clear()<<std::endl;
std::cout<<std::setw(width)<<"model.copy() : " <<model.copy()<<std::endl;
std::cout<<std::setw(width)<<"model.cast() : " <<model.cast()<<std::endl;
std::cout<<std::setw(width)<<"model.check() : " <<model.check()<<std::endl;
// Getters
std::cout<<std::endl;
std::cout<<std::setw(width)<<"Getters : " <<std::endl;
std::cout<<std::setw(width)<<"model.get() : " <<model.get()<<std::endl;
std::cout<<std::setw(width)<<"model.endianness() : " <<model.endianness()<<std::endl;
std::cout<<std::setw(width)<<"model.complement() : " <<model.complement()<<std::endl;
std::cout<<std::setw(width)<<"model.ieee754<float>() : " <<model.ieee754<float>()<<std::endl;
std::cout<<std::setw(width)<<"model.size<long double>() : " <<model.size<long double>()<<std::endl;
// Setters
std::cout<<std::endl;
std::cout<<std::setw(width*2)<<"Setters : " <<std::endl;
std::cout<<std::setw(width*2)<<"model.set(0, 1, 1, 1, 0, 8, 1, 1, 2, 4, 4, 8, 4, 8, 16) : " <<model.set(0, 1, 1, 1, 0, 8, 1, 1, 2, 4, 4, 8, 4, 8, 16)<<std::endl;
std::cout<<std::setw(width*2)<<"model.endianness(true) : " <<model.endianness(true)<<std::endl;
std::cout<<std::setw(width*2)<<"model.complement(false) : " <<model.complement(false)<<std::endl;
std::cout<<std::setw(width*2)<<"model.ieee754<float>(false) : " <<model.ieee754<float>(false)<<std::endl;
std::cout<<std::setw(width*2)<<"model.size<long double>(10) : " <<model.size<long double>(10)<<std::endl;
// Stream
std::cout<<std::endl;
std::cout<<std::setw(width)<<"Stream : " <<std::endl;
std::cout<<std::setw(width)<<"operator<<(std::cout, model) : " <<model<<std::endl;
// Helpers
std::cout<<std::endl;
std::cout<<std::setw(width*2)<<"Helpers : " <<std::endl;
std::cout<<std::setw(width*2)<<"model.fundamental<volatile signed int>() :" <<model.fundamental<volatile signed int>()<<std::endl;
std::cout<<std::setw(width*2)<<"model.control754<float>() : " <<model.control754<float>()<<std::endl;
std::cout<<std::setw(width*2)<<"model.control754<double>() : " <<model.control754<double>()<<std::endl;
std::cout<<std::setw(width*2)<<"model.control754<long double>() : " <<model.control754<long double>()<<std::endl;
std::cout<<std::setw(width*2)<<"model.control() : " <<model.control()<<std::endl;
// Predefined
std::cout<<std::endl;
std::cout<<std::setw(width)<<"Predefined : " <<std::endl;
std::cout<<std::setw(width)<<"model.system() : " <<model.system()<<std::endl;
// Finalize
std::cout<<std::noboolalpha<<std::right<<std::endl;
std::cout<<"END = DataModel::example()"<<std::endl;
return 0;
}
// -------------------------------------------------------------------------- //
/*////////////////////////////////////////////////////////////////////////////*/
} // namespace
#endif // DATAMODEL_H_INCLUDED
/*////////////////////////////////////////////////////////////////////////////*/
| 55.781843 | 772 | 0.542935 | [
"model"
] |
fa0a55b5667d132afc8988d2956d6aa73b2b3ba8 | 4,208 | h | C | ios/MobileRTC.framework/Headers/MobileRTCMeetingService+Customize.h | damphat/flutter_zoom_plugin | b93077b9094b9ac1c174c33ca65ba4a0ce259777 | [
"Apache-2.0"
] | 2 | 2020-11-23T20:08:10.000Z | 2020-11-23T20:08:14.000Z | ios/MobileRTC.framework/Headers/MobileRTCMeetingService+Customize.h | Awesome-T/flutter_zoom_plugin | 88d1fa2685f28d67410d46e094461a0a030d3192 | [
"Apache-2.0"
] | 1 | 2021-06-23T12:15:28.000Z | 2021-06-23T12:15:28.000Z | ios/MobileRTC.framework/Headers/MobileRTCMeetingService+Customize.h | Awesome-T/flutter_zoom_plugin | 88d1fa2685f28d67410d46e094461a0a030d3192 | [
"Apache-2.0"
] | 3 | 2020-11-04T08:50:24.000Z | 2020-11-06T04:48:34.000Z | //
// MobileRTCMeetingService+Customize.h
// MobileRTC
//
// Created by Robust Hu on 2017/2/27.
// Copyright © 2019年 Zoom Video Communications, Inc. All rights reserved.
//
#import <MobileRTC/MobileRTC.h>
#import <MobileRTC/MobileRTCRoomDevice.h>
#import <MobileRTC/MobileRTCCallCountryCode.h>
/*!
@brief Provide interfaces for outgoing calls and Call Room Device.
*/
@interface MobileRTCMeetingService (Customize)
/*!
@brief Set to customize the meeting title/topic which will be displayed in the meeting bar.
@param title The topic/title of the meeting.
@warning User should call the method before starting or joining the meeting if he wants to reset the title/topic of the meeting.
*/
- (void)customizeMeetingTitle:(NSString * _Nullable)title;
/*!
@brief Query if user can dial out in the meeting.
@return YES means able, No disable.
*/
- (BOOL)isDialOutSupported;
/*!
@brief Query if there is any outgoing call in process.
@return YES means that there is outgoing call in process.
*/
- (BOOL)isDialOutInProgress;
/*!
@brief Start to dial out.
@param phone The phone number of destination, you should add the country code in front of the phone number, such as +86123456789.
@param me YES means Call Me; NO means inviting others by Phone.
@param username The name of the user to be called.
@return YES means the method is called successfully, otherwise not.
*/
- (BOOL)dialOut:(nonnull NSString*)phone isCallMe:(BOOL)me withName:(nullable NSString*)username;
/*!
@brief Cancel to dial out.
@param isCallMe YES means Call Me; NO means inviting others by Phone.
@return YES means the method is called successfully, otherwise not.
*/
- (BOOL)cancelDialOut:(BOOL)isCallMe;
/*!
@brief Query if it is able to Call Room device(H.323).
@return YES means able, otherwise not.
*/
- (BOOL)isCallRoomDeviceSupported;
/*!
@brief Query if it is in process to call room device.
@return YES means calling room device in process, otherwise not.
*/
- (BOOL)isCallingRoomDevice;
/*!
@brief Cancel to call room device.
@return YES means the method is called successfully, otherwise not.
*/
- (BOOL)cancelCallRoomDevice;
/*!
@brief Get an array of IP Addresses of room device which is used for calling.
@return The array of IP Address; if there is no existed IP Address, it will return nil.
*/
- (nullable NSArray*)getIPAddressList;
/*!
@brief Get the password of the meeting running on H.323 device.
@return The meeting password. If no meeting is running, it will return nil.
*/
- (nullable NSString*)getH323MeetingPassword;
/*!
@brief Get room devices that can be called.
@return The array of room devices. If there is no any room device. it will return nil.
*/
- (nullable NSArray*)getRoomDeviceList;
/*!
@brief Get the pairing code when the room device call in.
@param code The pairing code which enable the device connect to the meeting.
@param meetingNumber The number of meeting.
@return YES means the method is called successfully, otherwise not.
@warning App can invite Room System while App is in Meeting or in pre-Meeting.
*/
- (BOOL)sendPairingCode:(nonnull NSString*)code WithMeetingNumber:(unsigned long long)meetingNumber;
/*!
@brief The user calls out to invite the room device.
@param device The room device.
@return YES means the method is called successfully, otherwise not.
*/
- (BOOL)callRoomDevice:(nonnull MobileRTCRoomDevice*)device;
/*!
@brief Get Participant ID.
@return The Participant ID.
*/
- (NSUInteger)getParticipantID;
/*!
@brief Get countrycode for the current user's locale.
@return The object of MobileRTCCallCountryCode for user's locale.
*/
- (nullable MobileRTCCallCountryCode *)getDialInCurrentCountryCode;
/*!
@brief Get all countrycodes
@return The array of all countrycode.
*/
- (nullable NSArray *)getDialInAllCountryCodes;
/*!
@brief Get to the countrycode specified by countryId
@return The array of countrycode.
*/
- (nullable NSArray *)getDialInCallCodesWithCountryId:(nullable NSString *)countryId;
/*!
@brief Make a phone call to access your voice
@return YES means the method is called successfully, otherwise not.
*/
- (BOOL)dialInCall:(nullable NSString *)countryNumber;
@end
| 30.492754 | 130 | 0.748812 | [
"object"
] |
fa0c61b6ba9aceecd5c3ad751868aa7f066deb94 | 4,543 | c | C | kernels/typing-game/game.c | nju-mips/am-kernels | 9ab41b3e051a49789b458deb0153c9dfe8e93d00 | [
"MIT"
] | 16 | 2020-11-16T12:15:17.000Z | 2022-03-30T13:23:38.000Z | kernels/typing-game/game.c | whysodangerous/am-kernels | fd779050c64b77f324848d5e78b2e0596d084366 | [
"MIT"
] | 1 | 2020-12-18T15:17:35.000Z | 2020-12-19T05:29:44.000Z | kernels/typing-game/game.c | whysodangerous/am-kernels | fd779050c64b77f324848d5e78b2e0596d084366 | [
"MIT"
] | 8 | 2020-11-16T12:15:19.000Z | 2022-03-22T13:12:52.000Z | #include <am.h>
#include <klib.h>
#include <klib-macros.h>
#define FPS 30
#define CPS 5
#define CHAR_W 8
#define CHAR_H 16
#define NCHAR 128
#define COL_WHITE 0xeeeeee
#define COL_RED 0xff0033
#define COL_GREEN 0x00cc33
#define COL_PURPLE 0x2a0a29
enum { WHITE = 0, RED, GREEN, PURPLE };
struct character {
char ch;
int x, y, v, t;
} chars[NCHAR];
int screen_w, screen_h, hit, miss, wrong;
uint32_t texture[3][26][CHAR_W * CHAR_H], blank[CHAR_W * CHAR_H];
int min(int a, int b) {
return (a < b) ? a : b;
}
int randint(int l, int r) {
return l + (rand() & 0x7fffffff) % (r - l + 1);
}
void new_char() {
for (int i = 0; i < LENGTH(chars); i++) {
struct character *c = &chars[i];
if (!c->ch) {
c->ch = 'A' + randint(0, 25);
c->x = randint(0, screen_w - CHAR_W);
c->y = 0;
c->v = (screen_h - CHAR_H + 1) / randint(FPS * 3 / 2, FPS * 2);
c->t = 0;
return;
}
}
}
void game_logic_update(int frame) {
if (frame % (FPS / CPS) == 0) new_char();
for (int i = 0; i < LENGTH(chars); i++) {
struct character *c = &chars[i];
if (c->ch) {
if (c->t > 0) {
if (--c->t == 0) {
c->ch = '\0';
}
} else {
c->y += c->v;
if (c->y < 0) {
c->ch = '\0';
}
if (c->y + CHAR_H >= screen_h) {
miss++;
c->v = 0;
c->y = screen_h - CHAR_H;
c->t = FPS;
}
}
}
}
}
void render() {
static int x[NCHAR], y[NCHAR], n = 0;
for (int i = 0; i < n; i++) {
io_write(AM_GPU_FBDRAW, x[i], y[i], blank, CHAR_W, CHAR_H, false);
}
n = 0;
for (int i = 0; i < LENGTH(chars); i++) {
struct character *c = &chars[i];
if (c->ch) {
x[n] = c->x; y[n] = c->y; n++;
int col = (c->v > 0) ? WHITE : (c->v < 0 ? GREEN : RED);
io_write(AM_GPU_FBDRAW, c->x, c->y, texture[col][c->ch - 'A'], CHAR_W, CHAR_H, false);
}
}
io_write(AM_GPU_FBDRAW, 0, 0, NULL, 0, 0, true);
for (int i = 0; i < 40; i++) putch('\b');
printf("Hit: %d; Miss: %d; Wrong: %d", hit, miss, wrong);
}
void check_hit(char ch) {
int m = -1;
for (int i = 0; i < LENGTH(chars); i++) {
struct character *c = &chars[i];
if (ch == c->ch && c->v > 0 && (m < 0 || c->y > chars[m].y)) {
m = i;
}
}
if (m == -1) {
wrong++;
} else {
hit++;
chars[m].v = -(screen_h - CHAR_H + 1) / (FPS);
}
}
void video_init() {
screen_w = io_read(AM_GPU_CONFIG).width;
screen_h = io_read(AM_GPU_CONFIG).height;
extern char font[];
for (int i = 0; i < CHAR_W * CHAR_H; i++)
blank[i] = COL_PURPLE;
for (int x = 0; x < screen_w; x += CHAR_W)
for (int y = 0; y < screen_h; y += CHAR_H) {
io_write(AM_GPU_FBDRAW, x, y, blank, min(CHAR_W, screen_w - x), min(CHAR_H, screen_h - y), false);
}
for (int ch = 0; ch < 26; ch++) {
char *c = &font[CHAR_H * ch];
for (int i = 0, y = 0; y < CHAR_H; y++)
for (int x = 0; x < CHAR_W; x++, i++) {
int t = (c[y] >> (CHAR_W - x - 1)) & 1;
texture[WHITE][ch][i] = t ? COL_WHITE : COL_PURPLE;
texture[GREEN][ch][i] = t ? COL_GREEN : COL_PURPLE;
texture[RED ][ch][i] = t ? COL_RED : COL_PURPLE;
}
}
}
char lut[256] = {
[AM_KEY_A] = 'A', [AM_KEY_B] = 'B', [AM_KEY_C] = 'C', [AM_KEY_D] = 'D',
[AM_KEY_E] = 'E', [AM_KEY_F] = 'F', [AM_KEY_G] = 'G', [AM_KEY_H] = 'H',
[AM_KEY_I] = 'I', [AM_KEY_J] = 'J', [AM_KEY_K] = 'K', [AM_KEY_L] = 'L',
[AM_KEY_M] = 'M', [AM_KEY_N] = 'N', [AM_KEY_O] = 'O', [AM_KEY_P] = 'P',
[AM_KEY_Q] = 'Q', [AM_KEY_R] = 'R', [AM_KEY_S] = 'S', [AM_KEY_T] = 'T',
[AM_KEY_U] = 'U', [AM_KEY_V] = 'V', [AM_KEY_W] = 'W', [AM_KEY_X] = 'X',
[AM_KEY_Y] = 'Y', [AM_KEY_Z] = 'Z',
};
int main() {
ioe_init();
video_init();
panic_on(!io_read(AM_TIMER_CONFIG).present, "requires timer");
panic_on(!io_read(AM_INPUT_CONFIG).present, "requires keyboard");
printf("Type 'ESC' to exit\n");
int current = 0, rendered = 0;
while (1) {
int frames = io_read(AM_TIMER_UPTIME).us / (1000000 / FPS);
for (; current < frames; current++) {
game_logic_update(current);
}
while (1) {
AM_INPUT_KEYBRD_T ev = io_read(AM_INPUT_KEYBRD);
if (ev.keycode == AM_KEY_NONE) break;
if (ev.keydown && ev.keycode == AM_KEY_ESCAPE) halt(0);
if (ev.keydown && lut[ev.keycode]) {
check_hit(lut[ev.keycode]);
}
};
if (current > rendered) {
render();
rendered = current;
}
}
}
| 25.8125 | 104 | 0.506053 | [
"render"
] |
fa12baf4eda7d039cfcb0b5c84dd84cbc614f8bf | 3,337 | h | C | cartographer/mapping/submaps.h | zhaozhi1995/cartographer | a9d4be9f46d5fad898dc0ceeea08bd985a57f0e6 | [
"Apache-2.0"
] | 12 | 2020-11-24T03:46:44.000Z | 2022-03-07T07:35:24.000Z | cartographer/mapping/submaps.h | rancheng/cartographer | a9d4be9f46d5fad898dc0ceeea08bd985a57f0e6 | [
"Apache-2.0"
] | null | null | null | cartographer/mapping/submaps.h | rancheng/cartographer | a9d4be9f46d5fad898dc0ceeea08bd985a57f0e6 | [
"Apache-2.0"
] | 9 | 2021-01-13T08:58:47.000Z | 2022-03-29T10:27:07.000Z | /*
* Copyright 2016 The Cartographer Authors
*
* 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 CARTOGRAPHER_MAPPING_SUBMAPS_H_
#define CARTOGRAPHER_MAPPING_SUBMAPS_H_
#include <memory>
#include <vector>
#include "Eigen/Geometry"
#include "cartographer/common/math.h"
#include "cartographer/common/port.h"
#include "cartographer/io/submap_painter.h"
#include "cartographer/mapping/id.h"
#include "cartographer/mapping/probability_values.h"
#include "cartographer/mapping/proto/serialization.pb.h"
#include "cartographer/mapping/proto/submap_visualization.pb.h"
#include "cartographer/mapping/trajectory_node.h"
#include "glog/logging.h"
namespace cartographer {
namespace mapping {
// Converts the given probability to log odds.
inline float Logit(float probability) {
return std::log(probability / (1.f - probability));
}
const float kMaxLogOdds = Logit(kMaxProbability);
const float kMinLogOdds = Logit(kMinProbability);
// Converts a probability to a log odds integer. 0 means unknown, [kMinLogOdds,
// kMaxLogOdds] is mapped to [1, 255].
inline uint8 ProbabilityToLogOddsInteger(const float probability) {
const int value = common::RoundToInt((Logit(probability) - kMinLogOdds) *
254.f / (kMaxLogOdds - kMinLogOdds)) +
1;
CHECK_LE(1, value);
CHECK_GE(255, value);
return value;
}
// An individual submap, which has a 'local_pose' in the local map frame, keeps
// track of how many range data were inserted into it, and sets
// 'insertion_finished' when the map no longer changes and is ready for loop
// closing.
class Submap {
public:
Submap(const transform::Rigid3d& local_submap_pose)
: local_pose_(local_submap_pose) {}
virtual ~Submap() {}
virtual proto::Submap ToProto(bool include_grid_data) const = 0;
virtual void UpdateFromProto(const proto::Submap& proto) = 0;
// Fills data into the 'response'.
virtual void ToResponseProto(
const transform::Rigid3d& global_submap_pose,
proto::SubmapQuery::Response* response) const = 0;
// Pose of this submap in the local map frame.
transform::Rigid3d local_pose() const { return local_pose_; }
// Number of RangeData inserted.
int num_range_data() const { return num_range_data_; }
void set_num_range_data(const int num_range_data) {
num_range_data_ = num_range_data;
}
bool insertion_finished() const { return insertion_finished_; }
void set_insertion_finished(bool insertion_finished) {
insertion_finished_ = insertion_finished;
}
virtual cartographer::io::UniqueCairoSurfacePtr DrawSurface() const = 0;
private:
const transform::Rigid3d local_pose_;
int num_range_data_ = 0;
bool insertion_finished_ = false;
};
} // namespace mapping
} // namespace cartographer
#endif // CARTOGRAPHER_MAPPING_SUBMAPS_H_
| 33.37 | 79 | 0.742283 | [
"geometry",
"vector",
"transform"
] |
fa13db24ff336433eb022245694c64e570187481 | 6,257 | h | C | src/timeseries.h | pausz/nftsim | 1adbdcd7d9ac0ec11c1ea1531b4c82b8b9c72f41 | [
"Apache-2.0"
] | null | null | null | src/timeseries.h | pausz/nftsim | 1adbdcd7d9ac0ec11c1ea1531b4c82b8b9c72f41 | [
"Apache-2.0"
] | null | null | null | src/timeseries.h | pausz/nftsim | 1adbdcd7d9ac0ec11c1ea1531b4c82b8b9c72f41 | [
"Apache-2.0"
] | null | null | null | /** @file timeseries.h
@brief A brief, one sentence description.
A more detailed multiline description...
@author Peter Drysdale, Felix Fung,
*/
#ifndef NFTSIM_SRC_TIMESERIES_H
#define NFTSIM_SRC_TIMESERIES_H
// Other nftsim headers
#include "configf.h" // Configf;
#include "nf.h" // NF;
#include "random.h" // Random;
// C++ standard library headers
#include <limits> // std::numeric_limits<double>::infinity()
#include <vector> // std::vector;
class Timeseries : public NF {
protected:
using series_size_type = std::vector<double>::size_type;
void init( Configf& configf ) override;
std::vector<Timeseries*> series;
std::vector<size_type> node;
double inf = std::numeric_limits<double>::infinity(); ///< Infinity
double t = 0.0; ///< Current time relative to stimulus onset.
double onset = 0.0; ///< Onset time for the stimulus.
double duration = inf; ///< Duration of the stimulus.
public:
Timeseries(const Timeseries&) = delete; // No copy constructor allowed.
Timeseries() = delete; // No default constructor allowed.
Timeseries( size_type nodes, double deltat, size_type index );
~Timeseries() override;
void step() override;
virtual void fire( std::vector<double>& Q ) const;
};
namespace TIMESERIES {
struct Const : public Timeseries {
double mean = 0.0; ///<
Const(size_type nodes, double deltat, size_type index) : Timeseries(nodes, deltat, index) {}
void init( Configf& configf ) override;
void fire( std::vector<double>& Q ) const override;
};
struct PulseRect : public Timeseries {
double amp = 0.0; ///< Amplitude of the pulse.
double width = 0.0; ///< Width of the pulse [s].
double period = 0.0; ///< Time between the start of each pulse [s].
double pulses = 0.0; ///< Maximum number of pulses.
PulseRect(size_type nodes, double deltat, size_type index) : Timeseries(nodes, deltat, index) {}
void init( Configf& configf ) override;
void fire( std::vector<double>& Q ) const override;
};
struct PulseSine : public Timeseries {
double amp = 0.0; ///< Amplitude of the pulse.
double width = 0.0; ///< Width of the pulse [s], wavelength of sine.
double period = 0.0; ///< Time between the start of each pulse [s].
double phase = 0.0; ///< Phase of the sine wave in [degrees].
double pulses = 0.0; ///< Maximum number of pulses.
PulseSine(size_type nodes, double deltat, size_type index) : Timeseries(nodes, deltat, index) {}
~PulseSine() override = default;
void init( Configf& configf ) override;
void fire( std::vector<double>& Q ) const override;
};
struct PulseSigmoid : public Timeseries {
double amp = 0.0; ///< Amplitude of the pulse.
double width = 0.0; ///< Width of the pulse [s].
double period = 0.0; ///< Time between the start of each pulse [s].
double pulses = 0.0; ///< Maximum number of pulses.
double sigma = 0.03125; ///< Width of transition.
PulseSigmoid(size_type nodes, double deltat, size_type index) : Timeseries(nodes, deltat, index) {}
void init( Configf& configf ) override;
void fire( std::vector<double>& Q ) const override;
std::vector<double> onset_midpoints;
double first_pulse_mid = 0.0; ///< Mid-point of the first pulse.
static constexpr double pi_on_sqrt3 = 1.813799364234217836866491779801435768604278564; //M_PI / std::sqrt(3.0);
size_type pulse_count = 0; ///< Number of pulses, min of pulses and number of pulses that fit in duration.
};
struct Sine : public Timeseries {
double amp = 0.0; ///< Amplitude of the sine wave.
double freq = 0.0; ///< Frequency of the sine wave [s^-1].
Sine(size_type nodes, double deltat, size_type index) : Timeseries(nodes, deltat, index) {}
~Sine() override = default;
void init( Configf& configf ) override;
void fire( std::vector<double>& Q ) const override;
};
struct White : public Timeseries {
uint_fast64_t seed = 0; ///<
double stddev = 0.0; ///<
double asd = 0.0; ///<
double mean = 0.0; ///<
double deltax = 0.0; ///<
Random* random;
White(size_type nodes, double deltat, size_type index) : Timeseries(nodes, deltat, index) {}
~White() override {
delete random;
}
void init( Configf& configf ) override;
void fire( std::vector<double>& Q ) const override;
};
struct WhiteCoherent : public Timeseries {
uint_fast64_t seed = 0; ///<
double stddev = 0.0; ///<
double asd = 0.0; ///<
double mean = 0.0; ///<
Random* random;
WhiteCoherent(size_type nodes, double deltat, size_type index) : Timeseries(nodes, deltat, index) {}
~WhiteCoherent() override {
delete random;
}
void init( Configf& configf ) override;
void fire( std::vector<double>& Q ) const override;
};
struct PAS : public Timeseries {
double n20w = 0.0; ///< Width of the negative amplitude response at around 20 ms.
double n20h = 0.0; ///< Height of the negative amplitude response at around 20 ms.
double p25w = 0.0; ///< Width of the positive amplitude response at around 25 ms.
double p25h = 0.0; ///< Height of the positive amplitude response at around 25 ms.
double tmsw = 0.0; ///< Width of the Transcranial Magnetic Stimulation(TMS).
double tmsh = 0.0; ///< Height of the Transcranial Magnetic Stimulation(TMS).
double t_mns = 0.0; ///<
double isi = 0.0; ///< Inter-Stimulus-Interval.
PAS(size_type nodes, double deltat, size_type index) : Timeseries(nodes, deltat, index) {}
void init( Configf& configf ) override;
void fire( std::vector<double>& Q ) const override;
};
struct Burst : public Timeseries {
double amp = 0.0; ///<
double width = 0.0; ///<
double bursts = 0.0; ///<
double freq = 0.0; ///<
double oscillation_freq = 0.0; ///<
double on = 0.0; ///<
double off = 0.0; ///<
double total = 0.0; ///<
Burst(size_type nodes, double deltat, size_type index) : Timeseries(nodes, deltat, index) {}
void init( Configf& configf ) override;
void fire( std::vector<double>& Q ) const override;
};
} // namespace TIMESERIES
#endif //NFTSIM_SRC_TIMESERIES_H
| 40.108974 | 115 | 0.647275 | [
"vector"
] |
fa16ad66758fd867193bb09290a6459be420fd85 | 4,482 | h | C | pink/include/backend_thread.h | kernelai/pinktest | 51a5f2afd4c3f71ba03660f50099a0c2267b8c10 | [
"BSD-3-Clause"
] | 264 | 2016-07-03T05:45:31.000Z | 2022-03-25T03:05:45.000Z | pink/include/backend_thread.h | kernelai/pinktest | 51a5f2afd4c3f71ba03660f50099a0c2267b8c10 | [
"BSD-3-Clause"
] | 16 | 2016-10-13T04:08:36.000Z | 2018-01-05T02:41:42.000Z | pink/include/backend_thread.h | kernelai/pinktest | 51a5f2afd4c3f71ba03660f50099a0c2267b8c10 | [
"BSD-3-Clause"
] | 132 | 2016-08-13T15:18:31.000Z | 2022-03-26T12:54:43.000Z | // Copyright (c) 2015-present, Qihoo, Inc. All rights reserved.
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree. An additional grant
// of patent rights can be found in the PATENTS file in the same directory.
#ifndef PINK_INCLUDE_BACKEND_THREAD_H_
#define PINK_INCLUDE_BACKEND_THREAD_H_
#include <sys/epoll.h>
#include <set>
#include <string>
#include <map>
#include <memory>
#include <vector>
#include "slash/include/slash_status.h"
#include "slash/include/slash_mutex.h"
#include "pink/include/pink_thread.h"
// remove 'unused parameter' warning
#define UNUSED(expr) do { (void)(expr); } while (0)
#define kConnWriteBuf (1024*1024*100) // cache 100 MB data per connection
namespace pink {
class PinkEpoll;
struct PinkFiredEvent;
class ConnFactory;
class PinkConn;
/*
* BackendHandle will be invoked at appropriate occasion
* in client thread's main loop.
*/
class BackendHandle {
public:
BackendHandle() {}
virtual ~BackendHandle() {}
/*
* CronHandle() will be invoked on every cron_interval elapsed.
*/
virtual void CronHandle() const {}
/*
* FdTimeoutHandle(...) will be invoked after connection timeout.
*/
virtual void FdTimeoutHandle(int fd, const std::string& ip_port) const {
UNUSED(fd);
UNUSED(ip_port);
}
/*
* FdClosedHandle(...) will be invoked before connection closed.
*/
virtual void FdClosedHandle(int fd, const std::string& ip_port) const {
UNUSED(fd);
UNUSED(ip_port);
}
/*
* AccessHandle(...) will be invoked after Write invoked
* but before handled.
*/
virtual bool AccessHandle(std::string& ip) const {
UNUSED(ip);
return true;
}
/*
* CreateWorkerSpecificData(...) will be invoked in StartThread() routine.
* 'data' pointer should be assigned.
*/
virtual int CreateWorkerSpecificData(void** data) const {
UNUSED(data);
return 0;
}
/*
* DeleteWorkerSpecificData(...) is related to CreateWorkerSpecificData(...),
* it will be invoked in StopThread(...) routine,
* resources assigned in CreateWorkerSpecificData(...) should be deleted in
* this handle
*/
virtual int DeleteWorkerSpecificData(void* data) const {
UNUSED(data);
return 0;
}
/*
* DestConnectFailedHandle(...) will run the invoker's logic when socket connect failed
*/
virtual void DestConnectFailedHandle(std::string ip_port, std::string reason) const {
UNUSED(ip_port);
UNUSED(reason);
}
};
class BackendThread : public Thread {
public:
BackendThread(ConnFactory* conn_factory, int cron_interval, int keepalive_timeout, BackendHandle* handle, void* private_data);
virtual ~BackendThread();
/*
* StartThread will return the error code as pthread_create return
* Return 0 if success
*/
virtual int StartThread() override;
virtual int StopThread() override;
slash::Status Write(const int fd, const std::string& msg);
slash::Status Close(const int fd);
// Try to connect fd noblock, if return EINPROGRESS or EAGAIN or EWOULDBLOCK
// put this fd in epoll (SetWaitConnectOnEpoll), process in ProcessConnectStatus
slash::Status Connect(const std::string& dst_ip, const int dst_port, int *fd);
std::shared_ptr<PinkConn> GetConn(int fd);
private:
virtual void *ThreadMain() override;
void InternalDebugPrint();
// Set connect fd into epoll
// connect condition: no EPOLLERR EPOLLHUP events, no error in socket opt
slash::Status ProcessConnectStatus(PinkFiredEvent* pfe, int* should_close);
void SetWaitConnectOnEpoll(int sockfd);
void AddConnection(const std::string& peer_ip, int peer_port, int sockfd);
void CloseFd(std::shared_ptr<PinkConn> conn);
void CloseFd(const int fd);
void CleanUpConnRemaining(const int fd);
void DoCronTask();
void NotifyWrite(const std::string ip_port);
void NotifyWrite(const int fd);
void NotifyClose(const int fd);
void ProcessNotifyEvents(const PinkFiredEvent* pfe);
int keepalive_timeout_;
int cron_interval_;
BackendHandle* handle_;
bool own_handle_;
void* private_data_;
/*
* The Epoll event handler
*/
PinkEpoll *pink_epoll_;
ConnFactory *conn_factory_;
slash::Mutex mu_;
std::map<int, std::vector<std::string>> to_send_; // ip+":"+port, to_send_msg
std::map<int, std::shared_ptr<PinkConn>> conns_;
std::set<int> connecting_fds_;
};
} // namespace pink
#endif // PINK_INCLUDE_CLIENT_THREAD_H_
| 27.666667 | 128 | 0.71419 | [
"vector"
] |
fa1b22e3af487b19b8b7885b7c3740b6249c73eb | 4,402 | h | C | tensorflow/c/eager/c_api_internal.h | gehring/tensorflow | e6d171a2afcf0b7a1f77f125751727232480edbe | [
"Apache-2.0"
] | 2 | 2018-10-05T05:16:30.000Z | 2018-10-05T05:16:32.000Z | tensorflow/c/eager/c_api_internal.h | gehring/tensorflow | e6d171a2afcf0b7a1f77f125751727232480edbe | [
"Apache-2.0"
] | null | null | null | tensorflow/c/eager/c_api_internal.h | gehring/tensorflow | e6d171a2afcf0b7a1f77f125751727232480edbe | [
"Apache-2.0"
] | null | null | null | /* Copyright 2017 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#ifndef TENSORFLOW_C_EAGER_C_API_INTERNAL_H_
#define TENSORFLOW_C_EAGER_C_API_INTERNAL_H_
#include "tensorflow/c/eager/c_api.h"
#include <algorithm>
#include <cstddef>
#include <map>
#include <memory>
#include <queue>
#include <string>
#include <thread>
#include <vector>
#include "tensorflow/c/c_api.h"
#include "tensorflow/c/c_api_internal.h"
#include "tensorflow/core/common_runtime/device_factory.h"
#include "tensorflow/core/common_runtime/eager/attr_builder.h"
#include "tensorflow/core/common_runtime/eager/context.h"
#include "tensorflow/core/common_runtime/eager/eager_executor.h"
#include "tensorflow/core/common_runtime/eager/eager_operation.h"
#include "tensorflow/core/common_runtime/eager/kernel_and_device.h"
#include "tensorflow/core/common_runtime/eager/tensor_handle.h"
#include "tensorflow/core/common_runtime/function.h"
#include "tensorflow/core/common_runtime/rendezvous_mgr.h"
#include "tensorflow/core/distributed_runtime/eager/eager_client.h"
#include "tensorflow/core/distributed_runtime/remote_device.h"
#include "tensorflow/core/distributed_runtime/rpc/grpc_server_lib.h"
#include "tensorflow/core/distributed_runtime/rpc/grpc_worker_cache.h"
#include "tensorflow/core/distributed_runtime/rpc/grpc_worker_service.h"
#include "tensorflow/core/distributed_runtime/rpc/rpc_rendezvous_mgr.h"
#include "tensorflow/core/distributed_runtime/server_lib.h"
#include "tensorflow/core/distributed_runtime/worker_env.h"
#include "tensorflow/core/framework/rendezvous.h"
#include "tensorflow/core/lib/core/stringpiece.h"
#include "tensorflow/core/lib/gtl/inlined_vector.h"
#include "tensorflow/core/lib/gtl/map_util.h"
#include "tensorflow/core/lib/gtl/stl_util.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/thread_annotations.h"
#include "tensorflow/core/public/version.h"
struct TFE_ContextOptions {
TF_SessionOptions session_options;
// true if async execution is enabled.
bool async = false;
TFE_ContextDevicePlacementPolicy policy{TFE_DEVICE_PLACEMENT_SILENT};
};
struct TFE_Context {
TFE_Context(const tensorflow::SessionOptions& opts,
TFE_ContextDevicePlacementPolicy default_policy, bool async,
const tensorflow::DeviceMgr* device_mgr, bool device_mgr_owned,
tensorflow::Rendezvous* rendezvous)
: context(opts,
static_cast<tensorflow::ContextDevicePlacementPolicy>(
default_policy),
async, device_mgr, device_mgr_owned, rendezvous) {}
tensorflow::EagerContext context;
};
struct TFE_TensorHandle {
TFE_TensorHandle(const tensorflow::Tensor& t, tensorflow::Device* d,
tensorflow::Device* op_device)
: handle(new tensorflow::TensorHandle(t, d, op_device, nullptr)) {}
TFE_TensorHandle(tensorflow::TensorHandle* handle) : handle(handle) {}
tensorflow::TensorHandle* handle;
};
struct TFE_TensorDebugInfo {
TFE_TensorDebugInfo(const std::vector<tensorflow::int64>& dims)
: dev_dims(dims) {}
// Fully-padded, minor-to-major.
std::vector<tensorflow::int64> dev_dims;
};
struct TFE_Op {
// t is NULL iff the TFE_Op corresponds to a TensorFlow function instead of a
// primitive operation.
TFE_Op(TFE_Context* ctx, const char* op, const tensorflow::AttrTypeMap* t)
: operation(&ctx->context, op, t) {}
tensorflow::EagerOperation operation;
};
namespace tensorflow {
// Set an AttrValue on the op. Doesn't handle the list types.
void SetOpAttrValueScalar(TFE_Context* ctx, TFE_Op* op,
const tensorflow::AttrValue& default_value,
const char* attr_name, TF_Status* status);
} // namespace tensorflow
#endif // TENSORFLOW_C_EAGER_C_API_INTERNAL_H_
| 39.303571 | 80 | 0.752158 | [
"vector"
] |
fa1b374b8a3dc70db00e20683a0ad53e7728128c | 5,579 | h | C | Sourcecode/mx/core/elements/NotationsChoice.h | diskzero/MusicXML-Class-Library | bd4d1357b8ab2d4df8f1c6077883bbf169f6f0db | [
"MIT"
] | null | null | null | Sourcecode/mx/core/elements/NotationsChoice.h | diskzero/MusicXML-Class-Library | bd4d1357b8ab2d4df8f1c6077883bbf169f6f0db | [
"MIT"
] | null | null | null | Sourcecode/mx/core/elements/NotationsChoice.h | diskzero/MusicXML-Class-Library | bd4d1357b8ab2d4df8f1c6077883bbf169f6f0db | [
"MIT"
] | null | null | null | // MusicXML Class Library
// Copyright (c) by Matthew James Briggs
// Distributed under the MIT License
#pragma once
#include "mx/core/ForwardDeclare.h"
#include "mx/core/ElementInterface.h"
#include <iosfwd>
#include <memory>
#include <vector>
namespace mx
{
namespace core
{
MX_FORWARD_DECLARE_ELEMENT( AccidentalMark )
MX_FORWARD_DECLARE_ELEMENT( Arpeggiate )
MX_FORWARD_DECLARE_ELEMENT( Articulations )
MX_FORWARD_DECLARE_ELEMENT( Dynamics )
MX_FORWARD_DECLARE_ELEMENT( Fermata )
MX_FORWARD_DECLARE_ELEMENT( Glissando )
MX_FORWARD_DECLARE_ELEMENT( NonArpeggiate )
MX_FORWARD_DECLARE_ELEMENT( Ornaments )
MX_FORWARD_DECLARE_ELEMENT( OtherNotation )
MX_FORWARD_DECLARE_ELEMENT( Slide )
MX_FORWARD_DECLARE_ELEMENT( Slur )
MX_FORWARD_DECLARE_ELEMENT( Technical )
MX_FORWARD_DECLARE_ELEMENT( Tied )
MX_FORWARD_DECLARE_ELEMENT( Tuplet )
MX_FORWARD_DECLARE_ELEMENT( NotationsChoice )
inline NotationsChoicePtr makeNotationsChoice() { return std::make_shared<NotationsChoice>(); }
class NotationsChoice : public ElementInterface
{
public:
enum class Choice
{
tied = 1,
slur = 2,
tuplet = 3,
glissando = 4,
slide = 5,
ornaments = 6,
technical = 7,
articulations = 8,
dynamics = 9,
fermata = 10,
arpeggiate = 11,
nonArpeggiate = 12,
accidentalMark = 13,
otherNotation = 14
};
NotationsChoice();
virtual bool hasAttributes() const;
virtual std::ostream& streamAttributes( std::ostream& os ) const;
virtual std::ostream& streamName( std::ostream& os ) const;
virtual bool hasContents() const;
virtual std::ostream& streamContents( std::ostream& os, const int indentLevel, bool& isOneLineOnly ) const;
/* _________ Choice minOccurs = 1, maxOccurs = 1 _________ */
NotationsChoice::Choice getChoice() const;
void setChoice( const NotationsChoice::Choice value );
/* _________ Tied minOccurs = 1, maxOccurs = 1 _________ */
TiedPtr getTied() const;
void setTied( const TiedPtr& value );
/* _________ Slur minOccurs = 1, maxOccurs = 1 _________ */
SlurPtr getSlur() const;
void setSlur( const SlurPtr& value );
/* _________ Tuplet minOccurs = 1, maxOccurs = 1 _________ */
TupletPtr getTuplet() const;
void setTuplet( const TupletPtr& value );
/* _________ Glissando minOccurs = 1, maxOccurs = 1 _________ */
GlissandoPtr getGlissando() const;
void setGlissando( const GlissandoPtr& value );
/* _________ Slide minOccurs = 1, maxOccurs = 1 _________ */
SlidePtr getSlide() const;
void setSlide( const SlidePtr& value );
/* _________ Ornaments minOccurs = 1, maxOccurs = 1 _________ */
OrnamentsPtr getOrnaments() const;
void setOrnaments( const OrnamentsPtr& value );
/* _________ Technical minOccurs = 1, maxOccurs = 1 _________ */
TechnicalPtr getTechnical() const;
void setTechnical( const TechnicalPtr& value );
/* _________ Articulations minOccurs = 1, maxOccurs = 1 _________ */
ArticulationsPtr getArticulations() const;
void setArticulations( const ArticulationsPtr& value );
/* _________ Dynamics minOccurs = 1, maxOccurs = 1 _________ */
DynamicsPtr getDynamics() const;
void setDynamics( const DynamicsPtr& value );
/* _________ Fermata minOccurs = 1, maxOccurs = 1 _________ */
FermataPtr getFermata() const;
void setFermata( const FermataPtr& value );
/* _________ Arpeggiate minOccurs = 1, maxOccurs = 1 _________ */
ArpeggiatePtr getArpeggiate() const;
void setArpeggiate( const ArpeggiatePtr& value );
/* _________ NonArpeggiate minOccurs = 1, maxOccurs = 1 _________ */
NonArpeggiatePtr getNonArpeggiate() const;
void setNonArpeggiate( const NonArpeggiatePtr& value );
/* _________ AccidentalMark minOccurs = 1, maxOccurs = 1 _________ */
AccidentalMarkPtr getAccidentalMark() const;
void setAccidentalMark( const AccidentalMarkPtr& value );
/* _________ OtherNotation minOccurs = 1, maxOccurs = 1 _________ */
OtherNotationPtr getOtherNotation() const;
void setOtherNotation( const OtherNotationPtr& value );
private:
virtual bool fromXElementImpl( std::ostream& message, xml::XElement& xelement );
private:
Choice myChoice;
TiedPtr myTied;
SlurPtr mySlur;
TupletPtr myTuplet;
GlissandoPtr myGlissando;
SlidePtr mySlide;
OrnamentsPtr myOrnaments;
TechnicalPtr myTechnical;
ArticulationsPtr myArticulations;
DynamicsPtr myDynamics;
FermataPtr myFermata;
ArpeggiatePtr myArpeggiate;
NonArpeggiatePtr myNonArpeggiate;
AccidentalMarkPtr myAccidentalMark;
OtherNotationPtr myOtherNotation;
};
}
}
| 37.952381 | 119 | 0.607636 | [
"vector"
] |
fa1c3578d722d1aceae4691f1f55fa6b419aefa9 | 4,689 | h | C | aws-cpp-sdk-email/include/aws/email/model/ListIdentitiesRequest.h | ambasta/aws-sdk-cpp | c81192e00b572b76d175d84dff77185bd17ae1ac | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-email/include/aws/email/model/ListIdentitiesRequest.h | ambasta/aws-sdk-cpp | c81192e00b572b76d175d84dff77185bd17ae1ac | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-email/include/aws/email/model/ListIdentitiesRequest.h | ambasta/aws-sdk-cpp | c81192e00b572b76d175d84dff77185bd17ae1ac | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2010-2016 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/email/SES_EXPORTS.h>
#include <aws/email/SESRequest.h>
#include <aws/email/model/IdentityType.h>
#include <aws/core/utils/memory/stl/AWSString.h>
namespace Aws
{
namespace SES
{
namespace Model
{
/**
* <p>Represents a request to return a list of all identities (email addresses and
* domains) that you have attempted to verify under your AWS account, regardless of
* verification status.</p>
*/
class AWS_SES_API ListIdentitiesRequest : public SESRequest
{
public:
ListIdentitiesRequest();
Aws::String SerializePayload() const override;
/**
* <p>The type of the identities to list. Possible values are "EmailAddress" and
* "Domain". If this parameter is omitted, then all identities will be listed.</p>
*/
inline const IdentityType& GetIdentityType() const{ return m_identityType; }
/**
* <p>The type of the identities to list. Possible values are "EmailAddress" and
* "Domain". If this parameter is omitted, then all identities will be listed.</p>
*/
inline void SetIdentityType(const IdentityType& value) { m_identityTypeHasBeenSet = true; m_identityType = value; }
/**
* <p>The type of the identities to list. Possible values are "EmailAddress" and
* "Domain". If this parameter is omitted, then all identities will be listed.</p>
*/
inline void SetIdentityType(IdentityType&& value) { m_identityTypeHasBeenSet = true; m_identityType = value; }
/**
* <p>The type of the identities to list. Possible values are "EmailAddress" and
* "Domain". If this parameter is omitted, then all identities will be listed.</p>
*/
inline ListIdentitiesRequest& WithIdentityType(const IdentityType& value) { SetIdentityType(value); return *this;}
/**
* <p>The type of the identities to list. Possible values are "EmailAddress" and
* "Domain". If this parameter is omitted, then all identities will be listed.</p>
*/
inline ListIdentitiesRequest& WithIdentityType(IdentityType&& value) { SetIdentityType(value); return *this;}
/**
* <p>The token to use for pagination.</p>
*/
inline const Aws::String& GetNextToken() const{ return m_nextToken; }
/**
* <p>The token to use for pagination.</p>
*/
inline void SetNextToken(const Aws::String& value) { m_nextTokenHasBeenSet = true; m_nextToken = value; }
/**
* <p>The token to use for pagination.</p>
*/
inline void SetNextToken(Aws::String&& value) { m_nextTokenHasBeenSet = true; m_nextToken = value; }
/**
* <p>The token to use for pagination.</p>
*/
inline void SetNextToken(const char* value) { m_nextTokenHasBeenSet = true; m_nextToken.assign(value); }
/**
* <p>The token to use for pagination.</p>
*/
inline ListIdentitiesRequest& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}
/**
* <p>The token to use for pagination.</p>
*/
inline ListIdentitiesRequest& WithNextToken(Aws::String&& value) { SetNextToken(value); return *this;}
/**
* <p>The token to use for pagination.</p>
*/
inline ListIdentitiesRequest& WithNextToken(const char* value) { SetNextToken(value); return *this;}
/**
* <p>The maximum number of identities per page. Possible values are 1-1000
* inclusive.</p>
*/
inline int GetMaxItems() const{ return m_maxItems; }
/**
* <p>The maximum number of identities per page. Possible values are 1-1000
* inclusive.</p>
*/
inline void SetMaxItems(int value) { m_maxItemsHasBeenSet = true; m_maxItems = value; }
/**
* <p>The maximum number of identities per page. Possible values are 1-1000
* inclusive.</p>
*/
inline ListIdentitiesRequest& WithMaxItems(int value) { SetMaxItems(value); return *this;}
private:
IdentityType m_identityType;
bool m_identityTypeHasBeenSet;
Aws::String m_nextToken;
bool m_nextTokenHasBeenSet;
int m_maxItems;
bool m_maxItemsHasBeenSet;
};
} // namespace Model
} // namespace SES
} // namespace Aws
| 34.992537 | 119 | 0.684794 | [
"model"
] |
fa235c92dd93b7e3c01d69d46679ecc80db8191b | 7,160 | h | C | src/ResizeArrayRaw.h | gwli/namd | a2ce2a1bfe68350cde94a72d32192ad8f1ffa175 | [
"BSD-3-Clause"
] | null | null | null | src/ResizeArrayRaw.h | gwli/namd | a2ce2a1bfe68350cde94a72d32192ad8f1ffa175 | [
"BSD-3-Clause"
] | null | null | null | src/ResizeArrayRaw.h | gwli/namd | a2ce2a1bfe68350cde94a72d32192ad8f1ffa175 | [
"BSD-3-Clause"
] | null | null | null | /**
*** Copyright (c) 1995, 1996, 1997, 1998, 1999, 2000 by
*** The Board of Trustees of the University of Illinois.
*** All rights reserved.
**/
/*
Data storage class for ResizeArray and related container classes.
Copy and assignment copy raw pointers, use copy() to copy data.
Destructor does not delete data, call free first.
*/
#ifndef RESIZEARRAYRAW_H
#define RESIZEARRAYRAW_H
#include <new>
#include <string.h>
#include "common.h"
#define ResizeArrayGrowthFactor 1.5
#define ResizeArrayMinSize 8
// Need this juju to use templated friend below
template <class Type> class ResizeArray;
template <class Type> class SortableResizeArray;
template <class Type> class SortedArray;
template <class Type> class UniqueSortedArray;
template <class Type> class ResizeArrayIter;
// Class assumes that one can bit move objects
// around on array. This will be true
// as long as object has no pointers to itself.
template <class Elem> class ResizeArrayRaw {
private:
Elem *array;
unsigned char *varray;
// Use of int (int32) is safe for counting elements.
int arraySize;
int allocSize;
// No constructor run on new elements
// arraySize is not adjusted, only allocSize
void resizeRaw(int size) {
if (size <= allocSize) return;
// Note that ResizeArrayGrowthFactor is type double so the
// multiplication below is also done in double.
// Assuming int32, the conversion from double overflows at
// allocSize = 1431655765
// Conditional remains safe if overflow causes RHS < 0.
if (size < (int)(allocSize*ResizeArrayGrowthFactor)) {
size = (int)(allocSize*ResizeArrayGrowthFactor);
}
// The next conditional will test true either for very small or
// unallocated arrays or if the above conditional causes overflow.
if ( (size-allocSize) < ResizeArrayMinSize) {
// Overflow occurs here only when allocSize is within
// ResizeArrayMinSize of 2^31.
size = allocSize+ResizeArrayMinSize;
}
// Align everything to 64-byte boundaries (if possible).
// Use of sizeof below promotes expression to type size_t.
unsigned char *tmpv = new unsigned char[size*sizeof(Elem)+63];
//Elem *tmpa = (Elem *)((((long)tmpv)+63L)&(-64L));
// Someday we might need this alternate form.
//
// The following pointer manipulation is dangerous. We should use
// reinterpret_cast<uintptr_t> or equivalent to convert tmpv+63
// to an unsigned integer type before doing bitwise and operation.
//
// The 63 value (64-byte alignment) aligns for AVX-512 registers.
// Would be better to use a macro or maybe even a template parameter
// instead of hard-coding the alignment. With a template parameter,
// we could override the alignment where optimization warrants or
// target builds towards a particular alignment, e.g., AVX needs
// only 32-byte alignment.
Elem *tmpa = (Elem *)(tmpv+63 - (((long)(tmpv+63))&(63L)));
if (arraySize) CmiMemcpy((void *)tmpa, (void *)array, sizeof(Elem)*arraySize);
if (allocSize) delete[] varray;
varray = tmpv;
array = tmpa;
allocSize = size;
}
friend class ResizeArray<Elem>;
friend class SortableResizeArray<Elem>;
friend class SortedArray<Elem>;
friend class UniqueSortedArray<Elem>;
friend class ResizeArrayIter<Elem>;
inline int size(void) const { return arraySize; }
inline Elem &operator[](int index) const { return array[index]; }
// DMK - MIC Support - Allow us to see the buffer's size, not just how much of it is used
#if NAMD_MIC != 0
inline int bufSize(void) const { return allocSize; }
#endif
// Default constructor
ResizeArrayRaw(void) :
array((Elem *)0), varray((unsigned char *)0), arraySize(0), allocSize(0) { }
// Encap a pre-existing array
ResizeArrayRaw( Elem * * const array, int arraySize, int allocSize) {
if (allocSize < arraySize) allocSize = arraySize;
this->allocSize = allocSize;
this->arraySize = arraySize;
varray = (unsigned char *)*array;
this->array = (Elem *)*array;
*array = 0;
}
// copy data
void copy(const ResizeArrayRaw<Elem> &rar ) {
// Clean up this array
resize(0);
resizeRaw(rar.size());
CmiMemcpy((void*)array, (void*)rar.array, sizeof(Elem)*rar.size());
arraySize = rar.size();
}
// Properly constructs default object on new elements
// Properly destructs on removed elements
// arraySize is properly updated
void resize(int size) {
int i;
if (size < arraySize) {
for (i=size; i<arraySize; i++) {
array[i].~Elem();
}
} else if (size > arraySize) {
resizeRaw(size);
for (i=arraySize; i<size; i++) {
new ((void *)&array[i]) Elem;
}
}
arraySize = size;
}
// needed for ResizeArray destructor
void free(void) {
for (int i=0; i < arraySize; i++) {
array[i].~Elem();
}
delete[] varray;
}
// resize to 0 and free storage
void clear(void) {
free();
array = 0;
varray = 0;
arraySize = 0;
allocSize = 0;
}
inline int del(int index, int number) {
int i;
// Fix up number to delete if deletes off end of array
if (index >= arraySize) {
number=0; // for inline sake, don't have multiple returns
} else if (index+number-1 > arraySize) {
number = index-arraySize+1;
}
// Destruct objects to be deleted
for (i=index; i < index+number; i++) {
array[i].~Elem();
}
// Shift down
memmove((void *)(array+index),
(void *)(array+index+number),
(arraySize-number-index)*sizeof(Elem));
// fixup size of array
arraySize -= number;
return(number);
}
// Insert element in array
// If index is over the end of array, default
// constructor should be run over blank elements to pad.
inline void ins(const Elem &e, int index) {
// Size array depending if index is in current array or reaches beyond.
if (index < arraySize) {
resizeRaw(arraySize+1);
// Shift up
memmove((void *)(array+index+1),
(void *)(array+index),
(arraySize-index)*sizeof(Elem));
} else {
resizeRaw(index+1);
}
// Write in new element via assignment - allows any refcounting
// etc. to take place correctly!
new((void *)&array[index]) Elem;
array[index] = e;
// Take care of fill and setting correct arraySize
if (index > arraySize) {
for (Elem *tmp = array+arraySize; tmp < array+index; tmp++) {
new ((void *)tmp) Elem;
}
arraySize = index+1;
} else {
arraySize++;
}
}
inline int find(const Elem &e) const {
for (int i=0; i<arraySize; i++) {
if (array[i] == e) return i;
}
return -1;
}
}; // end template definition
#endif
| 30.995671 | 93 | 0.615922 | [
"object"
] |
fa2630ba726a5964b440fa7d95df9fda2ec17fe0 | 3,002 | h | C | source/blender/editors/include/ED_undo.h | atlantic-crypto/blender | 65fdf6f0ed592082ead87c76ea9be46cd54dba26 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 116 | 2015-11-02T16:36:53.000Z | 2021-06-08T20:36:18.000Z | source/blender/editors/include/ED_undo.h | atlantic-crypto/blender | 65fdf6f0ed592082ead87c76ea9be46cd54dba26 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 39 | 2016-04-25T12:18:34.000Z | 2021-03-01T19:06:36.000Z | source/blender/editors/include/ED_undo.h | atlantic-crypto/blender | 65fdf6f0ed592082ead87c76ea9be46cd54dba26 | [
"Naumen",
"Condor-1.1",
"MS-PL"
] | 19 | 2016-01-24T14:24:00.000Z | 2020-07-19T05:26:24.000Z | /*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/** \file
* \ingroup editors
*/
#ifndef __ED_UNDO_H__
#define __ED_UNDO_H__
#include "BLI_compiler_attrs.h"
struct CLG_LogRef;
struct Object;
struct UndoStack;
struct ViewLayer;
struct bContext;
struct wmOperator;
struct wmOperatorType;
/* undo.c */
void ED_undo_push(struct bContext *C, const char *str);
void ED_undo_push_op(struct bContext *C, struct wmOperator *op);
void ED_undo_grouped_push(struct bContext *C, const char *str);
void ED_undo_grouped_push_op(struct bContext *C, struct wmOperator *op);
void ED_undo_pop_op(struct bContext *C, struct wmOperator *op);
void ED_undo_pop(struct bContext *C);
void ED_undo_redo(struct bContext *C);
void ED_OT_undo(struct wmOperatorType *ot);
void ED_OT_undo_push(struct wmOperatorType *ot);
void ED_OT_redo(struct wmOperatorType *ot);
void ED_OT_undo_redo(struct wmOperatorType *ot);
void ED_OT_undo_history(struct wmOperatorType *ot);
int ED_undo_operator_repeat(struct bContext *C, struct wmOperator *op);
/* convenience since UI callbacks use this mostly*/
void ED_undo_operator_repeat_cb(struct bContext *C, void *arg_op, void *arg_unused);
void ED_undo_operator_repeat_cb_evt(struct bContext *C, void *arg_op, int arg_unused);
bool ED_undo_is_valid(const struct bContext *C, const char *undoname);
bool ED_undo_is_memfile_compatible(const struct bContext *C);
/* Unfortunate workaround for limits mixing undo systems. */
bool ED_undo_is_legacy_compatible_for_property(struct bContext *C, struct ID *id);
void ED_undo_object_editmode_restore_helper(struct bContext *C,
struct Object **object_array,
uint object_array_len,
uint object_array_stride);
struct UndoStack *ED_undo_stack_get(void);
/* helpers */
void ED_undo_object_set_active_or_warn(struct ViewLayer *view_layer,
struct Object *ob,
const char *info,
struct CLG_LogRef *log);
/* undo_system_types.c */
void ED_undosys_type_init(void);
void ED_undosys_type_free(void);
/* memfile_undo.c */
struct MemFile *ED_undosys_stack_memfile_get_active(struct UndoStack *ustack);
#endif /* __ED_UNDO_H__ */
| 37.061728 | 86 | 0.722851 | [
"object"
] |
fa29a9d99c5e1fc13f85795a07783faeea2dd61e | 18,149 | c | C | zfs-fuse/src/lib/libzpool/dnode_sync.c | zhihui-slash2/slash2-stable | e75d3049602b1f1a36c2df25f4e12c3ade1ae11d | [
"0BSD"
] | null | null | null | zfs-fuse/src/lib/libzpool/dnode_sync.c | zhihui-slash2/slash2-stable | e75d3049602b1f1a36c2df25f4e12c3ade1ae11d | [
"0BSD"
] | null | null | null | zfs-fuse/src/lib/libzpool/dnode_sync.c | zhihui-slash2/slash2-stable | e75d3049602b1f1a36c2df25f4e12c3ade1ae11d | [
"0BSD"
] | null | null | null | /*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
* or http://www.opensolaris.org/os/licensing.
* See the License for the specific language governing permissions
* and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at usr/src/OPENSOLARIS.LICENSE.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2009 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
#include <sys/zfs_context.h>
#include <sys/dbuf.h>
#include <sys/dnode.h>
#include <sys/dmu.h>
#include <sys/dmu_tx.h>
#include <sys/dmu_objset.h>
#include <sys/dsl_dataset.h>
#include <sys/spa.h>
static void
dnode_increase_indirection(dnode_t *dn, dmu_tx_t *tx)
{
dmu_buf_impl_t *db;
int txgoff = tx->tx_txg & TXG_MASK;
int nblkptr = dn->dn_phys->dn_nblkptr;
int old_toplvl = dn->dn_phys->dn_nlevels - 1;
int new_level = dn->dn_next_nlevels[txgoff];
int i;
rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
/* this dnode can't be paged out because it's dirty */
ASSERT(dn->dn_phys->dn_type != DMU_OT_NONE);
ASSERT(RW_WRITE_HELD(&dn->dn_struct_rwlock));
ASSERT(new_level > 1 && dn->dn_phys->dn_nlevels > 0);
db = dbuf_hold_level(dn, dn->dn_phys->dn_nlevels, 0, FTAG);
ASSERT(db != NULL);
dn->dn_phys->dn_nlevels = new_level;
dprintf("os=%p obj=%llu, increase to %d\n", dn->dn_objset,
dn->dn_object, dn->dn_phys->dn_nlevels);
/* check for existing blkptrs in the dnode */
for (i = 0; i < nblkptr; i++)
if (!BP_IS_HOLE(&dn->dn_phys->dn_blkptr[i]))
break;
if (i != nblkptr) {
/* transfer dnode's block pointers to new indirect block */
(void) dbuf_read(db, NULL, DB_RF_MUST_SUCCEED|DB_RF_HAVESTRUCT);
ASSERT(db->db.db_data);
ASSERT(arc_released(db->db_buf));
ASSERT3U(sizeof (blkptr_t) * nblkptr, <=, db->db.db_size);
bcopy(dn->dn_phys->dn_blkptr, db->db.db_data,
sizeof (blkptr_t) * nblkptr);
arc_buf_freeze(db->db_buf);
}
/* set dbuf's parent pointers to new indirect buf */
for (i = 0; i < nblkptr; i++) {
dmu_buf_impl_t *child = dbuf_find(dn, old_toplvl, i);
if (child == NULL)
continue;
ASSERT3P(child->db_dnode, ==, dn);
if (child->db_parent && child->db_parent != dn->dn_dbuf) {
ASSERT(child->db_parent->db_level == db->db_level);
ASSERT(child->db_blkptr !=
&dn->dn_phys->dn_blkptr[child->db_blkid]);
mutex_exit(&child->db_mtx);
continue;
}
ASSERT(child->db_parent == NULL ||
child->db_parent == dn->dn_dbuf);
child->db_parent = db;
dbuf_add_ref(db, child);
if (db->db.db_data)
child->db_blkptr = (blkptr_t *)db->db.db_data + i;
else
child->db_blkptr = NULL;
dprintf_dbuf_bp(child, child->db_blkptr,
"changed db_blkptr to new indirect %s", "");
mutex_exit(&child->db_mtx);
}
bzero(dn->dn_phys->dn_blkptr, sizeof (blkptr_t) * nblkptr);
dbuf_rele(db, FTAG);
rw_exit(&dn->dn_struct_rwlock);
}
static int
free_blocks(dnode_t *dn, blkptr_t *bp, int num, dmu_tx_t *tx)
{
dsl_dataset_t *ds = dn->dn_objset->os_dsl_dataset;
uint64_t bytesfreed = 0;
int i, blocks_freed = 0;
dprintf("ds=%p obj=%llx num=%d\n", ds, dn->dn_object, num);
for (i = 0; i < num; i++, bp++) {
if (BP_IS_HOLE(bp))
continue;
bytesfreed += dsl_dataset_block_kill(ds, bp, tx, B_FALSE);
ASSERT3U(bytesfreed, <=, DN_USED_BYTES(dn->dn_phys));
bzero(bp, sizeof (blkptr_t));
blocks_freed += 1;
}
dnode_diduse_space(dn, -bytesfreed);
return (blocks_freed);
}
#ifdef ZFS_DEBUG
static void
free_verify(dmu_buf_impl_t *db, uint64_t start, uint64_t end, dmu_tx_t *tx)
{
int off, num;
int i, err, epbs;
uint64_t txg = tx->tx_txg;
epbs = db->db_dnode->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
off = start - (db->db_blkid * 1<<epbs);
num = end - start + 1;
ASSERT3U(off, >=, 0);
ASSERT3U(num, >=, 0);
ASSERT3U(db->db_level, >, 0);
ASSERT3U(db->db.db_size, ==, 1<<db->db_dnode->dn_phys->dn_indblkshift);
ASSERT3U(off+num, <=, db->db.db_size >> SPA_BLKPTRSHIFT);
ASSERT(db->db_blkptr != NULL);
for (i = off; i < off+num; i++) {
uint64_t *buf;
dmu_buf_impl_t *child;
dbuf_dirty_record_t *dr;
int j;
ASSERT(db->db_level == 1);
rw_enter(&db->db_dnode->dn_struct_rwlock, RW_READER);
err = dbuf_hold_impl(db->db_dnode, db->db_level-1,
(db->db_blkid << epbs) + i, TRUE, FTAG, &child);
rw_exit(&db->db_dnode->dn_struct_rwlock);
if (err == ENOENT)
continue;
ASSERT(err == 0);
ASSERT(child->db_level == 0);
dr = child->db_last_dirty;
while (dr && dr->dr_txg > txg)
dr = dr->dr_next;
ASSERT(dr == NULL || dr->dr_txg == txg);
/* data_old better be zeroed */
if (dr) {
buf = dr->dt.dl.dr_data->b_data;
for (j = 0; j < child->db.db_size >> 3; j++) {
if (buf[j] != 0) {
panic("freed data not zero: "
"child=%p i=%d off=%d num=%d\n",
(void *)child, i, off, num);
}
}
}
/*
* db_data better be zeroed unless it's dirty in a
* future txg.
*/
mutex_enter(&child->db_mtx);
buf = child->db.db_data;
if (buf != NULL && child->db_state != DB_FILL &&
child->db_last_dirty == NULL) {
for (j = 0; j < child->db.db_size >> 3; j++) {
if (buf[j] != 0) {
panic("freed data not zero: "
"child=%p i=%d off=%d num=%d\n",
(void *)child, i, off, num);
}
}
}
mutex_exit(&child->db_mtx);
dbuf_rele(child, FTAG);
}
}
#endif
#define ALL -1
static int
free_children(dmu_buf_impl_t *db, uint64_t blkid, uint64_t nblks, int trunc,
dmu_tx_t *tx)
{
dnode_t *dn = db->db_dnode;
blkptr_t *bp;
dmu_buf_impl_t *subdb;
uint64_t start, end, dbstart, dbend, i;
int epbs, shift, err;
int all = TRUE;
int blocks_freed = 0;
/*
* There is a small possibility that this block will not be cached:
* 1 - if level > 1 and there are no children with level <= 1
* 2 - if we didn't get a dirty hold (because this block had just
* finished being written -- and so had no holds), and then this
* block got evicted before we got here.
*/
if (db->db_state != DB_CACHED)
(void) dbuf_read(db, NULL, DB_RF_MUST_SUCCEED);
dbuf_release_bp(db);
bp = (blkptr_t *)db->db.db_data;
epbs = db->db_dnode->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT;
shift = (db->db_level - 1) * epbs;
dbstart = db->db_blkid << epbs;
start = blkid >> shift;
if (dbstart < start) {
bp += start - dbstart;
all = FALSE;
} else {
start = dbstart;
}
dbend = ((db->db_blkid + 1) << epbs) - 1;
end = (blkid + nblks - 1) >> shift;
if (dbend <= end)
end = dbend;
else if (all)
all = trunc;
ASSERT3U(start, <=, end);
if (db->db_level == 1) {
FREE_VERIFY(db, start, end, tx);
blocks_freed = free_blocks(dn, bp, end-start+1, tx);
arc_buf_freeze(db->db_buf);
ASSERT(all || blocks_freed == 0 || db->db_last_dirty);
return (all ? ALL : blocks_freed);
}
for (i = start; i <= end; i++, bp++) {
if (BP_IS_HOLE(bp))
continue;
rw_enter(&dn->dn_struct_rwlock, RW_READER);
err = dbuf_hold_impl(dn, db->db_level-1, i, TRUE, FTAG, &subdb);
ASSERT3U(err, ==, 0);
rw_exit(&dn->dn_struct_rwlock);
if (free_children(subdb, blkid, nblks, trunc, tx) == ALL) {
ASSERT3P(subdb->db_blkptr, ==, bp);
blocks_freed += free_blocks(dn, bp, 1, tx);
} else {
all = FALSE;
}
dbuf_rele(subdb, FTAG);
}
arc_buf_freeze(db->db_buf);
#ifdef ZFS_DEBUG
bp -= (end-start)+1;
for (i = start; i <= end; i++, bp++) {
if (i == start && blkid != 0)
continue;
else if (i == end && !trunc)
continue;
ASSERT3U(bp->blk_birth, ==, 0);
}
#endif
ASSERT(all || blocks_freed == 0 || db->db_last_dirty);
return (all ? ALL : blocks_freed);
}
/*
* free_range: Traverse the indicated range of the provided file
* and "free" all the blocks contained there.
*/
static void
dnode_sync_free_range(dnode_t *dn, uint64_t blkid, uint64_t nblks, dmu_tx_t *tx)
{
blkptr_t *bp = dn->dn_phys->dn_blkptr;
dmu_buf_impl_t *db;
int trunc, start, end, shift, i, err;
int dnlevel = dn->dn_phys->dn_nlevels;
if (blkid > dn->dn_phys->dn_maxblkid)
return;
ASSERT(dn->dn_phys->dn_maxblkid < UINT64_MAX);
trunc = blkid + nblks > dn->dn_phys->dn_maxblkid;
if (trunc)
nblks = dn->dn_phys->dn_maxblkid - blkid + 1;
/* There are no indirect blocks in the object */
if (dnlevel == 1) {
if (blkid >= dn->dn_phys->dn_nblkptr) {
/* this range was never made persistent */
return;
}
ASSERT3U(blkid + nblks, <=, dn->dn_phys->dn_nblkptr);
(void) free_blocks(dn, bp + blkid, nblks, tx);
if (trunc) {
uint64_t off = (dn->dn_phys->dn_maxblkid + 1) *
(dn->dn_phys->dn_datablkszsec << SPA_MINBLOCKSHIFT);
dn->dn_phys->dn_maxblkid = (blkid ? blkid - 1 : 0);
ASSERT(off < dn->dn_phys->dn_maxblkid ||
dn->dn_phys->dn_maxblkid == 0 ||
dnode_next_offset(dn, 0, &off, 1, 1, 0) != 0);
}
return;
}
shift = (dnlevel - 1) * (dn->dn_phys->dn_indblkshift - SPA_BLKPTRSHIFT);
start = blkid >> shift;
ASSERT(start < dn->dn_phys->dn_nblkptr);
end = (blkid + nblks - 1) >> shift;
bp += start;
for (i = start; i <= end; i++, bp++) {
if (BP_IS_HOLE(bp))
continue;
rw_enter(&dn->dn_struct_rwlock, RW_READER);
err = dbuf_hold_impl(dn, dnlevel-1, i, TRUE, FTAG, &db);
ASSERT3U(err, ==, 0);
rw_exit(&dn->dn_struct_rwlock);
if (free_children(db, blkid, nblks, trunc, tx) == ALL) {
ASSERT3P(db->db_blkptr, ==, bp);
(void) free_blocks(dn, bp, 1, tx);
}
dbuf_rele(db, FTAG);
}
if (trunc) {
uint64_t off = (dn->dn_phys->dn_maxblkid + 1) *
(dn->dn_phys->dn_datablkszsec << SPA_MINBLOCKSHIFT);
dn->dn_phys->dn_maxblkid = (blkid ? blkid - 1 : 0);
ASSERT(off < dn->dn_phys->dn_maxblkid ||
dn->dn_phys->dn_maxblkid == 0 ||
dnode_next_offset(dn, 0, &off, 1, 1, 0) != 0);
}
}
/*
* Try to kick all the dnodes dbufs out of the cache...
*/
void
dnode_evict_dbufs(dnode_t *dn)
{
int progress;
int pass = 0;
do {
dmu_buf_impl_t *db, marker;
int evicting = FALSE;
progress = FALSE;
mutex_enter(&dn->dn_dbufs_mtx);
list_insert_tail(&dn->dn_dbufs, &marker);
db = list_head(&dn->dn_dbufs);
for (; db != ▮ db = list_head(&dn->dn_dbufs)) {
list_remove(&dn->dn_dbufs, db);
list_insert_tail(&dn->dn_dbufs, db);
ASSERT3P(db->db_dnode, ==, dn);
mutex_enter(&db->db_mtx);
if (db->db_state == DB_EVICTING) {
progress = TRUE;
evicting = TRUE;
mutex_exit(&db->db_mtx);
} else if (refcount_is_zero(&db->db_holds)) {
progress = TRUE;
dbuf_clear(db); /* exits db_mtx for us */
} else {
mutex_exit(&db->db_mtx);
}
}
list_remove(&dn->dn_dbufs, &marker);
/*
* NB: we need to drop dn_dbufs_mtx between passes so
* that any DB_EVICTING dbufs can make progress.
* Ideally, we would have some cv we could wait on, but
* since we don't, just wait a bit to give the other
* thread a chance to run.
*/
mutex_exit(&dn->dn_dbufs_mtx);
if (evicting)
delay(1);
pass++;
ASSERT(pass < 100); /* sanity check */
} while (progress);
rw_enter(&dn->dn_struct_rwlock, RW_WRITER);
if (dn->dn_bonus && refcount_is_zero(&dn->dn_bonus->db_holds)) {
mutex_enter(&dn->dn_bonus->db_mtx);
dbuf_evict(dn->dn_bonus);
dn->dn_bonus = NULL;
}
rw_exit(&dn->dn_struct_rwlock);
}
static void
dnode_undirty_dbufs(list_t *list)
{
dbuf_dirty_record_t *dr;
while (dr = list_head(list)) {
dmu_buf_impl_t *db = dr->dr_dbuf;
uint64_t txg = dr->dr_txg;
if (db->db_level != 0)
dnode_undirty_dbufs(&dr->dt.di.dr_children);
mutex_enter(&db->db_mtx);
/* XXX - use dbuf_undirty()? */
list_remove(list, dr);
ASSERT(db->db_last_dirty == dr);
db->db_last_dirty = NULL;
db->db_dirtycnt -= 1;
if (db->db_level == 0) {
ASSERT(db->db_blkid == DB_BONUS_BLKID ||
dr->dt.dl.dr_data == db->db_buf);
dbuf_unoverride(dr);
}
kmem_free(dr, sizeof (dbuf_dirty_record_t));
dbuf_rele_and_unlock(db, (void *)(uintptr_t)txg);
}
}
static void
dnode_sync_free(dnode_t *dn, dmu_tx_t *tx)
{
int txgoff = tx->tx_txg & TXG_MASK;
ASSERT(dmu_tx_is_syncing(tx));
/*
* Our contents should have been freed in dnode_sync() by the
* free range record inserted by the caller of dnode_free().
*/
ASSERT3U(DN_USED_BYTES(dn->dn_phys), ==, 0);
ASSERT(BP_IS_HOLE(dn->dn_phys->dn_blkptr));
dnode_undirty_dbufs(&dn->dn_dirty_records[txgoff]);
dnode_evict_dbufs(dn);
ASSERT3P(list_head(&dn->dn_dbufs), ==, NULL);
/*
* XXX - It would be nice to assert this, but we may still
* have residual holds from async evictions from the arc...
*
* zfs_obj_to_path() also depends on this being
* commented out.
*
* ASSERT3U(refcount_count(&dn->dn_holds), ==, 1);
*/
/* Undirty next bits */
dn->dn_next_nlevels[txgoff] = 0;
dn->dn_next_indblkshift[txgoff] = 0;
dn->dn_next_blksz[txgoff] = 0;
/* ASSERT(blkptrs are zero); */
ASSERT(dn->dn_phys->dn_type != DMU_OT_NONE);
ASSERT(dn->dn_type != DMU_OT_NONE);
ASSERT(dn->dn_free_txg > 0);
if (dn->dn_allocated_txg != dn->dn_free_txg)
dbuf_will_dirty(dn->dn_dbuf, tx);
bzero(dn->dn_phys, sizeof (dnode_phys_t));
mutex_enter(&dn->dn_mtx);
dn->dn_type = DMU_OT_NONE;
dn->dn_maxblkid = 0;
dn->dn_allocated_txg = 0;
dn->dn_free_txg = 0;
mutex_exit(&dn->dn_mtx);
ASSERT(dn->dn_object != DMU_META_DNODE_OBJECT);
dnode_rele(dn, (void *)(uintptr_t)tx->tx_txg);
/*
* Now that we've released our hold, the dnode may
* be evicted, so we musn't access it.
*/
}
/*
* Write out the dnode's dirty buffers.
*/
void
dnode_sync(dnode_t *dn, dmu_tx_t *tx)
{
free_range_t *rp;
dnode_phys_t *dnp = dn->dn_phys;
int txgoff = tx->tx_txg & TXG_MASK;
list_t *list = &dn->dn_dirty_records[txgoff];
static const dnode_phys_t zerodn = { 0 };
ASSERT(dmu_tx_is_syncing(tx));
ASSERT(dnp->dn_type != DMU_OT_NONE || dn->dn_allocated_txg);
ASSERT(dnp->dn_type != DMU_OT_NONE ||
bcmp(dnp, &zerodn, DNODE_SIZE) == 0);
DNODE_VERIFY(dn);
ASSERT(dn->dn_dbuf == NULL || arc_released(dn->dn_dbuf->db_buf));
if (dmu_objset_userused_enabled(dn->dn_objset) &&
!DMU_OBJECT_IS_SPECIAL(dn->dn_object)) {
ASSERT(dn->dn_oldphys == NULL);
dn->dn_oldphys = zio_buf_alloc(sizeof (dnode_phys_t));
*dn->dn_oldphys = *dn->dn_phys; /* struct assignment */
dn->dn_phys->dn_flags |= DNODE_FLAG_USERUSED_ACCOUNTED;
} else {
/* Once we account for it, we should always account for it. */
ASSERT(!(dn->dn_phys->dn_flags &
DNODE_FLAG_USERUSED_ACCOUNTED));
}
mutex_enter(&dn->dn_mtx);
if (dn->dn_allocated_txg == tx->tx_txg) {
/* The dnode is newly allocated or reallocated */
if (dnp->dn_type == DMU_OT_NONE) {
/* this is a first alloc, not a realloc */
dnp->dn_nlevels = 1;
dnp->dn_nblkptr = dn->dn_nblkptr;
}
dnp->dn_type = dn->dn_type;
dnp->dn_bonustype = dn->dn_bonustype;
dnp->dn_bonuslen = dn->dn_bonuslen;
}
ASSERT(dnp->dn_nlevels > 1 ||
BP_IS_HOLE(&dnp->dn_blkptr[0]) ||
BP_GET_LSIZE(&dnp->dn_blkptr[0]) ==
dnp->dn_datablkszsec << SPA_MINBLOCKSHIFT);
if (dn->dn_next_blksz[txgoff]) {
ASSERT(P2PHASE(dn->dn_next_blksz[txgoff],
SPA_MINBLOCKSIZE) == 0);
ASSERT(BP_IS_HOLE(&dnp->dn_blkptr[0]) ||
dn->dn_maxblkid == 0 || list_head(list) != NULL ||
dn->dn_next_blksz[txgoff] >> SPA_MINBLOCKSHIFT ==
dnp->dn_datablkszsec);
dnp->dn_datablkszsec =
dn->dn_next_blksz[txgoff] >> SPA_MINBLOCKSHIFT;
dn->dn_next_blksz[txgoff] = 0;
}
if (dn->dn_next_bonuslen[txgoff]) {
if (dn->dn_next_bonuslen[txgoff] == DN_ZERO_BONUSLEN)
dnp->dn_bonuslen = 0;
else
dnp->dn_bonuslen = dn->dn_next_bonuslen[txgoff];
ASSERT(dnp->dn_bonuslen <= DN_MAX_BONUSLEN);
dn->dn_next_bonuslen[txgoff] = 0;
}
if (dn->dn_next_indblkshift[txgoff]) {
ASSERT(dnp->dn_nlevels == 1);
dnp->dn_indblkshift = dn->dn_next_indblkshift[txgoff];
dn->dn_next_indblkshift[txgoff] = 0;
}
/*
* Just take the live (open-context) values for checksum and compress.
* Strictly speaking it's a future leak, but nothing bad happens if we
* start using the new checksum or compress algorithm a little early.
*/
dnp->dn_checksum = dn->dn_checksum;
dnp->dn_compress = dn->dn_compress;
mutex_exit(&dn->dn_mtx);
/* process all the "freed" ranges in the file */
while (rp = avl_last(&dn->dn_ranges[txgoff])) {
dnode_sync_free_range(dn, rp->fr_blkid, rp->fr_nblks, tx);
/* grab the mutex so we don't race with dnode_block_freed() */
mutex_enter(&dn->dn_mtx);
avl_remove(&dn->dn_ranges[txgoff], rp);
mutex_exit(&dn->dn_mtx);
kmem_free(rp, sizeof (free_range_t));
}
if (dn->dn_free_txg > 0 && dn->dn_free_txg <= tx->tx_txg) {
dnode_sync_free(dn, tx);
return;
}
if (dn->dn_next_nblkptr[txgoff]) {
/* this should only happen on a realloc */
ASSERT(dn->dn_allocated_txg == tx->tx_txg);
if (dn->dn_next_nblkptr[txgoff] > dnp->dn_nblkptr) {
/* zero the new blkptrs we are gaining */
bzero(dnp->dn_blkptr + dnp->dn_nblkptr,
sizeof (blkptr_t) *
(dn->dn_next_nblkptr[txgoff] - dnp->dn_nblkptr));
#ifdef ZFS_DEBUG
} else {
int i;
ASSERT(dn->dn_next_nblkptr[txgoff] < dnp->dn_nblkptr);
/* the blkptrs we are losing better be unallocated */
for (i = dn->dn_next_nblkptr[txgoff];
i < dnp->dn_nblkptr; i++)
ASSERT(BP_IS_HOLE(&dnp->dn_blkptr[i]));
#endif
}
mutex_enter(&dn->dn_mtx);
dnp->dn_nblkptr = dn->dn_next_nblkptr[txgoff];
dn->dn_next_nblkptr[txgoff] = 0;
mutex_exit(&dn->dn_mtx);
}
if (dn->dn_next_nlevels[txgoff]) {
dnode_increase_indirection(dn, tx);
dn->dn_next_nlevels[txgoff] = 0;
}
dbuf_sync_list(list, tx);
if (!DMU_OBJECT_IS_SPECIAL(dn->dn_object)) {
ASSERT3P(list_head(list), ==, NULL);
dnode_rele(dn, (void *)(uintptr_t)tx->tx_txg);
}
/*
* Although we have dropped our reference to the dnode, it
* can't be evicted until its written, and we haven't yet
* initiated the IO for the dnode's dbuf.
*/
}
| 27.964561 | 80 | 0.656896 | [
"object"
] |
fa2a17ed401712c6c8d59d2b421008555ad49603 | 5,763 | h | C | COGengine/src/Behaviors/SteeringBehavior.h | dodoknight/CogEngine | fda1193c2d1258ba9780e1025933d33a8dce2284 | [
"MIT"
] | 3 | 2016-06-01T10:14:00.000Z | 2016-10-11T15:53:45.000Z | COGengine/src/Behaviors/SteeringBehavior.h | dormantor/ofxCogEngine | fda1193c2d1258ba9780e1025933d33a8dce2284 | [
"MIT"
] | null | null | null | COGengine/src/Behaviors/SteeringBehavior.h | dormantor/ofxCogEngine | fda1193c2d1258ba9780e1025933d33a8dce2284 | [
"MIT"
] | 1 | 2020-08-15T17:01:00.000Z | 2020-08-15T17:01:00.000Z | #pragma once
#include "Behavior.h"
#include "Dynamics.h"
#include "Path.h"
#include "SteeringMath.h"
namespace Cog {
/**
* Base class for all steering behaviors
* Steering behavior aim to help autonomous characters move in a realistic manner, by using simple forces
* For more informations, see http://gamedevelopment.tutsplus.com/series/understanding-steering-behaviors--gamedev-12732
*/
class SteeringBehavior : public Behavior {
protected:
SteeringMath steeringMath;
/**
* Clamps angle to the interval <0,360>
*/
float ClampAngle(float x);
/**
* Sets rotation direction according to the actual movement forces
*/
void SetRotationDirection(Dynamics* dynamics, Trans& transform, ofVec2f destination, float maxAcceleration, uint64 delta);
public:
SteeringBehavior() {
}
virtual void Update(const uint64 delta, const uint64 absolute) {
}
};
/**
* Seek behavior: accelerates against destination point
* Involves two forces: desired velocity and steering
*/
class SeekBehavior : public SteeringBehavior {
private:
float maxAcceleration = 0;
StrId forceId;
StrId seekDest = StrId(ATTR_STEERING_BEH_DEST);
StrId attrMovement = StrId(ATTR_MOVEMENT);
public:
SeekBehavior(float maxAcceleration) :maxAcceleration(maxAcceleration){
forceId = StrId(this->GetId());
}
void OnStart();
virtual void Update(const uint64 delta, const uint64 absolute);
};
/**
* Arrive behavior: the same as seek with the exception that it prevents
* the character from moving through the target; the character slows down as
* it approaches the destination
*/
class ArriveBehavior : public SteeringBehavior {
private:
float decelerationSpeed = 0;
float rotationSpeed = 0;
// point of tolerance that indicates how far from
// the destination point can the characted stop
float pointTolerance = 0;
StrId forceId;
StrId seekDest = StrId(ATTR_STEERING_BEH_DEST);
StrId attrMovement = StrId(ATTR_MOVEMENT);
public:
ArriveBehavior(float decelerationSpeed, float rotationSpeed, float pointTolerance) :
decelerationSpeed(decelerationSpeed),
rotationSpeed(rotationSpeed),
pointTolerance(pointTolerance){
forceId = StrId(this->GetId());
}
void OnStart();
virtual void Update(const uint64 delta, const uint64 absolute);
};
/**
* Flee behavior, opposite of seek: characted flees away from the destination
*/
class FleeBehavior : public SteeringBehavior {
private:
float maxAcceleration = 0;
float fleeDistance = 0;
StrId forceId;
StrId seekDest = StrId(ATTR_STEERING_BEH_DEST);
StrId attrMovement = StrId(ATTR_MOVEMENT);
public:
FleeBehavior(float maxAcceleration, float fleeDistance) :maxAcceleration(maxAcceleration),
fleeDistance(fleeDistance){
forceId = StrId(this->GetId());
}
void OnStart();
virtual void Update(const uint64 delta, const uint64 absolute);
};
/**
* Follow behavior - character follows the path, consisting of an array of checkpoints
*/
class FollowBehavior : public SteeringBehavior {
private:
Path* path;
int currentPathIndex = 0;
float maxRadialAcceleration = 0;
// indicates how far from checkpoint may the character go
float pointTolerance = 0;
// indicates how far from the last checkpoint may the character stop
float finalPointTolerance = 0;
StrId forceId;
StrId attrMovement = StrId(ATTR_MOVEMENT);
bool pathFinished = false;
public:
float maxAcceleration = 0;
float forceStrength = 1;
/**
* Creates a new follow behavior
* @param path path to follow
* @param maxAcceleration maximum acceleration
* @param maxRadialAcceleration maximum radial acceleration
* @param pointTolerance indicates how far from checkpoint may the character go
* @param finalPointTolerance indicates how far from the last checkpoint may the character stop
*/
FollowBehavior(Path* path, float maxAcceleration, float maxRadialAcceleration, float pointTolerance, float finalPointTolerance)
: path(path), maxAcceleration(maxAcceleration), maxRadialAcceleration(maxRadialAcceleration),
pointTolerance(pointTolerance), finalPointTolerance(finalPointTolerance) {
forceId = StrId(this->GetId());
}
void ResetPath(Path* path) {
this->path = path;
this->currentPathIndex = 0;
this->pathFinished = false;
}
bool PathFinished() const {
return pathFinished || path->GetSegments().size() < 2;
}
void OnStart();
virtual void Update(const uint64 delta, const uint64 absolute);
};
/**
* Behavior that produces a realistic casual movement which will make the player think
* that the character is really alive and walking around
*
* The wandering is provided by projecting a circle in front of the characted; the movement
* dependes on the angle between character and a point on the circle which moves along
* the circumference randomly
*/
class WanderBehavior : public SteeringBehavior {
private:
// radius of the wandering circle
float wanderRadius = 0;
// distance of the wandering circle
float wanderDistance = 0;
// randomness of the point on the circle
float wanderJitter = 0;
StrId forceId;
StrId wanderDest = StrId(ATTR_STEERING_BEH_WANDER);
StrId attrMovement = StrId(ATTR_MOVEMENT);
public:
/**
* Creates a new wander behavior
* @param wanderRadius radius of the wandering circle
* @param wanderDistance distance of the wandering circle
* @param wanderJitter randomness of the point on the circle
*/
WanderBehavior(float wanderRadius, float wanderDistance, float wanderJitter) :
wanderRadius(wanderRadius), wanderDistance(wanderDistance), wanderJitter(wanderJitter){
forceId = StrId(this->GetId());
}
void OnStart();
virtual void Update(const uint64 delta, const uint64 absolute);
};
}// namespace | 29.403061 | 129 | 0.745792 | [
"transform"
] |
fa2b80ee518005ea7dc5ddf9202a2e318fc49f16 | 29,765 | c | C | GraphBLAS/Source/GB_AxB_saxpy3_slice_balanced.c | ByLiZhao/SuiteSparse | 880be9f60c2fca519117159d954f86783b252ed3 | [
"Apache-2.0"
] | 27 | 2016-10-25T08:07:32.000Z | 2022-02-06T20:20:59.000Z | GraphBLAS/Source/GB_AxB_saxpy3_slice_balanced.c | ByLiZhao/SuiteSparse | 880be9f60c2fca519117159d954f86783b252ed3 | [
"Apache-2.0"
] | 2 | 2020-01-28T18:47:50.000Z | 2021-09-09T17:56:52.000Z | GraphBLAS/Source/GB_AxB_saxpy3_slice_balanced.c | ByLiZhao/SuiteSparse | 880be9f60c2fca519117159d954f86783b252ed3 | [
"Apache-2.0"
] | 10 | 2016-03-02T04:15:56.000Z | 2021-03-31T03:20:46.000Z | //------------------------------------------------------------------------------
// GB_AxB_saxpy3_slice_balanced: construct balanced tasks for GB_AxB_saxpy3
//------------------------------------------------------------------------------
// SuiteSparse:GraphBLAS, Timothy A. Davis, (c) 2017-2021, All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
//------------------------------------------------------------------------------
// If the mask is present but must be discarded, this function returns
// GrB_NO_VALUE, to indicate that the analysis was terminated early.
#include "GB_AxB_saxpy3.h"
// control parameters for generating parallel tasks
#define GB_NTASKS_PER_THREAD 2
#define GB_COSTLY 1.2
#define GB_FINE_WORK 2
#define GB_MWORK_ALPHA 0.01
#define GB_MWORK_BETA 0.10
#define GB_FREE_WORK \
{ \
GB_WERK_POP (Fine_fl, int64_t) ; \
GB_WERK_POP (Fine_slice, int64_t) ; \
GB_WERK_POP (Coarse_Work, int64_t) ; \
GB_WERK_POP (Coarse_initial, int64_t) ; \
}
#define GB_FREE_ALL \
{ \
GB_FREE_WORK ; \
GB_FREE_WERK (&SaxpyTasks, SaxpyTasks_size) ; \
}
//------------------------------------------------------------------------------
// GB_hash_table_size
//------------------------------------------------------------------------------
// flmax is the max flop count for computing A*B(:,j), for any vector j that
// this task computes. If the mask M is present, flmax also includes the
// number of entries in M(:,j). GB_hash_table_size determines the hash table
// size for this task, which is twice the smallest power of 2 larger than
// flmax. If flmax is large enough, the hash_size is returned as cvlen, so
// that Gustavson's method will be used instead of the Hash method.
// By default, Gustavson vs Hash is selected automatically. AxB_method can be
// selected via the descriptor or a global setting, as the non-default
// GxB_AxB_GUSTAVSON or GxB_AxB_HASH settings, to enforce the selection of
// either of those methods. However, if Hash is selected but the hash table
// equals or exceeds cvlen, then Gustavson's method is used instead.
static inline int64_t GB_hash_table_size
(
int64_t flmax, // max flop count for any vector computed by this task
int64_t cvlen, // vector length of C
const GrB_Desc_Value AxB_method // Default, Gustavson, or Hash
)
{
int64_t hash_size ;
if (AxB_method == GxB_AxB_GUSTAVSON || flmax >= cvlen/2)
{
//----------------------------------------------------------------------
// use Gustavson if selected explicitly or if flmax is large
//----------------------------------------------------------------------
hash_size = cvlen ;
}
else
{
//----------------------------------------------------------------------
// flmax is small; consider hash vs Gustavson
//----------------------------------------------------------------------
// hash_size = 2 * (smallest power of 2 >= flmax)
hash_size = ((uint64_t) 2) << (GB_FLOOR_LOG2 (flmax) + 1) ;
bool use_Gustavson ;
if (AxB_method == GxB_AxB_HASH)
{
// always use Hash method, unless the hash_size >= cvlen
use_Gustavson = (hash_size >= cvlen) ;
}
else
{
// default: auto selection:
// use Gustavson's method if hash_size is too big
use_Gustavson = (hash_size >= cvlen/12) ;
}
if (use_Gustavson)
{
hash_size = cvlen ;
}
}
//--------------------------------------------------------------------------
// return result
//--------------------------------------------------------------------------
return (hash_size) ;
}
//------------------------------------------------------------------------------
// GB_create_coarse_task: create a single coarse task
//------------------------------------------------------------------------------
// Compute the max flop count for any vector in a coarse task, determine the
// hash table size, and construct the coarse task.
static inline void GB_create_coarse_task
(
int64_t kfirst, // coarse task consists of vectors kfirst:klast
int64_t klast,
GB_saxpy3task_struct *SaxpyTasks,
int taskid, // taskid for this coarse task
int64_t *Bflops, // size bnvec; cum sum of flop counts for vectors of B
int64_t cvlen, // vector length of B and C
double chunk,
int nthreads_max,
int64_t *Coarse_Work, // workspace for parallel reduction for flop count
const GrB_Desc_Value AxB_method // Default, Gustavson, or Hash
)
{
//--------------------------------------------------------------------------
// find the max # of flops for any vector in this task
//--------------------------------------------------------------------------
int64_t nk = klast - kfirst + 1 ;
int nth = GB_nthreads (nk, chunk, nthreads_max) ;
// each thread finds the max flop count for a subset of the vectors
int tid ;
#pragma omp parallel for num_threads(nth) schedule(static)
for (tid = 0 ; tid < nth ; tid++)
{
int64_t my_flmax = 1, istart, iend ;
GB_PARTITION (istart, iend, nk, tid, nth) ;
for (int64_t i = istart ; i < iend ; i++)
{
int64_t kk = kfirst + i ;
int64_t fl = Bflops [kk+1] - Bflops [kk] ;
my_flmax = GB_IMAX (my_flmax, fl) ;
}
Coarse_Work [tid] = my_flmax ;
}
// combine results from each thread
int64_t flmax = 1 ;
for (tid = 0 ; tid < nth ; tid++)
{
flmax = GB_IMAX (flmax, Coarse_Work [tid]) ;
}
// check the parallel computation
#ifdef GB_DEBUG
int64_t flmax2 = 1 ;
for (int64_t kk = kfirst ; kk <= klast ; kk++)
{
int64_t fl = Bflops [kk+1] - Bflops [kk] ;
flmax2 = GB_IMAX (flmax2, fl) ;
}
ASSERT (flmax == flmax2) ;
#endif
//--------------------------------------------------------------------------
// define the coarse task
//--------------------------------------------------------------------------
SaxpyTasks [taskid].start = kfirst ;
SaxpyTasks [taskid].end = klast ;
SaxpyTasks [taskid].vector = -1 ;
SaxpyTasks [taskid].hsize = GB_hash_table_size (flmax, cvlen, AxB_method) ;
SaxpyTasks [taskid].Hi = NULL ; // assigned later
SaxpyTasks [taskid].Hf = NULL ; // assigned later
SaxpyTasks [taskid].Hx = NULL ; // assigned later
SaxpyTasks [taskid].my_cjnz = 0 ; // for fine tasks only
SaxpyTasks [taskid].leader = taskid ;
SaxpyTasks [taskid].team_size = 1 ;
}
//------------------------------------------------------------------------------
// GB_AxB_saxpy3_slice_balanced: create balanced tasks for saxpy3
//------------------------------------------------------------------------------
GrB_Info GB_AxB_saxpy3_slice_balanced
(
// inputs
GrB_Matrix C, // output matrix
const GrB_Matrix M, // optional mask matrix
const bool Mask_comp, // if true, use !M
const GrB_Matrix A, // input matrix A
const GrB_Matrix B, // input matrix B
GrB_Desc_Value AxB_method, // Default, Gustavson, or Hash
// outputs
GB_saxpy3task_struct **SaxpyTasks_handle,
size_t *SaxpyTasks_size_handle,
bool *apply_mask, // if true, apply M during sapxy3
bool *M_packed_in_place, // if true, use M in-place
int *ntasks, // # of tasks created (coarse and fine)
int *nfine, // # of fine tasks created
int *nthreads, // # of threads to use
GB_Context Context
)
{
//--------------------------------------------------------------------------
// check inputs
//--------------------------------------------------------------------------
GrB_Info info ;
(*apply_mask) = false ;
(*M_packed_in_place) = false ;
(*ntasks) = 0 ;
(*nfine) = 0 ;
(*nthreads) = 0 ;
ASSERT_MATRIX_OK_OR_NULL (M, "M for saxpy3_slice_balanced A*B", GB0) ;
ASSERT (!GB_PENDING (M)) ;
ASSERT (GB_JUMBLED_OK (M)) ;
ASSERT (!GB_ZOMBIES (M)) ;
ASSERT_MATRIX_OK (A, "A for saxpy3_slice_balanced A*B", GB0) ;
ASSERT (!GB_PENDING (A)) ;
ASSERT (GB_JUMBLED_OK (A)) ;
ASSERT (!GB_ZOMBIES (A)) ;
ASSERT_MATRIX_OK (B, "B for saxpy3_slice_balanced A*B", GB0) ;
ASSERT (!GB_PENDING (B)) ;
ASSERT (GB_JUMBLED_OK (B)) ;
ASSERT (!GB_ZOMBIES (B)) ;
//--------------------------------------------------------------------------
// determine the # of threads to use
//--------------------------------------------------------------------------
GB_GET_NTHREADS_MAX (nthreads_max, chunk, Context) ;
//--------------------------------------------------------------------------
// define result and workspace
//--------------------------------------------------------------------------
GB_saxpy3task_struct *restrict SaxpyTasks = NULL ;
size_t SaxpyTasks_size = 0 ;
GB_WERK_DECLARE (Coarse_initial, int64_t) ; // initial coarse tasks
GB_WERK_DECLARE (Coarse_Work, int64_t) ; // workspace for flop counts
GB_WERK_DECLARE (Fine_slice, int64_t) ;
GB_WERK_DECLARE (Fine_fl, int64_t) ; // size max(nnz(B(:,j)))
//--------------------------------------------------------------------------
// get A, and B
//--------------------------------------------------------------------------
const int64_t *restrict Ap = A->p ;
const int64_t *restrict Ah = A->h ;
const int64_t avlen = A->vlen ;
const int64_t anvec = A->nvec ;
const bool A_is_hyper = GB_IS_HYPERSPARSE (A) ;
const int64_t *restrict Bp = B->p ;
const int64_t *restrict Bh = B->h ;
const int8_t *restrict Bb = B->b ;
const int64_t *restrict Bi = B->i ;
const int64_t bvdim = B->vdim ;
const int64_t bnz = GB_NNZ_HELD (B) ;
const int64_t bnvec = B->nvec ;
const int64_t bvlen = B->vlen ;
const bool B_is_hyper = GB_IS_HYPERSPARSE (B) ;
int64_t cvlen = avlen ;
int64_t cvdim = bvdim ;
//--------------------------------------------------------------------------
// compute flop counts for each vector of B and C
//--------------------------------------------------------------------------
int64_t Mwork = 0 ;
int64_t *restrict Bflops = C->p ; // use C->p as workspace for Bflops
GB_OK (GB_AxB_saxpy3_flopcount (&Mwork, Bflops, M, Mask_comp, A, B,
Context)) ;
int64_t total_flops = Bflops [bnvec] ;
double axbflops = total_flops - Mwork ;
GBURBLE ("axbwork %g ", axbflops) ;
if (Mwork > 0) GBURBLE ("mwork %g ", (double) Mwork) ;
//--------------------------------------------------------------------------
// determine if the mask M should be applied, or done later
//--------------------------------------------------------------------------
if (M == NULL)
{
//----------------------------------------------------------------------
// M is not present
//----------------------------------------------------------------------
(*apply_mask) = false ;
}
else if (GB_is_packed (M))
{
//----------------------------------------------------------------------
// M is present and full, bitmap, or sparse/hyper with all entries
//----------------------------------------------------------------------
// Choose all-hash or all-Gustavson tasks, and apply M during saxpy3.
(*apply_mask) = true ;
// The work for M has not yet been added Bflops.
// Each vector M(:,j) has cvlen entries.
Mwork = cvlen * cvdim ;
if (!(AxB_method == GxB_AxB_HASH || AxB_method == GxB_AxB_GUSTAVSON))
{
if (axbflops < (double) Mwork * GB_MWORK_BETA)
{
// The mask is too costly to scatter into the Hf workspace.
// Leave it in place and use all-hash tasks.
AxB_method = GxB_AxB_HASH ;
}
else
{
// Scatter M into Hf and use all-Gustavson tasks.
AxB_method = GxB_AxB_GUSTAVSON ;
}
}
if (AxB_method == GxB_AxB_HASH)
{
// Use the hash method for all tasks (except for those tasks which
// require a hash table size >= cvlen; those tasks use Gustavson).
// Do not scatter the mask into the Hf hash workspace. The work
// for the mask is not accounted for in Bflops, so the hash tables
// can be small.
(*M_packed_in_place) = true ;
GBURBLE ("(use packed mask in-place) ") ;
}
else
{
// Use the Gustavson method for all tasks, and scatter M into the
// fine Gustavson workspace. The work for M is not yet in the
// Bflops cumulative sum. Add it now.
ASSERT (AxB_method == GxB_AxB_GUSTAVSON)
int nth = GB_nthreads (bnvec, chunk, nthreads_max) ;
int64_t kk ;
#pragma omp parallel for num_threads(nth) schedule(static)
for (kk = 0 ; kk <= bnvec ; kk++)
{
Bflops [kk] += cvlen * (kk+1) ;
}
total_flops = Bflops [bnvec] ;
GBURBLE ("(use packed mask) ") ;
}
}
else if (axbflops < ((double) Mwork * GB_MWORK_ALPHA))
{
//----------------------------------------------------------------------
// M is costly to use; apply it after C=A*B
//----------------------------------------------------------------------
// Do not use M during the computation of A*B. Instead, compute C=A*B
// and then apply the mask later. Tell the caller that the mask should
// not be applied, so that it will be applied later in GB_mxm.
(*apply_mask) = false ;
GBURBLE ("(discard mask) ") ;
GB_FREE_ALL ;
return (GrB_NO_VALUE) ;
}
else
{
//----------------------------------------------------------------------
// use M during saxpy3
//----------------------------------------------------------------------
(*apply_mask) = true ;
GBURBLE ("(use mask) ") ;
}
//--------------------------------------------------------------------------
// determine # of threads and # of initial coarse tasks
//--------------------------------------------------------------------------
(*nthreads) = GB_nthreads ((double) total_flops, chunk, nthreads_max) ;
int ntasks_initial = ((*nthreads) == 1) ? 1 :
(GB_NTASKS_PER_THREAD * (*nthreads)) ;
//--------------------------------------------------------------------------
// give preference to Gustavson when using few threads
//--------------------------------------------------------------------------
if ((*nthreads) <= 8 &&
(!(AxB_method == GxB_AxB_HASH || AxB_method == GxB_AxB_GUSTAVSON)))
{
// Unless a specific method has been explicitly requested, see if
// Gustavson should be used with a small number of threads.
// Matrix-vector has a maximum intensity of 1, so this heuristic only
// applies to GrB_mxm.
double abnz = GB_NNZ (A) + GB_NNZ (B) + 1 ;
double workspace = (double) ntasks_initial * (double) cvlen ;
double intensity = total_flops / abnz ;
GBURBLE ("(intensity: %0.3g workspace/(nnz(A)+nnz(B)): %0.3g",
intensity, workspace / abnz) ;
if (intensity >= 8 && workspace < abnz)
{
// work intensity is large, and Gustvason workspace is modest;
// use Gustavson for all tasks
AxB_method = GxB_AxB_GUSTAVSON ;
GBURBLE (": select Gustvason) ") ;
}
else
{
// use default task creation: mix of Hash and Gustavson
GBURBLE (") ") ;
}
}
//--------------------------------------------------------------------------
// determine target task size
//--------------------------------------------------------------------------
double target_task_size = ((double) total_flops) / ntasks_initial ;
target_task_size = GB_IMAX (target_task_size, chunk) ;
double target_fine_size = target_task_size / GB_FINE_WORK ;
target_fine_size = GB_IMAX (target_fine_size, chunk) ;
//--------------------------------------------------------------------------
// determine # of parallel tasks
//--------------------------------------------------------------------------
int ncoarse = 0 ; // # of coarse tasks
int max_bjnz = 0 ; // max (nnz (B (:,j))) of fine tasks
// FUTURE: also use ultra-fine tasks that compute A(i1:i2,k)*B(k,j)
if (ntasks_initial > 1)
{
//----------------------------------------------------------------------
// construct initial coarse tasks
//----------------------------------------------------------------------
GB_WERK_PUSH (Coarse_initial, ntasks_initial + 1, int64_t) ;
if (Coarse_initial == NULL)
{
// out of memory
GB_FREE_ALL ;
return (GrB_OUT_OF_MEMORY) ;
}
GB_pslice (Coarse_initial, Bflops, bnvec, ntasks_initial, true) ;
//----------------------------------------------------------------------
// split the work into coarse and fine tasks
//----------------------------------------------------------------------
for (int taskid = 0 ; taskid < ntasks_initial ; taskid++)
{
// get the initial coarse task
int64_t kfirst = Coarse_initial [taskid] ;
int64_t klast = Coarse_initial [taskid+1] ;
int64_t task_ncols = klast - kfirst ;
int64_t task_flops = Bflops [klast] - Bflops [kfirst] ;
if (task_ncols == 0)
{
// This coarse task is empty, having been squeezed out by
// costly vectors in adjacent coarse tasks.
}
else if (task_flops > 2 * GB_COSTLY * target_task_size)
{
// This coarse task is too costly, because it contains one or
// more costly vectors. Split its vectors into a mixture of
// coarse and fine tasks.
int64_t kcoarse_start = kfirst ;
for (int64_t kk = kfirst ; kk < klast ; kk++)
{
// jflops = # of flops to compute a single vector A*B(:,j)
// where j == GBH (Bh, kk)
double jflops = Bflops [kk+1] - Bflops [kk] ;
// bjnz = nnz (B (:,j))
int64_t bjnz = (Bp == NULL) ? bvlen : (Bp [kk+1] - Bp [kk]);
if (jflops > GB_COSTLY * target_task_size && bjnz > 1)
{
// A*B(:,j) is costly; split it into 2 or more fine
// tasks. First flush the prior coarse task, if any.
if (kcoarse_start < kk)
{
// vectors kcoarse_start to kk-1 form a single
// coarse task
ncoarse++ ;
}
// next coarse task (if any) starts at kk+1
kcoarse_start = kk+1 ;
// vectors kk will be split into multiple fine tasks
max_bjnz = GB_IMAX (max_bjnz, bjnz) ;
int team_size = ceil (jflops / target_fine_size) ;
(*nfine) += team_size ;
}
}
// flush the last coarse task, if any
if (kcoarse_start < klast)
{
// vectors kcoarse_start to klast-1 form a single
// coarse task
ncoarse++ ;
}
}
else
{
// This coarse task is OK as-is.
ncoarse++ ;
}
}
}
else
{
//----------------------------------------------------------------------
// entire computation in a single fine or coarse task
//----------------------------------------------------------------------
if (bnvec == 1)
{
// If B is a single vector, and is computed by a single thread,
// then a single fine task is used.
(*nfine) = 1 ;
ncoarse = 0 ;
}
else
{
// One thread uses a single coarse task if B is not a vector.
(*nfine) = 0 ;
ncoarse = 1 ;
}
}
(*ntasks) = ncoarse + (*nfine) ;
//--------------------------------------------------------------------------
// allocate the tasks, and workspace to construct fine tasks
//--------------------------------------------------------------------------
SaxpyTasks = GB_MALLOC_WERK ((*ntasks), GB_saxpy3task_struct,
&SaxpyTasks_size) ;
GB_WERK_PUSH (Coarse_Work, nthreads_max, int64_t) ;
if (max_bjnz > 0)
{
// also allocate workspace to construct fine tasks
GB_WERK_PUSH (Fine_slice, (*ntasks)+1, int64_t) ;
// Fine_fl will only fit on the Werk stack if max_bjnz is small,
// but try anyway, in case it fits. It is placed at the top of the
// Werk stack.
GB_WERK_PUSH (Fine_fl, max_bjnz+1, int64_t) ;
}
if (SaxpyTasks == NULL || Coarse_Work == NULL ||
(max_bjnz > 0 && (Fine_slice == NULL || Fine_fl == NULL)))
{
// out of memory
GB_FREE_ALL ;
return (GrB_OUT_OF_MEMORY) ;
}
// clear SaxpyTasks
memset (SaxpyTasks, 0, SaxpyTasks_size) ;
//--------------------------------------------------------------------------
// create the tasks
//--------------------------------------------------------------------------
if (ntasks_initial > 1)
{
//----------------------------------------------------------------------
// create the coarse and fine tasks
//----------------------------------------------------------------------
int nf = 0 ; // fine tasks have task id 0:nfine-1
int nc = (*nfine) ; // coarse task ids are nfine:ntasks-1
for (int taskid = 0 ; taskid < ntasks_initial ; taskid++)
{
// get the initial coarse task
int64_t kfirst = Coarse_initial [taskid] ;
int64_t klast = Coarse_initial [taskid+1] ;
int64_t task_ncols = klast - kfirst ;
int64_t task_flops = Bflops [klast] - Bflops [kfirst] ;
if (task_ncols == 0)
{
// This coarse task is empty, having been squeezed out by
// costly vectors in adjacent coarse tasks.
}
else if (task_flops > 2 * GB_COSTLY * target_task_size)
{
// This coarse task is too costly, because it contains one or
// more costly vectors. Split its vectors into a mixture of
// coarse and fine tasks.
int64_t kcoarse_start = kfirst ;
for (int64_t kk = kfirst ; kk < klast ; kk++)
{
// jflops = # of flops to compute a single vector A*B(:,j)
double jflops = Bflops [kk+1] - Bflops [kk] ;
// bjnz = nnz (B (:,j))
int64_t bjnz = (Bp == NULL) ? bvlen : (Bp [kk+1] - Bp [kk]);
if (jflops > GB_COSTLY * target_task_size && bjnz > 1)
{
// A*B(:,j) is costly; split it into 2 or more fine
// tasks. First flush the prior coarse task, if any.
if (kcoarse_start < kk)
{
// kcoarse_start:kk-1 form a single coarse task
GB_create_coarse_task (kcoarse_start, kk-1,
SaxpyTasks, nc++, Bflops, cvlen, chunk,
nthreads_max, Coarse_Work, AxB_method) ;
}
// next coarse task (if any) starts at kk+1
kcoarse_start = kk+1 ;
// count the work for each entry B(k,j). Do not
// include the work to scan M(:,j), since that will
// be evenly divided between all tasks in this team.
int64_t pB_start = GBP (Bp, kk, bvlen) ;
int nth = GB_nthreads (bjnz, chunk, nthreads_max) ;
int64_t s ;
#pragma omp parallel for num_threads(nth) \
schedule(static)
for (s = 0 ; s < bjnz ; s++)
{
// get B(k,j)
Fine_fl [s] = 1 ;
int64_t pB = pB_start + s ;
if (!GBB (Bb, pB)) continue ;
int64_t k = GBI (Bi, pB, bvlen) ;
// fl = flop count for just A(:,k)*B(k,j)
int64_t pA, pA_end ;
int64_t pleft = 0 ;
GB_lookup (A_is_hyper, Ah, Ap, avlen, &pleft,
anvec-1, k, &pA, &pA_end) ;
int64_t fl = pA_end - pA ;
Fine_fl [s] = fl ;
ASSERT (fl >= 0) ;
}
// cumulative sum of flops to compute A*B(:,j)
GB_cumsum (Fine_fl, bjnz, NULL, nth, Context) ;
// slice B(:,j) into fine tasks
int team_size = ceil (jflops / target_fine_size) ;
ASSERT (Fine_slice != NULL) ;
GB_pslice (Fine_slice, Fine_fl, bjnz, team_size, false);
// shared hash table for all fine tasks for A*B(:,j)
int64_t hsize =
GB_hash_table_size (jflops, cvlen, AxB_method) ;
// construct the fine tasks for C(:,j)=A*B(:,j)
int leader = nf ;
for (int fid = 0 ; fid < team_size ; fid++)
{
int64_t pstart = Fine_slice [fid] ;
int64_t pend = Fine_slice [fid+1] ;
int64_t fl = Fine_fl [pend] - Fine_fl [pstart] ;
SaxpyTasks [nf].start = pB_start + pstart ;
SaxpyTasks [nf].end = pB_start + pend - 1 ;
SaxpyTasks [nf].vector = kk ;
SaxpyTasks [nf].hsize = hsize ;
SaxpyTasks [nf].Hi = NULL ; // assigned later
SaxpyTasks [nf].Hf = NULL ; // assigned later
SaxpyTasks [nf].Hx = NULL ; // assigned later
SaxpyTasks [nf].my_cjnz = 0 ;
SaxpyTasks [nf].leader = leader ;
SaxpyTasks [nf].team_size = team_size ;
nf++ ;
}
}
}
// flush the last coarse task, if any
if (kcoarse_start < klast)
{
// kcoarse_start:klast-1 form a single coarse task
GB_create_coarse_task (kcoarse_start, klast-1, SaxpyTasks,
nc++, Bflops, cvlen, chunk, nthreads_max,
Coarse_Work, AxB_method) ;
}
}
else
{
// This coarse task is OK as-is.
GB_create_coarse_task (kfirst, klast-1, SaxpyTasks,
nc++, Bflops, cvlen, chunk, nthreads_max,
Coarse_Work, AxB_method) ;
}
}
}
else
{
//----------------------------------------------------------------------
// entire computation in a single fine or coarse task
//----------------------------------------------------------------------
// create a single coarse task: hash or Gustavson
GB_create_coarse_task (0, bnvec-1, SaxpyTasks, 0, Bflops, cvlen, 1, 1,
Coarse_Work, AxB_method) ;
if (bnvec == 1)
{
// convert the single coarse task into a single fine task
SaxpyTasks [0].start = 0 ; // first entry in B(:,0)
SaxpyTasks [0].end = bnz - 1 ; // last entry in B(:,0)
SaxpyTasks [0].vector = 0 ;
}
}
//--------------------------------------------------------------------------
// free workspace and return result
//--------------------------------------------------------------------------
GB_FREE_WORK ;
(*SaxpyTasks_handle) = SaxpyTasks ;
(*SaxpyTasks_size_handle) = SaxpyTasks_size ;
return (GrB_SUCCESS) ;
}
| 39.633822 | 80 | 0.435108 | [
"vector"
] |
fa2de16f40fc7ee5708cafadd1e68ded66637464 | 5,362 | h | C | examples/chip-tool/commands/common/Command.h | hnnajh/connectedhomeip | 249a6c65a820c711d23135d38eec0ab288d3f38f | [
"Apache-2.0"
] | null | null | null | examples/chip-tool/commands/common/Command.h | hnnajh/connectedhomeip | 249a6c65a820c711d23135d38eec0ab288d3f38f | [
"Apache-2.0"
] | null | null | null | examples/chip-tool/commands/common/Command.h | hnnajh/connectedhomeip | 249a6c65a820c711d23135d38eec0ab288d3f38f | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2020 Project CHIP Authors
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#pragma once
#include "controller/ExampleOperationalCredentialsIssuer.h"
#include <controller/CHIPDeviceController.h>
#include <inet/InetInterface.h>
#include <lib/support/Span.h>
#include <lib/support/logging/CHIPLogging.h>
#include <atomic>
#include <condition_variable>
#include <memory>
#include <mutex>
#include <vector>
class Command;
template <typename T, typename... Args>
std::unique_ptr<Command> make_unique(Args &&... args)
{
return std::unique_ptr<Command>(new T(std::forward<Args>(args)...));
}
struct movable_initializer_list
{
movable_initializer_list(std::unique_ptr<Command> && in) : item(std::move(in)) {}
operator std::unique_ptr<Command>() const && { return std::move(item); }
mutable std::unique_ptr<Command> item;
};
typedef std::initializer_list<movable_initializer_list> commands_list;
enum ArgumentType
{
Number_uint8,
Number_uint16,
Number_uint32,
Number_uint64,
Number_int8,
Number_int16,
Number_int32,
Number_int64,
Boolean,
String,
CharString,
OctetString,
Attribute,
Address
};
struct Argument
{
const char * name;
ArgumentType type;
int64_t min;
uint64_t max;
void * value;
};
class Command
{
public:
struct AddressWithInterface
{
::chip::Inet::IPAddress address;
::chip::Inet::InterfaceId interfaceId;
};
Command(const char * commandName) : mName(commandName) {}
virtual ~Command() {}
const char * GetName(void) const { return mName; }
const char * GetAttribute(void) const;
const char * GetArgumentName(size_t index) const;
size_t GetArgumentsCount(void) const { return mArgs.size(); }
bool InitArguments(int argc, char ** argv);
size_t AddArgument(const char * name, const char * value);
/**
* @brief
* Add a char string command argument
*
* @param name The name that will be displayed in the command help
* @param value A pointer to a `char *` where the argv value will be stored
* @returns The number of arguments currently added to the command
*/
size_t AddArgument(const char * name, char ** value);
/**
* Add an octet string command argument
*/
size_t AddArgument(const char * name, chip::ByteSpan * value);
size_t AddArgument(const char * name, chip::Span<const char> * value);
size_t AddArgument(const char * name, AddressWithInterface * out);
size_t AddArgument(const char * name, int64_t min, uint64_t max, bool * out)
{
return AddArgument(name, min, max, reinterpret_cast<void *>(out), Boolean);
}
size_t AddArgument(const char * name, int64_t min, uint64_t max, int8_t * out)
{
return AddArgument(name, min, max, reinterpret_cast<void *>(out), Number_int8);
}
size_t AddArgument(const char * name, int64_t min, uint64_t max, int16_t * out)
{
return AddArgument(name, min, max, reinterpret_cast<void *>(out), Number_int16);
}
size_t AddArgument(const char * name, int64_t min, uint64_t max, int32_t * out)
{
return AddArgument(name, min, max, reinterpret_cast<void *>(out), Number_int32);
}
size_t AddArgument(const char * name, int64_t min, uint64_t max, int64_t * out)
{
return AddArgument(name, min, max, reinterpret_cast<void *>(out), Number_int64);
}
size_t AddArgument(const char * name, int64_t min, uint64_t max, uint8_t * out)
{
return AddArgument(name, min, max, reinterpret_cast<void *>(out), Number_uint8);
}
size_t AddArgument(const char * name, int64_t min, uint64_t max, uint16_t * out)
{
return AddArgument(name, min, max, reinterpret_cast<void *>(out), Number_uint16);
}
size_t AddArgument(const char * name, int64_t min, uint64_t max, uint32_t * out)
{
return AddArgument(name, min, max, reinterpret_cast<void *>(out), Number_uint32);
}
size_t AddArgument(const char * name, int64_t min, uint64_t max, uint64_t * out)
{
return AddArgument(name, min, max, reinterpret_cast<void *>(out), Number_uint64);
}
template <typename T, typename = std::enable_if_t<std::is_enum<T>::value>>
size_t AddArgument(const char * name, int64_t min, uint64_t max, T * out)
{
return AddArgument(name, min, max, reinterpret_cast<std::underlying_type_t<T> *>(out));
}
virtual CHIP_ERROR Run() = 0;
private:
bool InitArgument(size_t argIndex, char * argValue);
size_t AddArgument(const char * name, int64_t min, uint64_t max, void * out, ArgumentType type);
size_t AddArgument(const char * name, int64_t min, uint64_t max, void * out);
const char * mName = nullptr;
std::vector<Argument> mArgs;
};
| 32.695122 | 100 | 0.67997 | [
"vector"
] |
fa372b13c770320048dfa8a5bd855103612c47f2 | 854 | h | C | ZMShow/ZPlayList.h | zaxai/ZMShow_Windows | c82edfd7cf337406fefebc91484060ae4778c755 | [
"MIT"
] | null | null | null | ZMShow/ZPlayList.h | zaxai/ZMShow_Windows | c82edfd7cf337406fefebc91484060ae4778c755 | [
"MIT"
] | null | null | null | ZMShow/ZPlayList.h | zaxai/ZMShow_Windows | c82edfd7cf337406fefebc91484060ae4778c755 | [
"MIT"
] | null | null | null | #pragma once
#include "ZUtil.h"
#include "ZSqlite3.h"
class ZPlayList
{
public:
ZPlayList();
~ZPlayList();
private:
CString m_strPathDB;
static bool m_bIsSrand;
public:
bool IsExist();
bool InsertItem(int nID, int nParentID, int nClass, CString strName, CString strPath, int nLastPlayProgress);
void GetAllItem(std::vector<std::vector <CString>> & vec2_strData);
bool DeleteItem(int nID);
bool DeleteAllItem(void);
CString GetPath(int nID);
int GetParentID(int nID);
int GetClass(int nID);
int GetIDByPath(CString strPath);
void GetChildPath(int nID, std::vector<std::vector <CString>> & vec2_strData);
int GetNextID(int nID, int nListMode, bool bIsPrev);
void SearchKey(CString strKey, std::vector<std::vector <CString>> & vec2_strData);
int GetLastPlayProgress(int nID);
bool SetLastPlayProgress(int nID, int nLastPlayProgress);
};
| 28.466667 | 110 | 0.755269 | [
"vector"
] |
fa391d1526322e7d0515467725cb1db28e0a0f11 | 7,714 | h | C | Charts/Core/vtkPlotPoints.h | collects/VTK | 004944f0d54df673c38b3d4016a4bee74fa7d813 | [
"BSD-3-Clause"
] | null | null | null | Charts/Core/vtkPlotPoints.h | collects/VTK | 004944f0d54df673c38b3d4016a4bee74fa7d813 | [
"BSD-3-Clause"
] | null | null | null | Charts/Core/vtkPlotPoints.h | collects/VTK | 004944f0d54df673c38b3d4016a4bee74fa7d813 | [
"BSD-3-Clause"
] | 2 | 2019-09-09T22:42:12.000Z | 2020-10-22T07:10:08.000Z | /*=========================================================================
Program: Visualization Toolkit
Module: vtkPlotPoints.h
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm 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.
=========================================================================*/
// .NAME vtkPlotPoints - Class for drawing an points given two columns from a
// vtkTable.
//
// .SECTION Description
// This class draws points in a plot given two columns from a table. If you need
// a line as well you should use vtkPlotLine which derives from vtkPlotPoints
// and is capable of drawing both points and a line.
//
// .SECTION See Also
// vtkPlotLine
#ifndef __vtkPlotPoints_h
#define __vtkPlotPoints_h
#include "vtkChartsCoreModule.h" // For export macro
#include "vtkPlot.h"
#include "vtkScalarsToColors.h" // For VTK_COLOR_MODE_DEFAULT and _MAP_SCALARS
#include "vtkStdString.h" // For color array name
#include "vtkNew.h" // For ivars
#include "vtkRenderingCoreEnums.h" // For marker enum
class vtkCharArray;
class vtkContext2D;
class vtkTable;
class vtkPoints2D;
class vtkFloatArray;
class vtkStdString;
class vtkImageData;
class vtkScalarsToColors;
class vtkUnsignedCharArray;
class VTKCHARTSCORE_EXPORT vtkPlotPoints : public vtkPlot
{
public:
vtkTypeMacro(vtkPlotPoints, vtkPlot);
virtual void PrintSelf(ostream &os, vtkIndent indent);
// Description:
// Creates a 2D Chart object.
static vtkPlotPoints *New();
// Description:
// Perform any updates to the item that may be necessary before rendering.
// The scene should take care of calling this on all items before their
// Paint function is invoked.
virtual void Update();
// Description:
// Paint event for the XY plot, called whenever the chart needs to be drawn
virtual bool Paint(vtkContext2D *painter);
// Description:
// Paint legend event for the XY plot, called whenever the legend needs the
// plot items symbol/mark/line drawn. A rect is supplied with the lower left
// corner of the rect (elements 0 and 1) and with width x height (elements 2
// and 3). The plot can choose how to fill the space supplied.
virtual bool PaintLegend(vtkContext2D *painter, const vtkRectf& rect,
int legendIndex);
// Description:
// Get the bounds for this plot as (Xmin, Xmax, Ymin, Ymax).
virtual void GetBounds(double bounds[4]);
// Description:
// Get the non-log-scaled bounds on chart inputs for this plot as (Xmin, Xmax, Ymin, Ymax).
virtual void GetUnscaledInputBounds(double bounds[4]);
// Description:
// Specify a lookup table for the mapper to use.
void SetLookupTable(vtkScalarsToColors *lut);
vtkScalarsToColors *GetLookupTable();
// Description:
// Create default lookup table. Generally used to create one when none
// is available with the scalar data.
virtual void CreateDefaultLookupTable();
// Description:
// Turn on/off flag to control whether scalar data is used to color objects.
vtkSetMacro(ScalarVisibility,int);
vtkGetMacro(ScalarVisibility,int);
vtkBooleanMacro(ScalarVisibility,int);
// Description:
// When ScalarMode is set to UsePointFieldData or UseCellFieldData,
// you can specify which array to use for coloring using these methods.
// The lookup table will decide how to convert vectors to colors.
void SelectColorArray(vtkIdType arrayNum);
void SelectColorArray(const vtkStdString& arrayName);
// Description:
// Get the array name to color by.
vtkStdString GetColorArrayName();
//BTX
// Description:
// Function to query a plot for the nearest point to the specified coordinate.
// Returns the index of the data series with which the point is associated or
// -1.
virtual vtkIdType GetNearestPoint(const vtkVector2f& point,
const vtkVector2f& tolerance,
vtkVector2f* location);
// Description:
// Select all points in the specified rectangle.
virtual bool SelectPoints(const vtkVector2f& min, const vtkVector2f& max);
// Description:
// Select all points in the specified polygon.
virtual bool SelectPointsInPolygon(const vtkContextPolygon &polygon);
// Description:
// Enum containing various marker styles that can be used in a plot.
enum {
NONE = VTK_MARKER_NONE,
CROSS = VTK_MARKER_CROSS,
PLUS = VTK_MARKER_PLUS,
SQUARE = VTK_MARKER_SQUARE,
CIRCLE = VTK_MARKER_CIRCLE,
DIAMOND = VTK_MARKER_DIAMOND
};
//ETX
// Description:
// Get/set the marker style that should be used. The default is none, the enum
// in this class is used as a parameter.
vtkGetMacro(MarkerStyle, int);
vtkSetMacro(MarkerStyle, int);
// Description:
// Get/set the marker size that should be used. The default is negative, and
// in that case it is 2.3 times the pen width, if less than 8 will be used.
vtkGetMacro(MarkerSize, float);
vtkSetMacro(MarkerSize, float);
// Description:
// Get/set the valid point mask array name.
vtkGetMacro(ValidPointMaskName, vtkStdString)
vtkSetMacro(ValidPointMaskName, vtkStdString)
//BTX
protected:
vtkPlotPoints();
~vtkPlotPoints();
// Description:
// Update the table cache.
bool UpdateTableCache(vtkTable *table);
// Description:
// Handle calculating the log of the x or y series if necessary. Should be
// called by UpdateTableCache once the data has been updated in Points.
void CalculateLogSeries();
// Description:
// Find all of the "bad points" in the series. This is mainly used to cache
// bad points for performance reasons, but could also be used plot the bad
// points in the future.
void FindBadPoints();
// Description:
// Calculate the bounds of the plot, ignoring the bad points.
void CalculateBounds(double bounds[4]);
// Description:
// Create the sorted point list if necessary.
void CreateSortedPoints();
// Description:
// Store a well packed set of XY coordinates for this data series.
vtkPoints2D *Points;
vtkNew<vtkFloatArray> SelectedPoints;
// Description:
// Sorted points, used when searching for the nearest point.
class VectorPIMPL;
VectorPIMPL* Sorted;
// Description:
// An array containing the indices of all the "bad points", meaning any x, y
// pair that has an infinity, -infinity or not a number value.
vtkIdTypeArray* BadPoints;
// Description:
// Array which marks valid points in the array. If NULL (the default), all
// points in the input array are considered valid.
vtkCharArray* ValidPointMask;
// Description:
// Name of the valid point mask array.
vtkStdString ValidPointMaskName;
// Description:
// The point cache is marked dirty until it has been initialized.
vtkTimeStamp BuildTime;
// Description:
// The marker style that should be used
int MarkerStyle;
float MarkerSize;
bool LogX, LogY;
// Description:
// Lookup Table for coloring points by scalar value
vtkScalarsToColors *LookupTable;
vtkUnsignedCharArray *Colors;
int ScalarVisibility;
vtkStdString ColorArrayName;
// Description:
// Cached bounds on the plot input axes
double UnscaledInputBounds[4];
private:
vtkPlotPoints(const vtkPlotPoints &); // Not implemented.
void operator=(const vtkPlotPoints &); // Not implemented.
// #define VTK_COLOR_MODE_DEFAULT 0
// #define VTK_COLOR_MODE_MAP_SCALARS 1
//ETX
};
#endif //__vtkPlotPoints_h
| 32.141667 | 93 | 0.713378 | [
"object"
] |
fa396719b1cd3de2f81a6193e225eadbd7f71f66 | 12,144 | h | C | oap-native-sql/cpp/src/codegen/arrow_compute/code_generator.h | xuechendi/OAP | 4340f924d411d35802b1d6e9b0fbeda7856b78d0 | [
"Apache-2.0"
] | null | null | null | oap-native-sql/cpp/src/codegen/arrow_compute/code_generator.h | xuechendi/OAP | 4340f924d411d35802b1d6e9b0fbeda7856b78d0 | [
"Apache-2.0"
] | 2 | 2020-09-01T05:30:56.000Z | 2020-12-07T08:17:24.000Z | oap-native-sql/cpp/src/codegen/arrow_compute/code_generator.h | xuechendi/OAP | 4340f924d411d35802b1d6e9b0fbeda7856b78d0 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include <arrow/pretty_print.h>
#include <arrow/record_batch.h>
#include <arrow/type.h>
#include <chrono>
#include "codegen/arrow_compute/expr_visitor.h"
#include "codegen/code_generator.h"
#include "codegen/common/result_iterator.h"
#include "utils/macros.h"
namespace sparkcolumnarplugin {
namespace codegen {
namespace arrowcompute {
class ArrowComputeCodeGenerator : public CodeGenerator {
public:
ArrowComputeCodeGenerator(
std::shared_ptr<arrow::Schema> schema_ptr,
std::vector<std::shared_ptr<gandiva::Expression>> expr_vector,
std::vector<std::shared_ptr<arrow::Field>> ret_types, bool return_when_finish,
std::vector<std::shared_ptr<::gandiva::Expression>> finish_exprs_vector)
: schema_(schema_ptr),
ret_types_(ret_types),
return_when_finish_(return_when_finish) {
int i = 0;
for (auto expr : expr_vector) {
std::shared_ptr<ExprVisitor> root_visitor;
if (finish_exprs_vector.empty()) {
auto visitor = MakeExprVisitor(schema_ptr, expr, ret_types_, &expr_visitor_cache_,
&root_visitor);
auto status = DistinctInsert(root_visitor, &visitor_list_);
} else {
auto visitor =
MakeExprVisitor(schema_ptr, expr, ret_types_, finish_exprs_vector[i++],
&expr_visitor_cache_, &root_visitor);
auto status = DistinctInsert(root_visitor, &visitor_list_);
}
}
for (auto visitor : visitor_list_) {
auto status = visitor->Init();
}
#ifdef DEBUG_DATA
std::cout << "new ExprVisitor for " << schema_->ToString() << std::endl;
#endif
}
~ArrowComputeCodeGenerator() {
expr_visitor_cache_.clear();
visitor_list_.clear();
}
arrow::Status DistinctInsert(const std::shared_ptr<ExprVisitor>& in,
std::vector<std::shared_ptr<ExprVisitor>>* visitor_list) {
for (auto visitor : *visitor_list) {
if (visitor == in) return arrow::Status::OK();
}
visitor_list->push_back(in);
return arrow::Status::OK();
}
arrow::Status getSchema(std::shared_ptr<arrow::Schema>* out) {
*out = schema_;
return arrow::Status::OK();
}
arrow::Status getResSchema(std::shared_ptr<arrow::Schema>* out) {
*out = res_schema_;
return arrow::Status::OK();
}
arrow::Status SetMember(const std::shared_ptr<arrow::RecordBatch>& member_set) {
for (auto visitor : visitor_list_) {
RETURN_NOT_OK(visitor->SetMember(member_set));
}
return arrow::Status::OK();
}
arrow::Status SetDependency(
const std::shared_ptr<ResultIterator<arrow::RecordBatch>>& dependency_iter,
int index) override {
for (auto visitor : visitor_list_) {
RETURN_NOT_OK(visitor->SetDependency(dependency_iter, index));
}
return arrow::Status::OK();
}
arrow::Status SetResSchema(const std::shared_ptr<arrow::Schema>& in) override {
ret_types_ = in->fields();
return arrow::Status::OK();
}
arrow::Status evaluate(const std::shared_ptr<arrow::RecordBatch>& in,
std::vector<std::shared_ptr<arrow::RecordBatch>>* out) {
arrow::Status status = arrow::Status::OK();
std::vector<ArrayList> batch_array;
std::vector<int> batch_size_array;
std::vector<std::shared_ptr<arrow::Field>> fields;
for (auto visitor : visitor_list_) {
TIME_MICRO_OR_RAISE(eval_elapse_time_, visitor->Eval(in));
if (!return_when_finish_) {
RETURN_NOT_OK(GetResult(visitor, &batch_array, &batch_size_array, &fields));
}
}
if (!return_when_finish_) {
res_schema_ = arrow::schema(ret_types_);
for (int i = 0; i < batch_array.size(); i++) {
auto record_batch =
arrow::RecordBatch::Make(res_schema_, batch_size_array[i], batch_array[i]);
#ifdef DEBUG_LEVEL_1
std::cout << "ArrowCompute Finish func get output recordBatch length "
<< record_batch->num_rows() << std::endl;
auto status = arrow::PrettyPrint(*record_batch.get(), 2, &std::cout);
#endif
out->push_back(record_batch);
}
// we need to clean up this visitor chain result for next record_batch.
for (auto visitor : visitor_list_) {
RETURN_NOT_OK(visitor->Reset());
}
} else {
for (auto visitor : visitor_list_) {
RETURN_NOT_OK(visitor->ResetDependency());
}
}
return status;
}
arrow::Status evaluate(const std::shared_ptr<arrow::Array>& selection_in,
const std::shared_ptr<arrow::RecordBatch>& in,
std::vector<std::shared_ptr<arrow::RecordBatch>>* out) {
arrow::Status status = arrow::Status::OK();
std::vector<ArrayList> batch_array;
std::vector<int> batch_size_array;
std::vector<std::shared_ptr<arrow::Field>> fields;
for (auto visitor : visitor_list_) {
TIME_MICRO_OR_RAISE(eval_elapse_time_, visitor->Eval(selection_in, in));
if (!return_when_finish_) {
RETURN_NOT_OK(GetResult(visitor, &batch_array, &batch_size_array, &fields));
}
}
if (!return_when_finish_) {
res_schema_ = arrow::schema(ret_types_);
for (int i = 0; i < batch_array.size(); i++) {
auto record_batch =
arrow::RecordBatch::Make(res_schema_, batch_size_array[i], batch_array[i]);
#ifdef DEBUG_LEVEL_1
std::cout << "ArrowCompute Finish func get output recordBatch length "
<< record_batch->num_rows() << std::endl;
auto status = arrow::PrettyPrint(*record_batch.get(), 2, &std::cout);
#endif
out->push_back(record_batch);
}
// we need to clean up this visitor chain result for next record_batch.
for (auto visitor : visitor_list_) {
RETURN_NOT_OK(visitor->Reset());
}
} else {
for (auto visitor : visitor_list_) {
RETURN_NOT_OK(visitor->ResetDependency());
}
}
return status;
}
arrow::Status finish(std::vector<std::shared_ptr<arrow::RecordBatch>>* out) {
arrow::Status status = arrow::Status::OK();
std::vector<ArrayList> batch_array;
std::vector<int> batch_size_array;
std::vector<std::shared_ptr<arrow::Field>> fields;
for (auto visitor : visitor_list_) {
std::shared_ptr<ExprVisitor> finish_visitor;
TIME_MICRO_OR_RAISE(finish_elapse_time_, visitor->Finish(&finish_visitor));
if (finish_visitor) {
RETURN_NOT_OK(
GetResult(finish_visitor, &batch_array, &batch_size_array, &fields));
} else {
RETURN_NOT_OK(GetResult(visitor, &batch_array, &batch_size_array, &fields));
}
visitor->PrintMetrics();
std::cout << std::endl;
}
for (auto arr : batch_array[0]) {
std::cout << arr->ToString();
}
for (auto field : fields) {
std::cout << field->ToString();
}
res_schema_ = arrow::schema(ret_types_);
for (int i = 0; i < batch_array.size(); i++) {
std::cout << res_schema_->ToString() << std::endl;
auto record_batch =
arrow::RecordBatch::Make(res_schema_, batch_size_array[i], batch_array[i]);
#ifdef DEBUG
std::cout << "ArrowCompute Finish func get output recordBatch length "
<< record_batch->num_rows() << std::endl;
auto status = arrow::PrettyPrint(*record_batch.get(), 2, &std::cout);
#endif
out->push_back(record_batch);
}
// we need to clean up this visitor chain result for next record_batch.
for (auto visitor : visitor_list_) {
RETURN_NOT_OK(visitor->Reset());
}
std::cout << "Evaluate took " << TIME_TO_STRING(eval_elapse_time_) << ", Finish took "
<< TIME_TO_STRING(finish_elapse_time_) << std::endl;
return status;
}
arrow::Status finish(
std::shared_ptr<ResultIterator<arrow::RecordBatch>>* out) override {
for (auto visitor : visitor_list_) {
TIME_MICRO_OR_RAISE(finish_elapse_time_,
visitor->MakeResultIterator(arrow::schema(ret_types_), out));
visitor->PrintMetrics();
std::cout << std::endl;
}
return arrow::Status::OK();
}
private:
std::vector<std::shared_ptr<ExprVisitor>> visitor_list_;
std::shared_ptr<arrow::Schema> schema_;
std::shared_ptr<arrow::Schema> res_schema_;
std::vector<std::shared_ptr<arrow::Field>> ret_types_;
// metrics
uint64_t eval_elapse_time_ = 0;
uint64_t finish_elapse_time_ = 0;
bool return_when_finish_;
// ExprVisitor Cache, used when multiple node depends on same node.
ExprVisitorMap expr_visitor_cache_;
arrow::Status MakeBatchFromArray(std::shared_ptr<arrow::Array> column, int batch_index,
std::vector<ArrayList>* batch_array,
std::vector<int>* batch_size_array) {
int res_len = 0;
RETURN_NOT_OK(GetOrInsert(batch_index, batch_size_array, &res_len));
batch_size_array->at(batch_index) =
(res_len < column->length()) ? column->length() : res_len;
ArrayList batch_array_item;
RETURN_NOT_OK(GetOrInsert(batch_index, batch_array, &batch_array_item));
batch_array->at(batch_index).push_back(column);
return arrow::Status::OK();
}
arrow::Status MakeBatchFromArrayList(ArrayList column_list,
std::vector<ArrayList>* batch_array,
std::vector<int>* batch_size_array) {
for (int i = 0; i < column_list.size(); i++) {
RETURN_NOT_OK(MakeBatchFromArray(column_list[i], i, batch_array, batch_size_array));
}
return arrow::Status::OK();
}
arrow::Status MakeBatchFromBatch(ArrayList batch, std::vector<ArrayList>* batch_array,
std::vector<int>* batch_size_array) {
int length = 0;
int i = 0;
for (auto column : batch) {
if (length != 0 && length != column->length()) {
return arrow::Status::Invalid(
"ArrowCompute MakeBatchFromBatch found batch contains columns with different "
"lengths, expect ",
length, " while got ", column->length(), " from ", i, "th column.");
}
length = column->length();
i++;
}
batch_array->push_back(batch);
batch_size_array->push_back(length);
return arrow::Status::OK();
}
template <typename T>
arrow::Status GetOrInsert(int i, std::vector<T>* input, T* out) {
if (i > input->size()) {
return arrow::Status::Invalid("GetOrInser index: ", i, " is out of range.");
}
if (i == input->size()) {
T new_data = *out;
input->push_back(new_data);
}
*out = input->at(i);
return arrow::Status::OK();
}
arrow::Status GetResult(std::shared_ptr<ExprVisitor> visitor,
std::vector<ArrayList>* batch_array,
std::vector<int>* batch_size_array,
std::vector<std::shared_ptr<arrow::Field>>* fields) {
auto status = arrow::Status::OK();
std::vector<std::shared_ptr<arrow::Field>> return_fields;
switch (visitor->GetResultType()) {
case ArrowComputeResultType::BatchList: {
RETURN_NOT_OK(visitor->GetResult(batch_array, batch_size_array, &return_fields));
} break;
case ArrowComputeResultType::Batch: {
if (batch_array->size() == 0) {
ArrayList res;
batch_array->push_back(res);
}
RETURN_NOT_OK(visitor->GetResult(&(batch_array->at(0)), fields));
batch_size_array->push_back((batch_array->at(0))[0]->length());
} break;
case ArrowComputeResultType::Array: {
std::shared_ptr<arrow::Array> result_column;
RETURN_NOT_OK(visitor->GetResult(&result_column, &return_fields));
RETURN_NOT_OK(
MakeBatchFromArray(result_column, 0, batch_array, batch_size_array));
} break;
default:
return arrow::Status::Invalid("ArrowComputeResultType is invalid.");
}
fields->insert(fields->end(), return_fields.begin(), return_fields.end());
return status;
}
}; // namespace arrowcompute
} // namespace arrowcompute
} // namespace codegen
} // namespace sparkcolumnarplugin
| 36.911854 | 90 | 0.636364 | [
"vector"
] |
fa3b4206fb308f3f467b1073f2f3b2c6826c96c7 | 237,710 | c | C | dlls/gdi32/tests/font.c | Eltechs/wine | 5ef54904f24c7dfc4a0bfd1795e59cf510c425d2 | [
"MIT"
] | 20 | 2015-03-12T09:04:07.000Z | 2022-01-28T22:50:46.000Z | dlls/gdi32/tests/font.c | Eltechs/wine | 5ef54904f24c7dfc4a0bfd1795e59cf510c425d2 | [
"MIT"
] | null | null | null | dlls/gdi32/tests/font.c | Eltechs/wine | 5ef54904f24c7dfc4a0bfd1795e59cf510c425d2 | [
"MIT"
] | 10 | 2016-07-19T05:39:39.000Z | 2021-08-05T09:09:27.000Z | /*
* Unit test suite for fonts
*
* Copyright 2002 Mike McCormack
* Copyright 2004 Dmitry Timoshkov
*
* 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 <stdarg.h>
#include <assert.h>
#include "windef.h"
#include "winbase.h"
#include "wingdi.h"
#include "winuser.h"
#include "winnls.h"
#include "wine/test.h"
/* Do not allow more than 1 deviation here */
#define match_off_by_1(a, b, exact) (abs((a) - (b)) <= ((exact) ? 0 : 1))
#define near_match(a, b) (abs((a) - (b)) <= 6)
#define expect(expected, got) ok(got == expected, "Expected %.8x, got %.8x\n", expected, got)
static LONG (WINAPI *pGdiGetCharDimensions)(HDC hdc, LPTEXTMETRICW lptm, LONG *height);
static DWORD (WINAPI *pGdiGetCodePage)(HDC hdc);
static BOOL (WINAPI *pGetCharABCWidthsI)(HDC hdc, UINT first, UINT count, LPWORD glyphs, LPABC abc);
static BOOL (WINAPI *pGetCharABCWidthsA)(HDC hdc, UINT first, UINT last, LPABC abc);
static BOOL (WINAPI *pGetCharABCWidthsW)(HDC hdc, UINT first, UINT last, LPABC abc);
static BOOL (WINAPI *pGetCharABCWidthsFloatW)(HDC hdc, UINT first, UINT last, LPABCFLOAT abc);
static BOOL (WINAPI *pGetCharWidth32A)(HDC hdc, UINT first, UINT last, LPINT buffer);
static BOOL (WINAPI *pGetCharWidth32W)(HDC hdc, UINT first, UINT last, LPINT buffer);
static DWORD (WINAPI *pGetFontUnicodeRanges)(HDC hdc, LPGLYPHSET lpgs);
static DWORD (WINAPI *pGetGlyphIndicesA)(HDC hdc, LPCSTR lpstr, INT count, LPWORD pgi, DWORD flags);
static DWORD (WINAPI *pGetGlyphIndicesW)(HDC hdc, LPCWSTR lpstr, INT count, LPWORD pgi, DWORD flags);
static BOOL (WINAPI *pGetTextExtentExPointI)(HDC hdc, const WORD *indices, INT count, INT max_ext,
LPINT nfit, LPINT dxs, LPSIZE size );
static BOOL (WINAPI *pGdiRealizationInfo)(HDC hdc, DWORD *);
static HFONT (WINAPI *pCreateFontIndirectExA)(const ENUMLOGFONTEXDVA *);
static HANDLE (WINAPI *pAddFontMemResourceEx)(PVOID, DWORD, PVOID, DWORD *);
static BOOL (WINAPI *pRemoveFontMemResourceEx)(HANDLE);
static INT (WINAPI *pAddFontResourceExA)(LPCSTR, DWORD, PVOID);
static BOOL (WINAPI *pRemoveFontResourceExA)(LPCSTR, DWORD, PVOID);
static HMODULE hgdi32 = 0;
static const MAT2 mat = { {0,1}, {0,0}, {0,0}, {0,1} };
static WORD system_lang_id;
#ifdef WORDS_BIGENDIAN
#define GET_BE_WORD(x) (x)
#define GET_BE_DWORD(x) (x)
#else
#define GET_BE_WORD(x) MAKEWORD(HIBYTE(x), LOBYTE(x))
#define GET_BE_DWORD(x) MAKELONG(GET_BE_WORD(HIWORD(x)), GET_BE_WORD(LOWORD(x)));
#endif
#define MS_MAKE_TAG(ch0, ch1, ch2, ch3) \
((DWORD)(BYTE)(ch0) | ((DWORD)(BYTE)(ch1) << 8) | \
((DWORD)(BYTE)(ch2) << 16) | ((DWORD)(BYTE)(ch3) << 24))
#define MS_OS2_TAG MS_MAKE_TAG('O','S','/','2')
#define MS_CMAP_TAG MS_MAKE_TAG('c','m','a','p')
#define MS_NAME_TAG MS_MAKE_TAG('n','a','m','e')
static void init(void)
{
hgdi32 = GetModuleHandleA("gdi32.dll");
pGdiGetCharDimensions = (void *)GetProcAddress(hgdi32, "GdiGetCharDimensions");
pGdiGetCodePage = (void *) GetProcAddress(hgdi32,"GdiGetCodePage");
pGetCharABCWidthsI = (void *)GetProcAddress(hgdi32, "GetCharABCWidthsI");
pGetCharABCWidthsA = (void *)GetProcAddress(hgdi32, "GetCharABCWidthsA");
pGetCharABCWidthsW = (void *)GetProcAddress(hgdi32, "GetCharABCWidthsW");
pGetCharABCWidthsFloatW = (void *)GetProcAddress(hgdi32, "GetCharABCWidthsFloatW");
pGetCharWidth32A = (void *)GetProcAddress(hgdi32, "GetCharWidth32A");
pGetCharWidth32W = (void *)GetProcAddress(hgdi32, "GetCharWidth32W");
pGetFontUnicodeRanges = (void *)GetProcAddress(hgdi32, "GetFontUnicodeRanges");
pGetGlyphIndicesA = (void *)GetProcAddress(hgdi32, "GetGlyphIndicesA");
pGetGlyphIndicesW = (void *)GetProcAddress(hgdi32, "GetGlyphIndicesW");
pGetTextExtentExPointI = (void *)GetProcAddress(hgdi32, "GetTextExtentExPointI");
pGdiRealizationInfo = (void *)GetProcAddress(hgdi32, "GdiRealizationInfo");
pCreateFontIndirectExA = (void *)GetProcAddress(hgdi32, "CreateFontIndirectExA");
pAddFontMemResourceEx = (void *)GetProcAddress(hgdi32, "AddFontMemResourceEx");
pRemoveFontMemResourceEx = (void *)GetProcAddress(hgdi32, "RemoveFontMemResourceEx");
pAddFontResourceExA = (void *)GetProcAddress(hgdi32, "AddFontResourceExA");
pRemoveFontResourceExA = (void *)GetProcAddress(hgdi32, "RemoveFontResourceExA");
system_lang_id = PRIMARYLANGID(GetSystemDefaultLangID());
}
static INT CALLBACK is_truetype_font_installed_proc(const LOGFONTA *elf, const TEXTMETRICA *ntm, DWORD type, LPARAM lParam)
{
if (type != TRUETYPE_FONTTYPE) return 1;
return 0;
}
static BOOL is_truetype_font_installed(const char *name)
{
HDC hdc = GetDC(0);
BOOL ret = FALSE;
if (!EnumFontFamiliesA(hdc, name, is_truetype_font_installed_proc, 0))
ret = TRUE;
ReleaseDC(0, hdc);
return ret;
}
static INT CALLBACK is_font_installed_proc(const LOGFONTA *elf, const TEXTMETRICA *ntm, DWORD type, LPARAM lParam)
{
return 0;
}
static BOOL is_font_installed(const char *name)
{
HDC hdc = GetDC(0);
BOOL ret = FALSE;
if(!EnumFontFamiliesA(hdc, name, is_font_installed_proc, 0))
ret = TRUE;
ReleaseDC(0, hdc);
return ret;
}
static void *get_res_data(const char *fontname, DWORD *rsrc_size)
{
HRSRC rsrc;
void *rsrc_data;
rsrc = FindResourceA(GetModuleHandleA(NULL), fontname, (LPCSTR)RT_RCDATA);
if (!rsrc) return NULL;
rsrc_data = LockResource(LoadResource(GetModuleHandleA(NULL), rsrc));
if (!rsrc_data) return NULL;
*rsrc_size = SizeofResource(GetModuleHandleA(NULL), rsrc);
if (!*rsrc_size) return NULL;
return rsrc_data;
}
static BOOL write_tmp_file( const void *data, DWORD *size, char *tmp_name )
{
char tmp_path[MAX_PATH];
HANDLE hfile;
BOOL ret;
GetTempPathA(MAX_PATH, tmp_path);
GetTempFileNameA(tmp_path, "ttf", 0, tmp_name);
hfile = CreateFileA(tmp_name, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0);
if (hfile == INVALID_HANDLE_VALUE) return FALSE;
ret = WriteFile(hfile, data, *size, size, NULL);
CloseHandle(hfile);
return ret;
}
static BOOL write_ttf_file(const char *fontname, char *tmp_name)
{
void *rsrc_data;
DWORD rsrc_size;
rsrc_data = get_res_data( fontname, &rsrc_size );
if (!rsrc_data) return FALSE;
return write_tmp_file( rsrc_data, &rsrc_size, tmp_name );
}
static void check_font(const char* test, const LOGFONTA* lf, HFONT hfont)
{
LOGFONTA getobj_lf;
int ret, minlen = 0;
if (!hfont)
return;
ret = GetObjectA(hfont, sizeof(getobj_lf), &getobj_lf);
/* NT4 tries to be clever and only returns the minimum length */
while (lf->lfFaceName[minlen] && minlen < LF_FACESIZE-1)
minlen++;
minlen += FIELD_OFFSET(LOGFONTA, lfFaceName) + 1;
ok(ret == sizeof(LOGFONTA) || ret == minlen, "%s: GetObject returned %d\n", test, ret);
ok(lf->lfHeight == getobj_lf.lfHeight ||
broken((SHORT)lf->lfHeight == getobj_lf.lfHeight), /* win9x */
"lfHeight: expect %08x got %08x\n", lf->lfHeight, getobj_lf.lfHeight);
ok(lf->lfWidth == getobj_lf.lfWidth ||
broken((SHORT)lf->lfWidth == getobj_lf.lfWidth), /* win9x */
"lfWidth: expect %08x got %08x\n", lf->lfWidth, getobj_lf.lfWidth);
ok(lf->lfEscapement == getobj_lf.lfEscapement ||
broken((SHORT)lf->lfEscapement == getobj_lf.lfEscapement), /* win9x */
"lfEscapement: expect %08x got %08x\n", lf->lfEscapement, getobj_lf.lfEscapement);
ok(lf->lfOrientation == getobj_lf.lfOrientation ||
broken((SHORT)lf->lfOrientation == getobj_lf.lfOrientation), /* win9x */
"lfOrientation: expect %08x got %08x\n", lf->lfOrientation, getobj_lf.lfOrientation);
ok(lf->lfWeight == getobj_lf.lfWeight ||
broken((SHORT)lf->lfWeight == getobj_lf.lfWeight), /* win9x */
"lfWeight: expect %08x got %08x\n", lf->lfWeight, getobj_lf.lfWeight);
ok(lf->lfItalic == getobj_lf.lfItalic, "lfItalic: expect %02x got %02x\n", lf->lfItalic, getobj_lf.lfItalic);
ok(lf->lfUnderline == getobj_lf.lfUnderline, "lfUnderline: expect %02x got %02x\n", lf->lfUnderline, getobj_lf.lfUnderline);
ok(lf->lfStrikeOut == getobj_lf.lfStrikeOut, "lfStrikeOut: expect %02x got %02x\n", lf->lfStrikeOut, getobj_lf.lfStrikeOut);
ok(lf->lfCharSet == getobj_lf.lfCharSet, "lfCharSet: expect %02x got %02x\n", lf->lfCharSet, getobj_lf.lfCharSet);
ok(lf->lfOutPrecision == getobj_lf.lfOutPrecision, "lfOutPrecision: expect %02x got %02x\n", lf->lfOutPrecision, getobj_lf.lfOutPrecision);
ok(lf->lfClipPrecision == getobj_lf.lfClipPrecision, "lfClipPrecision: expect %02x got %02x\n", lf->lfClipPrecision, getobj_lf.lfClipPrecision);
ok(lf->lfQuality == getobj_lf.lfQuality, "lfQuality: expect %02x got %02x\n", lf->lfQuality, getobj_lf.lfQuality);
ok(lf->lfPitchAndFamily == getobj_lf.lfPitchAndFamily, "lfPitchAndFamily: expect %02x got %02x\n", lf->lfPitchAndFamily, getobj_lf.lfPitchAndFamily);
ok(!lstrcmpA(lf->lfFaceName, getobj_lf.lfFaceName) ||
broken(!memcmp(lf->lfFaceName, getobj_lf.lfFaceName, LF_FACESIZE-1)), /* win9x doesn't ensure '\0' termination */
"%s: font names don't match: %s != %s\n", test, lf->lfFaceName, getobj_lf.lfFaceName);
}
static HFONT create_font(const char* test, const LOGFONTA* lf)
{
HFONT hfont = CreateFontIndirectA(lf);
ok(hfont != 0, "%s: CreateFontIndirect failed\n", test);
if (hfont)
check_font(test, lf, hfont);
return hfont;
}
static void test_logfont(void)
{
LOGFONTA lf;
HFONT hfont;
memset(&lf, 0, sizeof lf);
lf.lfCharSet = ANSI_CHARSET;
lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
lf.lfWeight = FW_DONTCARE;
lf.lfHeight = 16;
lf.lfWidth = 16;
lf.lfQuality = DEFAULT_QUALITY;
lstrcpyA(lf.lfFaceName, "Arial");
hfont = create_font("Arial", &lf);
DeleteObject(hfont);
memset(&lf, 'A', sizeof(lf));
hfont = CreateFontIndirectA(&lf);
ok(hfont != 0, "CreateFontIndirectA with strange LOGFONT failed\n");
lf.lfFaceName[LF_FACESIZE - 1] = 0;
check_font("AAA...", &lf, hfont);
DeleteObject(hfont);
}
static INT CALLBACK font_enum_proc(const LOGFONTA *elf, const TEXTMETRICA *ntm, DWORD type, LPARAM lParam)
{
if (type & RASTER_FONTTYPE)
{
LOGFONTA *lf = (LOGFONTA *)lParam;
*lf = *elf;
return 0; /* stop enumeration */
}
return 1; /* continue enumeration */
}
static void compare_tm(const TEXTMETRICA *tm, const TEXTMETRICA *otm)
{
ok(tm->tmHeight == otm->tmHeight, "tmHeight %d != %d\n", tm->tmHeight, otm->tmHeight);
ok(tm->tmAscent == otm->tmAscent, "tmAscent %d != %d\n", tm->tmAscent, otm->tmAscent);
ok(tm->tmDescent == otm->tmDescent, "tmDescent %d != %d\n", tm->tmDescent, otm->tmDescent);
ok(tm->tmInternalLeading == otm->tmInternalLeading, "tmInternalLeading %d != %d\n", tm->tmInternalLeading, otm->tmInternalLeading);
ok(tm->tmExternalLeading == otm->tmExternalLeading, "tmExternalLeading %d != %d\n", tm->tmExternalLeading, otm->tmExternalLeading);
ok(tm->tmAveCharWidth == otm->tmAveCharWidth, "tmAveCharWidth %d != %d\n", tm->tmAveCharWidth, otm->tmAveCharWidth);
ok(tm->tmMaxCharWidth == otm->tmMaxCharWidth, "tmMaxCharWidth %d != %d\n", tm->tmMaxCharWidth, otm->tmMaxCharWidth);
ok(tm->tmWeight == otm->tmWeight, "tmWeight %d != %d\n", tm->tmWeight, otm->tmWeight);
ok(tm->tmOverhang == otm->tmOverhang, "tmOverhang %d != %d\n", tm->tmOverhang, otm->tmOverhang);
ok(tm->tmDigitizedAspectX == otm->tmDigitizedAspectX, "tmDigitizedAspectX %d != %d\n", tm->tmDigitizedAspectX, otm->tmDigitizedAspectX);
ok(tm->tmDigitizedAspectY == otm->tmDigitizedAspectY, "tmDigitizedAspectY %d != %d\n", tm->tmDigitizedAspectY, otm->tmDigitizedAspectY);
ok(tm->tmFirstChar == otm->tmFirstChar, "tmFirstChar %d != %d\n", tm->tmFirstChar, otm->tmFirstChar);
ok(tm->tmLastChar == otm->tmLastChar, "tmLastChar %d != %d\n", tm->tmLastChar, otm->tmLastChar);
ok(tm->tmDefaultChar == otm->tmDefaultChar, "tmDefaultChar %d != %d\n", tm->tmDefaultChar, otm->tmDefaultChar);
ok(tm->tmBreakChar == otm->tmBreakChar, "tmBreakChar %d != %d\n", tm->tmBreakChar, otm->tmBreakChar);
ok(tm->tmItalic == otm->tmItalic, "tmItalic %d != %d\n", tm->tmItalic, otm->tmItalic);
ok(tm->tmUnderlined == otm->tmUnderlined, "tmUnderlined %d != %d\n", tm->tmUnderlined, otm->tmUnderlined);
ok(tm->tmStruckOut == otm->tmStruckOut, "tmStruckOut %d != %d\n", tm->tmStruckOut, otm->tmStruckOut);
ok(tm->tmPitchAndFamily == otm->tmPitchAndFamily, "tmPitchAndFamily %d != %d\n", tm->tmPitchAndFamily, otm->tmPitchAndFamily);
ok(tm->tmCharSet == otm->tmCharSet, "tmCharSet %d != %d\n", tm->tmCharSet, otm->tmCharSet);
}
static void test_font_metrics(HDC hdc, HFONT hfont, LONG lfHeight,
LONG lfWidth, const char *test_str,
INT test_str_len, const TEXTMETRICA *tm_orig,
const SIZE *size_orig, INT width_of_A_orig,
INT scale_x, INT scale_y)
{
LOGFONTA lf;
OUTLINETEXTMETRICA otm;
TEXTMETRICA tm;
SIZE size;
INT width_of_A, cx, cy;
UINT ret;
if (!hfont)
return;
ok(GetCurrentObject(hdc, OBJ_FONT) == hfont, "hfont should be selected\n");
GetObjectA(hfont, sizeof(lf), &lf);
if (GetOutlineTextMetricsA(hdc, 0, NULL))
{
otm.otmSize = sizeof(otm) / 2;
ret = GetOutlineTextMetricsA(hdc, otm.otmSize, &otm);
ok(ret == sizeof(otm)/2 /* XP */ ||
ret == 1 /* Win9x */, "expected sizeof(otm)/2, got %u\n", ret);
memset(&otm, 0x1, sizeof(otm));
otm.otmSize = sizeof(otm);
ret = GetOutlineTextMetricsA(hdc, otm.otmSize, &otm);
ok(ret == sizeof(otm) /* XP */ ||
ret == 1 /* Win9x */, "expected sizeof(otm), got %u\n", ret);
memset(&tm, 0x2, sizeof(tm));
ret = GetTextMetricsA(hdc, &tm);
ok(ret, "GetTextMetricsA failed\n");
/* the structure size is aligned */
if (memcmp(&tm, &otm.otmTextMetrics, FIELD_OFFSET(TEXTMETRICA, tmCharSet) + 1))
{
ok(0, "tm != otm\n");
compare_tm(&tm, &otm.otmTextMetrics);
}
tm = otm.otmTextMetrics;
if (0) /* these metrics are scaled too, but with rounding errors */
{
ok(otm.otmAscent == tm.tmAscent, "ascent %d != %d\n", otm.otmAscent, tm.tmAscent);
ok(otm.otmDescent == -tm.tmDescent, "descent %d != %d\n", otm.otmDescent, -tm.tmDescent);
}
ok(otm.otmMacAscent == tm.tmAscent, "ascent %d != %d\n", otm.otmMacAscent, tm.tmAscent);
ok(otm.otmDescent < 0, "otm.otmDescent should be < 0\n");
ok(otm.otmMacDescent < 0, "otm.otmMacDescent should be < 0\n");
ok(tm.tmDescent > 0, "tm.tmDescent should be > 0\n");
ok(otm.otmMacDescent == -tm.tmDescent, "descent %d != %d\n", otm.otmMacDescent, -tm.tmDescent);
ok(otm.otmEMSquare == 2048, "expected 2048, got %d\n", otm.otmEMSquare);
}
else
{
ret = GetTextMetricsA(hdc, &tm);
ok(ret, "GetTextMetricsA failed\n");
}
cx = tm.tmAveCharWidth / tm_orig->tmAveCharWidth;
cy = tm.tmHeight / tm_orig->tmHeight;
ok(cx == scale_x && cy == scale_y, "height %d: expected scale_x %d, scale_y %d, got cx %d, cy %d\n",
lfHeight, scale_x, scale_y, cx, cy);
ok(tm.tmHeight == tm_orig->tmHeight * scale_y, "height %d != %d\n", tm.tmHeight, tm_orig->tmHeight * scale_y);
ok(tm.tmAscent == tm_orig->tmAscent * scale_y, "ascent %d != %d\n", tm.tmAscent, tm_orig->tmAscent * scale_y);
ok(tm.tmDescent == tm_orig->tmDescent * scale_y, "descent %d != %d\n", tm.tmDescent, tm_orig->tmDescent * scale_y);
ok(near_match(tm.tmAveCharWidth, tm_orig->tmAveCharWidth * scale_x), "ave width %d != %d\n", tm.tmAveCharWidth, tm_orig->tmAveCharWidth * scale_x);
ok(near_match(tm.tmMaxCharWidth, tm_orig->tmMaxCharWidth * scale_x), "max width %d != %d\n", tm.tmMaxCharWidth, tm_orig->tmMaxCharWidth * scale_x);
ok(lf.lfHeight == lfHeight, "lfHeight %d != %d\n", lf.lfHeight, lfHeight);
if (lf.lfHeight)
{
if (lf.lfWidth)
ok(lf.lfWidth == tm.tmAveCharWidth, "lfWidth %d != tm %d\n", lf.lfWidth, tm.tmAveCharWidth);
}
else
ok(lf.lfWidth == lfWidth, "lfWidth %d != %d\n", lf.lfWidth, lfWidth);
GetTextExtentPoint32A(hdc, test_str, test_str_len, &size);
ok(near_match(size.cx, size_orig->cx * scale_x), "cx %d != %d\n", size.cx, size_orig->cx * scale_x);
ok(size.cy == size_orig->cy * scale_y, "cy %d != %d\n", size.cy, size_orig->cy * scale_y);
GetCharWidthA(hdc, 'A', 'A', &width_of_A);
ok(near_match(width_of_A, width_of_A_orig * scale_x), "width A %d != %d\n", width_of_A, width_of_A_orig * scale_x);
}
/* Test how GDI scales bitmap font metrics */
static void test_bitmap_font(void)
{
static const char test_str[11] = "Test String";
HDC hdc;
LOGFONTA bitmap_lf;
HFONT hfont, old_hfont;
TEXTMETRICA tm_orig;
SIZE size_orig;
INT ret, i, width_orig, height_orig, scale, lfWidth;
hdc = CreateCompatibleDC(0);
/* "System" has only 1 pixel size defined, otherwise the test breaks */
ret = EnumFontFamiliesA(hdc, "System", font_enum_proc, (LPARAM)&bitmap_lf);
if (ret)
{
ReleaseDC(0, hdc);
trace("no bitmap fonts were found, skipping the test\n");
return;
}
trace("found bitmap font %s, height %d\n", bitmap_lf.lfFaceName, bitmap_lf.lfHeight);
height_orig = bitmap_lf.lfHeight;
lfWidth = bitmap_lf.lfWidth;
hfont = create_font("bitmap", &bitmap_lf);
old_hfont = SelectObject(hdc, hfont);
ok(GetTextMetricsA(hdc, &tm_orig), "GetTextMetricsA failed\n");
ok(GetTextExtentPoint32A(hdc, test_str, sizeof(test_str), &size_orig), "GetTextExtentPoint32A failed\n");
ok(GetCharWidthA(hdc, 'A', 'A', &width_orig), "GetCharWidthA failed\n");
SelectObject(hdc, old_hfont);
DeleteObject(hfont);
bitmap_lf.lfHeight = 0;
bitmap_lf.lfWidth = 4;
hfont = create_font("bitmap", &bitmap_lf);
old_hfont = SelectObject(hdc, hfont);
test_font_metrics(hdc, hfont, 0, 4, test_str, sizeof(test_str), &tm_orig, &size_orig, width_orig, 1, 1);
SelectObject(hdc, old_hfont);
DeleteObject(hfont);
bitmap_lf.lfHeight = height_orig;
bitmap_lf.lfWidth = lfWidth;
/* test fractional scaling */
for (i = 1; i <= height_orig * 6; i++)
{
INT nearest_height;
bitmap_lf.lfHeight = i;
hfont = create_font("fractional", &bitmap_lf);
scale = (i + height_orig - 1) / height_orig;
nearest_height = scale * height_orig;
/* Only jump to the next height if the difference <= 25% original height */
if (scale > 2 && nearest_height - i > height_orig / 4) scale--;
/* The jump between unscaled and doubled is delayed by 1 in winnt+ but not in win9x,
so we'll not test this particular height. */
else if(scale == 2 && nearest_height - i == (height_orig / 4)) continue;
else if(scale == 2 && nearest_height - i > (height_orig / 4 - 1)) scale--;
old_hfont = SelectObject(hdc, hfont);
test_font_metrics(hdc, hfont, bitmap_lf.lfHeight, 0, test_str, sizeof(test_str), &tm_orig, &size_orig, width_orig, 1, scale);
SelectObject(hdc, old_hfont);
DeleteObject(hfont);
}
/* test integer scaling 3x2 */
bitmap_lf.lfHeight = height_orig * 2;
bitmap_lf.lfWidth *= 3;
hfont = create_font("3x2", &bitmap_lf);
old_hfont = SelectObject(hdc, hfont);
test_font_metrics(hdc, hfont, bitmap_lf.lfHeight, 0, test_str, sizeof(test_str), &tm_orig, &size_orig, width_orig, 3, 2);
SelectObject(hdc, old_hfont);
DeleteObject(hfont);
/* test integer scaling 3x3 */
bitmap_lf.lfHeight = height_orig * 3;
bitmap_lf.lfWidth = 0;
hfont = create_font("3x3", &bitmap_lf);
old_hfont = SelectObject(hdc, hfont);
test_font_metrics(hdc, hfont, bitmap_lf.lfHeight, 0, test_str, sizeof(test_str), &tm_orig, &size_orig, width_orig, 3, 3);
SelectObject(hdc, old_hfont);
DeleteObject(hfont);
DeleteDC(hdc);
}
/* Test how GDI scales outline font metrics */
static void test_outline_font(void)
{
static const char test_str[11] = "Test String";
HDC hdc, hdc_2;
LOGFONTA lf;
HFONT hfont, old_hfont, old_hfont_2;
OUTLINETEXTMETRICA otm;
SIZE size_orig;
INT width_orig, height_orig, lfWidth;
XFORM xform;
GLYPHMETRICS gm;
MAT2 mat2 = { {0x8000,0}, {0,0}, {0,0}, {0x8000,0} };
POINT pt;
INT ret;
if (!is_truetype_font_installed("Arial"))
{
skip("Arial is not installed\n");
return;
}
hdc = CreateCompatibleDC(0);
memset(&lf, 0, sizeof(lf));
strcpy(lf.lfFaceName, "Arial");
lf.lfHeight = 72;
hfont = create_font("outline", &lf);
old_hfont = SelectObject(hdc, hfont);
otm.otmSize = sizeof(otm);
ok(GetOutlineTextMetricsA(hdc, sizeof(otm), &otm), "GetTextMetricsA failed\n");
ok(GetTextExtentPoint32A(hdc, test_str, sizeof(test_str), &size_orig), "GetTextExtentPoint32A failed\n");
ok(GetCharWidthA(hdc, 'A', 'A', &width_orig), "GetCharWidthA failed\n");
test_font_metrics(hdc, hfont, lf.lfHeight, otm.otmTextMetrics.tmAveCharWidth, test_str, sizeof(test_str), &otm.otmTextMetrics, &size_orig, width_orig, 1, 1);
SelectObject(hdc, old_hfont);
DeleteObject(hfont);
/* font of otmEMSquare height helps to avoid a lot of rounding errors */
lf.lfHeight = otm.otmEMSquare;
lf.lfHeight = -lf.lfHeight;
hfont = create_font("outline", &lf);
old_hfont = SelectObject(hdc, hfont);
otm.otmSize = sizeof(otm);
ok(GetOutlineTextMetricsA(hdc, sizeof(otm), &otm), "GetTextMetricsA failed\n");
ok(GetTextExtentPoint32A(hdc, test_str, sizeof(test_str), &size_orig), "GetTextExtentPoint32A failed\n");
ok(GetCharWidthA(hdc, 'A', 'A', &width_orig), "GetCharWidthA failed\n");
SelectObject(hdc, old_hfont);
DeleteObject(hfont);
height_orig = otm.otmTextMetrics.tmHeight;
lfWidth = otm.otmTextMetrics.tmAveCharWidth;
/* test integer scaling 3x2 */
lf.lfHeight = height_orig * 2;
lf.lfWidth = lfWidth * 3;
hfont = create_font("3x2", &lf);
old_hfont = SelectObject(hdc, hfont);
test_font_metrics(hdc, hfont, lf.lfHeight, lf.lfWidth, test_str, sizeof(test_str), &otm.otmTextMetrics, &size_orig, width_orig, 3, 2);
SelectObject(hdc, old_hfont);
DeleteObject(hfont);
/* test integer scaling 3x3 */
lf.lfHeight = height_orig * 3;
lf.lfWidth = lfWidth * 3;
hfont = create_font("3x3", &lf);
old_hfont = SelectObject(hdc, hfont);
test_font_metrics(hdc, hfont, lf.lfHeight, lf.lfWidth, test_str, sizeof(test_str), &otm.otmTextMetrics, &size_orig, width_orig, 3, 3);
SelectObject(hdc, old_hfont);
DeleteObject(hfont);
/* test integer scaling 1x1 */
lf.lfHeight = height_orig * 1;
lf.lfWidth = lfWidth * 1;
hfont = create_font("1x1", &lf);
old_hfont = SelectObject(hdc, hfont);
test_font_metrics(hdc, hfont, lf.lfHeight, lf.lfWidth, test_str, sizeof(test_str), &otm.otmTextMetrics, &size_orig, width_orig, 1, 1);
SelectObject(hdc, old_hfont);
DeleteObject(hfont);
/* test integer scaling 1x1 */
lf.lfHeight = height_orig;
lf.lfWidth = 0;
hfont = create_font("1x1", &lf);
old_hfont = SelectObject(hdc, hfont);
test_font_metrics(hdc, hfont, lf.lfHeight, lf.lfWidth, test_str, sizeof(test_str), &otm.otmTextMetrics, &size_orig, width_orig, 1, 1);
/* with an identity matrix */
memset(&gm, 0, sizeof(gm));
SetLastError(0xdeadbeef);
ret = GetGlyphOutlineA(hdc, 'A', GGO_METRICS, &gm, 0, NULL, &mat);
ok(ret != GDI_ERROR, "GetGlyphOutlineA error %d\n", GetLastError());
trace("gm.gmCellIncX %d, width_orig %d\n", gm.gmCellIncX, width_orig);
ok(gm.gmCellIncX == width_orig, "incX %d != %d\n", gm.gmCellIncX, width_orig);
ok(gm.gmCellIncY == 0, "incY %d != 0\n", gm.gmCellIncY);
/* with a custom matrix */
memset(&gm, 0, sizeof(gm));
SetLastError(0xdeadbeef);
ret = GetGlyphOutlineA(hdc, 'A', GGO_METRICS, &gm, 0, NULL, &mat2);
ok(ret != GDI_ERROR, "GetGlyphOutlineA error %d\n", GetLastError());
trace("gm.gmCellIncX %d, width_orig %d\n", gm.gmCellIncX, width_orig);
ok(gm.gmCellIncX == width_orig/2, "incX %d != %d\n", gm.gmCellIncX, width_orig/2);
ok(gm.gmCellIncY == 0, "incY %d != 0\n", gm.gmCellIncY);
/* Test that changing the DC transformation affects only the font
* selected on this DC and doesn't affect the same font selected on
* another DC.
*/
hdc_2 = CreateCompatibleDC(0);
old_hfont_2 = SelectObject(hdc_2, hfont);
test_font_metrics(hdc_2, hfont, lf.lfHeight, lf.lfWidth, test_str, sizeof(test_str), &otm.otmTextMetrics, &size_orig, width_orig, 1, 1);
SetMapMode(hdc, MM_ANISOTROPIC);
/* font metrics on another DC should be unchanged */
test_font_metrics(hdc_2, hfont, lf.lfHeight, lf.lfWidth, test_str, sizeof(test_str), &otm.otmTextMetrics, &size_orig, width_orig, 1, 1);
/* test restrictions of compatibility mode GM_COMPATIBLE */
/* part 1: rescaling only X should not change font scaling on screen.
So compressing the X axis by 2 is not done, and this
appears as X scaling of 2 that no one requested. */
SetWindowExtEx(hdc, 100, 100, NULL);
SetViewportExtEx(hdc, 50, 100, NULL);
test_font_metrics(hdc, hfont, lf.lfHeight, lf.lfWidth, test_str, sizeof(test_str), &otm.otmTextMetrics, &size_orig, width_orig, 2, 1);
/* font metrics on another DC should be unchanged */
test_font_metrics(hdc_2, hfont, lf.lfHeight, lf.lfWidth, test_str, sizeof(test_str), &otm.otmTextMetrics, &size_orig, width_orig, 1, 1);
/* part 2: rescaling only Y should change font scaling.
As also X is scaled by a factor of 2, but this is not
requested by the DC transformation, we get a scaling factor
of 2 in the X coordinate. */
SetViewportExtEx(hdc, 100, 200, NULL);
test_font_metrics(hdc, hfont, lf.lfHeight, lf.lfWidth, test_str, sizeof(test_str), &otm.otmTextMetrics, &size_orig, width_orig, 2, 1);
/* font metrics on another DC should be unchanged */
test_font_metrics(hdc_2, hfont, lf.lfHeight, lf.lfWidth, test_str, sizeof(test_str), &otm.otmTextMetrics, &size_orig, width_orig, 1, 1);
/* restore scaling */
SetMapMode(hdc, MM_TEXT);
/* font metrics on another DC should be unchanged */
test_font_metrics(hdc_2, hfont, lf.lfHeight, lf.lfWidth, test_str, sizeof(test_str), &otm.otmTextMetrics, &size_orig, width_orig, 1, 1);
SelectObject(hdc_2, old_hfont_2);
DeleteDC(hdc_2);
if (!SetGraphicsMode(hdc, GM_ADVANCED))
{
SelectObject(hdc, old_hfont);
DeleteObject(hfont);
DeleteDC(hdc);
skip("GM_ADVANCED is not supported on this platform\n");
return;
}
xform.eM11 = 20.0f;
xform.eM12 = 0.0f;
xform.eM21 = 0.0f;
xform.eM22 = 20.0f;
xform.eDx = 0.0f;
xform.eDy = 0.0f;
SetLastError(0xdeadbeef);
ret = SetWorldTransform(hdc, &xform);
ok(ret, "SetWorldTransform error %u\n", GetLastError());
test_font_metrics(hdc, hfont, lf.lfHeight, lf.lfWidth, test_str, sizeof(test_str), &otm.otmTextMetrics, &size_orig, width_orig, 1, 1);
/* with an identity matrix */
memset(&gm, 0, sizeof(gm));
SetLastError(0xdeadbeef);
ret = GetGlyphOutlineA(hdc, 'A', GGO_METRICS, &gm, 0, NULL, &mat);
ok(ret != GDI_ERROR, "GetGlyphOutlineA error %d\n", GetLastError());
trace("gm.gmCellIncX %d, width_orig %d\n", gm.gmCellIncX, width_orig);
pt.x = width_orig; pt.y = 0;
LPtoDP(hdc, &pt, 1);
ok(gm.gmCellIncX == pt.x, "incX %d != %d\n", gm.gmCellIncX, pt.x);
ok(gm.gmCellIncX == 20 * width_orig, "incX %d != %d\n", gm.gmCellIncX, 20 * width_orig);
ok(gm.gmCellIncY == 0, "incY %d != 0\n", gm.gmCellIncY);
/* with a custom matrix */
memset(&gm, 0, sizeof(gm));
SetLastError(0xdeadbeef);
ret = GetGlyphOutlineA(hdc, 'A', GGO_METRICS, &gm, 0, NULL, &mat2);
ok(ret != GDI_ERROR, "GetGlyphOutlineA error %d\n", GetLastError());
trace("gm.gmCellIncX %d, width_orig %d\n", gm.gmCellIncX, width_orig);
pt.x = width_orig; pt.y = 0;
LPtoDP(hdc, &pt, 1);
ok(gm.gmCellIncX == pt.x/2, "incX %d != %d\n", gm.gmCellIncX, pt.x/2);
ok(near_match(gm.gmCellIncX, 10 * width_orig), "incX %d != %d\n", gm.gmCellIncX, 10 * width_orig);
ok(gm.gmCellIncY == 0, "incY %d != 0\n", gm.gmCellIncY);
SetLastError(0xdeadbeef);
ret = SetMapMode(hdc, MM_LOMETRIC);
ok(ret == MM_TEXT, "expected MM_TEXT, got %d, error %u\n", ret, GetLastError());
test_font_metrics(hdc, hfont, lf.lfHeight, lf.lfWidth, test_str, sizeof(test_str), &otm.otmTextMetrics, &size_orig, width_orig, 1, 1);
/* with an identity matrix */
memset(&gm, 0, sizeof(gm));
SetLastError(0xdeadbeef);
ret = GetGlyphOutlineA(hdc, 'A', GGO_METRICS, &gm, 0, NULL, &mat);
ok(ret != GDI_ERROR, "GetGlyphOutlineA error %d\n", GetLastError());
trace("gm.gmCellIncX %d, width_orig %d\n", gm.gmCellIncX, width_orig);
pt.x = width_orig; pt.y = 0;
LPtoDP(hdc, &pt, 1);
ok(near_match(gm.gmCellIncX, pt.x), "incX %d != %d\n", gm.gmCellIncX, pt.x);
ok(gm.gmCellIncY == 0, "incY %d != 0\n", gm.gmCellIncY);
/* with a custom matrix */
memset(&gm, 0, sizeof(gm));
SetLastError(0xdeadbeef);
ret = GetGlyphOutlineA(hdc, 'A', GGO_METRICS, &gm, 0, NULL, &mat2);
ok(ret != GDI_ERROR, "GetGlyphOutlineA error %d\n", GetLastError());
trace("gm.gmCellIncX %d, width_orig %d\n", gm.gmCellIncX, width_orig);
pt.x = width_orig; pt.y = 0;
LPtoDP(hdc, &pt, 1);
ok(near_match(gm.gmCellIncX, (pt.x + 1)/2), "incX %d != %d\n", gm.gmCellIncX, (pt.x + 1)/2);
ok(gm.gmCellIncY == 0, "incY %d != 0\n", gm.gmCellIncY);
SetLastError(0xdeadbeef);
ret = SetMapMode(hdc, MM_TEXT);
ok(ret == MM_LOMETRIC, "expected MM_LOMETRIC, got %d, error %u\n", ret, GetLastError());
test_font_metrics(hdc, hfont, lf.lfHeight, lf.lfWidth, test_str, sizeof(test_str), &otm.otmTextMetrics, &size_orig, width_orig, 1, 1);
/* with an identity matrix */
memset(&gm, 0, sizeof(gm));
SetLastError(0xdeadbeef);
ret = GetGlyphOutlineA(hdc, 'A', GGO_METRICS, &gm, 0, NULL, &mat);
ok(ret != GDI_ERROR, "GetGlyphOutlineA error %d\n", GetLastError());
trace("gm.gmCellIncX %d, width_orig %d\n", gm.gmCellIncX, width_orig);
pt.x = width_orig; pt.y = 0;
LPtoDP(hdc, &pt, 1);
ok(gm.gmCellIncX == pt.x, "incX %d != %d\n", gm.gmCellIncX, pt.x);
ok(gm.gmCellIncX == 20 * width_orig, "incX %d != %d\n", gm.gmCellIncX, 20 * width_orig);
ok(gm.gmCellIncY == 0, "incY %d != 0\n", gm.gmCellIncY);
/* with a custom matrix */
memset(&gm, 0, sizeof(gm));
SetLastError(0xdeadbeef);
ret = GetGlyphOutlineA(hdc, 'A', GGO_METRICS, &gm, 0, NULL, &mat2);
ok(ret != GDI_ERROR, "GetGlyphOutlineA error %d\n", GetLastError());
trace("gm.gmCellIncX %d, width_orig %d\n", gm.gmCellIncX, width_orig);
pt.x = width_orig; pt.y = 0;
LPtoDP(hdc, &pt, 1);
ok(gm.gmCellIncX == pt.x/2, "incX %d != %d\n", gm.gmCellIncX, pt.x/2);
ok(gm.gmCellIncX == 10 * width_orig, "incX %d != %d\n", gm.gmCellIncX, 10 * width_orig);
ok(gm.gmCellIncY == 0, "incY %d != 0\n", gm.gmCellIncY);
SelectObject(hdc, old_hfont);
DeleteObject(hfont);
DeleteDC(hdc);
}
static INT CALLBACK find_font_proc(const LOGFONTA *elf, const TEXTMETRICA *ntm, DWORD type, LPARAM lParam)
{
LOGFONTA *lf = (LOGFONTA *)lParam;
if (elf->lfHeight == lf->lfHeight && !strcmp(elf->lfFaceName, lf->lfFaceName))
{
*lf = *elf;
return 0; /* stop enumeration */
}
return 1; /* continue enumeration */
}
static BOOL is_CJK(void)
{
return (system_lang_id == LANG_CHINESE || system_lang_id == LANG_JAPANESE || system_lang_id == LANG_KOREAN);
}
#define FH_SCALE 0x80000000
static void test_bitmap_font_metrics(void)
{
static const struct font_data
{
const char face_name[LF_FACESIZE];
int weight, height, ascent, descent, int_leading, ext_leading;
int ave_char_width, max_char_width, dpi;
BYTE first_char, last_char, def_char, break_char;
DWORD ansi_bitfield;
WORD skip_lang_id;
int scaled_height;
} fd[] =
{
{ "MS Sans Serif", FW_NORMAL, FH_SCALE | 6, 11, 2, 2, 0, 5, 11, 96, 0x20, 0xff, 0x81, 0x20, FS_LATIN1 | FS_LATIN2, LANG_ARABIC, 13 },
{ "MS Sans Serif", FW_NORMAL, FH_SCALE | 6, 11, 2, 2, 0, 5, 11, 96, 0x20, 0xff, 0x7f, 0x20, FS_CYRILLIC, 0, 13 },
{ "MS Sans Serif", FW_NORMAL, FH_SCALE | 8, 11, 2, 2, 0, 5, 11, 96, 0x20, 0xff, 0x81, 0x20, FS_LATIN1 | FS_LATIN2, LANG_ARABIC, 13 },
{ "MS Sans Serif", FW_NORMAL, FH_SCALE | 8, 11, 2, 2, 0, 5, 11, 96, 0x20, 0xff, 0x7f, 0x20, FS_CYRILLIC, 0, 13 },
{ "MS Sans Serif", FW_NORMAL, FH_SCALE | 10, 11, 2, 2, 0, 5, 11, 96, 0x20, 0xff, 0x81, 0x20, FS_LATIN1 | FS_LATIN2, LANG_ARABIC, 13 },
{ "MS Sans Serif", FW_NORMAL, FH_SCALE | 10, 11, 2, 2, 0, 5, 11, 96, 0x20, 0xff, 0x7f, 0x20, FS_CYRILLIC, 0, 13 },
{ "MS Sans Serif", FW_NORMAL, FH_SCALE | 14, 11, 2, 2, 0, 5, 11, 96, 0x20, 0xff, 0x81, 0x20, FS_LATIN1 | FS_LATIN2, LANG_ARABIC, 13 },
{ "MS Sans Serif", FW_NORMAL, FH_SCALE | 14, 11, 2, 2, 0, 5, 11, 96, 0x20, 0xff, 0x7f, 0x20, FS_CYRILLIC, 0, 13 },
{ "MS Sans Serif", FW_NORMAL, FH_SCALE | 18, 13, 3, 3, 0, 7, 14, 96, 0x20, 0xff, 0x81, 0x20, FS_LATIN1 | FS_LATIN2, LANG_ARABIC, 16 },
{ "MS Sans Serif", FW_NORMAL, FH_SCALE | 18, 13, 3, 3, 0, 7, 14, 96, 0x20, 0xff, 0x7f, 0x20, FS_CYRILLIC, 0, 16 },
{ "MS Sans Serif", FW_NORMAL, FH_SCALE | 6, 13, 3, 3, 0, 7, 14, 120, 0x20, 0xff, 0x81, 0x20, FS_LATIN1 | FS_LATIN2, 0, 16 },
{ "MS Sans Serif", FW_NORMAL, FH_SCALE | 6, 13, 3, 3, 0, 7, 14, 120, 0x20, 0xff, 0x7f, 0x20, FS_CYRILLIC, 0, 16 },
{ "MS Sans Serif", FW_NORMAL, FH_SCALE | 8, 13, 3, 3, 0, 7, 14, 120, 0x20, 0xff, 0x81, 0x20, FS_LATIN1 | FS_LATIN2, 0, 16 },
{ "MS Sans Serif", FW_NORMAL, FH_SCALE | 8, 13, 3, 3, 0, 7, 14, 120, 0x20, 0xff, 0x7f, 0x20, FS_CYRILLIC, 0, 16 },
{ "MS Sans Serif", FW_NORMAL, FH_SCALE | 10, 13, 3, 3, 0, 7, 14, 120, 0x20, 0xff, 0x81, 0x20, FS_LATIN1 | FS_LATIN2, 0, 16 },
{ "MS Sans Serif", FW_NORMAL, FH_SCALE | 10, 13, 3, 3, 0, 7, 14, 120, 0x20, 0xff, 0x7f, 0x20, FS_CYRILLIC, 0, 16 },
{ "MS Sans Serif", FW_NORMAL, FH_SCALE | 14, 13, 3, 3, 0, 7, 14, 120, 0x20, 0xff, 0x81, 0x20, FS_LATIN1 | FS_LATIN2, 0, 16 },
{ "MS Sans Serif", FW_NORMAL, FH_SCALE | 14, 13, 3, 3, 0, 7, 14, 120, 0x20, 0xff, 0x7f, 0x20, FS_CYRILLIC, 0, 16 },
{ "MS Sans Serif", FW_NORMAL, FH_SCALE | 18, 13, 3, 3, 0, 7, 14, 120, 0x20, 0xff, 0x81, 0x20, FS_LATIN1 | FS_LATIN2, 0, 16 },
{ "MS Sans Serif", FW_NORMAL, FH_SCALE | 18, 13, 3, 3, 0, 7, 14, 120, 0x20, 0xff, 0x7f, 0x20, FS_CYRILLIC, 0, 16 },
{ "MS Sans Serif", FW_NORMAL, 13, 11, 2, 2, 0, 5, 11, 96, 0x20, 0xff, 0x81, 0x20, FS_LATIN1 | FS_LATIN2 },
{ "MS Sans Serif", FW_NORMAL, 13, 11, 2, 2, 0, 5, 11, 96, 0x20, 0xff, 0x7f, 0x20, FS_CYRILLIC },
{ "MS Sans Serif", FW_NORMAL, 16, 13, 3, 3, 0, 7, 14, 96, 0x20, 0xff, 0x81, 0x20, FS_LATIN1 | FS_LATIN2 },
{ "MS Sans Serif", FW_NORMAL, 16, 13, 3, 3, 0, 7, 14, 96, 0x20, 0xff, 0x7f, 0x20, FS_CYRILLIC },
{ "MS Sans Serif", FW_NORMAL, 20, 16, 4, 4, 0, 8, 16, 96, 0x20, 0xff, 0x81, 0x20, FS_LATIN1 },
{ "MS Sans Serif", FW_NORMAL, 20, 16, 4, 4, 0, 8, 18, 96, 0x20, 0xff, 0x81, 0x20, FS_LATIN2 },
{ "MS Sans Serif", FW_NORMAL, 20, 16, 4, 4, 0, 8, 16, 96, 0x20, 0xff, 0x7f, 0x20, FS_CYRILLIC },
{ "MS Sans Serif", FW_NORMAL, 24, 19, 5, 6, 0, 9, 19, 96, 0x20, 0xff, 0x81, 0x20, FS_LATIN1 },
{ "MS Sans Serif", FW_NORMAL, 24, 19, 5, 6, 0, 9, 24, 96, 0x20, 0xff, 0x81, 0x40, FS_LATIN2 },
{ "MS Sans Serif", FW_NORMAL, 24, 19, 5, 6, 0, 9, 20, 96, 0x20, 0xff, 0x7f, 0x20, FS_CYRILLIC },
{ "MS Sans Serif", FW_NORMAL, 29, 23, 6, 5, 0, 12, 24, 96, 0x20, 0xff, 0x81, 0x20, FS_LATIN1 },
{ "MS Sans Serif", FW_NORMAL, 29, 23, 6, 6, 0, 12, 24, 96, 0x20, 0xff, 0x81, 0x20, FS_LATIN2 },
{ "MS Sans Serif", FW_NORMAL, 29, 23, 6, 5, 0, 12, 25, 96, 0x20, 0xff, 0x7f, 0x20, FS_CYRILLIC },
{ "MS Sans Serif", FW_NORMAL, 37, 29, 8, 5, 0, 16, 32, 96, 0x20, 0xff, 0x81, 0x20, FS_LATIN1 },
{ "MS Sans Serif", FW_NORMAL, 37, 29, 8, 5, 0, 16, 32, 96, 0x20, 0xff, 0x81, 0x40, FS_LATIN2 },
{ "MS Sans Serif", FW_NORMAL, 37, 29, 8, 5, 0, 16, 32, 96, 0x20, 0xff, 0x7f, 0x20, FS_CYRILLIC },
{ "MS Sans Serif", FW_NORMAL, 16, 13, 3, 3, 0, 7, 14, 120, 0x20, 0xff, 0x81, 0x20, FS_LATIN1 | FS_LATIN2 },
{ "MS Sans Serif", FW_NORMAL, 16, 13, 3, 3, 0, 7, 14, 120, 0x20, 0xff, 0x7f, 0x20, FS_CYRILLIC },
{ "MS Sans Serif", FW_NORMAL, 20, 16, 4, 4, 0, 8, 18, 120, 0x20, 0xff, 0x81, 0x20, FS_LATIN1 | FS_LATIN2 },
{ "MS Sans Serif", FW_NORMAL, 20, 16, 4, 4, 0, 8, 17, 120, 0x20, 0xff, 0x7f, 0x20, FS_CYRILLIC },
{ "MS Sans Serif", FW_NORMAL, 25, 20, 5, 5, 0, 10, 21, 120, 0x20, 0xff, 0x81, 0x20, FS_LATIN1 | FS_LATIN2 },
{ "MS Sans Serif", FW_NORMAL, 25, 20, 5, 5, 0, 10, 21, 120, 0x20, 0xff, 0x7f, 0x20, FS_CYRILLIC },
{ "MS Sans Serif", FW_NORMAL, 29, 23, 6, 6, 0, 12, 24, 120, 0x20, 0xff, 0x81, 0x20, FS_LATIN1 | FS_LATIN2 },
{ "MS Sans Serif", FW_NORMAL, 29, 23, 6, 5, 0, 12, 24, 120, 0x20, 0xff, 0x7f, 0x20, FS_CYRILLIC },
{ "MS Sans Serif", FW_NORMAL, 36, 29, 7, 6, 0, 15, 30, 120, 0x20, 0xff, 0x81, 0x20, FS_LATIN1 | FS_LATIN2 },
{ "MS Sans Serif", FW_NORMAL, 36, 29, 7, 6, 0, 15, 30, 120, 0x20, 0xff, 0x7f, 0x20, FS_CYRILLIC },
{ "MS Sans Serif", FW_NORMAL, 46, 37, 9, 6, 0, 20, 40, 120, 0x20, 0xff, 0x81, 0x20, FS_LATIN1 | FS_LATIN2 },
{ "MS Sans Serif", FW_NORMAL, 46, 37, 9, 6, 0, 20, 40, 120, 0x20, 0xff, 0x7f, 0x20, FS_CYRILLIC },
{ "MS Serif", FW_NORMAL, 10, 8, 2, 2, 0, 4, 8, 96, 0x20, 0xff, 0x80, 0x20, FS_LATIN1 | FS_LATIN2 },
{ "MS Serif", FW_NORMAL, 10, 8, 2, 2, 0, 5, 8, 96, 0x20, 0xff, 0x80, 0x20, FS_CYRILLIC },
{ "MS Serif", FW_NORMAL, 11, 9, 2, 2, 0, 5, 9, 96, 0x20, 0xff, 0x80, 0x20, FS_LATIN1 | FS_LATIN2 | FS_CYRILLIC },
{ "MS Serif", FW_NORMAL, 13, 11, 2, 2, 0, 5, 11, 96, 0x20, 0xff, 0x80, 0x20, FS_LATIN1 },
{ "MS Serif", FW_NORMAL, 13, 11, 2, 2, 0, 5, 12, 96, 0x20, 0xff, 0x80, 0x20, FS_LATIN2 | FS_CYRILLIC },
{ "MS Serif", FW_NORMAL, 16, 13, 3, 3, 0, 6, 14, 96, 0x20, 0xff, 0x80, 0x20, FS_LATIN1 | FS_LATIN2 },
{ "MS Serif", FW_NORMAL, 16, 13, 3, 3, 0, 6, 16, 96, 0x20, 0xff, 0x80, 0x20, FS_CYRILLIC },
{ "MS Serif", FW_NORMAL, 19, 15, 4, 3, 0, 8, 18, 96, 0x20, 0xff, 0x80, 0x20, FS_LATIN1 | FS_LATIN2 },
{ "MS Serif", FW_NORMAL, 19, 15, 4, 3, 0, 8, 19, 96, 0x20, 0xff, 0x80, 0x20, FS_CYRILLIC },
{ "MS Serif", FW_NORMAL, 21, 16, 5, 3, 0, 9, 17, 96, 0x20, 0xff, 0x80, 0x20, FS_LATIN1 },
{ "MS Serif", FW_NORMAL, 21, 16, 5, 3, 0, 9, 22, 96, 0x20, 0xff, 0x80, 0x20, FS_LATIN2 },
{ "MS Serif", FW_NORMAL, 21, 16, 5, 3, 0, 9, 23, 96, 0x20, 0xff, 0x80, 0x20, FS_CYRILLIC },
{ "MS Serif", FW_NORMAL, 27, 21, 6, 3, 0, 12, 23, 96, 0x20, 0xff, 0x80, 0x20, FS_LATIN1 },
{ "MS Serif", FW_NORMAL, 27, 21, 6, 3, 0, 12, 26, 96, 0x20, 0xff, 0x80, 0x20, FS_LATIN2 },
{ "MS Serif", FW_NORMAL, 27, 21, 6, 3, 0, 12, 27, 96, 0x20, 0xff, 0x80, 0x20, FS_CYRILLIC },
{ "MS Serif", FW_NORMAL, 35, 27, 8, 3, 0, 16, 33, 96, 0x20, 0xff, 0x80, 0x20, FS_LATIN1 | FS_LATIN2 },
{ "MS Serif", FW_NORMAL, 35, 27, 8, 3, 0, 16, 34, 96, 0x20, 0xff, 0x80, 0x20, FS_CYRILLIC },
{ "MS Serif", FW_NORMAL, 16, 13, 3, 3, 0, 6, 14, 120, 0x20, 0xff, 0x80, 0x20, FS_LATIN1 | FS_CYRILLIC },
{ "MS Serif", FW_NORMAL, 16, 13, 3, 3, 0, 6, 13, 120, 0x20, 0xff, 0x80, 0x20, FS_LATIN2 },
{ "MS Serif", FW_NORMAL, 20, 16, 4, 4, 0, 8, 18, 120, 0x20, 0xff, 0x80, 0x20, FS_LATIN1 | FS_CYRILLIC },
{ "MS Serif", FW_NORMAL, 20, 16, 4, 4, 0, 8, 15, 120, 0x20, 0xff, 0x80, 0x20, FS_LATIN2 },
{ "MS Serif", FW_NORMAL, 23, 18, 5, 3, 0, 10, 21, 120, 0x20, 0xff, 0x80, 0x20, FS_LATIN1 | FS_CYRILLIC },
{ "MS Serif", FW_NORMAL, 23, 18, 5, 3, 0, 10, 19, 120, 0x20, 0xff, 0x80, 0x20, FS_LATIN2 },
{ "MS Serif", FW_NORMAL, 27, 21, 6, 4, 0, 12, 23, 120, 0x20, 0xff, 0x80, 0x20, FS_LATIN1 | FS_LATIN2 },
{ "MS Serif", FW_MEDIUM, 27, 22, 5, 2, 0, 12, 30, 120, 0x20, 0xff, 0x80, 0x20, FS_CYRILLIC },
{ "MS Serif", FW_NORMAL, 33, 26, 7, 3, 0, 14, 30, 120, 0x20, 0xff, 0x80, 0x20, FS_LATIN1 | FS_LATIN2 },
{ "MS Serif", FW_MEDIUM, 32, 25, 7, 2, 0, 14, 32, 120, 0x20, 0xff, 0x80, 0x20, FS_CYRILLIC },
{ "MS Serif", FW_NORMAL, 43, 34, 9, 3, 0, 19, 39, 120, 0x20, 0xff, 0x80, 0x20, FS_LATIN1 | FS_LATIN2 | FS_CYRILLIC },
{ "Courier", FW_NORMAL, 13, 11, 2, 0, 0, 8, 8, 96, 0x20, 0xff, 0x80, 0x20, FS_LATIN1 | FS_LATIN2 | FS_CYRILLIC },
{ "Courier", FW_NORMAL, 16, 13, 3, 0, 0, 9, 9, 96, 0x20, 0xff, 0x80, 0x20, FS_LATIN1 | FS_LATIN2 | FS_CYRILLIC },
{ "Courier", FW_NORMAL, 20, 16, 4, 0, 0, 12, 12, 96, 0x20, 0xff, 0x80, 0x20, FS_LATIN1 | FS_LATIN2 | FS_CYRILLIC },
{ "Courier", FW_NORMAL, 16, 13, 3, 0, 0, 9, 9, 120, 0x20, 0xff, 0x80, 0x20, FS_LATIN1 | FS_LATIN2 | FS_CYRILLIC },
{ "Courier", FW_NORMAL, 20, 16, 4, 0, 0, 12, 12, 120, 0x20, 0xff, 0x80, 0x20, FS_LATIN1 | FS_LATIN2 | FS_CYRILLIC },
{ "Courier", FW_NORMAL, 25, 20, 5, 0, 0, 15, 15, 120, 0x20, 0xff, 0x40, 0x20, FS_LATIN1 | FS_LATIN2 | FS_CYRILLIC },
{ "System", FW_BOLD, 16, 13, 3, 3, 0, 7, 14, 96, 0x20, 0xff, 0x80, 0x20, FS_LATIN1 },
{ "System", FW_BOLD, 16, 13, 3, 3, 0, 7, 15, 96, 0x20, 0xff, 0x80, 0x20, FS_LATIN2 | FS_CYRILLIC },
{ "System", FW_NORMAL, 18, 16, 2, 0, 2, 8, 16, 96, 0x20, 0xff, 0x80, 0x20, FS_JISJAPAN },
{ "System", FW_BOLD, 20, 16, 4, 4, 0, 9, 14, 120, 0x20, 0xff, 0x80, 0x20, FS_LATIN1 },
{ "System", FW_BOLD, 20, 16, 4, 4, 0, 9, 17, 120, 0x20, 0xff, 0x80, 0x20, FS_LATIN2 | FS_CYRILLIC },
{ "Small Fonts", FW_NORMAL, 3, 2, 1, 0, 0, 1, 2, 96, 0x20, 0xff, 0x80, 0x20, FS_LATIN1 },
{ "Small Fonts", FW_NORMAL, 3, 2, 1, 0, 0, 1, 8, 96, 0x20, 0xff, 0x80, 0x20, FS_LATIN2 | FS_CYRILLIC },
{ "Small Fonts", FW_NORMAL, 3, 2, 1, 0, 0, 2, 4, 96, 0x20, 0xff, 0x80, 0x20, FS_JISJAPAN },
{ "Small Fonts", FW_NORMAL, 5, 4, 1, 1, 0, 3, 4, 96, 0x20, 0xff, 0x80, 0x20, FS_LATIN1, LANG_ARABIC },
{ "Small Fonts", FW_NORMAL, 5, 4, 1, 1, 0, 2, 8, 96, 0x20, 0xff, 0x80, 0x20, FS_LATIN2 | FS_CYRILLIC },
{ "Small Fonts", FW_NORMAL, 5, 4, 1, 0, 0, 3, 6, 96, 0x20, 0xff, 0x80, 0x20, FS_JISJAPAN },
{ "Small Fonts", FW_NORMAL, 6, 5, 1, 1, 0, 3, 13, 96, 0x20, 0xff, 0x80, 0x20, FS_LATIN1, LANG_ARABIC },
{ "Small Fonts", FW_NORMAL, 6, 5, 1, 1, 0, 3, 8, 96, 0x20, 0xff, 0x80, 0x20, FS_LATIN2 | FS_CYRILLIC },
{ "Small Fonts", FW_NORMAL, 6, 5, 1, 1, 0, 3, 8, 96, 0x00, 0xff, 0x60, 0x00, FS_ARABIC },
{ "Small Fonts", FW_NORMAL, 6, 5, 1, 0, 0, 4, 8, 96, 0x20, 0xff, 0x80, 0x20, FS_JISJAPAN },
{ "Small Fonts", FW_NORMAL, 8, 7, 1, 1, 0, 4, 7, 96, 0x20, 0xff, 0x80, 0x20, FS_LATIN1, LANG_ARABIC },
{ "Small Fonts", FW_NORMAL, 8, 7, 1, 1, 0, 4, 8, 96, 0x20, 0xff, 0x80, 0x20, FS_LATIN2 | FS_CYRILLIC },
{ "Small Fonts", FW_NORMAL, 8, 7, 1, 1, 0, 4, 8, 96, 0x00, 0xff, 0x60, 0x00, FS_ARABIC },
{ "Small Fonts", FW_NORMAL, 8, 7, 1, 0, 0, 5, 10, 96, 0x20, 0xff, 0x80, 0x20, FS_JISJAPAN },
{ "Small Fonts", FW_NORMAL, 10, 8, 2, 2, 0, 4, 8, 96, 0x20, 0xff, 0x80, 0x20, FS_LATIN1 | FS_LATIN2, LANG_ARABIC },
{ "Small Fonts", FW_NORMAL, 10, 8, 2, 2, 0, 5, 8, 96, 0x20, 0xff, 0x80, 0x20, FS_CYRILLIC },
{ "Small Fonts", FW_NORMAL, 10, 8, 2, 2, 0, 4, 9, 96, 0x00, 0xff, 0x60, 0x00, FS_ARABIC },
{ "Small Fonts", FW_NORMAL, 10, 8, 2, 0, 0, 6, 12, 96, 0x20, 0xff, 0x80, 0x20, FS_JISJAPAN },
{ "Small Fonts", FW_NORMAL, 11, 9, 2, 2, 0, 5, 9, 96, 0x20, 0xff, 0x80, 0x20, FS_LATIN1 | FS_LATIN2 | FS_CYRILLIC, LANG_ARABIC },
{ "Small Fonts", FW_NORMAL, 11, 9, 2, 2, 0, 4, 10, 96, 0x00, 0xff, 0x60, 0x00, FS_ARABIC },
{ "Small Fonts", FW_NORMAL, 11, 9, 2, 0, 0, 7, 14, 96, 0x20, 0xff, 0x80, 0x20, FS_JISJAPAN },
{ "Small Fonts", FW_NORMAL, 3, 2, 1, 0, 0, 1, 2, 120, 0x20, 0xff, 0x80, 0x20, FS_LATIN1 | FS_JISJAPAN },
{ "Small Fonts", FW_NORMAL, 3, 2, 1, 0, 0, 1, 8, 120, 0x20, 0xff, 0x80, 0x20, FS_LATIN2 | FS_CYRILLIC },
{ "Small Fonts", FW_NORMAL, 6, 5, 1, 1, 0, 3, 5, 120, 0x20, 0xff, 0x80, 0x20, FS_LATIN1 | FS_JISJAPAN },
{ "Small Fonts", FW_NORMAL, 6, 5, 1, 1, 0, 3, 8, 120, 0x20, 0xff, 0x80, 0x20, FS_LATIN2 | FS_CYRILLIC },
{ "Small Fonts", FW_NORMAL, 8, 7, 1, 1, 0, 4, 7, 120, 0x20, 0xff, 0x80, 0x20, FS_LATIN1 | FS_JISJAPAN },
{ "Small Fonts", FW_NORMAL, 8, 7, 1, 1, 0, 4, 8, 120, 0x20, 0xff, 0x80, 0x20, FS_LATIN2 | FS_CYRILLIC },
{ "Small Fonts", FW_NORMAL, 10, 8, 2, 2, 0, 5, 9, 120, 0x20, 0xff, 0x80, 0x20, FS_LATIN1 | FS_LATIN2 | FS_JISJAPAN },
{ "Small Fonts", FW_NORMAL, 10, 8, 2, 2, 0, 5, 8, 120, 0x20, 0xff, 0x80, 0x20, FS_CYRILLIC },
{ "Small Fonts", FW_NORMAL, 12, 10, 2, 2, 0, 5, 10, 120, 0x20, 0xff, 0x80, 0x20, FS_LATIN1 | FS_LATIN2 | FS_JISJAPAN },
{ "Small Fonts", FW_NORMAL, 12, 10, 2, 2, 0, 6, 10, 120, 0x20, 0xff, 0x80, 0x20, FS_CYRILLIC },
{ "Small Fonts", FW_NORMAL, 13, 11, 2, 2, 0, 6, 12, 120, 0x20, 0xff, 0x80, 0x20, FS_LATIN1 | FS_LATIN2 | FS_JISJAPAN },
{ "Small Fonts", FW_NORMAL, 13, 11, 2, 2, 0, 6, 11, 120, 0x20, 0xff, 0x80, 0x20, FS_CYRILLIC },
{ "Fixedsys", FW_NORMAL, 15, 12, 3, 3, 0, 8, 8, 96, 0x20, 0xff, 0x80, 0x20, FS_LATIN1 | FS_LATIN2 },
{ "Fixedsys", FW_NORMAL, 16, 12, 4, 3, 0, 8, 8, 96, 0x20, 0xff, 0x80, 0x20, FS_CYRILLIC },
{ "FixedSys", FW_NORMAL, 18, 16, 2, 0, 0, 8, 16, 96, 0x20, 0xff, 0xa0, 0x20, FS_JISJAPAN },
{ "Fixedsys", FW_NORMAL, 20, 16, 4, 2, 0, 10, 10, 120, 0x20, 0xff, 0x80, 0x20, FS_LATIN1 | FS_LATIN2 | FS_CYRILLIC }
/* FIXME: add "Terminal" */
};
static const int font_log_pixels[] = { 96, 120 };
HDC hdc;
LOGFONTA lf;
HFONT hfont, old_hfont;
TEXTMETRICA tm;
INT ret, i, expected_cs, screen_log_pixels, diff, font_res;
char face_name[LF_FACESIZE];
CHARSETINFO csi;
trace("system language id %04x\n", system_lang_id);
expected_cs = GetACP();
if (!TranslateCharsetInfo(ULongToPtr(expected_cs), &csi, TCI_SRCCODEPAGE))
{
skip("TranslateCharsetInfo failed for code page %d\n", expected_cs);
return;
}
expected_cs = csi.ciCharset;
trace("ACP %d -> charset %d\n", GetACP(), expected_cs);
hdc = CreateCompatibleDC(0);
assert(hdc);
trace("logpixelsX %d, logpixelsY %d\n", GetDeviceCaps(hdc, LOGPIXELSX),
GetDeviceCaps(hdc, LOGPIXELSY));
screen_log_pixels = GetDeviceCaps(hdc, LOGPIXELSY);
diff = 32768;
font_res = 0;
for (i = 0; i < sizeof(font_log_pixels)/sizeof(font_log_pixels[0]); i++)
{
int new_diff = abs(font_log_pixels[i] - screen_log_pixels);
if (new_diff < diff)
{
diff = new_diff;
font_res = font_log_pixels[i];
}
}
trace("best font resolution is %d\n", font_res);
for (i = 0; i < sizeof(fd)/sizeof(fd[0]); i++)
{
int bit, height;
memset(&lf, 0, sizeof(lf));
height = fd[i].height & ~FH_SCALE;
lf.lfHeight = height;
strcpy(lf.lfFaceName, fd[i].face_name);
for(bit = 0; bit < 32; bit++)
{
GLYPHMETRICS gm;
DWORD fs[2];
BOOL bRet;
fs[0] = 1L << bit;
fs[1] = 0;
if((fd[i].ansi_bitfield & fs[0]) == 0) continue;
if(!TranslateCharsetInfo( fs, &csi, TCI_SRCFONTSIG )) continue;
lf.lfCharSet = csi.ciCharset;
trace("looking for %s height %d charset %d\n", lf.lfFaceName, lf.lfHeight, lf.lfCharSet);
ret = EnumFontFamiliesExA(hdc, &lf, find_font_proc, (LPARAM)&lf, 0);
if (fd[i].height & FH_SCALE)
ok(ret, "scaled font height %d should not be enumerated\n", height);
else
{
if (font_res == fd[i].dpi && lf.lfCharSet == expected_cs)
{
if (ret) /* FIXME: Remove once Wine is fixed */
todo_wine ok(!ret, "%s height %d charset %d dpi %d should be enumerated\n", lf.lfFaceName, lf.lfHeight, lf.lfCharSet, fd[i].dpi);
else
ok(!ret, "%s height %d charset %d dpi %d should be enumerated\n", lf.lfFaceName, lf.lfHeight, lf.lfCharSet, fd[i].dpi);
}
}
if (ret && !(fd[i].height & FH_SCALE))
continue;
hfont = create_font(lf.lfFaceName, &lf);
old_hfont = SelectObject(hdc, hfont);
SetLastError(0xdeadbeef);
ret = GetTextFaceA(hdc, sizeof(face_name), face_name);
ok(ret, "GetTextFace error %u\n", GetLastError());
if (strcmp(face_name, fd[i].face_name) != 0)
{
ok(ret != ANSI_CHARSET, "font charset should not be ANSI_CHARSET\n");
ok(ret != expected_cs, "font charset %d should not be %d\n", ret, expected_cs);
trace("Skipping replacement %s height %d charset %d\n", face_name, tm.tmHeight, tm.tmCharSet);
SelectObject(hdc, old_hfont);
DeleteObject(hfont);
continue;
}
memset(&gm, 0, sizeof(gm));
SetLastError(0xdeadbeef);
ret = GetGlyphOutlineA(hdc, 'A', GGO_METRICS, &gm, 0, NULL, &mat);
todo_wine {
ok(ret == GDI_ERROR, "GetGlyphOutline should fail for a bitmap font\n");
ok(GetLastError() == ERROR_CAN_NOT_COMPLETE, "expected ERROR_CAN_NOT_COMPLETE, got %u\n", GetLastError());
}
bRet = GetTextMetricsA(hdc, &tm);
ok(bRet, "GetTextMetrics error %d\n", GetLastError());
SetLastError(0xdeadbeef);
ret = GetTextCharset(hdc);
if (is_CJK() && lf.lfCharSet == ANSI_CHARSET)
ok(ret == ANSI_CHARSET, "got charset %d, expected ANSI_CHARSETd\n", ret);
else
ok(ret == expected_cs, "got charset %d, expected %d\n", ret, expected_cs);
trace("created %s, height %d charset %x dpi %d\n", face_name, tm.tmHeight, tm.tmCharSet, tm.tmDigitizedAspectX);
trace("expected %s, height %d scaled_hight %d, dpi %d\n", fd[i].face_name, height, fd[i].scaled_height, fd[i].dpi);
if(fd[i].dpi == tm.tmDigitizedAspectX)
{
trace("matched %s, height %d charset %x dpi %d\n", lf.lfFaceName, lf.lfHeight, lf.lfCharSet, fd[i].dpi);
if (fd[i].skip_lang_id == 0 || system_lang_id != fd[i].skip_lang_id)
{
ok(tm.tmWeight == fd[i].weight, "%s(%d): tm.tmWeight %d != %d\n", fd[i].face_name, height, tm.tmWeight, fd[i].weight);
if (fd[i].height & FH_SCALE)
ok(tm.tmHeight == fd[i].scaled_height, "%s(%d): tm.tmHeight %d != %d\n", fd[i].face_name, height, tm.tmHeight, fd[i].scaled_height);
else
ok(tm.tmHeight == fd[i].height, "%s(%d): tm.tmHeight %d != %d\n", fd[i].face_name, fd[i].height, tm.tmHeight, fd[i].height);
ok(tm.tmAscent == fd[i].ascent, "%s(%d): tm.tmAscent %d != %d\n", fd[i].face_name, height, tm.tmAscent, fd[i].ascent);
ok(tm.tmDescent == fd[i].descent, "%s(%d): tm.tmDescent %d != %d\n", fd[i].face_name, height, tm.tmDescent, fd[i].descent);
ok(tm.tmInternalLeading == fd[i].int_leading, "%s(%d): tm.tmInternalLeading %d != %d\n", fd[i].face_name, height, tm.tmInternalLeading, fd[i].int_leading);
ok(tm.tmExternalLeading == fd[i].ext_leading, "%s(%d): tm.tmExternalLeading %d != %d\n", fd[i].face_name, height, tm.tmExternalLeading, fd[i].ext_leading);
ok(tm.tmAveCharWidth == fd[i].ave_char_width, "%s(%d): tm.tmAveCharWidth %d != %d\n", fd[i].face_name, height, tm.tmAveCharWidth, fd[i].ave_char_width);
ok(tm.tmFirstChar == fd[i].first_char, "%s(%d): tm.tmFirstChar = %02x\n", fd[i].face_name, height, tm.tmFirstChar);
ok(tm.tmLastChar == fd[i].last_char, "%s(%d): tm.tmLastChar = %02x\n", fd[i].face_name, height, tm.tmLastChar);
/* Substitutions like MS Sans Serif,0=MS Sans Serif,204
make default char test fail */
if (tm.tmCharSet == lf.lfCharSet)
ok(tm.tmDefaultChar == fd[i].def_char, "%s(%d): tm.tmDefaultChar = %02x\n", fd[i].face_name, height, tm.tmDefaultChar);
ok(tm.tmBreakChar == fd[i].break_char, "%s(%d): tm.tmBreakChar = %02x\n", fd[i].face_name, height, tm.tmBreakChar);
ok(tm.tmCharSet == expected_cs || tm.tmCharSet == ANSI_CHARSET, "%s(%d): tm.tmCharSet %d != %d\n", fd[i].face_name, height, tm.tmCharSet, expected_cs);
/* Don't run the max char width test on System/ANSI_CHARSET. We have extra characters in our font
that make the max width bigger */
if ((strcmp(lf.lfFaceName, "System") || lf.lfCharSet != ANSI_CHARSET) && tm.tmDigitizedAspectX == 96)
ok(tm.tmMaxCharWidth == fd[i].max_char_width, "%s(%d): tm.tmMaxCharWidth %d != %d\n", fd[i].face_name, height, tm.tmMaxCharWidth, fd[i].max_char_width);
}
else
skip("Skipping font metrics test for system langid 0x%x\n",
system_lang_id);
}
SelectObject(hdc, old_hfont);
DeleteObject(hfont);
}
}
DeleteDC(hdc);
}
static void test_GdiGetCharDimensions(void)
{
HDC hdc;
TEXTMETRICW tm;
LONG ret;
SIZE size;
LONG avgwidth, height;
static const char szAlphabet[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
if (!pGdiGetCharDimensions)
{
win_skip("GdiGetCharDimensions not available on this platform\n");
return;
}
hdc = CreateCompatibleDC(NULL);
GetTextExtentPointA(hdc, szAlphabet, strlen(szAlphabet), &size);
avgwidth = ((size.cx / 26) + 1) / 2;
ret = pGdiGetCharDimensions(hdc, &tm, &height);
ok(ret == avgwidth, "GdiGetCharDimensions should have returned width of %d instead of %d\n", avgwidth, ret);
ok(height == tm.tmHeight, "GdiGetCharDimensions should have set height to %d instead of %d\n", tm.tmHeight, height);
ret = pGdiGetCharDimensions(hdc, &tm, NULL);
ok(ret == avgwidth, "GdiGetCharDimensions should have returned width of %d instead of %d\n", avgwidth, ret);
ret = pGdiGetCharDimensions(hdc, NULL, NULL);
ok(ret == avgwidth, "GdiGetCharDimensions should have returned width of %d instead of %d\n", avgwidth, ret);
height = 0;
ret = pGdiGetCharDimensions(hdc, NULL, &height);
ok(ret == avgwidth, "GdiGetCharDimensions should have returned width of %d instead of %d\n", avgwidth, ret);
ok(height == size.cy, "GdiGetCharDimensions should have set height to %d instead of %d\n", size.cy, height);
DeleteDC(hdc);
}
static int CALLBACK create_font_proc(const LOGFONTA *lpelfe,
const TEXTMETRICA *lpntme,
DWORD FontType, LPARAM lParam)
{
if (FontType & TRUETYPE_FONTTYPE)
{
HFONT hfont;
hfont = CreateFontIndirectA(lpelfe);
if (hfont)
{
*(HFONT *)lParam = hfont;
return 0;
}
}
return 1;
}
static void ABCWidths_helper(const char* description, HDC hdc, WORD *glyphs, ABC *base_abci, ABC *base_abcw, ABCFLOAT *base_abcf, INT todo)
{
ABC abc[1];
ABCFLOAT abcf[1];
BOOL ret = FALSE;
ret = pGetCharABCWidthsI(hdc, 0, 1, glyphs, abc);
ok(ret, "%s: GetCharABCWidthsI should have succeeded\n", description);
ok ((INT)abc->abcB > 0, "%s: abcB should be positive\n", description);
if (todo) todo_wine ok(abc->abcA * base_abci->abcA >= 0, "%s: abcA's sign should be unchanged\n", description);
else ok(abc->abcA * base_abci->abcA >= 0, "%s: abcA's sign should be unchanged\n", description);
if (todo) todo_wine ok(abc->abcC * base_abci->abcC >= 0, "%s: abcC's sign should be unchanged\n", description);
else ok(abc->abcC * base_abci->abcC >= 0, "%s: abcC's sign should be unchanged\n", description);
ret = pGetCharABCWidthsW(hdc, 'i', 'i', abc);
ok(ret, "%s: GetCharABCWidthsW should have succeeded\n", description);
ok ((INT)abc->abcB > 0, "%s: abcB should be positive\n", description);
if (todo) todo_wine ok(abc->abcA * base_abcw->abcA >= 0, "%s: abcA's sign should be unchanged\n", description);
else ok(abc->abcA * base_abcw->abcA >= 0, "%s: abcA's sign should be unchanged\n", description);
if (todo) todo_wine ok(abc->abcC * base_abcw->abcC >= 0, "%s: abcC's sign should be unchanged\n", description);
else ok(abc->abcC * base_abcw->abcC >= 0, "%s: abcC's should be unchanged\n", description);
ret = pGetCharABCWidthsFloatW(hdc, 'i', 'i', abcf);
ok(ret, "%s: GetCharABCWidthsFloatW should have succeeded\n", description);
ok (abcf->abcfB > 0.0, "%s: abcfB should be positive\n", description);
if (todo) todo_wine ok(abcf->abcfA * base_abcf->abcfA >= 0.0, "%s: abcfA's sign should be unchanged\n", description);
else ok(abcf->abcfA * base_abcf->abcfA >= 0.0, "%s: abcfA's should be unchanged\n", description);
if (todo) todo_wine ok(abcf->abcfC * base_abcf->abcfC >= 0.0, "%s: abcfC's sign should be unchanged\n", description);
else ok(abcf->abcfC * base_abcf->abcfC >= 0.0, "%s: abcfC's sign should be unchanged\n", description);
}
static void test_GetCharABCWidths(void)
{
static const WCHAR str[] = {'i',0};
BOOL ret;
HDC hdc;
LOGFONTA lf;
HFONT hfont;
ABC abc[1];
ABC abcw[1];
ABCFLOAT abcf[1];
WORD glyphs[1];
DWORD nb;
HWND hwnd;
static const struct
{
UINT first;
UINT last;
} range[] =
{
{0xff, 0xff},
{0x100, 0x100},
{0xff, 0x100},
{0x1ff, 0xff00},
{0xffff, 0xffff},
{0x10000, 0x10000},
{0xffff, 0x10000},
{0xffffff, 0xffffff},
{0x1000000, 0x1000000},
{0xffffff, 0x1000000},
{0xffffffff, 0xffffffff},
{0x00, 0xff}
};
static const struct
{
UINT cs;
UINT a;
UINT w;
BOOL r[sizeof range / sizeof range[0]];
} c[] =
{
{ANSI_CHARSET, 0x30, 0x30,
{TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE}},
{SHIFTJIS_CHARSET, 0x82a0, 0x3042,
{TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE}},
{HANGEUL_CHARSET, 0x8141, 0xac02,
{TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE}},
{GB2312_CHARSET, 0x8141, 0x4e04,
{TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE}},
{CHINESEBIG5_CHARSET, 0xa142, 0x3001,
{TRUE, TRUE, FALSE, FALSE, TRUE, FALSE, FALSE, FALSE, FALSE, FALSE, FALSE, TRUE}}
};
UINT i;
if (!pGetCharABCWidthsA || !pGetCharABCWidthsW || !pGetCharABCWidthsFloatW || !pGetCharABCWidthsI)
{
win_skip("GetCharABCWidthsA/W/I not available on this platform\n");
return;
}
memset(&lf, 0, sizeof(lf));
strcpy(lf.lfFaceName, "System");
lf.lfHeight = 20;
hfont = CreateFontIndirectA(&lf);
hdc = GetDC(0);
hfont = SelectObject(hdc, hfont);
nb = pGetGlyphIndicesW(hdc, str, 1, glyphs, 0);
ok(nb == 1, "GetGlyphIndicesW should have returned 1\n");
ret = pGetCharABCWidthsI(NULL, 0, 1, glyphs, abc);
ok(!ret, "GetCharABCWidthsI should have failed\n");
ret = pGetCharABCWidthsI(hdc, 0, 1, glyphs, NULL);
ok(!ret, "GetCharABCWidthsI should have failed\n");
ret = pGetCharABCWidthsI(hdc, 0, 1, glyphs, abc);
ok(ret, "GetCharABCWidthsI should have succeeded\n");
ret = pGetCharABCWidthsW(NULL, 'a', 'a', abc);
ok(!ret, "GetCharABCWidthsW should have failed\n");
ret = pGetCharABCWidthsW(hdc, 'a', 'a', NULL);
ok(!ret, "GetCharABCWidthsW should have failed\n");
ret = pGetCharABCWidthsW(hdc, 'a', 'a', abc);
ok(!ret, "GetCharABCWidthsW should have failed\n");
ret = pGetCharABCWidthsFloatW(NULL, 'a', 'a', abcf);
ok(!ret, "GetCharABCWidthsFloatW should have failed\n");
ret = pGetCharABCWidthsFloatW(hdc, 'a', 'a', NULL);
ok(!ret, "GetCharABCWidthsFloatW should have failed\n");
ret = pGetCharABCWidthsFloatW(hdc, 'a', 'a', abcf);
ok(ret, "GetCharABCWidthsFloatW should have succeeded\n");
hfont = SelectObject(hdc, hfont);
DeleteObject(hfont);
for (i = 0; i < sizeof c / sizeof c[0]; ++i)
{
ABC a[2], w[2];
ABC full[256];
UINT code = 0x41, j;
lf.lfFaceName[0] = '\0';
lf.lfCharSet = c[i].cs;
lf.lfPitchAndFamily = 0;
if (EnumFontFamiliesExA(hdc, &lf, create_font_proc, (LPARAM)&hfont, 0))
{
skip("TrueType font for charset %u is not installed\n", c[i].cs);
continue;
}
memset(a, 0, sizeof a);
memset(w, 0, sizeof w);
hfont = SelectObject(hdc, hfont);
ok(pGetCharABCWidthsA(hdc, c[i].a, c[i].a + 1, a) &&
pGetCharABCWidthsW(hdc, c[i].w, c[i].w + 1, w) &&
memcmp(a, w, sizeof a) == 0,
"GetCharABCWidthsA and GetCharABCWidthsW should return same widths. charset = %u\n", c[i].cs);
memset(a, 0xbb, sizeof a);
ret = pGetCharABCWidthsA(hdc, code, code, a);
ok(ret, "GetCharABCWidthsA should have succeeded\n");
memset(full, 0xcc, sizeof full);
ret = pGetCharABCWidthsA(hdc, 0x00, code, full);
ok(ret, "GetCharABCWidthsA should have succeeded\n");
ok(memcmp(&a[0], &full[code], sizeof(ABC)) == 0,
"GetCharABCWidthsA info should match. codepage = %u\n", c[i].cs);
for (j = 0; j < sizeof range / sizeof range[0]; ++j)
{
memset(full, 0xdd, sizeof full);
ret = pGetCharABCWidthsA(hdc, range[j].first, range[j].last, full);
ok(ret == c[i].r[j], "GetCharABCWidthsA %x - %x should have %s\n",
range[j].first, range[j].last, c[i].r[j] ? "succeeded" : "failed");
if (ret)
{
UINT last = range[j].last - range[j].first;
ret = pGetCharABCWidthsA(hdc, range[j].last, range[j].last, a);
ok(ret && memcmp(&full[last], &a[0], sizeof(ABC)) == 0,
"GetCharABCWidthsA %x should match. codepage = %u\n",
range[j].last, c[i].cs);
}
}
hfont = SelectObject(hdc, hfont);
DeleteObject(hfont);
}
memset(&lf, 0, sizeof(lf));
strcpy(lf.lfFaceName, "Tahoma");
lf.lfHeight = 200;
hfont = CreateFontIndirectA(&lf);
/* test empty glyph's metrics */
hfont = SelectObject(hdc, hfont);
ret = pGetCharABCWidthsFloatW(hdc, ' ', ' ', abcf);
ok(ret, "GetCharABCWidthsFloatW should have succeeded\n");
ok(abcf[0].abcfB == 1.0, "got %f\n", abcf[0].abcfB);
ret = pGetCharABCWidthsW(hdc, ' ', ' ', abcw);
ok(ret, "GetCharABCWidthsW should have succeeded\n");
ok(abcw[0].abcB == 1, "got %u\n", abcw[0].abcB);
/* 1) prepare unrotated font metrics */
ret = pGetCharABCWidthsW(hdc, 'a', 'a', abcw);
ok(ret, "GetCharABCWidthsW should have succeeded\n");
DeleteObject(SelectObject(hdc, hfont));
/* 2) get rotated font metrics */
lf.lfEscapement = lf.lfOrientation = 900;
hfont = CreateFontIndirectA(&lf);
hfont = SelectObject(hdc, hfont);
ret = pGetCharABCWidthsW(hdc, 'a', 'a', abc);
ok(ret, "GetCharABCWidthsW should have succeeded\n");
/* 3) compare ABC results */
ok(match_off_by_1(abcw[0].abcA, abc[0].abcA, FALSE),
"got %d, expected %d (A)\n", abc[0].abcA, abcw[0].abcA);
ok(match_off_by_1(abcw[0].abcB, abc[0].abcB, FALSE),
"got %d, expected %d (B)\n", abc[0].abcB, abcw[0].abcB);
ok(match_off_by_1(abcw[0].abcC, abc[0].abcC, FALSE),
"got %d, expected %d (C)\n", abc[0].abcC, abcw[0].abcC);
DeleteObject(SelectObject(hdc, hfont));
ReleaseDC(NULL, hdc);
trace("ABC sign test for a variety of transforms:\n");
memset(&lf, 0, sizeof(lf));
strcpy(lf.lfFaceName, "Tahoma");
lf.lfHeight = 20;
hfont = CreateFontIndirectA(&lf);
hwnd = CreateWindowExA(0, "static", "", WS_POPUP, 0,0,100,100,
0, 0, 0, NULL);
hdc = GetDC(hwnd);
SetMapMode(hdc, MM_ANISOTROPIC);
SelectObject(hdc, hfont);
nb = pGetGlyphIndicesW(hdc, str, 1, glyphs, 0);
ok(nb == 1, "GetGlyphIndicesW should have returned 1\n");
ret = pGetCharABCWidthsI(hdc, 0, 1, glyphs, abc);
ok(ret, "GetCharABCWidthsI should have succeeded\n");
ret = pGetCharABCWidthsW(hdc, 'i', 'i', abcw);
ok(ret, "GetCharABCWidthsW should have succeeded\n");
ret = pGetCharABCWidthsFloatW(hdc, 'i', 'i', abcf);
ok(ret, "GetCharABCWidthsFloatW should have succeeded\n");
ABCWidths_helper("LTR", hdc, glyphs, abc, abcw, abcf, 0);
SetWindowExtEx(hdc, -1, -1, NULL);
SetGraphicsMode(hdc, GM_COMPATIBLE);
ABCWidths_helper("LTR -1 compatible", hdc, glyphs, abc, abcw, abcf, 0);
SetGraphicsMode(hdc, GM_ADVANCED);
ABCWidths_helper("LTR -1 advanced", hdc, glyphs, abc, abcw, abcf, 1);
SetWindowExtEx(hdc, 1, 1, NULL);
SetGraphicsMode(hdc, GM_COMPATIBLE);
ABCWidths_helper("LTR 1 compatible", hdc, glyphs, abc, abcw, abcf, 0);
SetGraphicsMode(hdc, GM_ADVANCED);
ABCWidths_helper("LTR 1 advanced", hdc, glyphs, abc, abcw, abcf, 0);
ReleaseDC(hwnd, hdc);
DestroyWindow(hwnd);
trace("RTL layout\n");
hwnd = CreateWindowExA(WS_EX_LAYOUTRTL, "static", "", WS_POPUP, 0,0,100,100,
0, 0, 0, NULL);
hdc = GetDC(hwnd);
SetMapMode(hdc, MM_ANISOTROPIC);
SelectObject(hdc, hfont);
ABCWidths_helper("RTL", hdc, glyphs, abc, abcw, abcf, 0);
SetWindowExtEx(hdc, -1, -1, NULL);
SetGraphicsMode(hdc, GM_COMPATIBLE);
ABCWidths_helper("RTL -1 compatible", hdc, glyphs, abc, abcw, abcf, 0);
SetGraphicsMode(hdc, GM_ADVANCED);
ABCWidths_helper("RTL -1 advanced", hdc, glyphs, abc, abcw, abcf, 0);
SetWindowExtEx(hdc, 1, 1, NULL);
SetGraphicsMode(hdc, GM_COMPATIBLE);
ABCWidths_helper("RTL 1 compatible", hdc, glyphs, abc, abcw, abcf, 0);
SetGraphicsMode(hdc, GM_ADVANCED);
ABCWidths_helper("RTL 1 advanced", hdc, glyphs, abc, abcw, abcf, 1);
ReleaseDC(hwnd, hdc);
DestroyWindow(hwnd);
DeleteObject(hfont);
}
static void test_text_extents(void)
{
static const WCHAR wt[] = {'O','n','e','\n','t','w','o',' ','3',0};
LPINT extents;
INT i, len, fit1, fit2, extents2[3];
LOGFONTA lf;
TEXTMETRICA tm;
HDC hdc;
HFONT hfont;
SIZE sz;
SIZE sz1, sz2;
BOOL ret;
memset(&lf, 0, sizeof(lf));
strcpy(lf.lfFaceName, "Arial");
lf.lfHeight = 20;
hfont = CreateFontIndirectA(&lf);
hdc = GetDC(0);
hfont = SelectObject(hdc, hfont);
GetTextMetricsA(hdc, &tm);
GetTextExtentPointA(hdc, "o", 1, &sz);
ok(sz.cy == tm.tmHeight, "cy %d tmHeight %d\n", sz.cy, tm.tmHeight);
SetLastError(0xdeadbeef);
GetTextExtentExPointW(hdc, wt, 1, 1, &fit1, &fit2, &sz1);
if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
{
win_skip("Skipping remainder of text extents test on a Win9x platform\n");
hfont = SelectObject(hdc, hfont);
DeleteObject(hfont);
ReleaseDC(0, hdc);
return;
}
len = lstrlenW(wt);
extents = HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, len * sizeof extents[0]);
extents[0] = 1; /* So that the increasing sequence test will fail
if the extents array is untouched. */
GetTextExtentExPointW(hdc, wt, len, 32767, &fit1, extents, &sz1);
GetTextExtentPointW(hdc, wt, len, &sz2);
ok(sz1.cy == sz2.cy,
"cy from GetTextExtentExPointW (%d) and GetTextExtentPointW (%d) differ\n", sz1.cy, sz2.cy);
/* Because of the '\n' in the string GetTextExtentExPoint and
GetTextExtentPoint return different widths under Win2k, but
under WinXP they return the same width. So we don't test that
here. */
for (i = 1; i < len; ++i)
ok(extents[i-1] <= extents[i],
"GetTextExtentExPointW generated a non-increasing sequence of partial extents (at position %d)\n",
i);
ok(extents[len-1] == sz1.cx, "GetTextExtentExPointW extents and size don't match\n");
ok(0 <= fit1 && fit1 <= len, "GetTextExtentExPointW generated illegal value %d for fit\n", fit1);
ok(0 < fit1, "GetTextExtentExPointW says we can't even fit one letter in 32767 logical units\n");
GetTextExtentExPointW(hdc, wt, len, extents[2], &fit2, NULL, &sz2);
ok(sz1.cx == sz2.cx && sz1.cy == sz2.cy, "GetTextExtentExPointW returned different sizes for the same string\n");
ok(fit2 == 3, "GetTextExtentExPointW extents isn't consistent with fit\n");
GetTextExtentExPointW(hdc, wt, len, extents[2]-1, &fit2, NULL, &sz2);
ok(fit2 == 2, "GetTextExtentExPointW extents isn't consistent with fit\n");
GetTextExtentExPointW(hdc, wt, 2, 0, NULL, extents + 2, &sz2);
ok(extents[0] == extents[2] && extents[1] == extents[3],
"GetTextExtentExPointW with lpnFit == NULL returns incorrect results\n");
GetTextExtentExPointW(hdc, wt, 2, 0, NULL, NULL, &sz1);
ok(sz1.cx == sz2.cx && sz1.cy == sz2.cy,
"GetTextExtentExPointW with lpnFit and alpDx both NULL returns incorrect results\n");
/* extents functions fail with -ve counts (the interesting case being -1) */
ret = GetTextExtentPointA(hdc, "o", -1, &sz);
ok(ret == FALSE, "got %d\n", ret);
ret = GetTextExtentExPointA(hdc, "o", -1, 0, NULL, NULL, &sz);
ok(ret == FALSE, "got %d\n", ret);
ret = GetTextExtentExPointW(hdc, wt, -1, 0, NULL, NULL, &sz1);
ok(ret == FALSE, "got %d\n", ret);
/* max_extent = 0 succeeds and returns zero */
fit1 = fit2 = -215;
ret = GetTextExtentExPointA(hdc, NULL, 0, 0, &fit1, NULL, &sz);
ok(ret == TRUE ||
broken(ret == FALSE), /* NT4, 2k */
"got %d\n", ret);
ok(fit1 == 0 ||
broken(fit1 == -215), /* NT4, 2k */
"fit = %d\n", fit1);
ret = GetTextExtentExPointW(hdc, NULL, 0, 0, &fit2, NULL, &sz1);
ok(ret == TRUE, "got %d\n", ret);
ok(fit2 == 0, "fit = %d\n", fit2);
/* max_extent = -1 is interpreted as a very large width that will
* definitely fit our three characters */
fit1 = fit2 = -215;
ret = GetTextExtentExPointA(hdc, "One", 3, -1, &fit1, NULL, &sz);
ok(ret == TRUE, "got %d\n", ret);
ok(fit1 == 3, "fit = %d\n", fit1);
ret = GetTextExtentExPointW(hdc, wt, 3, -1, &fit2, NULL, &sz);
ok(ret == TRUE, "got %d\n", ret);
ok(fit2 == 3, "fit = %d\n", fit2);
/* max_extent = -2 is interpreted similarly, but the Ansi version
* rejects it while the Unicode one accepts it */
fit1 = fit2 = -215;
ret = GetTextExtentExPointA(hdc, "One", 3, -2, &fit1, NULL, &sz);
ok(ret == FALSE, "got %d\n", ret);
ok(fit1 == -215, "fit = %d\n", fit1);
ret = GetTextExtentExPointW(hdc, wt, 3, -2, &fit2, NULL, &sz);
ok(ret == TRUE, "got %d\n", ret);
ok(fit2 == 3, "fit = %d\n", fit2);
hfont = SelectObject(hdc, hfont);
DeleteObject(hfont);
/* non-MM_TEXT mapping mode */
lf.lfHeight = 2000;
hfont = CreateFontIndirectA(&lf);
hfont = SelectObject(hdc, hfont);
SetMapMode( hdc, MM_HIMETRIC );
ret = GetTextExtentExPointW(hdc, wt, 3, 0, NULL, extents, &sz);
ok(ret, "got %d\n", ret);
ok(sz.cx == extents[2], "got %d vs %d\n", sz.cx, extents[2]);
ret = GetTextExtentExPointW(hdc, wt, 3, extents[1], &fit1, extents2, &sz2);
ok(ret, "got %d\n", ret);
ok(fit1 == 2, "got %d\n", fit1);
ok(sz2.cx == sz.cx, "got %d vs %d\n", sz2.cx, sz.cx);
for(i = 0; i < 2; i++)
ok(extents2[i] == extents[i], "%d: %d, %d\n", i, extents2[i], extents[i]);
hfont = SelectObject(hdc, hfont);
DeleteObject(hfont);
HeapFree(GetProcessHeap(), 0, extents);
ReleaseDC(NULL, hdc);
}
static void test_GetGlyphIndices(void)
{
HDC hdc;
HFONT hfont;
DWORD charcount;
LOGFONTA lf;
DWORD flags = 0;
WCHAR testtext[] = {'T','e','s','t',0xffff,0};
WORD glyphs[(sizeof(testtext)/2)-1];
TEXTMETRICA textm;
HFONT hOldFont;
if (!pGetGlyphIndicesW) {
win_skip("GetGlyphIndicesW not available on platform\n");
return;
}
hdc = GetDC(0);
memset(&lf, 0, sizeof(lf));
strcpy(lf.lfFaceName, "System");
lf.lfHeight = 16;
lf.lfCharSet = ANSI_CHARSET;
hfont = CreateFontIndirectA(&lf);
ok(hfont != 0, "CreateFontIndirectEx failed\n");
ok(GetTextMetricsA(hdc, &textm), "GetTextMetric failed\n");
if (textm.tmCharSet == ANSI_CHARSET)
{
flags |= GGI_MARK_NONEXISTING_GLYPHS;
charcount = pGetGlyphIndicesW(hdc, testtext, (sizeof(testtext)/2)-1, glyphs, flags);
ok(charcount == 5, "GetGlyphIndicesW count of glyphs should = 5 not %d\n", charcount);
ok((glyphs[4] == 0x001f || glyphs[4] == 0xffff /* Vista */), "GetGlyphIndicesW should have returned a nonexistent char not %04x\n", glyphs[4]);
flags = 0;
charcount = pGetGlyphIndicesW(hdc, testtext, (sizeof(testtext)/2)-1, glyphs, flags);
ok(charcount == 5, "GetGlyphIndicesW count of glyphs should = 5 not %d\n", charcount);
ok(glyphs[4] == textm.tmDefaultChar, "GetGlyphIndicesW should have returned a %04x not %04x\n",
textm.tmDefaultChar, glyphs[4]);
}
else
/* FIXME: Write tests for non-ANSI charsets. */
skip("GetGlyphIndices System font tests only for ANSI_CHARSET\n");
if(!is_font_installed("Tahoma"))
{
skip("Tahoma is not installed so skipping this test\n");
return;
}
memset(&lf, 0, sizeof(lf));
strcpy(lf.lfFaceName, "Tahoma");
lf.lfHeight = 20;
hfont = CreateFontIndirectA(&lf);
hOldFont = SelectObject(hdc, hfont);
ok(GetTextMetricsA(hdc, &textm), "GetTextMetric failed\n");
flags |= GGI_MARK_NONEXISTING_GLYPHS;
charcount = pGetGlyphIndicesW(hdc, testtext, (sizeof(testtext)/2)-1, glyphs, flags);
ok(charcount == 5, "GetGlyphIndicesW count of glyphs should = 5 not %d\n", charcount);
ok(glyphs[4] == 0xffff, "GetGlyphIndicesW should have returned 0xffff char not %04x\n", glyphs[4]);
flags = 0;
testtext[0] = textm.tmDefaultChar;
charcount = pGetGlyphIndicesW(hdc, testtext, (sizeof(testtext)/2)-1, glyphs, flags);
ok(charcount == 5, "GetGlyphIndicesW count of glyphs should = 5 not %d\n", charcount);
ok(glyphs[0] == 0, "GetGlyphIndicesW for tmDefaultChar should be 0 not %04x\n", glyphs[0]);
ok(glyphs[4] == 0, "GetGlyphIndicesW should have returned 0 not %04x\n", glyphs[4]);
DeleteObject(SelectObject(hdc, hOldFont));
}
static void test_GetKerningPairs(void)
{
static const struct kerning_data
{
const char face_name[LF_FACESIZE];
LONG height;
/* some interesting fields from OUTLINETEXTMETRIC */
LONG tmHeight, tmAscent, tmDescent;
UINT otmEMSquare;
INT otmAscent;
INT otmDescent;
UINT otmLineGap;
UINT otmsCapEmHeight;
UINT otmsXHeight;
INT otmMacAscent;
INT otmMacDescent;
UINT otmMacLineGap;
UINT otmusMinimumPPEM;
/* small subset of kerning pairs to test */
DWORD total_kern_pairs;
const KERNINGPAIR kern_pair[26];
} kd[] =
{
{"Arial", 12, 12, 9, 3,
2048, 7, -2, 1, 5, 2, 8, -2, 0, 9,
26,
{
{' ','A',-1},{' ','T',0},{' ','Y',0},{'1','1',-1},
{'A',' ',-1},{'A','T',-1},{'A','V',-1},{'A','W',0},
{'A','Y',-1},{'A','v',0},{'A','w',0},{'A','y',0},
{'F',',',-1},{'F','.',-1},{'F','A',-1},{'L',' ',0},
{'L','T',-1},{'L','V',-1},{'L','W',-1},{'L','Y',-1},
{915,912,+1},{915,913,-1},{910,912,+1},{910,913,-1},
{933,970,+1},{933,972,-1}
}
},
{"Arial", -34, 39, 32, 7,
2048, 25, -7, 5, 17, 9, 31, -7, 1, 9,
26,
{
{' ','A',-2},{' ','T',-1},{' ','Y',-1},{'1','1',-3},
{'A',' ',-2},{'A','T',-3},{'A','V',-3},{'A','W',-1},
{'A','Y',-3},{'A','v',-1},{'A','w',-1},{'A','y',-1},
{'F',',',-4},{'F','.',-4},{'F','A',-2},{'L',' ',-1},
{'L','T',-3},{'L','V',-3},{'L','W',-3},{'L','Y',-3},
{915,912,+3},{915,913,-3},{910,912,+3},{910,913,-3},
{933,970,+2},{933,972,-3}
}
},
{ "Arial", 120, 120, 97, 23,
2048, 79, -23, 16, 54, 27, 98, -23, 4, 9,
26,
{
{' ','A',-6},{' ','T',-2},{' ','Y',-2},{'1','1',-8},
{'A',' ',-6},{'A','T',-8},{'A','V',-8},{'A','W',-4},
{'A','Y',-8},{'A','v',-2},{'A','w',-2},{'A','y',-2},
{'F',',',-12},{'F','.',-12},{'F','A',-6},{'L',' ',-4},
{'L','T',-8},{'L','V',-8},{'L','W',-8},{'L','Y',-8},
{915,912,+9},{915,913,-10},{910,912,+9},{910,913,-8},
{933,970,+6},{933,972,-10}
}
},
#if 0 /* this set fails due to +1/-1 errors (rounding bug?), needs investigation. */
{ "Arial", 1024 /* usually 1/2 of EM Square */, 1024, 830, 194,
2048, 668, -193, 137, 459, 229, 830, -194, 30, 9,
26,
{
{' ','A',-51},{' ','T',-17},{' ','Y',-17},{'1','1',-68},
{'A',' ',-51},{'A','T',-68},{'A','V',-68},{'A','W',-34},
{'A','Y',-68},{'A','v',-17},{'A','w',-17},{'A','y',-17},
{'F',',',-102},{'F','.',-102},{'F','A',-51},{'L',' ',-34},
{'L','T',-68},{'L','V',-68},{'L','W',-68},{'L','Y',-68},
{915,912,+73},{915,913,-84},{910,912,+76},{910,913,-68},
{933,970,+54},{933,972,-83}
}
}
#endif
};
LOGFONTA lf;
HFONT hfont, hfont_old;
KERNINGPAIR *kern_pair;
HDC hdc;
DWORD total_kern_pairs, ret, i, n, matches;
hdc = GetDC(0);
/* GetKerningPairsA maps unicode set of kerning pairs to current code page
* which may render this test unusable, so we're trying to avoid that.
*/
SetLastError(0xdeadbeef);
GetKerningPairsW(hdc, 0, NULL);
if (GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
{
win_skip("Skipping the GetKerningPairs test on a Win9x platform\n");
ReleaseDC(0, hdc);
return;
}
for (i = 0; i < sizeof(kd)/sizeof(kd[0]); i++)
{
OUTLINETEXTMETRICW otm;
UINT uiRet;
if (!is_font_installed(kd[i].face_name))
{
trace("%s is not installed so skipping this test\n", kd[i].face_name);
continue;
}
trace("testing font %s, height %d\n", kd[i].face_name, kd[i].height);
memset(&lf, 0, sizeof(lf));
strcpy(lf.lfFaceName, kd[i].face_name);
lf.lfHeight = kd[i].height;
hfont = CreateFontIndirectA(&lf);
assert(hfont != 0);
hfont_old = SelectObject(hdc, hfont);
SetLastError(0xdeadbeef);
otm.otmSize = sizeof(otm); /* just in case for Win9x compatibility */
uiRet = GetOutlineTextMetricsW(hdc, sizeof(otm), &otm);
ok(uiRet == sizeof(otm), "GetOutlineTextMetricsW error %d\n", GetLastError());
ok(match_off_by_1(kd[i].tmHeight, otm.otmTextMetrics.tmHeight, FALSE), "expected %d, got %d\n",
kd[i].tmHeight, otm.otmTextMetrics.tmHeight);
ok(match_off_by_1(kd[i].tmAscent, otm.otmTextMetrics.tmAscent, FALSE), "expected %d, got %d\n",
kd[i].tmAscent, otm.otmTextMetrics.tmAscent);
ok(kd[i].tmDescent == otm.otmTextMetrics.tmDescent, "expected %d, got %d\n",
kd[i].tmDescent, otm.otmTextMetrics.tmDescent);
ok(kd[i].otmEMSquare == otm.otmEMSquare, "expected %u, got %u\n",
kd[i].otmEMSquare, otm.otmEMSquare);
ok(kd[i].otmAscent == otm.otmAscent, "expected %d, got %d\n",
kd[i].otmAscent, otm.otmAscent);
ok(kd[i].otmDescent == otm.otmDescent, "expected %d, got %d\n",
kd[i].otmDescent, otm.otmDescent);
ok(kd[i].otmLineGap == otm.otmLineGap, "expected %u, got %u\n",
kd[i].otmLineGap, otm.otmLineGap);
ok(near_match(kd[i].otmMacDescent, otm.otmMacDescent), "expected %d, got %d\n",
kd[i].otmMacDescent, otm.otmMacDescent);
ok(near_match(kd[i].otmMacAscent, otm.otmMacAscent), "expected %d, got %d\n",
kd[i].otmMacAscent, otm.otmMacAscent);
todo_wine {
ok(kd[i].otmsCapEmHeight == otm.otmsCapEmHeight, "expected %u, got %u\n",
kd[i].otmsCapEmHeight, otm.otmsCapEmHeight);
ok(kd[i].otmsXHeight == otm.otmsXHeight, "expected %u, got %u\n",
kd[i].otmsXHeight, otm.otmsXHeight);
/* FIXME: this one sometimes succeeds due to expected 0, enable it when removing todo */
if (0) ok(kd[i].otmMacLineGap == otm.otmMacLineGap, "expected %u, got %u\n",
kd[i].otmMacLineGap, otm.otmMacLineGap);
ok(kd[i].otmusMinimumPPEM == otm.otmusMinimumPPEM, "expected %u, got %u\n",
kd[i].otmusMinimumPPEM, otm.otmusMinimumPPEM);
}
total_kern_pairs = GetKerningPairsW(hdc, 0, NULL);
trace("total_kern_pairs %u\n", total_kern_pairs);
kern_pair = HeapAlloc(GetProcessHeap(), 0, total_kern_pairs * sizeof(*kern_pair));
/* Win98 (GetKerningPairsA) and XP behave differently here, the test
* passes on XP.
*/
SetLastError(0xdeadbeef);
ret = GetKerningPairsW(hdc, 0, kern_pair);
ok(GetLastError() == ERROR_INVALID_PARAMETER,
"got error %u, expected ERROR_INVALID_PARAMETER\n", GetLastError());
ok(ret == 0, "got %u, expected 0\n", ret);
ret = GetKerningPairsW(hdc, 100, NULL);
ok(ret == total_kern_pairs, "got %u, expected %u\n", ret, total_kern_pairs);
ret = GetKerningPairsW(hdc, total_kern_pairs/2, kern_pair);
ok(ret == total_kern_pairs/2, "got %u, expected %u\n", ret, total_kern_pairs/2);
ret = GetKerningPairsW(hdc, total_kern_pairs, kern_pair);
ok(ret == total_kern_pairs, "got %u, expected %u\n", ret, total_kern_pairs);
matches = 0;
for (n = 0; n < ret; n++)
{
DWORD j;
/* Disabled to limit console spam */
if (0 && kern_pair[n].wFirst < 127 && kern_pair[n].wSecond < 127)
trace("{'%c','%c',%d},\n",
kern_pair[n].wFirst, kern_pair[n].wSecond, kern_pair[n].iKernAmount);
for (j = 0; j < kd[i].total_kern_pairs; j++)
{
if (kern_pair[n].wFirst == kd[i].kern_pair[j].wFirst &&
kern_pair[n].wSecond == kd[i].kern_pair[j].wSecond)
{
ok(kern_pair[n].iKernAmount == kd[i].kern_pair[j].iKernAmount,
"pair %d:%d got %d, expected %d\n",
kern_pair[n].wFirst, kern_pair[n].wSecond,
kern_pair[n].iKernAmount, kd[i].kern_pair[j].iKernAmount);
matches++;
}
}
}
ok(matches == kd[i].total_kern_pairs, "got matches %u, expected %u\n",
matches, kd[i].total_kern_pairs);
HeapFree(GetProcessHeap(), 0, kern_pair);
SelectObject(hdc, hfont_old);
DeleteObject(hfont);
}
ReleaseDC(0, hdc);
}
struct font_data
{
const char face_name[LF_FACESIZE];
int requested_height;
int weight, height, ascent, descent, int_leading, ext_leading, dpi;
BOOL exact;
};
static void test_height( HDC hdc, const struct font_data *fd )
{
LOGFONTA lf;
HFONT hfont, old_hfont;
TEXTMETRICA tm;
INT ret, i;
for (i = 0; fd[i].face_name[0]; i++)
{
if (!is_truetype_font_installed(fd[i].face_name))
{
skip("%s is not installed\n", fd[i].face_name);
continue;
}
memset(&lf, 0, sizeof(lf));
lf.lfHeight = fd[i].requested_height;
lf.lfWeight = fd[i].weight;
strcpy(lf.lfFaceName, fd[i].face_name);
hfont = CreateFontIndirectA(&lf);
assert(hfont);
old_hfont = SelectObject(hdc, hfont);
ret = GetTextMetricsA(hdc, &tm);
ok(ret, "GetTextMetrics error %d\n", GetLastError());
if(fd[i].dpi == tm.tmDigitizedAspectX)
{
trace("found font %s, height %d charset %x dpi %d\n", lf.lfFaceName, lf.lfHeight, lf.lfCharSet, fd[i].dpi);
ok(tm.tmWeight == fd[i].weight, "%s(%d): tm.tmWeight %d != %d\n", fd[i].face_name, fd[i].requested_height, tm.tmWeight, fd[i].weight);
ok(match_off_by_1(tm.tmHeight, fd[i].height, fd[i].exact), "%s(%d): tm.tmHeight %d != %d\n", fd[i].face_name, fd[i].requested_height, tm.tmHeight, fd[i].height);
ok(match_off_by_1(tm.tmAscent, fd[i].ascent, fd[i].exact), "%s(%d): tm.tmAscent %d != %d\n", fd[i].face_name, fd[i].requested_height, tm.tmAscent, fd[i].ascent);
ok(match_off_by_1(tm.tmDescent, fd[i].descent, fd[i].exact), "%s(%d): tm.tmDescent %d != %d\n", fd[i].face_name, fd[i].requested_height, tm.tmDescent, fd[i].descent);
ok(match_off_by_1(tm.tmInternalLeading, fd[i].int_leading, fd[i].exact), "%s(%d): tm.tmInternalLeading %d != %d\n", fd[i].face_name, fd[i].requested_height, tm.tmInternalLeading, fd[i].int_leading);
ok(tm.tmExternalLeading == fd[i].ext_leading, "%s(%d): tm.tmExternalLeading %d != %d\n", fd[i].face_name, fd[i].requested_height, tm.tmExternalLeading, fd[i].ext_leading);
}
SelectObject(hdc, old_hfont);
DeleteObject(hfont);
}
}
static void *find_ttf_table( void *ttf, DWORD size, DWORD tag )
{
WORD i, num_tables = GET_BE_WORD(*((WORD *)ttf + 2));
DWORD *table = (DWORD *)ttf + 3;
for (i = 0; i < num_tables; i++)
{
if (table[0] == tag)
return (BYTE *)ttf + GET_BE_DWORD(table[2]);
table += 4;
}
return NULL;
}
static void test_height_selection_vdmx( HDC hdc )
{
static const struct font_data charset_0[] = /* doesn't use VDMX */
{
{ "wine_vdmx", 10, FW_NORMAL, 10, 8, 2, 2, 0, 96, TRUE },
{ "wine_vdmx", 11, FW_NORMAL, 11, 9, 2, 2, 0, 96, TRUE },
{ "wine_vdmx", 12, FW_NORMAL, 12, 10, 2, 2, 0, 96, TRUE },
{ "wine_vdmx", 13, FW_NORMAL, 13, 11, 2, 2, 0, 96, TRUE },
{ "wine_vdmx", 14, FW_NORMAL, 14, 12, 2, 2, 0, 96, TRUE },
{ "wine_vdmx", 15, FW_NORMAL, 15, 12, 3, 3, 0, 96, FALSE },
{ "wine_vdmx", 16, FW_NORMAL, 16, 13, 3, 3, 0, 96, TRUE },
{ "wine_vdmx", 17, FW_NORMAL, 17, 14, 3, 3, 0, 96, TRUE },
{ "wine_vdmx", 18, FW_NORMAL, 18, 15, 3, 3, 0, 96, TRUE },
{ "wine_vdmx", 19, FW_NORMAL, 19, 16, 3, 3, 0, 96, TRUE },
{ "wine_vdmx", 20, FW_NORMAL, 20, 17, 3, 4, 0, 96, FALSE },
{ "wine_vdmx", 21, FW_NORMAL, 21, 17, 4, 4, 0, 96, TRUE },
{ "wine_vdmx", 22, FW_NORMAL, 22, 18, 4, 4, 0, 96, TRUE },
{ "wine_vdmx", 23, FW_NORMAL, 23, 19, 4, 4, 0, 96, TRUE },
{ "wine_vdmx", 24, FW_NORMAL, 24, 20, 4, 4, 0, 96, TRUE },
{ "wine_vdmx", 25, FW_NORMAL, 25, 21, 4, 4, 0, 96, TRUE },
{ "wine_vdmx", 26, FW_NORMAL, 26, 22, 4, 5, 0, 96, FALSE },
{ "wine_vdmx", 27, FW_NORMAL, 27, 22, 5, 5, 0, 96, TRUE },
{ "wine_vdmx", 28, FW_NORMAL, 28, 23, 5, 5, 0, 96, TRUE },
{ "wine_vdmx", 29, FW_NORMAL, 29, 24, 5, 5, 0, 96, TRUE },
{ "wine_vdmx", 30, FW_NORMAL, 30, 25, 5, 5, 0, 96, TRUE },
{ "wine_vdmx", 31, FW_NORMAL, 31, 26, 5, 5, 0, 96, TRUE },
{ "wine_vdmx", 32, FW_NORMAL, 32, 27, 5, 6, 0, 96, FALSE },
{ "wine_vdmx", 48, FW_NORMAL, 48, 40, 8, 8, 0, 96, TRUE },
{ "wine_vdmx", 64, FW_NORMAL, 64, 53, 11, 11, 0, 96, TRUE },
{ "wine_vdmx", 96, FW_NORMAL, 96, 80, 16, 17, 0, 96, FALSE },
{ "wine_vdmx", -10, FW_NORMAL, 12, 10, 2, 2, 0, 96, TRUE },
{ "wine_vdmx", -11, FW_NORMAL, 13, 11, 2, 2, 0, 96, TRUE },
{ "wine_vdmx", -12, FW_NORMAL, 14, 12, 2, 2, 0, 96, TRUE },
{ "wine_vdmx", -13, FW_NORMAL, 16, 13, 3, 3, 0, 96, TRUE },
{ "wine_vdmx", -14, FW_NORMAL, 17, 14, 3, 3, 0, 96, TRUE },
{ "wine_vdmx", -15, FW_NORMAL, 18, 15, 3, 3, 0, 96, TRUE },
{ "wine_vdmx", -16, FW_NORMAL, 19, 16, 3, 3, 0, 96, TRUE },
{ "wine_vdmx", -17, FW_NORMAL, 21, 17, 4, 4, 0, 96, TRUE },
{ "wine_vdmx", -18, FW_NORMAL, 22, 18, 4, 4, 0, 96, TRUE },
{ "wine_vdmx", -19, FW_NORMAL, 23, 19, 4, 4, 0, 96, TRUE },
{ "wine_vdmx", -20, FW_NORMAL, 24, 20, 4, 4, 0, 96, TRUE },
{ "wine_vdmx", -21, FW_NORMAL, 25, 21, 4, 4, 0, 96, TRUE },
{ "wine_vdmx", -22, FW_NORMAL, 27, 22, 5, 5, 0, 96, TRUE },
{ "wine_vdmx", -23, FW_NORMAL, 28, 23, 5, 5, 0, 96, TRUE },
{ "wine_vdmx", -24, FW_NORMAL, 29, 24, 5, 5, 0, 96, TRUE },
{ "wine_vdmx", -25, FW_NORMAL, 30, 25, 5, 5, 0, 96, TRUE },
{ "wine_vdmx", -26, FW_NORMAL, 31, 26, 5, 5, 0, 96, TRUE },
{ "wine_vdmx", -27, FW_NORMAL, 33, 27, 6, 6, 0, 96, TRUE },
{ "wine_vdmx", -28, FW_NORMAL, 34, 28, 6, 6, 0, 96, TRUE },
{ "wine_vdmx", -29, FW_NORMAL, 35, 29, 6, 6, 0, 96, TRUE },
{ "wine_vdmx", -30, FW_NORMAL, 36, 30, 6, 6, 0, 96, TRUE },
{ "wine_vdmx", -31, FW_NORMAL, 37, 31, 6, 6, 0, 96, TRUE },
{ "wine_vdmx", -32, FW_NORMAL, 39, 32, 7, 7, 0, 96, TRUE },
{ "wine_vdmx", -48, FW_NORMAL, 58, 48, 10, 10, 0, 96, TRUE },
{ "wine_vdmx", -64, FW_NORMAL, 77, 64, 13, 13, 0, 96, TRUE },
{ "wine_vdmx", -96, FW_NORMAL, 116, 96, 20, 20, 0, 96, TRUE },
{ "", 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};
static const struct font_data charset_1[] = /* Uses VDMX */
{
{ "wine_vdmx", 10, FW_NORMAL, 10, 8, 2, 2, 0, 96, TRUE },
{ "wine_vdmx", 11, FW_NORMAL, 11, 9, 2, 2, 0, 96, TRUE },
{ "wine_vdmx", 12, FW_NORMAL, 12, 10, 2, 2, 0, 96, TRUE },
{ "wine_vdmx", 13, FW_NORMAL, 13, 11, 2, 2, 0, 96, TRUE },
{ "wine_vdmx", 14, FW_NORMAL, 13, 11, 2, 2, 0, 96, TRUE },
{ "wine_vdmx", 15, FW_NORMAL, 13, 11, 2, 2, 0, 96, TRUE },
{ "wine_vdmx", 16, FW_NORMAL, 16, 13, 3, 4, 0, 96, TRUE },
{ "wine_vdmx", 17, FW_NORMAL, 16, 13, 3, 3, 0, 96, TRUE },
{ "wine_vdmx", 18, FW_NORMAL, 16, 13, 3, 3, 0, 96, TRUE },
{ "wine_vdmx", 19, FW_NORMAL, 19, 15, 4, 5, 0, 96, TRUE },
{ "wine_vdmx", 20, FW_NORMAL, 20, 16, 4, 5, 0, 96, TRUE },
{ "wine_vdmx", 21, FW_NORMAL, 21, 17, 4, 5, 0, 96, TRUE },
{ "wine_vdmx", 22, FW_NORMAL, 22, 18, 4, 5, 0, 96, TRUE },
{ "wine_vdmx", 23, FW_NORMAL, 23, 19, 4, 5, 0, 96, TRUE },
{ "wine_vdmx", 24, FW_NORMAL, 23, 19, 4, 5, 0, 96, TRUE },
{ "wine_vdmx", 25, FW_NORMAL, 25, 21, 4, 6, 0, 96, TRUE },
{ "wine_vdmx", 26, FW_NORMAL, 26, 22, 4, 6, 0, 96, TRUE },
{ "wine_vdmx", 27, FW_NORMAL, 27, 23, 4, 6, 0, 96, TRUE },
{ "wine_vdmx", 28, FW_NORMAL, 27, 23, 4, 5, 0, 96, TRUE },
{ "wine_vdmx", 29, FW_NORMAL, 29, 24, 5, 6, 0, 96, TRUE },
{ "wine_vdmx", 30, FW_NORMAL, 29, 24, 5, 6, 0, 96, TRUE },
{ "wine_vdmx", 31, FW_NORMAL, 29, 24, 5, 6, 0, 96, TRUE },
{ "wine_vdmx", 32, FW_NORMAL, 32, 26, 6, 8, 0, 96, TRUE },
{ "wine_vdmx", 48, FW_NORMAL, 48, 40, 8, 10, 0, 96, TRUE },
{ "wine_vdmx", 64, FW_NORMAL, 64, 54, 10, 13, 0, 96, TRUE },
{ "wine_vdmx", 96, FW_NORMAL, 95, 79, 16, 18, 0, 96, TRUE },
{ "wine_vdmx", -10, FW_NORMAL, 12, 10, 2, 2, 0, 96, TRUE },
{ "wine_vdmx", -11, FW_NORMAL, 13, 11, 2, 2, 0, 96, TRUE },
{ "wine_vdmx", -12, FW_NORMAL, 16, 13, 3, 4, 0, 96, TRUE },
{ "wine_vdmx", -13, FW_NORMAL, 16, 13, 3, 3, 0, 96, TRUE },
{ "wine_vdmx", -14, FW_NORMAL, 19, 15, 4, 5, 0, 96, TRUE },
{ "wine_vdmx", -15, FW_NORMAL, 20, 16, 4, 5, 0, 96, TRUE },
{ "wine_vdmx", -16, FW_NORMAL, 21, 17, 4, 5, 0, 96, TRUE },
{ "wine_vdmx", -17, FW_NORMAL, 22, 18, 4, 5, 0, 96, TRUE },
{ "wine_vdmx", -18, FW_NORMAL, 23, 19, 4, 5, 0, 96, TRUE },
{ "wine_vdmx", -19, FW_NORMAL, 25, 21, 4, 6, 0, 96, TRUE },
{ "wine_vdmx", -20, FW_NORMAL, 26, 22, 4, 6, 0, 96, TRUE },
{ "wine_vdmx", -21, FW_NORMAL, 27, 23, 4, 6, 0, 96, TRUE },
{ "wine_vdmx", -22, FW_NORMAL, 27, 23, 4, 5, 0, 96, TRUE },
{ "wine_vdmx", -23, FW_NORMAL, 29, 24, 5, 6, 0, 96, TRUE },
{ "wine_vdmx", -24, FW_NORMAL, 32, 26, 6, 8, 0, 96, TRUE },
{ "wine_vdmx", -25, FW_NORMAL, 32, 26, 6, 7, 0, 96, TRUE },
{ "wine_vdmx", -26, FW_NORMAL, 33, 27, 6, 7, 0, 96, TRUE },
{ "wine_vdmx", -27, FW_NORMAL, 35, 29, 6, 8, 0, 96, TRUE },
{ "wine_vdmx", -28, FW_NORMAL, 36, 30, 6, 8, 0, 96, TRUE },
{ "wine_vdmx", -29, FW_NORMAL, 36, 30, 6, 7, 0, 96, TRUE },
{ "wine_vdmx", -30, FW_NORMAL, 38, 32, 6, 8, 0, 96, TRUE },
{ "wine_vdmx", -31, FW_NORMAL, 39, 33, 6, 8, 0, 96, TRUE },
{ "wine_vdmx", -32, FW_NORMAL, 40, 33, 7, 8, 0, 96, TRUE },
{ "wine_vdmx", -48, FW_NORMAL, 60, 50, 10, 12, 0, 96, TRUE },
{ "wine_vdmx", -64, FW_NORMAL, 81, 67, 14, 17, 0, 96, TRUE },
{ "wine_vdmx", -96, FW_NORMAL, 119, 99, 20, 23, 0, 96, TRUE },
{ "", 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};
static const struct vdmx_data
{
WORD version;
BYTE bCharSet;
const struct font_data *fd;
} data[] =
{
{ 0, 0, charset_0 },
{ 0, 1, charset_1 },
{ 1, 0, charset_0 },
{ 1, 1, charset_1 }
};
int i;
DWORD size, num;
WORD *vdmx_header;
BYTE *ratio_rec;
char ttf_name[MAX_PATH];
void *res, *copy;
if (!pAddFontResourceExA)
{
win_skip("AddFontResourceExA unavailable\n");
return;
}
for (i = 0; i < sizeof(data) / sizeof(data[0]); i++)
{
res = get_res_data( "wine_vdmx.ttf", &size );
copy = HeapAlloc( GetProcessHeap(), 0, size );
memcpy( copy, res, size );
vdmx_header = find_ttf_table( copy, size, MS_MAKE_TAG('V','D','M','X') );
vdmx_header[0] = GET_BE_WORD( data[i].version );
ok( GET_BE_WORD( vdmx_header[1] ) == 1, "got %04x\n", GET_BE_WORD( vdmx_header[1] ) );
ok( GET_BE_WORD( vdmx_header[2] ) == 1, "got %04x\n", GET_BE_WORD( vdmx_header[2] ) );
ratio_rec = (BYTE *)&vdmx_header[3];
ratio_rec[0] = data[i].bCharSet;
write_tmp_file( copy, &size, ttf_name );
HeapFree( GetProcessHeap(), 0, copy );
ok( !is_truetype_font_installed("wine_vdmx"), "Already installed\n" );
num = pAddFontResourceExA( ttf_name, FR_PRIVATE, 0 );
if (!num) win_skip("Unable to add ttf font resource\n");
else
{
ok( is_truetype_font_installed("wine_vdmx"), "Not installed\n" );
test_height( hdc, data[i].fd );
pRemoveFontResourceExA( ttf_name, FR_PRIVATE, 0 );
}
DeleteFileA( ttf_name );
}
}
static void test_height_selection(void)
{
static const struct font_data tahoma[] =
{
{"Tahoma", -12, FW_NORMAL, 14, 12, 2, 2, 0, 96, TRUE },
{"Tahoma", -24, FW_NORMAL, 29, 24, 5, 5, 0, 96, TRUE },
{"Tahoma", -48, FW_NORMAL, 58, 48, 10, 10, 0, 96, TRUE },
{"Tahoma", -96, FW_NORMAL, 116, 96, 20, 20, 0, 96, TRUE },
{"Tahoma", -192, FW_NORMAL, 232, 192, 40, 40, 0, 96, TRUE },
{"Tahoma", 12, FW_NORMAL, 12, 10, 2, 2, 0, 96, TRUE },
{"Tahoma", 24, FW_NORMAL, 24, 20, 4, 4, 0, 96, TRUE },
{"Tahoma", 48, FW_NORMAL, 48, 40, 8, 8, 0, 96, TRUE },
{"Tahoma", 96, FW_NORMAL, 96, 80, 16, 17, 0, 96, FALSE },
{"Tahoma", 192, FW_NORMAL, 192, 159, 33, 33, 0, 96, TRUE },
{"", 0, 0, 0, 0, 0, 0, 0, 0, 0 }
};
HDC hdc = CreateCompatibleDC(0);
assert(hdc);
test_height( hdc, tahoma );
test_height_selection_vdmx( hdc );
DeleteDC(hdc);
}
static void test_GetOutlineTextMetrics(void)
{
OUTLINETEXTMETRICA *otm;
LOGFONTA lf;
HFONT hfont, hfont_old;
HDC hdc;
DWORD ret, otm_size;
LPSTR unset_ptr;
if (!is_font_installed("Arial"))
{
skip("Arial is not installed\n");
return;
}
hdc = GetDC(0);
memset(&lf, 0, sizeof(lf));
strcpy(lf.lfFaceName, "Arial");
lf.lfHeight = -13;
lf.lfWeight = FW_NORMAL;
lf.lfPitchAndFamily = DEFAULT_PITCH;
lf.lfQuality = PROOF_QUALITY;
hfont = CreateFontIndirectA(&lf);
assert(hfont != 0);
hfont_old = SelectObject(hdc, hfont);
otm_size = GetOutlineTextMetricsA(hdc, 0, NULL);
trace("otm buffer size %u (0x%x)\n", otm_size, otm_size);
otm = HeapAlloc(GetProcessHeap(), 0, otm_size);
memset(otm, 0xAA, otm_size);
SetLastError(0xdeadbeef);
otm->otmSize = sizeof(*otm); /* just in case for Win9x compatibility */
ret = GetOutlineTextMetricsA(hdc, otm->otmSize, otm);
ok(ret == 1 /* Win9x */ ||
ret == otm->otmSize /* XP*/,
"expected %u, got %u, error %d\n", otm->otmSize, ret, GetLastError());
if (ret != 1) /* Win9x doesn't care about pointing beyond of the buffer */
{
ok(otm->otmpFamilyName == NULL, "expected NULL got %p\n", otm->otmpFamilyName);
ok(otm->otmpFaceName == NULL, "expected NULL got %p\n", otm->otmpFaceName);
ok(otm->otmpStyleName == NULL, "expected NULL got %p\n", otm->otmpStyleName);
ok(otm->otmpFullName == NULL, "expected NULL got %p\n", otm->otmpFullName);
}
memset(otm, 0xAA, otm_size);
SetLastError(0xdeadbeef);
otm->otmSize = otm_size; /* just in case for Win9x compatibility */
ret = GetOutlineTextMetricsA(hdc, otm->otmSize, otm);
ok(ret == 1 /* Win9x */ ||
ret == otm->otmSize /* XP*/,
"expected %u, got %u, error %d\n", otm->otmSize, ret, GetLastError());
if (ret != 1) /* Win9x doesn't care about pointing beyond of the buffer */
{
ok(otm->otmpFamilyName != NULL, "expected not NULL got %p\n", otm->otmpFamilyName);
ok(otm->otmpFaceName != NULL, "expected not NULL got %p\n", otm->otmpFaceName);
ok(otm->otmpStyleName != NULL, "expected not NULL got %p\n", otm->otmpStyleName);
ok(otm->otmpFullName != NULL, "expected not NULL got %p\n", otm->otmpFullName);
}
/* ask about truncated data */
memset(otm, 0xAA, otm_size);
memset(&unset_ptr, 0xAA, sizeof(unset_ptr));
SetLastError(0xdeadbeef);
otm->otmSize = sizeof(*otm) - sizeof(LPSTR); /* just in case for Win9x compatibility */
ret = GetOutlineTextMetricsA(hdc, otm->otmSize, otm);
ok(ret == 1 /* Win9x */ ||
ret == otm->otmSize /* XP*/,
"expected %u, got %u, error %d\n", otm->otmSize, ret, GetLastError());
if (ret != 1) /* Win9x doesn't care about pointing beyond of the buffer */
{
ok(otm->otmpFamilyName == NULL, "expected NULL got %p\n", otm->otmpFamilyName);
ok(otm->otmpFaceName == NULL, "expected NULL got %p\n", otm->otmpFaceName);
ok(otm->otmpStyleName == NULL, "expected NULL got %p\n", otm->otmpStyleName);
}
ok(otm->otmpFullName == unset_ptr, "expected %p got %p\n", unset_ptr, otm->otmpFullName);
HeapFree(GetProcessHeap(), 0, otm);
SelectObject(hdc, hfont_old);
DeleteObject(hfont);
ReleaseDC(0, hdc);
}
static void testJustification(HDC hdc, PCSTR str, RECT *clientArea)
{
INT y,
breakCount,
areaWidth = clientArea->right - clientArea->left,
nErrors = 0, e;
const char *pFirstChar, *pLastChar;
SIZE size;
TEXTMETRICA tm;
struct err
{
const char *start;
int len;
int GetTextExtentExPointWWidth;
} error[20];
GetTextMetricsA(hdc, &tm);
y = clientArea->top;
do {
breakCount = 0;
while (*str == tm.tmBreakChar) str++; /* skip leading break chars */
pFirstChar = str;
do {
pLastChar = str;
/* if not at the end of the string, ... */
if (*str == '\0') break;
/* ... add the next word to the current extent */
while (*str != '\0' && *str++ != tm.tmBreakChar);
breakCount++;
SetTextJustification(hdc, 0, 0);
GetTextExtentPoint32A(hdc, pFirstChar, str - pFirstChar - 1, &size);
} while ((int) size.cx < areaWidth);
/* ignore trailing break chars */
breakCount--;
while (*(pLastChar - 1) == tm.tmBreakChar)
{
pLastChar--;
breakCount--;
}
if (*str == '\0' || breakCount <= 0) pLastChar = str;
SetTextJustification(hdc, 0, 0);
GetTextExtentPoint32A(hdc, pFirstChar, pLastChar - pFirstChar, &size);
/* do not justify the last extent */
if (*str != '\0' && breakCount > 0)
{
SetTextJustification(hdc, areaWidth - size.cx, breakCount);
GetTextExtentPoint32A(hdc, pFirstChar, pLastChar - pFirstChar, &size);
if (size.cx != areaWidth && nErrors < sizeof(error)/sizeof(error[0]) - 1)
{
error[nErrors].start = pFirstChar;
error[nErrors].len = pLastChar - pFirstChar;
error[nErrors].GetTextExtentExPointWWidth = size.cx;
nErrors++;
}
}
trace( "%u %.*s\n", size.cx, (int)(pLastChar - pFirstChar), pFirstChar);
y += size.cy;
str = pLastChar;
} while (*str && y < clientArea->bottom);
for (e = 0; e < nErrors; e++)
{
/* The width returned by GetTextExtentPoint32() is exactly the same
returned by GetTextExtentExPointW() - see dlls/gdi32/font.c */
ok(error[e].GetTextExtentExPointWWidth == areaWidth,
"GetTextExtentPointW() for \"%.*s\" should have returned a width of %d, not %d.\n",
error[e].len, error[e].start, areaWidth, error[e].GetTextExtentExPointWWidth);
}
}
static void test_SetTextJustification(void)
{
HDC hdc;
RECT clientArea;
LOGFONTA lf;
HFONT hfont;
HWND hwnd;
SIZE size, expect;
int i;
WORD indices[2];
static const char testText[] =
"Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do "
"eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut "
"enim ad minim veniam, quis nostrud exercitation ullamco laboris "
"nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in "
"reprehenderit in voluptate velit esse cillum dolore eu fugiat "
"nulla pariatur. Excepteur sint occaecat cupidatat non proident, "
"sunt in culpa qui officia deserunt mollit anim id est laborum.";
hwnd = CreateWindowExA(0, "static", "", WS_POPUP, 0,0, 400,400, 0, 0, 0, NULL);
GetClientRect( hwnd, &clientArea );
hdc = GetDC( hwnd );
if (!is_font_installed("Times New Roman"))
{
skip("Times New Roman is not installed\n");
return;
}
memset(&lf, 0, sizeof lf);
lf.lfCharSet = ANSI_CHARSET;
lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
lf.lfWeight = FW_DONTCARE;
lf.lfHeight = 20;
lf.lfQuality = DEFAULT_QUALITY;
lstrcpyA(lf.lfFaceName, "Times New Roman");
hfont = create_font("Times New Roman", &lf);
SelectObject(hdc, hfont);
testJustification(hdc, testText, &clientArea);
if (!pGetGlyphIndicesA || !pGetTextExtentExPointI) goto done;
pGetGlyphIndicesA( hdc, "A ", 2, indices, 0 );
SetTextJustification(hdc, 0, 0);
GetTextExtentPoint32A(hdc, " ", 1, &expect);
GetTextExtentPoint32A(hdc, " ", 3, &size);
ok( size.cx == 3 * expect.cx, "wrong size %d/%d\n", size.cx, expect.cx );
SetTextJustification(hdc, 4, 1);
GetTextExtentPoint32A(hdc, " ", 1, &size);
ok( size.cx == expect.cx + 4, "wrong size %d/%d\n", size.cx, expect.cx );
SetTextJustification(hdc, 9, 2);
GetTextExtentPoint32A(hdc, " ", 2, &size);
ok( size.cx == 2 * expect.cx + 9, "wrong size %d/%d\n", size.cx, expect.cx );
SetTextJustification(hdc, 7, 3);
GetTextExtentPoint32A(hdc, " ", 3, &size);
ok( size.cx == 3 * expect.cx + 7, "wrong size %d/%d\n", size.cx, expect.cx );
SetTextJustification(hdc, 7, 3);
SetTextCharacterExtra(hdc, 2 );
GetTextExtentPoint32A(hdc, " ", 3, &size);
ok( size.cx == 3 * (expect.cx + 2) + 7, "wrong size %d/%d\n", size.cx, expect.cx );
SetTextJustification(hdc, 0, 0);
SetTextCharacterExtra(hdc, 0);
size.cx = size.cy = 1234;
GetTextExtentPoint32A(hdc, " ", 0, &size);
ok( size.cx == 0 && size.cy == 0, "wrong size %d,%d\n", size.cx, size.cy );
pGetTextExtentExPointI(hdc, indices, 2, -1, NULL, NULL, &expect);
SetTextJustification(hdc, 5, 1);
pGetTextExtentExPointI(hdc, indices, 2, -1, NULL, NULL, &size);
ok( size.cx == expect.cx + 5, "wrong size %d/%d\n", size.cx, expect.cx );
SetTextJustification(hdc, 0, 0);
SetMapMode( hdc, MM_ANISOTROPIC );
SetWindowExtEx( hdc, 2, 2, NULL );
GetClientRect( hwnd, &clientArea );
DPtoLP( hdc, (POINT *)&clientArea, 2 );
testJustification(hdc, testText, &clientArea);
GetTextExtentPoint32A(hdc, "A", 1, &expect);
for (i = 0; i < 10; i++)
{
SetTextCharacterExtra(hdc, i);
GetTextExtentPoint32A(hdc, "A", 1, &size);
ok( size.cx == expect.cx + i, "wrong size %d/%d+%d\n", size.cx, expect.cx, i );
}
SetTextCharacterExtra(hdc, 0);
pGetTextExtentExPointI(hdc, indices, 1, -1, NULL, NULL, &expect);
for (i = 0; i < 10; i++)
{
SetTextCharacterExtra(hdc, i);
pGetTextExtentExPointI(hdc, indices, 1, -1, NULL, NULL, &size);
ok( size.cx == expect.cx + i, "wrong size %d/%d+%d\n", size.cx, expect.cx, i );
}
SetTextCharacterExtra(hdc, 0);
SetViewportExtEx( hdc, 3, 3, NULL );
GetClientRect( hwnd, &clientArea );
DPtoLP( hdc, (POINT *)&clientArea, 2 );
testJustification(hdc, testText, &clientArea);
GetTextExtentPoint32A(hdc, "A", 1, &expect);
for (i = 0; i < 10; i++)
{
SetTextCharacterExtra(hdc, i);
GetTextExtentPoint32A(hdc, "A", 1, &size);
ok( size.cx == expect.cx + i, "wrong size %d/%d+%d\n", size.cx, expect.cx, i );
}
done:
DeleteObject(hfont);
ReleaseDC(hwnd, hdc);
DestroyWindow(hwnd);
}
static BOOL get_glyph_indices(INT charset, UINT code_page, WORD *idx, UINT count, BOOL unicode)
{
HDC hdc;
LOGFONTA lf;
HFONT hfont, hfont_old;
CHARSETINFO csi;
FONTSIGNATURE fs;
INT cs;
DWORD i, ret;
char name[64];
assert(count <= 128);
memset(&lf, 0, sizeof(lf));
lf.lfCharSet = charset;
lf.lfHeight = 10;
lstrcpyA(lf.lfFaceName, "Arial");
SetLastError(0xdeadbeef);
hfont = CreateFontIndirectA(&lf);
ok(hfont != 0, "CreateFontIndirectA error %u\n", GetLastError());
hdc = GetDC(0);
hfont_old = SelectObject(hdc, hfont);
cs = GetTextCharsetInfo(hdc, &fs, 0);
ok(cs == charset, "expected %d, got %d\n", charset, cs);
SetLastError(0xdeadbeef);
ret = GetTextFaceA(hdc, sizeof(name), name);
ok(ret, "GetTextFaceA error %u\n", GetLastError());
if (charset == SYMBOL_CHARSET)
{
ok(strcmp("Arial", name), "face name should NOT be Arial\n");
ok(fs.fsCsb[0] & (1 << 31), "symbol encoding should be available\n");
}
else
{
ok(!strcmp("Arial", name), "face name should be Arial, not %s\n", name);
ok(!(fs.fsCsb[0] & (1 << 31)), "symbol encoding should NOT be available\n");
}
if (!TranslateCharsetInfo((DWORD *)(INT_PTR)cs, &csi, TCI_SRCCHARSET))
{
trace("Can't find codepage for charset %d\n", cs);
ReleaseDC(0, hdc);
return FALSE;
}
ok(csi.ciACP == code_page, "expected %d, got %d\n", code_page, csi.ciACP);
if (pGdiGetCodePage != NULL && pGdiGetCodePage(hdc) != code_page)
{
skip("Font code page %d, looking for code page %d\n",
pGdiGetCodePage(hdc), code_page);
ReleaseDC(0, hdc);
return FALSE;
}
if (unicode)
{
char ansi_buf[128];
WCHAR unicode_buf[128];
for (i = 0; i < count; i++) ansi_buf[i] = (BYTE)(i + 128);
MultiByteToWideChar(code_page, 0, ansi_buf, count, unicode_buf, count);
SetLastError(0xdeadbeef);
ret = pGetGlyphIndicesW(hdc, unicode_buf, count, idx, 0);
ok(ret == count, "GetGlyphIndicesW expected %d got %d, error %u\n",
count, ret, GetLastError());
}
else
{
char ansi_buf[128];
for (i = 0; i < count; i++) ansi_buf[i] = (BYTE)(i + 128);
SetLastError(0xdeadbeef);
ret = pGetGlyphIndicesA(hdc, ansi_buf, count, idx, 0);
ok(ret == count, "GetGlyphIndicesA expected %d got %d, error %u\n",
count, ret, GetLastError());
}
SelectObject(hdc, hfont_old);
DeleteObject(hfont);
ReleaseDC(0, hdc);
return TRUE;
}
static void test_font_charset(void)
{
static struct charset_data
{
INT charset;
UINT code_page;
WORD font_idxA[128], font_idxW[128];
} cd[] =
{
{ ANSI_CHARSET, 1252 },
{ RUSSIAN_CHARSET, 1251 },
{ SYMBOL_CHARSET, CP_SYMBOL } /* keep it as the last one */
};
int i;
if (!pGetGlyphIndicesA || !pGetGlyphIndicesW)
{
win_skip("Skipping the font charset test on a Win9x platform\n");
return;
}
if (!is_font_installed("Arial"))
{
skip("Arial is not installed\n");
return;
}
for (i = 0; i < sizeof(cd)/sizeof(cd[0]); i++)
{
if (cd[i].charset == SYMBOL_CHARSET)
{
if (!is_font_installed("Symbol") && !is_font_installed("Wingdings"))
{
skip("Symbol or Wingdings is not installed\n");
break;
}
}
if (get_glyph_indices(cd[i].charset, cd[i].code_page, cd[i].font_idxA, 128, FALSE) &&
get_glyph_indices(cd[i].charset, cd[i].code_page, cd[i].font_idxW, 128, TRUE))
ok(!memcmp(cd[i].font_idxA, cd[i].font_idxW, 128*sizeof(WORD)), "%d: indices don't match\n", i);
}
ok(memcmp(cd[0].font_idxW, cd[1].font_idxW, 128*sizeof(WORD)), "0 vs 1: indices shouldn't match\n");
if (i > 2)
{
ok(memcmp(cd[0].font_idxW, cd[2].font_idxW, 128*sizeof(WORD)), "0 vs 2: indices shouldn't match\n");
ok(memcmp(cd[1].font_idxW, cd[2].font_idxW, 128*sizeof(WORD)), "1 vs 2: indices shouldn't match\n");
}
else
skip("Symbol or Wingdings is not installed\n");
}
static void test_GdiGetCodePage(void)
{
static const struct _matching_data
{
UINT current_codepage;
LPCSTR lfFaceName;
UCHAR lfCharSet;
UINT expected_codepage;
} matching_data[] = {
{1251, "Arial", ANSI_CHARSET, 1252},
{1251, "Tahoma", ANSI_CHARSET, 1252},
{1252, "Arial", ANSI_CHARSET, 1252},
{1252, "Tahoma", ANSI_CHARSET, 1252},
{1253, "Arial", ANSI_CHARSET, 1252},
{1253, "Tahoma", ANSI_CHARSET, 1252},
{ 932, "Arial", ANSI_CHARSET, 1252}, /* Japanese Windows returns 1252, not 932 */
{ 932, "Tahoma", ANSI_CHARSET, 1252},
{ 932, "MS UI Gothic", ANSI_CHARSET, 1252},
{ 936, "Arial", ANSI_CHARSET, 936},
{ 936, "Tahoma", ANSI_CHARSET, 936},
{ 936, "Simsun", ANSI_CHARSET, 936},
{ 949, "Arial", ANSI_CHARSET, 949},
{ 949, "Tahoma", ANSI_CHARSET, 949},
{ 949, "Gulim", ANSI_CHARSET, 949},
{ 950, "Arial", ANSI_CHARSET, 950},
{ 950, "Tahoma", ANSI_CHARSET, 950},
{ 950, "PMingLiU", ANSI_CHARSET, 950},
};
HDC hdc;
LOGFONTA lf;
HFONT hfont;
UINT charset, acp;
DWORD codepage;
int i;
if (!pGdiGetCodePage)
{
skip("GdiGetCodePage not available on this platform\n");
return;
}
acp = GetACP();
for (i = 0; i < sizeof(matching_data) / sizeof(struct _matching_data); i++)
{
/* only test data matched current locale codepage */
if (matching_data[i].current_codepage != acp)
continue;
if (!is_font_installed(matching_data[i].lfFaceName))
{
skip("%s is not installed\n", matching_data[i].lfFaceName);
continue;
}
hdc = GetDC(0);
memset(&lf, 0, sizeof(lf));
lf.lfHeight = -16;
lf.lfCharSet = matching_data[i].lfCharSet;
lstrcpyA(lf.lfFaceName, matching_data[i].lfFaceName);
hfont = CreateFontIndirectA(&lf);
ok(hfont != 0, "CreateFontIndirectA error %u\n", GetLastError());
hfont = SelectObject(hdc, hfont);
charset = GetTextCharset(hdc);
codepage = pGdiGetCodePage(hdc);
trace("acp=%d, lfFaceName=%s, lfCharSet=%d, GetTextCharset=%d, GdiGetCodePage=%d, expected codepage=%d\n",
acp, lf.lfFaceName, lf.lfCharSet, charset, codepage, matching_data[i].expected_codepage);
ok(codepage == matching_data[i].expected_codepage,
"GdiGetCodePage should have returned %d, got %d\n", matching_data[i].expected_codepage, codepage);
hfont = SelectObject(hdc, hfont);
DeleteObject(hfont);
ReleaseDC(NULL, hdc);
}
}
static void test_GetFontUnicodeRanges(void)
{
LOGFONTA lf;
HDC hdc;
HFONT hfont, hfont_old;
DWORD size;
GLYPHSET *gs;
DWORD i;
if (!pGetFontUnicodeRanges)
{
win_skip("GetFontUnicodeRanges not available before W2K\n");
return;
}
memset(&lf, 0, sizeof(lf));
lstrcpyA(lf.lfFaceName, "Arial");
hfont = create_font("Arial", &lf);
hdc = GetDC(0);
hfont_old = SelectObject(hdc, hfont);
size = pGetFontUnicodeRanges(NULL, NULL);
ok(!size, "GetFontUnicodeRanges succeeded unexpectedly\n");
size = pGetFontUnicodeRanges(hdc, NULL);
ok(size, "GetFontUnicodeRanges failed unexpectedly\n");
gs = HeapAlloc(GetProcessHeap(), 0, size);
size = pGetFontUnicodeRanges(hdc, gs);
ok(size, "GetFontUnicodeRanges failed\n");
if (0) /* Disabled to limit console spam */
for (i = 0; i < gs->cRanges; i++)
trace("%03d wcLow %04x cGlyphs %u\n", i, gs->ranges[i].wcLow, gs->ranges[i].cGlyphs);
trace("found %u ranges\n", gs->cRanges);
HeapFree(GetProcessHeap(), 0, gs);
SelectObject(hdc, hfont_old);
DeleteObject(hfont);
ReleaseDC(NULL, hdc);
}
#define MAX_ENUM_FONTS 4096
struct enum_font_data
{
int total;
LOGFONTA lf[MAX_ENUM_FONTS];
};
struct enum_fullname_data
{
int total;
ENUMLOGFONTA elf[MAX_ENUM_FONTS];
};
struct enum_font_dataW
{
int total;
LOGFONTW lf[MAX_ENUM_FONTS];
};
static INT CALLBACK arial_enum_proc(const LOGFONTA *lf, const TEXTMETRICA *tm, DWORD type, LPARAM lParam)
{
struct enum_font_data *efd = (struct enum_font_data *)lParam;
const NEWTEXTMETRICA *ntm = (const NEWTEXTMETRICA *)tm;
ok(lf->lfHeight == tm->tmHeight, "lfHeight %d != tmHeight %d\n", lf->lfHeight, tm->tmHeight);
ok(lf->lfHeight > 0 && lf->lfHeight < 200, "enumerated font height %d\n", lf->lfHeight);
if (type != TRUETYPE_FONTTYPE) return 1;
ok(ntm->ntmCellHeight + ntm->ntmCellHeight/5 >= ntm->ntmSizeEM, "ntmCellHeight %d should be close to ntmSizeEM %d\n", ntm->ntmCellHeight, ntm->ntmSizeEM);
if (0) /* Disabled to limit console spam */
trace("enumed font \"%s\", charset %d, height %d, weight %d, italic %d\n",
lf->lfFaceName, lf->lfCharSet, lf->lfHeight, lf->lfWeight, lf->lfItalic);
if (efd->total < MAX_ENUM_FONTS)
efd->lf[efd->total++] = *lf;
else
trace("enum tests invalid; you have more than %d fonts\n", MAX_ENUM_FONTS);
return 1;
}
static INT CALLBACK arial_enum_procw(const LOGFONTW *lf, const TEXTMETRICW *tm, DWORD type, LPARAM lParam)
{
struct enum_font_dataW *efd = (struct enum_font_dataW *)lParam;
const NEWTEXTMETRICW *ntm = (const NEWTEXTMETRICW *)tm;
ok(lf->lfHeight == tm->tmHeight, "lfHeight %d != tmHeight %d\n", lf->lfHeight, tm->tmHeight);
ok(lf->lfHeight > 0 && lf->lfHeight < 200, "enumerated font height %d\n", lf->lfHeight);
if (type != TRUETYPE_FONTTYPE) return 1;
ok(ntm->ntmCellHeight + ntm->ntmCellHeight/5 >= ntm->ntmSizeEM, "ntmCellHeight %d should be close to ntmSizeEM %d\n", ntm->ntmCellHeight, ntm->ntmSizeEM);
if (0) /* Disabled to limit console spam */
trace("enumed font %s, charset %d, height %d, weight %d, italic %d\n",
wine_dbgstr_w(lf->lfFaceName), lf->lfCharSet, lf->lfHeight, lf->lfWeight, lf->lfItalic);
if (efd->total < MAX_ENUM_FONTS)
efd->lf[efd->total++] = *lf;
else
trace("enum tests invalid; you have more than %d fonts\n", MAX_ENUM_FONTS);
return 1;
}
static void get_charset_stats(struct enum_font_data *efd,
int *ansi_charset, int *symbol_charset,
int *russian_charset)
{
int i;
*ansi_charset = 0;
*symbol_charset = 0;
*russian_charset = 0;
for (i = 0; i < efd->total; i++)
{
switch (efd->lf[i].lfCharSet)
{
case ANSI_CHARSET:
(*ansi_charset)++;
break;
case SYMBOL_CHARSET:
(*symbol_charset)++;
break;
case RUSSIAN_CHARSET:
(*russian_charset)++;
break;
}
}
}
static void get_charset_statsW(struct enum_font_dataW *efd,
int *ansi_charset, int *symbol_charset,
int *russian_charset)
{
int i;
*ansi_charset = 0;
*symbol_charset = 0;
*russian_charset = 0;
for (i = 0; i < efd->total; i++)
{
switch (efd->lf[i].lfCharSet)
{
case ANSI_CHARSET:
(*ansi_charset)++;
break;
case SYMBOL_CHARSET:
(*symbol_charset)++;
break;
case RUSSIAN_CHARSET:
(*russian_charset)++;
break;
}
}
}
static void test_EnumFontFamilies(const char *font_name, INT font_charset)
{
struct enum_font_data efd;
struct enum_font_dataW efdw;
LOGFONTA lf;
HDC hdc;
int i, ret, ansi_charset, symbol_charset, russian_charset;
trace("Testing font %s, charset %d\n", *font_name ? font_name : "<empty>", font_charset);
if (*font_name && !is_truetype_font_installed(font_name))
{
skip("%s is not installed\n", font_name);
return;
}
hdc = GetDC(0);
/* Observed behaviour: EnumFontFamilies enumerates aliases like "Arial Cyr"
* while EnumFontFamiliesEx doesn't.
*/
if (!*font_name && font_charset == DEFAULT_CHARSET) /* do it only once */
{
/*
* Use EnumFontFamiliesW since win98 crashes when the
* second parameter is NULL using EnumFontFamilies
*/
efdw.total = 0;
SetLastError(0xdeadbeef);
ret = EnumFontFamiliesW(hdc, NULL, arial_enum_procw, (LPARAM)&efdw);
ok(ret || GetLastError() == ERROR_CALL_NOT_IMPLEMENTED, "EnumFontFamiliesW error %u\n", GetLastError());
if(ret)
{
get_charset_statsW(&efdw, &ansi_charset, &symbol_charset, &russian_charset);
trace("enumerated ansi %d, symbol %d, russian %d fonts for NULL\n",
ansi_charset, symbol_charset, russian_charset);
ok(efdw.total > 0, "fonts enumerated: NULL\n");
ok(ansi_charset > 0, "NULL family should enumerate ANSI_CHARSET\n");
ok(symbol_charset > 0, "NULL family should enumerate SYMBOL_CHARSET\n");
ok(russian_charset > 0 ||
broken(russian_charset == 0), /* NT4 */
"NULL family should enumerate RUSSIAN_CHARSET\n");
}
efdw.total = 0;
SetLastError(0xdeadbeef);
ret = EnumFontFamiliesExW(hdc, NULL, arial_enum_procw, (LPARAM)&efdw, 0);
ok(ret || GetLastError() == ERROR_CALL_NOT_IMPLEMENTED, "EnumFontFamiliesExW error %u\n", GetLastError());
if(ret)
{
get_charset_statsW(&efdw, &ansi_charset, &symbol_charset, &russian_charset);
trace("enumerated ansi %d, symbol %d, russian %d fonts for NULL\n",
ansi_charset, symbol_charset, russian_charset);
ok(efdw.total > 0, "fonts enumerated: NULL\n");
ok(ansi_charset > 0, "NULL family should enumerate ANSI_CHARSET\n");
ok(symbol_charset > 0, "NULL family should enumerate SYMBOL_CHARSET\n");
ok(russian_charset > 0, "NULL family should enumerate RUSSIAN_CHARSET\n");
}
}
efd.total = 0;
SetLastError(0xdeadbeef);
ret = EnumFontFamiliesA(hdc, font_name, arial_enum_proc, (LPARAM)&efd);
ok(ret, "EnumFontFamilies error %u\n", GetLastError());
get_charset_stats(&efd, &ansi_charset, &symbol_charset, &russian_charset);
trace("enumerated ansi %d, symbol %d, russian %d fonts for %s\n",
ansi_charset, symbol_charset, russian_charset,
*font_name ? font_name : "<empty>");
if (*font_name)
ok(efd.total > 0, "no fonts enumerated: %s\n", font_name);
else
ok(!efd.total, "no fonts should be enumerated for empty font_name\n");
for (i = 0; i < efd.total; i++)
{
/* FIXME: remove completely once Wine is fixed */
if (efd.lf[i].lfCharSet != font_charset)
{
todo_wine
ok(efd.lf[i].lfCharSet == font_charset, "%d: got charset %d\n", i, efd.lf[i].lfCharSet);
}
else
ok(efd.lf[i].lfCharSet == font_charset, "%d: got charset %d\n", i, efd.lf[i].lfCharSet);
ok(!strcmp(efd.lf[i].lfFaceName, font_name), "expected %s, got %s\n",
font_name, efd.lf[i].lfFaceName);
}
memset(&lf, 0, sizeof(lf));
lf.lfCharSet = ANSI_CHARSET;
strcpy(lf.lfFaceName, font_name);
efd.total = 0;
SetLastError(0xdeadbeef);
ret = EnumFontFamiliesExA(hdc, &lf, arial_enum_proc, (LPARAM)&efd, 0);
ok(ret, "EnumFontFamiliesEx error %u\n", GetLastError());
get_charset_stats(&efd, &ansi_charset, &symbol_charset, &russian_charset);
trace("enumerated ansi %d, symbol %d, russian %d fonts for %s ANSI_CHARSET\n",
ansi_charset, symbol_charset, russian_charset,
*font_name ? font_name : "<empty>");
if (font_charset == SYMBOL_CHARSET)
{
if (*font_name)
ok(efd.total == 0, "no fonts should be enumerated: %s ANSI_CHARSET\n", font_name);
else
ok(efd.total > 0, "no fonts enumerated: %s\n", font_name);
}
else
{
ok(efd.total > 0, "no fonts enumerated: %s ANSI_CHARSET\n", font_name);
for (i = 0; i < efd.total; i++)
{
ok(efd.lf[i].lfCharSet == ANSI_CHARSET, "%d: got charset %d\n", i, efd.lf[i].lfCharSet);
if (*font_name)
ok(!strcmp(efd.lf[i].lfFaceName, font_name), "expected %s, got %s\n",
font_name, efd.lf[i].lfFaceName);
}
}
/* DEFAULT_CHARSET should enumerate all available charsets */
memset(&lf, 0, sizeof(lf));
lf.lfCharSet = DEFAULT_CHARSET;
strcpy(lf.lfFaceName, font_name);
efd.total = 0;
SetLastError(0xdeadbeef);
EnumFontFamiliesExA(hdc, &lf, arial_enum_proc, (LPARAM)&efd, 0);
ok(ret, "EnumFontFamiliesEx error %u\n", GetLastError());
get_charset_stats(&efd, &ansi_charset, &symbol_charset, &russian_charset);
trace("enumerated ansi %d, symbol %d, russian %d fonts for %s DEFAULT_CHARSET\n",
ansi_charset, symbol_charset, russian_charset,
*font_name ? font_name : "<empty>");
ok(efd.total > 0, "no fonts enumerated: %s DEFAULT_CHARSET\n", font_name);
for (i = 0; i < efd.total; i++)
{
if (*font_name)
ok(!strcmp(efd.lf[i].lfFaceName, font_name), "expected %s, got %s\n",
font_name, efd.lf[i].lfFaceName);
}
if (*font_name)
{
switch (font_charset)
{
case ANSI_CHARSET:
ok(ansi_charset > 0,
"ANSI_CHARSET should enumerate ANSI_CHARSET for %s\n", font_name);
ok(!symbol_charset,
"ANSI_CHARSET should NOT enumerate SYMBOL_CHARSET for %s\n", font_name);
ok(russian_charset > 0,
"ANSI_CHARSET should enumerate RUSSIAN_CHARSET for %s\n", font_name);
break;
case SYMBOL_CHARSET:
ok(!ansi_charset,
"SYMBOL_CHARSET should NOT enumerate ANSI_CHARSET for %s\n", font_name);
ok(symbol_charset,
"SYMBOL_CHARSET should enumerate SYMBOL_CHARSET for %s\n", font_name);
ok(!russian_charset,
"SYMBOL_CHARSET should NOT enumerate RUSSIAN_CHARSET for %s\n", font_name);
break;
case DEFAULT_CHARSET:
ok(ansi_charset > 0,
"DEFAULT_CHARSET should enumerate ANSI_CHARSET for %s\n", font_name);
ok(symbol_charset > 0,
"DEFAULT_CHARSET should enumerate SYMBOL_CHARSET for %s\n", font_name);
ok(russian_charset > 0,
"DEFAULT_CHARSET should enumerate RUSSIAN_CHARSET for %s\n", font_name);
break;
}
}
else
{
ok(ansi_charset > 0,
"DEFAULT_CHARSET should enumerate ANSI_CHARSET for %s\n", *font_name ? font_name : "<empty>");
ok(symbol_charset > 0,
"DEFAULT_CHARSET should enumerate SYMBOL_CHARSET for %s\n", *font_name ? font_name : "<empty>");
ok(russian_charset > 0,
"DEFAULT_CHARSET should enumerate RUSSIAN_CHARSET for %s\n", *font_name ? font_name : "<empty>");
}
memset(&lf, 0, sizeof(lf));
lf.lfCharSet = SYMBOL_CHARSET;
strcpy(lf.lfFaceName, font_name);
efd.total = 0;
SetLastError(0xdeadbeef);
EnumFontFamiliesExA(hdc, &lf, arial_enum_proc, (LPARAM)&efd, 0);
ok(ret, "EnumFontFamiliesEx error %u\n", GetLastError());
get_charset_stats(&efd, &ansi_charset, &symbol_charset, &russian_charset);
trace("enumerated ansi %d, symbol %d, russian %d fonts for %s SYMBOL_CHARSET\n",
ansi_charset, symbol_charset, russian_charset,
*font_name ? font_name : "<empty>");
if (*font_name && font_charset == ANSI_CHARSET)
ok(efd.total == 0, "no fonts should be enumerated: %s SYMBOL_CHARSET\n", font_name);
else
{
ok(efd.total > 0, "no fonts enumerated: %s SYMBOL_CHARSET\n", font_name);
for (i = 0; i < efd.total; i++)
{
ok(efd.lf[i].lfCharSet == SYMBOL_CHARSET, "%d: got charset %d\n", i, efd.lf[i].lfCharSet);
if (*font_name)
ok(!strcmp(efd.lf[i].lfFaceName, font_name), "expected %s, got %s\n",
font_name, efd.lf[i].lfFaceName);
}
ok(!ansi_charset,
"SYMBOL_CHARSET should NOT enumerate ANSI_CHARSET for %s\n", *font_name ? font_name : "<empty>");
ok(symbol_charset > 0,
"SYMBOL_CHARSET should enumerate SYMBOL_CHARSET for %s\n", *font_name ? font_name : "<empty>");
ok(!russian_charset,
"SYMBOL_CHARSET should NOT enumerate RUSSIAN_CHARSET for %s\n", *font_name ? font_name : "<empty>");
}
ReleaseDC(0, hdc);
}
static INT CALLBACK enum_multi_charset_font_proc(const LOGFONTA *lf, const TEXTMETRICA *tm, DWORD type, LPARAM lParam)
{
const NEWTEXTMETRICEXA *ntm = (const NEWTEXTMETRICEXA *)tm;
LOGFONTA *target = (LOGFONTA *)lParam;
const DWORD valid_bits = 0x003f01ff;
CHARSETINFO csi;
DWORD fs;
if (type != TRUETYPE_FONTTYPE) return TRUE;
if (TranslateCharsetInfo(ULongToPtr(target->lfCharSet), &csi, TCI_SRCCHARSET)) {
fs = ntm->ntmFontSig.fsCsb[0] & valid_bits;
if ((fs & csi.fs.fsCsb[0]) && (fs & ~csi.fs.fsCsb[0]) && (fs & FS_LATIN1)) {
*target = *lf;
return FALSE;
}
}
return TRUE;
}
static INT CALLBACK enum_font_data_proc(const LOGFONTA *lf, const TEXTMETRICA *ntm, DWORD type, LPARAM lParam)
{
struct enum_font_data *efd = (struct enum_font_data *)lParam;
if (type != TRUETYPE_FONTTYPE) return 1;
if (efd->total < MAX_ENUM_FONTS)
efd->lf[efd->total++] = *lf;
else
trace("enum tests invalid; you have more than %d fonts\n", MAX_ENUM_FONTS);
return 1;
}
static INT CALLBACK enum_fullname_data_proc(const LOGFONTA *lf, const TEXTMETRICA *ntm, DWORD type, LPARAM lParam)
{
struct enum_fullname_data *efnd = (struct enum_fullname_data *)lParam;
if (type != TRUETYPE_FONTTYPE) return 1;
if (efnd->total < MAX_ENUM_FONTS)
efnd->elf[efnd->total++] = *(ENUMLOGFONTA *)lf;
else
trace("enum tests invalid; you have more than %d fonts\n", MAX_ENUM_FONTS);
return 1;
}
static void test_EnumFontFamiliesEx_default_charset(void)
{
struct enum_font_data efd;
LOGFONTA target, enum_font;
UINT acp;
HDC hdc;
CHARSETINFO csi;
acp = GetACP();
if (!TranslateCharsetInfo(ULongToPtr(acp), &csi, TCI_SRCCODEPAGE)) {
skip("TranslateCharsetInfo failed for code page %u.\n", acp);
return;
}
hdc = GetDC(0);
memset(&enum_font, 0, sizeof(enum_font));
enum_font.lfCharSet = csi.ciCharset;
target.lfFaceName[0] = '\0';
target.lfCharSet = csi.ciCharset;
EnumFontFamiliesExA(hdc, &enum_font, enum_multi_charset_font_proc, (LPARAM)&target, 0);
if (target.lfFaceName[0] == '\0') {
skip("suitable font isn't found for charset %d.\n", enum_font.lfCharSet);
return;
}
if (acp == 874 || acp == 1255 || acp == 1256) {
/* these codepage use complex script, expecting ANSI_CHARSET here. */
target.lfCharSet = ANSI_CHARSET;
}
efd.total = 0;
memset(&enum_font, 0, sizeof(enum_font));
strcpy(enum_font.lfFaceName, target.lfFaceName);
enum_font.lfCharSet = DEFAULT_CHARSET;
EnumFontFamiliesExA(hdc, &enum_font, enum_font_data_proc, (LPARAM)&efd, 0);
ReleaseDC(0, hdc);
trace("'%s' has %d charsets.\n", target.lfFaceName, efd.total);
if (efd.total < 2) {
ok(0, "EnumFontFamilies is broken. Expected >= 2, got %d.\n", efd.total);
return;
}
ok(efd.lf[0].lfCharSet == target.lfCharSet,
"(%s) got charset %d expected %d\n",
efd.lf[0].lfFaceName, efd.lf[0].lfCharSet, target.lfCharSet);
return;
}
static void test_negative_width(HDC hdc, const LOGFONTA *lf)
{
HFONT hfont, hfont_prev;
DWORD ret;
GLYPHMETRICS gm1, gm2;
LOGFONTA lf2 = *lf;
WORD idx;
if(!pGetGlyphIndicesA)
return;
/* negative widths are handled just as positive ones */
lf2.lfWidth = -lf->lfWidth;
SetLastError(0xdeadbeef);
hfont = CreateFontIndirectA(lf);
ok(hfont != 0, "CreateFontIndirect error %u\n", GetLastError());
check_font("original", lf, hfont);
hfont_prev = SelectObject(hdc, hfont);
ret = pGetGlyphIndicesA(hdc, "x", 1, &idx, GGI_MARK_NONEXISTING_GLYPHS);
if (ret == GDI_ERROR || idx == 0xffff)
{
SelectObject(hdc, hfont_prev);
DeleteObject(hfont);
skip("Font %s doesn't contain 'x', skipping the test\n", lf->lfFaceName);
return;
}
/* filling with 0xaa causes false pass under WINEDEBUG=warn+heap */
memset(&gm1, 0xab, sizeof(gm1));
SetLastError(0xdeadbeef);
ret = GetGlyphOutlineA(hdc, 'x', GGO_METRICS, &gm1, 0, NULL, &mat);
ok(ret != GDI_ERROR, "GetGlyphOutline error 0x%x\n", GetLastError());
SelectObject(hdc, hfont_prev);
DeleteObject(hfont);
SetLastError(0xdeadbeef);
hfont = CreateFontIndirectA(&lf2);
ok(hfont != 0, "CreateFontIndirect error %u\n", GetLastError());
check_font("negative width", &lf2, hfont);
hfont_prev = SelectObject(hdc, hfont);
memset(&gm2, 0xbb, sizeof(gm2));
SetLastError(0xdeadbeef);
ret = GetGlyphOutlineA(hdc, 'x', GGO_METRICS, &gm2, 0, NULL, &mat);
ok(ret != GDI_ERROR, "GetGlyphOutline error 0x%x\n", GetLastError());
SelectObject(hdc, hfont_prev);
DeleteObject(hfont);
ok(gm1.gmBlackBoxX == gm2.gmBlackBoxX &&
gm1.gmBlackBoxY == gm2.gmBlackBoxY &&
gm1.gmptGlyphOrigin.x == gm2.gmptGlyphOrigin.x &&
gm1.gmptGlyphOrigin.y == gm2.gmptGlyphOrigin.y &&
gm1.gmCellIncX == gm2.gmCellIncX &&
gm1.gmCellIncY == gm2.gmCellIncY,
"gm1=%d,%d,%d,%d,%d,%d gm2=%d,%d,%d,%d,%d,%d\n",
gm1.gmBlackBoxX, gm1.gmBlackBoxY, gm1.gmptGlyphOrigin.x,
gm1.gmptGlyphOrigin.y, gm1.gmCellIncX, gm1.gmCellIncY,
gm2.gmBlackBoxX, gm2.gmBlackBoxY, gm2.gmptGlyphOrigin.x,
gm2.gmptGlyphOrigin.y, gm2.gmCellIncX, gm2.gmCellIncY);
}
/* PANOSE is 10 bytes in size, need to pack the structure properly */
#include "pshpack2.h"
typedef struct
{
USHORT version;
SHORT xAvgCharWidth;
USHORT usWeightClass;
USHORT usWidthClass;
SHORT fsType;
SHORT ySubscriptXSize;
SHORT ySubscriptYSize;
SHORT ySubscriptXOffset;
SHORT ySubscriptYOffset;
SHORT ySuperscriptXSize;
SHORT ySuperscriptYSize;
SHORT ySuperscriptXOffset;
SHORT ySuperscriptYOffset;
SHORT yStrikeoutSize;
SHORT yStrikeoutPosition;
SHORT sFamilyClass;
PANOSE panose;
ULONG ulUnicodeRange1;
ULONG ulUnicodeRange2;
ULONG ulUnicodeRange3;
ULONG ulUnicodeRange4;
CHAR achVendID[4];
USHORT fsSelection;
USHORT usFirstCharIndex;
USHORT usLastCharIndex;
/* According to the Apple spec, original version didn't have the below fields,
* version numbers were taken from the OpenType spec.
*/
/* version 0 (TrueType 1.5) */
USHORT sTypoAscender;
USHORT sTypoDescender;
USHORT sTypoLineGap;
USHORT usWinAscent;
USHORT usWinDescent;
/* version 1 (TrueType 1.66) */
ULONG ulCodePageRange1;
ULONG ulCodePageRange2;
/* version 2 (OpenType 1.2) */
SHORT sxHeight;
SHORT sCapHeight;
USHORT usDefaultChar;
USHORT usBreakChar;
USHORT usMaxContext;
} TT_OS2_V2;
#include "poppack.h"
typedef struct
{
USHORT version;
USHORT num_tables;
} cmap_header;
typedef struct
{
USHORT plat_id;
USHORT enc_id;
ULONG offset;
} cmap_encoding_record;
typedef struct
{
USHORT format;
USHORT length;
USHORT language;
BYTE glyph_ids[256];
} cmap_format_0;
typedef struct
{
USHORT format;
USHORT length;
USHORT language;
USHORT seg_countx2;
USHORT search_range;
USHORT entry_selector;
USHORT range_shift;
USHORT end_count[1]; /* this is a variable-sized array of length seg_countx2 / 2 */
/* Then follows:
USHORT pad;
USHORT start_count[seg_countx2 / 2];
USHORT id_delta[seg_countx2 / 2];
USHORT id_range_offset[seg_countx2 / 2];
USHORT glyph_ids[];
*/
} cmap_format_4;
typedef struct
{
USHORT end_count;
USHORT start_count;
USHORT id_delta;
USHORT id_range_offset;
} cmap_format_4_seg;
static void expect_ff(const TEXTMETRICA *tmA, const TT_OS2_V2 *os2, WORD family, const char *name)
{
ok((tmA->tmPitchAndFamily & 0xf0) == family ||
broken(PRIMARYLANGID(GetSystemDefaultLangID()) != LANG_ENGLISH),
"%s: expected family %02x got %02x. panose %d-%d-%d-%d-...\n",
name, family, tmA->tmPitchAndFamily, os2->panose.bFamilyType, os2->panose.bSerifStyle,
os2->panose.bWeight, os2->panose.bProportion);
}
static BOOL get_first_last_from_cmap0(void *ptr, DWORD *first, DWORD *last)
{
int i;
cmap_format_0 *cmap = (cmap_format_0*)ptr;
*first = 256;
for(i = 0; i < 256; i++)
{
if(cmap->glyph_ids[i] == 0) continue;
*last = i;
if(*first == 256) *first = i;
}
if(*first == 256) return FALSE;
return TRUE;
}
static void get_seg4(cmap_format_4 *cmap, USHORT seg_num, cmap_format_4_seg *seg)
{
USHORT segs = GET_BE_WORD(cmap->seg_countx2) / 2;
seg->end_count = GET_BE_WORD(cmap->end_count[seg_num]);
seg->start_count = GET_BE_WORD(cmap->end_count[segs + 1 + seg_num]);
seg->id_delta = GET_BE_WORD(cmap->end_count[2 * segs + 1 + seg_num]);
seg->id_range_offset = GET_BE_WORD(cmap->end_count[3 * segs + 1 + seg_num]);
}
static BOOL get_first_last_from_cmap4(void *ptr, DWORD *first, DWORD *last, DWORD limit)
{
int i;
cmap_format_4 *cmap = (cmap_format_4*)ptr;
USHORT seg_count = GET_BE_WORD(cmap->seg_countx2) / 2;
USHORT const *glyph_ids = cmap->end_count + 4 * seg_count + 1;
*first = 0x10000;
for(i = 0; i < seg_count; i++)
{
DWORD code, index;
cmap_format_4_seg seg;
get_seg4(cmap, i, &seg);
for(code = seg.start_count; code <= seg.end_count; code++)
{
if(seg.id_range_offset == 0)
index = (seg.id_delta + code) & 0xffff;
else
{
index = seg.id_range_offset / 2
+ code - seg.start_count
+ i - seg_count;
/* some fonts have broken last segment */
if ((char *)(glyph_ids + index + 1) < (char *)ptr + limit)
index = GET_BE_WORD(glyph_ids[index]);
else
{
trace("segment %04x/%04x index %04x points to nowhere\n",
seg.start_count, seg.end_count, index);
index = 0;
}
if(index) index += seg.id_delta;
}
if(*first == 0x10000)
*last = *first = code;
else if(index)
*last = code;
}
}
if(*first == 0x10000) return FALSE;
return TRUE;
}
static void *get_cmap(cmap_header *header, USHORT plat_id, USHORT enc_id)
{
USHORT i;
cmap_encoding_record *record = (cmap_encoding_record *)(header + 1);
for(i = 0; i < GET_BE_WORD(header->num_tables); i++)
{
if(GET_BE_WORD(record->plat_id) == plat_id && GET_BE_WORD(record->enc_id) == enc_id)
return (BYTE *)header + GET_BE_DWORD(record->offset);
record++;
}
return NULL;
}
typedef enum
{
cmap_none,
cmap_ms_unicode,
cmap_ms_symbol
} cmap_type;
static BOOL get_first_last_from_cmap(HDC hdc, DWORD *first, DWORD *last, cmap_type *cmap_type)
{
LONG size, ret;
cmap_header *header;
void *cmap;
BOOL r = FALSE;
WORD format;
size = GetFontData(hdc, MS_CMAP_TAG, 0, NULL, 0);
ok(size != GDI_ERROR, "no cmap table found\n");
if(size == GDI_ERROR) return FALSE;
header = HeapAlloc(GetProcessHeap(), 0, size);
ret = GetFontData(hdc, MS_CMAP_TAG, 0, header, size);
ok(ret == size, "GetFontData should return %u not %u\n", size, ret);
ok(GET_BE_WORD(header->version) == 0, "got cmap version %d\n", GET_BE_WORD(header->version));
cmap = get_cmap(header, 3, 1);
if(cmap)
*cmap_type = cmap_ms_unicode;
else
{
cmap = get_cmap(header, 3, 0);
if(cmap) *cmap_type = cmap_ms_symbol;
}
if(!cmap)
{
*cmap_type = cmap_none;
goto end;
}
format = GET_BE_WORD(*(WORD *)cmap);
switch(format)
{
case 0:
r = get_first_last_from_cmap0(cmap, first, last);
break;
case 4:
r = get_first_last_from_cmap4(cmap, first, last, size);
break;
default:
trace("unhandled cmap format %d\n", format);
break;
}
end:
HeapFree(GetProcessHeap(), 0, header);
return r;
}
#define TT_PLATFORM_MICROSOFT 3
#define TT_MS_ID_SYMBOL_CS 0
#define TT_MS_ID_UNICODE_CS 1
#define TT_MS_LANGID_ENGLISH_UNITED_STATES 0x0409
#define TT_NAME_ID_FONT_FAMILY 1
#define TT_NAME_ID_FONT_SUBFAMILY 2
#define TT_NAME_ID_UNIQUE_ID 3
#define TT_NAME_ID_FULL_NAME 4
static BOOL get_ttf_nametable_entry(HDC hdc, WORD name_id, WCHAR *out_buf, SIZE_T out_size, LCID language_id)
{
struct sfnt_name_header
{
USHORT format;
USHORT number_of_record;
USHORT storage_offset;
} *header;
struct sfnt_name
{
USHORT platform_id;
USHORT encoding_id;
USHORT language_id;
USHORT name_id;
USHORT length;
USHORT offset;
} *entry;
BOOL r = FALSE;
LONG size, offset, length;
LONG c, ret;
WCHAR *name;
BYTE *data;
USHORT i;
size = GetFontData(hdc, MS_NAME_TAG, 0, NULL, 0);
ok(size != GDI_ERROR, "no name table found\n");
if(size == GDI_ERROR) return FALSE;
data = HeapAlloc(GetProcessHeap(), 0, size);
ret = GetFontData(hdc, MS_NAME_TAG, 0, data, size);
ok(ret == size, "GetFontData should return %u not %u\n", size, ret);
header = (void *)data;
header->format = GET_BE_WORD(header->format);
header->number_of_record = GET_BE_WORD(header->number_of_record);
header->storage_offset = GET_BE_WORD(header->storage_offset);
if (header->format != 0)
{
trace("got format %u\n", header->format);
goto out;
}
if (header->number_of_record == 0 || sizeof(*header) + header->number_of_record * sizeof(*entry) > size)
{
trace("number records out of range: %d\n", header->number_of_record);
goto out;
}
if (header->storage_offset >= size)
{
trace("storage_offset %u > size %u\n", header->storage_offset, size);
goto out;
}
entry = (void *)&header[1];
for (i = 0; i < header->number_of_record; i++)
{
if (GET_BE_WORD(entry[i].platform_id) != TT_PLATFORM_MICROSOFT ||
(GET_BE_WORD(entry[i].encoding_id) != TT_MS_ID_UNICODE_CS && GET_BE_WORD(entry[i].encoding_id) != TT_MS_ID_SYMBOL_CS) ||
GET_BE_WORD(entry[i].language_id) != language_id ||
GET_BE_WORD(entry[i].name_id) != name_id)
{
continue;
}
offset = header->storage_offset + GET_BE_WORD(entry[i].offset);
length = GET_BE_WORD(entry[i].length);
if (offset + length > size)
{
trace("entry %d is out of range\n", i);
break;
}
if (length >= out_size)
{
trace("buffer too small for entry %d\n", i);
break;
}
name = (WCHAR *)(data + offset);
for (c = 0; c < length / 2; c++)
out_buf[c] = GET_BE_WORD(name[c]);
out_buf[c] = 0;
r = TRUE;
break;
}
out:
HeapFree(GetProcessHeap(), 0, data);
return r;
}
static void test_text_metrics(const LOGFONTA *lf, const NEWTEXTMETRICA *ntm)
{
HDC hdc;
HFONT hfont, hfont_old;
TEXTMETRICA tmA;
TT_OS2_V2 tt_os2;
LONG size, ret;
const char *font_name = lf->lfFaceName;
DWORD cmap_first = 0, cmap_last = 0;
UINT ascent, descent, cell_height;
cmap_type cmap_type;
BOOL sys_lang_non_english;
sys_lang_non_english = PRIMARYLANGID(GetSystemDefaultLangID()) != LANG_ENGLISH;
hdc = GetDC(0);
SetLastError(0xdeadbeef);
hfont = CreateFontIndirectA(lf);
ok(hfont != 0, "CreateFontIndirect error %u\n", GetLastError());
hfont_old = SelectObject(hdc, hfont);
size = GetFontData(hdc, MS_OS2_TAG, 0, NULL, 0);
if (size == GDI_ERROR)
{
trace("OS/2 chunk was not found\n");
goto end_of_test;
}
if (size > sizeof(tt_os2))
{
trace("got too large OS/2 chunk of size %u\n", size);
size = sizeof(tt_os2);
}
memset(&tt_os2, 0, sizeof(tt_os2));
ret = GetFontData(hdc, MS_OS2_TAG, 0, &tt_os2, size);
ok(ret == size, "GetFontData should return %u not %u\n", size, ret);
SetLastError(0xdeadbeef);
ret = GetTextMetricsA(hdc, &tmA);
ok(ret, "GetTextMetricsA error %u\n", GetLastError());
if(!get_first_last_from_cmap(hdc, &cmap_first, &cmap_last, &cmap_type))
{
skip("%s is not a Windows font, OS/2 metrics may be invalid.\n",font_name);
}
else
{
USHORT expect_first_A, expect_last_A, expect_break_A, expect_default_A;
USHORT expect_first_W, expect_last_W, expect_break_W, expect_default_W;
UINT os2_first_char, os2_last_char, default_char, break_char;
USHORT version;
TEXTMETRICW tmW;
ascent = GET_BE_WORD(tt_os2.usWinAscent);
descent = GET_BE_WORD(tt_os2.usWinDescent);
cell_height = ascent + descent;
ok(ntm->ntmCellHeight == cell_height, "%s: ntmCellHeight %u != %u, os2.usWinAscent/os2.usWinDescent %u/%u\n",
font_name, ntm->ntmCellHeight, cell_height, ascent, descent);
version = GET_BE_WORD(tt_os2.version);
os2_first_char = GET_BE_WORD(tt_os2.usFirstCharIndex);
os2_last_char = GET_BE_WORD(tt_os2.usLastCharIndex);
default_char = GET_BE_WORD(tt_os2.usDefaultChar);
break_char = GET_BE_WORD(tt_os2.usBreakChar);
trace("font %s charset %u: %x-%x (%x-%x) default %x break %x OS/2 version %u vendor %4.4s\n",
font_name, lf->lfCharSet, os2_first_char, os2_last_char, cmap_first, cmap_last,
default_char, break_char, version, (LPCSTR)&tt_os2.achVendID);
if (cmap_type == cmap_ms_symbol || (cmap_first >= 0xf000 && cmap_first < 0xf100))
{
expect_first_W = 0;
switch(GetACP())
{
case 1257: /* Baltic */
expect_last_W = 0xf8fd;
break;
default:
expect_last_W = 0xf0ff;
}
expect_break_W = 0x20;
expect_default_W = expect_break_W - 1;
expect_first_A = 0x1e;
expect_last_A = min(os2_last_char - os2_first_char + 0x20, 0xff);
}
else
{
expect_first_W = cmap_first;
expect_last_W = min(cmap_last, os2_last_char);
if(os2_first_char <= 1)
expect_break_W = os2_first_char + 2;
else if(os2_first_char > 0xff)
expect_break_W = 0x20;
else
expect_break_W = os2_first_char;
expect_default_W = expect_break_W - 1;
expect_first_A = expect_default_W - 1;
expect_last_A = min(expect_last_W, 0xff);
}
expect_break_A = expect_break_W;
expect_default_A = expect_default_W;
/* Wine currently uses SYMBOL_CHARSET to identify whether the ANSI metrics need special handling */
if(cmap_type != cmap_ms_symbol && tmA.tmCharSet == SYMBOL_CHARSET && expect_first_A != 0x1e)
todo_wine ok(tmA.tmFirstChar == expect_first_A ||
tmA.tmFirstChar == expect_first_A + 1 /* win9x */,
"A: tmFirstChar for %s got %02x expected %02x\n", font_name, tmA.tmFirstChar, expect_first_A);
else
ok(tmA.tmFirstChar == expect_first_A ||
tmA.tmFirstChar == expect_first_A + 1 /* win9x */,
"A: tmFirstChar for %s got %02x expected %02x\n", font_name, tmA.tmFirstChar, expect_first_A);
if (pGdiGetCodePage == NULL || ! IsDBCSLeadByteEx(pGdiGetCodePage(hdc), tmA.tmLastChar))
ok(tmA.tmLastChar == expect_last_A ||
tmA.tmLastChar == 0xff /* win9x */,
"A: tmLastChar for %s got %02x expected %02x\n", font_name, tmA.tmLastChar, expect_last_A);
else
skip("tmLastChar is DBCS lead byte\n");
ok(tmA.tmBreakChar == expect_break_A, "A: tmBreakChar for %s got %02x expected %02x\n",
font_name, tmA.tmBreakChar, expect_break_A);
ok(tmA.tmDefaultChar == expect_default_A || broken(sys_lang_non_english),
"A: tmDefaultChar for %s got %02x expected %02x\n",
font_name, tmA.tmDefaultChar, expect_default_A);
SetLastError(0xdeadbeef);
ret = GetTextMetricsW(hdc, &tmW);
ok(ret || GetLastError() == ERROR_CALL_NOT_IMPLEMENTED,
"GetTextMetricsW error %u\n", GetLastError());
if (ret)
{
/* Wine uses the os2 first char */
if(cmap_first != os2_first_char && cmap_type != cmap_ms_symbol)
todo_wine ok(tmW.tmFirstChar == expect_first_W, "W: tmFirstChar for %s got %02x expected %02x\n",
font_name, tmW.tmFirstChar, expect_first_W);
else
ok(tmW.tmFirstChar == expect_first_W, "W: tmFirstChar for %s got %02x expected %02x\n",
font_name, tmW.tmFirstChar, expect_first_W);
/* Wine uses the os2 last char */
if(expect_last_W != os2_last_char && cmap_type != cmap_ms_symbol)
todo_wine ok(tmW.tmLastChar == expect_last_W, "W: tmLastChar for %s got %02x expected %02x\n",
font_name, tmW.tmLastChar, expect_last_W);
else
ok(tmW.tmLastChar == expect_last_W, "W: tmLastChar for %s got %02x expected %02x\n",
font_name, tmW.tmLastChar, expect_last_W);
ok(tmW.tmBreakChar == expect_break_W, "W: tmBreakChar for %s got %02x expected %02x\n",
font_name, tmW.tmBreakChar, expect_break_W);
ok(tmW.tmDefaultChar == expect_default_W || broken(sys_lang_non_english),
"W: tmDefaultChar for %s got %02x expected %02x\n",
font_name, tmW.tmDefaultChar, expect_default_W);
/* Test the aspect ratio while we have tmW */
ret = GetDeviceCaps(hdc, LOGPIXELSX);
ok(tmW.tmDigitizedAspectX == ret, "W: tmDigitizedAspectX %u != %u\n",
tmW.tmDigitizedAspectX, ret);
ret = GetDeviceCaps(hdc, LOGPIXELSY);
ok(tmW.tmDigitizedAspectX == ret, "W: tmDigitizedAspectY %u != %u\n",
tmW.tmDigitizedAspectX, ret);
}
}
/* test FF_ values */
switch(tt_os2.panose.bFamilyType)
{
case PAN_ANY:
case PAN_NO_FIT:
case PAN_FAMILY_TEXT_DISPLAY:
case PAN_FAMILY_PICTORIAL:
default:
if((tmA.tmPitchAndFamily & 1) == 0 || /* fixed */
tt_os2.panose.bProportion == PAN_PROP_MONOSPACED)
{
expect_ff(&tmA, &tt_os2, FF_MODERN, font_name);
break;
}
switch(tt_os2.panose.bSerifStyle)
{
case PAN_ANY:
case PAN_NO_FIT:
default:
expect_ff(&tmA, &tt_os2, FF_DONTCARE, font_name);
break;
case PAN_SERIF_COVE:
case PAN_SERIF_OBTUSE_COVE:
case PAN_SERIF_SQUARE_COVE:
case PAN_SERIF_OBTUSE_SQUARE_COVE:
case PAN_SERIF_SQUARE:
case PAN_SERIF_THIN:
case PAN_SERIF_BONE:
case PAN_SERIF_EXAGGERATED:
case PAN_SERIF_TRIANGLE:
expect_ff(&tmA, &tt_os2, FF_ROMAN, font_name);
break;
case PAN_SERIF_NORMAL_SANS:
case PAN_SERIF_OBTUSE_SANS:
case PAN_SERIF_PERP_SANS:
case PAN_SERIF_FLARED:
case PAN_SERIF_ROUNDED:
expect_ff(&tmA, &tt_os2, FF_SWISS, font_name);
break;
}
break;
case PAN_FAMILY_SCRIPT:
expect_ff(&tmA, &tt_os2, FF_SCRIPT, font_name);
break;
case PAN_FAMILY_DECORATIVE:
expect_ff(&tmA, &tt_os2, FF_DECORATIVE, font_name);
break;
}
test_negative_width(hdc, lf);
end_of_test:
SelectObject(hdc, hfont_old);
DeleteObject(hfont);
ReleaseDC(0, hdc);
}
static INT CALLBACK enum_truetype_font_proc(const LOGFONTA *lf, const TEXTMETRICA *ntm, DWORD type, LPARAM lParam)
{
INT *enumed = (INT *)lParam;
if (type == TRUETYPE_FONTTYPE)
{
(*enumed)++;
test_text_metrics(lf, (const NEWTEXTMETRICA *)ntm);
}
return 1;
}
static void test_GetTextMetrics(void)
{
LOGFONTA lf;
HDC hdc;
INT enumed;
/* Report only once */
if(!pGetGlyphIndicesA)
win_skip("GetGlyphIndicesA is unavailable, negative width will not be checked\n");
hdc = GetDC(0);
memset(&lf, 0, sizeof(lf));
lf.lfCharSet = DEFAULT_CHARSET;
enumed = 0;
EnumFontFamiliesExA(hdc, &lf, enum_truetype_font_proc, (LPARAM)&enumed, 0);
trace("Tested metrics of %d truetype fonts\n", enumed);
ReleaseDC(0, hdc);
}
static void test_nonexistent_font(void)
{
static const struct
{
const char *name;
int charset;
} font_subst[] =
{
{ "Times New Roman Baltic", 186 },
{ "Times New Roman CE", 238 },
{ "Times New Roman CYR", 204 },
{ "Times New Roman Greek", 161 },
{ "Times New Roman TUR", 162 }
};
LOGFONTA lf;
HDC hdc;
HFONT hfont;
CHARSETINFO csi;
INT cs, expected_cs, i;
char buf[LF_FACESIZE];
if (!is_truetype_font_installed("Arial") ||
!is_truetype_font_installed("Times New Roman"))
{
skip("Arial or Times New Roman not installed\n");
return;
}
expected_cs = GetACP();
if (!TranslateCharsetInfo(ULongToPtr(expected_cs), &csi, TCI_SRCCODEPAGE))
{
skip("TranslateCharsetInfo failed for code page %d\n", expected_cs);
return;
}
expected_cs = csi.ciCharset;
trace("ACP %d -> charset %d\n", GetACP(), expected_cs);
hdc = GetDC(0);
memset(&lf, 0, sizeof(lf));
lf.lfHeight = 100;
lf.lfWeight = FW_REGULAR;
lf.lfCharSet = ANSI_CHARSET;
lf.lfPitchAndFamily = FF_SWISS;
strcpy(lf.lfFaceName, "Nonexistent font");
hfont = CreateFontIndirectA(&lf);
hfont = SelectObject(hdc, hfont);
GetTextFaceA(hdc, sizeof(buf), buf);
ok(!lstrcmpiA(buf, "Arial"), "Got %s\n", buf);
cs = GetTextCharset(hdc);
ok(cs == ANSI_CHARSET, "expected ANSI_CHARSET, got %d\n", cs);
DeleteObject(SelectObject(hdc, hfont));
memset(&lf, 0, sizeof(lf));
lf.lfHeight = -13;
lf.lfWeight = FW_DONTCARE;
strcpy(lf.lfFaceName, "Nonexistent font");
hfont = CreateFontIndirectA(&lf);
hfont = SelectObject(hdc, hfont);
GetTextFaceA(hdc, sizeof(buf), buf);
todo_wine /* Wine uses Arial for all substitutions */
ok(!lstrcmpiA(buf, "Nonexistent font") /* XP, Vista */ ||
!lstrcmpiA(buf, "MS Serif") || /* Win9x */
!lstrcmpiA(buf, "MS Sans Serif"), /* win2k3 */
"Got %s\n", buf);
cs = GetTextCharset(hdc);
ok(cs == expected_cs || cs == ANSI_CHARSET, "expected %d, got %d\n", expected_cs, cs);
DeleteObject(SelectObject(hdc, hfont));
memset(&lf, 0, sizeof(lf));
lf.lfHeight = -13;
lf.lfWeight = FW_REGULAR;
strcpy(lf.lfFaceName, "Nonexistent font");
hfont = CreateFontIndirectA(&lf);
hfont = SelectObject(hdc, hfont);
GetTextFaceA(hdc, sizeof(buf), buf);
ok(!lstrcmpiA(buf, "Arial") /* XP, Vista */ ||
!lstrcmpiA(buf, "Times New Roman") /* Win9x */, "Got %s\n", buf);
cs = GetTextCharset(hdc);
ok(cs == ANSI_CHARSET, "expected ANSI_CHARSET, got %d\n", cs);
DeleteObject(SelectObject(hdc, hfont));
memset(&lf, 0, sizeof(lf));
lf.lfHeight = -13;
lf.lfWeight = FW_DONTCARE;
strcpy(lf.lfFaceName, "Times New Roman");
hfont = CreateFontIndirectA(&lf);
hfont = SelectObject(hdc, hfont);
GetTextFaceA(hdc, sizeof(buf), buf);
ok(!lstrcmpiA(buf, "Times New Roman"), "Got %s\n", buf);
cs = GetTextCharset(hdc);
ok(cs == ANSI_CHARSET, "expected ANSI_CHARSET, got %d\n", cs);
DeleteObject(SelectObject(hdc, hfont));
for (i = 0; i < sizeof(font_subst)/sizeof(font_subst[0]); i++)
{
memset(&lf, 0, sizeof(lf));
lf.lfHeight = -13;
lf.lfWeight = FW_REGULAR;
strcpy(lf.lfFaceName, font_subst[i].name);
hfont = CreateFontIndirectA(&lf);
hfont = SelectObject(hdc, hfont);
cs = GetTextCharset(hdc);
if (font_subst[i].charset == expected_cs)
{
ok(cs == expected_cs, "expected %d, got %d for font %s\n", expected_cs, cs, font_subst[i].name);
GetTextFaceA(hdc, sizeof(buf), buf);
ok(!lstrcmpiA(buf, font_subst[i].name), "expected %s, got %s\n", font_subst[i].name, buf);
}
else
{
ok(cs == ANSI_CHARSET, "expected ANSI_CHARSET, got %d for font %s\n", cs, font_subst[i].name);
GetTextFaceA(hdc, sizeof(buf), buf);
ok(!lstrcmpiA(buf, "Arial") /* XP, Vista */ ||
!lstrcmpiA(buf, "Times New Roman") /* Win9x */, "got %s for font %s\n", buf, font_subst[i].name);
}
DeleteObject(SelectObject(hdc, hfont));
memset(&lf, 0, sizeof(lf));
lf.lfHeight = -13;
lf.lfWeight = FW_DONTCARE;
strcpy(lf.lfFaceName, font_subst[i].name);
hfont = CreateFontIndirectA(&lf);
hfont = SelectObject(hdc, hfont);
GetTextFaceA(hdc, sizeof(buf), buf);
ok(!lstrcmpiA(buf, "Arial") /* Wine */ ||
!lstrcmpiA(buf, font_subst[i].name) /* XP, Vista */ ||
!lstrcmpiA(buf, "MS Serif") /* Win9x */ ||
!lstrcmpiA(buf, "MS Sans Serif"), /* win2k3 */
"got %s for font %s\n", buf, font_subst[i].name);
cs = GetTextCharset(hdc);
ok(cs == expected_cs || cs == ANSI_CHARSET, "expected %d, got %d for font %s\n", expected_cs, cs, font_subst[i].name);
DeleteObject(SelectObject(hdc, hfont));
}
ReleaseDC(0, hdc);
}
static void test_GdiRealizationInfo(void)
{
HDC hdc;
DWORD info[4];
BOOL r;
HFONT hfont, hfont_old;
LOGFONTA lf;
if(!pGdiRealizationInfo)
{
win_skip("GdiRealizationInfo not available\n");
return;
}
hdc = GetDC(0);
memset(info, 0xcc, sizeof(info));
r = pGdiRealizationInfo(hdc, info);
ok(r != 0, "ret 0\n");
ok((info[0] & 0xf) == 1, "info[0] = %x for the system font\n", info[0]);
ok(info[3] == 0xcccccccc, "structure longer than 3 dwords\n");
if (!is_truetype_font_installed("Arial"))
{
skip("skipping GdiRealizationInfo with truetype font\n");
goto end;
}
memset(&lf, 0, sizeof(lf));
strcpy(lf.lfFaceName, "Arial");
lf.lfHeight = 20;
lf.lfWeight = FW_NORMAL;
hfont = CreateFontIndirectA(&lf);
hfont_old = SelectObject(hdc, hfont);
memset(info, 0xcc, sizeof(info));
r = pGdiRealizationInfo(hdc, info);
ok(r != 0, "ret 0\n");
ok((info[0] & 0xf) == 3, "info[0] = %x for arial\n", info[0]);
ok(info[3] == 0xcccccccc, "structure longer than 3 dwords\n");
DeleteObject(SelectObject(hdc, hfont_old));
end:
ReleaseDC(0, hdc);
}
/* Tests on XP SP2 show that the ANSI version of GetTextFace does NOT include
the nul in the count of characters copied when the face name buffer is not
NULL, whereas it does if the buffer is NULL. Further, the Unicode version
always includes it. */
static void test_GetTextFace(void)
{
static const char faceA[] = "Tahoma";
static const WCHAR faceW[] = {'T','a','h','o','m','a', 0};
LOGFONTA fA = {0};
LOGFONTW fW = {0};
char bufA[LF_FACESIZE];
WCHAR bufW[LF_FACESIZE];
HFONT f, g;
HDC dc;
int n;
if(!is_font_installed("Tahoma"))
{
skip("Tahoma is not installed so skipping this test\n");
return;
}
/* 'A' case. */
memcpy(fA.lfFaceName, faceA, sizeof faceA);
f = CreateFontIndirectA(&fA);
ok(f != NULL, "CreateFontIndirectA failed\n");
dc = GetDC(NULL);
g = SelectObject(dc, f);
n = GetTextFaceA(dc, sizeof bufA, bufA);
ok(n == sizeof faceA - 1, "GetTextFaceA returned %d\n", n);
ok(lstrcmpA(faceA, bufA) == 0, "GetTextFaceA\n");
/* Play with the count arg. */
bufA[0] = 'x';
n = GetTextFaceA(dc, 0, bufA);
ok(n == 0, "GetTextFaceA returned %d\n", n);
ok(bufA[0] == 'x', "GetTextFaceA buf[0] == %d\n", bufA[0]);
bufA[0] = 'x';
n = GetTextFaceA(dc, 1, bufA);
ok(n == 0, "GetTextFaceA returned %d\n", n);
ok(bufA[0] == '\0', "GetTextFaceA buf[0] == %d\n", bufA[0]);
bufA[0] = 'x'; bufA[1] = 'y';
n = GetTextFaceA(dc, 2, bufA);
ok(n == 1, "GetTextFaceA returned %d\n", n);
ok(bufA[0] == faceA[0] && bufA[1] == '\0', "GetTextFaceA didn't copy\n");
n = GetTextFaceA(dc, 0, NULL);
ok(n == sizeof faceA ||
broken(n == 0), /* win98, winMe */
"GetTextFaceA returned %d\n", n);
DeleteObject(SelectObject(dc, g));
ReleaseDC(NULL, dc);
/* 'W' case. */
memcpy(fW.lfFaceName, faceW, sizeof faceW);
SetLastError(0xdeadbeef);
f = CreateFontIndirectW(&fW);
if (!f && GetLastError() == ERROR_CALL_NOT_IMPLEMENTED)
{
win_skip("CreateFontIndirectW is not implemented\n");
return;
}
ok(f != NULL, "CreateFontIndirectW failed\n");
dc = GetDC(NULL);
g = SelectObject(dc, f);
n = GetTextFaceW(dc, sizeof bufW / sizeof bufW[0], bufW);
ok(n == sizeof faceW / sizeof faceW[0], "GetTextFaceW returned %d\n", n);
ok(lstrcmpW(faceW, bufW) == 0, "GetTextFaceW\n");
/* Play with the count arg. */
bufW[0] = 'x';
n = GetTextFaceW(dc, 0, bufW);
ok(n == 0, "GetTextFaceW returned %d\n", n);
ok(bufW[0] == 'x', "GetTextFaceW buf[0] == %d\n", bufW[0]);
bufW[0] = 'x';
n = GetTextFaceW(dc, 1, bufW);
ok(n == 1, "GetTextFaceW returned %d\n", n);
ok(bufW[0] == '\0', "GetTextFaceW buf[0] == %d\n", bufW[0]);
bufW[0] = 'x'; bufW[1] = 'y';
n = GetTextFaceW(dc, 2, bufW);
ok(n == 2, "GetTextFaceW returned %d\n", n);
ok(bufW[0] == faceW[0] && bufW[1] == '\0', "GetTextFaceW didn't copy\n");
n = GetTextFaceW(dc, 0, NULL);
ok(n == sizeof faceW / sizeof faceW[0], "GetTextFaceW returned %d\n", n);
DeleteObject(SelectObject(dc, g));
ReleaseDC(NULL, dc);
}
static void test_orientation(void)
{
static const char test_str[11] = "Test String";
HDC hdc;
LOGFONTA lf;
HFONT hfont, old_hfont;
SIZE size;
if (!is_truetype_font_installed("Arial"))
{
skip("Arial is not installed\n");
return;
}
hdc = CreateCompatibleDC(0);
memset(&lf, 0, sizeof(lf));
lstrcpyA(lf.lfFaceName, "Arial");
lf.lfHeight = 72;
lf.lfOrientation = lf.lfEscapement = 900;
hfont = create_font("orientation", &lf);
old_hfont = SelectObject(hdc, hfont);
ok(GetTextExtentExPointA(hdc, test_str, sizeof(test_str), 32767, NULL, NULL, &size), "GetTextExtentExPointA failed\n");
ok(near_match(311, size.cx), "cx should be about 311, got %d\n", size.cx);
ok(near_match(75, size.cy), "cy should be about 75, got %d\n", size.cy);
SelectObject(hdc, old_hfont);
DeleteObject(hfont);
DeleteDC(hdc);
}
static void test_oemcharset(void)
{
HDC hdc;
LOGFONTA lf, clf;
HFONT hfont, old_hfont;
int charset;
hdc = CreateCompatibleDC(0);
ZeroMemory(&lf, sizeof(lf));
lf.lfHeight = 12;
lf.lfCharSet = OEM_CHARSET;
lf.lfPitchAndFamily = FIXED_PITCH | FF_MODERN;
lstrcpyA(lf.lfFaceName, "Terminal");
hfont = CreateFontIndirectA(&lf);
old_hfont = SelectObject(hdc, hfont);
charset = GetTextCharset(hdc);
todo_wine
ok(charset == OEM_CHARSET, "expected %d charset, got %d\n", OEM_CHARSET, charset);
hfont = SelectObject(hdc, old_hfont);
GetObjectA(hfont, sizeof(clf), &clf);
ok(!lstrcmpA(clf.lfFaceName, lf.lfFaceName), "expected %s face name, got %s\n", lf.lfFaceName, clf.lfFaceName);
ok(clf.lfPitchAndFamily == lf.lfPitchAndFamily, "expected %x family, got %x\n", lf.lfPitchAndFamily, clf.lfPitchAndFamily);
ok(clf.lfCharSet == lf.lfCharSet, "expected %d charset, got %d\n", lf.lfCharSet, clf.lfCharSet);
ok(clf.lfHeight == lf.lfHeight, "expected %d height, got %d\n", lf.lfHeight, clf.lfHeight);
DeleteObject(hfont);
DeleteDC(hdc);
}
static int CALLBACK create_fixed_pitch_font_proc(const LOGFONTA *lpelfe,
const TEXTMETRICA *lpntme,
DWORD FontType, LPARAM lParam)
{
const NEWTEXTMETRICEXA *lpntmex = (const NEWTEXTMETRICEXA *)lpntme;
CHARSETINFO csi;
LOGFONTA lf = *lpelfe;
HFONT hfont;
DWORD found_subset;
/* skip bitmap, proportional or vertical font */
if ((FontType & TRUETYPE_FONTTYPE) == 0 ||
(lf.lfPitchAndFamily & 0xf) != FIXED_PITCH ||
lf.lfFaceName[0] == '@')
return 1;
/* skip linked font */
if (!TranslateCharsetInfo((DWORD*)(INT_PTR)lpelfe->lfCharSet, &csi, TCI_SRCCHARSET) ||
(lpntmex->ntmFontSig.fsCsb[0] & csi.fs.fsCsb[0]) == 0)
return 1;
/* skip linked font, like SimSun-ExtB */
switch (lpelfe->lfCharSet) {
case SHIFTJIS_CHARSET:
found_subset = lpntmex->ntmFontSig.fsUsb[1] & (1 << 17); /* Hiragana */
break;
case GB2312_CHARSET:
case CHINESEBIG5_CHARSET:
found_subset = lpntmex->ntmFontSig.fsUsb[1] & (1 << 16); /* CJK Symbols And Punctuation */
break;
case HANGEUL_CHARSET:
found_subset = lpntmex->ntmFontSig.fsUsb[1] & (1 << 24); /* Hangul Syllables */
break;
default:
found_subset = lpntmex->ntmFontSig.fsUsb[0] & (1 << 0); /* Basic Latin */
break;
}
if (!found_subset)
return 1;
/* test with an odd height */
lf.lfHeight = -19;
lf.lfWidth = 0;
hfont = CreateFontIndirectA(&lf);
if (hfont)
{
*(HFONT *)lParam = hfont;
return 0;
}
return 1;
}
static void test_GetGlyphOutline(void)
{
HDC hdc;
GLYPHMETRICS gm, gm2;
LOGFONTA lf;
HFONT hfont, old_hfont;
INT ret, ret2;
const UINT fmt[] = { GGO_METRICS, GGO_BITMAP, GGO_GRAY2_BITMAP,
GGO_GRAY4_BITMAP, GGO_GRAY8_BITMAP };
static const struct
{
UINT cs;
UINT a;
UINT w;
} c[] =
{
{ANSI_CHARSET, 0x30, 0x30},
{SHIFTJIS_CHARSET, 0x82a0, 0x3042},
{HANGEUL_CHARSET, 0x8141, 0xac02},
{GB2312_CHARSET, 0x8141, 0x4e04},
{CHINESEBIG5_CHARSET, 0xa142, 0x3001}
};
UINT i;
if (!is_truetype_font_installed("Tahoma"))
{
skip("Tahoma is not installed\n");
return;
}
hdc = CreateCompatibleDC(0);
memset(&lf, 0, sizeof(lf));
lf.lfHeight = 72;
lstrcpyA(lf.lfFaceName, "Tahoma");
SetLastError(0xdeadbeef);
hfont = CreateFontIndirectA(&lf);
ok(hfont != 0, "CreateFontIndirectA error %u\n", GetLastError());
old_hfont = SelectObject(hdc, hfont);
memset(&gm, 0, sizeof(gm));
SetLastError(0xdeadbeef);
ret = GetGlyphOutlineA(hdc, 'A', GGO_METRICS, &gm, 0, NULL, &mat);
ok(ret != GDI_ERROR, "GetGlyphOutlineA error %u\n", GetLastError());
memset(&gm, 0, sizeof(gm));
SetLastError(0xdeadbeef);
ret = GetGlyphOutlineA(hdc, 'A', GGO_METRICS, &gm, 0, NULL, NULL);
ok(ret == GDI_ERROR, "GetGlyphOutlineA should fail\n");
ok(GetLastError() == 0xdeadbeef ||
GetLastError() == ERROR_INVALID_PARAMETER, /* win98, winMe */
"expected 0xdeadbeef, got %u\n", GetLastError());
memset(&gm, 0, sizeof(gm));
SetLastError(0xdeadbeef);
ret = GetGlyphOutlineW(hdc, 'A', GGO_METRICS, &gm, 0, NULL, &mat);
if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
ok(ret != GDI_ERROR, "GetGlyphOutlineW error %u\n", GetLastError());
memset(&gm, 0, sizeof(gm));
SetLastError(0xdeadbeef);
ret = GetGlyphOutlineW(hdc, 'A', GGO_METRICS, &gm, 0, NULL, NULL);
if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
{
ok(ret == GDI_ERROR, "GetGlyphOutlineW should fail\n");
ok(GetLastError() == 0xdeadbeef, "expected 0xdeadbeef, got %u\n", GetLastError());
}
/* test for needed buffer size request on space char */
memset(&gm, 0, sizeof(gm));
SetLastError(0xdeadbeef);
ret = GetGlyphOutlineW(hdc, ' ', GGO_NATIVE, &gm, 0, NULL, &mat);
if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
ok(ret == 0, "GetGlyphOutlineW should return 0 buffer size for space char\n");
/* requesting buffer size for space char + error */
memset(&gm, 0, sizeof(gm));
SetLastError(0xdeadbeef);
ret = GetGlyphOutlineW(0, ' ', GGO_NATIVE, &gm, 0, NULL, NULL);
if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
{
ok(ret == GDI_ERROR, "GetGlyphOutlineW should return GDI_ERROR\n");
ok(GetLastError() == 0xdeadbeef, "expected 0xdeadbeef, got %u\n", GetLastError());
}
for (i = 0; i < sizeof(fmt) / sizeof(fmt[0]); ++i)
{
DWORD dummy;
memset(&gm, 0xab, sizeof(gm));
SetLastError(0xdeadbeef);
ret = GetGlyphOutlineW(hdc, ' ', fmt[i], &gm, 0, NULL, &mat);
if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
{
if (fmt[i] == GGO_METRICS)
ok(ret != GDI_ERROR, "%2d:GetGlyphOutlineW should succeed, got %d\n", fmt[i], ret);
else
ok(ret == 0, "%2d:GetGlyphOutlineW should return 0, got %d\n", fmt[i], ret);
ok(gm.gmBlackBoxX == 1, "%2d:expected 1, got %u\n", fmt[i], gm.gmBlackBoxX);
ok(gm.gmBlackBoxY == 1, "%2d:expected 1, got %u\n", fmt[i], gm.gmBlackBoxY);
}
memset(&gm, 0xab, sizeof(gm));
SetLastError(0xdeadbeef);
ret = GetGlyphOutlineW(hdc, ' ', fmt[i], &gm, 0, &dummy, &mat);
if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
{
if (fmt[i] == GGO_METRICS)
ok(ret != GDI_ERROR, "%2d:GetGlyphOutlineW should succeed, got %d\n", fmt[i], ret);
else
ok(ret == 0, "%2d:GetGlyphOutlineW should return 0, got %d\n", fmt[i], ret);
ok(gm.gmBlackBoxX == 1, "%2d:expected 1, got %u\n", fmt[i], gm.gmBlackBoxX);
ok(gm.gmBlackBoxY == 1, "%2d:expected 1, got %u\n", fmt[i], gm.gmBlackBoxY);
}
memset(&gm, 0xab, sizeof(gm));
SetLastError(0xdeadbeef);
ret = GetGlyphOutlineW(hdc, ' ', fmt[i], &gm, sizeof(dummy), NULL, &mat);
if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
{
if (fmt[i] == GGO_METRICS)
ok(ret != GDI_ERROR, "%2d:GetGlyphOutlineW should succeed, got %d\n", fmt[i], ret);
else
ok(ret == 0, "%2d:GetGlyphOutlineW should return 0, got %d\n", fmt[i], ret);
ok(gm.gmBlackBoxX == 1, "%2d:expected 1, got %u\n", fmt[i], gm.gmBlackBoxX);
ok(gm.gmBlackBoxY == 1, "%2d:expected 1, got %u\n", fmt[i], gm.gmBlackBoxY);
}
memset(&gm, 0xab, sizeof(gm));
SetLastError(0xdeadbeef);
ret = GetGlyphOutlineW(hdc, ' ', fmt[i], &gm, sizeof(dummy), &dummy, &mat);
if (GetLastError() != ERROR_CALL_NOT_IMPLEMENTED)
{
if (fmt[i] == GGO_METRICS) {
ok(ret != GDI_ERROR, "%2d:GetGlyphOutlineW should succeed, got %d\n", fmt[i], ret);
ok(gm.gmBlackBoxX == 1, "%2d:expected 1, got %u\n", fmt[i], gm.gmBlackBoxX);
ok(gm.gmBlackBoxY == 1, "%2d:expected 1, got %u\n", fmt[i], gm.gmBlackBoxY);
}
else
{
ok(ret == GDI_ERROR, "%2d:GetGlyphOutlineW should return GDI_ERROR, got %d\n", fmt[i], ret);
memset(&gm2, 0xab, sizeof(gm2));
ok(memcmp(&gm, &gm2, sizeof(GLYPHMETRICS)) == 0,
"%2d:GLYPHMETRICS shouldn't be touched on error\n", fmt[i]);
}
}
}
SelectObject(hdc, old_hfont);
DeleteObject(hfont);
for (i = 0; i < sizeof c / sizeof c[0]; ++i)
{
static const MAT2 rotate_mat = {{0, 0}, {0, -1}, {0, 1}, {0, 0}};
TEXTMETRICA tm;
lf.lfFaceName[0] = '\0';
lf.lfCharSet = c[i].cs;
lf.lfPitchAndFamily = 0;
if (EnumFontFamiliesExA(hdc, &lf, create_font_proc, (LPARAM)&hfont, 0))
{
skip("TrueType font for charset %u is not installed\n", c[i].cs);
continue;
}
old_hfont = SelectObject(hdc, hfont);
/* expected to ignore superfluous bytes (sigle-byte character) */
ret = GetGlyphOutlineA(hdc, 0x8041, GGO_BITMAP, &gm, 0, NULL, &mat);
ret2 = GetGlyphOutlineA(hdc, 0x41, GGO_BITMAP, &gm2, 0, NULL, &mat);
ok(ret == ret2 && memcmp(&gm, &gm2, sizeof gm) == 0, "%d %d\n", ret, ret2);
ret = GetGlyphOutlineA(hdc, 0xcc8041, GGO_BITMAP, &gm, 0, NULL, &mat);
ok(ret == ret2 && memcmp(&gm, &gm2, sizeof gm) == 0,
"Expected to ignore superfluous bytes, got %d %d\n", ret, ret2);
/* expected to ignore superfluous bytes (double-byte character) */
ret = GetGlyphOutlineA(hdc, c[i].a, GGO_BITMAP, &gm, 0, NULL, &mat);
ret2 = GetGlyphOutlineA(hdc, c[i].a | 0xdead0000, GGO_BITMAP, &gm2, 0, NULL, &mat);
ok(ret == ret2 && memcmp(&gm, &gm2, sizeof gm) == 0,
"Expected to ignore superfluous bytes, got %d %d\n", ret, ret2);
/* expected to match wide-char version results */
ret2 = GetGlyphOutlineW(hdc, c[i].w, GGO_BITMAP, &gm2, 0, NULL, &mat);
ok(ret == ret2 && memcmp(&gm, &gm2, sizeof gm) == 0, "%d %d\n", ret, ret2);
if (EnumFontFamiliesExA(hdc, &lf, create_fixed_pitch_font_proc, (LPARAM)&hfont, 0))
{
skip("Fixed-pitch TrueType font for charset %u is not available\n", c[i].cs);
continue;
}
DeleteObject(SelectObject(hdc, hfont));
if (c[i].a <= 0xff)
{
DeleteObject(SelectObject(hdc, old_hfont));
continue;
}
ret = GetObjectA(hfont, sizeof lf, &lf);
ok(ret > 0, "GetObject error %u\n", GetLastError());
ret = GetTextMetricsA(hdc, &tm);
ok(ret, "GetTextMetrics error %u\n", GetLastError());
ret = GetGlyphOutlineA(hdc, c[i].a, GGO_METRICS, &gm2, 0, NULL, &mat);
ok(ret != GDI_ERROR, "GetGlyphOutlineA error %u\n", GetLastError());
trace("Tests with height=%d,avg=%d,full=%d,face=%s,charset=%d\n",
-lf.lfHeight, tm.tmAveCharWidth, gm2.gmCellIncX, lf.lfFaceName, lf.lfCharSet);
ok(gm2.gmCellIncX == tm.tmAveCharWidth * 2 || broken(gm2.gmCellIncX == -lf.lfHeight),
"expected %d, got %d (%s:%d)\n",
tm.tmAveCharWidth * 2, gm2.gmCellIncX, lf.lfFaceName, lf.lfCharSet);
ret = GetGlyphOutlineA(hdc, c[i].a, GGO_METRICS, &gm2, 0, NULL, &rotate_mat);
ok(ret != GDI_ERROR, "GetGlyphOutlineA error %u\n", GetLastError());
ok(gm2.gmCellIncY == -lf.lfHeight,
"expected %d, got %d (%s:%d)\n",
-lf.lfHeight, gm2.gmCellIncY, lf.lfFaceName, lf.lfCharSet);
lf.lfItalic = TRUE;
hfont = CreateFontIndirectA(&lf);
ok(hfont != NULL, "CreateFontIndirect error %u\n", GetLastError());
DeleteObject(SelectObject(hdc, hfont));
ret = GetTextMetricsA(hdc, &tm);
ok(ret, "GetTextMetrics error %u\n", GetLastError());
ret = GetGlyphOutlineA(hdc, c[i].a, GGO_METRICS, &gm2, 0, NULL, &mat);
ok(ret != GDI_ERROR, "GetGlyphOutlineA error %u\n", GetLastError());
ok(gm2.gmCellIncX == tm.tmAveCharWidth * 2 || broken(gm2.gmCellIncX == -lf.lfHeight),
"expected %d, got %d (%s:%d)\n",
tm.tmAveCharWidth * 2, gm2.gmCellIncX, lf.lfFaceName, lf.lfCharSet);
lf.lfItalic = FALSE;
lf.lfEscapement = lf.lfOrientation = 2700;
hfont = CreateFontIndirectA(&lf);
ok(hfont != NULL, "CreateFontIndirect error %u\n", GetLastError());
DeleteObject(SelectObject(hdc, hfont));
ret = GetGlyphOutlineA(hdc, c[i].a, GGO_METRICS, &gm2, 0, NULL, &mat);
ok(ret != GDI_ERROR, "GetGlyphOutlineA error %u\n", GetLastError());
ok(gm2.gmCellIncY == -lf.lfHeight,
"expected %d, got %d (%s:%d)\n",
-lf.lfHeight, gm2.gmCellIncY, lf.lfFaceName, lf.lfCharSet);
hfont = SelectObject(hdc, old_hfont);
DeleteObject(hfont);
}
DeleteDC(hdc);
}
/* bug #9995: there is a limit to the character width that can be specified */
static void test_GetTextMetrics2(const char *fontname, int font_height)
{
HFONT of, hf;
HDC hdc;
TEXTMETRICA tm;
BOOL ret;
int ave_width, height, width, ratio, scale;
if (!is_truetype_font_installed( fontname)) {
skip("%s is not installed\n", fontname);
return;
}
hdc = CreateCompatibleDC(0);
ok( hdc != NULL, "CreateCompatibleDC failed\n");
/* select width = 0 */
hf = CreateFontA(font_height, 0, 0, 0, FW_REGULAR, FALSE, FALSE, FALSE,
DEFAULT_CHARSET, OUT_TT_PRECIS, CLIP_LH_ANGLES,
DEFAULT_QUALITY, VARIABLE_PITCH,
fontname);
ok( hf != NULL, "CreateFontA(%s, %d) failed\n", fontname, font_height);
of = SelectObject( hdc, hf);
ret = GetTextMetricsA( hdc, &tm);
ok(ret, "GetTextMetricsA error %u\n", GetLastError());
height = tm.tmHeight;
ave_width = tm.tmAveCharWidth;
SelectObject( hdc, of);
DeleteObject( hf);
trace("height %d, ave width %d\n", height, ave_width);
for (width = ave_width * 2; /* nothing*/; width += ave_width)
{
hf = CreateFontA(height, width, 0, 0, FW_REGULAR, FALSE, FALSE, FALSE,
DEFAULT_CHARSET, OUT_TT_PRECIS, CLIP_LH_ANGLES,
DEFAULT_QUALITY, VARIABLE_PITCH, fontname);
ok(hf != 0, "CreateFont failed\n");
of = SelectObject(hdc, hf);
ret = GetTextMetricsA(hdc, &tm);
ok(ret, "GetTextMetrics error %u\n", GetLastError());
SelectObject(hdc, of);
DeleteObject(hf);
if (match_off_by_1(tm.tmAveCharWidth, ave_width, FALSE) || width / height > 200)
break;
}
DeleteDC(hdc);
ratio = width / height;
scale = width / ave_width;
trace("max width/height ratio (%d / %d) %d, max width scale (%d / %d) %d\n",
width, height, ratio, width, ave_width, scale);
ok(ratio >= 90 && ratio <= 110, "expected width/height ratio 90-110, got %d\n", ratio);
}
static void test_CreateFontIndirect(void)
{
LOGFONTA lf, getobj_lf;
int ret, i;
HFONT hfont;
char TestName[][16] = {"Arial", "Arial Bold", "Arial Italic", "Arial Baltic"};
memset(&lf, 0, sizeof(lf));
lf.lfCharSet = ANSI_CHARSET;
lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
lf.lfHeight = 16;
lf.lfWidth = 16;
lf.lfQuality = DEFAULT_QUALITY;
lf.lfItalic = FALSE;
lf.lfWeight = FW_DONTCARE;
for (i = 0; i < sizeof(TestName)/sizeof(TestName[0]); i++)
{
lstrcpyA(lf.lfFaceName, TestName[i]);
hfont = CreateFontIndirectA(&lf);
ok(hfont != 0, "CreateFontIndirectA failed\n");
SetLastError(0xdeadbeef);
ret = GetObjectA(hfont, sizeof(getobj_lf), &getobj_lf);
ok(ret, "GetObject failed: %d\n", GetLastError());
ok(lf.lfItalic == getobj_lf.lfItalic, "lfItalic: expect %02x got %02x\n", lf.lfItalic, getobj_lf.lfItalic);
ok(lf.lfWeight == getobj_lf.lfWeight ||
broken((SHORT)lf.lfWeight == getobj_lf.lfWeight), /* win9x */
"lfWeight: expect %08x got %08x\n", lf.lfWeight, getobj_lf.lfWeight);
ok(!lstrcmpA(lf.lfFaceName, getobj_lf.lfFaceName) ||
broken(!memcmp(lf.lfFaceName, getobj_lf.lfFaceName, LF_FACESIZE-1)), /* win9x doesn't ensure '\0' termination */
"font names don't match: %s != %s\n", lf.lfFaceName, getobj_lf.lfFaceName);
DeleteObject(hfont);
}
}
static void test_CreateFontIndirectEx(void)
{
ENUMLOGFONTEXDVA lfex;
HFONT hfont;
if (!pCreateFontIndirectExA)
{
win_skip("CreateFontIndirectExA is not available\n");
return;
}
if (!is_truetype_font_installed("Arial"))
{
skip("Arial is not installed\n");
return;
}
SetLastError(0xdeadbeef);
hfont = pCreateFontIndirectExA(NULL);
ok(hfont == NULL, "got %p\n", hfont);
ok(GetLastError() == 0xdeadbeef, "got error %d\n", GetLastError());
memset(&lfex, 0, sizeof(lfex));
lstrcpyA(lfex.elfEnumLogfontEx.elfLogFont.lfFaceName, "Arial");
hfont = pCreateFontIndirectExA(&lfex);
ok(hfont != 0, "CreateFontIndirectEx failed\n");
if (hfont)
check_font("Arial", &lfex.elfEnumLogfontEx.elfLogFont, hfont);
DeleteObject(hfont);
}
static void free_font(void *font)
{
UnmapViewOfFile(font);
}
static void *load_font(const char *font_name, DWORD *font_size)
{
char file_name[MAX_PATH];
HANDLE file, mapping;
void *font;
if (!GetWindowsDirectoryA(file_name, sizeof(file_name))) return NULL;
strcat(file_name, "\\fonts\\");
strcat(file_name, font_name);
file = CreateFileA(file_name, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, 0);
if (file == INVALID_HANDLE_VALUE) return NULL;
*font_size = GetFileSize(file, NULL);
mapping = CreateFileMappingA(file, NULL, PAGE_READONLY, 0, 0, NULL);
if (!mapping)
{
CloseHandle(file);
return NULL;
}
font = MapViewOfFile(mapping, FILE_MAP_READ, 0, 0, 0);
CloseHandle(file);
CloseHandle(mapping);
return font;
}
static void test_AddFontMemResource(void)
{
void *font;
DWORD font_size, num_fonts;
HANDLE ret;
BOOL bRet;
if (!pAddFontMemResourceEx || !pRemoveFontMemResourceEx)
{
win_skip("AddFontMemResourceEx is not available on this platform\n");
return;
}
font = load_font("sserife.fon", &font_size);
if (!font)
{
skip("Unable to locate and load font sserife.fon\n");
return;
}
SetLastError(0xdeadbeef);
ret = pAddFontMemResourceEx(NULL, 0, NULL, NULL);
ok(!ret, "AddFontMemResourceEx should fail\n");
ok(GetLastError() == ERROR_INVALID_PARAMETER,
"Expected GetLastError() to return ERROR_INVALID_PARAMETER, got %u\n",
GetLastError());
SetLastError(0xdeadbeef);
ret = pAddFontMemResourceEx(NULL, 10, NULL, NULL);
ok(!ret, "AddFontMemResourceEx should fail\n");
ok(GetLastError() == ERROR_INVALID_PARAMETER,
"Expected GetLastError() to return ERROR_INVALID_PARAMETER, got %u\n",
GetLastError());
SetLastError(0xdeadbeef);
ret = pAddFontMemResourceEx(NULL, 0, NULL, &num_fonts);
ok(!ret, "AddFontMemResourceEx should fail\n");
ok(GetLastError() == ERROR_INVALID_PARAMETER,
"Expected GetLastError() to return ERROR_INVALID_PARAMETER, got %u\n",
GetLastError());
SetLastError(0xdeadbeef);
ret = pAddFontMemResourceEx(NULL, 10, NULL, &num_fonts);
ok(!ret, "AddFontMemResourceEx should fail\n");
ok(GetLastError() == ERROR_INVALID_PARAMETER,
"Expected GetLastError() to return ERROR_INVALID_PARAMETER, got %u\n",
GetLastError());
SetLastError(0xdeadbeef);
ret = pAddFontMemResourceEx(font, 0, NULL, NULL);
ok(!ret, "AddFontMemResourceEx should fail\n");
ok(GetLastError() == ERROR_INVALID_PARAMETER,
"Expected GetLastError() to return ERROR_INVALID_PARAMETER, got %u\n",
GetLastError());
SetLastError(0xdeadbeef);
ret = pAddFontMemResourceEx(font, 10, NULL, NULL);
ok(!ret, "AddFontMemResourceEx should fail\n");
ok(GetLastError() == ERROR_INVALID_PARAMETER,
"Expected GetLastError() to return ERROR_INVALID_PARAMETER, got %u\n",
GetLastError());
num_fonts = 0xdeadbeef;
SetLastError(0xdeadbeef);
ret = pAddFontMemResourceEx(font, 0, NULL, &num_fonts);
ok(!ret, "AddFontMemResourceEx should fail\n");
ok(GetLastError() == ERROR_INVALID_PARAMETER,
"Expected GetLastError() to return ERROR_INVALID_PARAMETER, got %u\n",
GetLastError());
ok(num_fonts == 0xdeadbeef, "number of loaded fonts should be 0xdeadbeef\n");
if (0) /* hangs under windows 2000 */
{
num_fonts = 0xdeadbeef;
SetLastError(0xdeadbeef);
ret = pAddFontMemResourceEx(font, 10, NULL, &num_fonts);
ok(!ret, "AddFontMemResourceEx should fail\n");
ok(GetLastError() == 0xdeadbeef,
"Expected GetLastError() to return 0xdeadbeef, got %u\n",
GetLastError());
ok(num_fonts == 0xdeadbeef, "number of loaded fonts should be 0xdeadbeef\n");
}
num_fonts = 0xdeadbeef;
SetLastError(0xdeadbeef);
ret = pAddFontMemResourceEx(font, font_size, NULL, &num_fonts);
ok(ret != 0, "AddFontMemResourceEx error %d\n", GetLastError());
ok(num_fonts != 0xdeadbeef, "number of loaded fonts should not be 0xdeadbeef\n");
ok(num_fonts != 0, "number of loaded fonts should not be 0\n");
free_font(font);
SetLastError(0xdeadbeef);
bRet = pRemoveFontMemResourceEx(ret);
ok(bRet, "RemoveFontMemResourceEx error %d\n", GetLastError());
/* test invalid pointer to number of loaded fonts */
font = load_font("sserife.fon", &font_size);
ok(font != NULL, "Unable to locate and load font sserife.fon\n");
SetLastError(0xdeadbeef);
ret = pAddFontMemResourceEx(font, font_size, NULL, (void *)0xdeadbeef);
ok(!ret, "AddFontMemResourceEx should fail\n");
ok(GetLastError() == 0xdeadbeef,
"Expected GetLastError() to return 0xdeadbeef, got %u\n",
GetLastError());
SetLastError(0xdeadbeef);
ret = pAddFontMemResourceEx(font, font_size, NULL, NULL);
ok(!ret, "AddFontMemResourceEx should fail\n");
ok(GetLastError() == ERROR_INVALID_PARAMETER,
"Expected GetLastError() to return ERROR_INVALID_PARAMETER, got %u\n",
GetLastError());
free_font(font);
}
static INT CALLBACK enum_fonts_proc(const LOGFONTA *elf, const TEXTMETRICA *ntm, DWORD type, LPARAM lparam)
{
LOGFONTA *lf;
if (type != TRUETYPE_FONTTYPE) return 1;
ok(ntm->tmWeight == elf->lfWeight, "expected %d got %d\n", ntm->tmWeight, elf->lfWeight);
lf = (LOGFONTA *)lparam;
*lf = *elf;
return 0;
}
static INT CALLBACK enum_all_fonts_proc(const LOGFONTA *elf, const TEXTMETRICA *ntm, DWORD type, LPARAM lparam)
{
int ret;
LOGFONTA *lf;
if (type != TRUETYPE_FONTTYPE) return 1;
lf = (LOGFONTA *)lparam;
ret = strcmp(lf->lfFaceName, elf->lfFaceName);
if(ret == 0)
{
ok(ntm->tmWeight == elf->lfWeight, "expected %d got %d\n", ntm->tmWeight, elf->lfWeight);
*lf = *elf;
return 0;
}
return 1;
}
static INT CALLBACK enum_with_magic_retval_proc(const LOGFONTA *elf, const TEXTMETRICA *ntm, DWORD type, LPARAM lparam)
{
return lparam;
}
static void test_EnumFonts(void)
{
int ret;
LOGFONTA lf;
HDC hdc;
if (!is_truetype_font_installed("Arial"))
{
skip("Arial is not installed\n");
return;
}
/* Windows uses localized font face names, so Arial Bold won't be found */
if (PRIMARYLANGID(GetUserDefaultLangID()) != LANG_ENGLISH)
{
skip("User locale is not English, skipping the test\n");
return;
}
hdc = CreateCompatibleDC(0);
/* check that the enumproc's retval is returned */
ret = EnumFontFamiliesA(hdc, NULL, enum_with_magic_retval_proc, 0xcafe);
ok(ret == 0xcafe, "got %08x\n", ret);
ret = EnumFontFamiliesA(hdc, "Arial", enum_fonts_proc, (LPARAM)&lf);
ok(!ret, "font Arial is not enumerated\n");
ret = strcmp(lf.lfFaceName, "Arial");
ok(!ret, "expected Arial got %s\n", lf.lfFaceName);
ok(lf.lfWeight == FW_NORMAL, "expected FW_NORMAL got %d\n", lf.lfWeight);
strcpy(lf.lfFaceName, "Arial");
ret = EnumFontFamiliesA(hdc, NULL, enum_all_fonts_proc, (LPARAM)&lf);
ok(!ret, "font Arial is not enumerated\n");
ret = strcmp(lf.lfFaceName, "Arial");
ok(!ret, "expected Arial got %s\n", lf.lfFaceName);
ok(lf.lfWeight == FW_NORMAL, "expected FW_NORMAL got %d\n", lf.lfWeight);
ret = EnumFontFamiliesA(hdc, "Arial Bold", enum_fonts_proc, (LPARAM)&lf);
ok(!ret, "font Arial Bold is not enumerated\n");
ret = strcmp(lf.lfFaceName, "Arial");
ok(!ret, "expected Arial got %s\n", lf.lfFaceName);
ok(lf.lfWeight == FW_BOLD, "expected FW_BOLD got %d\n", lf.lfWeight);
strcpy(lf.lfFaceName, "Arial Bold");
ret = EnumFontFamiliesA(hdc, NULL, enum_all_fonts_proc, (LPARAM)&lf);
ok(ret, "font Arial Bold should not be enumerated\n");
ret = EnumFontFamiliesA(hdc, "Arial Bold Italic", enum_fonts_proc, (LPARAM)&lf);
ok(!ret, "font Arial Bold Italic is not enumerated\n");
ret = strcmp(lf.lfFaceName, "Arial");
ok(!ret, "expected Arial got %s\n", lf.lfFaceName);
ok(lf.lfWeight == FW_BOLD, "expected FW_BOLD got %d\n", lf.lfWeight);
strcpy(lf.lfFaceName, "Arial Bold Italic");
ret = EnumFontFamiliesA(hdc, NULL, enum_all_fonts_proc, (LPARAM)&lf);
ok(ret, "font Arial Bold Italic should not be enumerated\n");
ret = EnumFontFamiliesA(hdc, "Arial Italic Bold", enum_fonts_proc, (LPARAM)&lf);
ok(ret, "font Arial Italic Bold should not be enumerated\n");
strcpy(lf.lfFaceName, "Arial Italic Bold");
ret = EnumFontFamiliesA(hdc, NULL, enum_all_fonts_proc, (LPARAM)&lf);
ok(ret, "font Arial Italic Bold should not be enumerated\n");
DeleteDC(hdc);
}
static INT CALLBACK is_font_installed_fullname_proc(const LOGFONTA *lf, const TEXTMETRICA *ntm, DWORD type, LPARAM lParam)
{
const ENUMLOGFONTA *elf = (const ENUMLOGFONTA *)lf;
const char *fullname = (const char *)lParam;
if (!strcmp((const char *)elf->elfFullName, fullname)) return 0;
return 1;
}
static BOOL is_font_installed_fullname(const char *family, const char *fullname)
{
HDC hdc = GetDC(0);
BOOL ret = FALSE;
if(!EnumFontFamiliesA(hdc, family, is_font_installed_fullname_proc, (LPARAM)fullname))
ret = TRUE;
ReleaseDC(0, hdc);
return ret;
}
static void test_fullname(void)
{
static const char *TestName[] = {"Lucida Sans Demibold Roman", "Lucida Sans Italic", "Lucida Sans Regular"};
WCHAR bufW[LF_FULLFACESIZE];
char bufA[LF_FULLFACESIZE];
HFONT hfont, of;
LOGFONTA lf;
HDC hdc;
int i;
DWORD ret;
hdc = CreateCompatibleDC(0);
ok(hdc != NULL, "CreateCompatibleDC failed\n");
memset(&lf, 0, sizeof(lf));
lf.lfCharSet = ANSI_CHARSET;
lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
lf.lfHeight = 16;
lf.lfWidth = 16;
lf.lfQuality = DEFAULT_QUALITY;
lf.lfItalic = FALSE;
lf.lfWeight = FW_DONTCARE;
for (i = 0; i < sizeof(TestName) / sizeof(TestName[0]); i++)
{
if (!is_font_installed_fullname("Lucida Sans", TestName[i]))
{
skip("%s is not installed\n", TestName[i]);
continue;
}
lstrcpyA(lf.lfFaceName, TestName[i]);
hfont = CreateFontIndirectA(&lf);
ok(hfont != 0, "CreateFontIndirectA failed\n");
of = SelectObject(hdc, hfont);
bufW[0] = 0;
bufA[0] = 0;
ret = get_ttf_nametable_entry(hdc, TT_NAME_ID_FULL_NAME, bufW, sizeof(bufW), TT_MS_LANGID_ENGLISH_UNITED_STATES);
ok(ret, "face full name could not be read\n");
WideCharToMultiByte(CP_ACP, 0, bufW, -1, bufA, sizeof(bufA), NULL, FALSE);
ok(!lstrcmpA(bufA, TestName[i]), "font full names don't match: %s != %s\n", TestName[i], bufA);
SelectObject(hdc, of);
DeleteObject(hfont);
}
DeleteDC(hdc);
}
static WCHAR *prepend_at(WCHAR *family)
{
if (!family)
return NULL;
memmove(family + 1, family, (lstrlenW(family) + 1) * sizeof(WCHAR));
family[0] = '@';
return family;
}
static void test_fullname2_helper(const char *Family)
{
char *FamilyName, *FaceName, *StyleName, *otmStr;
struct enum_fullname_data efnd;
WCHAR *bufW;
char *bufA;
HFONT hfont, of;
LOGFONTA lf;
HDC hdc;
int i;
DWORD otm_size, ret, buf_size;
OUTLINETEXTMETRICA *otm;
BOOL want_vertical, get_vertical;
want_vertical = ( Family[0] == '@' );
hdc = CreateCompatibleDC(0);
ok(hdc != NULL, "CreateCompatibleDC failed\n");
memset(&lf, 0, sizeof(lf));
lf.lfCharSet = DEFAULT_CHARSET;
lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
lf.lfHeight = 16;
lf.lfWidth = 16;
lf.lfQuality = DEFAULT_QUALITY;
lf.lfItalic = FALSE;
lf.lfWeight = FW_DONTCARE;
strcpy(lf.lfFaceName, Family);
efnd.total = 0;
EnumFontFamiliesExA(hdc, &lf, enum_fullname_data_proc, (LPARAM)&efnd, 0);
if (efnd.total == 0)
skip("%s is not installed\n", lf.lfFaceName);
for (i = 0; i < efnd.total; i++)
{
FamilyName = (char *)efnd.elf[i].elfLogFont.lfFaceName;
FaceName = (char *)efnd.elf[i].elfFullName;
StyleName = (char *)efnd.elf[i].elfStyle;
trace("Checking font %s:\nFamilyName: %s; FaceName: %s; StyleName: %s\n", Family, FamilyName, FaceName, StyleName);
get_vertical = ( FamilyName[0] == '@' );
ok(get_vertical == want_vertical, "Vertical flags don't match: %s %s\n", Family, FamilyName);
lstrcpyA(lf.lfFaceName, FaceName);
hfont = CreateFontIndirectA(&lf);
ok(hfont != 0, "CreateFontIndirectA failed\n");
of = SelectObject(hdc, hfont);
buf_size = GetFontData(hdc, MS_NAME_TAG, 0, NULL, 0);
ok(buf_size != GDI_ERROR, "no name table found\n");
if (buf_size == GDI_ERROR) continue;
bufW = HeapAlloc(GetProcessHeap(), 0, buf_size);
bufA = HeapAlloc(GetProcessHeap(), 0, buf_size);
otm_size = GetOutlineTextMetricsA(hdc, 0, NULL);
otm = HeapAlloc(GetProcessHeap(), 0, otm_size);
memset(otm, 0, otm_size);
ret = GetOutlineTextMetricsA(hdc, otm_size, otm);
ok(ret != 0, "GetOutlineTextMetrics fails!\n");
if (ret == 0) continue;
bufW[0] = 0;
bufA[0] = 0;
ret = get_ttf_nametable_entry(hdc, TT_NAME_ID_FONT_FAMILY, bufW, buf_size, GetSystemDefaultLangID());
if (!ret)
{
trace("no localized FONT_FAMILY found.\n");
ret = get_ttf_nametable_entry(hdc, TT_NAME_ID_FONT_FAMILY, bufW, buf_size, TT_MS_LANGID_ENGLISH_UNITED_STATES);
}
ok(ret, "FAMILY (family name) could not be read\n");
if (want_vertical) bufW = prepend_at(bufW);
WideCharToMultiByte(CP_ACP, 0, bufW, -1, bufA, buf_size, NULL, FALSE);
ok(!lstrcmpA(FamilyName, bufA), "font family names don't match: returned %s, expect %s\n", FamilyName, bufA);
otmStr = (LPSTR)otm + (UINT_PTR)otm->otmpFamilyName;
ok(!lstrcmpA(FamilyName, otmStr), "FamilyName %s doesn't match otmpFamilyName %s\n", FamilyName, otmStr);
bufW[0] = 0;
bufA[0] = 0;
ret = get_ttf_nametable_entry(hdc, TT_NAME_ID_FULL_NAME, bufW, buf_size, GetSystemDefaultLangID());
if (!ret)
{
trace("no localized FULL_NAME found.\n");
ret = get_ttf_nametable_entry(hdc, TT_NAME_ID_FULL_NAME, bufW, buf_size, TT_MS_LANGID_ENGLISH_UNITED_STATES);
}
ok(ret, "FULL_NAME (face name) could not be read\n");
if (want_vertical) bufW = prepend_at(bufW);
WideCharToMultiByte(CP_ACP, 0, bufW, -1, bufA, buf_size, NULL, FALSE);
ok(!lstrcmpA(FaceName, bufA), "font face names don't match: returned %s, expect %s\n", FaceName, bufA);
otmStr = (LPSTR)otm + (UINT_PTR)otm->otmpFaceName;
ok(!lstrcmpA(FaceName, otmStr), "FaceName %s doesn't match otmpFaceName %s\n", FaceName, otmStr);
bufW[0] = 0;
bufA[0] = 0;
ret = get_ttf_nametable_entry(hdc, TT_NAME_ID_FONT_SUBFAMILY, bufW, buf_size, GetSystemDefaultLangID());
if (!ret)
{
trace("no localized FONT_SUBFAMILY found.\n");
ret = get_ttf_nametable_entry(hdc, TT_NAME_ID_FONT_SUBFAMILY, bufW, buf_size, TT_MS_LANGID_ENGLISH_UNITED_STATES);
}
ok(ret, "SUBFAMILY (style name) could not be read\n");
WideCharToMultiByte(CP_ACP, 0, bufW, -1, bufA, buf_size, NULL, FALSE);
ok(!lstrcmpA(StyleName, bufA), "style names don't match: returned %s, expect %s\n", StyleName, bufA);
otmStr = (LPSTR)otm + (UINT_PTR)otm->otmpStyleName;
ok(!lstrcmpA(StyleName, otmStr), "StyleName %s doesn't match otmpStyleName %s\n", StyleName, otmStr);
bufW[0] = 0;
bufA[0] = 0;
ret = get_ttf_nametable_entry(hdc, TT_NAME_ID_UNIQUE_ID, bufW, buf_size, GetSystemDefaultLangID());
if (!ret)
{
trace("no localized UNIQUE_ID found.\n");
ret = get_ttf_nametable_entry(hdc, TT_NAME_ID_UNIQUE_ID, bufW, buf_size, TT_MS_LANGID_ENGLISH_UNITED_STATES);
}
ok(ret, "UNIQUE_ID (full name) could not be read\n");
WideCharToMultiByte(CP_ACP, 0, bufW, -1, bufA, buf_size, NULL, FALSE);
otmStr = (LPSTR)otm + (UINT_PTR)otm->otmpFullName;
ok(!lstrcmpA(otmStr, bufA), "UNIQUE ID (full name) doesn't match: returned %s, expect %s\n", otmStr, bufA);
SelectObject(hdc, of);
DeleteObject(hfont);
HeapFree(GetProcessHeap(), 0, otm);
HeapFree(GetProcessHeap(), 0, bufW);
HeapFree(GetProcessHeap(), 0, bufA);
}
DeleteDC(hdc);
}
static void test_fullname2(void)
{
test_fullname2_helper("Arial");
test_fullname2_helper("DejaVu Sans");
test_fullname2_helper("Lucida Sans");
test_fullname2_helper("Tahoma");
test_fullname2_helper("Webdings");
test_fullname2_helper("Wingdings");
test_fullname2_helper("SimSun");
test_fullname2_helper("NSimSun");
test_fullname2_helper("MingLiu");
test_fullname2_helper("PMingLiu");
test_fullname2_helper("WenQuanYi Micro Hei");
test_fullname2_helper("MS UI Gothic");
test_fullname2_helper("Ume UI Gothic");
test_fullname2_helper("MS Gothic");
test_fullname2_helper("Ume Gothic");
test_fullname2_helper("MS PGothic");
test_fullname2_helper("Ume P Gothic");
test_fullname2_helper("Gulim");
test_fullname2_helper("Batang");
test_fullname2_helper("UnBatang");
test_fullname2_helper("UnDotum");
test_fullname2_helper("@SimSun");
test_fullname2_helper("@NSimSun");
test_fullname2_helper("@MingLiu");
test_fullname2_helper("@PMingLiu");
test_fullname2_helper("@WenQuanYi Micro Hei");
test_fullname2_helper("@MS UI Gothic");
test_fullname2_helper("@Ume UI Gothic");
test_fullname2_helper("@MS Gothic");
test_fullname2_helper("@Ume Gothic");
test_fullname2_helper("@MS PGothic");
test_fullname2_helper("@Ume P Gothic");
test_fullname2_helper("@Gulim");
test_fullname2_helper("@Batang");
test_fullname2_helper("@UnBatang");
test_fullname2_helper("@UnDotum");
}
static void test_GetGlyphOutline_empty_contour(void)
{
HDC hdc;
LOGFONTA lf;
HFONT hfont, hfont_prev;
TTPOLYGONHEADER *header;
GLYPHMETRICS gm;
char buf[1024];
DWORD ret;
memset(&lf, 0, sizeof(lf));
lf.lfHeight = 72;
lstrcpyA(lf.lfFaceName, "wine_test");
hfont = CreateFontIndirectA(&lf);
ok(hfont != 0, "CreateFontIndirectA error %u\n", GetLastError());
hdc = GetDC(NULL);
hfont_prev = SelectObject(hdc, hfont);
ok(hfont_prev != NULL, "SelectObject failed\n");
ret = GetGlyphOutlineW(hdc, 0xa8, GGO_NATIVE, &gm, 0, NULL, &mat);
ok(ret == 228, "GetGlyphOutline returned %d, expected 228\n", ret);
header = (TTPOLYGONHEADER*)buf;
ret = GetGlyphOutlineW(hdc, 0xa8, GGO_NATIVE, &gm, sizeof(buf), buf, &mat);
ok(ret == 228, "GetGlyphOutline returned %d, expected 228\n", ret);
ok(header->cb == 36, "header->cb = %d, expected 36\n", header->cb);
ok(header->dwType == TT_POLYGON_TYPE, "header->dwType = %d, expected TT_POLYGON_TYPE\n", header->dwType);
header = (TTPOLYGONHEADER*)((char*)header+header->cb);
ok(header->cb == 96, "header->cb = %d, expected 96\n", header->cb);
header = (TTPOLYGONHEADER*)((char*)header+header->cb);
ok(header->cb == 96, "header->cb = %d, expected 96\n", header->cb);
SelectObject(hdc, hfont_prev);
DeleteObject(hfont);
ReleaseDC(NULL, hdc);
}
static void test_GetGlyphOutline_metric_clipping(void)
{
HDC hdc;
LOGFONTA lf;
HFONT hfont, hfont_prev;
GLYPHMETRICS gm;
TEXTMETRICA tm;
DWORD ret;
memset(&lf, 0, sizeof(lf));
lf.lfHeight = 72;
lstrcpyA(lf.lfFaceName, "wine_test");
SetLastError(0xdeadbeef);
hfont = CreateFontIndirectA(&lf);
ok(hfont != 0, "CreateFontIndirectA error %u\n", GetLastError());
hdc = GetDC(NULL);
hfont_prev = SelectObject(hdc, hfont);
ok(hfont_prev != NULL, "SelectObject failed\n");
SetLastError(0xdeadbeef);
ret = GetTextMetricsA(hdc, &tm);
ok(ret, "GetTextMetrics error %u\n", GetLastError());
GetGlyphOutlineA(hdc, 'A', GGO_METRICS, &gm, 0, NULL, &mat);
ok(gm.gmptGlyphOrigin.y <= tm.tmAscent,
"Glyph top(%d) exceeds ascent(%d)\n",
gm.gmptGlyphOrigin.y, tm.tmAscent);
GetGlyphOutlineA(hdc, 'D', GGO_METRICS, &gm, 0, NULL, &mat);
ok(gm.gmptGlyphOrigin.y - gm.gmBlackBoxY >= -tm.tmDescent,
"Glyph bottom(%d) exceeds descent(%d)\n",
gm.gmptGlyphOrigin.y - gm.gmBlackBoxY, -tm.tmDescent);
SelectObject(hdc, hfont_prev);
DeleteObject(hfont);
ReleaseDC(NULL, hdc);
}
static void test_CreateScalableFontResource(void)
{
char ttf_name[MAX_PATH];
char tmp_path[MAX_PATH];
char fot_name[MAX_PATH];
char *file_part;
DWORD ret;
int i;
if (!pAddFontResourceExA || !pRemoveFontResourceExA)
{
win_skip("AddFontResourceExA is not available on this platform\n");
return;
}
if (!write_ttf_file("wine_test.ttf", ttf_name))
{
skip("Failed to create ttf file for testing\n");
return;
}
trace("created %s\n", ttf_name);
ret = is_truetype_font_installed("wine_test");
ok(!ret, "font wine_test should not be enumerated\n");
ret = GetTempPathA(MAX_PATH, tmp_path);
ok(ret, "GetTempPath() error %d\n", GetLastError());
ret = GetTempFileNameA(tmp_path, "fot", 0, fot_name);
ok(ret, "GetTempFileName() error %d\n", GetLastError());
ret = GetFileAttributesA(fot_name);
ok(ret != INVALID_FILE_ATTRIBUTES, "file %s does not exist\n", fot_name);
SetLastError(0xdeadbeef);
ret = CreateScalableFontResourceA(0, fot_name, ttf_name, NULL);
ok(!ret, "CreateScalableFontResource() should fail\n");
ok(GetLastError() == ERROR_FILE_EXISTS, "not expected error %d\n", GetLastError());
SetLastError(0xdeadbeef);
ret = CreateScalableFontResourceA(0, fot_name, ttf_name, "");
ok(!ret, "CreateScalableFontResource() should fail\n");
ok(GetLastError() == ERROR_FILE_EXISTS, "not expected error %d\n", GetLastError());
file_part = strrchr(ttf_name, '\\');
SetLastError(0xdeadbeef);
ret = CreateScalableFontResourceA(0, fot_name, file_part, tmp_path);
ok(!ret, "CreateScalableFontResource() should fail\n");
ok(GetLastError() == ERROR_FILE_EXISTS, "not expected error %d\n", GetLastError());
SetLastError(0xdeadbeef);
ret = CreateScalableFontResourceA(0, fot_name, "random file name", tmp_path);
ok(!ret, "CreateScalableFontResource() should fail\n");
ok(GetLastError() == ERROR_INVALID_PARAMETER, "not expected error %d\n", GetLastError());
SetLastError(0xdeadbeef);
ret = CreateScalableFontResourceA(0, fot_name, NULL, ttf_name);
ok(!ret, "CreateScalableFontResource() should fail\n");
ok(GetLastError() == ERROR_INVALID_PARAMETER, "not expected error %d\n", GetLastError());
ret = DeleteFileA(fot_name);
ok(ret, "DeleteFile() error %d\n", GetLastError());
ret = pRemoveFontResourceExA(fot_name, 0, 0);
ok(!ret, "RemoveFontResourceEx() should fail\n");
/* test public font resource */
SetLastError(0xdeadbeef);
ret = CreateScalableFontResourceA(0, fot_name, ttf_name, NULL);
ok(ret, "CreateScalableFontResource() error %d\n", GetLastError());
ret = is_truetype_font_installed("wine_test");
ok(!ret, "font wine_test should not be enumerated\n");
SetLastError(0xdeadbeef);
ret = pAddFontResourceExA(fot_name, 0, 0);
ok(ret, "AddFontResourceEx() error %d\n", GetLastError());
ret = is_truetype_font_installed("wine_test");
ok(ret, "font wine_test should be enumerated\n");
test_GetGlyphOutline_empty_contour();
test_GetGlyphOutline_metric_clipping();
ret = pRemoveFontResourceExA(fot_name, FR_PRIVATE, 0);
ok(!ret, "RemoveFontResourceEx() with not matching flags should fail\n");
SetLastError(0xdeadbeef);
ret = pRemoveFontResourceExA(fot_name, 0, 0);
ok(ret, "RemoveFontResourceEx() error %d\n", GetLastError());
ret = is_truetype_font_installed("wine_test");
ok(!ret, "font wine_test should not be enumerated\n");
ret = pRemoveFontResourceExA(fot_name, 0, 0);
ok(!ret, "RemoveFontResourceEx() should fail\n");
/* test refcounting */
for (i = 0; i < 5; i++)
{
SetLastError(0xdeadbeef);
ret = pAddFontResourceExA(fot_name, 0, 0);
ok(ret, "AddFontResourceEx() error %d\n", GetLastError());
}
for (i = 0; i < 5; i++)
{
SetLastError(0xdeadbeef);
ret = pRemoveFontResourceExA(fot_name, 0, 0);
ok(ret, "RemoveFontResourceEx() error %d\n", GetLastError());
}
ret = pRemoveFontResourceExA(fot_name, 0, 0);
ok(!ret, "RemoveFontResourceEx() should fail\n");
DeleteFileA(fot_name);
/* test hidden font resource */
SetLastError(0xdeadbeef);
ret = CreateScalableFontResourceA(1, fot_name, ttf_name, NULL);
ok(ret, "CreateScalableFontResource() error %d\n", GetLastError());
ret = is_truetype_font_installed("wine_test");
ok(!ret, "font wine_test should not be enumerated\n");
SetLastError(0xdeadbeef);
ret = pAddFontResourceExA(fot_name, 0, 0);
ok(ret, "AddFontResourceEx() error %d\n", GetLastError());
ret = is_truetype_font_installed("wine_test");
todo_wine
ok(!ret, "font wine_test should not be enumerated\n");
/* XP allows removing a private font added with 0 flags */
SetLastError(0xdeadbeef);
ret = pRemoveFontResourceExA(fot_name, FR_PRIVATE, 0);
ok(ret, "RemoveFontResourceEx() error %d\n", GetLastError());
ret = is_truetype_font_installed("wine_test");
ok(!ret, "font wine_test should not be enumerated\n");
ret = pRemoveFontResourceExA(fot_name, 0, 0);
ok(!ret, "RemoveFontResourceEx() should fail\n");
DeleteFileA(fot_name);
DeleteFileA(ttf_name);
}
static void check_vertical_font(const char *name, BOOL *installed, BOOL *selected, GLYPHMETRICS *gm, WORD *gi)
{
LOGFONTA lf;
HFONT hfont, hfont_prev;
HDC hdc;
char facename[100];
DWORD ret;
static const WCHAR str[] = { 0x2025 };
*installed = is_truetype_font_installed(name);
lf.lfHeight = -18;
lf.lfWidth = 0;
lf.lfEscapement = 0;
lf.lfOrientation = 0;
lf.lfWeight = FW_DONTCARE;
lf.lfItalic = 0;
lf.lfUnderline = 0;
lf.lfStrikeOut = 0;
lf.lfCharSet = DEFAULT_CHARSET;
lf.lfOutPrecision = OUT_TT_ONLY_PRECIS;
lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
lf.lfQuality = DEFAULT_QUALITY;
lf.lfPitchAndFamily = DEFAULT_PITCH | FF_DONTCARE;
strcpy(lf.lfFaceName, name);
hfont = CreateFontIndirectA(&lf);
ok(hfont != NULL, "CreateFontIndirectA failed\n");
hdc = GetDC(NULL);
hfont_prev = SelectObject(hdc, hfont);
ok(hfont_prev != NULL, "SelectObject failed\n");
ret = GetTextFaceA(hdc, sizeof facename, facename);
ok(ret, "GetTextFaceA failed\n");
*selected = !strcmp(facename, name);
ret = GetGlyphOutlineW(hdc, 0x2025, GGO_METRICS, gm, 0, NULL, &mat);
ok(ret != GDI_ERROR, "GetGlyphOutlineW failed\n");
if (!*selected)
memset(gm, 0, sizeof *gm);
ret = pGetGlyphIndicesW(hdc, str, 1, gi, 0);
ok(ret != GDI_ERROR, "GetGlyphIndicesW failed\n");
SelectObject(hdc, hfont_prev);
DeleteObject(hfont);
ReleaseDC(NULL, hdc);
}
static void check_vertical_metrics(const char *face)
{
LOGFONTA lf;
HFONT hfont, hfont_prev;
HDC hdc;
DWORD ret;
GLYPHMETRICS rgm, vgm;
const UINT code = 0x5EAD, height = 1000;
WORD idx;
ABC abc;
OUTLINETEXTMETRICA otm;
USHORT numOfLongVerMetrics;
hdc = GetDC(NULL);
memset(&lf, 0, sizeof(lf));
strcpy(lf.lfFaceName, face);
lf.lfHeight = -height;
lf.lfCharSet = DEFAULT_CHARSET;
lf.lfEscapement = lf.lfOrientation = 900;
hfont = CreateFontIndirectA(&lf);
hfont_prev = SelectObject(hdc, hfont);
ret = GetGlyphOutlineW(hdc, code, GGO_METRICS, &rgm, 0, NULL, &mat);
ok(ret != GDI_ERROR, "GetGlyphOutlineW failed\n");
ret = GetCharABCWidthsW(hdc, code, code, &abc);
ok(ret, "GetCharABCWidthsW failed\n");
DeleteObject(SelectObject(hdc, hfont_prev));
memset(&lf, 0, sizeof(lf));
strcpy(lf.lfFaceName, "@");
strcat(lf.lfFaceName, face);
lf.lfHeight = -height;
lf.lfCharSet = DEFAULT_CHARSET;
hfont = CreateFontIndirectA(&lf);
hfont_prev = SelectObject(hdc, hfont);
ret = GetGlyphOutlineW(hdc, code, GGO_METRICS, &vgm, 0, NULL, &mat);
ok(ret != GDI_ERROR, "GetGlyphOutlineW failed\n");
memset(&otm, 0, sizeof(otm));
otm.otmSize = sizeof(otm);
ret = GetOutlineTextMetricsA(hdc, sizeof(otm), &otm);
ok(ret != 0, "GetOutlineTextMetricsA failed\n");
if (GetFontData(hdc, MS_MAKE_TAG('v','h','e','a'), sizeof(SHORT) * 17,
&numOfLongVerMetrics, sizeof(numOfLongVerMetrics)) != GDI_ERROR) {
int offset;
SHORT topSideBearing;
if (!pGetGlyphIndicesW) {
win_skip("GetGlyphIndices is not available on this platform\n");
}
else {
ret = pGetGlyphIndicesW(hdc, (LPCWSTR)&code, 1, &idx, 0);
ok(ret != 0, "GetGlyphIndicesW failed\n");
numOfLongVerMetrics = GET_BE_WORD(numOfLongVerMetrics);
if (numOfLongVerMetrics > idx)
offset = idx * 2 + 1;
else
offset = numOfLongVerMetrics * 2 + (idx - numOfLongVerMetrics);
ret = GetFontData(hdc, MS_MAKE_TAG('v','m','t','x'), offset * sizeof(SHORT),
&topSideBearing, sizeof(SHORT));
ok(ret != GDI_ERROR, "GetFontData(vmtx) failed\n");
topSideBearing = GET_BE_WORD(topSideBearing);
ok(match_off_by_1(vgm.gmptGlyphOrigin.x,
MulDiv(topSideBearing, height, otm.otmEMSquare), FALSE),
"expected %d, got %d\n",
MulDiv(topSideBearing, height, otm.otmEMSquare), vgm.gmptGlyphOrigin.x);
}
}
else
{
ok(vgm.gmptGlyphOrigin.x == rgm.gmptGlyphOrigin.x + vgm.gmCellIncX + otm.otmDescent,
"got %d, expected rgm.origin.x(%d) + vgm.cellIncX(%d) + descent(%d)\n",
vgm.gmptGlyphOrigin.x, rgm.gmptGlyphOrigin.x, vgm.gmCellIncX, otm.otmDescent);
}
ok(vgm.gmptGlyphOrigin.y == abc.abcA + abc.abcB + otm.otmDescent ||
broken(vgm.gmptGlyphOrigin.y == abc.abcA + abc.abcB - otm.otmTextMetrics.tmDescent) /* win2k */,
"got %d, expected abcA(%d) + abcB(%u) + descent(%d)\n",
(INT)vgm.gmptGlyphOrigin.y, abc.abcA, abc.abcB, otm.otmDescent);
DeleteObject(SelectObject(hdc, hfont_prev));
ReleaseDC(NULL, hdc);
}
static void test_vertical_font(void)
{
char ttf_name[MAX_PATH];
int num, i;
BOOL ret, installed, selected;
GLYPHMETRICS gm;
WORD hgi, vgi;
const char* face_list[] = {
"@WineTestVertical", /* has vmtx table */
"@Ume Gothic", /* doesn't have vmtx table */
"@MS UI Gothic", /* has vmtx table, available on native */
};
if (!pAddFontResourceExA || !pRemoveFontResourceExA || !pGetGlyphIndicesW)
{
win_skip("AddFontResourceExA or GetGlyphIndicesW is not available on this platform\n");
return;
}
if (!write_ttf_file("vertical.ttf", ttf_name))
{
skip("Failed to create ttf file for testing\n");
return;
}
num = pAddFontResourceExA(ttf_name, FR_PRIVATE, 0);
ok(num == 2, "AddFontResourceExA should add 2 fonts from vertical.ttf\n");
check_vertical_font("WineTestVertical", &installed, &selected, &gm, &hgi);
ok(installed, "WineTestVertical is not installed\n");
ok(selected, "WineTestVertical is not selected\n");
ok(gm.gmBlackBoxX > gm.gmBlackBoxY,
"gmBlackBoxX(%u) should be greater than gmBlackBoxY(%u) if horizontal\n",
gm.gmBlackBoxX, gm.gmBlackBoxY);
check_vertical_font("@WineTestVertical", &installed, &selected, &gm, &vgi);
ok(installed, "@WineTestVertical is not installed\n");
ok(selected, "@WineTestVertical is not selected\n");
ok(gm.gmBlackBoxX > gm.gmBlackBoxY,
"gmBlackBoxX(%u) should be less than gmBlackBoxY(%u) if vertical\n",
gm.gmBlackBoxX, gm.gmBlackBoxY);
ok(hgi != vgi, "same glyph h:%u v:%u\n", hgi, vgi);
for (i = 0; i < sizeof(face_list)/sizeof(face_list[0]); i++) {
const char* face = face_list[i];
if (!is_truetype_font_installed(face)) {
skip("%s is not installed\n", face);
continue;
}
trace("Testing %s...\n", face);
check_vertical_metrics(&face[1]);
}
ret = pRemoveFontResourceExA(ttf_name, FR_PRIVATE, 0);
ok(ret, "RemoveFontResourceEx() error %d\n", GetLastError());
DeleteFileA(ttf_name);
}
static INT CALLBACK has_vertical_font_proc(const LOGFONTA *lf, const TEXTMETRICA *ntm,
DWORD type, LPARAM lParam)
{
if (lf->lfFaceName[0] == '@') {
return 0;
}
return 1;
}
static void test_east_asian_font_selection(void)
{
HDC hdc;
UINT charset[] = { SHIFTJIS_CHARSET, HANGEUL_CHARSET, JOHAB_CHARSET,
GB2312_CHARSET, CHINESEBIG5_CHARSET };
size_t i;
hdc = GetDC(NULL);
for (i = 0; i < sizeof(charset)/sizeof(charset[0]); i++)
{
LOGFONTA lf;
HFONT hfont;
char face_name[LF_FACESIZE];
int ret;
memset(&lf, 0, sizeof lf);
lf.lfFaceName[0] = '\0';
lf.lfCharSet = charset[i];
if (EnumFontFamiliesExA(hdc, &lf, has_vertical_font_proc, 0, 0))
{
skip("Vertical font for charset %u is not installed\n", charset[i]);
continue;
}
hfont = CreateFontIndirectA(&lf);
hfont = SelectObject(hdc, hfont);
memset(face_name, 0, sizeof face_name);
ret = GetTextFaceA(hdc, sizeof face_name, face_name);
ok(ret && face_name[0] != '@',
"expected non-vertical face for charset %u, got %s\n", charset[i], face_name);
DeleteObject(SelectObject(hdc, hfont));
memset(&lf, 0, sizeof lf);
strcpy(lf.lfFaceName, "@");
lf.lfCharSet = charset[i];
hfont = CreateFontIndirectA(&lf);
hfont = SelectObject(hdc, hfont);
memset(face_name, 0, sizeof face_name);
ret = GetTextFaceA(hdc, sizeof face_name, face_name);
ok(ret && face_name[0] == '@',
"expected vertical face for charset %u, got %s\n", charset[i], face_name);
DeleteObject(SelectObject(hdc, hfont));
}
ReleaseDC(NULL, hdc);
}
static int get_font_dpi(const LOGFONTA *lf, int *height)
{
HDC hdc = CreateCompatibleDC(0);
HFONT hfont;
TEXTMETRICA tm;
int ret;
hfont = CreateFontIndirectA(lf);
ok(hfont != 0, "CreateFontIndirect failed\n");
SelectObject(hdc, hfont);
ret = GetTextMetricsA(hdc, &tm);
ok(ret, "GetTextMetrics failed\n");
ret = tm.tmDigitizedAspectX;
if (height) *height = tm.tmHeight;
DeleteDC(hdc);
DeleteObject(hfont);
return ret;
}
static void test_stock_fonts(void)
{
static const int font[] =
{
ANSI_FIXED_FONT, ANSI_VAR_FONT, SYSTEM_FONT, DEVICE_DEFAULT_FONT, DEFAULT_GUI_FONT
/* SYSTEM_FIXED_FONT, OEM_FIXED_FONT */
};
static const struct test_data
{
int charset, weight, height, height_pixels, dpi;
const char face_name[LF_FACESIZE];
} td[][11] =
{
{ /* ANSI_FIXED_FONT */
{ DEFAULT_CHARSET, FW_NORMAL, 12, 13, 96, "Courier" },
{ DEFAULT_CHARSET, FW_NORMAL, 12, 13, 120, "Courier" },
{ 0 }
},
{ /* ANSI_VAR_FONT */
{ DEFAULT_CHARSET, FW_NORMAL, 12, 13, 96, "MS Sans Serif" },
{ DEFAULT_CHARSET, FW_NORMAL, 12, 13, 120, "MS Sans Serif" },
{ 0 }
},
{ /* SYSTEM_FONT */
{ SHIFTJIS_CHARSET, FW_NORMAL, 18, 18, 96, "System" },
{ SHIFTJIS_CHARSET, FW_NORMAL, 22, 22, 120, "System" },
{ HANGEUL_CHARSET, FW_NORMAL, 16, 16, 96, "System" },
{ HANGEUL_CHARSET, FW_NORMAL, 20, 20, 120, "System" },
{ DEFAULT_CHARSET, FW_BOLD, 16, 16, 96, "System" },
{ DEFAULT_CHARSET, FW_BOLD, 20, 20, 120, "System" },
{ 0 }
},
{ /* DEVICE_DEFAULT_FONT */
{ SHIFTJIS_CHARSET, FW_NORMAL, 18, 18, 96, "System" },
{ SHIFTJIS_CHARSET, FW_NORMAL, 22, 22, 120, "System" },
{ HANGEUL_CHARSET, FW_NORMAL, 16, 16, 96, "System" },
{ HANGEUL_CHARSET, FW_NORMAL, 20, 20, 120, "System" },
{ DEFAULT_CHARSET, FW_BOLD, 16, 16, 96, "System" },
{ DEFAULT_CHARSET, FW_BOLD, 20, 20, 120, "System" },
{ 0 }
},
{ /* DEFAULT_GUI_FONT */
{ SHIFTJIS_CHARSET, FW_NORMAL, -12, 15, 96, "?MS UI Gothic" },
{ SHIFTJIS_CHARSET, FW_NORMAL, -15, 18, 120, "?MS UI Gothic" },
{ HANGEUL_CHARSET, FW_NORMAL, -12, 15, 96, "?Gulim" },
{ HANGEUL_CHARSET, FW_NORMAL, -15, 18, 120, "?Gulim" },
{ GB2312_CHARSET, FW_NORMAL, -12, 15, 96, "?SimHei" },
{ GB2312_CHARSET, FW_NORMAL, -15, 18, 120, "?SimHei" },
{ CHINESEBIG5_CHARSET, FW_NORMAL, -12, 15, 96, "?MingLiU" },
{ CHINESEBIG5_CHARSET, FW_NORMAL, -15, 18, 120, "?MingLiU" },
{ DEFAULT_CHARSET, FW_NORMAL, -11, 13, 96, "MS Shell Dlg" },
{ DEFAULT_CHARSET, FW_NORMAL, -13, 16, 120, "MS Shell Dlg" },
{ 0 }
}
};
int i, j;
for (i = 0; i < sizeof(font)/sizeof(font[0]); i++)
{
HFONT hfont;
LOGFONTA lf;
int ret, height;
hfont = GetStockObject(font[i]);
ok(hfont != 0, "%d: GetStockObject(%d) failed\n", i, font[i]);
ret = GetObjectA(hfont, sizeof(lf), &lf);
if (ret != sizeof(lf))
{
/* NT4 */
win_skip("%d: GetObject returned %d instead of sizeof(LOGFONT)\n", i, ret);
continue;
}
for (j = 0; td[i][j].face_name[0] != 0; j++)
{
if (lf.lfCharSet != td[i][j].charset && td[i][j].charset != DEFAULT_CHARSET)
{
continue;
}
ret = get_font_dpi(&lf, &height);
if (ret != td[i][j].dpi)
{
trace("%d(%d): font %s %d dpi doesn't match test data %d\n",
i, j, lf.lfFaceName, ret, td[i][j].dpi);
continue;
}
/* FIXME: Remove once Wine is fixed */
if (td[i][j].dpi != 96 &&
/* MS Sans Serif for 120 dpi and higher should include 12 pixel bitmap set */
((!strcmp(td[i][j].face_name, "MS Sans Serif") && td[i][j].height == 12) ||
/* System for 120 dpi and higher should include 20 pixel bitmap set */
(!strcmp(td[i][j].face_name, "System") && td[i][j].height > 16)))
todo_wine
ok(height == td[i][j].height_pixels, "%d(%d): expected height %d, got %d\n", i, j, td[i][j].height_pixels, height);
else
ok(height == td[i][j].height_pixels, "%d(%d): expected height %d, got %d\n", i, j, td[i][j].height_pixels, height);
ok(td[i][j].weight == lf.lfWeight, "%d(%d): expected lfWeight %d, got %d\n", i, j, td[i][j].weight, lf.lfWeight);
ok(td[i][j].height == lf.lfHeight, "%d(%d): expected lfHeight %d, got %d\n", i, j, td[i][j].height, lf.lfHeight);
if (td[i][j].face_name[0] == '?')
{
/* Wine doesn't have this font, skip this case for now.
Actually, the face name is localized on Windows and varies
dpending on Windows versions (e.g. Japanese NT4 vs win2k). */
trace("%d(%d): default gui font is %s\n", i, j, lf.lfFaceName);
}
else
{
ok(!strcmp(td[i][j].face_name, lf.lfFaceName), "%d(%d): expected lfFaceName %s, got %s\n", i, j, td[i][j].face_name, lf.lfFaceName);
}
break;
}
}
}
static void test_max_height(void)
{
HDC hdc;
LOGFONTA lf;
HFONT hfont, hfont_old;
TEXTMETRICA tm1, tm;
BOOL r;
LONG invalid_height[] = { -65536, -123456, 123456 };
size_t i;
memset(&tm1, 0, sizeof(tm1));
memset(&lf, 0, sizeof(lf));
strcpy(lf.lfFaceName, "Tahoma");
lf.lfHeight = -1;
hdc = GetDC(NULL);
/* get 1 ppem value */
hfont = CreateFontIndirectA(&lf);
hfont_old = SelectObject(hdc, hfont);
r = GetTextMetricsA(hdc, &tm1);
ok(r, "GetTextMetrics failed\n");
ok(tm1.tmHeight > 0, "expected a positive value, got %d\n", tm1.tmHeight);
ok(tm1.tmAveCharWidth > 0, "expected a positive value, got %d\n", tm1.tmHeight);
DeleteObject(SelectObject(hdc, hfont_old));
/* test the largest value */
lf.lfHeight = -((1 << 16) - 1);
hfont = CreateFontIndirectA(&lf);
hfont_old = SelectObject(hdc, hfont);
memset(&tm, 0, sizeof(tm));
r = GetTextMetricsA(hdc, &tm);
ok(r, "GetTextMetrics failed\n");
ok(tm.tmHeight > tm1.tmHeight,
"expected greater than 1 ppem value (%d), got %d\n", tm1.tmHeight, tm.tmHeight);
ok(tm.tmAveCharWidth > tm1.tmAveCharWidth,
"expected greater than 1 ppem value (%d), got %d\n", tm1.tmAveCharWidth, tm.tmAveCharWidth);
DeleteObject(SelectObject(hdc, hfont_old));
/* test an invalid value */
for (i = 0; i < sizeof(invalid_height)/sizeof(invalid_height[0]); i++) {
lf.lfHeight = invalid_height[i];
hfont = CreateFontIndirectA(&lf);
hfont_old = SelectObject(hdc, hfont);
memset(&tm, 0, sizeof(tm));
r = GetTextMetricsA(hdc, &tm);
ok(r, "GetTextMetrics failed\n");
ok(tm.tmHeight == tm1.tmHeight,
"expected 1 ppem value (%d), got %d\n", tm1.tmHeight, tm.tmHeight);
ok(tm.tmAveCharWidth == tm1.tmAveCharWidth,
"expected 1 ppem value (%d), got %d\n", tm1.tmAveCharWidth, tm.tmAveCharWidth);
DeleteObject(SelectObject(hdc, hfont_old));
}
ReleaseDC(NULL, hdc);
return;
}
static void test_vertical_order(void)
{
struct enum_font_data efd;
LOGFONTA lf;
HDC hdc;
int i, j;
hdc = CreateCompatibleDC(0);
ok(hdc != NULL, "CreateCompatibleDC failed\n");
memset(&lf, 0, sizeof(lf));
lf.lfCharSet = DEFAULT_CHARSET;
lf.lfClipPrecision = CLIP_DEFAULT_PRECIS;
lf.lfHeight = 16;
lf.lfWidth = 16;
lf.lfQuality = DEFAULT_QUALITY;
lf.lfItalic = FALSE;
lf.lfWeight = FW_DONTCARE;
efd.total = 0;
EnumFontFamiliesExA(hdc, &lf, enum_font_data_proc, (LPARAM)&efd, 0);
for (i = 0; i < efd.total; i++)
{
if (efd.lf[i].lfFaceName[0] != '@') continue;
for (j = 0; j < efd.total; j++)
{
if (!strcmp(efd.lf[i].lfFaceName + 1, efd.lf[j].lfFaceName))
{
ok(i > j,"Found vertical font %s before its horizontal version\n", efd.lf[i].lfFaceName);
break;
}
}
}
DeleteDC( hdc );
}
static void test_GetCharWidth32(void)
{
BOOL ret;
HDC hdc;
LOGFONTA lf;
HFONT hfont;
INT bufferA;
INT bufferW;
HWND hwnd;
if (!pGetCharWidth32A || !pGetCharWidth32W)
{
win_skip("GetCharWidth32A/W not available on this platform\n");
return;
}
memset(&lf, 0, sizeof(lf));
strcpy(lf.lfFaceName, "System");
lf.lfHeight = 20;
hfont = CreateFontIndirectA(&lf);
hdc = GetDC(0);
hfont = SelectObject(hdc, hfont);
ret = pGetCharWidth32W(hdc, 'a', 'a', &bufferW);
ok(ret, "GetCharWidth32W should have succeeded\n");
ret = pGetCharWidth32A(hdc, 'a', 'a', &bufferA);
ok(ret, "GetCharWidth32A should have succeeded\n");
ok (bufferA == bufferW, "Widths should be the same\n");
ok (bufferA > 0," Width should be greater than zero\n");
hfont = SelectObject(hdc, hfont);
DeleteObject(hfont);
ReleaseDC(NULL, hdc);
memset(&lf, 0, sizeof(lf));
strcpy(lf.lfFaceName, "Tahoma");
lf.lfHeight = 20;
hfont = CreateFontIndirectA(&lf);
hwnd = CreateWindowExA(0, "static", "", WS_POPUP, 0,0,100,100,
0, 0, 0, NULL);
hdc = GetDC(hwnd);
SetMapMode( hdc, MM_ANISOTROPIC );
SelectObject(hdc, hfont);
ret = pGetCharWidth32W(hdc, 'a', 'a', &bufferW);
ok(ret, "GetCharWidth32W should have succeeded\n");
ok (bufferW > 0," Width should be greater than zero\n");
SetWindowExtEx(hdc, -1,-1,NULL);
SetGraphicsMode(hdc, GM_COMPATIBLE);
ret = pGetCharWidth32W(hdc, 'a', 'a', &bufferW);
ok(ret, "GetCharWidth32W should have succeeded\n");
ok (bufferW > 0," Width should be greater than zero\n");
SetGraphicsMode(hdc, GM_ADVANCED);
ret = pGetCharWidth32W(hdc, 'a', 'a', &bufferW);
ok(ret, "GetCharWidth32W should have succeeded\n");
todo_wine ok (bufferW > 0," Width should be greater than zero\n");
SetWindowExtEx(hdc, 1,1,NULL);
SetGraphicsMode(hdc, GM_COMPATIBLE);
ret = pGetCharWidth32W(hdc, 'a', 'a', &bufferW);
ok(ret, "GetCharWidth32W should have succeeded\n");
ok (bufferW > 0," Width should be greater than zero\n");
SetGraphicsMode(hdc, GM_ADVANCED);
ret = pGetCharWidth32W(hdc, 'a', 'a', &bufferW);
ok(ret, "GetCharWidth32W should have succeeded\n");
ok (bufferW > 0," Width should be greater than zero\n");
ReleaseDC(hwnd, hdc);
DestroyWindow(hwnd);
hwnd = CreateWindowExA(WS_EX_LAYOUTRTL, "static", "", WS_POPUP, 0,0,100,100,
0, 0, 0, NULL);
hdc = GetDC(hwnd);
SetMapMode( hdc, MM_ANISOTROPIC );
SelectObject(hdc, hfont);
ret = pGetCharWidth32W(hdc, 'a', 'a', &bufferW);
ok(ret, "GetCharWidth32W should have succeeded\n");
ok (bufferW > 0," Width should be greater than zero\n");
SetWindowExtEx(hdc, -1,-1,NULL);
SetGraphicsMode(hdc, GM_COMPATIBLE);
ret = pGetCharWidth32W(hdc, 'a', 'a', &bufferW);
ok(ret, "GetCharWidth32W should have succeeded\n");
ok (bufferW > 0," Width should be greater than zero\n");
SetGraphicsMode(hdc, GM_ADVANCED);
ret = pGetCharWidth32W(hdc, 'a', 'a', &bufferW);
ok(ret, "GetCharWidth32W should have succeeded\n");
ok (bufferW > 0," Width should be greater than zero\n");
SetWindowExtEx(hdc, 1,1,NULL);
SetGraphicsMode(hdc, GM_COMPATIBLE);
ret = pGetCharWidth32W(hdc, 'a', 'a', &bufferW);
ok(ret, "GetCharWidth32W should have succeeded\n");
ok (bufferW > 0," Width should be greater than zero\n");
SetGraphicsMode(hdc, GM_ADVANCED);
ret = pGetCharWidth32W(hdc, 'a', 'a', &bufferW);
ok(ret, "GetCharWidth32W should have succeeded\n");
todo_wine ok (bufferW > 0," Width should be greater than zero\n");
ReleaseDC(hwnd, hdc);
DestroyWindow(hwnd);
DeleteObject(hfont);
}
static void test_fake_bold_font(void)
{
HDC hdc;
HFONT hfont, hfont_old;
LOGFONTA lf;
BOOL ret;
TEXTMETRICA tm[2];
ABC abc[2];
INT w[2];
if (!pGetCharWidth32A || !pGetCharABCWidthsA) {
win_skip("GetCharWidth32A/GetCharABCWidthA is not available on this platform\n");
return;
}
/* Test outline font */
memset(&lf, 0, sizeof(lf));
strcpy(lf.lfFaceName, "Wingdings");
lf.lfWeight = FW_NORMAL;
lf.lfCharSet = SYMBOL_CHARSET;
hfont = CreateFontIndirectA(&lf);
hdc = GetDC(NULL);
hfont_old = SelectObject(hdc, hfont);
/* base metrics */
ret = GetTextMetricsA(hdc, &tm[0]);
ok(ret, "got %d\n", ret);
ret = pGetCharABCWidthsA(hdc, 0x76, 0x76, &abc[0]);
ok(ret, "got %d\n", ret);
lf.lfWeight = FW_BOLD;
hfont = CreateFontIndirectA(&lf);
DeleteObject(SelectObject(hdc, hfont));
/* bold metrics */
ret = GetTextMetricsA(hdc, &tm[1]);
ok(ret, "got %d\n", ret);
ret = pGetCharABCWidthsA(hdc, 0x76, 0x76, &abc[1]);
ok(ret, "got %d\n", ret);
DeleteObject(SelectObject(hdc, hfont_old));
ReleaseDC(NULL, hdc);
/* compare results (outline) */
ok(tm[0].tmHeight == tm[1].tmHeight, "expected %d, got %d\n", tm[0].tmHeight, tm[1].tmHeight);
ok(tm[0].tmAscent == tm[1].tmAscent, "expected %d, got %d\n", tm[0].tmAscent, tm[1].tmAscent);
ok(tm[0].tmDescent == tm[1].tmDescent, "expected %d, got %d\n", tm[0].tmDescent, tm[1].tmDescent);
ok((tm[0].tmAveCharWidth + 1) == tm[1].tmAveCharWidth,
"expected %d, got %d\n", tm[0].tmAveCharWidth + 1, tm[1].tmAveCharWidth);
ok((tm[0].tmMaxCharWidth + 1) == tm[1].tmMaxCharWidth,
"expected %d, got %d\n", tm[0].tmMaxCharWidth + 1, tm[1].tmMaxCharWidth);
ok(tm[0].tmOverhang == tm[1].tmOverhang, "expected %d, got %d\n", tm[0].tmOverhang, tm[1].tmOverhang);
w[0] = abc[0].abcA + abc[0].abcB + abc[0].abcC;
w[1] = abc[1].abcA + abc[1].abcB + abc[1].abcC;
ok((w[0] + 1) == w[1], "expected %d, got %d\n", w[0] + 1, w[1]);
}
static void test_bitmap_font_glyph_index(void)
{
const WCHAR text[] = {'#','!','/','b','i','n','/','s','h',0};
const struct {
LPCSTR face;
BYTE charset;
} bitmap_font_list[] = {
{ "Courier", ANSI_CHARSET },
{ "Small Fonts", ANSI_CHARSET },
{ "Fixedsys", DEFAULT_CHARSET },
{ "System", DEFAULT_CHARSET }
};
HDC hdc;
LOGFONTA lf;
HFONT hFont;
CHAR facename[LF_FACESIZE];
BITMAPINFO bmi;
HBITMAP hBmp[2];
void *pixels[2];
int i, j;
DWORD ret;
BITMAP bmp;
TEXTMETRICA tm;
CHARSETINFO ci;
BYTE chr = '\xA9';
if (!pGetGlyphIndicesW || !pGetGlyphIndicesA) {
win_skip("GetGlyphIndices is unavailable\n");
return;
}
hdc = CreateCompatibleDC(0);
ok(hdc != NULL, "CreateCompatibleDC failed\n");
memset(&bmi, 0, sizeof(bmi));
bmi.bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
bmi.bmiHeader.biBitCount = 32;
bmi.bmiHeader.biPlanes = 1;
bmi.bmiHeader.biWidth = 128;
bmi.bmiHeader.biHeight = 32;
bmi.bmiHeader.biCompression = BI_RGB;
for (i = 0; i < sizeof(bitmap_font_list)/sizeof(bitmap_font_list[0]); i++) {
memset(&lf, 0, sizeof(lf));
lf.lfCharSet = bitmap_font_list[i].charset;
strcpy(lf.lfFaceName, bitmap_font_list[i].face);
hFont = CreateFontIndirectA(&lf);
ok(hFont != NULL, "Can't create font (%s:%d)\n", lf.lfFaceName, lf.lfCharSet);
hFont = SelectObject(hdc, hFont);
ret = GetTextMetricsA(hdc, &tm);
ok(ret, "GetTextMetric failed\n");
ret = GetTextFaceA(hdc, sizeof(facename), facename);
ok(ret, "GetTextFace failed\n");
if (tm.tmPitchAndFamily & TMPF_TRUETYPE) {
skip("TrueType font (%s) was selected for \"%s\"\n", facename, bitmap_font_list[i].face);
continue;
}
if (lstrcmpiA(facename, lf.lfFaceName) != 0) {
skip("expected %s, got %s\n", lf.lfFaceName, facename);
continue;
}
for (j = 0; j < 2; j++) {
HBITMAP hBmpPrev;
hBmp[j] = CreateDIBSection(hdc, &bmi, DIB_RGB_COLORS, &pixels[j], NULL, 0);
ok(hBmp[j] != NULL, "Can't create DIB\n");
hBmpPrev = SelectObject(hdc, hBmp[j]);
switch (j) {
case 0:
ret = ExtTextOutW(hdc, 0, 0, 0, NULL, text, lstrlenW(text), NULL);
break;
case 1:
{
int len = lstrlenW(text);
LPWORD indices = HeapAlloc(GetProcessHeap(), 0, len * sizeof(WORD));
ret = pGetGlyphIndicesW(hdc, text, len, indices, 0);
ok(ret, "GetGlyphIndices failed\n");
ok(memcmp(indices, text, sizeof(WORD) * len) == 0,
"Glyph indices and text are different for %s:%d\n", lf.lfFaceName, tm.tmCharSet);
ret = ExtTextOutW(hdc, 0, 0, ETO_GLYPH_INDEX, NULL, indices, len, NULL);
HeapFree(GetProcessHeap(), 0, indices);
break;
}
}
ok(ret, "ExtTextOutW failed\n");
SelectObject(hdc, hBmpPrev);
}
GetObjectA(hBmp[0], sizeof(bmp), &bmp);
ok(memcmp(pixels[0], pixels[1], bmp.bmHeight * bmp.bmWidthBytes) == 0,
"Images are different (%s:%d)\n", lf.lfFaceName, tm.tmCharSet);
ret = TranslateCharsetInfo((LPDWORD)(DWORD_PTR)tm.tmCharSet, &ci, TCI_SRCCHARSET);
if (!ret) {
skip("Can't get charset info for (%s:%d)\n", lf.lfFaceName, tm.tmCharSet);
goto next;
}
if (IsDBCSLeadByteEx(ci.ciACP, chr)) {
skip("High-ascii character is not defined in codepage %d\n", ci.ciACP);
goto next;
}
for (j = 0; j < 2; j++) {
HBITMAP hBmpPrev;
WORD code;
hBmpPrev = SelectObject(hdc, hBmp[j]);
switch (j) {
case 0:
ret = ExtTextOutA(hdc, 100, 0, 0, NULL, (LPCSTR)&chr, 1, NULL);
break;
case 1:
ret = pGetGlyphIndicesA(hdc, (LPCSTR)&chr, 1, &code, 0);
ok(ret, "GetGlyphIndices failed\n");
ok(code == chr, "expected %02x, got %02x (%s:%d)\n", chr, code, lf.lfFaceName, tm.tmCharSet);
ret = ExtTextOutA(hdc, 100, 0, ETO_GLYPH_INDEX, NULL, (LPCSTR)&code, 1, NULL);
break;
}
ok(ret, "ExtTextOutA failed\n");
SelectObject(hdc, hBmpPrev);
}
ok(memcmp(pixels[0], pixels[1], bmp.bmHeight * bmp.bmWidthBytes) == 0,
"Images are different (%s:%d)\n", lf.lfFaceName, tm.tmCharSet);
next:
for (j = 0; j < 2; j++)
DeleteObject(hBmp[j]);
hFont = SelectObject(hdc, hFont);
DeleteObject(hFont);
}
DeleteDC(hdc);
}
START_TEST(font)
{
init();
test_stock_fonts();
test_logfont();
test_bitmap_font();
test_outline_font();
test_bitmap_font_metrics();
test_GdiGetCharDimensions();
test_GetCharABCWidths();
test_text_extents();
test_GetGlyphIndices();
test_GetKerningPairs();
test_GetOutlineTextMetrics();
test_SetTextJustification();
test_font_charset();
test_GdiGetCodePage();
test_GetFontUnicodeRanges();
test_nonexistent_font();
test_orientation();
test_height_selection();
test_AddFontMemResource();
test_EnumFonts();
/* On Windows Arial has a lot of default charset aliases such as Arial Cyr,
* I'd like to avoid them in this test.
*/
test_EnumFontFamilies("Arial Black", ANSI_CHARSET);
test_EnumFontFamilies("Symbol", SYMBOL_CHARSET);
if (is_truetype_font_installed("Arial Black") &&
(is_truetype_font_installed("Symbol") || is_truetype_font_installed("Wingdings")))
{
test_EnumFontFamilies("", ANSI_CHARSET);
test_EnumFontFamilies("", SYMBOL_CHARSET);
test_EnumFontFamilies("", DEFAULT_CHARSET);
}
else
skip("Arial Black or Symbol/Wingdings is not installed\n");
test_EnumFontFamiliesEx_default_charset();
test_GetTextMetrics();
test_GdiRealizationInfo();
test_GetTextFace();
test_GetGlyphOutline();
test_GetTextMetrics2("Tahoma", -11);
test_GetTextMetrics2("Tahoma", -55);
test_GetTextMetrics2("Tahoma", -110);
test_GetTextMetrics2("Arial", -11);
test_GetTextMetrics2("Arial", -55);
test_GetTextMetrics2("Arial", -110);
test_CreateFontIndirect();
test_CreateFontIndirectEx();
test_oemcharset();
test_fullname();
test_fullname2();
test_east_asian_font_selection();
test_max_height();
test_vertical_order();
test_GetCharWidth32();
test_fake_bold_font();
test_bitmap_font_glyph_index();
/* These tests should be last test until RemoveFontResource
* is properly implemented.
*/
test_vertical_font();
test_CreateScalableFontResource();
}
| 39.16145 | 210 | 0.604699 | [
"render"
] |
fa3c7b28cb1f47f528c5151d3b3a941779447184 | 4,852 | h | C | src/Patch/Types.h | gmh5225/QBDI | d31872adae1099ac74a2e2238f909ad1e63cc3e8 | [
"Apache-2.0"
] | null | null | null | src/Patch/Types.h | gmh5225/QBDI | d31872adae1099ac74a2e2238f909ad1e63cc3e8 | [
"Apache-2.0"
] | null | null | null | src/Patch/Types.h | gmh5225/QBDI | d31872adae1099ac74a2e2238f909ad1e63cc3e8 | [
"Apache-2.0"
] | null | null | null | /*
* This file is part of QBDI.
*
* Copyright 2017 - 2021 Quarkslab
*
* 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 TYPES_H
#define TYPES_H
#include <vector>
#include "ExecBlock/Context.h"
#include "Patch/Register.h"
#include "QBDI/State.h"
namespace QBDI {
/*! Structure representing a register variable in PatchDSL.
*/
struct Reg {
unsigned int id;
public:
using Vec = std::vector<Reg>;
/*! Create a new register variable.
*
* @param[in] id The id of the register to represent.
*/
inline Reg(unsigned int id) : id(id){};
/*! Convert this structure to an LLVM register id.
*
* @return LLVM register id.
*/
inline operator unsigned int() const { return GPR_ID[id]; }
/*! Get back the id of the register in GPRState
*
* @return GPRState register id.
*/
inline unsigned int getID() const { return id; }
/*! Return the offset of this register storage in the context part of the data
* block.
*
* @return The offset.
*/
inline rword offset() const {
return offsetof(Context, gprState) + sizeof(rword) * id;
}
};
/*! Structure representing a shadow variable in PatchDSL.
*/
struct Shadow {
uint16_t tag;
public:
/*! Allocate a new shadow variable in the data block with the corresponding
* tag.
*
* @param[in] tag The tag of the new shadow variable.
*/
inline Shadow(uint16_t tag) : tag(tag) {}
/*! Return the tag associated with this shadow variable.
*
* @return The tag of the shadow variable.
*/
inline rword getTag() const { return tag; }
};
enum ShadowReservedTag : uint16_t {
// MemoryAccess Tag
MEMORY_TAG_BEGIN = 0xffe0,
MEMORY_TAG_END = 0xfff0,
// also defined in Callback.h
Untagged = 0xffff,
};
/*! Structure representing a constant value in PatchDSL.
*/
struct Constant {
rword v;
/*! Represent a constant value.
*
* @param[in] v The represented value.
*/
inline Constant(rword v) : v(v) {}
/*! Convert this structure to its value.
*
* @return This constant value.
*/
inline operator rword() const { return v; }
};
/*! Structure representing a memory offset variable in PatchDSL.
*/
struct Offset {
int64_t offset;
public:
/*! Allocate a new offset variable with its offset value.
*
* @param[in] offset The offset value
*/
inline Offset(int64_t offset) : offset(offset) {}
/*! Allocate a new offset variable with the offset in the context of a
* specific register.
*
* @param[in] reg The register whose offset to represent.
*/
inline Offset(Reg reg) : offset(reg.offset()) {}
/*! Convert this structure to its value.
*
* @return This offset value.
*/
inline operator int64_t() const { return offset; }
};
/*! Structure representing a temporary register variable in PatchDSL.
*/
struct Temp {
unsigned int id;
public:
/*! Represent a temporary register variable idenified by a unique ID. Inside a
* patch rules or a instrumentation rules, Temp with identical ids point to
* the same physical register. The id 0xFFFFFFFF is reserved for internal
* uses. The mapping from id to physical register is determined at generation
* time and the allocation and deallocation instructions are automatically
* added to the patch.
*
* @param[in] id The id of the temp to represent.
*/
inline Temp(unsigned int id) : id(id) {}
/*! Convert this Temp to its id.
*
* @return This Temp id.
*/
inline operator unsigned int() const { return id; }
};
/*! Structure representing an operand instruction variable in PatchDSL.
*/
struct Operand {
unsigned int idx;
public:
/*! Represent an operand instruction identified by its index in the LLVM
* MCInst representation of the instruction.
*
* @param[in] idx The operand index.
*/
inline Operand(unsigned int idx) : idx(idx) {}
/*! Convert this Operand to its idx.
*
* @return This Operand idx.
*/
inline operator unsigned int() const { return idx; }
};
/* Tag value for RelocatableInst
*/
enum RelocatableInstTag {
RelocInst = 0,
RelocTagPreInstMemAccess = 0x10,
RelocTagPreInstStdCBK = 0x11,
RelocTagPatchBegin = 0x20,
RelocTagPatchEnd = 0x21,
RelocTagPostInstMemAccess = 0x30,
RelocTagPostInstStdCBK = 0x31,
RelocTagInvalid = 0xff,
};
} // namespace QBDI
#endif // TYPES_H
| 23.668293 | 80 | 0.681781 | [
"vector"
] |
fa3dbfd87ef8f70d47b611b228c36404907e26dd | 526 | h | C | Code/Framework/AzQtComponents/AzQtComponents/Gallery/TreeViewPage.h | cypherdotXd/o3de | bb90c4ddfe2d495e9c00ebf1e2650c6d603a5676 | [
"Apache-2.0",
"MIT"
] | 11 | 2021-07-08T09:58:26.000Z | 2022-03-17T17:59:26.000Z | Code/Framework/AzQtComponents/AzQtComponents/Gallery/TreeViewPage.h | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 29 | 2021-07-06T19:33:52.000Z | 2022-03-22T10:27:49.000Z | Code/Framework/AzQtComponents/AzQtComponents/Gallery/TreeViewPage.h | RoddieKieley/o3de | e804fd2a4241b039a42d9fa54eaae17dc94a7a92 | [
"Apache-2.0",
"MIT"
] | 4 | 2021-07-06T19:24:43.000Z | 2022-03-31T12:42:27.000Z | /*
* Copyright (c) Contributors to the Open 3D Engine Project.
* For complete copyright and license terms please see the LICENSE at the root of this distribution.
*
* SPDX-License-Identifier: Apache-2.0 OR MIT
*
*/
#pragma once
#if !defined(Q_MOC_RUN)
#include <QWidget>
#include <QScopedPointer>
#endif
namespace Ui
{
class TreeViewPage;
}
class TreeViewPage
: public QWidget
{
Q_OBJECT
public:
explicit TreeViewPage(QWidget* parent = nullptr);
private:
QScopedPointer<Ui::TreeViewPage> ui;
};
| 16.967742 | 100 | 0.718631 | [
"3d"
] |
fa42b1ad14881c11540e6f86557e550604e3cd36 | 26,320 | h | C | hal/nRF/nRF5_SDK/external/infineon/optiga/include/optiga/optiga_crypt.h | yhsb2k/omef | 7425b62dd4b5d0af4e320816293f69d16d39f57a | [
"MIT"
] | 15 | 2019-02-25T20:25:29.000Z | 2021-02-27T17:57:38.000Z | hal/nRF/nRF5_SDK/external/infineon/optiga/include/optiga/optiga_crypt.h | yhsb2k/omef | 7425b62dd4b5d0af4e320816293f69d16d39f57a | [
"MIT"
] | 3 | 2020-02-21T22:35:38.000Z | 2020-10-05T02:25:30.000Z | hal/nRF/nRF5_SDK/external/infineon/optiga/include/optiga/optiga_crypt.h | yhsb2k/omef | 7425b62dd4b5d0af4e320816293f69d16d39f57a | [
"MIT"
] | 9 | 2021-03-30T06:15:51.000Z | 2022-03-20T20:39:36.000Z | /**
* MIT License
*
* Copyright (c) 2018 Infineon Technologies AG
*
* 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
*
* \brief This file implements the prototype declarations of OPTIGA Crypt.
*
* \addtogroup grOptigaCrypt
* @{
*/
#ifndef _OPTIGA_CRYPT_H_
#define _OPTIGA_CRYPT_H_
#ifdef __cplusplus
extern "C" {
#endif
#include "optiga/common/Datatypes.h"
#include "optiga/cmd/CommandLib.h"
/**
* OPTIGA crypt module return values
*/
///OPTIGA crypt API execution is successful
#define OPTIGA_CRYPT_SUCCESS (0x0000)
///OPTIGA crypt module in busy state
#define OPTIGA_CRYPT_BUSY (0x0001)
///OPTIGA crypt API failed
#define OPTIGA_CRYPT_ERROR (0x0402)
///OPTIGA crypt API called with invalid inputs
#define OPTIGA_CRYPT_ERROR_INVALID_INPUT (0x0403)
///OPTIGA crypt API called with insufficient memory buffer
#define OPTIGA_CRYPT_ERROR_MEMORY_INSUFFICIENT (0x0404)
///OPTIGA crypt API called when, a request of same instance is already in service
#define OPTIGA_CRYPT_ERROR_INSTANCE_IN_USE (0x0405)
/**
* \brief Typedef for Key IDs
* The KEY_STORE_ID_xxx holds only private key
*
* The SESSION_ID_xxx can hold private key, premaster secret(ECDH) and master secret(PRF).
* But only one at a time.
*/
typedef enum optiga_key_id
{
/// Key from key store (non-volatile)
OPTIGA_KEY_STORE_ID_E0F0 = 0xE0F0,
/// Key from key store (non-volatile)
OPTIGA_KEY_STORE_ID_E0F1 = 0xE0F1,
/// Key from key store (non-volatile)
OPTIGA_KEY_STORE_ID_E0F2 = 0xE0F2,
/// Key from key store (non-volatile)
OPTIGA_KEY_STORE_ID_E0F3 = 0xE0F3,
/// Key from Session context id 1 (volatile)
OPTIGA_SESSION_ID_E100 = 0xE100,
/// Key from Session context id 2 (volatile)
OPTIGA_SESSION_ID_E101 = 0xE101,
/// Key from Session context id 3 (volatile)
OPTIGA_SESSION_ID_E102 = 0xE102,
/// Key from Session context id 4 (volatile)
OPTIGA_SESSION_ID_E103 = 0xE103,
} optiga_key_id_t;
/**
* OPTIGA Random Generation types
*/
typedef enum optiga_rng_types
{
/// Generate Random data using TRNG
OPTIGA_RNG_TYPE_TRNG = 0x00,
/// Generate Random data using DRNG
OPTIGA_RNG_TYPE_DRNG = 0x01,
} optiga_rng_types_t;
typedef enum optiga_ecc_curve
{
//TBD: values to be aligned as per the specification
///
OPTIGA_ECC_NIST_P_256 = 0x03,
///
OPTIGA_ECC_NIST_P_384 = 0x04,
} optiga_ecc_curve_t;
typedef enum optiga_key_usage
{
/// This enables the private key for the signature generation as part of authentication commands
OPTIGA_KEY_USAGE_AUTHENTICATION = 0x01,
/// This enables the private key for the signature generation
OPTIGA_KEY_USAGE_SIGN = 0x10,
/// This enables the private key for key agreement (e.g. ecdh operations)
OPTIGA_KEY_USAGE_KEY_AGREEMENT = 0x20,
} optiga_key_usage_t;
/**
* \brief To specify the hash context information.
*/
typedef struct optiga_hash_context
{
///buffer to hold the context data
uint8_t * context_buffer;
///context length
uint16_t context_buffer_length;
///hashing algorithm
uint8_t hash_algo;
} optiga_hash_context_t;
/**
* \brief Specifies the hashing algorithm type in OPTIGA.
*/
typedef enum optiga_hash_type
{
/// Hash algorithm type SHA256
OPTIGA_HASH_TYPE_SHA_256 = 0xE2
} optiga_hash_type_t;
/** @brief Data is provided by host*/
#define OPTIGA_CRYPT_HOST_DATA (0x01)
/** @brief Data in internal to optiga OID */
#define OPTIGA_CRYPT_OID_DATA (0x00)
/**
* \brief To specify the data coming from the host for hashing.
*/
typedef struct hash_data_from_host
{
/// data for hashing
const uint8_t * buffer;
/// data length for hashing
uint32_t length;
} hash_data_from_host_t;
/**
* \brief To specify the data object for hashing.
*/
typedef struct hash_data_in_optiga
{
///OID of data object
uint16_t oid;
///Offset within the data object
uint16_t offset;
///Number of data bytes starting from the offset
uint16_t length;
} hash_data_in_optiga_t;
/**
* \brief To specifiy the Public Key details (key, size and algorithm)
*/
typedef struct public_key_from_host
{
/// Public Key
uint8_t * public_key;
/// Length of public key
uint16_t length;
/// Public key algorithm
uint8_t curve;
} public_key_from_host_t;
/**
* \brief To specify the OID which holds the shared secret.
*/
typedef struct key_from_opitga
{
///
uint16_t key_oid;
} optiga_shared_secret_t;
/**
* @brief Generates a random number.
*
* Generates the requested random stream of data for the user provided length.<br>
*
*
*<b>Pre Conditions:</b>
* - The application on OPTIGA must be opened using optiga_util_open_application before using this API.<br>
*
*<b>API Details:</b>
* - Invokes optiga_cmd_get_random API, based on the input arguments to retrieve random data .<br>
*<br>
*
*<b>Notes:</b>
* - Error codes from lower layers will be returned as it is.<br>
* - The maximum value of the <b>random_data_length</b> parameter is size of buffer <b>random_data</b>.
* In case the value is greater than buffer size, memory corruption can occur.<br>
*
* \param[in] rng_type Type of random data generator.
* - The input must be from optiga_rng_type.
* - Argument check for rng_type is not done since OPTIGA will provide an error for invalid rng_type.
* \param[in,out] random_data Pointer to the buffer into which random data is stored, must not be NULL.
* \param[in] random_data_length Length of random data to be generated.
* - Range should be 8 - 256 bytes.
* - Length validation is not done, since OPTIGA will provide an error for invalid random_data_length.
*
* \retval OPTIGA_CRYPT_SUCCESS Successful invocation of optiga cmd module
* \retval OPTIGA_CRYPT_ERROR_INVALID_INPUT Wrong Input arguments provided
* \retval OPTIGA_CRYPT_ERROR_INSTANCE_IN_USE Same instance with ongoing request servicing is used
* \retval OPTIGA_DEVICE_ERROR Command execution failure in OPTIGA and the LSB indicates the error code.(Refer Solution Reference Manual)
*/
LIBRARY_EXPORTS optiga_lib_status_t optiga_crypt_random(optiga_rng_types_t rng_type,
uint8_t * random_data,
uint16_t random_data_length);
/**
*
* @brief Initializes a hash context.
*
* Sets up a hash context and exports it.<br>
*
*<b>Pre Conditions:</b>
* - The application on OPTIGA must be opened using optiga_util_open_application before using this API.<br>
*
*<b>API Details:</b><br>
* - Initializes a new hash context.<br>
* - Exports the hash context to caller.<br>
*
*<b>Notes:</b><br>
* - Error codes from lower layer will be returned as it is.<br>
* - User must save the output hash context for further usage as OPTIGA does not store it internally.<br>
*
*<br>
* \param[inout] hash_ctx Pointer to optiga_hash_context_t to store the hash context from OPTIGA
* - The input <b>hash_algo</b> in <b>hash_ctx</b> must be from optiga_hash_type.
*
* \retval OPTIGA_CRYPT_SUCCESS Successful invocation of optiga cmd module
* \retval OPTIGA_CRYPT_ERROR_INVALID_INPUT Wrong Input arguments provided
* \retval OPTIGA_CRYPT_ERROR_INSTANCE_IN_USE Same instance with ongoing request servicing is used
* \retval OPTIGA_DEVICE_ERROR Command execution failure in OPTIGA and the LSB indicates the error code.(Refer Solution Reference Manual)
*/
LIBRARY_EXPORTS optiga_lib_status_t optiga_crypt_hash_start(optiga_hash_context_t * hash_ctx);
/**
*
* @brief Updates a hash context with the input data.
*
* Updates hashing for the given data and hash context then export the updated hash context.<br>
*
*
*<b>Pre Conditions:</b>
* - The application on OPTIGA must be opened using optiga_util_open_application before using this API.<br>
* - optiga_hash_context_t from optiga_crypt_hash_start or optiga_crypt_hash_update must be available.
*
*<b>API Details:</b><br>
* - Update the input hash context.<br>
* - Exports the hash context to caller.<br>
*
*<b>Notes:</b><br>
* - Error codes from lower layer will be returned as it is.<br>
* - User must save the output hash context for further usage as OPTIGA does not store it internally.<br>
*
*<br>
* \param[in] hash_ctx Pointer to optiga_hash_context_t containing hash context from OPTIGA, must not be NULL
* \param[in] source_of_data_to_hash Data from host / Data in optiga. Must be one of the below
* - OPTIGA_CRYPT_HOST_DATA,if source of data is from Host.
* - OPTIGA_CRYPT_OID_DATA,if the source of data is from OPITGA.
* \param[in] data_to_hash Data for hashing either in hash_data_from_host or in hash_data_in_optiga
*
* \retval OPTIGA_CRYPT_SUCCESS Successful invocation of optiga cmd module
* \retval OPTIGA_CRYPT_ERROR_INVALID_INPUT Wrong Input arguments provided
* \retval OPTIGA_CRYPT_ERROR_INSTANCE_IN_USE Same instance with ongoing request servicing is used
* \retval OPTIGA_DEVICE_ERROR Command execution failure in OPTIGA and the LSB indicates the error code.(Refer Solution Reference Manual)
*/
LIBRARY_EXPORTS optiga_lib_status_t optiga_crypt_hash_update(optiga_hash_context_t * hash_ctx,
uint8_t source_of_data_to_hash,
void * data_to_hash);
/**
*
* @brief Finalizes and exports the hash output.
*
* Finalizes the hash context and returns hash as output.<br>
*
*<b>Pre Conditions:</b>
* - The application on OPTIGA must be opened using optiga_util_open_application before using this API.<br>
* - optiga_hash_context_t from optiga_crypt_hash_start or optiga_crypt_hash_update must be available.
*
*<b>API Details:</b><br>
* - Finalize the hash from the input hash context
* - Exports the finalized hash.
*
*<b>Notes:</b><br>
* - Error codes from lower layer will be returned as it is.<br>
* - hash context is not updated by this API. This can be used later to fulfill intermediate hash use-cases<br>
* - User must save the output hash context for further usage as OPTIGA does not store it internally.<br>
*
*<br>
* \param[in] hash_ctx Pointer to optiga_hash_context_t containing hash context from OPTIGA, must not be NULL
* \param[inout] hash_output Output Hash
*
* \retval OPTIGA_CRYPT_SUCCESS Successful invocation of optiga cmd module
* \retval OPTIGA_CRYPT_ERROR_INVALID_INPUT Wrong Input arguments provided
* \retval OPTIGA_CRYPT_ERROR_INSTANCE_IN_USE Same instance with ongoing request servicing is used
* \retval OPTIGA_DEVICE_ERROR Command execution failure in OPTIGA and the LSB indicates the error code.(Refer Solution Reference Manual)
*/
LIBRARY_EXPORTS optiga_lib_status_t optiga_crypt_hash_finalize(optiga_hash_context_t * hash_ctx,
uint8_t * hash_output);
/**
*
* @brief Generates an key pair based on ECC curves.
*
* Generates an ECC key-pair based on the type of the key.<br>
*
*
*<b>Pre Conditions:</b>
* - The application on OPTIGA must be opened using optiga_util_open_application before using this API.<br>
*
*<b>API Details:</b>
* - Generate an ECC key pair using OPTIGA.<br>
* - If export is requested, Exports the private key else stores it in the input private key OID.<br>
* - Exports the public key always.<br>
*<br>
*
*<b>Notes:</b>
* - Error codes from lower layers will be returned as it is.<br>
*
* \param[in] curve_id ECC curve id.
* \param[in] key_usage Key usage defined by optiga_key_usage_t.
* - Values from optiga_key_usage can be logically ORed and passed.<br>
* - It is ignored if export_private_key is FALSE (0).
* \param[in] export_private_key TRUE (1) - Exports both private key and public key to the host.<br>
* FALSE (0) - Exports only public key to the host. The input key_usage is ignored.
* \param[in] private_key Buffer to store private key or private key OID of OPTIGA, must not be NULL.
* - If export_private_key is TRUE, assign pointer to a buffer to store private key.
* - The size of the buffer must be sufficient enough to accommodate the key type and additional DER encoding formats.
* - If export_private_key is FALSE, assign pointer to variable of type optiga_key_id_t.
* \param[in,out] public_key Buffer to store public key, must not be NULL.
* \param[in] public_key_length Initially set as length of public_key, later updated as actual length of public_key.
*
* \retval OPTIGA_CRYPT_SUCCESS Successful invocation of optiga cmd module
* \retval OPTIGA_CRYPT_ERROR_INVALID_INPUT Wrong Input arguments provided
* \retval OPTIGA_CRYPT_ERROR_INSTANCE_IN_USE Same instance with ongoing request servicing is used
* \retval OPTIGA_DEVICE_ERROR Command execution failure in OPTIGA and the LSB indicates the error code.(Refer Solution Reference Manual)
*/
LIBRARY_EXPORTS optiga_lib_status_t optiga_crypt_ecc_generate_keypair(optiga_ecc_curve_t curve_id,
uint8_t key_usage,
bool_t export_private_key,
void * private_key,
uint8_t * public_key,
uint16_t * public_key_length);
/**
*
* @brief Generates a signature for the given digest.
*
* Generates a signature for the given digest using private key stored in OPTIGA.<br>
*
*
*<b>Pre Conditions:</b>
* - The application on OPTIGA must be opened using optiga_util_open_application before using this API.<br>.
*
*<b>API Details:</b>
* - Generated signature for the input digest.<br>
* - Exports the generated signature.<br>
*<br>
*
*<b>Notes:</b>
* - Error codes from lower layers will be returned as it is.<br>
*
* \param[in] digest Digest on which signature is generated.
* \param[in] digest_length Length of the input digest.
* \param[in] private_key Private key OID to generate signature.
* \param[in,out] signature Generated signature, must not be NULL.
* - The size of the buffer must be sufficient enough to accommodate the additional DER encoding formatting for R and S components of signature.
* \param[in] signature_length Length of signature.Intial value set as length of buffer, later updated as the actual length of generated signature.
*
* \retval OPTIGA_CRYPT_SUCCESS Successful invocation of optiga cmd module
* \retval OPTIGA_CRYPT_ERROR_INVALID_INPUT Wrong Input arguments provided
* \retval OPTIGA_CRYPT_ERROR_INSTANCE_IN_USE Same instance with ongoing request servicing is used
* \retval OPTIGA_DEVICE_ERROR Command execution failure in OPTIGA and the LSB indicates the error code.(Refer Solution Reference Manual)
*/
LIBRARY_EXPORTS optiga_lib_status_t optiga_crypt_ecdsa_sign(uint8_t * digest,
uint8_t digest_length,
optiga_key_id_t private_key,
uint8_t * signature,
uint16_t * signature_length);
/**
*
* @brief Verifies the signature over the given digest.
*
* Verifies the signature over a given digest provided with the input data.<br>
*
*<b>Pre Conditions:</b>
* - The application on OPTIGA must be opened using optiga_util_open_application.<br>
*
*<b>API Details:</b>
* - Verifies the signature over the given provided with the input data using public key.
*
*<b>Notes:</b>
* - Error codes from lower layers will be returned as it is to the application.<br>
*
* \param[in] digest Pointer to a given digest buffer, must not be NULL.
* \param[in] digest_length Length of digest
* \param[in] signature Pointer to a given signature buffer, must not be NULL.
* \param[in] signature_length Length of signature
* \param[in] public_key_source_type Public key from host / public key of certificate OID from OPTIGA. Value must be one of the below
* - OPTIGA_CRYPT_OID_DATA, if the public key is to used from the certificate data object from OPTIGA.
* - OPTIGA_CRYPT_HOST_DATA, if the public key is provided by host.
* \param[in] public_key Public key from host / public key of certificate OID. Value must be one of the below
* - For certificate OID, pointer OID value must be passed.
* - For Public key from host, pointer to public_key_from_host_t instance.
*
* \retval OPTIGA_CRYPT_SUCCESS Successful invocation of optiga cmd module
* \retval OPTIGA_CRYPT_ERROR_INVALID_INPUT Wrong Input arguments provided
* \retval OPTIGA_CRYPT_ERROR_INSTANCE_IN_USE Same instance with ongoing request servicing is used
* \retval OPTIGA_DEVICE_ERROR Command execution failure in OPTIGA and the LSB indicates the error code.(Refer Solution Reference Manual)
*/
LIBRARY_EXPORTS optiga_lib_status_t optiga_crypt_ecdsa_verify(uint8_t * digest,
uint8_t digest_length,
uint8_t * signature,
uint16_t signature_length,
uint8_t public_key_source_type,
void * public_key);
/**
* @brief Calculates the shared secret using ECDH algorithm.
*
* Calculates the shared secret using ECDH algorithm.<br>
*
*
*<b>Pre Conditions:</b>
* - The application on OPTIGA must be opened using optiga_util_open_application.<br>
* - There must be a secret available in the "session context / data object OID" provided as input parameter.<br>
*
*<b>API Details:</b>
* - Calculates the shared secret based on input private key object ID and public key.<br>
* - Based on user request(export_to_host), the shared secret can either be exported to the host or be stored in the acquired session object ID.<br>
*<br>
*
*<b>Notes:</b>
* - Error codes from lower layers will be returned as it is.<br>
* - The buffer size for shared secret should be appropriately provided by the user
* - If the user provides <b>private_key</b> as session based and <b>export_to_host</b> as FALSE,<br>
* then the shared secret generated will overwrite the private key stored in the session object ID
*
* \param[in] private_key Object ID of the private key stored in OPTIGA.<br>
* - Possible values are from the optiga_key_id_t <br>
* - Argument check for private_key is not done since OPTIGA will provide an error for invalid private_key.
* \param[in] public_key Pointer to the public key structure for shared secret generation with its properties, must not be NULL.<br>
* - Provide the inputs according to the structure type public_key_from_host_t
* \param[in] export_to_host TRUE (1) - Exports the generated shared secret to Host. <br>
* FALSE (0) - Stores the generated shared secret into the session object ID acquired by the instance.
* \param[in,out] shared_secret Pointer to the shared secret buffer, only if <b>export_to_host</b> is TRUE. <br>
* Otherwise supply NULL as input.
*
* \retval OPTIGA_CRYPT_SUCCESS Successful invocation of optiga cmd module
* \retval OPTIGA_CRYPT_ERROR_INVALID_INPUT Wrong Input arguments provided
* \retval OPTIGA_CRYPT_ERROR_INSTANCE_IN_USE Same instance with ongoing request servicing is used
* \retval OPTIGA_DEVICE_ERROR Command execution failure in OPTIGA and the LSB indicates the error code.(Refer Solution Reference Manual)
*/
LIBRARY_EXPORTS optiga_lib_status_t optiga_crypt_ecdh(optiga_key_id_t private_key,
public_key_from_host_t * public_key,
bool_t export_to_host,
uint8_t * shared_secret);
/**
* @brief Derives a key.
*
* Derives a key using the secret stored in OPTIGA.<br>
*
*<b>Pre Conditions:</b>
* - The application on OPTIGA must be opened using optiga_util_open_application.<br>
* - There must be a secret available in the "session context / data object OID" provided as input parameter.<br>
* - An instance of optiga_crypt_t must be created using the optiga_crypt_create API.
*
*<b>API Details:</b>
* - Derives a key using the secret stored in OPTIGA.
* - Provides the options to store the derived key into OPTIGA session context or export to the host.
* - It invokes the callback handler of the instance, when it is asynchronously completed.
*
*<b>Notes:</b>
* - At present, the minimum length of the output derived key is 16.
* - Error codes from lower layers will be returned as it is to the application.<br>
*
* \param[in] secret Object ID of the secret stored in OPTIGA.
* - OPTIGA_KEY_ID_SESSION_BASED from optiga_key_id_t, indicates the secret is available.
* in the session context acquired by the instance.
* - or any OPTIGA data object ID(16 bit OID) which holds the secret.
* \param[in] label Pointer to the label, can be NULL if not applicable.
* \param[in] label_length Length of the label.
* \param[in] seed Valid pointer to the seed, must not be NULL.
* \param[in] seed_length Length of the seed.
* \param[in] derived_key_length Length of derived key.
* \param[in] export_to_host TRUE (1) - Exports the derived key to Host. <br>
* FALSE (0) - Stores the derived key into the session object ID acquired by the instance.
* \param[in,out] derived_key Pointer to the valid buffer with a minimum size of derived_key_length,
* in case of exporting the key to host(<b>export_to_host= TRUE</b>). Otherwise set to NULL.
*
* \retval OPTIGA_CRYPT_SUCCESS Successful invocation of optiga cmd module
* \retval OPTIGA_CRYPT_ERROR_INVALID_INPUT Wrong Input arguments provided
* \retval OPTIGA_CRYPT_ERROR_INSTANCE_IN_USE Same instance with ongoing request servicing is used
* \retval OPTIGA_DEVICE_ERROR Command execution failure in OPTIGA and the LSB indicates the error code.(Refer Solution Reference Manual)
*/
LIBRARY_EXPORTS optiga_lib_status_t optiga_crypt_tls_prf_sha256(uint16_t secret,
uint8_t * label,
uint16_t label_length,
uint8_t * seed,
uint16_t seed_length,
uint16_t derived_key_length,
bool_t export_to_host,
uint8_t * derived_key);
#ifdef __cplusplus
}
#endif
#endif //_OPTIGA_CRYPT_H_
/**
* @}
*/
| 48.293578 | 178 | 0.636702 | [
"object"
] |
fa46a8f653cc7842fcd330d5398f134a1f45691e | 34,513 | h | C | include/sqlite3pp/sqlite3pp.h | GuramDuka/spacenet | d63a6bbe606aad3d9ae400d92371f8be36be359f | [
"MIT"
] | null | null | null | include/sqlite3pp/sqlite3pp.h | GuramDuka/spacenet | d63a6bbe606aad3d9ae400d92371f8be36be359f | [
"MIT"
] | null | null | null | include/sqlite3pp/sqlite3pp.h | GuramDuka/spacenet | d63a6bbe606aad3d9ae400d92371f8be36be359f | [
"MIT"
] | null | null | null | // sqlite3pp.h
//
// The MIT License
//
// Copyright (c) 2015 Wongoo Lee (iwongu at gmail dot com)
//
// 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 SQLITE3PP_H
#define SQLITE3PP_H
#define SQLITE3PP_VERSION "1.0.6"
#define SQLITE3PP_VERSION_MAJOR 1
#define SQLITE3PP_VERSION_MINOR 0
#define SQLITE3PP_VERSION_PATCH 6
#include <cstring>
#include <functional>
#include <iterator>
#include <stdexcept>
#include <string>
#include <tuple>
//#include <variant>
#include <vector>
#include <unordered_map>
#include "sqlite/sqlite3.h"
namespace sqlite3pp {
namespace ext {
class function;
class aggregate;
}
template <typename T>
struct convert {
using to_int = int;
};
class noncopyable {
protected:
noncopyable() = default;
~noncopyable() = default;
noncopyable(noncopyable&&) = default;
noncopyable& operator=(noncopyable&&) = default;
noncopyable(noncopyable const&) = delete;
noncopyable& operator=(noncopyable const&) = delete;
};
class database;
class database_error : public std::runtime_error {
public:
explicit database_error(char const * msg, int errcode = 0, int extended_errcode = 0) :
std::runtime_error(msg), errcode_(errcode), extended_errcode_(extended_errcode) {}
const int & errcode() const {
return errcode_;
}
const int & extended_errcode() const {
return extended_errcode_;
}
private:
int errcode_;
int extended_errcode_;
};
namespace {
int busy_handler_impl(void* p, int cnt);
int commit_hook_impl(void* p);
void rollback_hook_impl(void* p);
void update_hook_impl(void* p, int opcode, char const* dbname, char const* tablename, long long int rowid);
int authorizer_impl(void* p, int evcode, char const* p1, char const* p2, char const* dbname, char const* tvname);
} // namespace
class database : noncopyable {
friend class statement;
friend class database_error;
friend class ext::function;
friend class ext::aggregate;
public:
using busy_handler = std::function<int (int) >;
using commit_handler = std::function<int ()>;
using rollback_handler = std::function<void ()>;
using update_handler = std::function<void (int, char const*, char const*, long long int) >;
using authorize_handler = std::function<int (int, char const*, char const*, char const*, char const*) >;
using backup_handler = std::function<void (int, int, int) >;
explicit database() : db_(nullptr), exceptions_(true) {}
explicit database(char const* dbname, int flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, const char* vfs = nullptr)
: db_(nullptr), exceptions_(true) {
if (dbname != nullptr)
connect(dbname, flags, vfs);
}
explicit database(const std::string & dbname, int flags = SQLITE_OPEN_READWRITE | SQLITE_OPEN_CREATE, const char* vfs = nullptr)
: database(dbname.c_str(), flags, vfs) {
}
database(database&& db) :
db_(std::move(db.db_)),
bh_(std::move(db.bh_)),
ch_(std::move(db.ch_)),
rh_(std::move(db.rh_)),
uh_(std::move(db.uh_)),
ah_(std::move(db.ah_))
{
db.db_ = nullptr;
}
database& operator=(database&& db) {
db_ = std::move(db.db_);
db.db_ = nullptr;
bh_ = std::move(db.bh_);
ch_ = std::move(db.ch_);
rh_ = std::move(db.rh_);
uh_ = std::move(db.uh_);
ah_ = std::move(db.ah_);
return *this;
}
~database() {
disconnect();
}
int connect(char const* dbname, int flags, char const* vfs = nullptr) {
disconnect();
int rc = sqlite3_open_v2(dbname, &db_, flags, vfs);
if (rc != SQLITE_OK)
throw_database_error();
else
enable_extended_result_codes(true);
return rc;
}
int connect(const std::string & dbname, int flags, char const* vfs = nullptr) {
return connect(dbname.c_str(), flags, vfs);
}
int disconnect() {
auto rc = SQLITE_OK;
if (db_ != nullptr) {
rc = sqlite3_close_v2(db_);
if (rc != SQLITE_OK)
throw_database_error();
if (rc == SQLITE_OK)
db_ = nullptr;
}
return rc;
}
int attach(char const* dbname, char const* name) {
return executef("ATTACH '%q' AS '%q'", dbname, name);
}
int detach(char const* name) {
return executef("DETACH '%q'", name);
}
int backup(char const* dbname, database& destdb, char const* destdbname, backup_handler h, int step_page = 5) {
sqlite3_backup* bkup = sqlite3_backup_init(destdb.db_, destdbname, db_, dbname);
if (!bkup) {
return error_code();
}
auto rc = SQLITE_OK;
do {
rc = sqlite3_backup_step(bkup, step_page);
if (h) {
h(sqlite3_backup_remaining(bkup), sqlite3_backup_pagecount(bkup), rc);
}
} while (rc == SQLITE_OK || rc == SQLITE_BUSY || rc == SQLITE_LOCKED);
sqlite3_backup_finish(bkup);
return rc;
}
int backup(database& destdb, backup_handler h) {
return backup("main", destdb, "main", h);
}
void set_busy_handler(busy_handler h) {
bh_ = h;
sqlite3_busy_handler(db_, bh_ ? busy_handler_impl : 0, &bh_);
}
void set_commit_handler(commit_handler h) {
ch_ = h;
sqlite3_commit_hook(db_, ch_ ? commit_hook_impl : 0, &ch_);
}
void set_rollback_handler(rollback_handler h) {
rh_ = h;
sqlite3_rollback_hook(db_, rh_ ? rollback_hook_impl : 0, &rh_);
}
void set_update_handler(update_handler h) {
uh_ = h;
sqlite3_update_hook(db_, uh_ ? update_hook_impl : 0, &uh_);
}
void set_authorize_handler(authorize_handler h) {
ah_ = h;
sqlite3_set_authorizer(db_, ah_ ? authorizer_impl : 0, &ah_);
}
long long int last_insert_rowid() const {
return sqlite3_last_insert_rowid(db_);
}
int enable_foreign_keys(bool enable = true) {
return sqlite3_db_config(db_, SQLITE_DBCONFIG_ENABLE_FKEY, enable ? 1 : 0, nullptr);
}
int enable_triggers(bool enable = true) {
return sqlite3_db_config(db_, SQLITE_DBCONFIG_ENABLE_TRIGGER, enable ? 1 : 0, nullptr);
}
int enable_extended_result_codes(bool enable = true) {
return sqlite3_extended_result_codes(db_, enable ? 1 : 0);
}
int changes() const {
return sqlite3_changes(db_);
}
int error_code() const {
return sqlite3_errcode(db_);
}
int extended_error_code() const {
return sqlite3_extended_errcode(db_);
}
char const* error_msg() const {
return sqlite3_errmsg(db_);
}
int execute(char const* sql) {
int rc = sqlite3_exec(db_, sql, 0, 0, 0);
if (rc != SQLITE_OK)
throw_database_error();
return rc;
}
int execute(const std::string & sql) {
return execute(sql.c_str());
}
int execute_all(char const* sql);
int execute_all(const std::string & sql) {
return execute_all(sql.c_str());
}
int executef(char const* sql, ...) {
va_list ap;
va_start(ap, sql);
std::shared_ptr<char> msql(sqlite3_vmprintf(sql, ap), sqlite3_free);
va_end(ap);
return execute(msql.get());
}
int set_busy_timeout(int ms) {
auto rc = sqlite3_busy_timeout(db_, ms);
if (rc != SQLITE_OK)
throw_database_error();
return rc;
}
void throw_database_error() const {
if (exceptions_)
throw database_error(
sqlite3_errmsg(db_),
sqlite3_errcode(db_),
sqlite3_extended_errcode(db_));
}
database & exceptions(bool exceptions) {
exceptions_ = exceptions;
return *this;
}
const bool & exceptions() const {
return exceptions_;
}
sqlite3 * const & handle() const {
return db_;
}
bool connected() const {
return db_ != nullptr;
}
private:
sqlite3* db_;
busy_handler bh_;
commit_handler ch_;
rollback_handler rh_;
update_handler uh_;
authorize_handler ah_;
bool exceptions_;
};
namespace {
int busy_handler_impl(void* p, int cnt) {
auto h = static_cast<database::busy_handler*> (p);
return (*h)(cnt);
}
int commit_hook_impl(void* p) {
auto h = static_cast<database::commit_handler*> (p);
return (*h)();
}
void rollback_hook_impl(void* p) {
auto h = static_cast<database::rollback_handler*> (p);
(*h)();
}
void update_hook_impl(void* p, int opcode, char const* dbname, char const* tablename, long long int rowid) {
auto h = static_cast<database::update_handler*> (p);
(*h)(opcode, dbname, tablename, rowid);
}
int authorizer_impl(void* p, int evcode, char const* p1, char const* p2, char const* dbname, char const* tvname) {
auto h = static_cast<database::authorize_handler*> (p);
return (*h)(evcode, p1, p2, dbname, tvname);
}
} // namespace
enum copy_semantic {
copy, nocopy
};
class statement : noncopyable {
public:
int prepare(char const* stmt) {
finish();
prepare_impl(stmt);
param_cache_.clear();
build_param_cache();
return rc_;
}
int prepare(const std::string & stmt) {
return prepare(stmt.c_str());
}
int finish() {
rc_ = SQLITE_OK;
if (stmt_ != nullptr) {
finish_impl(stmt_);
if (rc_ != SQLITE_OK)
db_.throw_database_error();
stmt_ = nullptr;
}
tail_ = nullptr;
return rc_;
}
operator bool () const {
return rc_ != SQLITE_OK;
}
int step() {
rc_ = sqlite3_step(stmt_);
if (rc_ != SQLITE_ROW && rc_ != SQLITE_DONE)
db_.throw_database_error();
return rc_;
}
int reset() {
rc_ = sqlite3_reset(stmt_);
//if (rc_ != SQLITE_OK)
// db_.throw_database_error();
return rc_;
}
int bind(int idx, bool value) {
rc_ = sqlite3_bind_int(stmt_, idx, value ? 1 : 0);
if (rc_ == SQLITE_MISUSE) {
sqlite3_reset(stmt_);
rc_ = sqlite3_bind_int(stmt_, idx, value ? 1 : 0);
}
if (rc_ != SQLITE_OK)
db_.throw_database_error();
return rc_;
}
int bind(int idx, int value) {
rc_ = sqlite3_bind_int(stmt_, idx, value);
if (rc_ == SQLITE_MISUSE) {
sqlite3_reset(stmt_);
rc_ = sqlite3_bind_int(stmt_, idx, value);
}
if (rc_ != SQLITE_OK)
db_.throw_database_error();
return rc_;
}
int bind(int idx, unsigned value) {
rc_ = sqlite3_bind_int(stmt_, idx, value);
if (rc_ == SQLITE_MISUSE) {
sqlite3_reset(stmt_);
rc_ = sqlite3_bind_int(stmt_, idx, value);
}
if (rc_ != SQLITE_OK)
db_.throw_database_error();
return rc_;
}
int bind(int idx, double value) {
rc_ = sqlite3_bind_double(stmt_, idx, value);
if (rc_ == SQLITE_MISUSE) {
sqlite3_reset(stmt_);
rc_ = sqlite3_bind_double(stmt_, idx, value);
}
if (rc_ != SQLITE_OK)
db_.throw_database_error();
return rc_;
}
int bind(int idx, long long int value) {
rc_ = sqlite3_bind_int64(stmt_, idx, value);
if (rc_ == SQLITE_MISUSE) {
sqlite3_reset(stmt_);
rc_ = sqlite3_bind_int64(stmt_, idx, value);
}
if (rc_ != SQLITE_OK)
db_.throw_database_error();
return rc_;
}
int bind(int idx, long long unsigned value) {
rc_ = sqlite3_bind_int64(stmt_, idx, value);
if (rc_ == SQLITE_MISUSE) {
sqlite3_reset(stmt_);
rc_ = sqlite3_bind_int64(stmt_, idx, value);
}
if (rc_ != SQLITE_OK)
db_.throw_database_error();
return rc_;
}
int bind(int idx, char const* value, copy_semantic fcopy) {
rc_ = sqlite3_bind_text(stmt_, idx, value, int(std::strlen(value)), fcopy == copy ? SQLITE_TRANSIENT : SQLITE_STATIC);
if (rc_ == SQLITE_MISUSE) {
sqlite3_reset(stmt_);
rc_ = sqlite3_bind_text(stmt_, idx, value, int(std::strlen(value)), fcopy == copy ? SQLITE_TRANSIENT : SQLITE_STATIC);
}
if (rc_ != SQLITE_OK)
db_.throw_database_error();
return rc_;
}
int bind(int idx, void const* value, size_t n, copy_semantic fcopy) {
rc_ = sqlite3_bind_blob64(stmt_, idx, value, n, fcopy == copy ? SQLITE_TRANSIENT : SQLITE_STATIC);
if (rc_ == SQLITE_MISUSE) {
sqlite3_reset(stmt_);
rc_ = sqlite3_bind_blob64(stmt_, idx, value, n, fcopy == copy ? SQLITE_TRANSIENT : SQLITE_STATIC);
}
if (rc_ != SQLITE_OK)
db_.throw_database_error();
return rc_;
}
int bind(int idx, std::string const& value, copy_semantic fcopy) {
rc_ = sqlite3_bind_text64(stmt_, idx, value.c_str(), value.size(), fcopy == copy ? SQLITE_TRANSIENT : SQLITE_STATIC, SQLITE_UTF8);
if (rc_ == SQLITE_MISUSE) {
sqlite3_reset(stmt_);
rc_ = sqlite3_bind_text64(stmt_, idx, value.c_str(), value.size(), fcopy == copy ? SQLITE_TRANSIENT : SQLITE_STATIC, SQLITE_UTF8);
}
if (rc_ != SQLITE_OK)
db_.throw_database_error();
return rc_;
}
int bind(int idx) {
rc_ = sqlite3_bind_null(stmt_, idx);
if (rc_ == SQLITE_MISUSE) {
sqlite3_reset(stmt_);
rc_ = sqlite3_bind_null(stmt_, idx);
}
if (rc_ != SQLITE_OK)
db_.throw_database_error();
return rc_;
}
int bind(int idx, std::nullptr_t) {
return bind(idx);
}
int param_name2idx(const char * name) const {
auto i = param_cache_.find(name);
if( i == param_cache_.cend() )
throw database_error("Invalid parameter name");
return i->second;
}
int param_name2idx(const std::string & name) const {
return param_name2idx(name.c_str());
}
int bind(char const* name, bool value) {
//auto idx = sqlite3_bind_parameter_index(stmt_, name);
return bind(param_name2idx(name), value);
}
int bind(char const* name, int value) {
//auto idx = sqlite3_bind_parameter_index(stmt_, name);
return bind(param_name2idx(name), value);
}
int bind(char const* name, unsigned value) {
//auto idx = sqlite3_bind_parameter_index(stmt_, name);
return bind(param_name2idx(name), value);
}
int bind(char const* name, double value) {
//auto idx = sqlite3_bind_parameter_index(stmt_, name);
return bind(param_name2idx(name), value);
}
int bind(char const* name, long long int value) {
//auto idx = sqlite3_bind_parameter_index(stmt_, name);
return bind(param_name2idx(name), value);
}
int bind(char const* name, long long unsigned value) {
//auto idx = sqlite3_bind_parameter_index(stmt_, name);
return bind(param_name2idx(name), value);
}
int bind(char const* name, char const* value, copy_semantic fcopy) {
//auto idx = sqlite3_bind_parameter_index(stmt_, name);
return bind(param_name2idx(name), value, fcopy);
}
int bind(char const* name, void const* value, int n, copy_semantic fcopy) {
//auto idx = sqlite3_bind_parameter_index(stmt_, name);
return bind(param_name2idx(name), value, n, fcopy);
}
int bind(char const* name, std::string const& value, copy_semantic fcopy) {
//auto idx = sqlite3_bind_parameter_index(stmt_, name);
return bind(param_name2idx(name), value, fcopy);
}
int bind(char const* name) {
//auto idx = sqlite3_bind_parameter_index(stmt_, name);
return bind(param_name2idx(name));
}
int bind(char const* name, std::nullptr_t) {
return bind(name);
}
int bind(const std::string & name, std::nullptr_t) {
return bind(name.c_str());
}
template <typename T>
int bind(const std::string & name, const T & value) {
return bind(name.c_str(), value);
}
template <typename T>
int bind(const std::string & name, const T & value, copy_semantic fcopy) {
return bind(name.c_str(), value, fcopy);
}
template <typename T>
int bind(const char * name, const std::vector<T> & value, copy_semantic fcopy) {
return bind(name, (const void *) &value[0], int(value.size() * sizeof(T)), fcopy);
}
template <typename T>
int bind(const std::string & name, const std::vector<T> & value, copy_semantic fcopy) {
return bind(name.c_str(), (const void *) &value[0], int(value.size() * sizeof(T)), fcopy);
}
template <typename T>
int bind(const std::string & name, const T & value, int n, copy_semantic fcopy) {
return bind(name.c_str(), value, n, fcopy);
}
protected:
explicit statement(database& db, char const* stmt = nullptr)
: db_(db), stmt_(nullptr), tail_(nullptr), rc_(SQLITE_OK)
{
if (stmt != nullptr)
prepare(stmt);
}
~statement() {
// finish() can return error. If you want to check the error, call
// finish() explicitly before this object is destructed.
auto safe = db_.exceptions();
db_.exceptions(false);
finish();
db_.exceptions(safe);
}
int prepare_impl(char const* stmt) {
rc_ = sqlite3_prepare_v2(db_.db_, stmt, int(std::strlen(stmt)), &stmt_, &tail_);
if (rc_ != SQLITE_OK)
db_.throw_database_error();
return rc_;
}
int finish_impl(sqlite3_stmt* stmt) {
rc_ = sqlite3_finalize(stmt);
if (rc_ != SQLITE_OK)
db_.throw_database_error();
return rc_;
}
protected:
database & db_;
sqlite3_stmt * stmt_;
char const * tail_;
int rc_;
struct str_hash {
size_t operator() (const char * val) const {
size_t h = 0;
while( *val != '\0' ) {
h += *val++;
h += (h << 9);
h ^= (h >> 5);
}
h += (h << 3);
h ^= (h >> 10);
h += (h << 14);
return h;
}
};
struct str_equal {
bool operator()(const char * val1, const char * val2) const {
return strcmp(val1, val2) == 0;
}
};
typedef std::unordered_map<const char *, int, str_hash, str_equal> cache_type;
mutable cache_type param_cache_;
void build_param_cache() const {
int k = sqlite3_bind_parameter_count(stmt_);
for( int i = 1; i <= k; i++ ) {
auto p = sqlite3_bind_parameter_name(stmt_, i);
if( *p == ':' )
p++;
param_cache_.emplace(std::make_pair(p, i));
}
}
};
class command : public statement {
public:
explicit command(database& db, char const* stmt = nullptr) : statement(db, stmt) {}
explicit command(database& db, const std::string & stmt) : command(db, stmt.c_str()) {}
int execute() {
rc_ = reset();
if (rc_ == SQLITE_OK)
rc_ = step();
if (rc_ != SQLITE_ROW && rc_ != SQLITE_DONE)
db_.throw_database_error();
return rc_;
}
int execute_all() {
execute();
char const * sql = tail_;
while (std::strlen(sql) > 0) { // sqlite3_complete() is broken.
sqlite3_stmt* old_stmt = stmt_;
prepare_impl(sql);
// If the input text contains no SQL (if the input is an empty string or a comment) then stmt_ is set to nullptr
if (stmt_ == nullptr) {
stmt_ = old_stmt;
break;
}
if ((rc_ = sqlite3_transfer_bindings(old_stmt, stmt_)) != SQLITE_OK) {
database_error e(
db_.error_msg(),
db_.error_code(),
db_.extended_error_code());
finish_impl(old_stmt);
if( db_.exceptions( ))
throw e;
}
finish_impl(old_stmt);
execute();
if (rc_ != SQLITE_ROW && rc_ != SQLITE_DONE)
db_.throw_database_error();
sql = tail_;
}
return rc_;
}
};
inline int database::execute_all(const char *sql) {
return command(*this, sql).execute_all();
}
enum query_column_type {
SQL_INT = SQLITE_INTEGER,
SQL_FLT = SQLITE_FLOAT,
SQL_TXT = SQLITE_TEXT,
SQL_BLB = SQLITE_BLOB,
SQL_NIL = SQLITE_NULL
};
class query : public statement {
public:
class row {
public:
explicit row(query * cmd) : cmd_(cmd) {}
int data_count() const {
return sqlite3_data_count(cmd_->stmt_);
}
query_column_type column_type(int idx) const {
return static_cast<query_column_type>(sqlite3_column_type(cmd_->stmt_, idx));
}
query_column_type column_type(const char * name) const {
return static_cast<query_column_type>(sqlite3_column_type(cmd_->stmt_, cmd_->column_name2idx(name)));
}
query_column_type column_type(const std::string & name) const {
return static_cast<query_column_type>(sqlite3_column_type(cmd_->stmt_, cmd_->column_name2idx(name)));
}
bool column_isnull(int idx) const {
return column_type(idx) == SQL_NIL;
}
bool column_isnull(const char * name) const {
return column_type(name) == SQL_NIL;
}
bool column_isnull(const std::string & name) const {
return column_type(name) == SQL_NIL;
}
int column_bytes(int idx) const {
return sqlite3_column_bytes(cmd_->stmt_, idx);
}
template <typename T> T get(int idx) const {
return get(idx, T());
}
template <typename T> T get(const char * name) const {
return get(cmd_->column_name2idx(name), T());
}
template <typename T> T get(const std::string & name) const {
return get(cmd_->column_name2idx(name), T());
}
template <typename T> T & get(T & v, int idx) const {
return copy_impl(idx, v);
}
template <typename T> T & get(T & v, const char * name) const {
return copy_impl(cmd_->column_name2idx(name), v);
}
template <typename T> T & get(T & v, const std::string & name) const {
return copy_impl(cmd_->column_name2idx(name), v);
}
template <class... Ts>
std::tuple<Ts...> get_columns(typename convert<Ts>::to_int... idxs) const {
return std::make_tuple(get(idxs, Ts())...);
}
//using var_t = std::variant<int, long long int, double, std::string, std::vector<uint8_t>>;
private:
int get(int idx, int) const {
return sqlite3_column_int(cmd_->stmt_, idx);
}
unsigned int get(int idx, unsigned int) const {
return sqlite3_column_int(cmd_->stmt_, idx);
}
int & copy_impl(int idx, int & v) const {
return v = sqlite3_column_int(cmd_->stmt_, idx);
}
unsigned int & copy_impl(int idx, unsigned int & v) const {
return v = sqlite3_column_int(cmd_->stmt_, idx);
}
double get(int idx, double) const {
return sqlite3_column_double(cmd_->stmt_, idx);
}
double & copy_impl(int idx, double & v) const {
return v = sqlite3_column_double(cmd_->stmt_, idx);
}
long long int get(int idx, long long int) const {
return sqlite3_column_int64(cmd_->stmt_, idx);
}
long long unsigned int get(int idx, long long unsigned int) const {
return sqlite3_column_int64(cmd_->stmt_, idx);
}
long long int & copy_impl(int idx, long long int & v) const {
return v = sqlite3_column_int64(cmd_->stmt_, idx);
}
long long unsigned int & copy_impl(int idx, long long unsigned int & v) const {
return v = sqlite3_column_int64(cmd_->stmt_, idx);
}
char const* get(int idx, char const*) const {
return reinterpret_cast<char const*> (sqlite3_column_text(cmd_->stmt_, idx));
}
std::string get(int idx, std::string) const {
return reinterpret_cast<char const*> (sqlite3_column_text(cmd_->stmt_, idx));
}
std::string & copy_impl(int idx, std::string & v) const {
return v = reinterpret_cast<char const*> (sqlite3_column_text(cmd_->stmt_, idx));
}
void const* get(int idx, void const*) const {
return sqlite3_column_blob(cmd_->stmt_, idx);
}
template <typename T>
std::vector<T> get(int idx, std::vector<T>) const {
auto s = sqlite3_column_bytes(cmd_->stmt_, idx);
const T * p = static_cast<const T *> (sqlite3_column_blob(cmd_->stmt_, idx));
return std::vector<T>(p, p + s / sizeof (T) - 1);
}
template <typename T>
std::vector<T> & copy_impl(int idx, std::vector<T> & v) const {
auto s = sqlite3_column_bytes(cmd_->stmt_, idx);
const T * p = static_cast<const T *> (sqlite3_column_blob(cmd_->stmt_, idx));
v.assign(p, p + s / sizeof (T) - 1);
return v;
}
std::nullptr_t get(int /*idx*/, std::nullptr_t) const {
return nullptr;
}
protected:
query * cmd_;
};
class query_iterator : public std::iterator<std::input_iterator_tag, row>, private row {
public:
query_iterator() : row(nullptr), rc_(SQLITE_DONE) {}
explicit query_iterator(query * cmd) : row(cmd) {
rc_ = cmd_->step();
}
operator bool () const {
return rc_ != SQLITE_DONE;
}
bool operator == (query_iterator const& other) const {
return rc_ == other.rc_;
}
bool operator != (query_iterator const& other) const {
return rc_ != other.rc_;
}
// prefix form
query_iterator & operator ++ () {
rc_ = cmd_->step();
if (rc_ != SQLITE_ROW && rc_ != SQLITE_DONE)
cmd_->db_.throw_database_error();
return *this;
}
// postfix form
query_iterator & operator ++ (int) {
rc_ = cmd_->step();
if (rc_ != SQLITE_ROW && rc_ != SQLITE_DONE)
cmd_->db_.throw_database_error();
return *this;
}
value_type & operator * () const {
return *const_cast<value_type *>(static_cast<const value_type *>(this));
}
value_type * operator -> () const {
return const_cast<value_type *>(static_cast<const value_type *>(this));
}
private:
int rc_;
};
explicit query(database& db, char const* stmt = nullptr) : statement(db, nullptr) {
prepare(stmt);
}
explicit query(database& db, const std::string & stmt) : query(db, stmt.c_str()) {}
// overload
int prepare(const char * stmt) {
statement::prepare(stmt);
column_cache_.clear();
build_column_cache();
return rc_;
}
// overload
int prepare(const std::string & stmt) {
return prepare(stmt.c_str());
}
int column_count() const {
return sqlite3_column_count(stmt_);
}
char const* column_name(int idx) const {
return sqlite3_column_name(stmt_, idx);
}
char const* column_decltype(int idx) const {
return sqlite3_column_decltype(stmt_, idx);
}
int column_name2idx(const char * name) const {
auto i = column_cache_.find(name);
if( i == column_cache_.cend() )
throw database_error("Invalid column name");
return i->second;
}
int column_name2idx(const std::string & name) const {
return column_name2idx(name.c_str());
}
using iterator = query_iterator;
iterator begin() {
return query_iterator(this);
}
iterator end() {
return query_iterator();
}
private:
mutable cache_type column_cache_;
void build_column_cache() const {
int k = sqlite3_column_count(stmt_);
for( int i = 0; i < k; i++ )
column_cache_.emplace(std::make_pair(sqlite3_column_name(stmt_, i), i));
}
};
class transaction : noncopyable {
public:
explicit transaction(database& db, bool freserve = false, bool frollback = false)
: db_(&db), frollback_(frollback)
{
int rc = db_->execute(freserve ? "BEGIN IMMEDIATE" : "BEGIN");
if (rc != SQLITE_OK)
db_->throw_database_error();
}
~transaction() {
if (db_ != nullptr) {
// execute() can return error. If you want to check the error,
// call commit() or rollback() explicitly before this object is
// destructed.
db_->execute(frollback_ ? "ROLLBACK" : "COMMIT");
}
}
int commit() {
auto db = db_;
db_ = nullptr;
int rc = db->execute("COMMIT");
if (rc != SQLITE_OK)
db_->throw_database_error();
return rc;
}
int rollback() {
auto db = db_;
db_ = nullptr;
int rc = db->execute("ROLLBACK");
if (rc != SQLITE_OK)
db_->throw_database_error();
return rc;
}
private:
database * db_;
bool frollback_;
};
} // namespace sqlite3pp
#endif
| 32.528746 | 146 | 0.524208 | [
"object",
"vector"
] |
fa486df5d2f0545f21228c818af38d366b3885d3 | 11,187 | h | C | robotiq_s_model_articulated_gazebo_plugins/include/robotiq_s_model_articulated_gazebo_plugins/RobotiqHandPluginSingleHand.h | pidipidi/robotiq | 6c297a4f12607518a3c44d2323372b9cd43e783c | [
"BSD-2-Clause"
] | 2 | 2018-06-23T15:35:24.000Z | 2018-07-11T17:36:25.000Z | robotiq_s_model_articulated_gazebo_plugins/include/robotiq_s_model_articulated_gazebo_plugins/RobotiqHandPluginSingleHand.h | pidipidi/robotiq | 6c297a4f12607518a3c44d2323372b9cd43e783c | [
"BSD-2-Clause"
] | null | null | null | robotiq_s_model_articulated_gazebo_plugins/include/robotiq_s_model_articulated_gazebo_plugins/RobotiqHandPluginSingleHand.h | pidipidi/robotiq | 6c297a4f12607518a3c44d2323372b9cd43e783c | [
"BSD-2-Clause"
] | 2 | 2018-06-23T15:37:02.000Z | 2018-09-06T04:32:05.000Z | /*
* Copyright 2014 Open Source Robotics Foundation
* Copyright 2015 Clearpath Robotics
*
* 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 GAZEBO_ROBOTIQ_HAND_PLUGIN_SINGLE_HAND_HH
#define GAZEBO_ROBOTIQ_HAND_PLUGIN_SINGLE_HAND_HH
#include <robotiq_s_model_articulated_msgs/SModelRobotInput.h>
#include <robotiq_s_model_articulated_msgs/SModelRobotOutput.h>
#include <gazebo_plugins/PubQueue.h>
#include <ros/advertise_options.h>
#include <ros/callback_queue.h>
#include <ros/ros.h>
#include <ros/subscribe_options.h>
#include <sensor_msgs/JointState.h>
#include <string>
#include <vector>
#include <boost/scoped_ptr.hpp>
#include <boost/thread/mutex.hpp>
#include <gazebo/common/Plugin.hh>
#include <gazebo/common/Time.hh>
#include <gazebo/physics/physics.hh>
/// \brief A plugin that implements the Robotiq 3-Finger Adaptative Gripper.
/// The plugin exposes the next parameters via SDF tags:
/// * <side> Determines if we are controlling the left or right hand. This is
/// a required parameter and the allowed values are 'left' or 'right'
/// * <kp_position> P gain for the PID that controls the position
/// of the joints. This parameter is optional.
/// * <ki_position> I gain for the PID that controls the position
/// of the joints. This parameter is optional.
/// * <kd_position> D gain for the PID that controls the position
/// of the joints. This parameter is optional.
/// * <position_effort_min> Minimum output of the PID that controls the
/// position of the joints. This parameter is optional
/// * <position_effort_max> Maximum output of the PID that controls the
/// position of the joints. This parameter is optional
/// * <topic_command> ROS topic name used to send new commands to the hand.
/// This parameter is optional.
/// * <topic_state> ROS topic name used to receive state from the hand.
/// This parameter is optional.
class RobotiqHandPluginSingleHand : public gazebo::ModelPlugin
{
friend class gazebo::common::PID;
/// \brief Hand states.
enum State
{
Disabled = 0,
Emergency,
ICS,
ICF,
ChangeModeInProgress,
Simplified
};
/// \brief Different grasping modes.
enum GraspingMode
{
Basic = 0,
Pinch,
Wide,
Scissor
};
/// \brief Constructor.
public: RobotiqHandPluginSingleHand();
/// \brief Destructor.
public: virtual ~RobotiqHandPluginSingleHand();
// Documentation inherited.
public: void Load(gazebo::physics::ModelPtr _parent, sdf::ElementPtr _sdf);
/// \brief ROS callback queue thread.
private: void RosQueueThread();
/// \brief ROS topic callback to update Robotiq Hand Control Commands.
/// \param[in] _msg Incoming ROS message with the next hand command.
private: void SetHandleCommand(
const robotiq_s_model_articulated_msgs::SModelRobotOutput::ConstPtr &_msg);
/// \brief Update PID Joint controllers.
/// \param[in] _dt time step size since last update.
private: void UpdatePIDControl(double _dt);
/// \brief Publish Robotiq Hand state.
private: void GetAndPublishHandleState();
/// \brief Publish Robotiq Joint state.
private: void GetAndPublishJointState(const gazebo::common::Time &_curTime);
/// \brief Update the controller.
private: void UpdateStates();
/// \brief Grab pointers to all the joints.
/// \return true on success, false otherwise.
private: bool FindJoints();
/// \brief Fully open the hand at half of the maximum speed.
private: void ReleaseHand();
/// \brief Stop the fingers.
private: void StopHand();
/// \brief Checks if the hand is fully open.
/// return True when all the fingers are fully open or false otherwise.
private: bool IsHandFullyOpen();
/// \brief Internal helper to get the object detection value.
/// \param[in] _joint Finger joint.
/// \param[in] _index Index of the position PID for this joint.
/// \param[in] _rPR Current position request.
/// \param[in] _prevrPR Previous position request.
/// \return The information on possible object contact:
/// 0 Finger is in motion (only meaningful if gGTO = 1).
/// 1 Finger has stopped due to a contact while opening.
/// 2 Finger has stopped due to a contact while closing.
/// 3 Finger is at the requested position.
private: uint8_t GetObjectDetection(const gazebo::physics::JointPtr &_joint,
int _index, uint8_t _rPR, uint8_t _prevrPR);
/// \brief Internal helper to get the actual position of the finger.
/// \param[in] _joint Finger joint.
/// \return The actual position of the finger. 0 is the minimum position
/// (fully open) and 255 is the maximum position (fully closed).
private: uint8_t GetCurrentPosition(const gazebo::physics::JointPtr &_joint);
/// \brief Internal helper to reduce code duplication. If the joint name is
/// found, a pointer to the joint is added to a vector of joint pointers.
/// \param[in] _jointName Joint name.
/// \param[out] _joints Vector of joint pointers.
/// \return True when the joint was found or false otherwise.
private: bool GetAndPushBackJoint(const std::string& _jointName,
gazebo::physics::Joint_V& _joints);
/// \brief Verify that one command field is within the correct range.
/// \param[in] _label Label of the field. E.g.: rACT, rMOD.
/// \param[in] _min Minimum value.
/// \param[in] _max Maximum value.
/// \param[in] _v Value to be verified.
/// \return True when the value is within the limits or false otherwise.
private: bool VerifyField(const std::string &_label, int _min,
int _max, int _v);
/// \brief Verify that all the command fields are within the correct range.
/// \param[in] _command Robot output message.
/// \return True if all the fields are withing the correct range or false
/// otherwise.
private: bool VerifyCommand(
const robotiq_s_model_articulated_msgs::SModelRobotOutput::ConstPtr &_command);
/// \brief Number of joints in the hand.
/// The three fingers can do abduction/adduction.
/// Fingers 1 and 2 can do circumduction in one axis.
private: static const int NumJoints = 5;
/// \brief Velocity tolerance. Below this value we assume that the joint is
/// stopped (rad/s).
private: static constexpr double VelTolerance = 0.002;
/// \brief Position tolerance. If the difference between target position and
/// current position is within this value we'll conclude that the joint
/// reached its target (rad).
private: static constexpr double PoseTolerance = 0.002;
/// \brief Min. joint speed (rad/s). Finger is 125mm and tip speed is 22mm/s.
private: static constexpr double MinVelocity = 0.176;
/// \brief Max. joint speed (rad/s). Finger is 125mm and tip speed is 110mm/s.
private: static constexpr double MaxVelocity = 0.88;
/// \brief Default topic name for sending control updates to the left hand.
private: static const std::string DefaultLeftTopicCommand;
/// \brief Default topic name for receiving state updates from the left hand.
private: static const std::string DefaultLeftTopicState;
/// \brief Default topic name for sending control updates to the right hand.
private: static const std::string DefaultRightTopicCommand;
/// \brief Default topic name for receiving state updates from the right hand.
private: static const std::string DefaultRightTopicState;
/// \brief ROS NodeHandle.
private: boost::scoped_ptr<ros::NodeHandle> rosNode;
/// \brief ROS callback queue.
private: ros::CallbackQueue rosQueue;
/// \brief ROS callback queue thread.
private: boost::thread callbackQueueThread;
// ROS publish multi queue, prevents publish() blocking
private: PubMultiQueue pmq;
/// \brief ROS control interface
private: ros::Subscriber subHandleCommand;
/// \brief HandleControl message. Originally published by user but some of the
/// fields might be internally modified. E.g.: When releasing the hand for
// changing the grasping mode.
private: robotiq_s_model_articulated_msgs::SModelRobotOutput handleCommand;
/// \brief HandleControl message. Last command received before changing the
/// grasping mode.
private: robotiq_s_model_articulated_msgs::SModelRobotOutput lastHandleCommand;
/// \brief Previous command received. We know if the hand is opening or
/// closing by comparing the current command and the previous one.
private: robotiq_s_model_articulated_msgs::SModelRobotOutput prevCommand;
/// \brief Original HandleControl message (published by user and unmodified).
private: robotiq_s_model_articulated_msgs::SModelRobotOutput userHandleCommand;
/// \brief gazebo world update connection.
private: gazebo::event::ConnectionPtr updateConnection;
/// \brief keep track of controller update sim-time.
private: gazebo::common::Time lastControllerUpdateTime;
/// \brief Robotiq Hand State.
private: robotiq_s_model_articulated_msgs::SModelRobotInput handleState;
/// \brief Controller update mutex.
private: boost::mutex controlMutex;
/// \brief Grasping mode.
private: GraspingMode graspingMode;
/// \brief Hand state.
private: State handState;
/// \brief ROS publisher for Robotiq Hand state.
private: ros::Publisher pubHandleState;
/// \brief ROS publisher queue for Robotiq Hand state.
private: PubQueue<robotiq_s_model_articulated_msgs::SModelRobotInput>::Ptr pubHandleStateQueue;
/// \brief Joint state publisher (rviz visualization).
// private: ros::Publisher pubJointStates;
/// \brief ROS publisher queue for joint states.
// private: PubQueue<sensor_msgs::JointState>::Ptr pubJointStatesQueue;
/// \brief ROS joint state message.
private: sensor_msgs::JointState jointStates;
/// \brief World pointer.
private: gazebo::physics::WorldPtr world;
/// \brief Parent model of the hand.
private: gazebo::physics::ModelPtr model;
/// \brief Pointer to the SDF of this plugin.
private: sdf::ElementPtr sdf;
/// \brief Used to select between 'left' or 'right' hand.
//private: std::string side;
/// \brief Vector containing all the joint names.
private: std::vector<std::string> jointNames;
/// \brief Vector containing all the actuated finger joints.
private: gazebo::physics::Joint_V fingerJoints;
/// \brief Vector containing all the joints.
private: gazebo::physics::Joint_V joints;
/// \brief PIDs used to control the finger positions.
private: gazebo::common::PID posePID[NumJoints];
};
#endif // GAZEBO_ROBOTIQ_HAND_PLUGIN_HH
| 38.443299 | 97 | 0.717529 | [
"object",
"vector",
"model"
] |
fa489cdf920dea9792ef72961d4a6cdde54325e2 | 297 | h | C | event_handling/include/essentials/EventTrigger.h | hendrik-skubch/alica-essentials | f9d50e5a8fb0ce502b855503ad033b2986d7a5a0 | [
"MIT"
] | null | null | null | event_handling/include/essentials/EventTrigger.h | hendrik-skubch/alica-essentials | f9d50e5a8fb0ce502b855503ad033b2986d7a5a0 | [
"MIT"
] | null | null | null | event_handling/include/essentials/EventTrigger.h | hendrik-skubch/alica-essentials | f9d50e5a8fb0ce502b855503ad033b2986d7a5a0 | [
"MIT"
] | null | null | null | #pragma once
#include "ITrigger.h"
#include <vector>
#include <mutex>
#include <condition_variable>
namespace essentials {
class EventTrigger : public virtual ITrigger {
public:
EventTrigger();
virtual ~EventTrigger();
void run(bool notifyAll = true);
};
} // namespace essentials
| 17.470588 | 46 | 0.717172 | [
"vector"
] |
fa48a780c69ea746d863a7f8d84e2015ad96233c | 2,409 | h | C | common/beerocks/btl/include/btl/btl.h | ydx-coder/prplMesh | 6401b15c31c563f9e00ce6ff1b5513df3d39f157 | [
"BSD-2-Clause-Patent"
] | null | null | null | common/beerocks/btl/include/btl/btl.h | ydx-coder/prplMesh | 6401b15c31c563f9e00ce6ff1b5513df3d39f157 | [
"BSD-2-Clause-Patent"
] | null | null | null | common/beerocks/btl/include/btl/btl.h | ydx-coder/prplMesh | 6401b15c31c563f9e00ce6ff1b5513df3d39f157 | [
"BSD-2-Clause-Patent"
] | 1 | 2022-02-01T20:52:12.000Z | 2022-02-01T20:52:12.000Z | /* SPDX-License-Identifier: BSD-2-Clause-Patent
*
* Copyright (c) 2016-2019 Intel Corporation
*
* This code is subject to the terms of the BSD+Patent license.
* See LICENSE file for more details.
*/
#ifndef _BEEROCKS_MAPF_SOCKET_THREAD_H_
#define _BEEROCKS_MAPF_SOCKET_THREAD_H_
#include <bcl/beerocks_message_structs.h>
#include <bcl/beerocks_socket_thread.h>
#include <beerocks/tlvf/beerocks_message.h>
#include <tlvf/ieee_1905_1/eMessageType.h>
// Forward Declarations
namespace mapf {
class Poller;
class LocalBusInterface;
class SubSocket;
} // namespace mapf
namespace beerocks {
namespace btl {
class transport_socket_thread : public socket_thread {
public:
transport_socket_thread(const std::string &unix_socket_path_ = std::string());
virtual ~transport_socket_thread();
virtual bool init() override;
virtual void set_select_timeout(unsigned msec) override;
virtual bool work() override;
bool send_cmdu_to_bus(ieee1905_1::CmduMessageTx &cmdu, const std::string &dst_mac,
const std::string &src_mac);
protected:
void add_socket(Socket *s, bool add_to_vector = true) override;
void remove_socket(Socket *s) override;
bool read_ready(Socket *s) override;
bool configure_ieee1905_transport_interfaces(const std::string &bridge_iface,
const std::vector<std::string> &ifaces);
bool from_bus(Socket *sd);
bool bus_subscribe(const std::vector<ieee1905_1::eMessageType> &msg_types);
bool bus_connect(const std::string &beerocks_temp_path, const bool local_master);
void bus_connected(Socket *sd);
bool send_cmdu_to_bus(ieee1905_1::CmduMessage &cmdu, const std::string &dst_mac,
const std::string &src_mac, uint16_t length);
static const std::string MULTICAST_MAC_ADDR;
private:
bool bus_init();
bool bus_send(ieee1905_1::CmduMessage &cmdu, const std::string &dst_mac,
const std::string &src_mac, uint16_t length);
bool handle_cmdu_message_bus();
int poll_timeout_ms = 500;
#ifdef UDS_BUS
Socket *bus = nullptr;
std::unique_ptr<SocketServer> bus_server_socket;
#else
std::shared_ptr<mapf::LocalBusInterface> bus = nullptr;
std::shared_ptr<mapf::Poller> poller = nullptr;
#endif
};
} // namespace btl
} // namespace beerocks
#endif //_BEEROCKS_MAPF_SOCKET_THREAD_H_
| 31.285714 | 89 | 0.716895 | [
"vector"
] |
fa48b3729a2c19cc87206fa145d1c3b0bc960a5e | 956 | h | C | include/optimizer/adagrad/adagrad.h | Dando18/skepsi | 20820ee43a0eccaa39420a2bc2f4695007f79c2d | [
"MIT"
] | 25 | 2019-07-11T11:14:42.000Z | 2021-12-01T18:07:31.000Z | include/optimizer/adagrad/adagrad.h | Dando18/skepsi | 20820ee43a0eccaa39420a2bc2f4695007f79c2d | [
"MIT"
] | 30 | 2019-07-10T15:47:01.000Z | 2021-03-19T09:55:29.000Z | include/optimizer/adagrad/adagrad.h | Dando18/skepsi | 20820ee43a0eccaa39420a2bc2f4695007f79c2d | [
"MIT"
] | 12 | 2019-05-31T20:30:24.000Z | 2021-11-29T03:06:58.000Z | /**
* @file adagrad.h
* @author Sedrick Keh
* @version 1.0
* @date 2019-07-25
*
* @copyright Copyright (c) 2019
*/
#pragma once
#include <map>
#include "compute/gradients.h"
#include "compute/gradtable.h"
#include "compute/operation.h"
#include "math/optimizer_math/adagrad.h"
#include "optimizer/optimizer.h"
namespace magmadnn {
namespace optimizer {
template <typename T>
class AdaGrad : public Optimizer<T> {
public:
AdaGrad(T learning_rate);
virtual void minimize(op::Operation<T> *obj_func, const std::vector<op::Operation<T> *> &wrt);
void set_learning_rate(T learning_rate) { this->learning_rate = learning_rate; }
T get_learning_rate() { return this->learning_rate; }
protected:
virtual void update(op::Operation<T> *var, Tensor<T> *grad);
T learning_rate;
op::GradTable<T> table;
std::map<op::Operation<T> *, Tensor<T> *> scaling_tensors;
};
} // namespace optimizer
} // namespace magmadnn | 23.317073 | 98 | 0.692469 | [
"vector"
] |
fa4d0cc6596697e50cda9be4e793504aa43e1ed0 | 74,974 | c | C | iked/ikev1/oakley.c | jpuhlman/racoon2 | 7b68950328454b0e91ba24698c10c4a790705cc1 | [
"BSD-3-Clause"
] | 17 | 2018-06-27T02:55:47.000Z | 2022-01-12T03:18:30.000Z | iked/ikev1/oakley.c | jpuhlman/racoon2 | 7b68950328454b0e91ba24698c10c4a790705cc1 | [
"BSD-3-Clause"
] | 8 | 2019-01-10T22:13:21.000Z | 2022-03-07T09:04:27.000Z | iked/ikev1/oakley.c | jpuhlman/racoon2 | 7b68950328454b0e91ba24698c10c4a790705cc1 | [
"BSD-3-Clause"
] | 11 | 2018-07-29T18:02:29.000Z | 2021-06-30T02:58:49.000Z | /* $Id: oakley.c,v 1.14 2008/07/07 09:36:08 fukumoto Exp $ */
/*
* Copyright (C) 1995, 1996, 1997, and 1998 WIDE Project.
* 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. Neither the name of the project 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 PROJECT 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 PROJECT OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#include "config.h"
#include <sys/types.h>
#include <sys/param.h>
#include <sys/socket.h> /* XXX for subjectaltname */
#include <netinet/in.h> /* XXX for subjectaltname */
#include <netdb.h>
#include <openssl/pkcs7.h>
#include <openssl/x509.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#if TIME_WITH_SYS_TIME
# include <sys/time.h>
# include <time.h>
#else
# if HAVE_SYS_TIME_H
# include <sys/time.h>
# else
# include <time.h>
# endif
#endif
#ifdef ENABLE_HYBRID
#include <resolv.h>
#endif
#include "racoon.h"
#include "var.h"
/* #include "misc.h" */
/* #include "vmbuf.h" */
#include "str2val.h"
#include "plog.h"
#include "debug.h"
#include "isakmp.h"
#include "isakmp_var.h"
#ifdef ENABLE_HYBRID
#include "isakmp_xauth.h"
#include "isakmp_cfg.h"
#endif
#include "oakley.h"
/* #include "admin.h" */
/* #include "privsep.h" */
/* #include "localconf.h" */
#include "remoteconf.h"
/* #include "policy.h" */
#include "isakmp_impl.h"
#include "ikev1_impl.h"
#include "handler.h"
#include "ipsec_doi.h"
#include "algorithm.h"
#include "dhgroup.h"
/* #include "sainfo.h" */
#include "proposal.h"
#include "crypto_impl.h"
/* #include "dnssec.h" */
#include "sockmisc.h"
#include "strnames.h"
#include "gcmalloc.h"
/* #include "rsalist.h" */
#include "ike_conf.h"
#ifdef HAVE_GSSAPI
#include "gssapi.h"
#endif
#define OUTBOUND_SA 0
#define INBOUND_SA 1
#ifdef notyet
static int oakley_check_dh_pub (rc_vchar_t *, rc_vchar_t **);
#endif
static int oakley_compute_keymat_x (struct ph2handle *, int, int);
static int get_cert_fromlocal (struct ph1handle *, int);
#ifdef notyet
static int get_plainrsa_fromlocal (struct ph1handle *, int);
#endif
static int oakley_check_certid (struct ph1handle *iph1);
static int check_typeofcertname (int, int);
static cert_t *save_certbuf (struct isakmp_gen *);
static cert_t *save_certx509 (X509 *);
static int oakley_padlen (int, int);
int
oakley_get_defaultlifetime(void)
{
return OAKLEY_ATTR_SA_LD_SEC_DEFAULT;
}
void
oakley_dhgrp_free(struct dhgroup *dhgrp)
{
if (dhgrp->prime)
rc_vfree(dhgrp->prime);
if (dhgrp->curve_a)
rc_vfree(dhgrp->curve_a);
if (dhgrp->curve_b)
rc_vfree(dhgrp->curve_b);
if (dhgrp->order)
rc_vfree(dhgrp->order);
racoon_free(dhgrp);
}
#if 0
/*
* RFC2409 5
* The length of the Diffie-Hellman public value MUST be equal to the
* length of the prime modulus over which the exponentiation was
* performed, prepending zero bits to the value if necessary.
*/
static int
oakley_check_dh_pub(prime, pub0)
rc_vchar_t *prime, **pub0;
{
rc_vchar_t *tmp;
rc_vchar_t *pub = *pub0;
if (prime->l == pub->l)
return 0;
if (prime->l < pub->l) {
/* what should i do ? */
plog(PLOG_INTERR, PLOGLOC, NULL,
"invalid public information was generated.\n");
return -1;
}
/* prime->l > pub->l */
tmp = rc_vmalloc(prime->l);
if (tmp == NULL) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"failed to get DH buffer.\n");
return -1;
}
memcpy(tmp->v + prime->l - pub->l, pub->v, pub->l);
rc_vfree(*pub0);
*pub0 = tmp;
return 0;
}
#endif
/*
* copy pre-defined dhgroup values.
*/
int
oakley_setdhgroup(int group, struct dhgroup **dhgrp)
{
struct dhgroup *g;
*dhgrp = NULL; /* just make sure, initialize */
g = alg_oakley_dhdef_group(group);
if (g == NULL) {
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"invalid DH parameter grp=%d.\n", group);
return -1;
}
if (!g->type || !g->prime || !g->gen1) {
/* unsuported */
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"unsupported DH parameters grp=%d.\n", group);
return -1;
}
*dhgrp = racoon_calloc(1, sizeof(struct dhgroup));
if (*dhgrp == NULL) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"failed to get DH buffer.\n");
return 0;
}
/* set defined dh vlaues */
memcpy(*dhgrp, g, sizeof(*g));
(*dhgrp)->prime = rc_vdup(g->prime);
return 0;
}
/*
* PRF
*
* NOTE: we do not support prf with different input/output bitwidth,
* so we do not implement RFC2409 Appendix B (DOORAK-MAC example) in
* oakley_compute_keymat(). If you add support for such prf function,
* modify oakley_compute_keymat() accordingly.
*/
rc_vchar_t *
oakley_prf(rc_vchar_t *key, rc_vchar_t *buf, struct ph1handle *iph1)
{
rc_vchar_t *res = NULL;
int type;
if (iph1->approval == NULL) {
/*
* it's before negotiating hash algorithm.
* We use md5 as default.
*/
type = OAKLEY_ATTR_HASH_ALG_MD5;
} else
type = iph1->approval->hashtype;
res = alg_oakley_hmacdef_one(type, key, buf);
if (res == NULL) {
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"invalid hmac algorithm %d.\n", type);
return NULL;
}
return res;
}
/*
* hash
*/
rc_vchar_t *
oakley_hash(rc_vchar_t *buf, struct ph1handle *iph1)
{
rc_vchar_t *res = NULL;
int type;
if (iph1->approval == NULL) {
/*
* it's before negotiating hash algorithm.
* We use md5 as default.
*/
type = OAKLEY_ATTR_HASH_ALG_MD5;
} else
type = iph1->approval->hashtype;
res = alg_oakley_hashdef_one(type, buf);
if (res == NULL) {
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"invalid hash algoriym %d.\n", type);
return NULL;
}
return res;
}
/*
* compute KEYMAT
* see seciton 5.5 Phase 2 - Quick Mode in isakmp-oakley-05.
*/
int
oakley_compute_keymat(struct ph2handle *iph2, int side)
{
int error = -1;
/* compute sharing secret of DH when PFS */
if (iph2->approval->pfs_group && iph2->dhpub_p) {
if (oakley_dh_compute(iph2->pfsgrp, iph2->dhpub,
iph2->dhpriv, iph2->dhpub_p, &iph2->dhgxy) < 0)
goto end;
}
/* compute keymat */
if (oakley_compute_keymat_x(iph2, side, INBOUND_SA) < 0
|| oakley_compute_keymat_x(iph2, side, OUTBOUND_SA) < 0)
goto end;
plog(PLOG_DEBUG, PLOGLOC, NULL, "KEYMAT computed.\n");
error = 0;
end:
return error;
}
/*
* compute KEYMAT.
* KEYMAT = prf(SKEYID_d, protocol | SPI | Ni_b | Nr_b).
* If PFS is desired and KE payloads were exchanged,
* KEYMAT = prf(SKEYID_d, g(qm)^xy | protocol | SPI | Ni_b | Nr_b)
*
* NOTE: we do not support prf with different input/output bitwidth,
* so we do not implement RFC2409 Appendix B (DOORAK-MAC example).
*/
static int
oakley_compute_keymat_x(struct ph2handle *iph2, int side, int sa_dir)
{
rc_vchar_t *buf = NULL, *res = NULL, *bp;
char *p;
int len;
int error = -1;
int pfs = 0;
int dupkeymat; /* generate K[1-dupkeymat] */
struct saproto *pr;
struct satrns *tr;
int encklen, authklen, l;
pfs = ((iph2->approval->pfs_group && iph2->dhgxy) ? 1 : 0);
len = pfs ? iph2->dhgxy->l : 0;
len += (1
+ sizeof(uint32_t) /* XXX SPI size */
+ iph2->nonce->l
+ iph2->nonce_p->l);
buf = rc_vmalloc(len);
if (buf == NULL) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"failed to get keymat buffer.\n");
goto end;
}
for (pr = iph2->approval->head; pr != NULL; pr = pr->next) {
p = buf->v;
/* if PFS */
if (pfs) {
memcpy(p, iph2->dhgxy->v, iph2->dhgxy->l);
p += iph2->dhgxy->l;
}
p[0] = pr->proto_id;
p += 1;
memcpy(p, (sa_dir == INBOUND_SA ? &pr->spi : &pr->spi_p),
sizeof(pr->spi));
p += sizeof(pr->spi);
bp = (side == INITIATOR ? iph2->nonce : iph2->nonce_p);
memcpy(p, bp->v, bp->l);
p += bp->l;
bp = (side == INITIATOR ? iph2->nonce_p : iph2->nonce);
memcpy(p, bp->v, bp->l);
p += bp->l;
/* compute IV */
plog(PLOG_DEBUG, PLOGLOC, NULL, "KEYMAT compute with\n");
plogdump(PLOG_DEBUG, PLOGLOC, 0, buf->v, buf->l);
/* res = K1 */
res = oakley_prf(iph2->ph1->skeyid_d, buf, iph2->ph1);
if (res == NULL)
goto end;
/* compute key length needed */
encklen = authklen = 0;
switch (pr->proto_id) {
case IPSECDOI_PROTO_IPSEC_ESP:
for (tr = pr->head; tr; tr = tr->next) {
l = alg_ipsec_encdef_keylen(tr->trns_id,
tr->encklen);
if (l > encklen)
encklen = l;
l = alg_ipsec_hmacdef_hashlen(tr->authtype);
if (l > authklen)
authklen = l;
}
break;
case IPSECDOI_PROTO_IPSEC_AH:
for (tr = pr->head; tr; tr = tr->next) {
l = alg_ipsec_hmacdef_hashlen(tr->trns_id);
if (l > authklen)
authklen = l;
}
break;
default:
break;
}
plog(PLOG_DEBUG, PLOGLOC, NULL, "encklen=%d authklen=%d\n",
encklen, authklen);
dupkeymat = (encklen + authklen) / 8 / res->l;
dupkeymat += 2; /* safety mergin */
if (dupkeymat < 3)
dupkeymat = 3;
plog(PLOG_DEBUG, PLOGLOC, NULL,
"generating %zu bits of key (dupkeymat=%d)\n",
dupkeymat * 8 * res->l, dupkeymat);
if (0 < --dupkeymat) {
rc_vchar_t *prev = res; /* K(n-1) */
rc_vchar_t *seed = NULL; /* seed for Kn */
size_t xl;
/*
* generating long key (isakmp-oakley-08 5.5)
* KEYMAT = K1 | K2 | K3 | ...
* where
* src = [ g(qm)^xy | ] protocol | SPI | Ni_b | Nr_b
* K1 = prf(SKEYID_d, src)
* K2 = prf(SKEYID_d, K1 | src)
* K3 = prf(SKEYID_d, K2 | src)
* Kn = prf(SKEYID_d, K(n-1) | src)
*/
plog(PLOG_DEBUG, PLOGLOC, NULL,
"generating K1...K%d for KEYMAT.\n",
dupkeymat + 1);
seed = rc_vmalloc(prev->l + buf->l);
if (seed == NULL) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"failed to get keymat buffer.\n");
if (prev && prev != res)
rc_vfree(prev);
goto end;
}
while (dupkeymat--) {
rc_vchar_t *this = NULL; /* Kn */
int update_prev;
memcpy(seed->u, prev->v, prev->l);
memcpy(seed->u + prev->l, buf->v, buf->l);
this = oakley_prf(iph2->ph1->skeyid_d, seed,
iph2->ph1);
if (!this) {
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"oakley_prf memory overflow\n");
if (prev && prev != res)
rc_vfree(prev);
rc_vfree(this);
rc_vfree(seed);
goto end;
}
update_prev = (prev && prev == res) ? 1 : 0;
xl = res->l;
res = rc_vrealloc(res, xl + this->l);
if (update_prev)
prev = res;
if (res == NULL) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"failed to get keymat buffer.\n");
if (prev && prev != res)
rc_vfree(prev);
rc_vfree(this);
rc_vfree(seed);
goto end;
}
memcpy(res->u + xl, this->v, this->l);
if (prev && prev != res)
rc_vfree(prev);
prev = this;
this = NULL;
}
if (prev && prev != res)
rc_vfree(prev);
rc_vfree(seed);
}
plogdump(PLOG_DEBUG, PLOGLOC, 0, res->v, res->l);
if (sa_dir == INBOUND_SA)
pr->keymat = res;
else
pr->keymat_p = res;
res = NULL;
}
error = 0;
end:
if (error) {
for (pr = iph2->approval->head; pr != NULL; pr = pr->next) {
if (pr->keymat) {
rc_vfree(pr->keymat);
pr->keymat = NULL;
}
if (pr->keymat_p) {
rc_vfree(pr->keymat_p);
pr->keymat_p = NULL;
}
}
}
if (buf != NULL)
rc_vfree(buf);
if (res)
rc_vfree(res);
return error;
}
#if notyet
/*
* NOTE: Must terminate by NULL.
*/
rc_vchar_t *
oakley_compute_hashx(struct ph1handle *iph1, ...)
{
rc_vchar_t *buf, *res;
rc_vchar_t *s;
caddr_t p;
int len;
va_list ap;
/* get buffer length */
va_start(ap, iph1);
len = 0;
while ((s = va_arg(ap, rc_vchar_t *)) != NULL) {
len += s->l
}
va_end(ap);
buf = rc_vmalloc(len);
if (buf == NULL) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"failed to get hash buffer\n");
return NULL;
}
/* set buffer */
va_start(ap, iph1);
p = buf->v;
while ((s = va_arg(ap, char *)) != NULL) {
memcpy(p, s->v, s->l);
p += s->l;
}
va_end(ap);
plog(PLOG_DEBUG, PLOGLOC, NULL, "HASH with: \n");
plogdump(PLOG_DEBUG, PLOGLOC, 0, buf->v, buf->l);
/* compute HASH */
res = oakley_prf(iph1->skeyid_a, buf, iph1);
rc_vfree(buf);
if (res == NULL)
return NULL;
plog(PLOG_DEBUG, PLOGLOC, NULL, "HASH computed:\n");
plogdump(PLOG_DEBUG, PLOGLOC, 0, res->v, res->l);
return res;
}
#endif
/*
* compute HASH(3) prf(SKEYID_a, 0 | M-ID | Ni_b | Nr_b)
* see seciton 5.5 Phase 2 - Quick Mode in isakmp-oakley-05.
*/
rc_vchar_t *
oakley_compute_hash3(struct ph1handle *iph1, uint32_t msgid, rc_vchar_t *body)
{
rc_vchar_t *buf = 0, *res = 0;
int len;
/* create buffer */
len = 1 + sizeof(uint32_t) + body->l;
buf = rc_vmalloc(len);
if (buf == NULL) {
plog(PLOG_DEBUG, PLOGLOC, NULL,
"failed to get hash buffer\n");
goto end;
}
buf->u[0] = 0;
memcpy(buf->u + 1, (char *)&msgid, sizeof(msgid));
memcpy(buf->u + 1 + sizeof(uint32_t), body->v, body->l);
plog(PLOG_DEBUG, PLOGLOC, NULL, "HASH with: \n");
plogdump(PLOG_DEBUG, PLOGLOC, 0, buf->v, buf->l);
/* compute HASH */
res = oakley_prf(iph1->skeyid_a, buf, iph1);
if (res == NULL)
goto end;
plog(PLOG_DEBUG, PLOGLOC, NULL, "HASH computed:\n");
plogdump(PLOG_DEBUG, PLOGLOC, 0, res->v, res->l);
end:
if (buf != NULL)
rc_vfree(buf);
return res;
}
/*
* compute HASH type of prf(SKEYID_a, M-ID | buffer)
* e.g.
* for quick mode HASH(1):
* prf(SKEYID_a, M-ID | SA | Ni [ | KE ] [ | IDci | IDcr ])
* for quick mode HASH(2):
* prf(SKEYID_a, M-ID | Ni_b | SA | Nr [ | KE ] [ | IDci | IDcr ])
* for Informational exchange:
* prf(SKEYID_a, M-ID | N/D)
*/
rc_vchar_t *
oakley_compute_hash1(struct ph1handle *iph1, uint32_t msgid, rc_vchar_t *body)
{
rc_vchar_t *buf = NULL, *res = NULL;
char *p;
int len;
/* create buffer */
len = sizeof(uint32_t) + body->l;
buf = rc_vmalloc(len);
if (buf == NULL) {
plog(PLOG_DEBUG, PLOGLOC, NULL,
"failed to get hash buffer\n");
goto end;
}
p = buf->v;
memcpy(buf->v, (char *)&msgid, sizeof(msgid));
p += sizeof(uint32_t);
memcpy(p, body->v, body->l);
plog(PLOG_DEBUG, PLOGLOC, NULL, "HASH with:\n");
plogdump(PLOG_DEBUG, PLOGLOC, 0, buf->v, buf->l);
/* compute HASH */
res = oakley_prf(iph1->skeyid_a, buf, iph1);
if (res == NULL)
goto end;
plog(PLOG_DEBUG, PLOGLOC, NULL, "HASH computed:\n");
plogdump(PLOG_DEBUG, PLOGLOC, 0, res->v, res->l);
end:
if (buf != NULL)
rc_vfree(buf);
return res;
}
/*
* compute phase1 HASH
* main/aggressive
* I-digest = prf(SKEYID, g^i | g^r | CKY-I | CKY-R | SAi_b | ID_i1_b)
* R-digest = prf(SKEYID, g^r | g^i | CKY-R | CKY-I | SAi_b | ID_r1_b)
* for gssapi, also include all GSS tokens, and call gss_wrap on the result
*/
rc_vchar_t *
oakley_ph1hash_common(struct ph1handle *iph1, int sw)
{
rc_vchar_t *buf = NULL, *res = NULL, *bp;
char *p, *bp2;
int len, bl;
#ifdef HAVE_GSSAPI
rc_vchar_t *gsstokens = NULL;
#endif
/* create buffer */
len = iph1->dhpub->l
+ iph1->dhpub_p->l
+ sizeof(isakmp_cookie_t) * 2
+ iph1->sa->l
+ (sw == GENERATE ? iph1->id->l : iph1->id_p->l);
#ifdef HAVE_GSSAPI
if (AUTHMETHOD(iph1) == OAKLEY_ATTR_AUTH_METHOD_GSSAPI_KRB) {
if (iph1->gi_i != NULL && iph1->gi_r != NULL) {
bp = (sw == GENERATE ? iph1->gi_i : iph1->gi_r);
len += bp->l;
}
if (sw == GENERATE)
gssapi_get_itokens(iph1, &gsstokens);
else
gssapi_get_rtokens(iph1, &gsstokens);
if (gsstokens == NULL)
return NULL;
len += gsstokens->l;
}
#endif
buf = rc_vmalloc(len);
if (buf == NULL) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"failed to get hash buffer\n");
goto end;
}
p = buf->v;
bp = (sw == GENERATE ? iph1->dhpub : iph1->dhpub_p);
memcpy(p, bp->v, bp->l);
p += bp->l;
bp = (sw == GENERATE ? iph1->dhpub_p : iph1->dhpub);
memcpy(p, bp->v, bp->l);
p += bp->l;
if (iph1->side == INITIATOR)
bp2 = (sw == GENERATE ?
(char *)&iph1->index.i_ck : (char *)&iph1->index.r_ck);
else
bp2 = (sw == GENERATE ?
(char *)&iph1->index.r_ck : (char *)&iph1->index.i_ck);
bl = sizeof(isakmp_cookie_t);
memcpy(p, bp2, bl);
p += bl;
if (iph1->side == INITIATOR)
bp2 = (sw == GENERATE ?
(char *)&iph1->index.r_ck : (char *)&iph1->index.i_ck);
else
bp2 = (sw == GENERATE ?
(char *)&iph1->index.i_ck : (char *)&iph1->index.r_ck);
bl = sizeof(isakmp_cookie_t);
memcpy(p, bp2, bl);
p += bl;
bp = iph1->sa;
memcpy(p, bp->v, bp->l);
p += bp->l;
bp = (sw == GENERATE ? iph1->id : iph1->id_p);
memcpy(p, bp->v, bp->l);
p += bp->l;
#ifdef HAVE_GSSAPI
if (AUTHMETHOD(iph1) == OAKLEY_ATTR_AUTH_METHOD_GSSAPI_KRB) {
if (iph1->gi_i != NULL && iph1->gi_r != NULL) {
bp = (sw == GENERATE ? iph1->gi_i : iph1->gi_r);
memcpy(p, bp->v, bp->l);
p += bp->l;
}
memcpy(p, gsstokens->v, gsstokens->l);
p += gsstokens->l;
}
#endif
plog(PLOG_DEBUG, PLOGLOC, NULL, "HASH with:\n");
plogdump(PLOG_DEBUG, PLOGLOC, 0, buf->v, buf->l);
/* compute HASH */
res = oakley_prf(iph1->skeyid, buf, iph1);
if (res == NULL)
goto end;
plog(PLOG_DEBUG, PLOGLOC, NULL, "HASH (%s) computed:\n",
iph1->side == INITIATOR ? "init" : "resp");
plogdump(PLOG_DEBUG, PLOGLOC, 0, res->v, res->l);
end:
if (buf != NULL)
rc_vfree(buf);
#ifdef HAVE_GSSAPI
if (gsstokens != NULL)
rc_vfree(gsstokens);
#endif
return res;
}
/*
* compute HASH_I on base mode.
* base:psk,rsa
* HASH_I = prf(SKEYID, g^xi | CKY-I | CKY-R | SAi_b | IDii_b)
* base:sig
* HASH_I = prf(hash(Ni_b | Nr_b), g^xi | CKY-I | CKY-R | SAi_b | IDii_b)
*/
rc_vchar_t *
oakley_ph1hash_base_i(struct ph1handle *iph1, int sw)
{
rc_vchar_t *buf = NULL, *res = NULL, *bp;
rc_vchar_t *hashkey = NULL;
rc_vchar_t *hash = NULL; /* for signature mode */
char *p;
int len;
/* sanity check */
if (iph1->etype != ISAKMP_ETYPE_BASE) {
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"invalid etype for this hash function\n");
return NULL;
}
switch (AUTHMETHOD(iph1)) {
case OAKLEY_ATTR_AUTH_METHOD_PSKEY:
case OAKLEY_ATTR_AUTH_METHOD_RSAENC:
case OAKLEY_ATTR_AUTH_METHOD_RSAREV:
#ifdef ENABLE_HYBRID
case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSAENC_I:
case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSAENC_R:
case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSAREV_I:
case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSAREV_R:
case FICTIVE_AUTH_METHOD_XAUTH_PSKEY_I:
case OAKLEY_ATTR_AUTH_METHOD_XAUTH_PSKEY_R:
#endif
if (iph1->skeyid == NULL) {
plog(PLOG_PROTOERR, PLOGLOC, NULL, "no SKEYID found.\n");
return NULL;
}
hashkey = iph1->skeyid;
break;
case OAKLEY_ATTR_AUTH_METHOD_DSSSIG:
case OAKLEY_ATTR_AUTH_METHOD_RSASIG:
#ifdef HAVE_GSSAPI
case OAKLEY_ATTR_AUTH_METHOD_GSSAPI_KRB:
#endif
#ifdef ENABLE_HYBRID
case OAKLEY_ATTR_AUTH_METHOD_HYBRID_RSA_I:
case OAKLEY_ATTR_AUTH_METHOD_HYBRID_RSA_R:
case OAKLEY_ATTR_AUTH_METHOD_HYBRID_DSS_I:
case OAKLEY_ATTR_AUTH_METHOD_HYBRID_DSS_R:
case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSASIG_I:
case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSASIG_R:
case OAKLEY_ATTR_AUTH_METHOD_XAUTH_DSSSIG_I:
case OAKLEY_ATTR_AUTH_METHOD_XAUTH_DSSSIG_R:
#endif
/* make hash for seed */
len = iph1->nonce->l + iph1->nonce_p->l;
buf = rc_vmalloc(len);
if (buf == NULL) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"failed to get hash buffer\n");
goto end;
}
p = buf->v;
bp = (sw == GENERATE ? iph1->nonce_p : iph1->nonce);
memcpy(p, bp->v, bp->l);
p += bp->l;
bp = (sw == GENERATE ? iph1->nonce : iph1->nonce_p);
memcpy(p, bp->v, bp->l);
p += bp->l;
hash = oakley_hash(buf, iph1);
if (hash == NULL)
goto end;
rc_vfree(buf);
buf = NULL;
hashkey = hash;
break;
default:
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"not supported authentication method %d\n",
iph1->approval->authmethod);
return NULL;
}
len = (sw == GENERATE ? iph1->dhpub->l : iph1->dhpub_p->l)
+ sizeof(isakmp_cookie_t) * 2
+ iph1->sa->l
+ (sw == GENERATE ? iph1->id->l : iph1->id_p->l);
buf = rc_vmalloc(len);
if (buf == NULL) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"failed to get hash buffer\n");
goto end;
}
p = buf->v;
bp = (sw == GENERATE ? iph1->dhpub : iph1->dhpub_p);
memcpy(p, bp->v, bp->l);
p += bp->l;
memcpy(p, &iph1->index.i_ck, sizeof(isakmp_cookie_t));
p += sizeof(isakmp_cookie_t);
memcpy(p, &iph1->index.r_ck, sizeof(isakmp_cookie_t));
p += sizeof(isakmp_cookie_t);
memcpy(p, iph1->sa->v, iph1->sa->l);
p += iph1->sa->l;
bp = (sw == GENERATE ? iph1->id : iph1->id_p);
memcpy(p, bp->v, bp->l);
p += bp->l;
plog(PLOG_DEBUG, PLOGLOC, NULL, "HASH_I with:\n");
plogdump(PLOG_DEBUG, PLOGLOC, 0, buf->v, buf->l);
/* compute HASH */
res = oakley_prf(hashkey, buf, iph1);
if (res == NULL)
goto end;
plog(PLOG_DEBUG, PLOGLOC, NULL, "HASH_I computed:\n");
plogdump(PLOG_DEBUG, PLOGLOC, 0, res->v, res->l);
end:
if (hash != NULL)
rc_vfree(hash);
if (buf != NULL)
rc_vfree(buf);
return res;
}
/*
* compute HASH_R on base mode for signature method.
* base:
* HASH_R = prf(hash(Ni_b | Nr_b), g^xi | g^xr | CKY-I | CKY-R | SAi_b | IDii_b)
*/
rc_vchar_t *
oakley_ph1hash_base_r(struct ph1handle *iph1, int sw)
{
rc_vchar_t *buf = NULL, *res = NULL, *bp;
rc_vchar_t *hash = NULL;
char *p;
int len;
/* sanity check */
if (iph1->etype != ISAKMP_ETYPE_BASE) {
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"invalid etype for this hash function\n");
return NULL;
}
switch(AUTHMETHOD(iph1)) {
case OAKLEY_ATTR_AUTH_METHOD_DSSSIG:
case OAKLEY_ATTR_AUTH_METHOD_RSASIG:
#ifdef ENABLE_HYBRID
case OAKLEY_ATTR_AUTH_METHOD_HYBRID_RSA_I:
case OAKLEY_ATTR_AUTH_METHOD_HYBRID_RSA_R:
case OAKLEY_ATTR_AUTH_METHOD_HYBRID_DSS_I:
case OAKLEY_ATTR_AUTH_METHOD_HYBRID_DSS_R:
case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSASIG_I:
case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSASIG_R:
case OAKLEY_ATTR_AUTH_METHOD_XAUTH_DSSSIG_I:
case OAKLEY_ATTR_AUTH_METHOD_XAUTH_DSSSIG_R:
case FICTIVE_AUTH_METHOD_XAUTH_PSKEY_I:
#endif
break;
default:
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"not supported authentication method %d\n",
iph1->approval->authmethod);
return NULL;
break;
}
/* make hash for seed */
len = iph1->nonce->l + iph1->nonce_p->l;
buf = rc_vmalloc(len);
if (buf == NULL) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"failed to get hash buffer\n");
goto end;
}
p = buf->v;
bp = (sw == GENERATE ? iph1->nonce_p : iph1->nonce);
memcpy(p, bp->v, bp->l);
p += bp->l;
bp = (sw == GENERATE ? iph1->nonce : iph1->nonce_p);
memcpy(p, bp->v, bp->l);
p += bp->l;
hash = oakley_hash(buf, iph1);
if (hash == NULL)
goto end;
rc_vfree(buf);
buf = NULL;
/* make really hash */
len = (sw == GENERATE ? iph1->dhpub_p->l : iph1->dhpub->l)
+ (sw == GENERATE ? iph1->dhpub->l : iph1->dhpub_p->l)
+ sizeof(isakmp_cookie_t) * 2
+ iph1->sa->l
+ (sw == GENERATE ? iph1->id_p->l : iph1->id->l);
buf = rc_vmalloc(len);
if (buf == NULL) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"failed to get hash buffer\n");
goto end;
}
p = buf->v;
bp = (sw == GENERATE ? iph1->dhpub_p : iph1->dhpub);
memcpy(p, bp->v, bp->l);
p += bp->l;
bp = (sw == GENERATE ? iph1->dhpub : iph1->dhpub_p);
memcpy(p, bp->v, bp->l);
p += bp->l;
memcpy(p, &iph1->index.i_ck, sizeof(isakmp_cookie_t));
p += sizeof(isakmp_cookie_t);
memcpy(p, &iph1->index.r_ck, sizeof(isakmp_cookie_t));
p += sizeof(isakmp_cookie_t);
memcpy(p, iph1->sa->v, iph1->sa->l);
p += iph1->sa->l;
bp = (sw == GENERATE ? iph1->id_p : iph1->id);
memcpy(p, bp->v, bp->l);
p += bp->l;
plog(PLOG_DEBUG, PLOGLOC, NULL, "HASH with:\n");
plogdump(PLOG_DEBUG, PLOGLOC, 0, buf->v, buf->l);
/* compute HASH */
res = oakley_prf(hash, buf, iph1);
if (res == NULL)
goto end;
plog(PLOG_DEBUG, PLOGLOC, NULL, "HASH computed:\n");
plogdump(PLOG_DEBUG, PLOGLOC, 0, res->v, res->l);
end:
if (buf != NULL)
rc_vfree(buf);
if (hash)
rc_vfree(hash);
return res;
}
/*
* compute each authentication method in phase 1.
* OUT:
* 0: OK
* -1: error
* other: error to be reply with notification.
* the value is notification type.
*/
int
oakley_validate_auth(struct ph1handle *iph1)
{
rc_vchar_t *my_hash = NULL;
int result;
#ifdef HAVE_GSSAPI
rc_vchar_t *gsshash = NULL;
#endif
#ifdef ENABLE_STATS
struct timeval start, end;
#endif
#ifdef ENABLE_STATS
gettimeofday(&start, NULL);
#endif
switch (AUTHMETHOD(iph1)) {
case OAKLEY_ATTR_AUTH_METHOD_PSKEY:
#ifdef ENABLE_HYBRID
case FICTIVE_AUTH_METHOD_XAUTH_PSKEY_I:
case OAKLEY_ATTR_AUTH_METHOD_XAUTH_PSKEY_R:
#endif
/* validate HASH */
{
char *r_hash;
if (iph1->id_p == NULL || iph1->pl_hash == NULL) {
plog(PLOG_PROTOERR, PLOGLOC, 0,
"few isakmp message received.\n");
return ISAKMP_NTYPE_PAYLOAD_MALFORMED;
}
#ifdef ENABLE_HYBRID
if (AUTHMETHOD(iph1) == FICTIVE_AUTH_METHOD_XAUTH_PSKEY_I &&
((iph1->mode_cfg->flags & ISAKMP_CFG_VENDORID_XAUTH) == 0))
{
plog(PLOG_PROTOERR, PLOGLOC, NULL, "No SIG was passed, "
"hybrid auth is enabled, "
"but peer is no Xauth compliant\n");
return ISAKMP_NTYPE_SITUATION_NOT_SUPPORTED;
break;
}
#endif
r_hash = (caddr_t)(iph1->pl_hash + 1);
plog(PLOG_DEBUG, PLOGLOC, NULL, "HASH received:\n");
plogdump(PLOG_DEBUG, PLOGLOC, 0, r_hash,
get_uint16(&iph1->pl_hash->h.len) - sizeof(*iph1->pl_hash));
switch (iph1->etype) {
case ISAKMP_ETYPE_IDENT:
case ISAKMP_ETYPE_AGG:
my_hash = oakley_ph1hash_common(iph1, VALIDATE);
break;
case ISAKMP_ETYPE_BASE:
if (iph1->side == INITIATOR)
my_hash = oakley_ph1hash_common(iph1, VALIDATE);
else
my_hash = oakley_ph1hash_base_i(iph1, VALIDATE);
break;
default:
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"invalid etype %d\n", iph1->etype);
return ISAKMP_NTYPE_INVALID_EXCHANGE_TYPE;
}
if (my_hash == NULL)
return ISAKMP_INTERNAL_ERROR;
result = memcmp(my_hash->v, r_hash, my_hash->l);
rc_vfree(my_hash);
if (result) {
plog(PLOG_PROTOERR, PLOGLOC, NULL, "HASH mismatched\n");
return ISAKMP_NTYPE_INVALID_HASH_INFORMATION;
}
plog(PLOG_DEBUG, PLOGLOC, NULL, "HASH for PSK validated.\n");
}
break;
case OAKLEY_ATTR_AUTH_METHOD_DSSSIG:
case OAKLEY_ATTR_AUTH_METHOD_RSASIG:
#ifdef ENABLE_HYBRID
case OAKLEY_ATTR_AUTH_METHOD_HYBRID_RSA_I:
case OAKLEY_ATTR_AUTH_METHOD_HYBRID_DSS_I:
case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSASIG_I:
case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSASIG_R:
case OAKLEY_ATTR_AUTH_METHOD_XAUTH_DSSSIG_I:
case OAKLEY_ATTR_AUTH_METHOD_XAUTH_DSSSIG_R:
#endif
{
int error = 0;
int certtype = 0;
/* validation */
if (iph1->id_p == NULL) {
plog(PLOG_PROTOERR, PLOGLOC, 0,
"no ID payload was passed.\n");
return ISAKMP_NTYPE_PAYLOAD_MALFORMED;
}
if (iph1->sig_p == NULL) {
plog(PLOG_PROTOERR, PLOGLOC, 0,
"no SIG payload was passed.\n");
return ISAKMP_NTYPE_PAYLOAD_MALFORMED;
}
plog(PLOG_DEBUG, PLOGLOC, NULL, "SIGN passed:\n");
plogdump(PLOG_DEBUG, PLOGLOC, 0, iph1->sig_p->v, iph1->sig_p->l);
/* get peer's cert */
switch (ikev1_getcert_method(iph1->rmconf)) {
case ISAKMP_GETCERT_PAYLOAD:
if (iph1->cert_p == NULL) {
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"no peer's CERT payload found.\n");
return ISAKMP_INTERNAL_ERROR;
}
break;
case ISAKMP_GETCERT_LOCALFILE:
switch (ikev1_certtype(iph1->rmconf)) {
case ISAKMP_CERT_X509SIGN:
if (ikev1_peerscertfile(iph1->rmconf) == NULL) {
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"no peer's CERT file found.\n");
return ISAKMP_INTERNAL_ERROR;
}
/* don't use cached cert */
if (iph1->cert_p != NULL) {
oakley_delcert(iph1->cert_p);
iph1->cert_p = NULL;
}
error = get_cert_fromlocal(iph1, 0);
break;
#ifdef notyet
case ISAKMP_CERT_PLAINRSA:
error = get_plainrsa_fromlocal(iph1, 0);
break;
#endif
}
if (error)
return ISAKMP_INTERNAL_ERROR;
break;
#ifdef notyet
case ISAKMP_GETCERT_DNS:
#ifdef notyet
if (ikev1_peerscertfile(iph1->rmconf) != NULL) {
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"why peer's CERT file is defined "
"though getcert method is dns ?\n");
return ISAKMP_INTERNAL_ERROR;
}
/* don't use cached cert */
if (iph1->cert_p != NULL) {
oakley_delcert(iph1->cert_p);
iph1->cert_p = NULL;
}
iph1->cert_p = dnssec_getcert(iph1->id_p);
if (iph1->cert_p == NULL) {
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"no CERT RR found.\n");
return ISAKMP_INTERNAL_ERROR;
}
#else
plog(PLOG_PROTOERR, PLOGLOC, 0,
"GETCERT_DNS unimplemented\n");
return ISAKMP_INTERNAL_ERROR;
#endif
break;
#endif
default:
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"invalid getcert_mothod: %d\n",
ikev1_getcert_method(iph1->rmconf));
return ISAKMP_INTERNAL_ERROR;
}
/* compare ID payload and certificate name */
if (ikev1_verify_cert(iph1->rmconf) &&
(error = oakley_check_certid(iph1)) != 0)
return error;
/* verify certificate */
if (ikev1_verify_cert(iph1->rmconf)
&& ikev1_getcert_method(iph1->rmconf) == ISAKMP_GETCERT_PAYLOAD) {
certtype = ikev1_certtype(iph1->rmconf);
#ifdef ENABLE_HYBRID
switch (AUTHMETHOD(iph1)) {
case OAKLEY_ATTR_AUTH_METHOD_HYBRID_RSA_I:
case OAKLEY_ATTR_AUTH_METHOD_HYBRID_DSS_I:
certtype = iph1->cert_p->type;
break;
default:
break;
}
#endif
switch (certtype) {
case ISAKMP_CERT_X509SIGN: {
#ifdef notyet
char path[MAXPATHLEN];
char *ca;
if (ikev1_certtype(iph1->rmconf) != NULL) {
getpathname(path, sizeof(path),
LC_PATHTYPE_CERT,
iph1->rmconf->cacertfile);
ca = path;
} else {
ca = NULL;
}
error = eay_check_x509cert(&iph1->cert_p->cert,
lcconf->pathinfo[LC_PATHTYPE_CERT],
ca, 0);
#else
error = eay_check_x509cert(&iph1->cert_p->cert,
0);
#endif
break;
}
default:
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"no supported certtype %d\n", certtype);
return ISAKMP_INTERNAL_ERROR;
}
if (error != 0) {
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"the peer's certificate is not verified.\n");
return ISAKMP_NTYPE_INVALID_CERT_AUTHORITY;
}
}
plog(PLOG_DEBUG, PLOGLOC, NULL, "CERT validated\n");
/* compute hash */
switch (iph1->etype) {
case ISAKMP_ETYPE_IDENT:
case ISAKMP_ETYPE_AGG:
my_hash = oakley_ph1hash_common(iph1, VALIDATE);
break;
case ISAKMP_ETYPE_BASE:
if (iph1->side == INITIATOR)
my_hash = oakley_ph1hash_base_r(iph1, VALIDATE);
else
my_hash = oakley_ph1hash_base_i(iph1, VALIDATE);
break;
default:
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"invalid etype %d\n", iph1->etype);
return ISAKMP_NTYPE_INVALID_EXCHANGE_TYPE;
}
if (my_hash == NULL)
return ISAKMP_INTERNAL_ERROR;
certtype = ikev1_certtype(iph1->rmconf);
#ifdef ENABLE_HYBRID
switch (AUTHMETHOD(iph1)) {
case OAKLEY_ATTR_AUTH_METHOD_HYBRID_RSA_I:
case OAKLEY_ATTR_AUTH_METHOD_HYBRID_DSS_I:
certtype = iph1->cert_p->type;
break;
default:
break;
}
#endif
/* check signature */
switch (certtype) {
case ISAKMP_CERT_X509SIGN:
case ISAKMP_CERT_DNS:
error = eay_check_x509sign(my_hash,
iph1->sig_p,
&iph1->cert_p->cert);
break;
#ifdef notyet
case ISAKMP_CERT_PLAINRSA:
iph1->rsa_p = rsa_try_check_rsasign(my_hash,
iph1->sig_p, iph1->rsa_candidates);
error = iph1->rsa_p ? 0 : -1;
break;
#endif
default:
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"no supported certtype %d\n",
certtype);
rc_vfree(my_hash);
return ISAKMP_INTERNAL_ERROR;
}
rc_vfree(my_hash);
if (error != 0) {
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"Invalid SIG.\n");
return ISAKMP_NTYPE_INVALID_SIGNATURE;
}
plog(PLOG_DEBUG, PLOGLOC, NULL, "SIG authenticated\n");
}
break;
#ifdef ENABLE_HYBRID
case OAKLEY_ATTR_AUTH_METHOD_HYBRID_RSA_R:
case OAKLEY_ATTR_AUTH_METHOD_HYBRID_DSS_R:
{
if ((iph1->mode_cfg->flags & ISAKMP_CFG_VENDORID_XAUTH) == 0) {
plog(PLOG_PROTOERR, PLOGLOC, NULL, "No SIG was passed, "
"hybrid auth is enabled, "
"but peer is no Xauth compliant\n");
return ISAKMP_NTYPE_SITUATION_NOT_SUPPORTED;
break;
}
plog(PLOG_INFO, PLOGLOC, NULL, "No SIG was passed, "
"but hybrid auth is enabled\n");
return 0;
break;
}
#endif
#ifdef HAVE_GSSAPI
case OAKLEY_ATTR_AUTH_METHOD_GSSAPI_KRB:
/* check if we're not into XAUTH_PSKEY_I instead */
#ifdef ENABLE_HYBRID
if (iph1->rmconf->xauth)
break;
#endif
switch (iph1->etype) {
case ISAKMP_ETYPE_IDENT:
case ISAKMP_ETYPE_AGG:
my_hash = oakley_ph1hash_common(iph1, VALIDATE);
break;
default:
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"invalid etype %d\n", iph1->etype);
return ISAKMP_NTYPE_INVALID_EXCHANGE_TYPE;
}
if (my_hash == NULL) {
if (gssapi_more_tokens(iph1))
return ISAKMP_NTYPE_INVALID_EXCHANGE_TYPE;
else
return ISAKMP_NTYPE_INVALID_HASH_INFORMATION;
}
gsshash = gssapi_unwraphash(iph1);
if (gsshash == NULL) {
rc_vfree(my_hash);
return ISAKMP_NTYPE_INVALID_HASH_INFORMATION;
}
result = memcmp(my_hash->v, gsshash->v, my_hash->l);
rc_vfree(my_hash);
rc_vfree(gsshash);
if (result) {
plog(PLOG_PROTOERR, PLOGLOC, NULL, "HASH mismatched\n");
return ISAKMP_NTYPE_INVALID_HASH_INFORMATION;
}
plog(PLOG_DEBUG, PLOGLOC, NULL, "hash compared OK\n");
break;
#endif
case OAKLEY_ATTR_AUTH_METHOD_RSAENC:
case OAKLEY_ATTR_AUTH_METHOD_RSAREV:
#ifdef ENABLE_HYBRID
case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSAENC_I:
case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSAENC_R:
case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSAREV_I:
case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSAREV_R:
#endif
if (iph1->id_p == NULL || iph1->pl_hash == NULL) {
plog(PLOG_PROTOERR, PLOGLOC, 0,
"few isakmp message received.\n");
return ISAKMP_NTYPE_PAYLOAD_MALFORMED;
}
plog(PLOG_PROTOERR, PLOGLOC, 0,
"not supported authmethod type %s\n",
s_oakley_attr_method(iph1->approval->authmethod));
return ISAKMP_INTERNAL_ERROR;
default:
plog(PLOG_PROTOERR, PLOGLOC, 0,
"invalid authmethod %d why ?\n",
iph1->approval->authmethod);
return ISAKMP_INTERNAL_ERROR;
}
#ifdef ENABLE_STATS
gettimeofday(&end, NULL);
syslog(LOG_NOTICE, "%s(%s): %8.6f", __func__,
s_oakley_attr_method(iph1->approval->authmethod),
timedelta(&start, &end));
#endif
return 0;
}
/* get my certificate
* NOTE: include certificate type.
*/
int
oakley_getmycert(struct ph1handle *iph1)
{
switch (ikev1_certtype(iph1->rmconf)) {
case ISAKMP_CERT_X509SIGN:
if (iph1->cert)
return 0;
return get_cert_fromlocal(iph1, 1);
#ifdef notyet
case ISAKMP_CERT_PLAINRSA:
if (iph1->rsa)
return 0;
return get_plainrsa_fromlocal(iph1, 1);
#endif
default:
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"Unknown certtype #%d\n",
ikev1_certtype(iph1->rmconf));
return -1;
}
}
/*
* get a CERT from local file.
* IN:
* my != 0 my cert.
* my == 0 peer's cert.
*/
static int
get_cert_fromlocal(struct ph1handle *iph1, int my)
{
rc_vchar_t *cert = NULL;
cert_t **certpl;
const char *certfile;
int error = -1;
if (my) {
certfile = ikev1_mycertfile(iph1->rmconf);
certpl = &iph1->cert;
} else {
certfile = ikev1_peerscertfile(iph1->rmconf);
certpl = &iph1->cert_p;
}
if (!certfile) {
plog(PLOG_PROTOERR, PLOGLOC, NULL, "no CERT defined.\n");
return 0;
}
switch (ikev1_certtype(iph1->rmconf)) {
case ISAKMP_CERT_X509SIGN:
case ISAKMP_CERT_DNS:
/* make public file name */
#if 0
getpathname(path, sizeof(path), LC_PATHTYPE_CERT, certfile);
cert = eay_get_x509cert(path);
#else
cert = eay_get_x509cert(certfile);
#endif
if (cert) {
char *p = NULL;
p = eay_get_x509text(cert);
plog(PLOG_DEBUG, PLOGLOC, NULL, "%s", p ? p : "\n");
racoon_free(p);
};
break;
default:
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"not supported certtype %d\n",
ikev1_certtype(iph1->rmconf));
goto end;
}
if (!cert) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"failed to get %s CERT.\n",
my ? "my" : "peers");
goto end;
}
*certpl = oakley_newcert();
if (!*certpl) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"failed to get cert buffer.\n");
goto end;
}
(*certpl)->pl = rc_vmalloc(cert->l + 1);
if ((*certpl)->pl == NULL) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"failed to get cert buffer\n");
oakley_delcert(*certpl);
*certpl = NULL;
goto end;
}
memcpy((*certpl)->pl->u + 1, cert->v, cert->l);
(*certpl)->pl->u[0] = ikev1_certtype(iph1->rmconf);
(*certpl)->type = ikev1_certtype(iph1->rmconf);
(*certpl)->cert.u = (*certpl)->pl->u + 1;
(*certpl)->cert.l = (*certpl)->pl->l - 1;
plog(PLOG_DEBUG, PLOGLOC, NULL, "created CERT payload:\n");
plogdump(PLOG_DEBUG, PLOGLOC, 0, (*certpl)->pl->v, (*certpl)->pl->l);
error = 0;
end:
if (cert != NULL)
rc_vfree(cert);
return error;
}
#ifdef notyet
static int
get_plainrsa_fromlocal(struct ph1handle *iph1, int my)
{
char path[MAXPATHLEN];
rc_vchar_t *cert = NULL;
char *certfile;
iph1->rsa_candidates = rsa_lookup_keys(iph1, my);
if (!iph1->rsa_candidates || rsa_list_count(iph1->rsa_candidates) == 0) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"%s RSA key not found for %s\n",
my ? "Private" : "Public",
saddr2str_fromto("%s <-> %s", iph1->local, iph1->remote));
goto end;
}
if (my && rsa_list_count(iph1->rsa_candidates) > 1) {
plog(PLOG_INTWARN, PLOGLOC, NULL,
"More than one (=%lu) private PlainRSA key found for %s\n",
rsa_list_count(iph1->rsa_candidates),
saddr2str_fromto("%s <-> %s", iph1->local, iph1->remote));
plog(PLOG_INTWARN, PLOGLOC, NULL,
"This may have unpredictable results, i.e. wrong key could be used!\n");
plog(PLOG_INTWARN, PLOGLOC, NULL,
"Consider using only one single private key for all peers...\n");
}
if (my) {
iph1->rsa = ((struct rsa_key *)genlist_next(iph1->rsa_candidates, NULL))->rsa;
genlist_free(iph1->rsa_candidates, NULL);
iph1->rsa_candidates = NULL;
}
error = 0;
end:
return error;
}
#endif
/* get signature */
int
oakley_getsign(struct ph1handle *iph1)
{
#if 0
char path[MAXPATHLEN];
#endif
rc_vchar_t *privkey = NULL;
int error = -1;
switch (ikev1_certtype(iph1->rmconf)) {
case ISAKMP_CERT_X509SIGN:
case ISAKMP_CERT_DNS:
if (ikev1_myprivfile(iph1->rmconf) == NULL) {
plog(PLOG_INTERR, PLOGLOC, NULL, "no cert defined.\n");
goto end;
}
/* make private file name */
#if 0
getpathname(path, sizeof(path),
LC_PATHTYPE_CERT,
iph1->rmconf->myprivfile);
privkey = privsep_eay_get_pkcs1privkey(path);
#else
privkey = eay_get_pkcs1privkey(ikev1_myprivfile(iph1->rmconf));
#endif
if (privkey == NULL) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"failed to get private key.\n");
goto end;
}
plog(PLOG_DEBUG, PLOGLOC, NULL, "private key:\n");
plogdump(PLOG_DEBUG, PLOGLOC, 0, privkey->v, privkey->l);
iph1->sig = eay_get_x509sign(iph1->hash, privkey, 0); /* ??? */
break;
#ifdef notyet
case ISAKMP_CERT_PLAINRSA:
iph1->sig = eay_get_rsasign(iph1->hash, iph1->rsa);
break;
#endif
default:
plog(PLOG_INTERR, PLOGLOC, NULL,
"Unknown certtype #%d\n",
ikev1_certtype(iph1->rmconf));
goto end;
}
if (iph1->sig == NULL) {
plog(PLOG_INTERR, PLOGLOC, NULL, "failed to sign.\n");
goto end;
}
plog(PLOG_DEBUG, PLOGLOC, NULL, "SIGN computed:\n");
plogdump(PLOG_DEBUG, PLOGLOC, 0, iph1->sig->v, iph1->sig->l);
error = 0;
end:
if (privkey != NULL)
rc_vfree(privkey);
return error;
}
/*
* compare certificate name and ID value.
*/
static int
oakley_check_certid(struct ph1handle *iph1)
{
struct ipsecdoi_id_b *id_b;
rc_vchar_t *name = NULL;
char *altname = NULL;
size_t idlen;
int type;
int error;
if (iph1->id_p == NULL || iph1->cert_p == NULL) {
plog(PLOG_INTERR, PLOGLOC, NULL, "no ID nor CERT found.\n");
return ISAKMP_NTYPE_INVALID_ID_INFORMATION;
}
id_b = (struct ipsecdoi_id_b *)iph1->id_p->v;
idlen = iph1->id_p->l - sizeof(*id_b);
switch (id_b->type) {
case IPSECDOI_ID_DER_ASN1_DN:
name = eay_get_x509asn1subjectname(&iph1->cert_p->cert);
if (!name) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"failed to get subjectName\n");
return ISAKMP_NTYPE_INVALID_CERTIFICATE;
}
if (idlen != name->l) {
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"Invalid ID length in phase 1.\n");
rc_vfree(name);
return ISAKMP_NTYPE_INVALID_ID_INFORMATION;
}
error = memcmp(id_b + 1, name->v, idlen);
rc_vfree(name);
if (error != 0) {
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"ID mismatched with subjectAltName.\n");
return ISAKMP_NTYPE_INVALID_ID_INFORMATION;
}
return 0;
case IPSECDOI_ID_IPV4_ADDR:
case IPSECDOI_ID_IPV6_ADDR:
{
/*
* converting to binary from string because openssl return
* a string even if object is a binary.
* XXX fix it ! access by ASN.1 directly without.
*/
struct addrinfo hints, *res;
caddr_t a = NULL;
int pos;
for (pos = 1; ; pos++) {
if (eay_get_x509subjectaltname(&iph1->cert_p->cert,
&altname, &type, pos) !=0) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"failed to get subjectAltName\n");
return ISAKMP_NTYPE_INVALID_CERTIFICATE;
}
/* it's the end condition of the loop. */
if (!altname) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"no proper subjectAltName.\n");
return ISAKMP_NTYPE_INVALID_CERTIFICATE;
}
if (check_typeofcertname(id_b->type, type) == 0)
break;
/* next name */
racoon_free(altname);
altname = NULL;
}
memset(&hints, 0, sizeof(hints));
hints.ai_family = PF_UNSPEC;
hints.ai_socktype = SOCK_RAW;
hints.ai_flags = AI_NUMERICHOST;
error = getaddrinfo(altname, NULL, &hints, &res);
if (error != 0) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"no proper subjectAltName.\n");
racoon_free(altname);
return ISAKMP_NTYPE_INVALID_CERTIFICATE;
}
switch (res->ai_family) {
case AF_INET:
a = (caddr_t)&((struct sockaddr_in *)res->ai_addr)->sin_addr.s_addr;
break;
#ifdef INET6
case AF_INET6:
a = (caddr_t)&((struct sockaddr_in6 *)res->ai_addr)->sin6_addr.s6_addr;
break;
#endif
default:
plog(PLOG_INTERR, PLOGLOC, NULL,
"family not supported: %d.\n", res->ai_family);
racoon_free(altname);
freeaddrinfo(res);
return ISAKMP_NTYPE_INVALID_CERTIFICATE;
}
error = memcmp(id_b + 1, a, idlen);
freeaddrinfo(res);
rc_vfree(name);
if (error != 0) {
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"ID mismatched with subjectAltName.\n");
return ISAKMP_NTYPE_INVALID_ID_INFORMATION;
}
return 0;
}
case IPSECDOI_ID_FQDN:
case IPSECDOI_ID_USER_FQDN:
{
int pos;
for (pos = 1; ; pos++) {
if (eay_get_x509subjectaltname(&iph1->cert_p->cert,
&altname, &type, pos) != 0){
plog(PLOG_INTERR, PLOGLOC, NULL,
"failed to get subjectAltName\n");
return ISAKMP_NTYPE_INVALID_CERTIFICATE;
}
/* it's the end condition of the loop. */
if (!altname) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"no proper subjectAltName.\n");
return ISAKMP_NTYPE_INVALID_CERTIFICATE;
}
if (check_typeofcertname(id_b->type, type) == 0)
break;
/* next name */
racoon_free(altname);
altname = NULL;
}
if (idlen != strlen(altname)) {
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"Invalid ID length in phase 1.\n");
racoon_free(altname);
return ISAKMP_NTYPE_INVALID_ID_INFORMATION;
}
if (check_typeofcertname(id_b->type, type) != 0) {
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"ID type mismatched. ID: %s CERT: %s.\n",
s_ipsecdoi_ident(id_b->type),
s_ipsecdoi_ident(type));
racoon_free(altname);
return ISAKMP_NTYPE_INVALID_ID_INFORMATION;
}
error = memcmp(id_b + 1, altname, idlen);
if (error) {
plog(PLOG_PROTOERR, PLOGLOC, NULL, "ID mismatched.\n");
racoon_free(altname);
return ISAKMP_NTYPE_INVALID_ID_INFORMATION;
}
racoon_free(altname);
return 0;
}
default:
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"Inpropper ID type passed: %s.\n",
s_ipsecdoi_ident(id_b->type));
return ISAKMP_NTYPE_INVALID_ID_INFORMATION;
}
/*NOTREACHED*/
}
static int
check_typeofcertname(int doi, int genid)
{
switch (doi) {
case IPSECDOI_ID_IPV4_ADDR:
case IPSECDOI_ID_IPV4_ADDR_SUBNET:
case IPSECDOI_ID_IPV6_ADDR:
case IPSECDOI_ID_IPV6_ADDR_SUBNET:
case IPSECDOI_ID_IPV4_ADDR_RANGE:
case IPSECDOI_ID_IPV6_ADDR_RANGE:
if (genid != GENT_IPADD)
return -1;
return 0;
case IPSECDOI_ID_FQDN:
if (genid != GENT_DNS)
return -1;
return 0;
case IPSECDOI_ID_USER_FQDN:
if (genid != GENT_EMAIL)
return -1;
return 0;
case IPSECDOI_ID_DER_ASN1_DN: /* should not be passed to this function*/
case IPSECDOI_ID_DER_ASN1_GN:
case IPSECDOI_ID_KEY_ID:
default:
return -1;
}
/*NOTREACHED*/
}
/*
* save certificate including certificate type.
*/
int
oakley_savecert(struct ph1handle *iph1, struct isakmp_gen *gen)
{
cert_t **c;
uint8_t type;
STACK_OF(X509) *certs=NULL;
PKCS7 *p7;
type = *(uint8_t *)(gen + 1) & 0xff;
switch (type) {
case ISAKMP_CERT_DNS:
plog(PLOG_PROTOWARN, PLOGLOC, NULL,
"CERT payload is unnecessary in DNSSEC. "
"ignore this CERT payload.\n");
return 0;
case ISAKMP_CERT_PKCS7:
case ISAKMP_CERT_PGP:
case ISAKMP_CERT_X509SIGN:
case ISAKMP_CERT_KERBEROS:
case ISAKMP_CERT_SPKI:
c = &iph1->cert_p;
break;
case ISAKMP_CERT_CRL:
c = &iph1->crl_p;
break;
case ISAKMP_CERT_X509KE:
case ISAKMP_CERT_X509ATTR:
case ISAKMP_CERT_ARL:
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"No supported such CERT type %d\n", type);
return -1;
default:
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"Invalid CERT type %d\n", type);
return -1;
}
/* XXX choice the 1th cert, ignore after the cert. */
/* XXX should be processed. */
if (*c) {
plog(PLOG_PROTOWARN, PLOGLOC, NULL,
"ignore 2nd CERT payload.\n");
return 0;
}
if (type == ISAKMP_CERT_PKCS7) {
unsigned char *bp;
int i;
/* Skip the header */
bp = (unsigned char *)(gen + 1);
/* And the first byte is the certificate type,
* we know that already
*/
bp++;
p7 = d2i_PKCS7(NULL, (void *)&bp,
get_uint16(&gen->len) - sizeof(*gen) - 1);
if (!p7) {
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"Failed to parse PKCS#7 CERT.\n");
return -1;
}
/* Copied this from the openssl pkcs7 application;
* there"s little by way of documentation for any of
* it. I can only presume it"s correct.
*/
i = OBJ_obj2nid(p7->type);
switch (i) {
case NID_pkcs7_signed:
certs=p7->d.sign->cert;
break;
case NID_pkcs7_signedAndEnveloped:
certs=p7->d.signed_and_enveloped->cert;
break;
default:
break;
}
if (!certs) {
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"CERT PKCS#7 bundle contains no certs.\n");
PKCS7_free(p7);
return -1;
}
for (i = 0; i < sk_X509_num(certs); i++) {
X509 *cert = sk_X509_value(certs,i);
plog(PLOG_DEBUG, PLOGLOC, NULL,
"Trying PKCS#7 cert %d.\n", i);
/* We'll just try each cert in turn */
*c = save_certx509(cert);
if (!*c) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"Failed to get CERT buffer.\n");
continue;
}
/* Ignore cert if it doesn't match identity
* XXX If verify cert is disabled, we still just take
* the first certificate....
*/
if(ikev1_verify_cert(iph1->rmconf) &&
oakley_check_certid(iph1)) {
plog(PLOG_DEBUG, PLOGLOC, NULL,
"Discarding CERT: does not match ID.\n");
oakley_delcert((*c));
*c = NULL;
continue;
}
{
char *p = eay_get_x509text(&(*c)->cert);
plog(PLOG_DEBUG, PLOGLOC, NULL, "CERT saved:\n");
plogdump(PLOG_DEBUG, PLOGLOC, 0, (*c)->cert.v, (*c)->cert.l);
plog(PLOG_DEBUG, PLOGLOC, NULL, "%s",
p ? p : "\n");
racoon_free(p);
}
break;
}
PKCS7_free(p7);
} else {
*c = save_certbuf(gen);
if (!*c) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"Failed to get CERT buffer.\n");
return -1;
}
switch ((*c)->type) {
case ISAKMP_CERT_DNS:
plog(PLOG_PROTOWARN, PLOGLOC, NULL,
"CERT payload is unnecessary in DNSSEC. "
"ignore it.\n");
return 0;
case ISAKMP_CERT_PGP:
case ISAKMP_CERT_X509SIGN:
case ISAKMP_CERT_KERBEROS:
case ISAKMP_CERT_SPKI:
/* Ignore cert if it doesn't match identity
* XXX If verify cert is disabled, we still just take
* the first certificate....
*/
if(ikev1_verify_cert(iph1->rmconf) &&
oakley_check_certid(iph1)){
plog(PLOG_DEBUG, PLOGLOC, NULL,
"Discarding CERT: does not match ID.\n");
oakley_delcert((*c));
*c = NULL;
return 0;
}
{
char *p = eay_get_x509text(&(*c)->cert);
plog(PLOG_DEBUG, PLOGLOC, NULL, "CERT saved:\n");
plogdump(PLOG_DEBUG, PLOGLOC, 0, (*c)->cert.v, (*c)->cert.l);
plog(PLOG_DEBUG, PLOGLOC, NULL, "%s", p ? p : "\n");
racoon_free(p);
}
break;
case ISAKMP_CERT_CRL:
plog(PLOG_DEBUG, PLOGLOC, NULL, "CRL saved:\n");
plogdump(PLOG_DEBUG, PLOGLOC, 0, (*c)->cert.v, (*c)->cert.l);
break;
case ISAKMP_CERT_X509KE:
case ISAKMP_CERT_X509ATTR:
case ISAKMP_CERT_ARL:
default:
/* XXX */
oakley_delcert((*c));
*c = NULL;
return 0;
}
}
return 0;
}
/*
* save certificate including certificate type.
*/
int
oakley_savecr(struct ph1handle *iph1, struct isakmp_gen *gen)
{
cert_t **c;
uint8_t type;
type = *(uint8_t *)(gen + 1) & 0xff;
switch (type) {
case ISAKMP_CERT_DNS:
plog(PLOG_PROTOWARN, PLOGLOC, NULL,
"CERT payload is unnecessary in DNSSEC\n");
/*FALLTHRU*/
case ISAKMP_CERT_PKCS7:
case ISAKMP_CERT_PGP:
case ISAKMP_CERT_X509SIGN:
case ISAKMP_CERT_KERBEROS:
case ISAKMP_CERT_SPKI:
c = &iph1->cr_p;
break;
case ISAKMP_CERT_X509KE:
case ISAKMP_CERT_X509ATTR:
case ISAKMP_CERT_ARL:
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"No supported such CR type %d\n", type);
return -1;
case ISAKMP_CERT_CRL:
default:
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"Invalid CR type %d\n", type);
return -1;
}
*c = save_certbuf(gen);
if (!*c) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"Failed to get CR buffer.\n");
return -1;
}
plog(PLOG_DEBUG, PLOGLOC, NULL, "CR saved:\n");
plogdump(PLOG_DEBUG, PLOGLOC, 0, (*c)->cert.v, (*c)->cert.l);
return 0;
}
static cert_t *
save_certbuf(struct isakmp_gen *gen)
{
cert_t *new;
if(get_uint16(&gen->len) <= sizeof(*gen)){
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"Len is too small !!.\n");
return NULL;
}
new = oakley_newcert();
if (!new) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"Failed to get CERT buffer.\n");
return NULL;
}
new->pl = rc_vmalloc(get_uint16(&gen->len) - sizeof(*gen));
if (new->pl == NULL) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"Failed to copy CERT from packet.\n");
oakley_delcert(new);
new = NULL;
return NULL;
}
memcpy(new->pl->v, gen + 1, new->pl->l);
new->type = new->pl->u[0] & 0xff;
new->cert.u = new->pl->u + 1;
new->cert.l = new->pl->l - 1;
return new;
}
static cert_t *
save_certx509(X509 *cert)
{
cert_t *new;
int len;
unsigned char *bp;
new = oakley_newcert();
if (!new) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"Failed to get CERT buffer.\n");
return NULL;
}
len = i2d_X509(cert, NULL);
new->pl = rc_vmalloc(len);
if (new->pl == NULL) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"Failed to copy CERT from packet.\n");
oakley_delcert(new);
new = NULL;
return NULL;
}
bp = (unsigned char *) new->pl->v;
len = i2d_X509(cert, &bp);
new->type = ISAKMP_CERT_X509SIGN;
new->cert.v = new->pl->v;
new->cert.l = new->pl->l;
return new;
}
/*
* get my CR.
* NOTE: No Certificate Authority field is included to CR payload at the
* moment. Becuase any certificate authority are accepted without any check.
* The section 3.10 in RFC2408 says that this field SHOULD not be included,
* if there is no specific certificate authority requested.
*/
rc_vchar_t *
oakley_getcr(struct ph1handle *iph1)
{
rc_vchar_t *buf;
buf = rc_vmalloc(1);
if (buf == NULL) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"failed to get cr buffer\n");
return NULL;
}
if(ikev1_certtype(iph1->rmconf) == ISAKMP_CERT_NONE) {
buf->u[0] = ikev1_cacerttype(iph1->rmconf);
plog(PLOG_DEBUG, PLOGLOC, NULL, "create my CR: NONE, using %s instead\n",
s_isakmp_certtype(ikev1_cacerttype(iph1->rmconf)));
} else {
buf->u[0] = ikev1_certtype(iph1->rmconf);
plog(PLOG_DEBUG, PLOGLOC, NULL, "create my CR: %s\n",
s_isakmp_certtype(ikev1_certtype(iph1->rmconf)));
}
if (buf->l > 1)
plogdump(PLOG_DEBUG, PLOGLOC, 0, buf->v, buf->l);
return buf;
}
/*
* check peer's CR.
*/
int
oakley_checkcr(struct ph1handle *iph1)
{
if (iph1->cr_p == NULL)
return 0;
plog(PLOG_DEBUG, PLOGLOC, 0,/*iph1->remote,*/
"peer transmitted CR: %s\n",
s_isakmp_certtype(iph1->cr_p->type));
if (iph1->cr_p->type != ikev1_certtype(iph1->rmconf)) {
plog(PLOG_PROTOERR, PLOGLOC, 0 /*iph1->remote*/,
"such a cert type isn't supported: %d\n",
(char)iph1->cr_p->type);
return -1;
}
return 0;
}
/*
* check to need CR payload.
*/
int
oakley_needcr(int type)
{
switch (type) {
case OAKLEY_ATTR_AUTH_METHOD_DSSSIG:
case OAKLEY_ATTR_AUTH_METHOD_RSASIG:
#ifdef ENABLE_HYBRID
case OAKLEY_ATTR_AUTH_METHOD_HYBRID_RSA_I:
case OAKLEY_ATTR_AUTH_METHOD_HYBRID_DSS_I:
case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSASIG_I:
case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSASIG_R:
case OAKLEY_ATTR_AUTH_METHOD_XAUTH_DSSSIG_I:
case OAKLEY_ATTR_AUTH_METHOD_XAUTH_DSSSIG_R:
#endif
return 1;
default:
return 0;
}
/*NOTREACHED*/
}
/*
* compute SKEYID
* see seciton 5. Exchanges in RFC 2409
* psk: SKEYID = prf(pre-shared-key, Ni_b | Nr_b)
* sig: SKEYID = prf(Ni_b | Nr_b, g^ir)
* enc: SKEYID = prf(H(Ni_b | Nr_b), CKY-I | CKY-R)
*/
int
oakley_skeyid(struct ph1handle *iph1)
{
rc_vchar_t *buf = NULL, *bp;
char *p;
int len;
int error = -1;
/* SKEYID */
switch (AUTHMETHOD(iph1)) {
case OAKLEY_ATTR_AUTH_METHOD_PSKEY:
#ifdef ENABLE_HYBRID
case FICTIVE_AUTH_METHOD_XAUTH_PSKEY_I:
case OAKLEY_ATTR_AUTH_METHOD_XAUTH_PSKEY_R:
#endif
#if 0
if (iph1->etype != ISAKMP_ETYPE_IDENT) {
iph1->authstr = getpskbyname(iph1->id_p);
if (iph1->authstr == NULL) {
if (ikev1_verify_id(iph1->rmconf) == RCT_BOOL_ON) {
plog(PLOG_PROTOERR, PLOGLOC, 0 /*iph1->remote*/,
"couldn't find the pskey.\n");
goto end;
}
plog(PLOG_INFO, PLOGLOC, 0 /*iph1->remote*/,
"couldn't find the proper pskey, "
"try to get one by the peer's address.\n");
}
}
#endif
if (iph1->authstr == NULL) {
/*
* If the exchange type is the main mode or if it's
* failed to get the psk by ID, racoon try to get
* the psk by remote IP address.
* It may be nonsense.
*/
iph1->authstr = ikev1_pre_shared_key(iph1->rmconf);
if (iph1->authstr == NULL) {
plog(PLOG_PROTOERR, PLOGLOC, 0,
"couldn't find the pskey for %s.\n",
rcs_sa2str_wop(iph1->remote));
goto end;
}
}
plog(PLOG_DEBUG, PLOGLOC, NULL, "the psk found.\n");
/* should be secret PSK */
plog(PLOG_DEBUG, PLOGLOC, NULL, "psk: ");
plogdump(PLOG_DEBUG, PLOGLOC, 0, iph1->authstr->v, iph1->authstr->l);
len = iph1->nonce->l + iph1->nonce_p->l;
buf = rc_vmalloc(len);
if (buf == NULL) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"failed to get skeyid buffer\n");
goto end;
}
p = buf->v;
bp = (iph1->side == INITIATOR ? iph1->nonce : iph1->nonce_p);
plog(PLOG_DEBUG, PLOGLOC, NULL, "nonce 1: ");
plogdump(PLOG_DEBUG, PLOGLOC, 0, bp->v, bp->l);
memcpy(p, bp->v, bp->l);
p += bp->l;
bp = (iph1->side == INITIATOR ? iph1->nonce_p : iph1->nonce);
plog(PLOG_DEBUG, PLOGLOC, NULL, "nonce 2: ");
plogdump(PLOG_DEBUG, PLOGLOC, 0, bp->v, bp->l);
memcpy(p, bp->v, bp->l);
p += bp->l;
iph1->skeyid = oakley_prf(iph1->authstr, buf, iph1);
if (iph1->skeyid == NULL)
goto end;
break;
case OAKLEY_ATTR_AUTH_METHOD_DSSSIG:
case OAKLEY_ATTR_AUTH_METHOD_RSASIG:
#ifdef ENABLE_HYBRID
case OAKLEY_ATTR_AUTH_METHOD_HYBRID_RSA_I:
case OAKLEY_ATTR_AUTH_METHOD_HYBRID_DSS_I:
case OAKLEY_ATTR_AUTH_METHOD_HYBRID_RSA_R:
case OAKLEY_ATTR_AUTH_METHOD_HYBRID_DSS_R:
case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSASIG_I:
case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSASIG_R:
case OAKLEY_ATTR_AUTH_METHOD_XAUTH_DSSSIG_I:
case OAKLEY_ATTR_AUTH_METHOD_XAUTH_DSSSIG_R:
#endif
#ifdef HAVE_GSSAPI
case OAKLEY_ATTR_AUTH_METHOD_GSSAPI_KRB:
#endif
len = iph1->nonce->l + iph1->nonce_p->l;
buf = rc_vmalloc(len);
if (buf == NULL) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"failed to get nonce buffer\n");
goto end;
}
p = buf->v;
bp = (iph1->side == INITIATOR ? iph1->nonce : iph1->nonce_p);
plog(PLOG_DEBUG, PLOGLOC, NULL, "nonce1: ");
plogdump(PLOG_DEBUG, PLOGLOC, 0, bp->v, bp->l);
memcpy(p, bp->v, bp->l);
p += bp->l;
bp = (iph1->side == INITIATOR ? iph1->nonce_p : iph1->nonce);
plog(PLOG_DEBUG, PLOGLOC, NULL, "nonce2: ");
plogdump(PLOG_DEBUG, PLOGLOC, 0, bp->v, bp->l);
memcpy(p, bp->v, bp->l);
p += bp->l;
iph1->skeyid = oakley_prf(buf, iph1->dhgxy, iph1);
if (iph1->skeyid == NULL)
goto end;
break;
case OAKLEY_ATTR_AUTH_METHOD_RSAENC:
case OAKLEY_ATTR_AUTH_METHOD_RSAREV:
#ifdef ENABLE_HYBRID
case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSAENC_I:
case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSAENC_R:
case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSAREV_I:
case OAKLEY_ATTR_AUTH_METHOD_XAUTH_RSAREV_R:
#endif
plog(PLOG_PROTOWARN, PLOGLOC, NULL,
"not supported authentication method %s\n",
s_oakley_attr_method(iph1->approval->authmethod));
goto end;
default:
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"invalid authentication method %d\n",
iph1->approval->authmethod);
goto end;
}
plog(PLOG_DEBUG, PLOGLOC, NULL, "SKEYID computed:\n");
plogdump(PLOG_DEBUG, PLOGLOC, 0, iph1->skeyid->v, iph1->skeyid->l);
error = 0;
end:
if (buf != NULL)
rc_vfree(buf);
return error;
}
/*
* compute SKEYID_[dae]
* see seciton 5. Exchanges in RFC 2409
* SKEYID_d = prf(SKEYID, g^ir | CKY-I | CKY-R | 0)
* SKEYID_a = prf(SKEYID, SKEYID_d | g^ir | CKY-I | CKY-R | 1)
* SKEYID_e = prf(SKEYID, SKEYID_a | g^ir | CKY-I | CKY-R | 2)
*/
int
oakley_skeyid_dae(struct ph1handle *iph1)
{
rc_vchar_t *buf = NULL;
char *p;
int len;
int error = -1;
if (iph1->skeyid == NULL) {
plog(PLOG_INTERR, PLOGLOC, NULL, "no SKEYID found.\n");
goto end;
}
/* SKEYID D */
/* SKEYID_d = prf(SKEYID, g^xy | CKY-I | CKY-R | 0) */
len = iph1->dhgxy->l + sizeof(isakmp_cookie_t) * 2 + 1;
buf = rc_vmalloc(len);
if (buf == NULL) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"failed to get skeyid buffer\n");
goto end;
}
p = buf->v;
memcpy(p, iph1->dhgxy->v, iph1->dhgxy->l);
p += iph1->dhgxy->l;
memcpy(p, (caddr_t)&iph1->index.i_ck, sizeof(isakmp_cookie_t));
p += sizeof(isakmp_cookie_t);
memcpy(p, (caddr_t)&iph1->index.r_ck, sizeof(isakmp_cookie_t));
p += sizeof(isakmp_cookie_t);
*p = 0;
iph1->skeyid_d = oakley_prf(iph1->skeyid, buf, iph1);
if (iph1->skeyid_d == NULL)
goto end;
rc_vfree(buf);
buf = NULL;
plog(PLOG_DEBUG, PLOGLOC, NULL, "SKEYID_d computed:\n");
plogdump(PLOG_DEBUG, PLOGLOC, 0, iph1->skeyid_d->v, iph1->skeyid->l);
/* SKEYID A */
/* SKEYID_a = prf(SKEYID, SKEYID_d | g^xy | CKY-I | CKY-R | 1) */
len = iph1->skeyid_d->l + iph1->dhgxy->l + sizeof(isakmp_cookie_t) * 2 + 1;
buf = rc_vmalloc(len);
if (buf == NULL) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"failed to get skeyid buffer\n");
goto end;
}
p = buf->v;
memcpy(p, iph1->skeyid_d->v, iph1->skeyid_d->l);
p += iph1->skeyid_d->l;
memcpy(p, iph1->dhgxy->v, iph1->dhgxy->l);
p += iph1->dhgxy->l;
memcpy(p, (caddr_t)&iph1->index.i_ck, sizeof(isakmp_cookie_t));
p += sizeof(isakmp_cookie_t);
memcpy(p, (caddr_t)&iph1->index.r_ck, sizeof(isakmp_cookie_t));
p += sizeof(isakmp_cookie_t);
*p = 1;
iph1->skeyid_a = oakley_prf(iph1->skeyid, buf, iph1);
if (iph1->skeyid_a == NULL)
goto end;
rc_vfree(buf);
buf = NULL;
plog(PLOG_DEBUG, PLOGLOC, NULL, "SKEYID_a computed:\n");
plogdump(PLOG_DEBUG, PLOGLOC, 0, iph1->skeyid_a->v, iph1->skeyid_a->l);
/* SKEYID E */
/* SKEYID_e = prf(SKEYID, SKEYID_a | g^xy | CKY-I | CKY-R | 2) */
len = iph1->skeyid_a->l + iph1->dhgxy->l + sizeof(isakmp_cookie_t) * 2 + 1;
buf = rc_vmalloc(len);
if (buf == NULL) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"failed to get skeyid buffer\n");
goto end;
}
p = buf->v;
memcpy(p, iph1->skeyid_a->v, iph1->skeyid_a->l);
p += iph1->skeyid_a->l;
memcpy(p, iph1->dhgxy->v, iph1->dhgxy->l);
p += iph1->dhgxy->l;
memcpy(p, (caddr_t)&iph1->index.i_ck, sizeof(isakmp_cookie_t));
p += sizeof(isakmp_cookie_t);
memcpy(p, (caddr_t)&iph1->index.r_ck, sizeof(isakmp_cookie_t));
p += sizeof(isakmp_cookie_t);
*p = 2;
iph1->skeyid_e = oakley_prf(iph1->skeyid, buf, iph1);
if (iph1->skeyid_e == NULL)
goto end;
rc_vfree(buf);
buf = NULL;
plog(PLOG_DEBUG, PLOGLOC, NULL, "SKEYID_e computed:\n");
plogdump(PLOG_DEBUG, PLOGLOC, 0, iph1->skeyid_e->v, iph1->skeyid_e->l);
error = 0;
end:
if (buf != NULL)
rc_vfree(buf);
return error;
}
/*
* compute final encryption key.
* see Appendix B.
*/
int
oakley_compute_enckey(struct ph1handle *iph1)
{
int keylen, prflen;
int error = -1;
/* RFC2409 p39 */
keylen = alg_oakley_encdef_keylen(iph1->approval->enctype,
iph1->approval->encklen);
if (keylen == -1) {
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"invalid encryption algoritym %d, "
"or invalid key length %d.\n",
iph1->approval->enctype,
iph1->approval->encklen);
goto end;
}
iph1->key = rc_vmalloc(keylen >> 3);
if (iph1->key == NULL) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"failed to get key buffer\n");
goto end;
}
/* set prf length */
prflen = alg_oakley_hashdef_hashlen(iph1->approval->hashtype);
if (prflen == -1) {
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"invalid hash type %d.\n", iph1->approval->hashtype);
goto end;
}
/* see isakmp-oakley-08 5.3. */
if (iph1->key->l <= iph1->skeyid_e->l) {
/*
* if length(Ka) <= length(SKEYID_e)
* Ka = first length(K) bit of SKEYID_e
*/
memcpy(iph1->key->v, iph1->skeyid_e->v, iph1->key->l);
} else {
rc_vchar_t *buf = NULL, *res = NULL;
unsigned char *p, *ep;
int cplen;
int subkey;
/*
* otherwise,
* Ka = K1 | K2 | K3
* where
* K1 = prf(SKEYID_e, 0)
* K2 = prf(SKEYID_e, K1)
* K3 = prf(SKEYID_e, K2)
*/
plog(PLOG_DEBUG, PLOGLOC, NULL,
"len(SKEYID_e) < len(Ka) (%zu < %zu), "
"generating long key (Ka = K1 | K2 | ...)\n",
iph1->skeyid_e->l, iph1->key->l);
if ((buf = rc_vmalloc(prflen >> 3)) == 0) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"failed to get key buffer\n");
goto end;
}
p = (unsigned char *)iph1->key->v;
ep = p + iph1->key->l;
subkey = 1;
while (p < ep) {
size_t diff;
if (p == (unsigned char *)iph1->key->v) {
/* just for computing K1 */
buf->u[0] = 0;
buf->l = 1;
}
res = oakley_prf(iph1->skeyid_e, buf, iph1);
if (res == NULL) {
rc_vfree(buf);
goto end;
}
plog(PLOG_DEBUG, PLOGLOC, NULL,
"compute intermediate encryption key K%d\n",
subkey);
plogdump(PLOG_DEBUG, PLOGLOC, 0, buf->v, buf->l);
plogdump(PLOG_DEBUG, PLOGLOC, 0, res->v, res->l);
diff = (size_t)(ep - p);
cplen = res->l < diff ? res->l : diff;
memcpy(p, res->v, cplen);
p += cplen;
buf->l = prflen >> 3; /* to cancel K1 speciality */
if (res->l != buf->l) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"internal error: res->l=%zu buf->l=%zu\n",
res->l, buf->l);
rc_vfree(res);
rc_vfree(buf);
goto end;
}
memcpy(buf->v, res->v, res->l);
rc_vfree(res);
subkey++;
}
rc_vfree(buf);
}
/*
* don't check any weak key or not.
* draft-ietf-ipsec-ike-01.txt Appendix B.
* draft-ietf-ipsec-ciph-aes-cbc-00.txt Section 2.3.
*/
#if 0
/* weakkey check */
if (iph1->approval->enctype > ARRAYLEN(oakley_encdef)
|| oakley_encdef[iph1->approval->enctype].weakkey == NULL) {
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"encryption algoritym %d isn't supported.\n",
iph1->approval->enctype);
goto end;
}
if ((oakley_encdef[iph1->approval->enctype].weakkey)(iph1->key)) {
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"weakkey was generated.\n");
goto end;
}
#endif
plog(PLOG_DEBUG, PLOGLOC, NULL, "final encryption key computed:\n");
plogdump(PLOG_DEBUG, PLOGLOC, 0, iph1->key->v, iph1->key->l);
error = 0;
end:
return error;
}
/* allocated new buffer for CERT */
cert_t *
oakley_newcert(void)
{
cert_t *new;
new = racoon_calloc(1, sizeof(*new));
if (new == NULL) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"failed to get cert's buffer\n");
return NULL;
}
new->pl = NULL;
return new;
}
/* delete buffer for CERT */
void
oakley_delcert(cert_t *cert)
{
if (!cert)
return;
if (cert->pl)
VPTRINIT(cert->pl);
racoon_free(cert);
}
/*
* compute IV and set to ph1handle
* IV = hash(g^xi | g^xr)
* see 4.1 Phase 1 state in draft-ietf-ipsec-ike.
*/
int
oakley_newiv(struct ph1handle *iph1)
{
struct isakmp_ivm *newivm = NULL;
int ivlen;
rc_vchar_t *buf = NULL, *bp;
char *p;
int len;
/* create buffer */
len = iph1->dhpub->l + iph1->dhpub_p->l;
buf = rc_vmalloc(len);
if (buf == NULL) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"failed to get iv buffer\n");
return -1;
}
p = buf->v;
bp = (iph1->side == INITIATOR ? iph1->dhpub : iph1->dhpub_p);
memcpy(p, bp->v, bp->l);
p += bp->l;
bp = (iph1->side == INITIATOR ? iph1->dhpub_p : iph1->dhpub);
memcpy(p, bp->v, bp->l);
p += bp->l;
/* allocate IVm */
newivm = racoon_calloc(1, sizeof(struct isakmp_ivm));
if (newivm == NULL) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"failed to get iv buffer\n");
rc_vfree(buf);
return -1;
}
/* compute IV */
newivm->iv = oakley_hash(buf, iph1);
if (newivm->iv == NULL) {
rc_vfree(buf);
oakley_delivm(newivm);
return -1;
}
/* adjust length of iv */
ivlen = alg_oakley_encdef_blocklen(iph1->approval->enctype);
if (ivlen == -1) {
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"invalid encryption algoriym %d.\n",
iph1->approval->enctype);
rc_vfree(buf);
oakley_delivm(newivm);
return -1;
}
newivm->iv->l = ivlen;
/* create buffer to save iv */
if ((newivm->ive = rc_vdup(newivm->iv)) == NULL) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"rc_vdup (%s)\n", strerror(errno));
rc_vfree(buf);
oakley_delivm(newivm);
return -1;
}
rc_vfree(buf);
plog(PLOG_DEBUG, PLOGLOC, NULL, "IV computed:\n");
plogdump(PLOG_DEBUG, PLOGLOC, 0, newivm->iv->v, newivm->iv->l);
iph1->ivm = newivm;
return 0;
}
/*
* compute IV for the payload after phase 1.
* It's not limited for phase 2.
* if pahse 1 was encrypted.
* IV = hash(last CBC block of Phase 1 | M-ID)
* if phase 1 was not encrypted.
* IV = hash(phase 1 IV | M-ID)
* see 4.2 Phase 2 state in draft-ietf-ipsec-ike.
*/
struct isakmp_ivm *
oakley_newiv2(struct ph1handle *iph1, uint32_t msgid)
{
struct isakmp_ivm *newivm = NULL;
int ivlen;
rc_vchar_t *buf = NULL;
char *p;
int len;
int error = -1;
/* create buffer */
len = iph1->ivm->iv->l + sizeof(msgid_t);
buf = rc_vmalloc(len);
if (buf == NULL) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"failed to get iv buffer\n");
goto end;
}
p = buf->v;
memcpy(p, iph1->ivm->iv->v, iph1->ivm->iv->l);
p += iph1->ivm->iv->l;
memcpy(p, &msgid, sizeof(msgid));
plog(PLOG_DEBUG, PLOGLOC, NULL, "compute IV for phase2\n");
plog(PLOG_DEBUG, PLOGLOC, NULL, "phase1 last IV:\n");
plogdump(PLOG_DEBUG, PLOGLOC, 0, buf->v, buf->l);
/* allocate IVm */
newivm = racoon_calloc(1, sizeof(struct isakmp_ivm));
if (newivm == NULL) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"failed to get iv buffer\n");
goto end;
}
/* compute IV */
if ((newivm->iv = oakley_hash(buf, iph1)) == NULL)
goto end;
/* adjust length of iv */
ivlen = alg_oakley_encdef_blocklen(iph1->approval->enctype);
if (ivlen == -1) {
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"invalid encryption algoriym %d.\n",
iph1->approval->enctype);
goto end;
}
newivm->iv->l = ivlen;
/* create buffer to save new iv */
if ((newivm->ive = rc_vdup(newivm->iv)) == NULL) {
plog(PLOG_INTERR, PLOGLOC, NULL, "rc_vdup (%s)\n",
strerror(errno));
goto end;
}
error = 0;
plog(PLOG_DEBUG, PLOGLOC, NULL, "phase2 IV computed:\n");
plogdump(PLOG_DEBUG, PLOGLOC, 0, newivm->iv->v, newivm->iv->l);
end:
if (error && newivm != NULL){
oakley_delivm(newivm);
newivm=NULL;
}
if (buf != NULL)
rc_vfree(buf);
return newivm;
}
void
oakley_delivm(struct isakmp_ivm *ivm)
{
if (ivm == NULL)
return;
if (ivm->iv != NULL)
rc_vfree(ivm->iv);
if (ivm->ive != NULL)
rc_vfree(ivm->ive);
racoon_free(ivm);
plog(PLOG_DEBUG, PLOGLOC, NULL, "IV freed\n");
return;
}
/*
* decrypt packet.
* save new iv and old iv.
*/
rc_vchar_t *
oakley_do_decrypt(struct ph1handle *iph1, rc_vchar_t *msg,
rc_vchar_t *ivdp, rc_vchar_t *ivep)
{
rc_vchar_t *buf = NULL, *new = NULL;
char *pl;
int len;
uint8_t padlen;
int blen;
int error = -1;
plog(PLOG_DEBUG, PLOGLOC, NULL, "begin decryption.\n");
blen = alg_oakley_encdef_blocklen(iph1->approval->enctype);
if (blen == -1) {
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"invalid encryption algoriym %d.\n",
iph1->approval->enctype);
goto end;
}
/* save IV for next, but not sync. */
memset(ivep->v, 0, ivep->l);
memcpy(ivep->v, (caddr_t)&msg->u[msg->l - blen], blen);
plog(PLOG_DEBUG, PLOGLOC, NULL,
"IV was saved for next processing:\n");
plogdump(PLOG_DEBUG, PLOGLOC, 0, ivep->v, ivep->l);
pl = msg->s + sizeof(struct isakmp);
len = msg->l - sizeof(struct isakmp);
/* create buffer */
buf = rc_vmalloc(len);
if (buf == NULL) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"failed to get buffer to decrypt.\n");
goto end;
}
memcpy(buf->v, pl, len);
/* do decrypt */
new = alg_oakley_encdef_decrypt(iph1->approval->enctype,
buf, iph1->key, ivdp);
if (new == NULL) {
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"decryption %d failed.\n", iph1->approval->enctype);
goto end;
}
plog(PLOG_DEBUG, PLOGLOC, NULL, "with key:\n");
plogdump(PLOG_DEBUG, PLOGLOC, 0, iph1->key->v, iph1->key->l);
rc_vfree(buf);
buf = NULL;
plog(PLOG_DEBUG, PLOGLOC, NULL, "decrypted payload by IV:\n");
plogdump(PLOG_DEBUG, PLOGLOC, 0, ivdp->v, ivdp->l);
plog(PLOG_DEBUG, PLOGLOC, NULL,
"decrypted payload, but not trimed.\n");
plogdump(PLOG_DEBUG, PLOGLOC, 0, new->v, new->l);
/* get padding length */
#if 0
if (lcconf->pad_excltail)
padlen = new->u[new->l - 1] + 1;
else
#endif
padlen = new->u[new->l - 1];
plog(PLOG_DEBUG, PLOGLOC, NULL, "padding len=%u\n", padlen);
/* trim padding */
#if 0
if (lcconf->pad_strict) {
if (padlen > new->l) {
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"invalied padding len=%u, buflen=%zu.\n",
padlen, new->l);
plogdump(PLOG_PROTOERR, PLOGLOC, 0, new->v, new->l);
goto end;
}
new->l -= padlen;
plog(PLOG_DEBUG, PLOGLOC, NULL, "trimmed padding\n");
} else {
plog(PLOG_DEBUG, PLOGLOC, NULL, "skip to trim padding.\n");
}
#endif
/* create new buffer */
len = sizeof(struct isakmp) + new->l;
buf = rc_vmalloc(len);
if (buf == NULL) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"failed to get buffer to decrypt.\n");
goto end;
}
memcpy(buf->u, msg->v, sizeof(struct isakmp));
memcpy(buf->u + sizeof(struct isakmp), new->v, new->l);
put_uint32(&((struct isakmp *)buf->v)->len, buf->l);
plog(PLOG_DEBUG, PLOGLOC, NULL, "decrypted.\n");
plogdump(PLOG_DEBUG, PLOGLOC, 0, buf->v, buf->l);
#ifdef HAVE_PRINT_ISAKMP_C
isakmp_printpacket(buf, iph1->remote, iph1->local, 1);
#endif
error = 0;
end:
if (error && buf != NULL) {
rc_vfree(buf);
buf = NULL;
}
if (new != NULL)
rc_vfree(new);
return buf;
}
/*
* encrypt packet.
*/
rc_vchar_t *
oakley_do_encrypt(struct ph1handle *iph1,
rc_vchar_t *msg, rc_vchar_t *ivep, rc_vchar_t *ivp)
{
rc_vchar_t *buf = 0, *new = 0;
char *pl;
int len;
unsigned int padlen;
int blen;
int error = -1;
plog(PLOG_DEBUG, PLOGLOC, NULL, "begin encryption.\n");
/* set cbc block length */
blen = alg_oakley_encdef_blocklen(iph1->approval->enctype);
if (blen == -1) {
plog(PLOG_PROTOERR, PLOGLOC, NULL,
"invalid encryption algoriym %d.\n",
iph1->approval->enctype);
goto end;
}
pl = msg->s + sizeof(struct isakmp);
len = msg->l - sizeof(struct isakmp);
/* add padding */
padlen = oakley_padlen(len, blen);
plog(PLOG_DEBUG, PLOGLOC, NULL, "pad length = %u\n", padlen);
/* create buffer */
buf = rc_vmalloc(len + padlen);
if (buf == NULL) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"failed to get buffer to encrypt.\n");
goto end;
}
if (padlen) {
unsigned int i;
char *p = &buf->s[len];
if (ikev1_random_pad_content(iph1->rmconf) == RCT_BOOL_ON) {
for (i = 0; i < padlen; i++)
*p++ = eay_random_uint32() & 0xff;
} else {
for (i = 0; i < padlen; ++i)
p[i] = 0;
}
}
memcpy(buf->v, pl, len);
/* make pad into tail */
#ifdef notyet
if (lcconf->pad_excltail)
buf->u[len + padlen - 1] = padlen - 1;
else
#endif
buf->u[len + padlen - 1] = padlen;
plogdump(PLOG_DEBUG, PLOGLOC, 0, buf->v, buf->l);
/* do encrypt */
new = alg_oakley_encdef_encrypt(iph1->approval->enctype,
buf, iph1->key, ivep);
if (new == NULL) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"encryption %d failed.\n", iph1->approval->enctype);
goto end;
}
plog(PLOG_DEBUG, PLOGLOC, NULL, "with key:\n");
plogdump(PLOG_DEBUG, PLOGLOC, 0, iph1->key->v, iph1->key->l);
rc_vfree(buf);
buf = NULL;
plog(PLOG_DEBUG, PLOGLOC, NULL, "encrypted payload by IV:\n");
plogdump(PLOG_DEBUG, PLOGLOC, 0, ivep->v, ivep->l);
/* save IV for next */
memset(ivp->v, 0, ivp->l);
memcpy(ivp->v, &new->u[new->l - blen], blen);
plog(PLOG_DEBUG, PLOGLOC, NULL, "save IV for next:\n");
plogdump(PLOG_DEBUG, PLOGLOC, 0, ivp->v, ivp->l);
/* create new buffer */
len = sizeof(struct isakmp) + new->l;
buf = rc_vmalloc(len);
if (buf == NULL) {
plog(PLOG_INTERR, PLOGLOC, NULL,
"failed to get buffer to encrypt.\n");
goto end;
}
memcpy(buf->v, msg->v, sizeof(struct isakmp));
memcpy(buf->u + sizeof(struct isakmp), new->v, new->l);
put_uint32(&((struct isakmp *)buf->v)->len, buf->l);
error = 0;
plog(PLOG_DEBUG, PLOGLOC, NULL, "encrypted.\n");
end:
if (error && buf != NULL) {
rc_vfree(buf);
buf = NULL;
}
if (new != NULL)
rc_vfree(new);
return buf;
}
/* culculate padding length */
static int
oakley_padlen(int len, int base)
{
int padlen;
padlen = base - len % base;
#ifdef notyet
if (lcconf->pad_randomlen)
padlen += ((eay_random() % (lcconf->pad_maxsize + 1) + 1) *
base);
#endif
return padlen;
}
| 23.922782 | 80 | 0.653507 | [
"object"
] |
fa4d6b3b8129ca09ccb0e41f1f16cc97bd857fb2 | 11,563 | c | C | examples/lbm/fpc/d2q9/fpc_d2q9.c | nn4ip/pluto | 92ace2441b6b8d6b66d1bb7ef3e893df4ff23a4d | [
"MIT"
] | 183 | 2017-01-28T17:23:29.000Z | 2022-03-25T08:58:56.000Z | examples/lbm/fpc/d2q9/fpc_d2q9.c | nn4ip/pluto | 92ace2441b6b8d6b66d1bb7ef3e893df4ff23a4d | [
"MIT"
] | 70 | 2017-03-29T09:51:04.000Z | 2021-12-28T07:00:44.000Z | examples/lbm/fpc/d2q9/fpc_d2q9.c | nn4ip/pluto | 92ace2441b6b8d6b66d1bb7ef3e893df4ff23a4d | [
"MIT"
] | 57 | 2017-03-29T07:27:58.000Z | 2022-01-14T03:13:39.000Z | /*************************************************************************/
/* 2D Poiseuille sheet flow simulation using LBM with a D2Q9 lattice and */
/* Zou-He BC for inlet and outlet and SBB BC for top and bottom walls */
/* */
/* Scheme: 2-Grid, Pull, Compute, Keep */
/* */
/* Lattice naming convention */
/* c6[NW] c3[N] c5[NE] */
/* c2[W] c0[C] c1[E] */
/* c8[SW] c4[S] c7[SE] */
/* */
/* Author: Irshad Pananilath <pmirshad+code@gmail.com> */
/* */
/*************************************************************************/
#include <stdio.h>
#include <sys/time.h>
#include <math.h>
#ifndef nX
#define nX 1024 // Size of domain along x-axis
#endif
#ifndef nY
#define nY 256 // Size of domain along y-axis
#endif
#ifndef nK
#define nK 9 // D2Q9
#endif
#ifndef nTimesteps
#define nTimesteps 40000 // Number of timesteps for the simulation
#endif
#define C 0
#define E 1
#define W 2
#define N 3
#define S 4
#define NE 5
#define NW 6
#define SE 7
#define SW 8
/* Circle parameters */
const double circleX = nX / 5.0;
const double circleY = nY / 2.0 + 2.0; // asymmetrically mounted
const double circle_radius = nY / 10.0 + 1.0;
/* Tunable parameters */
const double tau = 0.9;
const double rho_in = 3.0 * 1.03;
const double rho_out = 3.0 * 1.0;
/* Calculated parameters: Set in main */
double omega = 0.0;
double circle_R2 = 0.0;
const double w1 = 4.0 / 9.0;
const double w2 = 1.0 / 9.0;
const double w3 = 1.0 / 36.0;
double grid[2][nY + 2 + 4][nX + 2 + 2][nK];
void lbm_kernel(double, double, double, double, double, double, double, double,
double, double *restrict, double *restrict, double *restrict,
double *restrict, double *restrict, double *restrict,
double *restrict, double *restrict, double *restrict, int, int,
int);
void dumpVelocities(int timestep);
int timeval_subtract(struct timeval *result, struct timeval *x,
struct timeval *y);
int main(void) {
int t, y, x, k;
double total_lattice_pts = (double)nY * (double)nX * (double)nTimesteps;
/* For timekeeping */
int ts_return = -1;
struct timeval start, end, result;
double tdiff = 0.0;
/* Compute values for global parameters */
omega = 1.0 / tau;
circle_R2 = circle_radius * circle_radius;
double rho_avg = (rho_in + rho_out) / 2.0;
printf(
"2D Flow Past Cylinder simulation with D2Q9 lattice:\n"
"\tscheme : 2-Grid, Fused, Pull\n"
"\tgrid size : %d x %d = %.2lf * 10^3 Cells\n"
"\tnTimeSteps : %d\n"
"\tomega : %.6lf\n",
nX, nY, nX * nY / 1.0e3, nTimesteps, omega);
/* Initialize all 9 PDFs for each point in the domain to 1.0 */
for (y = 0; y < nY + 2 + 4; y++) {
for (x = 0; x < nX + 2 + 2; x++) {
grid[0][y][x][0] = w1 * rho_avg;
grid[1][y][x][0] = w1 * rho_avg;
for (k = 1; k < 5; k++) {
grid[0][y][x][k] = w2 * rho_avg;
grid[1][y][x][k] = w2 * rho_avg;
}
for (k = 5; k < nK; k++) {
grid[0][y][x][k] = w3 * rho_avg;
grid[1][y][x][k] = w3 * rho_avg;
}
}
}
/* To satisfy PET */
short _nX = nX + 2;
short _nY = nY + 3;
int _nTimesteps = nTimesteps;
#ifdef TIME
gettimeofday(&start, 0);
#endif
#pragma scop
/* Kernel of the code */
for (t = 0; t < _nTimesteps; t++) {
for (y = 3; y < _nY; y++) {
for (x = 2; x < _nX; x++) {
lbm_kernel(grid[t % 2][y][x][C],
grid[t % 2][y - 1][x + 0][N],
grid[t % 2][y + 1][x + 0][S],
grid[t % 2][y + 0][x - 1][E],
grid[t % 2][y + 0][x + 1][W],
grid[t % 2][y - 1][x - 1][NE],
grid[t % 2][y - 1][x + 1][NW],
grid[t % 2][y + 1][x - 1][SE],
grid[t % 2][y + 1][x + 1][SW],
&grid[(t + 1) % 2][y][x][C],
&grid[(t + 1) % 2][y][x][N],
&grid[(t + 1) % 2][y][x][S],
&grid[(t + 1) % 2][y][x][E],
&grid[(t + 1) % 2][y][x][W],
&grid[(t + 1) % 2][y][x][NE],
&grid[(t + 1) % 2][y][x][NW],
&grid[(t + 1) % 2][y][x][SE],
&grid[(t + 1) % 2][y][x][SW],
t, y, x);
}
}
}
#pragma endscop
#ifdef TIME
gettimeofday(&end, 0);
ts_return = timeval_subtract(&result, &end, &start);
tdiff = (double)(result.tv_sec + result.tv_usec * 1.0e-6);
printf("\tTime taken : %7.5lfs\n", tdiff);
printf("\tMLUPS : %7.5lf\n", (total_lattice_pts / (1.0e6 * tdiff)));
#endif
#ifdef DEBUG
/* Dump rho, uX, uY for the entire domain to verify results */
dumpVelocities(t);
#endif
return 0;
}
/* Performs LBM kernel for one lattice cell */
void lbm_kernel(double in_c, double in_n, double in_s, double in_e, double in_w,
double in_ne, double in_nw, double in_se, double in_sw,
double *restrict out_c, double *restrict out_n,
double *restrict out_s, double *restrict out_e,
double *restrict out_w, double *restrict out_ne,
double *restrict out_nw, double *restrict out_se,
double *restrict out_sw, int t, int y, int x) {
double rho, uX, uY, u2;
double position = pow(x - circleX, 2) + pow(y - circleY, 2);
if (((y == 3 || y == nY + 2) && (x > 2 && x < nX + 1)) || (position <= circle_R2)) {
/* Bounce back boundary condition at walls and cylinder boundary */
*out_c = in_c;
*out_s = in_n;
*out_n = in_s;
*out_w = in_e;
*out_e = in_w;
*out_sw = in_ne;
*out_se = in_nw;
*out_nw = in_se;
*out_ne = in_sw;
return;
}
/* Inlet pressue boundary conditions */
if ((x == 2) && (y == 3)) {
/* Bottom left point */
in_e = in_w;
in_n = in_s;
in_ne = in_sw;
in_nw = (1.0 / 2.0) * (rho_in - (in_c + in_e + in_w + in_n + in_s + in_ne + in_sw));
in_se = (1.0 / 2.0) * (rho_in - (in_c + in_e + in_w + in_n + in_s + in_ne + in_sw));
}
if ((x == 2) && (y == nY + 2)) {
/* Top left point */
in_e = in_w;
in_s = in_n;
in_se = in_nw;
in_sw = (1.0 / 2.0) * (rho_in - (in_c + in_e + in_w + in_n + in_s + in_se + in_nw));
in_ne = (1.0 / 2.0) * (rho_in - (in_c + in_e + in_w + in_n + in_s + in_se + in_nw));
}
/* Outlet pressure boundary conditions */
if ((x == nX + 1) && (y == 3)) {
/* Bottom right point */
in_w = in_e;
in_n = in_s;
in_nw = in_se;
in_ne = (1.0 / 2.0) * (rho_out - (in_c + in_e + in_w + in_n + in_s + in_nw + in_se));
in_sw = (1.0 / 2.0) * (rho_out - (in_c + in_e + in_w + in_n + in_s + in_nw + in_se));
}
if ((x == nX + 1) && (y == 3)) {
/* Top right point */
in_w = in_e;
in_s = in_n;
in_sw = in_ne;
in_nw = (1.0 / 2.0) * (rho_out - (in_c + in_e + in_w + in_n + in_s + in_ne + in_sw));
in_se = (1.0 / 2.0) * (rho_out - (in_c + in_e + in_w + in_n + in_s + in_ne + in_sw));
}
/* Compute rho */
rho = in_n + in_s + in_e + in_w + in_ne + in_nw + in_se + in_sw + in_c;
/* Compute velocity along x-axis */
uX = (in_se + in_e + in_ne) - (in_sw + in_w + in_nw);
uX = uX / rho;
/* Compute velocity along y-axis */
uY = (in_nw + in_n + in_ne) - (in_sw + in_s + in_se);
uY = uY / rho;
/* Apply Zou-He pressure boundary conditions */
/* Inlet */
if ((x == 2) && (y > 3 && y < nY + 2)) {
uX = 1.0 - ((in_c + in_n + in_s + 2.0 * (in_nw + in_w + in_sw)) / rho_in);
uY = 0.0;
rho = rho_in;
in_e = in_w + (2.0 / 3.0) * (rho_in * uX);
in_ne = in_sw - (1.0 / 2.0) * (in_n - in_s) + (1.0 / 6.0) * rho_in * uX;
in_se = in_nw + (1.0 / 2.0) * (in_n - in_s) + (1.0 / 6.0) * rho_in * uX;
}
/* Outlet */
if ((x == nX + 1) && (y > 3 && y < nY + 2)) {
uX = 1.0 - ((in_c + in_n + in_s + 2.0 * (in_ne + in_e + in_se)) / rho_out);
uY = 0.0;
rho = rho_out;
in_w = in_e - (2.0 / 3.0) * rho_out * uX;
in_nw = in_se - (1.0 / 6.0) * rho_out * uX - (1.0 / 2.0) * (in_n - in_s);
in_sw = in_ne - (1.0 / 6.0) * rho_out * uX + (1.0 / 2.0) * (in_n - in_s);
}
u2 = 1.5 * (uX * uX + uY * uY);
/* Compute and keep new PDFs */
*out_c = (1.0 - omega) * in_c + (omega * (w1 * rho * (1.0 - u2)));
*out_n = (1.0 - omega) * in_n +
(omega * (w2 * rho * (1.0 + 3.0 * uY + 4.5 * uY * uY - u2)));
*out_s = (1.0 - omega) * in_s +
(omega * (w2 * rho * (1.0 - 3.0 * uY + 4.5 * uY * uY - u2)));
*out_e = (1.0 - omega) * in_e +
(omega * (w2 * rho * (1.0 + 3.0 * uX + 4.5 * uX * uX - u2)));
*out_w = (1.0 - omega) * in_w +
(omega * (w2 * rho * (1.0 - 3.0 * uX + 4.5 * uX * uX - u2)));
*out_ne = (1.0 - omega) * in_ne + (omega * (w3 * rho *
(1.0 + 3.0 * (uX + uY) + 4.5 * (uX + uY) * (uX + uY) - u2)));
*out_nw = (1.0 - omega) * in_nw + (omega * (w3 * rho *
(1.0 + 3.0 * (-uX + uY) + 4.5 * (-uX + uY) * (-uX + uY) - u2)));
*out_se = (1.0 - omega) * in_se + (omega * (w3 * rho *
(1.0 + 3.0 * (uX - uY) + 4.5 * (uX - uY) * (uX - uY) - u2)));
*out_sw = (1.0 - omega) * in_sw + (omega * (w3 * rho *
(1.0 + 3.0 * (-uX - uY) + 4.5 * (-uX - uY) * (-uX - uY) - u2)));
}
void dumpVelocities(int t) {
int y, x;
double rho, uX, uY;
for (y = 4; y < nY + 2; y++) {
for (x = 3; x < nX + 1; x++) {
/* Compute rho */
rho = grid[t % 2][y - 1][x + 0][N] + grid[t % 2][y + 1][x + 0][S] +
grid[t % 2][y + 0][x - 1][E] + grid[t % 2][y + 0][x + 1][W] +
grid[t % 2][y - 1][x - 1][NE] + grid[t % 2][y - 1][x + 1][NW] +
grid[t % 2][y + 1][x - 1][SE] + grid[t % 2][y + 1][x + 1][SW] +
grid[t % 2][y + 0][x + 0][C];
/* Compute velocity along x-axis */
uX = (grid[t % 2][y + 1][x - 1][SE] + grid[t % 2][y + 0][x - 1][E] +
grid[t % 2][y - 1][x - 1][NE]) -
(grid[t % 2][y + 1][x + 1][SW] + grid[t % 2][y + 0][x + 1][W] +
grid[t % 2][y - 1][x + 1][NW]);
uX = uX / rho;
/* Compute velocity along y-axis */
uY = (grid[t % 2][y - 1][x + 1][NW] + grid[t % 2][y - 1][x + 0][N] +
grid[t % 2][y - 1][x - 1][NE]) -
(grid[t % 2][y + 1][x + 1][SW] + grid[t % 2][y + 1][x + 0][S] +
grid[t % 2][y + 1][x - 1][SE]);
uY = uY / rho;
fprintf(stderr, "%0.6lf,%0.6lf,%0.6lf\n", rho, uX, uY);
}
}
}
int timeval_subtract(struct timeval *result, struct timeval *x,
struct timeval *y) {
if (x->tv_usec < y->tv_usec) {
int nsec = (y->tv_usec - x->tv_usec) / 1000000 + 1;
y->tv_usec -= 1000000 * nsec;
y->tv_sec += nsec;
}
if (x->tv_usec - y->tv_usec > 1000000) {
int nsec = (x->tv_usec - y->tv_usec) / 1000000;
y->tv_usec += 1000000 * nsec;
y->tv_sec -= nsec;
}
result->tv_sec = x->tv_sec - y->tv_sec;
result->tv_usec = x->tv_usec - y->tv_usec;
return x->tv_sec < y->tv_sec;
}
/* icc -O3 -fp-model precise -restrict -DDEBUG -DTIME fpc_d2q9.c -o fpc_d2q9.elf */
| 32.119444 | 89 | 0.456283 | [
"model"
] |
fa57ab0aad6d5e6f128cbb6140f33bea18422f8e | 1,844 | h | C | gadgets/mri_core/AcquisitionAccumulateTriggerGadget.h | roopchansinghv/gadgetron | fb6c56b643911152c27834a754a7b6ee2dd912da | [
"MIT"
] | 1 | 2022-02-22T21:06:36.000Z | 2022-02-22T21:06:36.000Z | gadgets/mri_core/AcquisitionAccumulateTriggerGadget.h | apd47/gadgetron | 073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2 | [
"MIT"
] | null | null | null | gadgets/mri_core/AcquisitionAccumulateTriggerGadget.h | apd47/gadgetron | 073e84dabe77d2dae3b3dd9aa4bf9edbf1f890f2 | [
"MIT"
] | null | null | null | #pragma once
#include "Node.h"
#include "hoNDArray.h"
#include "mri_core_acquisition_bucket.h"
#include <complex>
#include <ismrmrd/ismrmrd.h>
#include <map>
namespace Gadgetron {
class AcquisitionAccumulateTriggerGadget
: public Core::ChannelGadget<Core::variant<Core::Acquisition, Core::Waveform>> {
public:
using Core::ChannelGadget<Core::variant<Core::Acquisition, Core::Waveform>>::ChannelGadget;
void process(Core::InputChannel<Core::variant<Core::Acquisition, Core::Waveform>>& in,
Core::OutputChannel& out) override;
enum class TriggerDimension {
kspace_encode_step_1,
kspace_encode_step_2,
average,
slice,
contrast,
phase,
repetition,
set,
segment,
user_0,
user_1,
user_2,
user_3,
user_4,
user_5,
user_6,
user_7,
n_acquisitions,
none
};
NODE_PROPERTY(trigger_dimension, TriggerDimension, "Dimension to trigger on", TriggerDimension::none);
NODE_PROPERTY(sorting_dimension, TriggerDimension, "Dimension to trigger on", TriggerDimension::none);
NODE_PROPERTY(n_acquisitions_before_trigger, unsigned long, "Number of acquisition before first trigger", 40);
NODE_PROPERTY(n_acquisitions_before_ongoing_trigger, unsigned long, "Number of acquisition before ongoing triggers", 40);
size_t trigger_events = 0;
private:
void send_data(Core::OutputChannel& out, std::map<unsigned short, AcquisitionBucket>& buckets,
std::vector<Core::Waveform>& waveforms);
};
void from_string(const std::string& str, AcquisitionAccumulateTriggerGadget::TriggerDimension& val);
}
| 32.350877 | 129 | 0.637744 | [
"vector"
] |
fa591da23143c70a53fdd0e7cd96b14835c737fd | 30,087 | h | C | geo3d/include/CGAL/Kernel_d/Linear_algebraHd_impl.h | vipuserr/vipuserr-Geological-hazard | 2b29c03cdac6f5e1ceac4cd2f15b594040ef909c | [
"MIT"
] | 187 | 2019-01-23T04:07:11.000Z | 2022-03-27T03:44:58.000Z | 3rd_party/cgal_4.9/include/cgal/Kernel_d/Linear_algebraHd_impl.h | nimzi/CGALViewer | 25e28196a9192c2b7174a5656f441f97b9c94bd8 | [
"MIT"
] | 8 | 2019-03-22T13:27:38.000Z | 2020-06-18T13:23:23.000Z | 3rd_party/cgal_4.9/include/cgal/Kernel_d/Linear_algebraHd_impl.h | nimzi/CGALViewer | 25e28196a9192c2b7174a5656f441f97b9c94bd8 | [
"MIT"
] | 34 | 2019-02-13T01:11:12.000Z | 2022-02-28T03:29:40.000Z | // Copyright (c) 1997-2000
// Utrecht University (The Netherlands),
// ETH Zurich (Switzerland),
// INRIA Sophia-Antipolis (France),
// Max-Planck-Institute Saarbruecken (Germany),
// and Tel-Aviv University (Israel). All rights reserved.
//
// This file is part of CGAL (www.cgal.org); 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.
//
// Licensees holding a valid commercial license may use this file in
// accordance with the commercial license agreement provided with the software.
//
// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
//
// $URL$
// $Id$
//
//
// Author(s) : Michael Seel <seel@mpi-sb.mpg.de>
//---------------------------------------------------------------------
// file generated by notangle from Linear_algebra.lw
// please debug or modify noweb file
// based on LEDA architecture by S. Naeher, C. Uhrig
// coding: K. Mehlhorn, M. Seel
// debugging and templatization: M. Seel
//---------------------------------------------------------------------
#ifndef CGAL_LINEAR_ALGEBRAHD_C
#define CGAL_LINEAR_ALGEBRAHD_C
namespace CGAL {
template <class RT_, class AL_>
bool Linear_algebraHd<RT_,AL_>::
linear_solver(const Matrix& A, const Vector& b,
Vector& x, RT& D,
Matrix& spanning_vectors, Vector& c)
{
bool solvable = true;
int i,j,k; // indices to step through the matrix
int rows = A.row_dimension();
int cols = A.column_dimension();
/* at this point one might want to check whether the computation can
be carried out with doubles, see section \ref{ optimization }. */
CGAL_assertion_msg(b.dimension() == rows,
"linear_solver: b has wrong dimension");
Matrix C(rows,cols + 1);
// the matrix in which we will calculate ($C = (A \vert b)$)
/* copy |A| and |b| into |C| and L becomes the identity matrix */
Matrix L(rows); // zero initialized
for(i=0; i<rows; i++) {
for(j=0; j<cols; j++)
C(i,j)=A(i,j);
C(i,cols)=b[i];
L(i,i) = 1; // diagonal elements are 1
}
std::vector<int> var(cols);
// column $j$ of |C| represents the |var[j]| - th variable
// the array is indexed between |0| and |cols - 1|
for(j=0; j<cols; j++)
var[j]= j; // at the beginning, variable $x_j$ stands in column $j$
RT_ denom = 1; // the determinant of an empty matrix is 1
int sign = 1; // no interchanges yet
int rank = 0; // we have not seen any non-zero row yet
/* here comes the main loop */
for(k=0; k<rows; k++) {
bool non_zero_found = false;
for(i = k; i < rows; i++) { // step through rows $k$ to |rows - 1|
for (j = k ; j < cols && C(i,j) == 0; j++) {}
// step through columns |k| to |cols - 1|
if (j < cols) {
non_zero_found = true;
break;
}
}
if ( non_zero_found ) {
rank++; //increase the rank
if (i != k) {
sign = -sign;
/* we interchange rows |k| and |i| of |L| and |C| */
L.swap_rows(i,k); C.swap_rows(i,k);
}
if (j != k) {
/* We interchange columns |k| and |j|, and
store the exchange of variables in |var| */
sign = - sign;
C.swap_columns(j,k);
std::swap(var[k],var[j]);
}
for(i = k + 1; i < rows; i++)
for (j = 0; j < rows; j++) //and all columns of |L|
L(i,j) = (L(i,j)*C(k,k) - C(i,k)*L(k,j))/denom;
for(i = k + 1; i < rows; i++) {
/* the following iteration uses and changes |C(i,k)| */
RT temp = C(i,k);
for (j = k; j <= cols; j++)
C(i,j) = (C(i,j)*C(k,k) - temp*C(k,j))/denom;
}
denom = C(k,k);
#ifdef CGAL_LA_SELFTEST
for(i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
RT Sum = 0;
for (int l = 0; l < rows; l++)
Sum += L(i,l)*A(l, var[j]);
CGAL_assertion_msg( Sum == C(i,j),
"linear_solver: L*A*P different from C");
}
RT Sum = 0;
for (int l = 0; l < rows; l++)
Sum += L(i,l)*b[l];
CGAL_assertion_msg( Sum == C(i,cols),
"linear_solver: L*A*P different from C");
}
#endif
}
else
break;
}
for(i = rank; i < rows && C(i,cols) == 0; ++i) {}
if (i < rows)
{ solvable = false; c = L.row(i); }
if (solvable) {
x = Vector(cols);
D = denom;
for(i = rank - 1; i >= 0; i--) {
RT_ h = C(i,cols) * D;
for (j = i + 1; j < rank; j++) {
h -= C(i,j)*x[var[j]];
}
x[var[i]]= h / C(i,i);
}
#ifdef CGAL_LA_SELFTEST
CGAL_assertion( (M*x).is_zero() );
#endif
int defect = cols - rank; // dimension of kernel
spanning_vectors = Matrix(cols,defect);
if (defect > 0) {
for(int l=0; l < defect; l++) {
spanning_vectors(var[rank + l],l)=D;
for(i = rank - 1; i >= 0 ; i--) {
RT_ h = - C(i,rank + l)*D;
for ( j= i + 1; j<rank; j++)
h -= C(i,j)*spanning_vectors(var[j],l);
spanning_vectors(var[i],l)= h / C(i,i);
}
#ifdef CGAL_LA_SELFTEST
/* we check whether the $l$ - th spanning vector is a solution
of the homogeneous system */
CGAL_assertion( (M*spanning_vectors.column(l)).is_zero() );
#endif
}
}
}
return solvable;
}
template <class RT_, class AL_>
RT_ Linear_algebraHd<RT_,AL_>::
determinant(const Matrix& A)
{
if (A.row_dimension() != A.column_dimension())
CGAL_error_msg( "determinant(): only square matrices are legal inputs.");
Vector b(A.row_dimension()); // zero - vector
int i,j,k; // indices to step through the matrix
int rows = A.row_dimension();
int cols = A.column_dimension();
/* at this point one might want to check whether the computation can
be carried out with doubles, see section \ref{ optimization }. */
CGAL_assertion_msg(b.dimension() == rows,
"linear_solver: b has wrong dimension");
Matrix C(rows,cols + 1);
// the matrix in which we will calculate ($C = (A \vert b)$)
/* copy |A| and |b| into |C| and L becomes the identity matrix */
Matrix L(rows); // zero initialized
for(i=0; i<rows; i++) {
for(j=0; j<cols; j++)
C(i,j)=A(i,j);
C(i,cols)=b[i];
L(i,i) = 1; // diagonal elements are 1
}
std::vector<int> var(cols);
// column $j$ of |C| represents the |var[j]| - th variable
// the array is indexed between |0| and |cols - 1|
for(j=0; j<cols; j++)
var[j]= j; // at the beginning, variable $x_j$ stands in column $j$
RT_ denom = 1; // the determinant of an empty matrix is 1
int sign = 1; // no interchanges yet
int rank = 0; // we have not seen any non-zero row yet
/* here comes the main loop */
for(k=0; k<rows; k++) {
bool non_zero_found = false;
for(i = k; i < rows; i++) { // step through rows $k$ to |rows - 1|
for (j = k ; j < cols && C(i,j) == 0; j++) {}
// step through columns |k| to |cols - 1|
if (j < cols) {
non_zero_found = true;
break;
}
}
if ( non_zero_found ) {
rank++; //increase the rank
if (i != k) {
sign = -sign;
/* we interchange rows |k| and |i| of |L| and |C| */
L.swap_rows(i,k); C.swap_rows(i,k);
}
if (j != k) {
/* We interchange columns |k| and |j|, and
store the exchange of variables in |var| */
sign = - sign;
C.swap_columns(j,k);
std::swap(var[k],var[j]);
}
for(i = k + 1; i < rows; i++)
for (j = 0; j < rows; j++) //and all columns of |L|
L(i,j) = (L(i,j)*C(k,k) - C(i,k)*L(k,j))/denom;
for(i = k + 1; i < rows; i++) {
/* the following iteration uses and changes |C(i,k)| */
RT temp = C(i,k);
for (j = k; j <= cols; j++)
C(i,j) = (C(i,j)*C(k,k) - temp*C(k,j))/denom;
}
denom = C(k,k);
#ifdef CGAL_LA_SELFTEST
for(i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
RT Sum = 0;
for (int l = 0; l < rows; l++)
Sum += L(i,l)*A(l, var[j]);
CGAL_assertion_msg( Sum == C(i,j),
"linear_solver: L*A*P different from C");
}
RT Sum = 0;
for (int l = 0; l < rows; l++)
Sum += L(i,l)*b[l];
CGAL_assertion_msg( Sum == C(i,cols),
"linear_solver: L*A*P different from C");
}
#endif
}
else
break;
}
if (rank < rows)
return 0;
else
return RT(sign) * denom;
}
template <class RT_, class AL_>
RT_ Linear_algebraHd<RT_,AL_>::
determinant(const Matrix& A,
Matrix& Ld, Matrix& Ud,
std::vector<int>& q, Vector& c)
{
if (A.row_dimension() != A.column_dimension())
CGAL_error_msg( "determinant(): only square matrices are legal inputs.");
Vector b(A.row_dimension()); // zero - vector
int i,j,k; // indices to step through the matrix
int rows = A.row_dimension();
int cols = A.column_dimension();
/* at this point one might want to check whether the computation can
be carried out with doubles, see section \ref{ optimization }. */
CGAL_assertion_msg(b.dimension() == rows,
"linear_solver: b has wrong dimension");
Matrix C(rows,cols + 1);
// the matrix in which we will calculate ($C = (A \vert b)$)
/* copy |A| and |b| into |C| and L becomes the identity matrix */
Matrix L(rows); // zero initialized
for(i=0; i<rows; i++) {
for(j=0; j<cols; j++)
C(i,j)=A(i,j);
C(i,cols)=b[i];
L(i,i) = 1; // diagonal elements are 1
}
std::vector<int> var(cols);
// column $j$ of |C| represents the |var[j]| - th variable
// the array is indexed between |0| and |cols - 1|
for(j=0; j<cols; j++)
var[j]= j; // at the beginning, variable $x_j$ stands in column $j$
RT_ denom = 1; // the determinant of an empty matrix is 1
int sign = 1; // no interchanges yet
int rank = 0; // we have not seen any non-zero row yet
/* here comes the main loop */
for(k=0; k<rows; k++) {
bool non_zero_found = false;
for(i = k; i < rows; i++) { // step through rows $k$ to |rows - 1|
for (j = k ; j < cols && C(i,j) == 0; j++) {}
// step through columns |k| to |cols - 1|
if (j < cols) {
non_zero_found = true;
break;
}
}
if ( non_zero_found ) {
rank++; //increase the rank
if (i != k) {
sign = -sign;
/* we interchange rows |k| and |i| of |L| and |C| */
L.swap_rows(i,k); C.swap_rows(i,k);
}
if (j != k) {
/* We interchange columns |k| and |j|, and
store the exchange of variables in |var| */
sign = - sign;
C.swap_columns(j,k);
std::swap(var[k],var[j]);
}
for(i = k + 1; i < rows; i++)
for (j = 0; j < rows; j++) //and all columns of |L|
L(i,j) = (L(i,j)*C(k,k) - C(i,k)*L(k,j))/denom;
for(i = k + 1; i < rows; i++) {
/* the following iteration uses and changes |C(i,k)| */
RT temp = C(i,k);
for (j = k; j <= cols; j++)
C(i,j) = (C(i,j)*C(k,k) - temp*C(k,j))/denom;
}
denom = C(k,k);
#ifdef CGAL_LA_SELFTEST
for(i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
RT Sum = 0;
for (int l = 0; l < rows; l++)
Sum += L(i,l)*A(l, var[j]);
CGAL_assertion_msg( Sum == C(i,j),
"linear_solver: L*A*P different from C");
}
RT Sum = 0;
for (int l = 0; l < rows; l++)
Sum += L(i,l)*b[l];
CGAL_assertion_msg( Sum == C(i,cols),
"linear_solver: L*A*P different from C");
}
#endif
}
else
break;
}
if (rank < rows) {
c = L.row(rows - 1);
return 0;
} else {
Ld = L;
Ud = Matrix(rows); // square
for (i = 0; i < rows; i++)
for(j = 0; j <rows; j++)
Ud(i,j) = C(i,j);
q = var;
return RT(sign) * denom;
}
}
template <class RT_, class AL_>
int Linear_algebraHd<RT_,AL_>::
sign_of_determinant(const Matrix& M)
{ return CGAL_NTS sign(determinant(M)); }
template <class RT_, class AL_>
bool Linear_algebraHd<RT_,AL_>::
verify_determinant(const Matrix& A, RT_ D,
Matrix& L, Matrix& U,
const std::vector<int>& q, Vector& c)
{
if ((int)q.size() != A.column_dimension())
CGAL_error_msg( "verify_determinant: q should be a permutation array \
with index range [0,A.column_dimension() - 1].");
int n = A.row_dimension();
int i,j;
if (D == 0) { /* we have $c^T \cdot A = 0$ */
Vector zero(n);
return (transpose(A) * c == zero);
} else {
/* we check the conditions on |L| and |U| */
if (L(0,0) != 1) return false;
for (i = 0; i<n; i++) {
for (j = 0; j < i; j++)
if (U(i,j) != 0)
return false;
if (i > 0 && L(i,i) != U(i - 1,i - 1))
return false;
for (j = i + 1; j < n; j++)
if (L(i,j) != 0)
return false;
}
/* check whether $L \cdot A \cdot Q = U$ */
Matrix LA = L * A;
for (j = 0; j < n; j++)
if (LA.column(q[j]) != U.column(j))
return false;
/* compute sign |s| of |Q| */
int sign = 1;
/* we chase the cycles of |q|. An even length cycle contributes - 1
and vice versa */
std::vector<bool> already_considered(n);
for (i = 0; i < n; i++)
already_considered[i] = false;
for (i = 0; i < n; i++)
already_considered[q[i]] = true;
for (i = 0; i < n; i++)
if (! already_considered[i])
CGAL_error_msg("verify_determinant:q is not a permutation.");
else
already_considered[i] = false;
for (i = 0; i < n; i++) {
if (already_considered[i]) continue;
/* we have found a new cycle with minimal element $i$. */
int k = q[i];
already_considered[i] =true;
while (k != i) {
sign = - sign;
already_considered[k]= true;
k = q[k];
}
}
return (D == RT(sign) * U(n - 1,n - 1));
}
}
template <class RT_, class AL_>
int Linear_algebraHd<RT_,AL_>::
independent_columns(const Matrix& A,
std::vector<int>& columns)
{
Vector b(A.row_dimension()); // zero - vector
int i,j,k; // indices to step through the matrix
int rows = A.row_dimension();
int cols = A.column_dimension();
/* at this point one might want to check whether the computation can
be carried out with doubles, see section \ref{ optimization }. */
CGAL_assertion_msg(b.dimension() == rows,
"linear_solver: b has wrong dimension");
Matrix C(rows,cols + 1);
// the matrix in which we will calculate ($C = (A \vert b)$)
/* copy |A| and |b| into |C| and L becomes the identity matrix */
Matrix L(rows); // zero initialized
for(i=0; i<rows; i++) {
for(j=0; j<cols; j++)
C(i,j)=A(i,j);
C(i,cols)=b[i];
L(i,i) = 1; // diagonal elements are 1
}
std::vector<int> var(cols);
// column $j$ of |C| represents the |var[j]| - th variable
// the array is indexed between |0| and |cols - 1|
for(j=0; j<cols; j++)
var[j]= j; // at the beginning, variable $x_j$ stands in column $j$
RT_ denom = 1; // the determinant of an empty matrix is 1
int sign = 1; // no interchanges yet
int rank = 0; // we have not seen any non-zero row yet
/* here comes the main loop */
for(k=0; k<rows; k++) {
bool non_zero_found = false;
for(i = k; i < rows; i++) { // step through rows $k$ to |rows - 1|
for (j = k ; j < cols && C(i,j) == 0; j++) {}
// step through columns |k| to |cols - 1|
if (j < cols) {
non_zero_found = true;
break;
}
}
if ( non_zero_found ) {
rank++; //increase the rank
if (i != k) {
sign = -sign;
/* we interchange rows |k| and |i| of |L| and |C| */
L.swap_rows(i,k); C.swap_rows(i,k);
}
if (j != k) {
/* We interchange columns |k| and |j|, and
store the exchange of variables in |var| */
sign = - sign;
C.swap_columns(j,k);
std::swap(var[k],var[j]);
}
for(i = k + 1; i < rows; i++)
for (j = 0; j < rows; j++) //and all columns of |L|
L(i,j) = (L(i,j)*C(k,k) - C(i,k)*L(k,j))/denom;
for(i = k + 1; i < rows; i++) {
/* the following iteration uses and changes |C(i,k)| */
RT temp = C(i,k);
for (j = k; j <= cols; j++)
C(i,j) = (C(i,j)*C(k,k) - temp*C(k,j))/denom;
}
denom = C(k,k);
#ifdef CGAL_LA_SELFTEST
for(i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
RT Sum = 0;
for (int l = 0; l < rows; l++)
Sum += L(i,l)*A(l, var[j]);
CGAL_assertion_msg( Sum == C(i,j),
"linear_solver: L*A*P different from C");
}
RT Sum = 0;
for (int l = 0; l < rows; l++)
Sum += L(i,l)*b[l];
CGAL_assertion_msg( Sum == C(i,cols),
"linear_solver: L*A*P different from C");
}
#endif
}
else
break;
}
/* at this point we have:
|C| has an $rank \times rank$ upper triangular matrix
in its left upper corner;
|var| tells us the columns of |A| corresponding to the
dependent variables; */
columns = std::vector<int>(rank);
for(i = 0; i < rank; i++)
columns[i] = var[i];
return rank;
}
template <class RT_, class AL_>
int Linear_algebraHd<RT_,AL_>::
rank(const Matrix& A)
{
Vector b(A.row_dimension()); // zero - vector
int i,j,k; // indices to step through the matrix
int rows = A.row_dimension();
int cols = A.column_dimension();
/* at this point one might want to check whether the computation can
be carried out with doubles, see section \ref{ optimization }. */
CGAL_assertion_msg(b.dimension() == rows,
"linear_solver: b has wrong dimension");
Matrix C(rows,cols + 1);
// the matrix in which we will calculate ($C = (A \vert b)$)
/* copy |A| and |b| into |C| and L becomes the identity matrix */
Matrix L(rows); // zero initialized
for(i=0; i<rows; i++) {
for(j=0; j<cols; j++)
C(i,j)=A(i,j);
C(i,cols)=b[i];
L(i,i) = 1; // diagonal elements are 1
}
std::vector<int> var(cols);
// column $j$ of |C| represents the |var[j]| - th variable
// the array is indexed between |0| and |cols - 1|
for(j=0; j<cols; j++)
var[j]= j; // at the beginning, variable $x_j$ stands in column $j$
RT_ denom = 1; // the determinant of an empty matrix is 1
int sign = 1; // no interchanges yet
int rank = 0; // we have not seen any non-zero row yet
/* here comes the main loop */
for(k=0; k<rows; k++) {
bool non_zero_found = false;
for(i = k; i < rows; i++) { // step through rows $k$ to |rows - 1|
for (j = k ; j < cols && C(i,j) == 0; j++) {}
// step through columns |k| to |cols - 1|
if (j < cols) {
non_zero_found = true;
break;
}
}
if ( non_zero_found ) {
rank++; //increase the rank
if (i != k) {
sign = -sign;
/* we interchange rows |k| and |i| of |L| and |C| */
L.swap_rows(i,k); C.swap_rows(i,k);
}
if (j != k) {
/* We interchange columns |k| and |j|, and
store the exchange of variables in |var| */
sign = - sign;
C.swap_columns(j,k);
std::swap(var[k],var[j]);
}
for(i = k + 1; i < rows; i++)
for (j = 0; j < rows; j++) //and all columns of |L|
L(i,j) = (L(i,j)*C(k,k) - C(i,k)*L(k,j))/denom;
for(i = k + 1; i < rows; i++) {
/* the following iteration uses and changes |C(i,k)| */
RT temp = C(i,k);
for (j = k; j <= cols; j++)
C(i,j) = (C(i,j)*C(k,k) - temp*C(k,j))/denom;
}
denom = C(k,k);
#ifdef CGAL_LA_SELFTEST
for(i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
RT Sum = 0;
for (int l = 0; l < rows; l++)
Sum += L(i,l)*A(l, var[j]);
CGAL_assertion_msg( Sum == C(i,j),
"linear_solver: L*A*P different from C");
}
RT Sum = 0;
for (int l = 0; l < rows; l++)
Sum += L(i,l)*b[l];
CGAL_assertion_msg( Sum == C(i,cols),
"linear_solver: L*A*P different from C");
}
#endif
}
else
break;
}
return rank;
}
template <class RT_, class AL_>
bool Linear_algebraHd<RT_,AL_>::
inverse(const Matrix& A, Matrix& inverse,
RT_& D, Vector& c)
{
if (A.row_dimension() != A.column_dimension())
CGAL_error_msg("inverse: only square matrices are legal inputs.");
Vector b(A.row_dimension()); // zero - vector
int i,j,k; // indices to step through the matrix
int rows = A.row_dimension();
int cols = A.column_dimension();
/* at this point one might want to check whether the computation can
be carried out with doubles, see section \ref{ optimization }. */
CGAL_assertion_msg(b.dimension() == rows,
"linear_solver: b has wrong dimension");
Matrix C(rows,cols + 1);
// the matrix in which we will calculate ($C = (A \vert b)$)
/* copy |A| and |b| into |C| and L becomes the identity matrix */
Matrix L(rows); // zero initialized
for(i=0; i<rows; i++) {
for(j=0; j<cols; j++)
C(i,j)=A(i,j);
C(i,cols)=b[i];
L(i,i) = 1; // diagonal elements are 1
}
std::vector<int> var(cols);
// column $j$ of |C| represents the |var[j]| - th variable
// the array is indexed between |0| and |cols - 1|
for(j=0; j<cols; j++)
var[j]= j; // at the beginning, variable $x_j$ stands in column $j$
RT_ denom = 1; // the determinant of an empty matrix is 1
int sign = 1; // no interchanges yet
int rank = 0; // we have not seen any non-zero row yet
/* here comes the main loop */
for(k=0; k<rows; k++) {
bool non_zero_found = false;
for(i = k; i < rows; i++) { // step through rows $k$ to |rows - 1|
for (j = k ; j < cols && C(i,j) == 0; j++) {}
// step through columns |k| to |cols - 1|
if (j < cols) {
non_zero_found = true;
break;
}
}
if ( non_zero_found ) {
rank++; //increase the rank
if (i != k) {
sign = -sign;
/* we interchange rows |k| and |i| of |L| and |C| */
L.swap_rows(i,k); C.swap_rows(i,k);
}
if (j != k) {
/* We interchange columns |k| and |j|, and
store the exchange of variables in |var| */
sign = - sign;
C.swap_columns(j,k);
std::swap(var[k],var[j]);
}
for(i = k + 1; i < rows; i++)
for (j = 0; j < rows; j++) //and all columns of |L|
L(i,j) = (L(i,j)*C(k,k) - C(i,k)*L(k,j))/denom;
for(i = k + 1; i < rows; i++) {
/* the following iteration uses and changes |C(i,k)| */
RT temp = C(i,k);
for (j = k; j <= cols; j++)
C(i,j) = (C(i,j)*C(k,k) - temp*C(k,j))/denom;
}
denom = C(k,k);
#ifdef CGAL_LA_SELFTEST
for(i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
RT Sum = 0;
for (int l = 0; l < rows; l++)
Sum += L(i,l)*A(l, var[j]);
CGAL_assertion_msg( Sum == C(i,j),
"linear_solver: L*A*P different from C");
}
RT Sum = 0;
for (int l = 0; l < rows; l++)
Sum += L(i,l)*b[l];
CGAL_assertion_msg( Sum == C(i,cols),
"linear_solver: L*A*P different from C");
}
#endif
}
else
break;
}
if (rank < rows) {
// matrix is singular; return a vector $c$ with $c^T \cdot A = 0$.*/
c = L.row(rows-1);
return false;
}
D = denom;
inverse = Matrix(rows); //square
RT_ h;
for(i = 0; i <rows; i++)
{ // $i$-th column of inverse
for (j = rows - 1; j >= 0; j--) {
h = L (j,i) * D;
for (int l = j + 1; l<rows; l++)
h -= C(j,l)*inverse(var[l],i);
inverse(var[j],i) = h / C(j,j);
}
}
#ifdef CGAL_LA_SELFTEST
if (A*inverse != Matrix(rows,Matrix::RT_val(1))*D)
CGAL_error_msg("inverse(): matrix inverse computed incorrectly.");
#endif
return true;
}
template <class RT_, class AL_>
int Linear_algebraHd<RT_,AL_>::
homogeneous_linear_solver(const Matrix &A,
Matrix& spanning_vectors)
/* returns the dimension of the solution space of the homogeneous system
$Ax = 0$. The columns of spanning\_vectors span the solution space. */
{
Vector b(A.row_dimension()); // zero - vector
RT_ D;
int i,j,k; // indices to step through the matrix
int rows = A.row_dimension();
int cols = A.column_dimension();
/* at this point one might want to check whether the computation can
be carried out with doubles, see section \ref{ optimization }. */
CGAL_assertion_msg(b.dimension() == rows,
"linear_solver: b has wrong dimension");
Matrix C(rows,cols + 1);
// the matrix in which we will calculate ($C = (A \vert b)$)
/* copy |A| and |b| into |C| and L becomes the identity matrix */
Matrix L(rows); // zero initialized
for(i=0; i<rows; i++) {
for(j=0; j<cols; j++)
C(i,j)=A(i,j);
C(i,cols)=b[i];
L(i,i) = 1; // diagonal elements are 1
}
std::vector<int> var(cols);
// column $j$ of |C| represents the |var[j]| - th variable
// the array is indexed between |0| and |cols - 1|
for(j=0; j<cols; j++)
var[j]= j; // at the beginning, variable $x_j$ stands in column $j$
RT_ denom = 1; // the determinant of an empty matrix is 1
int sign = 1; // no interchanges yet
int rank = 0; // we have not seen any non-zero row yet
/* here comes the main loop */
for(k=0; k<rows; k++) {
bool non_zero_found = false;
for(i = k; i < rows; i++) { // step through rows $k$ to |rows - 1|
for (j = k ; j < cols && C(i,j) == 0; j++) {}
// step through columns |k| to |cols - 1|
if (j < cols) {
non_zero_found = true;
break;
}
}
if ( non_zero_found ) {
rank++; //increase the rank
if (i != k) {
sign = -sign;
/* we interchange rows |k| and |i| of |L| and |C| */
L.swap_rows(i,k); C.swap_rows(i,k);
}
if (j != k) {
/* We interchange columns |k| and |j|, and
store the exchange of variables in |var| */
sign = - sign;
C.swap_columns(j,k);
std::swap(var[k],var[j]);
}
for(i = k + 1; i < rows; i++)
for (j = 0; j < rows; j++) //and all columns of |L|
L(i,j) = (L(i,j)*C(k,k) - C(i,k)*L(k,j))/denom;
for(i = k + 1; i < rows; i++) {
/* the following iteration uses and changes |C(i,k)| */
RT temp = C(i,k);
for (j = k; j <= cols; j++)
C(i,j) = (C(i,j)*C(k,k) - temp*C(k,j))/denom;
}
denom = C(k,k);
#ifdef CGAL_LA_SELFTEST
for(i = 0; i < rows; i++) {
for (j = 0; j < cols; j++) {
RT Sum = 0;
for (int l = 0; l < rows; l++)
Sum += L(i,l)*A(l, var[j]);
CGAL_assertion_msg( Sum == C(i,j),
"linear_solver: L*A*P different from C");
}
RT Sum = 0;
for (int l = 0; l < rows; l++)
Sum += L(i,l)*b[l];
CGAL_assertion_msg( Sum == C(i,cols),
"linear_solver: L*A*P different from C");
}
#endif
}
else
break;
}
Vector x;
x = Vector(cols);
D = denom;
for(i = rank - 1; i >= 0; i--) {
RT_ h = C(i,cols) * D;
for (j = i + 1; j < rank; j++) {
h -= C(i,j)*x[var[j]];
}
x[var[i]]= h / C(i,i);
}
#ifdef CGAL_LA_SELFTEST
CGAL_assertion( (M*x).is_zero() );
#endif
int defect = cols - rank; // dimension of kernel
spanning_vectors = Matrix(cols,defect);
if (defect > 0) {
for(int l=0; l < defect; l++) {
spanning_vectors(var[rank + l],l)=D;
for(i = rank - 1; i >= 0 ; i--) {
RT_ h = - C(i,rank + l)*D;
for ( j= i + 1; j<rank; j++)
h -= C(i,j)*spanning_vectors(var[j],l);
spanning_vectors(var[i],l)= h / C(i,i);
}
#ifdef CGAL_LA_SELFTEST
/* we check whether the $l$ - th spanning vector is a solution
of the homogeneous system */
CGAL_assertion( (M*spanning_vectors.column(l)).is_zero() );
#endif
}
}
;
return defect;
}
template <class RT_, class AL_>
bool Linear_algebraHd<RT_,AL_>::
homogeneous_linear_solver(const Matrix& A, Vector& x)
/* returns true if the homogeneous system $Ax = 0$ has a non - trivial
solution and false otherwise. */
{
x = Vector(A.row_dimension());
Matrix spanning_vectors;
int dimension = homogeneous_linear_solver(A,spanning_vectors);
if (dimension == 0) return false;
/* return first column of |spanning_vectors| */
for (int i = 0; i < spanning_vectors.row_dimension(); i++)
x[i] = spanning_vectors(i,0);
return true;
}
template <class RT_, class AL_>
typename Linear_algebraHd<RT_,AL_>::Matrix
Linear_algebraHd<RT_,AL_>::transpose(const Matrix& M)
{
int d1 = M.row_dimension();
int d2 = M.column_dimension();
Matrix result(d2,d1);
for(int i = 0; i < d2; i++)
for(int j = 0; j < d1; j++)
result(i,j) = M(j,i);
return result;
}
} //namespace CGAL
#endif //CGAL_LINEAR_ALGEBRAHD_C
| 29.410557 | 83 | 0.514674 | [
"vector"
] |
365381f2f545c3f675603cd0264a44e6e77183c1 | 3,870 | h | C | module/ABKCommon/src/abkstring.h | ilesser/TritonMacroPlace | 83866e14a6077e5ebaaed1f32d08344e0528d2b0 | [
"BSD-3-Clause"
] | 15 | 2019-07-21T02:15:52.000Z | 2021-04-13T01:14:18.000Z | module/ABKCommon/src/abkstring.h | abk-openroad/TritonMacroPlace | 83866e14a6077e5ebaaed1f32d08344e0528d2b0 | [
"BSD-3-Clause"
] | 6 | 2019-08-12T19:20:42.000Z | 2020-07-03T08:29:53.000Z | module/ABKCommon/src/abkstring.h | abk-openroad/TritonMacroPlace | 83866e14a6077e5ebaaed1f32d08344e0528d2b0 | [
"BSD-3-Clause"
] | 12 | 2019-12-12T02:57:08.000Z | 2021-12-21T13:18:39.000Z | /**************************************************************************
***
*** Copyright (c) 1995-2000 Regents of the University of California,
*** Andrew E. Caldwell, Andrew B. Kahng and Igor L. Markov
*** Copyright (c) 2000-2010 Regents of the University of Michigan,
*** Saurabh N. Adya, Jarrod A. Roy, David A. Papa and
*** Igor L. Markov
***
*** Contact author(s): abk@cs.ucsd.edu, imarkov@umich.edu
*** Original Affiliation: UCLA, Computer Science Department,
*** Los Angeles, CA 90095-1596 USA
***
*** 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.
***
***
***************************************************************************/
/*
*
* Copyright (c) 1995, by Sun Microsystems, Inc.
* Copyright (c) 1997, by ABKGroup and the Regents of the University of Calif.
*
*/
//! author="July, 1997 by Igor Markov, VLSI CAD ABKGroup UCLA/CS"
//! CHANGES=" abkstring.h 970820 ilm moved handling of strcasecmp and _stricmp from abktempl.h 990119 mro added analogous corresp. btw. strncasecmp and _strnicmp ilm: 970722 added for "symmetry" (NT -> Solaris portability) "
/* using the <string.h> distributed with the SunPro CC compiler
CHANGES (those made after August 18, 1997)
970820 ilm moved handling of strcasecmp and _stricmp from abktempl.h
990119 mro added analogous corresp. btw. strncasecmp and _strnicmp
ilm: 970722 added for "symmetry" (NT -> Solaris portability)
*/
#ifndef _STRINGS_H
#define _STRINGS_H
#if defined(WIN32) && !defined(STRCASECMP)
#define STRCASECMP
#define strcasecmp _stricmp
#endif
#if !defined(WIN32) && !defined(STRICMP) && !defined(STRCASECMP)
#define STRICMP
#define _stricmp strcasecmp
#endif
#if defined(WIN32) && !defined(STRNCASECMP)
#define STRNCASECMP
#define strncasecmp _strnicmp
#endif
#if !defined(WIN32) && !defined(STRNICMP) && !defined(STRCASECMP)
#define STRNICMP
#define _strnicmp strncasecmp
#endif
#ifdef WIN32
char *ulltostr(unsigned value,char *ptr);
char *lltostr(int value,char *ptr);
#endif
/* =========================================================================*/
#ifndef WIN32
#include <string.h>
#else
#if !defined(_XOPEN_SOURCE)
#include <string.h>
#endif
#ifdef __cplusplus
extern "C" {
#endif
#if defined(__STDC__)
extern int bcmp(const void *s1, const void *s2, size_t n);
extern void bcopy(const void *s1, void *s2, size_t n);
extern void bzero(void *s, size_t n);
extern char *index(const char *s, int c);
extern char *rindex(const char *s, int c);
#else
extern int bcmp();
extern void bcopy();
extern void bzero();
extern char *index();
extern char *rindex();
#endif /* __STDC__ */
#ifdef __cplusplus
}
#endif
#endif /* defined(WIN32)*/
int abk_strcasecmp(const char* a, const char* b);
#endif /* _STRINGS_H */
| 30 | 231 | 0.668475 | [
"cad"
] |
36556c24add85aaed8c23e7fdaf1ef4c4f377d39 | 2,473 | h | C | dev/Code/CryEngine/Cry3DEngine/DeformableNode.h | stickyparticles/lumberyard | dc523dd780f3cd1874251181b7cf6848b8db9959 | [
"AML"
] | 2 | 2018-03-29T10:56:36.000Z | 2020-12-12T15:28:14.000Z | dev/Code/CryEngine/Cry3DEngine/DeformableNode.h | JulianoCristian/Lumberyard-3 | dc523dd780f3cd1874251181b7cf6848b8db9959 | [
"AML"
] | null | null | null | dev/Code/CryEngine/Cry3DEngine/DeformableNode.h | JulianoCristian/Lumberyard-3 | dc523dd780f3cd1874251181b7cf6848b8db9959 | [
"AML"
] | 3 | 2019-05-13T09:41:33.000Z | 2021-04-09T12:12:38.000Z | /*
* All or portions of this file Copyright (c) Amazon.com, Inc. or its affiliates or
* its licensors.
*
* For complete copyright and license terms please see the LICENSE at the root of this
* distribution (the "License"). All use of this software is governed by the License,
* or, if provided, by the license below or the license accompanying this file. Do not
* remove or modify any license notices. This file is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*
*/
// Original file Copyright Crytek GMBH or its affiliates, used under license.
#ifndef CRYINCLUDE_CRY3DENGINE_DEFORMABLENODE_H
#define CRYINCLUDE_CRY3DENGINE_DEFORMABLENODE_H
#pragma once
struct SDeformableData;
struct SMMRMProjectile;
class CDeformableNode
{
SDeformableData** m_pData;
size_t m_nData;
uint32 m_nFrameId;
Vec3* m_wind;
primitives::sphere* m_Colliders;
int m_nColliders;
SMMRMProjectile* m_Projectiles;
int m_nProjectiles;
AABB m_bbox;
IGeneralMemoryHeap* m_pHeap;
std::vector<CRenderChunk> m_renderChunks;
_smart_ptr<IRenderMesh> m_renderMesh;
size_t m_numVertices, m_numIndices;
CStatObj* m_pStatObj;
JobManager::SJobState m_cullState;
JobManager::SJobState m_updateState;
bool m_all_prepared : 1;
protected:
void UpdateInternalDeform(SDeformableData* pData
, CRenderObject* pRenderObject, const AABB& bbox
, const SRenderingPassInfo& passInfo
, _smart_ptr<IRenderMesh>&
, strided_pointer<SVF_P3S_C4B_T2S>
, strided_pointer<SPipTangents>
, strided_pointer<Vec3>
, vtx_idx* idxBuf
, size_t& iv
, size_t& ii);
void ClearInstanceData();
void ClearSimulationData();
void CreateInstanceData(SDeformableData* pData, CStatObj* pStatObj);
void BakeInternal(SDeformableData* pData, const Matrix34& worldTM);
public:
CDeformableNode(uint16 slot);
~CDeformableNode();
void SetStatObj(CStatObj* pStatObj);
void CreateDeformableSubObject(bool create, const Matrix34& worldTM, IGeneralMemoryHeap* pHeap);
void RenderInternalDeform(CRenderObject* pRenderObject
, int nLod, const AABB& bbox, const SRenderingPassInfo& passInfo
, const SRendItemSorter& rendItemSorter);
void BakeDeform(const Matrix34& worldTM);
bool HasDeformableData() const { return m_nData != 0; }
};
#endif // CRYINCLUDE_CRY3DENGINE_DEFORMABLENODE_H
| 29.440476 | 100 | 0.736353 | [
"vector"
] |
365703773d03565564cec4ae7c9cdac7f264964b | 418 | c | C | src/graphics/gfx.c | Kubic-C/spok-engine | a3400c4664c08c049f778681ffa2ccef0180cc96 | [
"Apache-2.0"
] | null | null | null | src/graphics/gfx.c | Kubic-C/spok-engine | a3400c4664c08c049f778681ffa2ccef0180cc96 | [
"Apache-2.0"
] | null | null | null | src/graphics/gfx.c | Kubic-C/spok-engine | a3400c4664c08c049f778681ffa2ccef0180cc96 | [
"Apache-2.0"
] | null | null | null | #include "spok/gfx.h"
#include "core/state.h"
#include "render.h"
void spok_set_fov(float fov) {
render_state_tt* p_render_state = ((render_state_tt*)g_state.p_active->render_data);
int width, height;
p_render_state->fov = fov;
glfwGetWindowSize(g_state.p_active->window, &width, &height);
glm_perspective(glm_rad(p_render_state->fov), (float)width / (float)height, NEARZ, FARZ, p_render_state->proj);
}
| 32.153846 | 115 | 0.741627 | [
"render"
] |
365999d50d1d7207815c2c0ebd5786b96bf46070 | 1,572 | h | C | writer/frg_private/bgr_zip/frg_color_zip.h | sisong/libfrg | 9d1d4f2bd9ad0a29de5da3e65cc1f7d2f5d364ef | [
"MIT"
] | 20 | 2015-03-03T01:05:44.000Z | 2021-05-17T06:45:17.000Z | writer/frg_private/bgr_zip/frg_color_zip.h | sisong/libfrg | 9d1d4f2bd9ad0a29de5da3e65cc1f7d2f5d364ef | [
"MIT"
] | 5 | 2019-09-18T18:26:36.000Z | 2020-10-22T02:53:40.000Z | writer/frg_private/bgr_zip/frg_color_zip.h | sisong/libfrg | 9d1d4f2bd9ad0a29de5da3e65cc1f7d2f5d364ef | [
"MIT"
] | 8 | 2016-09-16T10:55:29.000Z | 2019-12-14T07:43:32.000Z | // frg_color_zip.h
// for frg_writer
// frg图片文件rgb压缩.
/*
This is the frg copyright.
Copyright (c) 2012-2013 HouSisong All Rights Reserved.
(The MIT License)
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 __LIBFRG_FRG_COLOR_ZIP_H_
#define __LIBFRG_FRG_COLOR_ZIP_H_
#include "frg_color_base.h"
namespace frg{
void bgrZiper_save(std::vector<TByte>& out_buf,const TPixels32Ref& src_ref,float colorQuality,bool isMustFitColorTable,TUInt* out_bgrColorTableLength);
}//end namespace frg
#endif //__LIBFRG_FRG_COLOR_ZIP_H_ | 38.341463 | 152 | 0.772265 | [
"vector"
] |
365bc091c121cce1178e8f8c9b133fce46b2e284 | 5,684 | h | C | chrome/browser/sync/test/integration/sessions_helper.h | google-ar/chromium | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 777 | 2017-08-29T15:15:32.000Z | 2022-03-21T05:29:41.000Z | chrome/browser/sync/test/integration/sessions_helper.h | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 66 | 2017-08-30T18:31:18.000Z | 2021-08-02T10:59:35.000Z | chrome/browser/sync/test/integration/sessions_helper.h | harrymarkovskiy/WebARonARCore | 2441c86a5fd975f09a6c30cddb57dfb7fc239699 | [
"Apache-2.0",
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 123 | 2017-08-30T01:19:34.000Z | 2022-03-17T22:55:31.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 CHROME_BROWSER_SYNC_TEST_INTEGRATION_SESSIONS_HELPER_H_
#define CHROME_BROWSER_SYNC_TEST_INTEGRATION_SESSIONS_HELPER_H_
#include <algorithm>
#include <map>
#include <memory>
#include <string>
#include <vector>
#include "base/compiler_specific.h"
#include "chrome/browser/sync/test/integration/multi_client_status_change_checker.h"
#include "chrome/browser/sync/test/integration/sync_test.h"
#include "components/sessions/core/session_types.h"
#include "components/sync/syncable/nigori_util.h"
#include "components/sync_sessions/synced_session.h"
class GURL;
namespace sessions_helper {
using SyncedSessionVector = std::vector<const sync_sessions::SyncedSession*>;
using SessionWindowMap = std::map<SessionID::id_type, sessions::SessionWindow*>;
using ScopedWindowMap =
std::map<SessionID::id_type, std::unique_ptr<sessions::SessionWindow>>;
// Copies the local session windows of profile |index| to |local_windows|.
// Returns true if successful.
bool GetLocalWindows(int index, ScopedWindowMap* local_windows);
// Creates and verifies the creation of a new window for profile |index| with
// one tab displaying |url|. Copies the SessionWindow associated with the new
// window to |local_windows|. Returns true if successful. This call results in
// multiple sessions changes, and performs synchronous blocking. It is rare, but
// possible, that multiple sync cycle commits occur as a result of this call.
// Test cases should be written to handle this possibility, otherwise they may
// flake.
bool OpenTabAndGetLocalWindows(int index,
const GURL& url,
ScopedWindowMap* local_windows);
// Checks that window count and foreign session count are 0.
bool CheckInitialState(int index);
// Returns number of open windows for a profile.
int GetNumWindows(int index);
// Returns number of foreign sessions for a profile.
int GetNumForeignSessions(int index);
// Fills the sessions vector with the model associator's foreign session data.
// Caller owns |sessions|, but not SyncedSessions objects within.
// Returns true if foreign sessions were found, false otherwise.
bool GetSessionData(int index, SyncedSessionVector* sessions);
// Compares a foreign session based on the first session window.
// Returns true based on the comparison of the session windows.
bool CompareSyncedSessions(const sync_sessions::SyncedSession* lhs,
const sync_sessions::SyncedSession* rhs);
// Sort a SyncedSession vector using our custom SyncedSession comparator.
void SortSyncedSessions(SyncedSessionVector* sessions);
// Compares two tab navigations base on the parameters we sync.
// (Namely, we don't sync state or type mask)
bool NavigationEquals(const sessions::SerializedNavigationEntry& expected,
const sessions::SerializedNavigationEntry& actual);
// Verifies that two SessionWindows match.
// Returns:
// - true if all the following match:
// 1. number of SessionWindows,
// 2. number of tabs per SessionWindow,
// 3. number of tab navigations per tab,
// 4. actual tab navigations contents
// - false otherwise.
bool WindowsMatch(const ScopedWindowMap& win1, const ScopedWindowMap& win2);
bool WindowsMatch(const SessionWindowMap& win1, const ScopedWindowMap& win2);
// Retrieves the foreign sessions for a particular profile and compares them
// with a reference SessionWindow list.
// Returns true if the session windows of the foreign session matches the
// reference.
bool CheckForeignSessionsAgainst(
int index,
const std::vector<ScopedWindowMap>& windows);
// Open a single tab and block until the session model associator is aware
// of it. Returns true upon success, false otherwise.
bool OpenTab(int index, const GURL& url);
// Open multiple tabs and block until the session model associator is aware
// of all of them. Returns true on success, false on failure.
bool OpenMultipleTabs(int index, const std::vector<GURL>& urls);
// Wait for a session change to propagate to the model associator. Will not
// return until each url in |urls| has been found.
bool WaitForTabsToLoad(int index, const std::vector<GURL>& urls);
// Check if the session model associator's knows that the current open tab
// has this url.
bool ModelAssociatorHasTabWithUrl(int index, const GURL& url);
// Stores a pointer to the local session for a given profile in |session|.
// Returns true on success, false on failure.
bool GetLocalSession(int index, const sync_sessions::SyncedSession** session);
// Deletes the foreign session with tag |session_tag| from the profile specified
// by |index|. This will affect all synced clients.
// Note: We pass the session_tag in by value to ensure it's not a reference
// to the session tag within the SyncedSession we plan to delete.
void DeleteForeignSession(int index, std::string session_tag);
} // namespace sessions_helper
// Checker to block until the foreign sessions for a particular profile matches
// the reference windows.
class ForeignSessionsMatchChecker : public MultiClientStatusChangeChecker {
public:
ForeignSessionsMatchChecker(
int index,
const std::vector<sessions_helper::ScopedWindowMap>& windows);
// StatusChangeChecker implementation.
bool IsExitConditionSatisfied() override;
std::string GetDebugMessage() const override;
private:
int index_;
const std::vector<sessions_helper::ScopedWindowMap>& windows_;
};
#endif // CHROME_BROWSER_SYNC_TEST_INTEGRATION_SESSIONS_HELPER_H_
| 41.489051 | 84 | 0.768649 | [
"vector",
"model"
] |
36611c25863004205f69123d16f6508fecdc8e73 | 2,444 | h | C | docopt/src/docopt/docopt_util.h | DrPizza/cpuid | f8901c5c7b9a4a62f550d835a2a14fc6eec147e5 | [
"MIT"
] | 3 | 2018-03-06T08:00:56.000Z | 2021-06-29T06:46:39.000Z | docopt/src/docopt/docopt_util.h | DrPizza/cpuid | f8901c5c7b9a4a62f550d835a2a14fc6eec147e5 | [
"MIT"
] | null | null | null | docopt/src/docopt/docopt_util.h | DrPizza/cpuid | f8901c5c7b9a4a62f550d835a2a14fc6eec147e5 | [
"MIT"
] | null | null | null | // from https://github.com/docopt/docopt.cpp, dual licensed under MIT and Boost license
//
// docopt_util.h
// docopt
//
// Created by Jared Grubb on 2013-11-04.
// Copyright (c) 2013 Jared Grubb. All rights reserved.
//
#ifndef docopt_docopt_util_h
#define docopt_docopt_util_h
#include <string>
#include <boost/xpressive/xpressive.hpp>
namespace xp = boost::xpressive;
namespace {
bool starts_with(std::string const& str, std::string const& prefix) {
if(str.length() < prefix.length()) {
return false;
}
return std::equal(prefix.begin(), prefix.end(), str.begin());
}
std::string trim(std::string&& str, const std::string& whitespace = " \t\n") {
const auto strEnd = str.find_last_not_of(whitespace);
if(strEnd == std::string::npos) {
return {}; // no content
}
str.erase(strEnd + 1);
const auto strBegin = str.find_first_not_of(whitespace);
str.erase(0, strBegin);
return std::move(str);
}
std::vector<std::string> split(std::string const& str, size_t pos = 0) {
const char* const anySpace = " \t\r\n\v\f";
std::vector<std::string> ret;
while(pos != std::string::npos) {
const auto start = str.find_first_not_of(anySpace, pos);
if(start == std::string::npos) {
break;
}
const auto end = str.find_first_of(anySpace, start);
const auto size = end == std::string::npos ? end : end - start;
ret.emplace_back(str.substr(start, size));
pos = end;
}
return ret;
}
std::tuple<std::string, std::string, std::string> partition(std::string str, std::string const& point) {
std::tuple<std::string, std::string, std::string> ret;
const auto i = str.find(point);
if(i == std::string::npos) {
// no match: string goes in 0th spot only
} else {
std::get<2>(ret) = str.substr(i + point.size());
std::get<1>(ret) = point;
str.resize(i);
}
std::get<0>(ret) = std::move(str);
return ret;
}
template <typename I>
std::string join(I iter, I end, std::string const& delim) {
if(iter == end) {
return {};
}
std::string ret = *iter;
for(++iter; iter != end; ++iter) {
ret.append(delim);
ret.append(*iter);
}
return ret;
}
std::vector<std::string> regex_split(std::string const& text, xp::sregex const& re) {
std::vector<std::string> ret;
for(auto it = xp::sregex_token_iterator(text.begin(), text.end(), re, -1);
it != xp::sregex_token_iterator();
++it) {
ret.emplace_back(*it);
}
return ret;
}
}
#endif
| 23.960784 | 105 | 0.639525 | [
"vector"
] |
3662e754623b60945a0f14949be0d1ae5da52071 | 8,768 | h | C | modules/core/include/lagrange/marching_triangles.h | LaudateCorpus1/lagrange | 2a49d3ee93c1f1e712c93c5c87ea25b9a83c8f40 | [
"Apache-2.0"
] | 156 | 2021-01-08T19:53:06.000Z | 2022-03-25T18:32:52.000Z | modules/core/include/lagrange/marching_triangles.h | LaudateCorpus1/lagrange | 2a49d3ee93c1f1e712c93c5c87ea25b9a83c8f40 | [
"Apache-2.0"
] | 2 | 2021-01-11T20:18:07.000Z | 2021-08-04T15:53:57.000Z | modules/core/include/lagrange/marching_triangles.h | LaudateCorpus1/lagrange | 2a49d3ee93c1f1e712c93c5c87ea25b9a83c8f40 | [
"Apache-2.0"
] | 10 | 2021-01-11T21:03:54.000Z | 2022-01-24T06:27:44.000Z | /*
* Copyright 2020 Adobe. All rights reserved.
* This file is licensed to you 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 REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
#pragma once
#include <map>
#include <memory>
#include <string>
#include <unordered_map>
#include <vector>
#include <Eigen/Core>
#include <lagrange/Edge.h>
#include <lagrange/MeshTrait.h>
#include <lagrange/utils/la_assert.h>
#include <lagrange/utils/range.h>
namespace lagrange {
template <typename MeshType_>
struct MarchingTrianglesOutput
{
using MeshType = MeshType_;
using Index = typename MeshType::Index;
using IndexList = typename MeshType::IndexList;
using Scalar = typename MeshType::Scalar;
using VertexArray = typename MeshType::VertexArray;
using EdgeArray = Eigen::Matrix<Index, Eigen::Dynamic, 2, Eigen::RowMajor>;
// The extracted vertices of the contour
VertexArray vertices;
// Note that the direction in the edges bears no particular meaning
EdgeArray edges;
// The edge parent that gives birth to a marching triangle vertex
IndexList vertices_parent_edge;
// The param ( 0 =< t =< 1 ) that gives birth to each vertex.
// NOTE: t is defined such that position of vertex is (1-t)*v0 + t*v1,
// i.e., t=0 means the vertex is on v0 and t=1 means that it is on v1.
std::vector<Scalar> vertices_parent_param;
};
// Perform marching triangles to extract the isocontours of a field
// defined by the linear interpolation of a vertex attribute.
//
// Adapted from https://www.cs.ubc.ca/~rbridson/download/common_2008_nov_12.tar.gz
// (code released to the __public domain__ by Robert Bridson)
//
// Input:
// mesh_ref, the mesh to run marching cubes on. Can be 2D or 3D,
// but must be triangular.
// isovalue, the isovalue to be extracted.
// vertex_attribute_name, the name of the vertex attribute
// attribute_col_index, which column of the vertex attribute should be used?
//
template <typename MeshType>
MarchingTrianglesOutput<MeshType> marching_triangles(
MeshType& mesh_ref,
const typename MeshType::Scalar isovalue,
const std::string vertex_attribute_name,
const typename MeshType::Index attribute_col_index = 0)
{
static_assert(MeshTrait<MeshType>::is_mesh(), "Input type is not Mesh");
using Index = typename MeshType::Index;
using Scalar = typename MeshType::Scalar;
using VertexType = typename MeshType::VertexType;
using MarchingTrianglesOutput = ::lagrange::MarchingTrianglesOutput<MeshType>;
using Edge = typename MeshType::Edge;
LA_ASSERT(
mesh_ref.has_vertex_attribute(vertex_attribute_name),
"attribute does not exist in the mesh");
LA_ASSERT(mesh_ref.get_vertex_per_facet() == 3, "only works for triangle meshes");
mesh_ref.initialize_edge_data();
const auto& attribute = mesh_ref.get_vertex_attribute(vertex_attribute_name);
LA_ASSERT(attribute_col_index < safe_cast<Index>(attribute.cols()), "col_index is invalid");
const auto& facets = mesh_ref.get_facets();
const auto& vertices = mesh_ref.get_vertices();
std::vector<Edge> extracted_edges;
std::vector<VertexType> extracted_vertices;
std::vector<Index> extracted_vertices_parent_edge;
std::vector<Scalar> extracted_vertices_parent_param;
std::vector<Index> parent_edge_to_extracted_vertex(
mesh_ref.get_num_edges(),
INVALID<Index>());
//
// Find the point that attains a zero value on an edge
// (if it does not exists, creates it)
// Returns the index of this vertex
//
auto find_zero = [&](Index parent_edge_id, Index v0, Index v1, Scalar p0, Scalar p1) -> Index {
if (parent_edge_to_extracted_vertex[parent_edge_id] != INVALID<Index>()) {
return parent_edge_to_extracted_vertex[parent_edge_id];
} else {
// Get the edge and see if the order of v0 v1 and the edge values are the same.
const auto parent_edge = mesh_ref.get_edge_vertices(parent_edge_id);
if ((v0 == parent_edge[1]) && (v1 == parent_edge[0])) {
std::swap(p0, p1);
std::swap(v0, v1);
}
assert((v1 == parent_edge[1]) && (v0 == parent_edge[0]));
// Now construct the vertex
const Scalar a = p1 / (p1 - p0);
const Scalar b = 1 - a;
assert(a >= 0);
assert(a <= 1);
assert(b >= 0);
assert(b <= 1);
LA_ASSERT(!std::isnan(a));
LA_ASSERT(!std::isnan(b));
const Index vertex_index = safe_cast<Index>(extracted_vertices.size());
const VertexType pos0 = vertices.row(v0);
const VertexType pos1 = vertices.row(v1);
// And push it into the data structures
extracted_vertices.emplace_back(a * pos0 + b * pos1);
extracted_vertices_parent_edge.emplace_back(parent_edge_id);
extracted_vertices_parent_param.emplace_back(b);
parent_edge_to_extracted_vertex[parent_edge_id] = vertex_index;
return vertex_index;
}
};
//
// Find the contour (if exists) in a triangle
//
auto contour_triangle = [&](const Index tri_id) {
const Index v0 = facets(tri_id, 0);
const Index v1 = facets(tri_id, 1);
const Index v2 = facets(tri_id, 2);
Scalar p0 = attribute(v0, attribute_col_index) - isovalue;
Scalar p1 = attribute(v1, attribute_col_index) - isovalue;
Scalar p2 = attribute(v2, attribute_col_index) - isovalue;
const Index e01 = mesh_ref.get_edge(tri_id, 0);
const Index e12 = mesh_ref.get_edge(tri_id, 1);
const Index e20 = mesh_ref.get_edge(tri_id, 2);
// guard against topological degeneracies
if (p0 == 0) p0 = Scalar(1e-30);
if (p1 == 0) p1 = Scalar(1e-30);
if (p2 == 0) p2 = Scalar(1e-30);
if (p0 < 0) {
if (p1 < 0) {
if (p2 < 0) {
return; // no contour here
} else { /* p2>0 */
extracted_edges.push_back(
Edge(find_zero(e12, v1, v2, p1, p2), find_zero(e20, v0, v2, p0, p2)));
} // p2
} else { // p1>0
if (p2 < 0) {
extracted_edges.push_back(
Edge(find_zero(e01, v0, v1, p0, p1), find_zero(e12, v1, v2, p1, p2)));
} else { /* p2>0 */
extracted_edges.push_back(
Edge(find_zero(e01, v0, v1, p0, p1), find_zero(e20, v0, v2, p0, p2)));
} // p2
} // p1
} else { // p0>0
if (p1 < 0) {
if (p2 < 0) {
extracted_edges.push_back(
Edge(find_zero(e20, v0, v2, p0, p2), find_zero(e01, v0, v1, p0, p1)));
} else { /* p2>0 */
extracted_edges.push_back(
Edge(find_zero(e12, v1, v2, p1, p2), find_zero(e01, v0, v1, p0, p1)));
} // p2
} else { // p1>0
if (p2 < 0) {
extracted_edges.push_back(
Edge(find_zero(e20, v0, v2, p0, p2), find_zero(e12, v1, v2, p1, p2)));
} else { /* p2>0 */
return; // no contour here
} // p2
} // p1
} // p0
};
//
// Contour all triangles
//
for (auto tri : range(mesh_ref.get_num_facets())) {
contour_triangle(tri);
}
//
// Now convert to output
//
MarchingTrianglesOutput output;
// Output edges
output.edges.resize(extracted_edges.size(), 2);
for (auto i : range(extracted_edges.size())) {
output.edges.row(i) << extracted_edges[i][0], extracted_edges[i][1];
}
// output vertices
// This we can just swap!
output.vertices_parent_edge.swap(extracted_vertices_parent_edge);
output.vertices_parent_param.swap(extracted_vertices_parent_param);
// rest we have to copy
output.vertices.resize(extracted_vertices.size(), mesh_ref.get_dim());
for (auto i : range(extracted_vertices.size())) {
output.vertices.row(i) = extracted_vertices[i];
}
return output;
}
} // namespace lagrange
| 39.674208 | 99 | 0.616446 | [
"mesh",
"vector",
"3d"
] |
3663ff2139cdfaa34b74614052225843d22429c4 | 3,677 | h | C | src/ray/raylet/task.h | cumttang/ray | eb1e5fa2cf26233701ccbda3eb8a301ecd418d8c | [
"Apache-2.0"
] | 2 | 2019-10-08T13:31:08.000Z | 2019-10-22T18:34:52.000Z | src/ray/raylet/task.h | cumttang/ray | eb1e5fa2cf26233701ccbda3eb8a301ecd418d8c | [
"Apache-2.0"
] | 1 | 2018-12-26T01:09:50.000Z | 2018-12-26T01:09:50.000Z | src/ray/raylet/task.h | cumttang/ray | eb1e5fa2cf26233701ccbda3eb8a301ecd418d8c | [
"Apache-2.0"
] | 6 | 2019-03-12T05:37:35.000Z | 2020-03-09T12:25:17.000Z | #ifndef RAY_RAYLET_TASK_H
#define RAY_RAYLET_TASK_H
#include <inttypes.h>
#include "ray/raylet/format/node_manager_generated.h"
#include "ray/raylet/task_execution_spec.h"
#include "ray/raylet/task_spec.h"
namespace ray {
namespace raylet {
/// \class Task
///
/// A Task represents a Ray task and a specification of its execution (e.g.,
/// resource demands). The task's specification contains both immutable fields,
/// determined at submission time, and mutable fields, determined at execution
/// time.
class Task {
public:
/// Create a task.
///
/// \param execution_spec The execution specification for the task. These are
/// the mutable fields in the task specification that may change at task
/// execution time.
/// \param task_spec The immutable specification for the task. These fields
/// are determined at task submission time.
Task(const TaskExecutionSpecification &execution_spec,
const TaskSpecification &task_spec)
: task_execution_spec_(execution_spec), task_spec_(task_spec) {
ComputeDependencies();
}
/// Create a task from a serialized flatbuffer.
///
/// \param task_flatbuffer The serialized task.
Task(const protocol::Task &task_flatbuffer)
: Task(*task_flatbuffer.task_execution_spec(),
*task_flatbuffer.task_specification()) {}
/// Create a task from a flatbuffer object.
///
/// \param task_data The task flatbuffer object.
Task(const protocol::TaskT &task_data)
: Task(*task_data.task_execution_spec, task_data.task_specification) {}
/// Destroy the task.
virtual ~Task() {}
/// Serialize a task to a flatbuffer.
///
/// \param fbb The flatbuffer builder.
/// \return An offset to the serialized task.
flatbuffers::Offset<protocol::Task> ToFlatbuffer(
flatbuffers::FlatBufferBuilder &fbb) const;
/// Get the mutable specification for the task. This specification may be
/// updated at runtime.
///
/// \return The mutable specification for the task.
const TaskExecutionSpecification &GetTaskExecutionSpec() const;
/// Get the immutable specification for the task.
///
/// \return The immutable specification for the task.
const TaskSpecification &GetTaskSpecification() const;
/// Set the task's execution dependencies.
///
/// \param dependencies The value to set the execution dependencies to.
void SetExecutionDependencies(const std::vector<ObjectID> &dependencies);
/// Increment the number of times this task has been forwarded.
void IncrementNumForwards();
/// Get the task's object dependencies. This comprises the immutable task
/// arguments and the mutable execution dependencies.
///
/// \return The object dependencies.
const std::vector<ObjectID> &GetDependencies() const;
/// Update the dynamic/mutable information for this task.
/// \param task Task structure with updated dynamic information.
void CopyTaskExecutionSpec(const Task &task);
private:
void ComputeDependencies();
/// Task execution specification, consisting of all dynamic/mutable
/// information about this task determined at execution time..
TaskExecutionSpecification task_execution_spec_;
/// Task specification object, consisting of immutable information about this
/// task determined at submission time. Includes resource demand, object
/// dependencies, etc.
TaskSpecification task_spec_;
/// A cached copy of the task's object dependencies, including arguments from
/// the TaskSpecification and execution dependencies from the
/// TaskExecutionSpecification.
std::vector<ObjectID> dependencies_;
};
} // namespace raylet
} // namespace ray
#endif // RAY_RAYLET_TASK_H
| 34.046296 | 79 | 0.735926 | [
"object",
"vector"
] |
36667744fc22eea7be029621b8cbf8a177b10628 | 711 | h | C | src/controller/menu.h | dgolbourn/Metallic-Crow | 0f073312c67d3f0542cc40f23e94a018bd5e52c5 | [
"MIT"
] | null | null | null | src/controller/menu.h | dgolbourn/Metallic-Crow | 0f073312c67d3f0542cc40f23e94a018bd5e52c5 | [
"MIT"
] | null | null | null | src/controller/menu.h | dgolbourn/Metallic-Crow | 0f073312c67d3f0542cc40f23e94a018bd5e52c5 | [
"MIT"
] | null | null | null | #ifndef MENU_H_
#define MENU_H_
#include "lua_stack.h"
#include "window.h"
#include <memory>
#include <command.h>
#include <vector>
#include "boost/filesystem.hpp"
namespace game
{
class Menu
{
public:
Menu() = default;
Menu(lua::Stack& lua, display::Window& window, boost::filesystem::path const& path);
auto Add(int index, event::Command const& command) -> void;
auto Previous() -> void;
auto Next() -> void;
auto Select() -> void;
auto Render() -> void;
typedef std::pair<std::string, bool> Option;
typedef std::vector<Option> Options;
auto operator()(Options const& options) -> void;
auto operator[](int index) -> void;
private:
class Impl;
std::shared_ptr<Impl> impl_;
};
}
#endif | 23.7 | 86 | 0.684951 | [
"render",
"vector"
] |
36675c7c89a12f6c39511cc9704f2012d860e29e | 1,361 | c | C | d/lingzhou/jiangjungate.c | afeizh/mud | 3a605483a38dd215e477d340c3f12387b9372fbe | [
"MIT"
] | 69 | 2018-03-08T18:24:44.000Z | 2022-02-24T13:43:53.000Z | d/lingzhou/jiangjungate.c | afeizh/mud | 3a605483a38dd215e477d340c3f12387b9372fbe | [
"MIT"
] | 3 | 2019-04-24T12:21:19.000Z | 2021-03-28T23:34:58.000Z | d/lingzhou/jiangjungate.c | afeizh/mud | 3a605483a38dd215e477d340c3f12387b9372fbe | [
"MIT"
] | 33 | 2017-12-23T05:06:58.000Z | 2021-08-16T02:42:59.000Z | // Room: /lingzhou/jiangjungate.c
// Java. Sep 21 1998
#include <room.h>
inherit ROOM;
void create()
{
set("short", "大将军府");
set("long", @LONG
这里是征东大将军赫连铁树的府第,在东大街的正中,对面就是衙
门。一色高檐大屋,两个校尉看上去彪悍骁勇,此刻正神气活现的挎着
弯刀守在门前。
LONG );
set("exits", ([
"north" : __DIR__"dongdajie",
"south" : __DIR__"jiangjunyuan",
]));
set("objects", ([
__DIR__"npc/xiaowei" : 2,
]));
setup();
create_door("south" , "油木大门", "north" , DOOR_CLOSED);
}
int valid_leave(object me, string dir)
{
// int i;
object wei;
wei = present("xiao wei", environment(me));
if (dir != "south" || ! objectp(wei) || ! living(wei))
return ::valid_leave(me, dir);
if (me->query("weiwang") >= 10000)
{
message_vision("$N笑道:“" + RANK_D->query_respect(me) +
",请进,请进!这就去让人通报。”\n", wei, me);
return ::valid_leave(me, dir);
}
if (me->query("special_skill/trick"))
{
message_vision("$N看见$n走了过来,刚想拦住,"
"却听$n一声断喝:“散开!”\n"
"不由得吓了一跳,讪讪的不敢说话。\n", wei, me);
return ::valid_leave(me, dir);
}
return notify_fail("校尉上前挡住你,朗声说道:这位" +
RANK_D->query_respect(me) + "请回吧。老爷不见客。\n");
}
| 25.679245 | 71 | 0.49155 | [
"object"
] |
36695acd768388771446aa33171acf0c2d193a61 | 11,013 | h | C | released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/gui/zobject3dscan.h | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | 1 | 2021-12-27T19:14:03.000Z | 2021-12-27T19:14:03.000Z | released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/gui/zobject3dscan.h | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | 1 | 2016-12-03T05:33:13.000Z | 2016-12-03T05:33:13.000Z | released_plugins/v3d_plugins/neurontracing_neutube/src_neutube/neurolabi/gui/zobject3dscan.h | zzhmark/vaa3d_tools | 3ca418add85a59ac7e805d55a600b78330d7e53d | [
"MIT"
] | null | null | null | #ifndef ZOBJECT3DSCAN_H
#define ZOBJECT3DSCAN_H
#include <vector>
#include <string>
#include <set>
#include <map>
#include <utility>
#include "zqtheader.h"
#include "c_stack.h"
#include "zcuboid.h"
#include "zstackdrawable.h"
#include "tz_cuboid_i.h"
#include "zhistogram.h"
#include "zvoxel.h"
class ZObject3d;
class ZGraph;
class ZObject3dStripe {
public:
ZObject3dStripe() : m_y(0), m_z(0), m_isCanonized(true) {
}
inline int getY() const { return m_y; }
inline int getZ() const { return m_z; }
int getMinX() const;
int getMaxX() const;
inline size_t getSize() const { return m_segmentArray.size() / 2; }
inline int getSegmentNumber() const { return getSize(); }
int getVoxelNumber() const;
inline void setY(int y) { m_y = y; }
inline void setZ(int z) { m_z = z; }
void addSegment(int x1, int x2, bool canonizing = true);
const int* getSegment(size_t index) const;
int getSegmentStart(size_t index) const;
int getSegmentEnd(size_t index) const;
void write(FILE *fp) const;
void read(FILE *fp);
void drawStack(Stack *stack, int v, const int *offset = NULL) const;
void drawStack(Stack *stack, uint8_t red, uint8_t green, uint8_t blue,
const int *offset = NULL) const;
/*!
* \brief Count the overlap area between an object and a stack
*
* \param stack Input stack. It's foreground is defined as any pixel with
* intensity > 0.
* \param offset Offset of the object.
* \return The number of voxels overlapped.
*/
size_t countForegroundOverlap(Stack *stack, const int *offset = NULL) const;
inline bool isEmpty() const { return m_segmentArray.empty(); }
inline bool isCanonized() const { return isEmpty() || m_isCanonized; }
void sort();
void canonize();
bool unify(const ZObject3dStripe &stripe, bool canonizing = true);
void print() const;
void downsample(int xintv);
void downsampleMax(int xintv);
void clearSegment();
void translate(int dx, int dy, int dz);
/*!
* \brief Add z value
*
* Basically it is the same as translate(0, 0, \a dz);
*/
void addZ(int dz);
bool isCanonizedActually();
/*!
* \brief Test if two stripe are the same with respect to internal representation
*/
bool equalsLiterally(const ZObject3dStripe &stripe) const;
void dilate();
inline void setCanonized(bool canonized) { m_isCanonized = canonized; }
private:
std::vector<int> m_segmentArray;
int m_y;
int m_z;
bool m_isCanonized;
};
//Scan-line representation of a 3D object
class ZObject3dScan : public ZStackDrawable
{
public:
ZObject3dScan();
virtual ~ZObject3dScan();
enum EComponent {
STRIPE_INDEX_MAP, INDEX_SEGMENT_MAP, ACCUMULATED_STRIPE_NUMBER,
ALL_COMPONENT
};
bool isDeprecated(EComponent comp) const;
void deprecate(EComponent comp);
void deprecateDependent(EComponent comp);
void clear();
ZObject3d* toObject3d() const;
bool isEmpty() const;
size_t getStripeNumber() const;
size_t getVoxelNumber() const;
/*!
* \brief Get voxel number at a certain slice
* \param z The slice position.
*/
size_t getVoxelNumber(int z) const;
/*!
* \brief Get the voxel number on each slice
* \return The ith element is the #voxel at slice i.
*/
std::vector<size_t> getSlicewiseVoxelNumber() const;
ZObject3dStripe getStripe(size_t index) const;
/*
const int* getFirstStripe() const;
static int getY(const int *stripe);
static int getZ(const int *stripe);
//return number of scan lines
static int getStripeSize(const int *stripe);
static int* getSegment(const int *stripe);
static void setStripeSize(int *stripe, int size);
const int* getLastStripe() const;
int* getLastStripe();
*/
void addStripe(int z, int y, bool canonizing = true);
void addSegment(int x1, int x2, bool canonizing = true);
void addSegment(int z, int y, int x1, int x2, bool canonizing = true);
void addStripe(const ZObject3dStripe &stripe, bool canonizing = true);
//Turn a binary stack into scanlines
void loadStack(const Stack *stack);
void print() const;
void save(const std::string &filePath) const;
bool load(const std::string &filePath);
/*!
* \brief Import a dvid object
*
* byte Payload descriptor:
Bit 0 (LSB) - 8-bit grayscale
Bit 1 - 16-bit grayscale
Bit 2 - 16-bit normal
...
uint8 Number of dimensions
uint8 Dimension of run (typically 0 = X)
byte Reserved (to be used later)
uint32 # Voxels [TODO. 0 for now]
uint32 # Spans
Repeating unit of:
int32 Coordinate of run start (dimension 0)
int32 Coordinate of run start (dimension 1)
int32 Coordinate of run start (dimension 2)
...
int32 Length of run
bytes Optional payload dependent on first byte descriptor
*/
bool importDvidObject(const std::string &filePath);
/*!
* \brief Import object from a byte array
*/
bool importDvidObject(const char *byteArray, size_t byteNumber);
template<class T>
int scanArray(const T *array, int x, int y, int z, int width);
void drawStack(Stack *stack, int v, const int *offset = NULL) const;
void drawStack(Stack *stack, uint8_t red, uint8_t green, uint8_t blue,
const int *offset = NULL) const;
void labelStack(Stack *stack, int startLabel, const int *offset = NULL);
/*!
* \brief Count overlap between the object and a stack
*
* Count the overlap between the object and \a stack. Any voxel in the object
* has postive value in \a stack is counted.
*
* \param offset The offset of the object to \a stack if it is not NULL.
* \return Number of voxels in the overlapping region. It returns 0 if \a stack
* is NULL.
*/
size_t countForegroundOverlap(Stack *stack, const int *offset = NULL);
//Sort the stripes in the ascending order
// s1 < s2 if
// z(s1) < z(s2) or
// z(s1) == z(s2) and y(s1) < y(s2)
void sort();
void canonize();
void unify(const ZObject3dScan &obj);
void concat(const ZObject3dScan &obj);
void downsample(int xintv, int yintv, int zintv);
void downsampleMax(int xintv, int yintv, int zintv);
Stack* toStack(int *offset = NULL) const;
ZCuboid getBoundBox() const;
void getBoundBox(Cuboid_I *box) const;
template<class T>
static std::map<int, ZObject3dScan*>* extractAllObject(
const T *array, int width, int height, int depth, int startPlane,
std::map<int, ZObject3dScan*> *bodySet);
ZGraph* buildConnectionGraph();
const std::vector<size_t> &getStripeNumberAccumulation() const;
const std::map<std::pair<int, int>, size_t>& getStripeMap() const;
std::vector<size_t> getConnectedObjectSize();
std::vector<ZObject3dScan> getConnectedComponent();
inline bool isCanonized() const { return isEmpty() || m_isCanonized; }
inline void setCanonized(bool canonized) { m_isCanonized = canonized; }
const std::map<size_t, std::pair<size_t, size_t> >&
getIndexSegmentMap() const;
bool getSegment(size_t index, int *z, int *y, int *x1, int *x2);
size_t getSegmentNumber();
void translate(int dx, int dy, int dz);
/*!
* \brief Add z value
*
* Basically it is the same as translate(0, 0, \a dz);
*/
void addZ(int dz);
bool isCanonizedActually();
void duplicateAcrossZ(int depth);
ZObject3dScan getSlice(int z) const;
ZObject3dScan getSlice(int minZ, int maxZ) const;
virtual void display(QPainter &painter, int z = 0, Display_Style option = NORMAL)
const;
virtual const std::string& className() const;
void dilate();
ZPoint getCentroid() const;
/*!
* \brief Get the single voxel representing the object
*
* \return A voxel on the object. It returns (-1, -1, -1) if the object is
* empty.
*/
ZVoxel getMarker() const;
ZHistogram getRadialHistogram(int z) const;
ZObject3dScan makeZProjection() const;
ZObject3dScan makeZProjection(int minZ, int maxZ);
/*!
* \brief Get minimal Z
*
* \return The minimal Z value of the object. If the object is empty,
* it returns 0.
*/
int getMinZ() const;
/*!
* \brief Get maximal Z
*
* \return The maximal Z value of the object. If the object is empty,
* it returns 0.
*/
int getMaxZ() const;
/*!
* \brief Test if two objects are the same with respect to internal representation
*/
bool equalsLiterally(const ZObject3dScan &obj) const;
/*!
* \brief Get the complement of the object
*
* The complement object is defined as the background of the bound box painted
* with the original object.
*/
ZObject3dScan getComplementObject();
/*!
* \brief Find all holes as a single object.
* \return An object composed of all holes of the original object.
*/
ZObject3dScan findHoleObject();
/*!
* \brief Find all holes as a single object
* \return An array of objects, each representing a hole.
*/
std::vector<ZObject3dScan> findHoleObjectArray();
/*!
* \brief Fill the holes of the object
*/
void fillHole();
private:
std::vector<ZObject3dStripe> m_stripeArray;
/*
int m_stripeNumber;
std::vector<int> m_sripeSize;
*/
mutable std::vector<size_t> m_accNumberArray;
mutable std::map<std::pair<int, int>, size_t> m_stripeMap;
mutable std::map<size_t, std::pair<size_t, size_t> > m_indexSegmentMap;
bool m_isCanonized;
//mutable int *m_lastStripe;
};
template<class T>
int ZObject3dScan::scanArray(const T *array, int x, int y, int z, int width)
{
if (array == NULL) {
return 0;
}
if (x < 0 || x >= width) {
return 0;
}
int length = 0;
T v = array[x];
if (isEmpty()) {
addStripe(z, y);
} else {
if (m_stripeArray.back().getY() != y || m_stripeArray.back().getZ() != z) {
addStripe(z, y);
}
}
while (array[x + length] == v) {
++length;
if (x + length >= width) {
break;
}
}
addSegment(x, x + length - 1, false);
return length;
}
template<class T>
std::map<int, ZObject3dScan*>* ZObject3dScan::extractAllObject(
const T *array, int width, int height, int depth, int startPlane,
std::map<int, ZObject3dScan*> *bodySet)
{
if (bodySet == NULL) {
bodySet = new std::map<int, ZObject3dScan*>;
}
ZObject3dScan *obj = NULL;
for (int z = 0; z < depth; ++z) {
for (int y = 0; y < height; ++y) {
int x = 0;
while (x < width) {
int v = array[x];
std::map<int, ZObject3dScan*>::iterator iter = bodySet->find(v);
if (iter == bodySet->end()) {
obj = new ZObject3dScan;
//(*bodySet)[v] = obj;
bodySet->insert(std::map<int, ZObject3dScan*>::value_type(v, obj));
} else {
obj = iter->second;
}
int length = obj->scanArray(array, x, y, z + startPlane, width);
x += length;
}
array += width;
}
}
return bodySet;
}
#endif // ZOBJECT3DSCAN_H
| 26.730583 | 84 | 0.654136 | [
"object",
"vector",
"3d"
] |
3669d3b6ea0b7082eb2dec53b04283522057a49b | 12,449 | c | C | ESMF/src/Infrastructure/Mesh/src/Zoltan/zoltan_timer.c | joeylamcy/gchp | 0e1676300fc91000ecb43539cabf1f342d718fb3 | [
"NCSA",
"Apache-2.0",
"MIT"
] | 1 | 2018-07-05T16:48:58.000Z | 2018-07-05T16:48:58.000Z | ESMF/src/Infrastructure/Mesh/src/Zoltan/zoltan_timer.c | joeylamcy/gchp | 0e1676300fc91000ecb43539cabf1f342d718fb3 | [
"NCSA",
"Apache-2.0",
"MIT"
] | 1 | 2022-03-04T16:12:02.000Z | 2022-03-04T16:12:02.000Z | ESMF/src/Infrastructure/Mesh/src/Zoltan/zoltan_timer.c | joeylamcy/gchp | 0e1676300fc91000ecb43539cabf1f342d718fb3 | [
"NCSA",
"Apache-2.0",
"MIT"
] | null | null | null | /*****************************************************************************
* Zoltan Library for Parallel Applications *
* Copyright (c) 2000,2001,2002, Sandia National Laboratories. *
* This software is distributed under the GNU Lesser General Public License. *
* For more info, see the README file in the top-level Zoltan directory. *
*****************************************************************************/
/*****************************************************************************
* CVS File Information :
* $RCSfile: zoltan_timer.c,v $
* $Author: dneckels $
* $Date: 2007/11/28 16:13:54 $
* Revision: 1.11 $
****************************************************************************/
#include "zoltan_timer.h"
#include "zoltan_types.h"
#include "zoltan_util.h"
#include "zoltan_mem.h"
#ifdef VAMPIR
#include <VT.h>
#endif
#ifdef __cplusplus
/* if C++, define the rest of this header file as extern C */
extern "C" {
#endif
/****************************************************************************/
/*
* Functions that implement a Timer "class," creating a Timer object
* with start, stop and print functions.
*
* This code was designed to be a stand-alone utility, relying only
* on Zoltan_Time, Zoltan error codes, Zoltan utilities, and libzoltan_mem.a.
* Some rearranging of the Zoltan_Time files is necessary to truly make
* this utility a standalone one.
*/
/****************************************************************************/
/* Number of timers initially in Timer object. */
#define INITLENGTH 30
/* Length of character strings naming each timer. */
/* If you change this constant, change the string format */
/* in Zoltan_Timer_Print, too. */
#define MAXNAMELEN 23
/* Flag indicating whether a timer is in use. */
#define INUSE 1
/* Flag indicating whether a timer is running. */
#define RUNNING 2
#define FATALERROR(yo, str) \
{ \
int proc; \
MPI_Comm_rank(MPI_COMM_WORLD, &proc); \
ZOLTAN_PRINT_ERROR(proc, yo, str); \
return ZOLTAN_FATAL; \
}
/* Macro to ensure that a Timer object is non-NULL */
#define TESTTIMER(zt, yo) \
if ((zt) == NULL) FATALERROR(yo, "NULL Zoltan_Timer")
/* Macro to ensure that a given timer index is valid. */
#define TESTINDEX(zt, ts_idx, yo) \
if ((ts_idx) >= (zt)->NextTimeStruct) FATALERROR(yo, "Invalid Timer Index")
/****************************************************************************/
/* Structure that implements an individual timer. */
typedef struct TimeStruct {
double Start_Time; /* Most recent start time;
set by Zoltan_Timer_Start */
double Stop_Time; /* Most recent end time;
set by Zoltan_Timer_Stop */
char Start_File[MAXNAMELEN+1]; /* Filename for most recent Start */
char Stop_File[MAXNAMELEN+1]; /* Filename for most recent Stop */
int Start_Line; /* Line # in Start_File for most recent Start */
int Stop_Line; /* Line # in Stop_File for most recent Stop */
double My_Tot_Time; /* Sum of stop_time-start_time over all invocations
of this timer */
int Use_Barrier; /* Flag indicating whether to perform a barrier
operation before starting the timer. */
int Status; /* Flag indicating status of TimeStruct:
> 0 --> In Use
> 2 --> Running */
char Name[MAXNAMELEN+1];/* String associated (and printed) with timer info */
#ifdef VAMPIR
int vt_handle; /* state handle for vampir traces */
#endif
} ZTIMER_TS;
/* Timer object consisting of many related timers.
* Applications access this structure. */
typedef struct Zoltan_Timer {
int Timer_Flag; /* Zoltan Timer_Flag flag passed to Zoltan_Time */
int Length; /* # of entries allocated in Times */
int NextTimeStruct; /* Index of next unused TimeStruct */
ZTIMER_TS *Times; /* Array of actual timing data -- individual timers */
} ZTIMER;
/****************************************************************************/
ZTIMER *Zoltan_Timer_Copy(ZTIMER *from)
{
ZTIMER *to = NULL;
Zoltan_Timer_Copy_To(&to, from);
return to;
}
int Zoltan_Timer_Copy_To(ZTIMER **to, ZTIMER *from)
{
ZTIMER *toptr = NULL;
if (!to){
return ZOLTAN_FATAL;
}
if (*to){
Zoltan_Timer_Destroy(to);
}
if (from){
*to = (ZTIMER *)ZOLTAN_MALLOC(sizeof(ZTIMER));
toptr = *to;
toptr->Timer_Flag = from->Timer_Flag;
toptr->Length = from->Length;
toptr->NextTimeStruct = from->NextTimeStruct;
if (toptr->Length > 0){
toptr->Times = (ZTIMER_TS *)ZOLTAN_MALLOC(sizeof(ZTIMER_TS) * toptr->Length);
memcpy(toptr->Times, from->Times, sizeof(ZTIMER_TS) * toptr->Length);
}
else{
toptr->Times = NULL;
}
}
return ZOLTAN_OK;
}
/****************************************************************************/
ZTIMER *Zoltan_Timer_Create(
int timer_flag
)
{
/* Allocates a Timer object for the application; returns a pointer to it.
* Does not start any timers.
*/
ZTIMER *zt;
int i;
zt = (ZTIMER *) ZOLTAN_MALLOC(sizeof(ZTIMER));
zt->Times = (ZTIMER_TS *) ZOLTAN_MALLOC(sizeof(ZTIMER_TS) * INITLENGTH);
zt->Timer_Flag = timer_flag;
zt->Length = INITLENGTH;
zt->NextTimeStruct = 0;
for (i = 0; i < zt->Length; i++)
zt->Times[i].Status = 0;
return zt;
}
/****************************************************************************/
int Zoltan_Timer_Init(
ZTIMER *zt, /* Ptr to Timer object */
int use_barrier, /* Flag indicating whether to perform a
barrier operation before starting the
timer. */
const char *name /* Name of this timer */
)
{
/* Function that returns the index of the next available Timer timer. */
int ret;
static const char *yo = "Zoltan_Timer_Init";
TESTTIMER(zt, yo);
ret = zt->NextTimeStruct++;
if (ret >= zt->Length) {
/* Realloc -- need more individual timers */
zt->Length += INITLENGTH;
zt->Times = (ZTIMER_TS *) ZOLTAN_REALLOC(zt->Times,
zt->Length * sizeof(ZTIMER_TS));
}
Zoltan_Timer_Reset(zt, ret, use_barrier, name);
#ifdef VAMPIR
if (VT_funcdef(name, VT_NOCLASS, &((zt->Times[ret]).vt_handle)) != VT_OK)
FATALERROR(yo, "VT_funcdef failed.");
#endif
return ret;
}
/****************************************************************************/
int Zoltan_Timer_Reset(
ZTIMER *zt,
int ts_idx, /* Index of the timer to reset */
int use_barrier, /* Flag indicating whether to perform a
barrier operation before starting the
timer. */
const char *name /* Name of this timer */
)
{
/* Initialize a timer for INUSE; reset its values to zero. */
static const char *yo = "Zoltan_Timer_Reset";
ZTIMER_TS *ts;
TESTTIMER(zt, yo);
TESTINDEX(zt, ts_idx, yo);
ts = &(zt->Times[ts_idx]);
ts->Status = INUSE;
ts->Start_Time = 0.;
ts->Stop_Time = 0.;
ts->My_Tot_Time = 0.;
ts->Use_Barrier = use_barrier;
strncpy(ts->Name, name, MAXNAMELEN);
ts->Name[MAXNAMELEN] = '\0';
ts->Start_File[0] = '\0';
ts->Start_Line = -1;
ts->Stop_File[0] = '\0';
ts->Stop_Line = -1;
return ZOLTAN_OK;
}
/****************************************************************************/
int Zoltan_Timer_ChangeFlag(
ZTIMER *zt,
int timer
)
{
static const char *yo = "Zoltan_Timer_ChangeFlag";
TESTTIMER(zt, yo);
zt->Timer_Flag = timer;
return ZOLTAN_OK;
}
/****************************************************************************/
int Zoltan_Timer_Start(
ZTIMER *zt, /* Ptr to Timer object */
int ts_idx, /* Index of the timer to use */
MPI_Comm comm, /* Communicator to use for synchronization,
if requested */
const char *filename, /* Filename of file calling the Start */
int lineno /* Line number where Start was called */
)
{
ZTIMER_TS *ts;
static const char *yo = "Zoltan_Timer_Start";
TESTTIMER(zt, yo);
TESTINDEX(zt, ts_idx, yo);
ts = &(zt->Times[ts_idx]);
if (ts->Status > 2) {
char msg[256];
sprintf(msg,
"Cannot start timer %d at %s:%d; timer already running from %s:%d.",
ts_idx, filename, lineno, ts->Start_File, ts->Start_Line);
FATALERROR(yo, msg)
}
ts->Status += RUNNING;
strncpy(ts->Start_File, filename, MAXNAMELEN);
ts->Start_Line = lineno;
if (ts->Use_Barrier)
MPI_Barrier(comm);
ts->Start_Time = Zoltan_Time(zt->Timer_Flag);
#ifdef VAMPIR
if (VT_begin(ts->vt_handle) != VT_OK)
FATALERROR(yo, "VT_begin failed.");
#endif
return ZOLTAN_OK;
}
/****************************************************************************/
int Zoltan_Timer_Stop(
ZTIMER *zt, /* Ptr to Timer object */
int ts_idx, /* Index of the timer to use */
MPI_Comm comm, /* Communicator to use for synchronization,
if requested */
const char *filename, /* Filename of file calling the Stop */
int lineno /* Line number where Stop was called */
)
{
/* Function to stop a timer and accrue its information */
ZTIMER_TS *ts;
static const char *yo = "Zoltan_Timer_Stop";
double my_time;
TESTTIMER(zt, yo);
TESTINDEX(zt, ts_idx, yo);
ts = &(zt->Times[ts_idx]);
if (ts->Status < 2) {
if (ts->Stop_Line == -1)
FATALERROR(yo, "Cannot stop timer; timer never started.")
else {
char msg[256];
sprintf(msg,
"Cannot stop timer %d at %s:%d; "
"timer already stopped from %s:%d.",
ts_idx, filename, lineno, ts->Stop_File, ts->Stop_Line);
FATALERROR(yo, msg)
}
}
#ifdef VAMPIR
if (VT_end(ts->vt_handle) != VT_OK)
FATALERROR(yo, "VT_end failed.");
#endif
if (ts->Use_Barrier)
MPI_Barrier(comm);
ts->Stop_Time = Zoltan_Time(zt->Timer_Flag);
ts->Status -= RUNNING;
ts->Stop_Line = lineno;
strncpy(ts->Stop_File, filename, MAXNAMELEN);
my_time = ts->Stop_Time - ts->Start_Time;
ts->My_Tot_Time += my_time;
return ZOLTAN_OK;
}
/****************************************************************************/
int Zoltan_Timer_Print(
ZTIMER *zt,
int ts_idx,
int proc, /* Rank of the processor (in comm) that should print the data. */
MPI_Comm comm,
FILE *fp
)
{
/* Accrues a single timer's values across a communicator and prints
* its information. This function must be called by all processors
* within the communicator.
*/
static const char *yo = "Zoltan_Timer_Print";
ZTIMER_TS *ts;
int my_proc, nproc;
double max_time;
double min_time;
double sum_time;
TESTTIMER(zt, yo);
TESTINDEX(zt, ts_idx, yo);
ts = &(zt->Times[ts_idx]);
MPI_Allreduce(&(ts->My_Tot_Time), &max_time, 1, MPI_DOUBLE, MPI_MAX, comm);
MPI_Allreduce(&(ts->My_Tot_Time), &min_time, 1, MPI_DOUBLE, MPI_MIN, comm);
MPI_Allreduce(&(ts->My_Tot_Time), &sum_time, 1, MPI_DOUBLE, MPI_SUM, comm);
MPI_Comm_rank(comm, &my_proc);
MPI_Comm_size(comm, &nproc);
if (proc == my_proc)
fprintf(fp,
"%3d ZOLTAN_TIMER %3d %23s: MyTime %7.4lf "
"MaxTime %7.4lf MinTime %7.4lf AvgTime %7.4lf\n",
proc, ts_idx, ts->Name, ts->My_Tot_Time,
max_time, min_time, sum_time/nproc);
return ZOLTAN_OK;
}
/****************************************************************************/
int Zoltan_Timer_PrintAll(
ZTIMER *zt,
int proc, /* Rank of the processor (in comm) that should print the data. */
MPI_Comm comm,
FILE *fp
)
{
/* Function to print all timer information */
static const char *yo = "Zoltan_Timer_PrintAll";
int i, ierr = ZOLTAN_OK;
TESTTIMER(zt, yo);
for (i = 0; i < zt->NextTimeStruct; i++)
if ((ierr = Zoltan_Timer_Print(zt, i, proc, comm, fp)) != ZOLTAN_OK)
break;
return ierr;
}
/****************************************************************************/
void Zoltan_Timer_Destroy(
ZTIMER **zt
)
{
/* Destroy a Timer object */
if (*zt != NULL) {
ZOLTAN_FREE(&((*zt)->Times));
ZOLTAN_FREE(zt);
}
}
/****************************************************************************/
#ifdef __cplusplus
} /* closing bracket for extern "C" */
#endif
| 29.640476 | 83 | 0.555466 | [
"object",
"3d"
] |
3669d90cd18502633bfaeebafc1ef0e1c1f90ea9 | 6,271 | h | C | flashlight/app/asr/criterion/Seq2SeqCriterion.h | massens/flashlight | a5877d6fe266c533349c78556b2971bb763adce6 | [
"BSD-3-Clause"
] | 1 | 2021-05-26T11:56:41.000Z | 2021-05-26T11:56:41.000Z | flashlight/app/asr/criterion/Seq2SeqCriterion.h | massens/flashlight | a5877d6fe266c533349c78556b2971bb763adce6 | [
"BSD-3-Clause"
] | null | null | null | flashlight/app/asr/criterion/Seq2SeqCriterion.h | massens/flashlight | a5877d6fe266c533349c78556b2971bb763adce6 | [
"BSD-3-Clause"
] | 1 | 2022-01-12T06:48:28.000Z | 2022-01-12T06:48:28.000Z | /*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
#pragma once
#include <memory>
#include "flashlight/app/asr/criterion/Defines.h"
#include "flashlight/app/asr/criterion/SequenceCriterion.h"
#include "flashlight/app/asr/criterion/attention/attention.h"
#include "flashlight/app/asr/criterion/attention/window.h"
#include "flashlight/ext/common/DistributedUtils.h"
namespace fl {
namespace app {
namespace asr {
struct Seq2SeqState {
fl::Variable alpha;
std::vector<fl::Variable> hidden;
fl::Variable summary;
int step;
int peakAttnPos;
bool isValid;
Seq2SeqState() : hidden(1), step(0), peakAttnPos(-1), isValid(false) {}
explicit Seq2SeqState(int nAttnRound)
: hidden(nAttnRound), step(0), peakAttnPos(-1), isValid(false) {}
};
typedef std::shared_ptr<Seq2SeqState> Seq2SeqStatePtr;
class Seq2SeqCriterion : public SequenceCriterion {
public:
struct CandidateHypo {
float score;
std::vector<int> path;
Seq2SeqState state;
explicit CandidateHypo() : score(0.0) {
path.resize(0);
}
CandidateHypo(float score_, std::vector<int> path_, Seq2SeqState state_)
: score(score_), path(path_), state(state_) {}
};
Seq2SeqCriterion(
int nClass,
int hiddenDim,
int eos,
int maxDecoderOutputLen,
const std::vector<std::shared_ptr<AttentionBase>>& attentions,
std::shared_ptr<WindowBase> window = nullptr,
bool trainWithWindow = false,
int pctTeacherForcing = 100,
double labelSmooth = 0.0,
bool inputFeeding = false,
std::string samplingStrategy = fl::app::asr::kRandSampling,
double gumbelTemperature = 1.0,
int nRnnLayer = 1,
int nAttnRound = 1,
float dropOut = 0.0);
std::vector<fl::Variable> forward(
const std::vector<fl::Variable>& inputs) override;
/* Next step predictions are based on the target at
* the previous time-step so this function should only
* be used for training purposes. */
std::pair<fl::Variable, fl::Variable> decoder(
const fl::Variable& input,
const fl::Variable& target);
std::pair<fl::Variable, fl::Variable> vectorizedDecoder(
const fl::Variable& input,
const fl::Variable& target);
af::array viterbiPath(const af::array& input) override;
std::pair<af::array, fl::Variable> viterbiPathBase(
const af::array& input,
bool saveAttn);
std::vector<CandidateHypo> beamSearch(
const af::array& input,
std::vector<Seq2SeqCriterion::CandidateHypo> beam,
int beamSize,
int maxLen);
std::vector<int> beamPath(const af::array& input, int beamSize = 10);
std::string prettyString() const override;
std::shared_ptr<fl::Embedding> embedding() const {
return std::static_pointer_cast<fl::Embedding>(module(0));
}
std::shared_ptr<fl::RNN> decodeRNN(int n) const {
return std::static_pointer_cast<fl::RNN>(module(n + 1));
}
std::shared_ptr<AttentionBase> attention(int n) const {
return std::static_pointer_cast<AttentionBase>(module(nAttnRound_ + n + 2));
}
std::shared_ptr<fl::Linear> linearOut() const {
return std::static_pointer_cast<fl::Linear>(module(nAttnRound_ + 1));
}
fl::Variable startEmbedding() const {
return params_.back();
}
std::pair<std::vector<std::vector<float>>, std::vector<Seq2SeqStatePtr>>
decodeBatchStep(
const fl::Variable& xEncoded,
std::vector<fl::Variable>& ys,
const std::vector<Seq2SeqState*>& inStates,
const int attentionThreshold = std::numeric_limits<int>::infinity(),
const float smoothingTemperature = 1.0) const;
std::pair<fl::Variable, Seq2SeqState> decodeStep(
const fl::Variable& xEncoded,
const fl::Variable& y,
const Seq2SeqState& instate) const;
void clearWindow() {
trainWithWindow_ = false;
window_ = nullptr;
}
void setSampling(std::string newSamplingStrategy, int newPctTeacherForcing) {
pctTeacherForcing_ = newPctTeacherForcing;
samplingStrategy_ = newSamplingStrategy;
setUseSequentialDecoder();
}
void setGumbelTemperature(double temperature) {
gumbelTemperature_ = temperature;
}
void setLabelSmooth(double labelSmooth) {
labelSmooth_ = labelSmooth;
}
private:
int eos_;
int maxDecoderOutputLen_;
std::shared_ptr<WindowBase> window_;
bool trainWithWindow_;
int pctTeacherForcing_;
bool useSequentialDecoder_;
double labelSmooth_;
bool inputFeeding_;
int nClass_;
std::string samplingStrategy_;
double gumbelTemperature_;
int nAttnRound_{1};
FL_SAVE_LOAD_WITH_BASE(
SequenceCriterion,
eos_,
maxDecoderOutputLen_,
window_,
trainWithWindow_,
pctTeacherForcing_,
useSequentialDecoder_,
labelSmooth_,
inputFeeding_,
nClass_,
fl::versioned(samplingStrategy_, 1),
fl::versioned(gumbelTemperature_, 2),
fl::versioned(nAttnRound_, 3))
Seq2SeqCriterion() = default;
void setUseSequentialDecoder();
};
fl::app::asr::Seq2SeqCriterion buildSeq2Seq(int numClasses, int eosIdx);
/* Decoder helpers */
struct Seq2SeqDecoderBuffer {
fl::Variable input;
Seq2SeqState dummyState;
std::vector<fl::Variable> ys;
std::vector<Seq2SeqState*> prevStates;
int attentionThreshold;
double smoothingTemperature;
Seq2SeqDecoderBuffer(
int nAttnRound,
int beamSize,
int attnThre,
int smootTemp)
: dummyState(nAttnRound),
attentionThreshold(attnThre),
smoothingTemperature(smootTemp) {
ys.reserve(beamSize);
prevStates.reserve(beamSize);
}
};
typedef std::shared_ptr<void> AMStatePtr;
typedef std::function<
std::pair<std::vector<std::vector<float>>, std::vector<AMStatePtr>>(
const float*,
const int,
const int,
const std::vector<int>&,
const std::vector<AMStatePtr>&,
int&)>
AMUpdateFunc;
AMUpdateFunc buildAmUpdateFunction(
std::shared_ptr<SequenceCriterion>& criterion);
} // namespace asr
} // namespace app
} // namespace fl
CEREAL_REGISTER_TYPE(fl::app::asr::Seq2SeqCriterion)
CEREAL_CLASS_VERSION(fl::app::asr::Seq2SeqCriterion, 3)
| 27.504386 | 80 | 0.694148 | [
"vector"
] |
3671182f26d48309fe4d33c410417199aac0cd5b | 3,354 | h | C | Modules/Filtering/FFT/include/itkVnlForwardFFTImageFilter.h | arobert01/ITK | 230d319fdeaa3877273fab5d409dd6c11f0a6874 | [
"Apache-2.0"
] | 945 | 2015-01-09T00:43:52.000Z | 2022-03-30T08:23:02.000Z | Modules/Filtering/FFT/include/itkVnlForwardFFTImageFilter.h | arobert01/ITK | 230d319fdeaa3877273fab5d409dd6c11f0a6874 | [
"Apache-2.0"
] | 2,354 | 2015-02-04T21:54:21.000Z | 2022-03-31T20:58:21.000Z | Modules/Filtering/FFT/include/itkVnlForwardFFTImageFilter.h | arobert01/ITK | 230d319fdeaa3877273fab5d409dd6c11f0a6874 | [
"Apache-2.0"
] | 566 | 2015-01-04T14:26:57.000Z | 2022-03-18T20:33:18.000Z | /*=========================================================================
*
* Copyright NumFOCUS
*
* 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.txt
*
* 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 "itkForwardFFTImageFilter.h"
#ifndef itkVnlForwardFFTImageFilter_h
# define itkVnlForwardFFTImageFilter_h
# include "vnl/algo/vnl_fft_base.h"
namespace itk
{
/**
*\class VnlForwardFFTImageFilter
*
* \brief VNL based forward Fast Fourier Transform.
*
* The input image size must be a multiple of combinations of 2s, 3s,
* and/or 5s in all dimensions (2, 3, and 5 should be the only prime
* factors of the image size along each dimension).
*
* \ingroup FourierTransform
*
* \sa ForwardFFTImageFilter
* \ingroup ITKFFT
*
*/
template <typename TInputImage,
typename TOutputImage = Image<std::complex<typename TInputImage::PixelType>, TInputImage::ImageDimension>>
class ITK_TEMPLATE_EXPORT VnlForwardFFTImageFilter : public ForwardFFTImageFilter<TInputImage, TOutputImage>
{
public:
ITK_DISALLOW_COPY_AND_MOVE(VnlForwardFFTImageFilter);
/** Standard class type aliases. */
using InputImageType = TInputImage;
using InputPixelType = typename InputImageType::PixelType;
using InputSizeType = typename InputImageType::SizeType;
using InputSizeValueType = typename InputImageType::SizeValueType;
using OutputImageType = TOutputImage;
using OutputPixelType = typename OutputImageType::PixelType;
using Self = VnlForwardFFTImageFilter;
using Superclass = ForwardFFTImageFilter<TInputImage, TOutputImage>;
using Pointer = SmartPointer<Self>;
using ConstPointer = SmartPointer<const Self>;
/** Method for creation through the object factory. */
itkNewMacro(Self);
/** Run-time type information (and related methods). */
itkTypeMacro(VnlForwardFFTImageFilter, ForwardFFTImageFilter);
/** Extract the dimensionality of the images. They are assumed to be
* the same. */
static constexpr unsigned int ImageDimension = TOutputImage::ImageDimension;
static constexpr unsigned int InputImageDimension = TInputImage::ImageDimension;
static constexpr unsigned int OutputImageDimension = TOutputImage::ImageDimension;
SizeValueType
GetSizeGreatestPrimeFactor() const override;
# ifdef ITK_USE_CONCEPT_CHECKING
// Begin concept checking
itkConceptMacro(ImageDimensionsMatchCheck, (Concept::SameDimension<InputImageDimension, OutputImageDimension>));
// End concept checking
# endif
protected:
VnlForwardFFTImageFilter() = default;
~VnlForwardFFTImageFilter() override = default;
void
GenerateData() override;
private:
using SignalVectorType = vnl_vector<std::complex<InputPixelType>>;
};
} // namespace itk
# ifndef ITK_MANUAL_INSTANTIATION
# include "itkVnlForwardFFTImageFilter.hxx"
# endif
#endif
| 33.54 | 116 | 0.733751 | [
"object",
"transform"
] |
36719c329f417da2bb218ae453d2df0e8d70e049 | 8,788 | c | C | src/FireFly/FireFlyGuess.c | xomachine/gabedit | 1f63b6675b8bffdda910012fec00b89630bcb4a2 | [
"MIT"
] | null | null | null | src/FireFly/FireFlyGuess.c | xomachine/gabedit | 1f63b6675b8bffdda910012fec00b89630bcb4a2 | [
"MIT"
] | null | null | null | src/FireFly/FireFlyGuess.c | xomachine/gabedit | 1f63b6675b8bffdda910012fec00b89630bcb4a2 | [
"MIT"
] | null | null | null | /* FireFlyGuess.c */
/**********************************************************************************************************
Copyright (c) 2002-2013 Abdul-Rahman Allouche. All rights reserved
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
documentation files (the Gabedit), 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 <stdlib.h>
#include <ctype.h>
#include <math.h>
#include <string.h>
#include "../../Config.h"
#include "../Common/Global.h"
#include "../FireFly/FireFlyTypes.h"
#include "../FireFly/FireFlyGlobal.h"
#include "../Utils/Utils.h"
#include "../Utils/UtilsInterface.h"
#include "../Utils/GabeditTextEdit.h"
#include "../Common/Windows.h"
#include "../Utils/Constants.h"
static GtkWidget *buttonPrintGuess = NULL;
static GtkWidget *buttonRotate = NULL;
static GtkWidget *guessFrame = NULL;
/*************************************************************************************************************/
static gchar* listGuessMethodView[] = { "Huckel", "Core" };
static gchar* listGuessMethodReal[] = { "NONE", "GUESS=HCORE" };
static guint numberOfGuessMethods = G_N_ELEMENTS (listGuessMethodView);
static gchar selectedGuessMethod[BSIZE]="NONE";
/*************************************************************************************************************/
void initFireFlyGuessFrame()
{
guessFrame = NULL;
}
/*************************************************************************************************************/
void setSensitiveFireFlyGuessFrame(gboolean sensitive)
{
if(!guessFrame) return;
gtk_widget_set_sensitive(guessFrame, sensitive);
}
/*************************************************************************************************************/
static void putFireFlyGuessOptionsInfoInTextEditor()
{
if(!GTK_TOGGLE_BUTTON (buttonPrintGuess)->active
&& !GTK_TOGGLE_BUTTON (buttonRotate)->active) return;
gabedit_text_insert (GABEDIT_TEXT(text), NULL, NULL, NULL, " ",-1);
gabedit_text_insert (GABEDIT_TEXT(text), NULL, &fireflyColorFore.keyWord, &fireflyColorBack.keyWord, "$GUESS",-1);
if(GTK_TOGGLE_BUTTON (buttonPrintGuess)->active)
gabedit_text_insert (GABEDIT_TEXT(text), NULL, NULL, NULL, " PRTMO=.TRUE.",-1);
if(GTK_TOGGLE_BUTTON (buttonRotate)->active)
gabedit_text_insert (GABEDIT_TEXT(text), NULL, NULL, NULL, " MIX=.TRUE.",-1);
gabedit_text_insert (GABEDIT_TEXT(text), NULL, NULL, NULL, " ",-1);
gabedit_text_insert (GABEDIT_TEXT(text), NULL, &fireflyColorFore.keyWord, &fireflyColorBack.keyWord, "$END\n",-1);
}
/************************************************************************************************************/
static void putFireFlyGuessMethodInfoInTextEditor()
{
if( strcmp(selectedGuessMethod,"NONE")==0 ) return;
gabedit_text_insert (GABEDIT_TEXT(text), NULL, NULL, NULL, " ",-1);
gabedit_text_insert (GABEDIT_TEXT(text), NULL, &fireflyColorFore.keyWord, &fireflyColorBack.keyWord, "$GUESS",-1);
gabedit_text_insert (GABEDIT_TEXT(text), NULL, NULL, NULL, " ",-1);
gabedit_text_insert (GABEDIT_TEXT(text), NULL, NULL, NULL, selectedGuessMethod,-1);
gabedit_text_insert (GABEDIT_TEXT(text), NULL, NULL, NULL, " ",-1);
gabedit_text_insert (GABEDIT_TEXT(text), NULL, &fireflyColorFore.keyWord, &fireflyColorBack.keyWord, "$END\n",-1);
}
/*************************************************************************************************************/
void putFireFlyGuessInfoInTextEditor()
{
putFireFlyGuessMethodInfoInTextEditor();
putFireFlyGuessOptionsInfoInTextEditor();
}
/************************************************************************************************************/
static void traitementGuessMethod (GtkComboBox *combobox, gpointer d)
{
GtkTreeIter iter;
gchar* data = NULL;
gchar* res = NULL;
gint i;
/* gchar* s;*/
if (gtk_combo_box_get_active_iter (combobox, &iter))
{
GtkTreeModel* model = gtk_combo_box_get_model(combobox);
gtk_tree_model_get (model, &iter, 0, &data, -1);
}
for(i=0;i<numberOfGuessMethods;i++)
{
if(strcmp((gchar*)data,listGuessMethodView[i])==0) res = listGuessMethodReal[i];
}
if(res) sprintf(selectedGuessMethod,"%s",res);
else sprintf(selectedGuessMethod,"MINI");
/* for(s=selectedGuessMethod;*s != 0;s++) *s = toupper(*s);*/
}
/********************************************************************************************************/
static GtkWidget *create_list_guessmethods()
{
GtkTreeIter iter;
GtkTreeStore *store;
GtkTreeModel *model;
GtkWidget *combobox;
GtkCellRenderer *renderer;
gint i;
GtkTreeIter iter0;
store = gtk_tree_store_new (1,G_TYPE_STRING);
for(i=0;i<numberOfGuessMethods;i++)
{
gtk_tree_store_append (store, &iter, NULL);
if(i==0) iter0 = iter;
gtk_tree_store_set (store, &iter, 0, listGuessMethodView[i], -1);
}
model = GTK_TREE_MODEL (store);
combobox = gtk_combo_box_new_with_model (model);
/*
gtk_combo_box_set_add_tearoffs (GTK_COMBO_BOX (combobox), TRUE);
*/
g_object_unref (model);
g_signal_connect (G_OBJECT(combobox), "changed", G_CALLBACK(traitementGuessMethod), NULL);
renderer = gtk_cell_renderer_text_new ();
gtk_cell_layout_pack_start (GTK_CELL_LAYOUT (combobox), renderer, TRUE);
gtk_cell_layout_set_attributes (GTK_CELL_LAYOUT (combobox), renderer, "text", 0, NULL);
gtk_combo_box_set_active_iter(GTK_COMBO_BOX (combobox), &iter0);
return combobox;
}
/************************************************************************************************************/
void createFireFlyGuessFrame(GtkWidget *win, GtkWidget *box)
{
GtkWidget* frame;
GtkWidget* vboxFrame;
GtkWidget* sep;
GtkWidget* combo = NULL;
gint l=0;
gint c=0;
gint ncases=1;
GtkWidget *table = gtk_table_new(4,3,FALSE);
buttonPrintGuess = NULL;
buttonRotate = NULL;
frame = gtk_frame_new (_("Mo Guess"));
guessFrame = frame;
gtk_widget_show (frame);
gtk_box_pack_start (GTK_BOX (box), frame, TRUE, TRUE, 3);
gtk_frame_set_label_align (GTK_FRAME (frame), 0.5, 0.5);
vboxFrame = gtk_vbox_new (FALSE, 3);
gtk_widget_show (vboxFrame);
gtk_container_add (GTK_CONTAINER (frame), vboxFrame);
gtk_box_pack_start (GTK_BOX (vboxFrame), table, TRUE, TRUE, 0);
/*------------------ Guess Method -----------------------------------------*/
l=0;
c = 0; ncases=1;
add_label_table(table,_("Initial Guess"),l,c);
c = 1; ncases=1;
add_label_table(table,":",l,c);
combo = create_list_guessmethods();
c = 2; ncases=1;
gtk_table_attach(GTK_TABLE(table),combo,c,c+ncases,l,l+1,
(GtkAttachOptions) (GTK_FILL | GTK_EXPAND),
(GtkAttachOptions) (GTK_FILL | GTK_SHRINK),
2,2);
/*------------------ separator -----------------------------------------*/
l++;
sep = gtk_hseparator_new ();;
c = 0; ncases=3;
gtk_table_attach(GTK_TABLE(table),sep,c,c+ncases,l,l+1,
(GtkAttachOptions) (GTK_FILL | GTK_EXPAND),
(GtkAttachOptions) (GTK_FILL | GTK_SHRINK),
2,2);
/*------------------ Print Orbs L ------------*/
l++;
c = 0; ncases=3;
buttonPrintGuess = gtk_check_button_new_with_label (_("Print the initial Guess"));
gtk_table_attach(GTK_TABLE(table),buttonPrintGuess,c,c+ncases,l,l+1,
(GtkAttachOptions) (GTK_FILL | GTK_EXPAND),
(GtkAttachOptions) (GTK_FILL | GTK_SHRINK),
2,2);
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (buttonPrintGuess), FALSE);
/*------------------ Mix ------------*/
l++;
c = 0; ncases=3;
buttonRotate = gtk_check_button_new_with_label (_("Rotate alpha and beta orbitals"));
gtk_table_attach(GTK_TABLE(table),buttonRotate,c,c+ncases,l,l+1,
(GtkAttachOptions) (GTK_FILL | GTK_EXPAND),
(GtkAttachOptions) (GTK_FILL | GTK_SHRINK),
2,2);
gtk_toggle_button_set_active (GTK_TOGGLE_BUTTON (buttonRotate), FALSE);
}
| 42.047847 | 122 | 0.612881 | [
"model"
] |
36724925ba18b67507fb8afac90ea43169f15a1b | 7,184 | h | C | src/beast/beast/module/core/containers/ElementComparator.h | vpaldev/vpal20 | 8bcebea3499b86559e244636a7285226a3ed6950 | [
"BSL-1.0"
] | 1 | 2020-03-20T00:21:26.000Z | 2020-03-20T00:21:26.000Z | src/beast/beast/module/core/containers/ElementComparator.h | vpaldev/vpal20 | 8bcebea3499b86559e244636a7285226a3ed6950 | [
"BSL-1.0"
] | null | null | null | src/beast/beast/module/core/containers/ElementComparator.h | vpaldev/vpal20 | 8bcebea3499b86559e244636a7285226a3ed6950 | [
"BSL-1.0"
] | 2 | 2016-07-16T05:24:05.000Z | 2020-03-20T00:21:34.000Z | //------------------------------------------------------------------------------
/*
Portions of this file are from Vpallab: https://github.com/vpallabs
Copyright (c) 2013 - 2014 - Vpallab.com.
Please visit http://www.vpallab.com/
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
Portions of this file are from JUCE.
Copyright (c) 2013 - Raw Material Software Ltd.
Please visit http://www.juce.com
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#ifndef BEAST_ELEMENTCOMPARATOR_H_INCLUDED
#define BEAST_ELEMENTCOMPARATOR_H_INCLUDED
namespace beast
{
#ifndef DOXYGEN
/** This is an internal helper class which converts a beast ElementComparator style
class (using a "compareElements" method) into a class that's compatible with
std::sort (i.e. using an operator() to compare the elements)
*/
template <typename ElementComparator>
struct SortFunctionConverter
{
SortFunctionConverter (ElementComparator& e) : comparator (e) {}
template <typename Type>
bool operator() (Type a, Type b) { return comparator.compareElements (a, b) < 0; }
private:
ElementComparator& comparator;
SortFunctionConverter& operator= (const SortFunctionConverter&);
};
#endif
//==============================================================================
/**
Sorts a range of elements in an array.
The comparator object that is passed-in must define a public method with the following
signature:
@code
int compareElements (ElementType first, ElementType second);
@endcode
..and this method must return:
- a value of < 0 if the first comes before the second
- a value of 0 if the two objects are equivalent
- a value of > 0 if the second comes before the first
To improve performance, the compareElements() method can be declared as static or const.
@param comparator an object which defines a compareElements() method
@param array the array to sort
@param firstElement the index of the first element of the range to be sorted
@param lastElement the index of the last element in the range that needs
sorting (this is inclusive)
@param retainOrderOfEquivalentItems if true, the order of items that the
comparator deems the same will be maintained - this will be
a slower algorithm than if they are allowed to be moved around.
@see sortArrayRetainingOrder
*/
template <class ElementType, class ElementComparator>
static void sortArray (ElementComparator& comparator,
ElementType* const array,
int firstElement,
int lastElement,
const bool retainOrderOfEquivalentItems)
{
SortFunctionConverter<ElementComparator> converter (comparator);
if (retainOrderOfEquivalentItems)
std::stable_sort (array + firstElement, array + lastElement + 1, converter);
else
std::sort (array + firstElement, array + lastElement + 1, converter);
}
//==============================================================================
/**
Searches a sorted array of elements, looking for the index at which a specified value
should be inserted for it to be in the correct order.
The comparator object that is passed-in must define a public method with the following
signature:
@code
int compareElements (ElementType first, ElementType second);
@endcode
..and this method must return:
- a value of < 0 if the first comes before the second
- a value of 0 if the two objects are equivalent
- a value of > 0 if the second comes before the first
To improve performance, the compareElements() method can be declared as static or const.
@param comparator an object which defines a compareElements() method
@param array the array to search
@param newElement the value that is going to be inserted
@param firstElement the index of the first element to search
@param lastElement the index of the last element in the range (this is non-inclusive)
*/
template <class ElementType, class ElementComparator>
static int findInsertIndexInSortedArray (ElementComparator& comparator,
ElementType* const array,
const ElementType newElement,
int firstElement,
int lastElement)
{
bassert (firstElement <= lastElement);
(void) comparator; // if you pass in an object with a static compareElements() method, this
// avoids getting warning messages about the parameter being unused
while (firstElement < lastElement)
{
if (comparator.compareElements (newElement, array [firstElement]) == 0)
{
++firstElement;
break;
}
else
{
const int halfway = (firstElement + lastElement) >> 1;
if (halfway == firstElement)
{
if (comparator.compareElements (newElement, array [halfway]) >= 0)
++firstElement;
break;
}
else if (comparator.compareElements (newElement, array [halfway]) >= 0)
{
firstElement = halfway;
}
else
{
lastElement = halfway;
}
}
}
return firstElement;
}
//==============================================================================
/**
A simple ElementComparator class that can be used to sort an array of
objects that support the '<' operator.
This will work for primitive types and objects that implement operator<().
Example: @code
Array <int> myArray;
DefaultElementComparator<int> sorter;
myArray.sort (sorter);
@endcode
@see ElementComparator
*/
template <class ElementType>
class DefaultElementComparator
{
private:
typedef ElementType ParameterType;
public:
static int compareElements (ParameterType first, ParameterType second)
{
return (first < second) ? -1 : ((second < first) ? 1 : 0);
}
};
} // beast
#endif
| 36.100503 | 96 | 0.617622 | [
"object"
] |
3673aeded8bba40c9b6277c929772d3847bb41d4 | 1,638 | h | C | igl/mat_min.h | aviadtzemah/animation2 | 9a3f980fbe27672fe71f8f61f73b5713f2af5089 | [
"Apache-2.0"
] | 2,392 | 2016-12-17T14:14:12.000Z | 2022-03-30T19:40:40.000Z | igl/mat_min.h | aviadtzemah/animation2 | 9a3f980fbe27672fe71f8f61f73b5713f2af5089 | [
"Apache-2.0"
] | 106 | 2018-04-19T17:47:31.000Z | 2022-03-01T19:44:11.000Z | igl/mat_min.h | aviadtzemah/animation2 | 9a3f980fbe27672fe71f8f61f73b5713f2af5089 | [
"Apache-2.0"
] | 184 | 2017-11-15T09:55:37.000Z | 2022-02-21T16:30:46.000Z | // This file is part of libigl, a simple c++ geometry processing library.
//
// Copyright (C) 2013 Alec Jacobson <alecjacobson@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla Public License
// v. 2.0. If a copy of the MPL was not distributed with this file, You can
// obtain one at http://mozilla.org/MPL/2.0/.
#ifndef IGL_MAT_MIN_H
#define IGL_MAT_MIN_H
#include "igl_inline.h"
#include <Eigen/Dense>
namespace igl
{
// Ideally this becomes a super overloaded function supporting everything
// that matlab's min supports
// Min function for matrices to act like matlab's min function. Specifically
// like [Y,I] = min(X,[],dim);
//
// Templates:
// T should be a eigen matrix primitive type like int or double
// Inputs:
// X m by n matrix
// dim dimension along which to take min
// Outputs:
// Y n-long sparse vector (if dim == 1)
// or
// Y m-long sparse vector (if dim == 2)
// I vector the same size as Y containing the indices along dim of minimum
// entries
//
// See also: mat_max
template <typename DerivedX, typename DerivedY, typename DerivedI>
IGL_INLINE void mat_min(
const Eigen::DenseBase<DerivedX> & X,
const int dim,
Eigen::PlainObjectBase<DerivedY> & Y,
Eigen::PlainObjectBase<DerivedI> & I);
// Use Y = X.colwise().minCoeff() instead
//// In-line wrapper
//template <typename T>
//IGL_INLINE Eigen::Matrix<T,Eigen::Dynamic,1> mat_min(
// const Eigen::Matrix<T,Eigen::Dynamic,Eigen::Dynamic> & X,
// const int dim);
}
#ifndef IGL_STATIC_LIBRARY
# include "mat_min.cpp"
#endif
#endif
| 30.90566 | 79 | 0.676435 | [
"geometry",
"vector"
] |
3676ff4d78fc898c88d684d239196176ebfc60c2 | 9,180 | h | C | mindspore/ccsrc/debug/debugger/debugger.h | kungfu-team/mindspore-bert | 71501cf52ae01db9d6a73fb64bcfe68a6509dc32 | [
"Apache-2.0"
] | null | null | null | mindspore/ccsrc/debug/debugger/debugger.h | kungfu-team/mindspore-bert | 71501cf52ae01db9d6a73fb64bcfe68a6509dc32 | [
"Apache-2.0"
] | null | null | null | mindspore/ccsrc/debug/debugger/debugger.h | kungfu-team/mindspore-bert | 71501cf52ae01db9d6a73fb64bcfe68a6509dc32 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2020 Huawei Technologies Co., Ltd
*
* 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 MINDSPORE_CCSRC_DEBUG_DEBUGGER_DEBUGGER_H_
#define MINDSPORE_CCSRC_DEBUG_DEBUGGER_DEBUGGER_H_
#include <list>
#include <memory>
#include <string>
#include <utility>
#include <vector>
#include <map>
#include "backend/session/kernel_graph.h"
#include "debug/debugger/grpc_client.h"
#include "debug/debug_services.h"
using debugger::Chunk;
using debugger::DataType;
using debugger::EventReply;
using debugger::GraphProto;
using debugger::ModelProto;
using debugger::TensorProto;
using debugger::WatchCondition;
using debugger::WatchCondition_Parameter;
using debugger::WatchNode;
using debugger::WatchpointHit;
template <class T>
using ProtoVector = google::protobuf::RepeatedPtrField<T>;
namespace mindspore {
// different types of command received by debugger
// need to keep sync with client-side proto and server-side proto
enum class DebuggerCommand {
kExitCMD = 2,
kRunCMD = 3,
kSetCMD = 4,
kViewCMD = 5,
kVersionMatchedCMD = 6,
kUnknownCMD = -1
};
class Debugger : public std::enable_shared_from_this<Debugger> {
public:
static std::shared_ptr<Debugger> GetInstance() {
std::lock_guard<std::mutex> i_lock(instance_lock_);
if (debugger_ == nullptr) {
debugger_ = std::shared_ptr<Debugger>(new (std::nothrow) Debugger());
}
return debugger_;
}
// deconstructor
~Debugger() = default;
// init
// only save device_id
void Init(const uint32_t device_id, const std::string device_target);
// reset debugger
void Reset();
// enable debugger
// send graph and wait for command
// do nothing if graph is set already
void PreExecute(const KernelGraphPtr &graph_ptr, uint32_t graph_sum = 1);
// analyze tensors and wait for command
// don't need a graph_ptr because it is saved during pre_execute
void PostExecute();
bool ReadNodeDataRequired(const CNodePtr &kernel);
void PostExecuteNode(const CNodePtr &kernel, bool last_kernel);
// suspend the execution after a debug_op
void PostDebugOp();
bool DumpTensorToFile(const std::string &tensor_name, bool trans_flag, const std::string &filepath,
const std::string &host_fmt, const std::vector<int64_t> &host_shape, TypeId host_type,
TypeId addr_type_id, const std::string &addr_format, size_t slot) const;
bool DebugServicesIsWatchPoint(const std::string &kernel_name, const CNodePtr &kernel = nullptr) const;
void EmptyTensor();
void SetTensorLoaderIterNum(uint32_t iter_num);
void EmptyPrevTensor();
uint32_t GetTensorLoaderIterNum() const;
bool LoadNewTensor(const std::shared_ptr<TensorData> &tensor, bool keep_prev);
bool debugger_enabled() const;
bool partial_memory();
void SetCurNode(std::string cur_name);
std::string run_level() const;
void SetStepNum(int32_t cur_num_step);
int32_t step_num() const;
void SetStreamTaskToOpnameMap(const std::map<std::pair<uint32_t, uint32_t>, std::string> &mapping);
// check if any feature that uses the debugger backend is enabled
bool DebuggerBackendEnabled();
void SetTrainingDone(bool training_done);
// returns true if reply received and mindspore version matched with mindinsight version
// version_check should be true if you want the function to do backend compatibility check with Mindinsight
bool SendMetadata(bool version_check);
void LoadParametersAndConst();
void UpdateStepNum(const session::KernelGraph *graph);
void ClearCurrentData();
void LoadGraphOutputs();
void CheckDatasetSinkMode();
void LoadGraphs(const KernelGraphPtr &graph_ptr);
uint32_t GetFirstRunGraphId();
void SetGraphPtr(const KernelGraphPtr &graph_ptr) { graph_ptr_ = graph_ptr; }
std::list<KernelGraphPtr> GetGraphPtrList() { return graph_ptr_list_; }
bool TensorExistsInCurrent(std::string tensor_name);
private:
// private constructor for singleton
Debugger();
// enable debugger
// instantiate class members
// read env variable for grpc client
void EnableDebugger();
void SetOpOverflowBinPath(uint32_t graph_id);
// check if dump using debugger backend is enabled
bool CheckDebuggerDumpEnabled();
// check if debugger enabled
bool CheckDebuggerEnabled();
void CheckDebuggerEnabledParam();
bool CheckDebuggerPartialMemoryEnabled();
// check and save graph pointer
void CheckGraphPtr(const KernelGraphPtr &graph_ptr);
// check if the graph is a dataset graph
void CheckDatasetGraph();
// serialize graph and get proto
GraphProto GetGraphProto(const KernelGraphPtr &graph_ptr) const;
// send graph and enter command wait loop
void SendGraphAndSuspend(const GraphProto &graph_proto);
void SendMultiGraphsAndSuspend(const std::list<GraphProto> &graph_proto_list, uint32_t graph_sum);
// wait for command and process command
// send command request and process reply in a loop
// break if RunCMD
void CommandLoop();
// Process the RunCMD
void ProcessRunCMD(const EventReply &reply);
// Process the KSetCMD
void ProcessKSetCMD(const EventReply &reply);
// Process the KViewCMD
void ProcessKViewCMD(const EventReply &reply);
// set what nodes and conditions to watch
void SetWatchpoint(const ProtoVector<WatchNode> &nodes, const WatchCondition &condition, const int32_t id,
const ProtoVector<WatchCondition_Parameter> ¶meters);
// remove watchpoint with id
void RemoveWatchpoint(const int32_t id);
// load tensor for view command
std::list<TensorProto> LoadTensors(const ProtoVector<TensorProto> &tensors) const;
// terminate training process
void Exit();
// analyze tensors and check watchpoint conditions
// return names of tensors and what condition they hit
std::list<WatchpointHit> CheckWatchpoints(const std::string &watchnode = std::string(),
const CNodePtr &kernel = nullptr, bool recheck = false);
// send watchpoints that hit
void SendWatchpoints(const std::list<WatchpointHit> &points);
// Find if any operation overflow happened and return their names
std::vector<std::string> CheckOpOverflow();
// Check if the port is valid
bool CheckPort(const char *port);
// Check if the IP is valid
bool CheckIp(const char *host);
void LoadSingleAnfnode(const AnfNodePtr &anf_node, const size_t output_index);
// class members
std::unique_ptr<GrpcClient> grpc_client_;
std::unique_ptr<DebugServices> debug_services_;
KernelGraphPtr graph_ptr_;
uint32_t device_id_;
std::string device_target_;
int32_t num_step_;
bool debugger_enabled_;
std::string run_level_;
std::string node_name_;
std::string cur_name_;
bool training_done_;
bool is_dataset_graph_;
bool partial_memory_;
std::mutex access_lock_;
std::map<std::pair<uint32_t, uint32_t>, std::string> stream_task_to_opname_;
std::map<uint32_t, std::vector<std::string>> overflow_ops_;
double last_overflow_bin_;
std::map<uint32_t, std::string> overflow_bin_path_;
// flag to keep track of the very first suspension of debugger
bool initial_suspend_;
std::list<GraphProto> graph_proto_list_;
std::list<KernelGraphPtr> graph_ptr_list_;
// singleton
static std::mutex instance_lock_;
static std::shared_ptr<Debugger> debugger_;
uint32_t not_dataset_graph_sum_;
std::list<uint32_t> rungraph_id_list_;
std::string version_;
};
using DebuggerPtr = std::shared_ptr<Debugger>;
// get debugger ModelProto
std::string GetDebuggerFuncGraphProtoString(const FuncGraphPtr &func_graph);
ModelProto GetDebuggerFuncGraphProto(const FuncGraphPtr &func_graph);
// for getting proto DataType from Type of Tensor
DataType GetDebuggerNumberDataType(const TypePtr &type);
// process reply and command type
DebuggerCommand GetCommand(const EventReply &reply);
// parse other data out of EventReply
ProtoVector<WatchCondition_Parameter> GetParameters(const EventReply &reply);
ProtoVector<WatchNode> GetWatchnodes(const EventReply &reply);
std::string GetNodeName(const EventReply &reply);
std::string GetRunLevel(const EventReply &reply);
WatchCondition GetWatchcondition(const EventReply &reply);
int32_t GetWatchpointID(const EventReply &reply);
bool GetWatchpointDelete(const EventReply &reply);
ProtoVector<TensorProto> GetTensors(const EventReply &reply);
bool GetMiVersionMatched(const EventReply &reply);
// get the full name of a tensor, which is the name used in TensorLoader
std::string GetTensorFullName(const TensorProto &tensor);
uint64_t BytestoInt64(const std::vector<char> &buffer);
} // namespace mindspore
#endif // MINDSPORE_CCSRC_DEBUG_DEBUGGER_DEBUGGER_H_
| 31.655172 | 110 | 0.757407 | [
"vector"
] |
367cdd9a65bc011c90783c8eeeb20bacec1b12e5 | 5,072 | h | C | lib/dpdk-20.08/drivers/bus/pci/private.h | jhyunleehi/poseidonos | 1d90e4320855d61742ff37af8c0148da579d95d4 | [
"BSD-3-Clause"
] | null | null | null | lib/dpdk-20.08/drivers/bus/pci/private.h | jhyunleehi/poseidonos | 1d90e4320855d61742ff37af8c0148da579d95d4 | [
"BSD-3-Clause"
] | null | null | null | lib/dpdk-20.08/drivers/bus/pci/private.h | jhyunleehi/poseidonos | 1d90e4320855d61742ff37af8c0148da579d95d4 | [
"BSD-3-Clause"
] | null | null | null | /* SPDX-License-Identifier: BSD-3-Clause
* Copyright(c) 2017 6WIND S.A.
*/
#ifndef _PCI_PRIVATE_H_
#define _PCI_PRIVATE_H_
#include <stdbool.h>
#include <stdio.h>
#include <rte_pci.h>
#include <rte_bus_pci.h>
extern struct rte_pci_bus rte_pci_bus;
struct rte_pci_driver;
struct rte_pci_device;
extern struct rte_pci_bus rte_pci_bus;
/**
* Scan the content of the PCI bus, and the devices in the devices
* list
*
* @return
* 0 on success, negative on error
*/
int rte_pci_scan(void);
/**
* Find the name of a PCI device.
*/
void
pci_name_set(struct rte_pci_device *dev);
/**
* Validate whether a device with given PCI address should be ignored or not.
*
* @param pci_addr
* PCI address of device to be validated
* @return
* true: if device is to be ignored,
* false: if device is to be scanned,
*/
bool rte_pci_ignore_device(const struct rte_pci_addr *pci_addr);
/**
* Add a PCI device to the PCI Bus (append to PCI Device list). This function
* also updates the bus references of the PCI Device (and the generic device
* object embedded within.
*
* @param pci_dev
* PCI device to add
* @return void
*/
void rte_pci_add_device(struct rte_pci_device *pci_dev);
/**
* Insert a PCI device in the PCI Bus at a particular location in the device
* list. It also updates the PCI Bus reference of the new devices to be
* inserted.
*
* @param exist_pci_dev
* Existing PCI device in PCI Bus
* @param new_pci_dev
* PCI device to be added before exist_pci_dev
* @return void
*/
void rte_pci_insert_device(struct rte_pci_device *exist_pci_dev,
struct rte_pci_device *new_pci_dev);
/**
* Update a pci device object by asking the kernel for the latest information.
*
* This function is private to EAL.
*
* @param addr
* The PCI Bus-Device-Function address to look for
* @return
* - 0 on success.
* - negative on error.
*/
int pci_update_device(const struct rte_pci_addr *addr);
/**
* Map the PCI resource of a PCI device in virtual memory
*
* This function is private to EAL.
*
* @return
* 0 on success, negative on error
*/
int pci_uio_map_resource(struct rte_pci_device *dev);
/**
* Unmap the PCI resource of a PCI device
*
* This function is private to EAL.
*/
void pci_uio_unmap_resource(struct rte_pci_device *dev);
/**
* Allocate uio resource for PCI device
*
* This function is private to EAL.
*
* @param dev
* PCI device to allocate uio resource
* @param uio_res
* Pointer to uio resource.
* If the function returns 0, the pointer will be filled.
* @return
* 0 on success, negative on error
*/
int pci_uio_alloc_resource(struct rte_pci_device *dev,
struct mapped_pci_resource **uio_res);
/**
* Free uio resource for PCI device
*
* This function is private to EAL.
*
* @param dev
* PCI device to free uio resource
* @param uio_res
* Pointer to uio resource.
*/
void pci_uio_free_resource(struct rte_pci_device *dev,
struct mapped_pci_resource *uio_res);
/**
* Remap the PCI resource of a PCI device in anonymous virtual memory.
*
* @param dev
* Point to the struct rte pci device.
* @return
* - On success, zero.
* - On failure, a negative value.
*/
int
pci_uio_remap_resource(struct rte_pci_device *dev);
/**
* Map device memory to uio resource
*
* This function is private to EAL.
*
* @param dev
* PCI device that has memory information.
* @param res_idx
* Memory resource index of the PCI device.
* @param uio_res
* uio resource that will keep mapping information.
* @param map_idx
* Mapping information index of the uio resource.
* @return
* 0 on success, negative on error
*/
int pci_uio_map_resource_by_index(struct rte_pci_device *dev, int res_idx,
struct mapped_pci_resource *uio_res, int map_idx);
/*
* Match the PCI Driver and Device using the ID Table
*
* @param pci_drv
* PCI driver from which ID table would be extracted
* @param pci_dev
* PCI device to match against the driver
* @return
* 1 for successful match
* 0 for unsuccessful match
*/
int
rte_pci_match(const struct rte_pci_driver *pci_drv,
const struct rte_pci_device *pci_dev);
/**
* OS specific callbacks for rte_pci_get_iommu_class
*
*/
bool
pci_device_iommu_support_va(const struct rte_pci_device *dev);
enum rte_iova_mode
pci_device_iova_mode(const struct rte_pci_driver *pci_drv,
const struct rte_pci_device *pci_dev);
/**
* Get iommu class of PCI devices on the bus.
* And return their preferred iova mapping mode.
*
* @return
* - enum rte_iova_mode.
*/
enum rte_iova_mode
rte_pci_get_iommu_class(void);
/*
* Iterate over internal devices,
* matching any device against the provided
* string.
*
* @param start
* Iteration starting point.
*
* @param str
* Device string to match against.
*
* @param it
* (unused) iterator structure.
*
* @return
* A pointer to the next matching device if any.
* NULL otherwise.
*/
void *
rte_pci_dev_iterate(const void *start,
const char *str,
const struct rte_dev_iterator *it);
#endif /* _PCI_PRIVATE_H_ */
| 22.950226 | 78 | 0.713525 | [
"object"
] |
367ec35361bd2c5b94ec3ecb45162badf7a95c45 | 609 | h | C | ogsr_engine/COMMON_AI/alife_human_brain_inline.h | stepa2/OGSR-Engine | 32a23aa30506684be1267d9c4fc272350cd167c5 | [
"Apache-2.0"
] | 247 | 2018-11-02T18:50:55.000Z | 2022-03-15T09:11:43.000Z | ogsr_engine/COMMON_AI/alife_human_brain_inline.h | stepa2/OGSR-Engine | 32a23aa30506684be1267d9c4fc272350cd167c5 | [
"Apache-2.0"
] | 193 | 2018-11-02T20:12:44.000Z | 2022-03-07T13:35:17.000Z | ogsr_engine/COMMON_AI/alife_human_brain_inline.h | stepa2/OGSR-Engine | 32a23aa30506684be1267d9c4fc272350cd167c5 | [
"Apache-2.0"
] | 106 | 2018-10-26T11:33:01.000Z | 2022-03-19T12:34:20.000Z | ////////////////////////////////////////////////////////////////////////////
// Module : alife_human_brain_inline.h
// Created : 06.10.2005
// Modified : 06.10.2005
// Author : Dmitriy Iassenev
// Description : ALife human brain class inline functions
////////////////////////////////////////////////////////////////////////////
#pragma once
IC CALifeHumanBrain::object_type &CALifeHumanBrain::object () const
{
VERIFY (m_object);
return (*m_object);
}
IC CALifeHumanBrain::object_handler_type &CALifeHumanBrain::objects () const
{
VERIFY (m_object_handler);
return (*m_object_handler);
}
| 27.681818 | 76 | 0.545156 | [
"object"
] |
3680b8896e0e1984c99da23e195f116937db1cda | 1,974 | h | C | include/compapi.h | jfecher/old-ante | 5808b6ad648009cd198e442e3cca2a9294cf902b | [
"MIT"
] | null | null | null | include/compapi.h | jfecher/old-ante | 5808b6ad648009cd198e442e3cca2a9294cf902b | [
"MIT"
] | null | null | null | include/compapi.h | jfecher/old-ante | 5808b6ad648009cd198e442e3cca2a9294cf902b | [
"MIT"
] | null | null | null | #ifndef AN_COMPAPI_H
#define AN_COMPAPI_H
#include "compiler.h"
#include "antevalue.h"
namespace ante {
// namespace for compiler-api handling functions.
// Actual compiler api functions such as Ante_eval are in the global namespace with the Ante_ prefix.
namespace capi {
/**
* Holds a c++ function.
*
* Used to represent compiler API functions and call them
* with compile-time constants as arguments
*/
struct CtFunc {
void *fn;
std::vector<AnType*> params;
AnType* retty;
size_t numParams() const { return params.size(); }
bool typeCheck(std::vector<AnType*> &args);
bool typeCheck(std::vector<TypedValue&> &args);
CtFunc(void* fn);
CtFunc(void* fn, AnType *retTy);
CtFunc(void* fn, AnType *retTy, std::vector<AnType*> params);
~CtFunc(){}
using Arg = AnteValue const&;
TypedValue* operator()(Compiler *c);
TypedValue* operator()(Compiler *c, Arg tv);
TypedValue* operator()(Compiler *c, Arg tv1, Arg tv2);
TypedValue* operator()(Compiler *c, Arg tv1, Arg tv2, Arg tv3);
TypedValue* operator()(Compiler *c, Arg tv1, Arg tv2, Arg tv3, Arg tv4);
TypedValue* operator()(Compiler *c, Arg tv1, Arg tv2, Arg tv3, Arg tv4, Arg tv5);
TypedValue* operator()(Compiler *c, Arg tv1, Arg tv2, Arg tv3, Arg tv4, Arg tv5, Arg tv6);
};
/**
* Initialize functions contained within the internal map.
* This should be called before capi::lookup.
*/
void init();
/**
* Lookup the name of a function in the list of compiler api functions.
* If no function is found, nullptr is returned.
*/
CtFunc* lookup(std::string const& fn);
TypedValue create_wrapper(Compiler *c, FuncDecl *fd);
}
}
#endif
| 33.457627 | 105 | 0.580041 | [
"vector"
] |
36828607099a76e16933992a794cce8a900bc6ee | 55,479 | h | C | src/third_party/icu4c-57.1/source/i18n/unicode/ucal.h | danx0r/mongo | 70d4944c235bcdf7fbbc63971099563d2af72956 | [
"Apache-2.0"
] | 4,879 | 2015-09-30T10:56:36.000Z | 2022-03-31T18:43:03.000Z | 3party/icu/i18n/unicode/ucal.h | mbrukman/omim | d22fe2b6e0beee697f096e931df97a64f9db9dc1 | [
"Apache-2.0"
] | 7,549 | 2015-09-30T10:52:53.000Z | 2022-03-31T22:04:22.000Z | 3party/icu/i18n/unicode/ucal.h | mbrukman/omim | d22fe2b6e0beee697f096e931df97a64f9db9dc1 | [
"Apache-2.0"
] | 1,493 | 2015-09-30T10:43:06.000Z | 2022-03-21T09:16:49.000Z | /*
*******************************************************************************
* Copyright (C) 1996-2015, International Business Machines Corporation and
* others. All Rights Reserved.
*******************************************************************************
*/
#ifndef UCAL_H
#define UCAL_H
#include "unicode/utypes.h"
#include "unicode/uenum.h"
#include "unicode/uloc.h"
#include "unicode/localpointer.h"
#if !UCONFIG_NO_FORMATTING
/**
* \file
* \brief C API: Calendar
*
* <h2>Calendar C API</h2>
*
* UCalendar C API is used for converting between a <code>UDate</code> object
* and a set of integer fields such as <code>UCAL_YEAR</code>, <code>UCAL_MONTH</code>,
* <code>UCAL_DAY</code>, <code>UCAL_HOUR</code>, and so on.
* (A <code>UDate</code> object represents a specific instant in
* time with millisecond precision. See UDate
* for information about the <code>UDate</code> .)
*
* <p>
* Types of <code>UCalendar</code> interpret a <code>UDate</code>
* according to the rules of a specific calendar system. The U_STABLE
* provides the enum UCalendarType with UCAL_TRADITIONAL and
* UCAL_GREGORIAN.
* <p>
* Like other locale-sensitive C API, calendar API provides a
* function, <code>ucal_open()</code>, which returns a pointer to
* <code>UCalendar</code> whose time fields have been initialized
* with the current date and time. We need to specify the type of
* calendar to be opened and the timezoneId.
* \htmlonly<blockquote>\endhtmlonly
* <pre>
* \code
* UCalendar *caldef;
* UChar *tzId;
* UErrorCode status;
* tzId=(UChar*)malloc(sizeof(UChar) * (strlen("PST") +1) );
* u_uastrcpy(tzId, "PST");
* caldef=ucal_open(tzID, u_strlen(tzID), NULL, UCAL_TRADITIONAL, &status);
* \endcode
* </pre>
* \htmlonly</blockquote>\endhtmlonly
*
* <p>
* A <code>UCalendar</code> object can produce all the time field values
* needed to implement the date-time formatting for a particular language
* and calendar style (for example, Japanese-Gregorian, Japanese-Traditional).
*
* <p>
* When computing a <code>UDate</code> from time fields, two special circumstances
* may arise: there may be insufficient information to compute the
* <code>UDate</code> (such as only year and month but no day in the month),
* or there may be inconsistent information (such as "Tuesday, July 15, 1996"
* -- July 15, 1996 is actually a Monday).
*
* <p>
* <strong>Insufficient information.</strong> The calendar will use default
* information to specify the missing fields. This may vary by calendar; for
* the Gregorian calendar, the default for a field is the same as that of the
* start of the epoch: i.e., UCAL_YEAR = 1970, UCAL_MONTH = JANUARY, UCAL_DATE = 1, etc.
*
* <p>
* <strong>Inconsistent information.</strong> If fields conflict, the calendar
* will give preference to fields set more recently. For example, when
* determining the day, the calendar will look for one of the following
* combinations of fields. The most recent combination, as determined by the
* most recently set single field, will be used.
*
* \htmlonly<blockquote>\endhtmlonly
* <pre>
* \code
* UCAL_MONTH + UCAL_DAY_OF_MONTH
* UCAL_MONTH + UCAL_WEEK_OF_MONTH + UCAL_DAY_OF_WEEK
* UCAL_MONTH + UCAL_DAY_OF_WEEK_IN_MONTH + UCAL_DAY_OF_WEEK
* UCAL_DAY_OF_YEAR
* UCAL_DAY_OF_WEEK + UCAL_WEEK_OF_YEAR
* \endcode
* </pre>
* \htmlonly</blockquote>\endhtmlonly
*
* For the time of day:
*
* \htmlonly<blockquote>\endhtmlonly
* <pre>
* \code
* UCAL_HOUR_OF_DAY
* UCAL_AM_PM + UCAL_HOUR
* \endcode
* </pre>
* \htmlonly</blockquote>\endhtmlonly
*
* <p>
* <strong>Note:</strong> for some non-Gregorian calendars, different
* fields may be necessary for complete disambiguation. For example, a full
* specification of the historial Arabic astronomical calendar requires year,
* month, day-of-month <em>and</em> day-of-week in some cases.
*
* <p>
* <strong>Note:</strong> There are certain possible ambiguities in
* interpretation of certain singular times, which are resolved in the
* following ways:
* <ol>
* <li> 24:00:00 "belongs" to the following day. That is,
* 23:59 on Dec 31, 1969 < 24:00 on Jan 1, 1970 < 24:01:00 on Jan 1, 1970
*
* <li> Although historically not precise, midnight also belongs to "am",
* and noon belongs to "pm", so on the same day,
* 12:00 am (midnight) < 12:01 am, and 12:00 pm (noon) < 12:01 pm
* </ol>
*
* <p>
* The date or time format strings are not part of the definition of a
* calendar, as those must be modifiable or overridable by the user at
* runtime. Use {@link icu::DateFormat}
* to format dates.
*
* <p>
* <code>Calendar</code> provides an API for field "rolling", where fields
* can be incremented or decremented, but wrap around. For example, rolling the
* month up in the date <code>December 12, <b>1996</b></code> results in
* <code>January 12, <b>1996</b></code>.
*
* <p>
* <code>Calendar</code> also provides a date arithmetic function for
* adding the specified (signed) amount of time to a particular time field.
* For example, subtracting 5 days from the date <code>September 12, 1996</code>
* results in <code>September 7, 1996</code>.
*
* @stable ICU 2.0
*/
/**
* The time zone ID reserved for unknown time zone.
* @stable ICU 4.8
*/
#define UCAL_UNKNOWN_ZONE_ID "Etc/Unknown"
/** A calendar.
* For usage in C programs.
* @stable ICU 2.0
*/
typedef void* UCalendar;
/** Possible types of UCalendars
* @stable ICU 2.0
*/
enum UCalendarType {
/**
* Despite the name, UCAL_TRADITIONAL designates the locale's default calendar,
* which may be the Gregorian calendar or some other calendar.
* @stable ICU 2.0
*/
UCAL_TRADITIONAL,
/**
* A better name for UCAL_TRADITIONAL.
* @stable ICU 4.2
*/
UCAL_DEFAULT = UCAL_TRADITIONAL,
/**
* Unambiguously designates the Gregorian calendar for the locale.
* @stable ICU 2.0
*/
UCAL_GREGORIAN
};
/** @stable ICU 2.0 */
typedef enum UCalendarType UCalendarType;
/** Possible fields in a UCalendar
* @stable ICU 2.0
*/
enum UCalendarDateFields {
/**
* Field number indicating the era, e.g., AD or BC in the Gregorian (Julian) calendar.
* This is a calendar-specific value.
* @stable ICU 2.6
*/
UCAL_ERA,
/**
* Field number indicating the year. This is a calendar-specific value.
* @stable ICU 2.6
*/
UCAL_YEAR,
/**
* Field number indicating the month. This is a calendar-specific value.
* The first month of the year is
* <code>JANUARY</code>; the last depends on the number of months in a year.
* @see #UCAL_JANUARY
* @see #UCAL_FEBRUARY
* @see #UCAL_MARCH
* @see #UCAL_APRIL
* @see #UCAL_MAY
* @see #UCAL_JUNE
* @see #UCAL_JULY
* @see #UCAL_AUGUST
* @see #UCAL_SEPTEMBER
* @see #UCAL_OCTOBER
* @see #UCAL_NOVEMBER
* @see #UCAL_DECEMBER
* @see #UCAL_UNDECIMBER
* @stable ICU 2.6
*/
UCAL_MONTH,
/**
* Field number indicating the
* week number within the current year. The first week of the year, as
* defined by <code>UCAL_FIRST_DAY_OF_WEEK</code> and <code>UCAL_MINIMAL_DAYS_IN_FIRST_WEEK</code>
* attributes, has value 1. Subclasses define
* the value of <code>UCAL_WEEK_OF_YEAR</code> for days before the first week of
* the year.
* @see ucal_getAttribute
* @see ucal_setAttribute
* @stable ICU 2.6
*/
UCAL_WEEK_OF_YEAR,
/**
* Field number indicating the
* week number within the current month. The first week of the month, as
* defined by <code>UCAL_FIRST_DAY_OF_WEEK</code> and <code>UCAL_MINIMAL_DAYS_IN_FIRST_WEEK</code>
* attributes, has value 1. Subclasses define
* the value of <code>WEEK_OF_MONTH</code> for days before the first week of
* the month.
* @see ucal_getAttribute
* @see ucal_setAttribute
* @see #UCAL_FIRST_DAY_OF_WEEK
* @see #UCAL_MINIMAL_DAYS_IN_FIRST_WEEK
* @stable ICU 2.6
*/
UCAL_WEEK_OF_MONTH,
/**
* Field number indicating the
* day of the month. This is a synonym for <code>DAY_OF_MONTH</code>.
* The first day of the month has value 1.
* @see #UCAL_DAY_OF_MONTH
* @stable ICU 2.6
*/
UCAL_DATE,
/**
* Field number indicating the day
* number within the current year. The first day of the year has value 1.
* @stable ICU 2.6
*/
UCAL_DAY_OF_YEAR,
/**
* Field number indicating the day
* of the week. This field takes values <code>SUNDAY</code>,
* <code>MONDAY</code>, <code>TUESDAY</code>, <code>WEDNESDAY</code>,
* <code>THURSDAY</code>, <code>FRIDAY</code>, and <code>SATURDAY</code>.
* @see #UCAL_SUNDAY
* @see #UCAL_MONDAY
* @see #UCAL_TUESDAY
* @see #UCAL_WEDNESDAY
* @see #UCAL_THURSDAY
* @see #UCAL_FRIDAY
* @see #UCAL_SATURDAY
* @stable ICU 2.6
*/
UCAL_DAY_OF_WEEK,
/**
* Field number indicating the
* ordinal number of the day of the week within the current month. Together
* with the <code>DAY_OF_WEEK</code> field, this uniquely specifies a day
* within a month. Unlike <code>WEEK_OF_MONTH</code> and
* <code>WEEK_OF_YEAR</code>, this field's value does <em>not</em> depend on
* <code>getFirstDayOfWeek()</code> or
* <code>getMinimalDaysInFirstWeek()</code>. <code>DAY_OF_MONTH 1</code>
* through <code>7</code> always correspond to <code>DAY_OF_WEEK_IN_MONTH
* 1</code>; <code>8</code> through <code>15</code> correspond to
* <code>DAY_OF_WEEK_IN_MONTH 2</code>, and so on.
* <code>DAY_OF_WEEK_IN_MONTH 0</code> indicates the week before
* <code>DAY_OF_WEEK_IN_MONTH 1</code>. Negative values count back from the
* end of the month, so the last Sunday of a month is specified as
* <code>DAY_OF_WEEK = SUNDAY, DAY_OF_WEEK_IN_MONTH = -1</code>. Because
* negative values count backward they will usually be aligned differently
* within the month than positive values. For example, if a month has 31
* days, <code>DAY_OF_WEEK_IN_MONTH -1</code> will overlap
* <code>DAY_OF_WEEK_IN_MONTH 5</code> and the end of <code>4</code>.
* @see #UCAL_DAY_OF_WEEK
* @see #UCAL_WEEK_OF_MONTH
* @stable ICU 2.6
*/
UCAL_DAY_OF_WEEK_IN_MONTH,
/**
* Field number indicating
* whether the <code>HOUR</code> is before or after noon.
* E.g., at 10:04:15.250 PM the <code>AM_PM</code> is <code>PM</code>.
* @see #UCAL_AM
* @see #UCAL_PM
* @see #UCAL_HOUR
* @stable ICU 2.6
*/
UCAL_AM_PM,
/**
* Field number indicating the
* hour of the morning or afternoon. <code>HOUR</code> is used for the 12-hour
* clock.
* E.g., at 10:04:15.250 PM the <code>HOUR</code> is 10.
* @see #UCAL_AM_PM
* @see #UCAL_HOUR_OF_DAY
* @stable ICU 2.6
*/
UCAL_HOUR,
/**
* Field number indicating the
* hour of the day. <code>HOUR_OF_DAY</code> is used for the 24-hour clock.
* E.g., at 10:04:15.250 PM the <code>HOUR_OF_DAY</code> is 22.
* @see #UCAL_HOUR
* @stable ICU 2.6
*/
UCAL_HOUR_OF_DAY,
/**
* Field number indicating the
* minute within the hour.
* E.g., at 10:04:15.250 PM the <code>UCAL_MINUTE</code> is 4.
* @stable ICU 2.6
*/
UCAL_MINUTE,
/**
* Field number indicating the
* second within the minute.
* E.g., at 10:04:15.250 PM the <code>UCAL_SECOND</code> is 15.
* @stable ICU 2.6
*/
UCAL_SECOND,
/**
* Field number indicating the
* millisecond within the second.
* E.g., at 10:04:15.250 PM the <code>UCAL_MILLISECOND</code> is 250.
* @stable ICU 2.6
*/
UCAL_MILLISECOND,
/**
* Field number indicating the
* raw offset from GMT in milliseconds.
* @stable ICU 2.6
*/
UCAL_ZONE_OFFSET,
/**
* Field number indicating the
* daylight savings offset in milliseconds.
* @stable ICU 2.6
*/
UCAL_DST_OFFSET,
/**
* Field number
* indicating the extended year corresponding to the
* <code>UCAL_WEEK_OF_YEAR</code> field. This may be one greater or less
* than the value of <code>UCAL_EXTENDED_YEAR</code>.
* @stable ICU 2.6
*/
UCAL_YEAR_WOY,
/**
* Field number
* indicating the localized day of week. This will be a value from 1
* to 7 inclusive, with 1 being the localized first day of the week.
* @stable ICU 2.6
*/
UCAL_DOW_LOCAL,
/**
* Year of this calendar system, encompassing all supra-year fields. For example,
* in Gregorian/Julian calendars, positive Extended Year values indicate years AD,
* 1 BC = 0 extended, 2 BC = -1 extended, and so on.
* @stable ICU 2.8
*/
UCAL_EXTENDED_YEAR,
/**
* Field number
* indicating the modified Julian day number. This is different from
* the conventional Julian day number in two regards. First, it
* demarcates days at local zone midnight, rather than noon GMT.
* Second, it is a local number; that is, it depends on the local time
* zone. It can be thought of as a single number that encompasses all
* the date-related fields.
* @stable ICU 2.8
*/
UCAL_JULIAN_DAY,
/**
* Ranges from 0 to 23:59:59.999 (regardless of DST). This field behaves <em>exactly</em>
* like a composite of all time-related fields, not including the zone fields. As such,
* it also reflects discontinuities of those fields on DST transition days. On a day
* of DST onset, it will jump forward. On a day of DST cessation, it will jump
* backward. This reflects the fact that it must be combined with the DST_OFFSET field
* to obtain a unique local time value.
* @stable ICU 2.8
*/
UCAL_MILLISECONDS_IN_DAY,
/**
* Whether or not the current month is a leap month (0 or 1). See the Chinese calendar for
* an example of this.
*/
UCAL_IS_LEAP_MONTH,
/**
* Field count
* @stable ICU 2.6
*/
UCAL_FIELD_COUNT,
/**
* Field number indicating the
* day of the month. This is a synonym for <code>UCAL_DATE</code>.
* The first day of the month has value 1.
* @see #UCAL_DATE
* Synonym for UCAL_DATE
* @stable ICU 2.8
**/
UCAL_DAY_OF_MONTH=UCAL_DATE
};
/** @stable ICU 2.0 */
typedef enum UCalendarDateFields UCalendarDateFields;
/**
* Useful constant for days of week. Note: Calendar day-of-week is 1-based. Clients
* who create locale resources for the field of first-day-of-week should be aware of
* this. For instance, in US locale, first-day-of-week is set to 1, i.e., UCAL_SUNDAY.
*/
/** Possible days of the week in a UCalendar
* @stable ICU 2.0
*/
enum UCalendarDaysOfWeek {
/** Sunday */
UCAL_SUNDAY = 1,
/** Monday */
UCAL_MONDAY,
/** Tuesday */
UCAL_TUESDAY,
/** Wednesday */
UCAL_WEDNESDAY,
/** Thursday */
UCAL_THURSDAY,
/** Friday */
UCAL_FRIDAY,
/** Saturday */
UCAL_SATURDAY
};
/** @stable ICU 2.0 */
typedef enum UCalendarDaysOfWeek UCalendarDaysOfWeek;
/** Possible months in a UCalendar. Note: Calendar month is 0-based.
* @stable ICU 2.0
*/
enum UCalendarMonths {
/** January */
UCAL_JANUARY,
/** February */
UCAL_FEBRUARY,
/** March */
UCAL_MARCH,
/** April */
UCAL_APRIL,
/** May */
UCAL_MAY,
/** June */
UCAL_JUNE,
/** July */
UCAL_JULY,
/** August */
UCAL_AUGUST,
/** September */
UCAL_SEPTEMBER,
/** October */
UCAL_OCTOBER,
/** November */
UCAL_NOVEMBER,
/** December */
UCAL_DECEMBER,
/** Value of the <code>UCAL_MONTH</code> field indicating the
* thirteenth month of the year. Although the Gregorian calendar
* does not use this value, lunar calendars do.
*/
UCAL_UNDECIMBER
};
/** @stable ICU 2.0 */
typedef enum UCalendarMonths UCalendarMonths;
/** Possible AM/PM values in a UCalendar
* @stable ICU 2.0
*/
enum UCalendarAMPMs {
/** AM */
UCAL_AM,
/** PM */
UCAL_PM
};
/** @stable ICU 2.0 */
typedef enum UCalendarAMPMs UCalendarAMPMs;
/**
* System time zone type constants used by filtering zones
* in ucal_openTimeZoneIDEnumeration.
* @see ucal_openTimeZoneIDEnumeration
* @stable ICU 4.8
*/
enum USystemTimeZoneType {
/**
* Any system zones.
* @stable ICU 4.8
*/
UCAL_ZONE_TYPE_ANY,
/**
* Canonical system zones.
* @stable ICU 4.8
*/
UCAL_ZONE_TYPE_CANONICAL,
/**
* Canonical system zones associated with actual locations.
* @stable ICU 4.8
*/
UCAL_ZONE_TYPE_CANONICAL_LOCATION
};
/** @stable ICU 4.8 */
typedef enum USystemTimeZoneType USystemTimeZoneType;
/**
* Create an enumeration over system time zone IDs with the given
* filter conditions.
* @param zoneType The system time zone type.
* @param region The ISO 3166 two-letter country code or UN M.49
* three-digit area code. When NULL, no filtering
* done by region.
* @param rawOffset An offset from GMT in milliseconds, ignoring the
* effect of daylight savings time, if any. When NULL,
* no filtering done by zone offset.
* @param ec A pointer to an UErrorCode to receive any errors
* @return an enumeration object that the caller must dispose of
* using enum_close(), or NULL upon failure. In case of failure,
* *ec will indicate the error.
* @stable ICU 4.8
*/
U_STABLE UEnumeration* U_EXPORT2
ucal_openTimeZoneIDEnumeration(USystemTimeZoneType zoneType, const char* region,
const int32_t* rawOffset, UErrorCode* ec);
/**
* Create an enumeration over all time zones.
*
* @param ec input/output error code
*
* @return an enumeration object that the caller must dispose of using
* uenum_close(), or NULL upon failure. In case of failure *ec will
* indicate the error.
*
* @stable ICU 2.6
*/
U_STABLE UEnumeration* U_EXPORT2
ucal_openTimeZones(UErrorCode* ec);
/**
* Create an enumeration over all time zones associated with the given
* country. Some zones are affiliated with no country (e.g., "UTC");
* these may also be retrieved, as a group.
*
* @param country the ISO 3166 two-letter country code, or NULL to
* retrieve zones not affiliated with any country
*
* @param ec input/output error code
*
* @return an enumeration object that the caller must dispose of using
* uenum_close(), or NULL upon failure. In case of failure *ec will
* indicate the error.
*
* @stable ICU 2.6
*/
U_STABLE UEnumeration* U_EXPORT2
ucal_openCountryTimeZones(const char* country, UErrorCode* ec);
/**
* Return the default time zone. The default is determined initially
* by querying the host operating system. It may be changed with
* ucal_setDefaultTimeZone() or with the C++ TimeZone API.
*
* @param result A buffer to receive the result, or NULL
*
* @param resultCapacity The capacity of the result buffer
*
* @param ec input/output error code
*
* @return The result string length, not including the terminating
* null
*
* @stable ICU 2.6
*/
U_STABLE int32_t U_EXPORT2
ucal_getDefaultTimeZone(UChar* result, int32_t resultCapacity, UErrorCode* ec);
/**
* Set the default time zone.
*
* @param zoneID null-terminated time zone ID
*
* @param ec input/output error code
*
* @stable ICU 2.6
*/
U_STABLE void U_EXPORT2
ucal_setDefaultTimeZone(const UChar* zoneID, UErrorCode* ec);
/**
* Return the amount of time in milliseconds that the clock is
* advanced during daylight savings time for the given time zone, or
* zero if the time zone does not observe daylight savings time.
*
* @param zoneID null-terminated time zone ID
*
* @param ec input/output error code
*
* @return the number of milliseconds the time is advanced with
* respect to standard time when the daylight savings rules are in
* effect. This is always a non-negative number, most commonly either
* 3,600,000 (one hour) or zero.
*
* @stable ICU 2.6
*/
U_STABLE int32_t U_EXPORT2
ucal_getDSTSavings(const UChar* zoneID, UErrorCode* ec);
/**
* Get the current date and time.
* The value returned is represented as milliseconds from the epoch.
* @return The current date and time.
* @stable ICU 2.0
*/
U_STABLE UDate U_EXPORT2
ucal_getNow(void);
/**
* Open a UCalendar.
* A UCalendar may be used to convert a millisecond value to a year,
* month, and day.
* <p>
* Note: When unknown TimeZone ID is specified or if the TimeZone ID specified is "Etc/Unknown",
* the UCalendar returned by the function is initialized with GMT zone with TimeZone ID
* <code>UCAL_UNKNOWN_ZONE_ID</code> ("Etc/Unknown") without any errors/warnings. If you want
* to check if a TimeZone ID is valid prior to this function, use <code>ucal_getCanonicalTimeZoneID</code>.
*
* @param zoneID The desired TimeZone ID. If 0, use the default time zone.
* @param len The length of zoneID, or -1 if null-terminated.
* @param locale The desired locale
* @param type The type of UCalendar to open. This can be UCAL_GREGORIAN to open the Gregorian
* calendar for the locale, or UCAL_DEFAULT to open the default calendar for the locale (the
* default calendar may also be Gregorian). To open a specific non-Gregorian calendar for the
* locale, use uloc_setKeywordValue to set the value of the calendar keyword for the locale
* and then pass the locale to ucal_open with UCAL_DEFAULT as the type.
* @param status A pointer to an UErrorCode to receive any errors
* @return A pointer to a UCalendar, or 0 if an error occurred.
* @see #UCAL_UNKNOWN_ZONE_ID
* @stable ICU 2.0
*/
U_STABLE UCalendar* U_EXPORT2
ucal_open(const UChar* zoneID,
int32_t len,
const char* locale,
UCalendarType type,
UErrorCode* status);
/**
* Close a UCalendar.
* Once closed, a UCalendar may no longer be used.
* @param cal The UCalendar to close.
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2
ucal_close(UCalendar *cal);
#if U_SHOW_CPLUSPLUS_API
U_NAMESPACE_BEGIN
/**
* \class LocalUCalendarPointer
* "Smart pointer" class, closes a UCalendar via ucal_close().
* For most methods see the LocalPointerBase base class.
*
* @see LocalPointerBase
* @see LocalPointer
* @stable ICU 4.4
*/
U_DEFINE_LOCAL_OPEN_POINTER(LocalUCalendarPointer, UCalendar, ucal_close);
U_NAMESPACE_END
#endif
/**
* Open a copy of a UCalendar.
* This function performs a deep copy.
* @param cal The calendar to copy
* @param status A pointer to an UErrorCode to receive any errors.
* @return A pointer to a UCalendar identical to cal.
* @stable ICU 4.0
*/
U_STABLE UCalendar* U_EXPORT2
ucal_clone(const UCalendar* cal,
UErrorCode* status);
/**
* Set the TimeZone used by a UCalendar.
* A UCalendar uses a timezone for converting from Greenwich time to local time.
* @param cal The UCalendar to set.
* @param zoneID The desired TimeZone ID. If 0, use the default time zone.
* @param len The length of zoneID, or -1 if null-terminated.
* @param status A pointer to an UErrorCode to receive any errors.
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2
ucal_setTimeZone(UCalendar* cal,
const UChar* zoneID,
int32_t len,
UErrorCode* status);
/**
* Get the ID of the UCalendar's time zone.
*
* @param cal The UCalendar to query.
* @param result Receives the UCalendar's time zone ID.
* @param resultLength The maximum size of result.
* @param status Receives the status.
* @return The total buffer size needed; if greater than resultLength, the output was truncated.
* @stable ICU 51
*/
U_STABLE int32_t U_EXPORT2
ucal_getTimeZoneID(const UCalendar *cal,
UChar *result,
int32_t resultLength,
UErrorCode *status);
/**
* Possible formats for a UCalendar's display name
* @stable ICU 2.0
*/
enum UCalendarDisplayNameType {
/** Standard display name */
UCAL_STANDARD,
/** Short standard display name */
UCAL_SHORT_STANDARD,
/** Daylight savings display name */
UCAL_DST,
/** Short daylight savings display name */
UCAL_SHORT_DST
};
/** @stable ICU 2.0 */
typedef enum UCalendarDisplayNameType UCalendarDisplayNameType;
/**
* Get the display name for a UCalendar's TimeZone.
* A display name is suitable for presentation to a user.
* @param cal The UCalendar to query.
* @param type The desired display name format; one of UCAL_STANDARD, UCAL_SHORT_STANDARD,
* UCAL_DST, UCAL_SHORT_DST
* @param locale The desired locale for the display name.
* @param result A pointer to a buffer to receive the formatted number.
* @param resultLength The maximum size of result.
* @param status A pointer to an UErrorCode to receive any errors
* @return The total buffer size needed; if greater than resultLength, the output was truncated.
* @stable ICU 2.0
*/
U_STABLE int32_t U_EXPORT2
ucal_getTimeZoneDisplayName(const UCalendar* cal,
UCalendarDisplayNameType type,
const char* locale,
UChar* result,
int32_t resultLength,
UErrorCode* status);
/**
* Determine if a UCalendar is currently in daylight savings time.
* Daylight savings time is not used in all parts of the world.
* @param cal The UCalendar to query.
* @param status A pointer to an UErrorCode to receive any errors
* @return TRUE if cal is currently in daylight savings time, FALSE otherwise
* @stable ICU 2.0
*/
U_STABLE UBool U_EXPORT2
ucal_inDaylightTime(const UCalendar* cal,
UErrorCode* status );
/**
* Sets the GregorianCalendar change date. This is the point when the switch from
* Julian dates to Gregorian dates occurred. Default is 00:00:00 local time, October
* 15, 1582. Previous to this time and date will be Julian dates.
*
* This function works only for Gregorian calendars. If the UCalendar is not
* an instance of a Gregorian calendar, then a U_UNSUPPORTED_ERROR
* error code is set.
*
* @param cal The calendar object.
* @param date The given Gregorian cutover date.
* @param pErrorCode Pointer to a standard ICU error code. Its input value must
* pass the U_SUCCESS() test, or else the function returns
* immediately. Check for U_FAILURE() on output or use with
* function chaining. (See User Guide for details.)
*
* @see GregorianCalendar::setGregorianChange
* @see ucal_getGregorianChange
* @stable ICU 3.6
*/
U_STABLE void U_EXPORT2
ucal_setGregorianChange(UCalendar *cal, UDate date, UErrorCode *pErrorCode);
/**
* Gets the Gregorian Calendar change date. This is the point when the switch from
* Julian dates to Gregorian dates occurred. Default is 00:00:00 local time, October
* 15, 1582. Previous to this time and date will be Julian dates.
*
* This function works only for Gregorian calendars. If the UCalendar is not
* an instance of a Gregorian calendar, then a U_UNSUPPORTED_ERROR
* error code is set.
*
* @param cal The calendar object.
* @param pErrorCode Pointer to a standard ICU error code. Its input value must
* pass the U_SUCCESS() test, or else the function returns
* immediately. Check for U_FAILURE() on output or use with
* function chaining. (See User Guide for details.)
* @return The Gregorian cutover time for this calendar.
*
* @see GregorianCalendar::getGregorianChange
* @see ucal_setGregorianChange
* @stable ICU 3.6
*/
U_STABLE UDate U_EXPORT2
ucal_getGregorianChange(const UCalendar *cal, UErrorCode *pErrorCode);
/**
* Types of UCalendar attributes
* @stable ICU 2.0
*/
enum UCalendarAttribute {
/**
* Lenient parsing
* @stable ICU 2.0
*/
UCAL_LENIENT,
/**
* First day of week
* @stable ICU 2.0
*/
UCAL_FIRST_DAY_OF_WEEK,
/**
* Minimum number of days in first week
* @stable ICU 2.0
*/
UCAL_MINIMAL_DAYS_IN_FIRST_WEEK,
/**
* The behavior for handling wall time repeating multiple times
* at negative time zone offset transitions
* @stable ICU 49
*/
UCAL_REPEATED_WALL_TIME,
/**
* The behavior for handling skipped wall time at positive time
* zone offset transitions.
* @stable ICU 49
*/
UCAL_SKIPPED_WALL_TIME
};
/** @stable ICU 2.0 */
typedef enum UCalendarAttribute UCalendarAttribute;
/**
* Options for handling ambiguous wall time at time zone
* offset transitions.
* @stable ICU 49
*/
enum UCalendarWallTimeOption {
/**
* An ambiguous wall time to be interpreted as the latest.
* This option is valid for UCAL_REPEATED_WALL_TIME and
* UCAL_SKIPPED_WALL_TIME.
* @stable ICU 49
*/
UCAL_WALLTIME_LAST,
/**
* An ambiguous wall time to be interpreted as the earliest.
* This option is valid for UCAL_REPEATED_WALL_TIME and
* UCAL_SKIPPED_WALL_TIME.
* @stable ICU 49
*/
UCAL_WALLTIME_FIRST,
/**
* An ambiguous wall time to be interpreted as the next valid
* wall time. This option is valid for UCAL_SKIPPED_WALL_TIME.
* @stable ICU 49
*/
UCAL_WALLTIME_NEXT_VALID
};
/** @stable ICU 49 */
typedef enum UCalendarWallTimeOption UCalendarWallTimeOption;
/**
* Get a numeric attribute associated with a UCalendar.
* Numeric attributes include the first day of the week, or the minimal numbers
* of days in the first week of the month.
* @param cal The UCalendar to query.
* @param attr The desired attribute; one of UCAL_LENIENT, UCAL_FIRST_DAY_OF_WEEK,
* UCAL_MINIMAL_DAYS_IN_FIRST_WEEK, UCAL_REPEATED_WALL_TIME or UCAL_SKIPPED_WALL_TIME
* @return The value of attr.
* @see ucal_setAttribute
* @stable ICU 2.0
*/
U_STABLE int32_t U_EXPORT2
ucal_getAttribute(const UCalendar* cal,
UCalendarAttribute attr);
/**
* Set a numeric attribute associated with a UCalendar.
* Numeric attributes include the first day of the week, or the minimal numbers
* of days in the first week of the month.
* @param cal The UCalendar to set.
* @param attr The desired attribute; one of UCAL_LENIENT, UCAL_FIRST_DAY_OF_WEEK,
* UCAL_MINIMAL_DAYS_IN_FIRST_WEEK, UCAL_REPEATED_WALL_TIME or UCAL_SKIPPED_WALL_TIME
* @param newValue The new value of attr.
* @see ucal_getAttribute
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2
ucal_setAttribute(UCalendar* cal,
UCalendarAttribute attr,
int32_t newValue);
/**
* Get a locale for which calendars are available.
* A UCalendar in a locale returned by this function will contain the correct
* day and month names for the locale.
* @param localeIndex The index of the desired locale.
* @return A locale for which calendars are available, or 0 if none.
* @see ucal_countAvailable
* @stable ICU 2.0
*/
U_STABLE const char* U_EXPORT2
ucal_getAvailable(int32_t localeIndex);
/**
* Determine how many locales have calendars available.
* This function is most useful as determining the loop ending condition for
* calls to \ref ucal_getAvailable.
* @return The number of locales for which calendars are available.
* @see ucal_getAvailable
* @stable ICU 2.0
*/
U_STABLE int32_t U_EXPORT2
ucal_countAvailable(void);
/**
* Get a UCalendar's current time in millis.
* The time is represented as milliseconds from the epoch.
* @param cal The UCalendar to query.
* @param status A pointer to an UErrorCode to receive any errors
* @return The calendar's current time in millis.
* @see ucal_setMillis
* @see ucal_setDate
* @see ucal_setDateTime
* @stable ICU 2.0
*/
U_STABLE UDate U_EXPORT2
ucal_getMillis(const UCalendar* cal,
UErrorCode* status);
/**
* Set a UCalendar's current time in millis.
* The time is represented as milliseconds from the epoch.
* @param cal The UCalendar to set.
* @param dateTime The desired date and time.
* @param status A pointer to an UErrorCode to receive any errors
* @see ucal_getMillis
* @see ucal_setDate
* @see ucal_setDateTime
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2
ucal_setMillis(UCalendar* cal,
UDate dateTime,
UErrorCode* status );
/**
* Set a UCalendar's current date.
* The date is represented as a series of 32-bit integers.
* @param cal The UCalendar to set.
* @param year The desired year.
* @param month The desired month; one of UCAL_JANUARY, UCAL_FEBRUARY, UCAL_MARCH, UCAL_APRIL, UCAL_MAY,
* UCAL_JUNE, UCAL_JULY, UCAL_AUGUST, UCAL_SEPTEMBER, UCAL_OCTOBER, UCAL_NOVEMBER, UCAL_DECEMBER, UCAL_UNDECIMBER
* @param date The desired day of the month.
* @param status A pointer to an UErrorCode to receive any errors
* @see ucal_getMillis
* @see ucal_setMillis
* @see ucal_setDateTime
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2
ucal_setDate(UCalendar* cal,
int32_t year,
int32_t month,
int32_t date,
UErrorCode* status);
/**
* Set a UCalendar's current date.
* The date is represented as a series of 32-bit integers.
* @param cal The UCalendar to set.
* @param year The desired year.
* @param month The desired month; one of UCAL_JANUARY, UCAL_FEBRUARY, UCAL_MARCH, UCAL_APRIL, UCAL_MAY,
* UCAL_JUNE, UCAL_JULY, UCAL_AUGUST, UCAL_SEPTEMBER, UCAL_OCTOBER, UCAL_NOVEMBER, UCAL_DECEMBER, UCAL_UNDECIMBER
* @param date The desired day of the month.
* @param hour The desired hour of day.
* @param minute The desired minute.
* @param second The desirec second.
* @param status A pointer to an UErrorCode to receive any errors
* @see ucal_getMillis
* @see ucal_setMillis
* @see ucal_setDate
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2
ucal_setDateTime(UCalendar* cal,
int32_t year,
int32_t month,
int32_t date,
int32_t hour,
int32_t minute,
int32_t second,
UErrorCode* status);
/**
* Returns TRUE if two UCalendars are equivalent. Equivalent
* UCalendars will behave identically, but they may be set to
* different times.
* @param cal1 The first of the UCalendars to compare.
* @param cal2 The second of the UCalendars to compare.
* @return TRUE if cal1 and cal2 are equivalent, FALSE otherwise.
* @stable ICU 2.0
*/
U_STABLE UBool U_EXPORT2
ucal_equivalentTo(const UCalendar* cal1,
const UCalendar* cal2);
/**
* Add a specified signed amount to a particular field in a UCalendar.
* This can modify more significant fields in the calendar.
* Adding a positive value always means moving forward in time, so for the Gregorian calendar,
* starting with 100 BC and adding +1 to year results in 99 BC (even though this actually reduces
* the numeric value of the field itself).
* @param cal The UCalendar to which to add.
* @param field The field to which to add the signed value; one of UCAL_ERA, UCAL_YEAR, UCAL_MONTH,
* UCAL_WEEK_OF_YEAR, UCAL_WEEK_OF_MONTH, UCAL_DATE, UCAL_DAY_OF_YEAR, UCAL_DAY_OF_WEEK,
* UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_AM_PM, UCAL_HOUR, UCAL_HOUR_OF_DAY, UCAL_MINUTE, UCAL_SECOND,
* UCAL_MILLISECOND, UCAL_ZONE_OFFSET, UCAL_DST_OFFSET.
* @param amount The signed amount to add to field. If the amount causes the value
* to exceed to maximum or minimum values for that field, other fields are modified
* to preserve the magnitude of the change.
* @param status A pointer to an UErrorCode to receive any errors
* @see ucal_roll
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2
ucal_add(UCalendar* cal,
UCalendarDateFields field,
int32_t amount,
UErrorCode* status);
/**
* Add a specified signed amount to a particular field in a UCalendar.
* This will not modify more significant fields in the calendar.
* Rolling by a positive value always means moving forward in time (unless the limit of the
* field is reached, in which case it may pin or wrap), so for Gregorian calendar,
* starting with 100 BC and rolling the year by +1 results in 99 BC.
* When eras have a definite beginning and end (as in the Chinese calendar, or as in most eras in the
* Japanese calendar) then rolling the year past either limit of the era will cause the year to wrap around.
* When eras only have a limit at one end, then attempting to roll the year past that limit will result in
* pinning the year at that limit. Note that for most calendars in which era 0 years move forward in time
* (such as Buddhist, Hebrew, or Islamic), it is possible for add or roll to result in negative years for
* era 0 (that is the only way to represent years before the calendar epoch).
* @param cal The UCalendar to which to add.
* @param field The field to which to add the signed value; one of UCAL_ERA, UCAL_YEAR, UCAL_MONTH,
* UCAL_WEEK_OF_YEAR, UCAL_WEEK_OF_MONTH, UCAL_DATE, UCAL_DAY_OF_YEAR, UCAL_DAY_OF_WEEK,
* UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_AM_PM, UCAL_HOUR, UCAL_HOUR_OF_DAY, UCAL_MINUTE, UCAL_SECOND,
* UCAL_MILLISECOND, UCAL_ZONE_OFFSET, UCAL_DST_OFFSET.
* @param amount The signed amount to add to field. If the amount causes the value
* to exceed to maximum or minimum values for that field, the field is pinned to a permissible
* value.
* @param status A pointer to an UErrorCode to receive any errors
* @see ucal_add
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2
ucal_roll(UCalendar* cal,
UCalendarDateFields field,
int32_t amount,
UErrorCode* status);
/**
* Get the current value of a field from a UCalendar.
* All fields are represented as 32-bit integers.
* @param cal The UCalendar to query.
* @param field The desired field; one of UCAL_ERA, UCAL_YEAR, UCAL_MONTH,
* UCAL_WEEK_OF_YEAR, UCAL_WEEK_OF_MONTH, UCAL_DATE, UCAL_DAY_OF_YEAR, UCAL_DAY_OF_WEEK,
* UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_AM_PM, UCAL_HOUR, UCAL_HOUR_OF_DAY, UCAL_MINUTE, UCAL_SECOND,
* UCAL_MILLISECOND, UCAL_ZONE_OFFSET, UCAL_DST_OFFSET.
* @param status A pointer to an UErrorCode to receive any errors
* @return The value of the desired field.
* @see ucal_set
* @see ucal_isSet
* @see ucal_clearField
* @see ucal_clear
* @stable ICU 2.0
*/
U_STABLE int32_t U_EXPORT2
ucal_get(const UCalendar* cal,
UCalendarDateFields field,
UErrorCode* status );
/**
* Set the value of a field in a UCalendar.
* All fields are represented as 32-bit integers.
* @param cal The UCalendar to set.
* @param field The field to set; one of UCAL_ERA, UCAL_YEAR, UCAL_MONTH,
* UCAL_WEEK_OF_YEAR, UCAL_WEEK_OF_MONTH, UCAL_DATE, UCAL_DAY_OF_YEAR, UCAL_DAY_OF_WEEK,
* UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_AM_PM, UCAL_HOUR, UCAL_HOUR_OF_DAY, UCAL_MINUTE, UCAL_SECOND,
* UCAL_MILLISECOND, UCAL_ZONE_OFFSET, UCAL_DST_OFFSET.
* @param value The desired value of field.
* @see ucal_get
* @see ucal_isSet
* @see ucal_clearField
* @see ucal_clear
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2
ucal_set(UCalendar* cal,
UCalendarDateFields field,
int32_t value);
/**
* Determine if a field in a UCalendar is set.
* All fields are represented as 32-bit integers.
* @param cal The UCalendar to query.
* @param field The desired field; one of UCAL_ERA, UCAL_YEAR, UCAL_MONTH,
* UCAL_WEEK_OF_YEAR, UCAL_WEEK_OF_MONTH, UCAL_DATE, UCAL_DAY_OF_YEAR, UCAL_DAY_OF_WEEK,
* UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_AM_PM, UCAL_HOUR, UCAL_HOUR_OF_DAY, UCAL_MINUTE, UCAL_SECOND,
* UCAL_MILLISECOND, UCAL_ZONE_OFFSET, UCAL_DST_OFFSET.
* @return TRUE if field is set, FALSE otherwise.
* @see ucal_get
* @see ucal_set
* @see ucal_clearField
* @see ucal_clear
* @stable ICU 2.0
*/
U_STABLE UBool U_EXPORT2
ucal_isSet(const UCalendar* cal,
UCalendarDateFields field);
/**
* Clear a field in a UCalendar.
* All fields are represented as 32-bit integers.
* @param cal The UCalendar containing the field to clear.
* @param field The field to clear; one of UCAL_ERA, UCAL_YEAR, UCAL_MONTH,
* UCAL_WEEK_OF_YEAR, UCAL_WEEK_OF_MONTH, UCAL_DATE, UCAL_DAY_OF_YEAR, UCAL_DAY_OF_WEEK,
* UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_AM_PM, UCAL_HOUR, UCAL_HOUR_OF_DAY, UCAL_MINUTE, UCAL_SECOND,
* UCAL_MILLISECOND, UCAL_ZONE_OFFSET, UCAL_DST_OFFSET.
* @see ucal_get
* @see ucal_set
* @see ucal_isSet
* @see ucal_clear
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2
ucal_clearField(UCalendar* cal,
UCalendarDateFields field);
/**
* Clear all fields in a UCalendar.
* All fields are represented as 32-bit integers.
* @param calendar The UCalendar to clear.
* @see ucal_get
* @see ucal_set
* @see ucal_isSet
* @see ucal_clearField
* @stable ICU 2.0
*/
U_STABLE void U_EXPORT2
ucal_clear(UCalendar* calendar);
/**
* Possible limit values for a UCalendar
* @stable ICU 2.0
*/
enum UCalendarLimitType {
/** Minimum value */
UCAL_MINIMUM,
/** Maximum value */
UCAL_MAXIMUM,
/** Greatest minimum value */
UCAL_GREATEST_MINIMUM,
/** Leaest maximum value */
UCAL_LEAST_MAXIMUM,
/** Actual minimum value */
UCAL_ACTUAL_MINIMUM,
/** Actual maximum value */
UCAL_ACTUAL_MAXIMUM
};
/** @stable ICU 2.0 */
typedef enum UCalendarLimitType UCalendarLimitType;
/**
* Determine a limit for a field in a UCalendar.
* A limit is a maximum or minimum value for a field.
* @param cal The UCalendar to query.
* @param field The desired field; one of UCAL_ERA, UCAL_YEAR, UCAL_MONTH,
* UCAL_WEEK_OF_YEAR, UCAL_WEEK_OF_MONTH, UCAL_DATE, UCAL_DAY_OF_YEAR, UCAL_DAY_OF_WEEK,
* UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_AM_PM, UCAL_HOUR, UCAL_HOUR_OF_DAY, UCAL_MINUTE, UCAL_SECOND,
* UCAL_MILLISECOND, UCAL_ZONE_OFFSET, UCAL_DST_OFFSET.
* @param type The desired critical point; one of UCAL_MINIMUM, UCAL_MAXIMUM, UCAL_GREATEST_MINIMUM,
* UCAL_LEAST_MAXIMUM, UCAL_ACTUAL_MINIMUM, UCAL_ACTUAL_MAXIMUM
* @param status A pointer to an UErrorCode to receive any errors.
* @return The requested value.
* @stable ICU 2.0
*/
U_STABLE int32_t U_EXPORT2
ucal_getLimit(const UCalendar* cal,
UCalendarDateFields field,
UCalendarLimitType type,
UErrorCode* status);
/** Get the locale for this calendar object. You can choose between valid and actual locale.
* @param cal The calendar object
* @param type type of the locale we're looking for (valid or actual)
* @param status error code for the operation
* @return the locale name
* @stable ICU 2.8
*/
U_STABLE const char * U_EXPORT2
ucal_getLocaleByType(const UCalendar *cal, ULocDataLocaleType type, UErrorCode* status);
/**
* Returns the timezone data version currently used by ICU.
* @param status error code for the operation
* @return the version string, such as "2007f"
* @stable ICU 3.8
*/
U_STABLE const char * U_EXPORT2
ucal_getTZDataVersion(UErrorCode* status);
/**
* Returns the canonical system timezone ID or the normalized
* custom time zone ID for the given time zone ID.
* @param id The input timezone ID to be canonicalized.
* @param len The length of id, or -1 if null-terminated.
* @param result The buffer receives the canonical system timezone ID
* or the custom timezone ID in normalized format.
* @param resultCapacity The capacity of the result buffer.
* @param isSystemID Receives if the given ID is a known system
* timezone ID.
* @param status Receives the status. When the given timezone ID
* is neither a known system time zone ID nor a
* valid custom timezone ID, U_ILLEGAL_ARGUMENT_ERROR
* is set.
* @return The result string length, not including the terminating
* null.
* @stable ICU 4.0
*/
U_STABLE int32_t U_EXPORT2
ucal_getCanonicalTimeZoneID(const UChar* id, int32_t len,
UChar* result, int32_t resultCapacity, UBool *isSystemID, UErrorCode* status);
/**
* Get the resource keyword value string designating the calendar type for the UCalendar.
* @param cal The UCalendar to query.
* @param status The error code for the operation.
* @return The resource keyword value string.
* @stable ICU 4.2
*/
U_STABLE const char * U_EXPORT2
ucal_getType(const UCalendar *cal, UErrorCode* status);
/**
* Given a key and a locale, returns an array of string values in a preferred
* order that would make a difference. These are all and only those values where
* the open (creation) of the service with the locale formed from the input locale
* plus input keyword and that value has different behavior than creation with the
* input locale alone.
* @param key one of the keys supported by this service. For now, only
* "calendar" is supported.
* @param locale the locale
* @param commonlyUsed if set to true it will return only commonly used values
* with the given locale in preferred order. Otherwise,
* it will return all the available values for the locale.
* @param status error status
* @return a string enumeration over keyword values for the given key and the locale.
* @stable ICU 4.2
*/
U_STABLE UEnumeration* U_EXPORT2
ucal_getKeywordValuesForLocale(const char* key,
const char* locale,
UBool commonlyUsed,
UErrorCode* status);
/** Weekday types, as returned by ucal_getDayOfWeekType().
* @stable ICU 4.4
*/
enum UCalendarWeekdayType {
/**
* Designates a full weekday (no part of the day is included in the weekend).
* @stable ICU 4.4
*/
UCAL_WEEKDAY,
/**
* Designates a full weekend day (the entire day is included in the weekend).
* @stable ICU 4.4
*/
UCAL_WEEKEND,
/**
* Designates a day that starts as a weekday and transitions to the weekend.
* Call ucal_getWeekendTransition() to get the time of transition.
* @stable ICU 4.4
*/
UCAL_WEEKEND_ONSET,
/**
* Designates a day that starts as the weekend and transitions to a weekday.
* Call ucal_getWeekendTransition() to get the time of transition.
* @stable ICU 4.4
*/
UCAL_WEEKEND_CEASE
};
/** @stable ICU 4.4 */
typedef enum UCalendarWeekdayType UCalendarWeekdayType;
/**
* Returns whether the given day of the week is a weekday, a weekend day,
* or a day that transitions from one to the other, for the locale and
* calendar system associated with this UCalendar (the locale's region is
* often the most determinant factor). If a transition occurs at midnight,
* then the days before and after the transition will have the
* type UCAL_WEEKDAY or UCAL_WEEKEND. If a transition occurs at a time
* other than midnight, then the day of the transition will have
* the type UCAL_WEEKEND_ONSET or UCAL_WEEKEND_CEASE. In this case, the
* function ucal_getWeekendTransition() will return the point of
* transition.
* @param cal The UCalendar to query.
* @param dayOfWeek The day of the week whose type is desired (UCAL_SUNDAY..UCAL_SATURDAY).
* @param status The error code for the operation.
* @return The UCalendarWeekdayType for the day of the week.
* @stable ICU 4.4
*/
U_STABLE UCalendarWeekdayType U_EXPORT2
ucal_getDayOfWeekType(const UCalendar *cal, UCalendarDaysOfWeek dayOfWeek, UErrorCode* status);
/**
* Returns the time during the day at which the weekend begins or ends in
* this calendar system. If ucal_getDayOfWeekType() returns UCAL_WEEKEND_ONSET
* for the specified dayOfWeek, return the time at which the weekend begins.
* If ucal_getDayOfWeekType() returns UCAL_WEEKEND_CEASE for the specified dayOfWeek,
* return the time at which the weekend ends. If ucal_getDayOfWeekType() returns
* some other UCalendarWeekdayType for the specified dayOfWeek, is it an error condition
* (U_ILLEGAL_ARGUMENT_ERROR).
* @param cal The UCalendar to query.
* @param dayOfWeek The day of the week for which the weekend transition time is
* desired (UCAL_SUNDAY..UCAL_SATURDAY).
* @param status The error code for the operation.
* @return The milliseconds after midnight at which the weekend begins or ends.
* @stable ICU 4.4
*/
U_STABLE int32_t U_EXPORT2
ucal_getWeekendTransition(const UCalendar *cal, UCalendarDaysOfWeek dayOfWeek, UErrorCode *status);
/**
* Returns TRUE if the given UDate is in the weekend in
* this calendar system.
* @param cal The UCalendar to query.
* @param date The UDate in question.
* @param status The error code for the operation.
* @return TRUE if the given UDate is in the weekend in
* this calendar system, FALSE otherwise.
* @stable ICU 4.4
*/
U_STABLE UBool U_EXPORT2
ucal_isWeekend(const UCalendar *cal, UDate date, UErrorCode *status);
/**
* Return the difference between the target time and the time this calendar object is currently set to.
* If the target time is after the current calendar setting, the the returned value will be positive.
* The field parameter specifies the units of the return value. For example, if field is UCAL_MONTH
* and ucal_getFieldDifference returns 3, then the target time is 3 to less than 4 months after the
* current calendar setting.
*
* As a side effect of this call, this calendar is advanced toward target by the given amount. That is,
* calling this function has the side effect of calling ucal_add on this calendar with the specified
* field and an amount equal to the return value from this function.
*
* A typical way of using this function is to call it first with the largest field of interest, then
* with progressively smaller fields.
*
* @param cal The UCalendar to compare and update.
* @param target The target date to compare to the current calendar setting.
* @param field The field to compare; one of UCAL_ERA, UCAL_YEAR, UCAL_MONTH,
* UCAL_WEEK_OF_YEAR, UCAL_WEEK_OF_MONTH, UCAL_DATE, UCAL_DAY_OF_YEAR, UCAL_DAY_OF_WEEK,
* UCAL_DAY_OF_WEEK_IN_MONTH, UCAL_AM_PM, UCAL_HOUR, UCAL_HOUR_OF_DAY, UCAL_MINUTE, UCAL_SECOND,
* UCAL_MILLISECOND, UCAL_ZONE_OFFSET, UCAL_DST_OFFSET.
* @param status A pointer to an UErrorCode to receive any errors
* @return The date difference for the specified field.
* @stable ICU 4.8
*/
U_STABLE int32_t U_EXPORT2
ucal_getFieldDifference(UCalendar* cal,
UDate target,
UCalendarDateFields field,
UErrorCode* status);
/**
* Time zone transition types for ucal_getTimeZoneTransitionDate
* @stable ICU 50
*/
enum UTimeZoneTransitionType {
/**
* Get the next transition after the current date,
* i.e. excludes the current date
* @stable ICU 50
*/
UCAL_TZ_TRANSITION_NEXT,
/**
* Get the next transition on or after the current date,
* i.e. may include the current date
* @stable ICU 50
*/
UCAL_TZ_TRANSITION_NEXT_INCLUSIVE,
/**
* Get the previous transition before the current date,
* i.e. excludes the current date
* @stable ICU 50
*/
UCAL_TZ_TRANSITION_PREVIOUS,
/**
* Get the previous transition on or before the current date,
* i.e. may include the current date
* @stable ICU 50
*/
UCAL_TZ_TRANSITION_PREVIOUS_INCLUSIVE
};
typedef enum UTimeZoneTransitionType UTimeZoneTransitionType; /**< @stable ICU 50 */
/**
* Get the UDate for the next/previous time zone transition relative to
* the calendar's current date, in the time zone to which the calendar
* is currently set. If there is no known time zone transition of the
* requested type relative to the calendar's date, the function returns
* FALSE.
* @param cal The UCalendar to query.
* @param type The type of transition desired.
* @param transition A pointer to a UDate to be set to the transition time.
* If the function returns FALSE, the value set is unspecified.
* @param status A pointer to a UErrorCode to receive any errors.
* @return TRUE if a valid transition time is set in *transition, FALSE
* otherwise.
* @stable ICU 50
*/
U_STABLE UBool U_EXPORT2
ucal_getTimeZoneTransitionDate(const UCalendar* cal, UTimeZoneTransitionType type,
UDate* transition, UErrorCode* status);
/**
* Converts a system time zone ID to an equivalent Windows time zone ID. For example,
* Windows time zone ID "Pacific Standard Time" is returned for input "America/Los_Angeles".
*
* <p>There are system time zones that cannot be mapped to Windows zones. When the input
* system time zone ID is unknown or unmappable to a Windows time zone, then this
* function returns 0 as the result length, but the operation itself remains successful
* (no error status set on return).
*
* <p>This implementation utilizes <a href="http://unicode.org/cldr/charts/supplemental/zone_tzid.html">
* Zone-Tzid mapping data</a>. The mapping data is updated time to time. To get the latest changes,
* please read the ICU user guide section <a href="http://userguide.icu-project.org/datetime/timezone#TOC-Updating-the-Time-Zone-Data">
* Updating the Time Zone Data</a>.
*
* @param id A system time zone ID.
* @param len The length of <code>id</code>, or -1 if null-terminated.
* @param winid A buffer to receive a Windows time zone ID.
* @param winidCapacity The capacity of the result buffer <code>winid</code>.
* @param status Receives the status.
* @return The result string length, not including the terminating null.
* @see ucal_getTimeZoneIDForWindowsID
*
* @stable ICU 52
*/
U_STABLE int32_t U_EXPORT2
ucal_getWindowsTimeZoneID(const UChar* id, int32_t len,
UChar* winid, int32_t winidCapacity, UErrorCode* status);
/**
* Converts a Windows time zone ID to an equivalent system time zone ID
* for a region. For example, system time zone ID "America/Los_Angeles" is returned
* for input Windows ID "Pacific Standard Time" and region "US" (or <code>null</code>),
* "America/Vancouver" is returned for the same Windows ID "Pacific Standard Time" and
* region "CA".
*
* <p>Not all Windows time zones can be mapped to system time zones. When the input
* Windows time zone ID is unknown or unmappable to a system time zone, then this
* function returns 0 as the result length, but the operation itself remains successful
* (no error status set on return).
*
* <p>This implementation utilizes <a href="http://unicode.org/cldr/charts/supplemental/zone_tzid.html">
* Zone-Tzid mapping data</a>. The mapping data is updated time to time. To get the latest changes,
* please read the ICU user guide section <a href="http://userguide.icu-project.org/datetime/timezone#TOC-Updating-the-Time-Zone-Data">
* Updating the Time Zone Data</a>.
*
* @param winid A Windows time zone ID.
* @param len The length of <code>winid</code>, or -1 if null-terminated.
* @param region A null-terminated region code, or <code>NULL</code> if no regional preference.
* @param id A buffer to receive a system time zone ID.
* @param idCapacity The capacity of the result buffer <code>id</code>.
* @param status Receives the status.
* @return The result string length, not including the terminating null.
* @see ucal_getWindowsTimeZoneID
*
* @stable ICU 52
*/
U_STABLE int32_t U_EXPORT2
ucal_getTimeZoneIDForWindowsID(const UChar* winid, int32_t len, const char* region,
UChar* id, int32_t idCapacity, UErrorCode* status);
#endif /* #if !UCONFIG_NO_FORMATTING */
#endif
| 35.540679 | 134 | 0.697615 | [
"object"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.