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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
c8c788804e7790b89b998c100e2d14d1aa324b56 | 1,703 | h | C | Web/WebGLExporter/vtkWebGLWidget.h | kaben/VTK | 6f1196980ac4d6187bc8069c5e2fd773d3e8524d | [
"BSD-3-Clause"
] | 1 | 2021-12-02T07:23:36.000Z | 2021-12-02T07:23:36.000Z | Web/WebGLExporter/vtkWebGLWidget.h | SINTEFMedtek/VTK | 6f1196980ac4d6187bc8069c5e2fd773d3e8524d | [
"BSD-3-Clause"
] | null | null | null | Web/WebGLExporter/vtkWebGLWidget.h | SINTEFMedtek/VTK | 6f1196980ac4d6187bc8069c5e2fd773d3e8524d | [
"BSD-3-Clause"
] | 1 | 2021-12-02T07:29:15.000Z | 2021-12-02T07:29:15.000Z | /*=========================================================================
Program: Visualization Toolkit
Module: vtkWebGLWidget.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.
=========================================================================*/
/**
* @class vtkWebGLWidget
*
* Widget representation for WebGL.
*/
#ifndef vtkWebGLWidget_h
#define vtkWebGLWidget_h
#include "vtkWebGLObject.h"
#include "vtkWebGLExporterModule.h" // needed for export macro
#include <vector> // Needed to store colors
class vtkActor2D;
class VTKWEBGLEXPORTER_EXPORT vtkWebGLWidget : public vtkWebGLObject
{
public:
static vtkWebGLWidget* New();
vtkTypeMacro(vtkWebGLWidget, vtkWebGLObject);
void PrintSelf(ostream &os, vtkIndent indent);
void GenerateBinaryData();
unsigned char* GetBinaryData(int part);
int GetBinarySize(int part);
int GetNumberOfParts();
void GetDataFromColorMap(vtkActor2D* actor);
protected:
vtkWebGLWidget();
~vtkWebGLWidget();
unsigned char* binaryData;
int binarySize;
int orientation;
char* title;
char* textFormat;
int textPosition;
float position[2];
float size[2];
int numberOfLabels;
std::vector <double*>colors; //x, r, g, b
private:
vtkWebGLWidget(const vtkWebGLWidget&) VTK_DELETE_FUNCTION;
void operator=(const vtkWebGLWidget&) VTK_DELETE_FUNCTION;
};
#endif
| 25.41791 | 75 | 0.671756 | [
"vector"
] |
c8c99a7ee048d61c0c97b2e19a807b513c0c1b60 | 42,253 | c | C | src/mice/src/cspice/zzhsc.c | jared711/meteoroid_orbits | 84428bc33a695fb4bebee383f5094b80ae1d7193 | [
"MIT"
] | 9 | 2018-03-28T16:03:28.000Z | 2022-01-30T20:36:00.000Z | src/mice/src/cspice/zzhsc.c | jared711/meteoroid_orbits | 84428bc33a695fb4bebee383f5094b80ae1d7193 | [
"MIT"
] | null | null | null | src/mice/src/cspice/zzhsc.c | jared711/meteoroid_orbits | 84428bc33a695fb4bebee383f5094b80ae1d7193 | [
"MIT"
] | 2 | 2021-01-25T10:11:10.000Z | 2022-01-09T06:37:06.000Z | /* zzhsc.f -- translated by f2c (version 19980913).
You must link the resulting object file with the libraries:
-lf2c -lm (in that order)
*/
#include "f2c.h"
/* $Procedure ZZHSC ( Private---Add-only Character Hash ) */
/* Subroutine */ int zzhsc_0_(int n__, integer *hashsz, integer *hedlst,
integer *collst, char *items, char *item, integer *itemat, logical *
new__, integer *avail, ftnlen items_len, ftnlen item_len)
{
/* System generated locals */
integer i__1;
/* Builtin functions */
integer s_cmp(char *, char *, ftnlen, ftnlen);
/* Subroutine */ int s_copy(char *, char *, ftnlen, ftnlen);
/* Local variables */
integer node;
logical full;
integer i__;
extern /* Subroutine */ int chkin_(char *, ftnlen), errch_(char *, char *,
ftnlen, ftnlen);
extern logical failed_(void);
logical lfound;
integer lookat;
extern /* Subroutine */ int sigerr_(char *, ftnlen), chkout_(char *,
ftnlen), setmsg_(char *, ftnlen);
extern logical return_(void);
extern integer zzhash2_(char *, integer *, ftnlen);
/* $ Abstract */
/* SPICE Private routine intended solely for the support of SPICE */
/* routines. Users should not call this routine directly due */
/* to the volatile nature of this routine. */
/* Manipulate add-only character hash. */
/* $ Disclaimer */
/* THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE */
/* CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S. */
/* GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE */
/* ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE */
/* PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS" */
/* TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY */
/* WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A */
/* PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC */
/* SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE */
/* SOFTWARE AND RELATED MATERIALS, HOWEVER USED. */
/* IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA */
/* BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT */
/* LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, */
/* INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS, */
/* REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE */
/* REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY. */
/* RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF */
/* THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY */
/* CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE */
/* ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE. */
/* $ Required_Reading */
/* None. */
/* $ Keywords */
/* PRIVATE UTILITY */
/* $ Declarations */
/* $ Brief_I/O */
/* Variable I/O Entry */
/* -------- --- -------------------------------------------------- */
/* HASHSZ I ZZHSCINI */
/* HEDLST I/O ZZHSCINI, ZZHSCADD, ZZHSCCHK, ZZHSCINF */
/* COLLST I/O ZZHSCINI, ZZHSCADD, ZZHSCCHK, ZZHSCAVL, ZZHSCINF */
/* ITEMS I/O ZZHSCINI, ZZHSCADD, ZZHSCCHK, ZZHSCINF */
/* ITEM I ZZHSCADD, ZZHSCCHK, ZZHSCINF */
/* ITEMAT O ZZHSCADD, ZZHSCCHK */
/* NEW O ZZHSCADD */
/* AVAIL O ZZHSCAVL, ZZHSCINF */
/* LBPOOL P (All) */
/* $ Detailed_Input */
/* See the ENTRY points for a discussion of their arguments. */
/* $ Detailed_Output */
/* See the ENTRY points for a discussion of their arguments. */
/* $ Parameters */
/* LBPOOL is the lower bound of the collision list array. */
/* $ Exceptions */
/* 1) If ZZHSC is called directly, the error SPICE(BOGUSENTRY) is */
/* signaled. */
/* $ Files */
/* None. */
/* $ Particulars */
/* ZZHSC should never be called directly, but should instead be */
/* accessed only through its entry points. */
/* The purpose of this routine is to manipulate add-only character */
/* hashes used for buffering purposes by various SPICE subsystems. */
/* This umbrella has the following entry points: */
/* ZZHSCINI Initialize a hash. */
/* ZZHSCADD Add an item to a hash. */
/* ZZHSCCHK Check if a item is in a hash. */
/* ZZHSCAVL Get available room in hash. */
/* ZZHSCINF Get h/k information about hash. */
/* An add-only hash consists of the head node pointer list (HEDLST), */
/* hash node collision list (COLLST), and the item list (ITEMS). */
/* The function ZZHASH2 computes the index of an element in the head */
/* node pointer list (HEDLST). */
/* The HEDLST element at this index contains either 0, indicating */
/* that there is not yet data for this hash value in the hash, or */
/* the index of the head node and its item in the hash collision */
/* (COLLST) and item (ITEMS) lists. */
/* The COLLST element at the head node index contain either 0, */
/* indicating that there is only one item for this hash value in the */
/* hash, or the index of the next node and its item in the hash */
/* collision (COLLST) and item (ITEMS) lists. */
/* The COLLST element at the next node index contain either 0, */
/* indicating that this is the last item for this hash value in the */
/* hash, or the index of the next node and its item in the hash */
/* collision (COLLST) and item (ITEMS) lists. */
/* And so on. */
/* Pictorially the hash looks like this: */
/* List of head List of hash List of */
/* nodes collisions items */
/* HEDLST COLLST ITEMS */
/* +---------+ */
/* | | */
/* +---------+ */
/* ... */
/* +---------+ */
/* | 1st Free| */
/* +---------+ */
/* | Size | */
/* +---------+ +---------+ +---------+ */
/* | | | | | | */
/* +---------+ !=0 +---------+ +---------+ */
/* .->|Head Node| -. | | | | */
/* | +---------+ | +---------+ +---------+ */
/* ZZHASH2(ITEM) | | | | | | | */
/* +---------+ | +---------+ +---------+ */
/* | | `->|Head of | |Item | */
/* | | |collision| !=0 |corresp. | */
/* | | |list for | -. |to head | */
/* | | | ITEM | | |of list | */
/* +---------+ +---------+ | +---------+ */
/* | | | | | | | */
/* +---------+ +---------+ | +---------+ */
/* | | | |<-' | | */
/* | | |Next Node| !=0 |Next Item| */
/* | | | |--. | | */
/* +---------+ +---------+ | +---------+ */
/* | | | | | | | */
/* +---------+ +---------+ | +---------+ */
/* | | | | | | | */
/* +---------+ +---------+ | +---------+ */
/* | | |Next Node|<-' |Next Item| */
/* +---------+ +---------+ etc +---------+ */
/* ... ... ... */
/* +---------+ +---------+ +---------+ */
/* | | | | | | */
/* +---------+ +---------+ +---------+ */
/* $ Examples */
/* An add-only hash used together with flat data arrays provides a */
/* simple, fast-access buffering mechanism. The subsystems that need */
/* such buffering would normally initialize the hash, add items to */
/* the hash and buffer data associated with items in flat data */
/* arrays, and find items in the hash and, if found, use buffered */
/* data associated with the items rather than computing/getting */
/* their data again. */
/* An add-only hash is normally used in one of the following ways -- */
/* set up to never be filled up, stop buffering when filled up, and */
/* trash when filled up and start buffering again. Three examples */
/* below illustrate each of these ways. */
/* Example 1: Set up to never be filled up */
/* --------------------------------------- */
/* C */
/* C Parameters: pool lower boundary, hash size and item */
/* C size. */
/* C */
/* INTEGER LBPOOL */
/* PARAMETER ( LBPOOL = -5 ) */
/* INTEGER HSHSIZ */
/* PARAMETER ( HSHSIS = 5003 ) */
/* INTEGER NAMSIZ */
/* PARAMETER ( NAMSIZ = 32 ) */
/* C */
/* C Hash arrays and data buffer. */
/* C */
/* INTEGER HEDLST ( HSHSIZ ) */
/* INTEGER COLLST ( LBPOOL : HSHSIZ ) */
/* CHARACTER*(NAMSIZ) ITEMS ( HSHSIZ ) */
/* INTEGER DATBUF ( HSHSIZ ) */
/* C */
/* C Miscellaneous variables. */
/* C */
/* CHARACTER*(NAMSIZ) ITEM */
/* INTEGER ITEMAT */
/* INTEGER MYDATA */
/* LOGICAL FIRST */
/* INTEGER AVAIL */
/* LOGICAL NEW */
/* C */
/* C Data items. */
/* C */
/* DATA FIRST / .TRUE. / */
/* C */
/* C Initialize hash. */
/* C */
/* IF ( FIRST ) THEN */
/* CALL ZZHSCINI ( HSHSIZ, HEDLST, COLLST ) */
/* FIRST = .FALSE. */
/* END IF */
/* ... */
/* C */
/* C Check for presence of or add an item to the hash. If the */
/* C item is in the hash, NEW will be .FALSE. If the item is */
/* C not in the hash, it will be added and NEW will be .TRUE. */
/* C This call can fail only if the hash fills up which */
/* C should not happen because it was declared to never fill */
/* C up. */
/* C */
/* CALL ZZHSCADD ( HEDLST, COLLST, ITEMS, ITEM, */
/* . ITEMAT, NEW ) */
/* IF ( FAILED() ) THEN */
/* RETURN */
/* END IF */
/* IF ( .NOT. NEW ) THEN */
/* C */
/* C Simply use buffered value. */
/* C */
/* MYDATA = DATBUF( ITEMAT ) */
/* ELSE */
/* C */
/* C Get value. */
/* C */
/* ... */
/* C */
/* C Buffer value. */
/* C */
/* DATBUF( ITEMAT ) = MYDATA */
/* END IF */
/* Example 2: Stop buffering when filled up */
/* ---------------------------------------- */
/* C */
/* C Use the same declarations as the first example. */
/* C */
/* ... */
/* C */
/* C Initialize hash. */
/* C */
/* IF ( FIRST ) THEN */
/* CALL ZZHSCINI ( HSHSIZ, HEDLST, COLLST ) */
/* FIRST = .FALSE. */
/* END IF */
/* ... */
/* C */
/* C Check if this item is in the hash. */
/* C */
/* CALL ZZHSCCHK ( HEDLST, COLLST, ITEMS, ITEM, ITEMAT ) */
/* IF ( ITEMAT .NE. 0 ) THEN */
/* C */
/* C Simply use buffered value. */
/* C */
/* MYDATA = DATBUF( ITEMAT ) */
/* ELSE */
/* C */
/* C Get value. */
/* C */
/* ... */
/* C */
/* C Buffer value, but only if the hash is not full. */
/* C */
/* CALL ZZHSCAVL( COLLST, AVAIL ) */
/* IF ( AVAIL .GT. 0 ) THEN */
/* CALL ZZHSCADD ( HEDLST, COLLST, ITEMS, ITEM, */
/* . ITEMAT, NEW ) */
/* DATBUF( ITEMAT ) = MYDATA */
/* END IF */
/* END IF */
/* Example 3: Trash when filled up and start buffering again */
/* --------------------------------------------------------- */
/* C */
/* C Use the same declarations as the first example. */
/* C */
/* ... */
/* C */
/* C Initialize hash. */
/* C */
/* IF ( FIRST ) THEN */
/* CALL ZZHSCINI ( HSHSIZ, HEDLST, COLLST ) */
/* FIRST = .FALSE. */
/* END IF */
/* ... */
/* C */
/* C Check if this item is in the hash. */
/* C */
/* CALL ZZHSCCHK ( HEDLST, COLLST, ITEMS, ITEM, ITEMAT ) */
/* IF ( ITEMAT .NE. 0 ) THEN */
/* C */
/* C Simply use buffered value. */
/* C */
/* MYDATA = DATBUF( ITEMAT ) */
/* ELSE */
/* C */
/* C Get value. */
/* C */
/* ... */
/* C */
/* C Buffer value, if the hash is full trash re-initialize */
/* C it first. */
/* C */
/* CALL ZZHSCAVL( COLLST, AVAIL ) */
/* IF ( AVAIL .LE. 0 ) THEN */
/* CALL ZZHSCINI ( HSHSIZ, HEDLST, COLLST ) */
/* END IF */
/* CALL ZZHSCADD ( HEDLST, COLLST, ITEMS, ITEM, */
/* . ITEMAT, NEW ) */
/* DATBUF( ITEMAT ) = MYDATA */
/* END IF */
/* $ Restrictions */
/* For sake of speed all entry points do no or minimal error */
/* checking. It is the responsibility of the caller to ensure that */
/* all inputs are properly initialized. */
/* $ Literature_References */
/* None. */
/* $ Author_and_Institution */
/* B.V. Semenov (JPL) */
/* $ Version */
/* - SPICELIB Version 1.0.0, 31-JUL-2013 (BVS) */
/* -& */
/* $ Index_Entries */
/* manipulate add-only character hash */
/* -& */
/* Hash control area items. */
/* SPICELIB functions. */
/* Local variables. */
/* Standard SPICE error handling. */
/* Parameter adjustments */
if (hedlst) {
}
if (items) {
}
/* Function Body */
switch(n__) {
case 1: goto L_zzhscini;
case 2: goto L_zzhscadd;
case 3: goto L_zzhscchk;
case 4: goto L_zzhscavl;
case 5: goto L_zzhscinf;
}
if (return_()) {
return 0;
} else {
chkin_("ZZHSC", (ftnlen)5);
}
/* Signal bogus entry error and check out. */
sigerr_("BOGUSENTRY", (ftnlen)10);
chkout_("ZZHSC", (ftnlen)5);
return 0;
/* $Procedure ZZHSCINI ( Private---Initialize Add-only Character Hash ) */
L_zzhscini:
/* $ Abstract */
/* SPICE Private routine intended solely for the support of SPICE */
/* routines. Users should not call this routine directly due */
/* to the volatile nature of this routine. */
/* Initialize an add-only character hash. */
/* $ Disclaimer */
/* THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE */
/* CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S. */
/* GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE */
/* ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE */
/* PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS" */
/* TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY */
/* WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A */
/* PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC */
/* SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE */
/* SOFTWARE AND RELATED MATERIALS, HOWEVER USED. */
/* IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA */
/* BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT */
/* LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, */
/* INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS, */
/* REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE */
/* REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY. */
/* RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF */
/* THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY */
/* CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE */
/* ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE. */
/* $ Required_Reading */
/* None. */
/* $ Keywords */
/* PRIVATE UTILITY */
/* $ Declarations */
/* INTEGER LBPOOL */
/* PARAMETER ( LBPOOL = -5 ) */
/* INTEGER HASHSZ */
/* INTEGER HEDLST ( * ) */
/* INTEGER COLLST ( LBPOOL : * ) */
/* $ Brief_I/O */
/* Variable I/O Entry */
/* -------- --- -------------------------------------------------- */
/* HASHSZ I Hash size */
/* HEDLST I/O Hash head node pointer list */
/* COLLST I/O Hash node collision list */
/* LBPOOL P Collision list array lower bound */
/* $ Detailed_Input */
/* HASHSZ is the hash size. For efficiency reasons it must be a */
/* prime number in the range from 1 to INTMAX/68 - 1. */
/* HEDLST */
/* COLLST are the head node pointer list and the node collision */
/* list components of an add-only character hash. */
/* $ Detailed_Output */
/* HEDLST */
/* COLLST are the head node pointer list and the node collision */
/* list components of an add-only character hash with all */
/* elements of the head node pointer list HEDLST set to */
/* zero and size and first-free elements of the head */
/* node pointer list COLLST set to HASHSZ and 1 */
/* correspondingly. */
/* $ Parameters */
/* LBPOOL is the lower bound of the collision list array. */
/* $ Exceptions */
/* 1) If HASHSZ is less than 1 or greater than the value that is */
/* guaranteed not to result in eventual integer overflow in */
/* ZZHASH2, the error will be signaled by ZZHASH2. */
/* $ Files */
/* None. */
/* $ Particulars */
/* See the header of the umbrella routine ZZHSC. */
/* $ Examples */
/* See the header of the umbrella routine ZZHSC. */
/* $ Restrictions */
/* See the header of the umbrella routine ZZHSC. */
/* $ Literature_References */
/* None. */
/* $ Author_and_Institution */
/* B.V. Semenov (JPL) */
/* $ Version */
/* - SPICELIB Version 1.0.0, 31-JUL-2013 (BVS) */
/* -& */
/* $ Index_Entries */
/* initialize add-only character hash */
/* -& */
/* Standard SPICE error handling. */
if (return_()) {
return 0;
}
chkin_("ZZHSCINI", (ftnlen)8);
/* The requested number of nodes must be in the valid range. If it */
/* is not, ZZHASH2 will signal an error. */
i__ = zzhash2_(" ", hashsz, (ftnlen)1);
if (failed_()) {
chkout_("ZZHSCINI", (ftnlen)8);
return 0;
}
/* Wipe out head node pointer list. */
i__1 = *hashsz;
for (i__ = 1; i__ <= i__1; ++i__) {
hedlst[i__ - 1] = 0;
}
/* Reset control area. */
collst[5] = *hashsz;
collst[4] = 1;
chkout_("ZZHSCINI", (ftnlen)8);
return 0;
/* $Procedure ZZHSCADD ( Private---Add Item to Add-only Character Hash ) */
L_zzhscadd:
/* $ Abstract */
/* SPICE Private routine intended solely for the support of SPICE */
/* routines. Users should not call this routine directly due */
/* to the volatile nature of this routine. */
/* Find or add, if not present, an item to an add-only character */
/* hash. */
/* $ Disclaimer */
/* THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE */
/* CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S. */
/* GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE */
/* ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE */
/* PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS" */
/* TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY */
/* WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A */
/* PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC */
/* SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE */
/* SOFTWARE AND RELATED MATERIALS, HOWEVER USED. */
/* IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA */
/* BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT */
/* LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, */
/* INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS, */
/* REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE */
/* REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY. */
/* RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF */
/* THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY */
/* CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE */
/* ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE. */
/* $ Required_Reading */
/* None. */
/* $ Keywords */
/* PRIVATE UTILITY */
/* $ Declarations */
/* INTEGER LBPOOL */
/* PARAMETER ( LBPOOL = -5 ) */
/* INTEGER HEDLST ( * ) */
/* INTEGER COLLST ( LBPOOL : * ) */
/* CHARACTER*(*) ITEMS ( * ) */
/* CHARACTER*(*) ITEM */
/* INTEGER ITEMAT */
/* LOGICAL NEW */
/* $ Brief_I/O */
/* Variable I/O Entry */
/* -------- --- -------------------------------------------------- */
/* HEDLST I/O Hash head node pointer list */
/* COLLST I/O Hash node collision list */
/* ITEMS I/O Hash item list */
/* ITEM I Item to be checked for/added */
/* ITEMAT O Item index in node collision and item lists */
/* NEW O Flag indicting if item was added */
/* LBPOOL P Collision list array lower bound */
/* $ Detailed_Input */
/* HEDLST */
/* COLLST */
/* ITEMS are the components of an add-only character */
/* hash. */
/* ITEM is an item to find and, if needed, add to the hash. */
/* $ Detailed_Output */
/* HEDLST */
/* COLLST */
/* ITEMS are the components of an add-only character */
/* hash with the new item added to it if needed. */
/* ITEMAT is the index of the item in the node collision and */
/* item lists. If the item could not be found in or */
/* added to the hash, ITEMAT is set to 0. */
/* NEW is a flag indicting if item was added to the hash. */
/* $ Parameters */
/* LBPOOL is the lower bound of the collision list array. */
/* $ Exceptions */
/* 1) If the hash is full, the error SPICE(HASHISFULL) is signaled. */
/* $ Files */
/* None. */
/* $ Particulars */
/* See the header of the umbrella routine ZZHSC. */
/* $ Examples */
/* See the header of the umbrella routine ZZHSC. */
/* $ Restrictions */
/* See the header of the umbrella routine ZZHSC. */
/* $ Literature_References */
/* None. */
/* $ Author_and_Institution */
/* B.V. Semenov (JPL) */
/* $ Version */
/* - SPICELIB Version 1.0.0, 31-JUL-2013 (BVS) */
/* -& */
/* $ Index_Entries */
/* add an item to add-only character hash */
/* -& */
/* Standard SPICE error handling. No checking-in here. We will do it */
/* when we have to. */
if (return_()) {
return 0;
}
/* Set flag indicating whether the hash is full. */
full = collst[4] > collst[5];
/* Use hash function to get index of the head node. */
lookat = zzhash2_(item, &collst[5], item_len);
node = hedlst[lookat - 1];
/* Set initial values. */
lfound = FALSE_;
*new__ = FALSE_;
/* See if this item (or one colliding with it in the hash scheme) */
/* has already been stored in the item list. */
if (node > 0) {
/* Start at the head node and check each item saved for this hash */
/* value until we find a item that matches or run out of items in */
/* this conflict resolution list. */
while(node > 0 && ! lfound) {
lfound = s_cmp(items + (node - 1) * items_len, item, items_len,
item_len) == 0;
*itemat = node;
node = collst[node + 5];
}
/* If we didn't find this item on the conflict resolution list */
/* and our hash is not full we will add this item to it. */
if (! lfound && ! full) {
/* Get next free node. */
node = collst[4];
/* Increment next free node pointer. */
++collst[4];
/* Set current node pointer to the node we just picked for */
/* this item. */
collst[*itemat + 5] = node;
/* Set new node pointer to 0, just in case. */
collst[node + 5] = 0;
/* Save item. */
s_copy(items + (node - 1) * items_len, item, items_len, item_len);
/* Set output node ID and new and found flags. */
*itemat = node;
*new__ = TRUE_;
lfound = TRUE_;
}
} else if (! full) {
/* Nothing like this item (in the hashing sense) has been stored */
/* so far and the hash is not full. */
/* Get next free node. */
node = collst[4];
/* Increment next free node pointer. */
++collst[4];
/* Set new node pointer to 0, just in case. */
collst[node + 5] = 0;
/* Set the head node pointer to this node. */
hedlst[lookat - 1] = node;
/* Save item. */
s_copy(items + (node - 1) * items_len, item, items_len, item_len);
/* Set output node ID and new and found flags. */
*itemat = node;
*new__ = TRUE_;
lfound = TRUE_;
}
/* Set ITEMAT to 0 if LFOUND is FALSE. */
if (! lfound) {
*itemat = 0;
}
/* If the item hash was full and we didn't find this item we've got */
/* an error. Report it and return. */
if (full && ! lfound) {
chkin_("ZZHSCADD", (ftnlen)8);
setmsg_("The hash has no room for any more items.", (ftnlen)40);
sigerr_("SPICE(HASHISFULL)", (ftnlen)17);
chkout_("ZZHSCADD", (ftnlen)8);
return 0;
}
return 0;
/* $Procedure ZZHSCCHK ( Private---Find Item in Add-only Character Hash ) */
L_zzhscchk:
/* $ Abstract */
/* SPICE Private routine intended solely for the support of SPICE */
/* routines. Users should not call this routine directly due */
/* to the volatile nature of this routine. */
/* Find an item in an add-only character hash. */
/* $ Disclaimer */
/* THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE */
/* CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S. */
/* GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE */
/* ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE */
/* PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS" */
/* TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY */
/* WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A */
/* PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC */
/* SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE */
/* SOFTWARE AND RELATED MATERIALS, HOWEVER USED. */
/* IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA */
/* BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT */
/* LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, */
/* INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS, */
/* REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE */
/* REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY. */
/* RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF */
/* THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY */
/* CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE */
/* ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE. */
/* $ Required_Reading */
/* None. */
/* $ Keywords */
/* PRIVATE UTILITY */
/* $ Declarations */
/* INTEGER LBPOOL */
/* PARAMETER ( LBPOOL = -5 ) */
/* INTEGER HEDLST ( * ) */
/* INTEGER COLLST ( LBPOOL : * ) */
/* CHARACTER*(*) ITEMS ( * ) */
/* CHARACTER*(*) ITEM */
/* INTEGER ITEMAT */
/* $ Brief_I/O */
/* Variable I/O Entry */
/* -------- --- -------------------------------------------------- */
/* HEDLST I Hash head node pointer list */
/* COLLST I Hash node collision list */
/* ITEMS I Hash item list */
/* ITEM I Item to find */
/* ITEMAT O Item index in node collision and item lists */
/* LBPOOL P Collision list array lower bound */
/* $ Detailed_Input */
/* HEDLST */
/* COLLST */
/* ITEMS are the components of an add-only character */
/* hash. */
/* ITEM is an item to find in the hash. */
/* $ Detailed_Output */
/* ITEMAT is the index of the item in the node collision and */
/* item lists. If item is not in the hash, ITEMAT is set */
/* to 0. */
/* $ Parameters */
/* LBPOOL is the lower bound of the collision list array. */
/* $ Exceptions */
/* Error free. */
/* $ Files */
/* None. */
/* $ Particulars */
/* See the header of the umbrella routine ZZHSC. */
/* $ Examples */
/* See the header of the umbrella routine ZZHSC. */
/* $ Restrictions */
/* See the header of the umbrella routine ZZHSC. */
/* $ Literature_References */
/* None. */
/* $ Author_and_Institution */
/* B.V. Semenov (JPL) */
/* $ Version */
/* - SPICELIB Version 1.0.0, 31-JUL-2013 (BVS) */
/* -& */
/* $ Index_Entries */
/* find item in add-only character hash */
/* -& */
/* Standard SPICE error handling. */
if (return_()) {
return 0;
}
/* Use hash function to get index of the head node. */
lookat = zzhash2_(item, &collst[5], item_len);
node = hedlst[lookat - 1];
/* Set initial values. */
lfound = FALSE_;
/* See if this item (or one colliding with it in the hash scheme) is */
/* in the item list. */
if (node > 0) {
/* Start at the head node and check each item saved for this hash */
/* value until we find a item that matches or run out of items in */
/* this conflict resolution list. */
while(node > 0 && ! lfound) {
lfound = s_cmp(items + (node - 1) * items_len, item, items_len,
item_len) == 0;
*itemat = node;
node = collst[node + 5];
}
}
/* If LFOUND is false, set ITEMAT to 0. */
if (! lfound) {
*itemat = 0;
}
return 0;
/* $Procedure ZZHSCAVL ( Private---Get room available in Add-only Hash ) */
L_zzhscavl:
/* $ Abstract */
/* SPICE Private routine intended solely for the support of SPICE */
/* routines. Users should not call this routine directly due */
/* to the volatile nature of this routine. */
/* Get room available in an add-only character hash. */
/* $ Disclaimer */
/* THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE */
/* CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S. */
/* GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE */
/* ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE */
/* PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS" */
/* TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY */
/* WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A */
/* PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC */
/* SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE */
/* SOFTWARE AND RELATED MATERIALS, HOWEVER USED. */
/* IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA */
/* BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT */
/* LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, */
/* INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS, */
/* REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE */
/* REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY. */
/* RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF */
/* THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY */
/* CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE */
/* ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE. */
/* $ Required_Reading */
/* None. */
/* $ Keywords */
/* PRIVATE UTILITY */
/* $ Declarations */
/* INTEGER LBPOOL */
/* PARAMETER ( LBPOOL = -5 ) */
/* INTEGER COLLST ( LBPOOL : * ) */
/* INTEGER AVAIL */
/* $ Brief_I/O */
/* Variable I/O Entry */
/* -------- --- -------------------------------------------------- */
/* COLLST I Hash node collision list */
/* AVAIL O Room available in the hash */
/* LBPOOL P Collision list array lower bound */
/* $ Detailed_Input */
/* COLLST is the add-only character hash node collision */
/* list. */
/* $ Detailed_Output */
/* AVAIL is the room (number of vacant slots) available in */
/* the hash. */
/* $ Parameters */
/* LBPOOL is the lower bound of the collision list array. */
/* $ Exceptions */
/* Error free. */
/* $ Files */
/* None. */
/* $ Particulars */
/* See the header of the umbrella routine ZZHSC. */
/* $ Examples */
/* See the header of the umbrella routine ZZHSC. */
/* $ Restrictions */
/* See the header of the umbrella routine ZZHSC. */
/* $ Literature_References */
/* None. */
/* $ Author_and_Institution */
/* B.V. Semenov (JPL) */
/* $ Version */
/* - SPICELIB Version 1.0.0, 31-JUL-2013 (BVS) */
/* -& */
/* $ Index_Entries */
/* get room available in add-only character hash */
/* -& */
/* Set the number of unoccupied slots in the hash. */
*avail = collst[5] - collst[4] + 1;
return 0;
/* $Procedure ZZHSCINF ( Private---Get Information about Add-only Hash ) */
L_zzhscinf:
/* $ Abstract */
/* SPICE Private routine intended solely for the support of SPICE */
/* routines. Users should not call this routine directly due */
/* to the volatile nature of this routine. */
/* Get information about an add-only character hash. */
/* $ Disclaimer */
/* THIS SOFTWARE AND ANY RELATED MATERIALS WERE CREATED BY THE */
/* CALIFORNIA INSTITUTE OF TECHNOLOGY (CALTECH) UNDER A U.S. */
/* GOVERNMENT CONTRACT WITH THE NATIONAL AERONAUTICS AND SPACE */
/* ADMINISTRATION (NASA). THE SOFTWARE IS TECHNOLOGY AND SOFTWARE */
/* PUBLICLY AVAILABLE UNDER U.S. EXPORT LAWS AND IS PROVIDED "AS-IS" */
/* TO THE RECIPIENT WITHOUT WARRANTY OF ANY KIND, INCLUDING ANY */
/* WARRANTIES OF PERFORMANCE OR MERCHANTABILITY OR FITNESS FOR A */
/* PARTICULAR USE OR PURPOSE (AS SET FORTH IN UNITED STATES UCC */
/* SECTIONS 2312-2313) OR FOR ANY PURPOSE WHATSOEVER, FOR THE */
/* SOFTWARE AND RELATED MATERIALS, HOWEVER USED. */
/* IN NO EVENT SHALL CALTECH, ITS JET PROPULSION LABORATORY, OR NASA */
/* BE LIABLE FOR ANY DAMAGES AND/OR COSTS, INCLUDING, BUT NOT */
/* LIMITED TO, INCIDENTAL OR CONSEQUENTIAL DAMAGES OF ANY KIND, */
/* INCLUDING ECONOMIC DAMAGE OR INJURY TO PROPERTY AND LOST PROFITS, */
/* REGARDLESS OF WHETHER CALTECH, JPL, OR NASA BE ADVISED, HAVE */
/* REASON TO KNOW, OR, IN FACT, SHALL KNOW OF THE POSSIBILITY. */
/* RECIPIENT BEARS ALL RISK RELATING TO QUALITY AND PERFORMANCE OF */
/* THE SOFTWARE AND ANY RELATED MATERIALS, AND AGREES TO INDEMNIFY */
/* CALTECH AND NASA FOR ALL THIRD-PARTY CLAIMS RESULTING FROM THE */
/* ACTIONS OF RECIPIENT IN THE USE OF THE SOFTWARE. */
/* $ Required_Reading */
/* None. */
/* $ Keywords */
/* PRIVATE UTILITY */
/* $ Declarations */
/* INTEGER LBPOOL */
/* PARAMETER ( LBPOOL = -5 ) */
/* INTEGER HEDLST ( * ) */
/* INTEGER COLLST ( LBPOOL : * ) */
/* CHARACTER*(*) ITEMS ( * ) */
/* CHARACTER*(*) ITEM */
/* INTEGER AVAIL */
/* $ Brief_I/O */
/* Variable I/O Entry */
/* -------- --- -------------------------------------------------- */
/* HEDLST I Hash head node pointer list */
/* COLLST I Hash node collision list */
/* ITEMS I Hash item list */
/* ITEM I parameter to report */
/* AVAIL O parameter Value */
/* LBPOOL P Collision list array lower bound */
/* $ Detailed_Input */
/* HEDLST */
/* COLLST */
/* ITEMS are the components of an add-only character */
/* hash. */
/* ITEM is the parameter to report: */
/* 'HASH SIZE' */
/* 'USED HEADNODE COUNT' */
/* 'UNUSED HEADNODE COUNT' */
/* 'USED ITEM COUNT' */
/* 'UNUSED ITEM COUNT' */
/* 'LONGEST LIST SIZE' */
/* $ Detailed_Output */
/* AVAIL is the value of the parameter of interest. */
/* $ Parameters */
/* LBPOOL is the lower bound of the collision list array. */
/* $ Exceptions */
/* 1) If the input ITEM is not recognized, the error */
/* SPICE(ITEMNOTRECOGNIZED) is signaled. */
/* $ Files */
/* None. */
/* $ Particulars */
/* See the header of the umbrella routine ZZHSC. */
/* $ Examples */
/* None. */
/* $ Restrictions */
/* See the header of the umbrella routine ZZHSC. */
/* $ Literature_References */
/* None. */
/* $ Author_and_Institution */
/* B.V. Semenov (JPL) */
/* $ Version */
/* - SPICELIB Version 1.0.0, 31-JUL-2013 (BVS) */
/* -& */
/* $ Index_Entries */
/* get information about add-only character hash */
/* -& */
/* Get the hash size. */
if (s_cmp(item, "HASH SIZE", item_len, (ftnlen)9) == 0) {
*avail = collst[5];
/* Get the count of used nodes in the head list. */
} else if (s_cmp(item, "USED HEADNODE COUNT", item_len, (ftnlen)19) == 0)
{
*avail = 0;
i__1 = collst[5];
for (i__ = 1; i__ <= i__1; ++i__) {
if (hedlst[i__ - 1] != 0) {
++(*avail);
}
}
/* Get the count of unused nodes in the head list. */
} else if (s_cmp(item, "UNUSED HEADNODE COUNT", item_len, (ftnlen)21) ==
0) {
*avail = 0;
i__1 = collst[5];
for (i__ = 1; i__ <= i__1; ++i__) {
if (hedlst[i__ - 1] == 0) {
++(*avail);
}
}
/* Get the count of used slots in the item list. */
} else if (s_cmp(item, "USED ITEM COUNT", item_len, (ftnlen)15) == 0) {
*avail = collst[4] - 1;
/* Get the count of unused slots in the item list. */
} else if (s_cmp(item, "UNUSED ITEM COUNT", item_len, (ftnlen)17) == 0) {
*avail = collst[5] - collst[4] + 1;
/* Get the size of the longest item list for any hash value. */
} else if (s_cmp(item, "LONGEST LIST SIZE", item_len, (ftnlen)17) == 0) {
*avail = 0;
i__1 = collst[5];
for (i__ = 1; i__ <= i__1; ++i__) {
node = hedlst[i__ - 1];
lookat = 0;
while(node > 0) {
++lookat;
node = collst[node + 5];
}
*avail = max(*avail,lookat);
}
/* This parameter is not supported. */
} else {
*avail = 0;
chkin_("ZZHSCINF", (ftnlen)8);
setmsg_("Parameter '#' is not recognized.", (ftnlen)32);
errch_("#", item, (ftnlen)1, item_len);
sigerr_("SPICE(ITEMNOTRECOGNIZED)", (ftnlen)24);
chkout_("ZZHSCINF", (ftnlen)8);
}
return 0;
} /* zzhsc_ */
/* Subroutine */ int zzhsc_(integer *hashsz, integer *hedlst, integer *collst,
char *items, char *item, integer *itemat, logical *new__, integer *
avail, ftnlen items_len, ftnlen item_len)
{
return zzhsc_0_(0, hashsz, hedlst, collst, items, item, itemat, new__,
avail, items_len, item_len);
}
/* Subroutine */ int zzhscini_(integer *hashsz, integer *hedlst, integer *
collst)
{
return zzhsc_0_(1, hashsz, hedlst, collst, (char *)0, (char *)0, (integer
*)0, (logical *)0, (integer *)0, (ftnint)0, (ftnint)0);
}
/* Subroutine */ int zzhscadd_(integer *hedlst, integer *collst, char *items,
char *item, integer *itemat, logical *new__, ftnlen items_len, ftnlen
item_len)
{
return zzhsc_0_(2, (integer *)0, hedlst, collst, items, item, itemat,
new__, (integer *)0, items_len, item_len);
}
/* Subroutine */ int zzhscchk_(integer *hedlst, integer *collst, char *items,
char *item, integer *itemat, ftnlen items_len, ftnlen item_len)
{
return zzhsc_0_(3, (integer *)0, hedlst, collst, items, item, itemat, (
logical *)0, (integer *)0, items_len, item_len);
}
/* Subroutine */ int zzhscavl_(integer *collst, integer *avail)
{
return zzhsc_0_(4, (integer *)0, (integer *)0, collst, (char *)0, (char *)
0, (integer *)0, (logical *)0, avail, (ftnint)0, (ftnint)0);
}
/* Subroutine */ int zzhscinf_(integer *hedlst, integer *collst, char *items,
char *item, integer *avail, ftnlen items_len, ftnlen item_len)
{
return zzhsc_0_(5, (integer *)0, hedlst, collst, items, item, (integer *)
0, (logical *)0, avail, items_len, item_len);
}
| 30.640319 | 78 | 0.527939 | [
"object"
] |
c8ca0274477543114251e8fc81c7b00f2a60f13f | 9,332 | h | C | 3rd/xulrunner-sdk/include/mozilla/dom/TabParent.h | ShoufuLuo/csaw | 0d030d5ab93e61b62dff10b27a15c83fcfce3ff3 | [
"Apache-2.0"
] | null | null | null | 3rd/xulrunner-sdk/include/mozilla/dom/TabParent.h | ShoufuLuo/csaw | 0d030d5ab93e61b62dff10b27a15c83fcfce3ff3 | [
"Apache-2.0"
] | null | null | null | 3rd/xulrunner-sdk/include/mozilla/dom/TabParent.h | ShoufuLuo/csaw | 0d030d5ab93e61b62dff10b27a15c83fcfce3ff3 | [
"Apache-2.0"
] | null | null | null | /* -*- Mode: C++; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* vim: set sw=4 ts=8 et tw=80 : */
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
* http://www.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Mozilla Content App.
*
* The Initial Developer of the Original Code is
* The Mozilla Foundation.
* Portions created by the Initial Developer are Copyright (C) 2009
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
#ifndef mozilla_tabs_TabParent_h
#define mozilla_tabs_TabParent_h
#include "mozilla/dom/PBrowserParent.h"
#include "mozilla/dom/PContentDialogParent.h"
#include "mozilla/ipc/GeckoChildProcessHost.h"
#include "jsapi.h"
#include "nsCOMPtr.h"
#include "nsITabParent.h"
#include "nsIBrowserDOMWindow.h"
#include "nsWeakReference.h"
#include "nsIDialogParamBlock.h"
#include "nsIAuthPromptProvider.h"
#include "nsISecureBrowserUI.h"
class nsFrameLoader;
class nsIURI;
class nsIDOMElement;
struct gfxMatrix;
struct JSContext;
struct JSObject;
namespace mozilla {
namespace dom {
class ContentDialogParent : public PContentDialogParent {};
class TabParent : public PBrowserParent
, public nsITabParent
, public nsIAuthPromptProvider
, public nsISecureBrowserUI
{
public:
TabParent();
virtual ~TabParent();
nsIDOMElement* GetOwnerElement() { return mFrameElement; }
void SetOwnerElement(nsIDOMElement* aElement);
nsIBrowserDOMWindow *GetBrowserDOMWindow() { return mBrowserDOMWindow; }
void SetBrowserDOMWindow(nsIBrowserDOMWindow* aBrowserDOMWindow) {
mBrowserDOMWindow = aBrowserDOMWindow;
}
void Destroy();
virtual bool RecvMoveFocus(const bool& aForward);
virtual bool RecvEvent(const RemoteDOMEvent& aEvent);
virtual bool AnswerCreateWindow(PBrowserParent** retval);
virtual bool RecvSyncMessage(const nsString& aMessage,
const nsString& aJSON,
InfallibleTArray<nsString>* aJSONRetVal);
virtual bool RecvAsyncMessage(const nsString& aMessage,
const nsString& aJSON);
virtual bool RecvNotifyIMEFocus(const PRBool& aFocus,
nsIMEUpdatePreference* aPreference,
PRUint32* aSeqno);
virtual bool RecvNotifyIMETextChange(const PRUint32& aStart,
const PRUint32& aEnd,
const PRUint32& aNewEnd);
virtual bool RecvNotifyIMESelection(const PRUint32& aSeqno,
const PRUint32& aAnchor,
const PRUint32& aFocus);
virtual bool RecvNotifyIMETextHint(const nsString& aText);
virtual bool RecvEndIMEComposition(const PRBool& aCancel,
nsString* aComposition);
virtual bool RecvGetIMEEnabled(PRUint32* aValue);
virtual bool RecvSetInputMode(const PRUint32& aValue, const nsString& aType, const nsString& aAction, const PRUint32& aReason);
virtual bool RecvGetIMEOpenState(PRBool* aValue);
virtual bool RecvSetIMEOpenState(const PRBool& aValue);
virtual bool RecvSetCursor(const PRUint32& aValue);
virtual bool RecvGetDPI(float* aValue);
virtual bool RecvGetWidgetNativeData(WindowsHandle* aValue);
virtual PContentDialogParent* AllocPContentDialog(const PRUint32& aType,
const nsCString& aName,
const nsCString& aFeatures,
const InfallibleTArray<int>& aIntParams,
const InfallibleTArray<nsString>& aStringParams);
virtual bool DeallocPContentDialog(PContentDialogParent* aDialog)
{
delete aDialog;
return true;
}
void LoadURL(nsIURI* aURI);
// XXX/cjones: it's not clear what we gain by hiding these
// message-sending functions under a layer of indirection and
// eating the return values
void Show(const nsIntSize& size);
void UpdateDimensions(const nsRect& rect, const nsIntSize& size);
void Activate();
void Deactivate();
void SendMouseEvent(const nsAString& aType, float aX, float aY,
PRInt32 aButton, PRInt32 aClickCount,
PRInt32 aModifiers, PRBool aIgnoreRootScrollFrame);
void SendKeyEvent(const nsAString& aType, PRInt32 aKeyCode,
PRInt32 aCharCode, PRInt32 aModifiers,
PRBool aPreventDefault);
bool SendRealMouseEvent(nsMouseEvent& event);
bool SendMouseScrollEvent(nsMouseScrollEvent& event);
bool SendRealKeyEvent(nsKeyEvent& event);
virtual PDocumentRendererParent*
AllocPDocumentRenderer(const nsRect& documentRect, const gfxMatrix& transform,
const nsString& bgcolor,
const PRUint32& renderFlags, const bool& flushLayout,
const nsIntSize& renderSize);
virtual bool DeallocPDocumentRenderer(PDocumentRendererParent* actor);
virtual PContentPermissionRequestParent* AllocPContentPermissionRequest(const nsCString& aType, const IPC::URI& uri);
virtual bool DeallocPContentPermissionRequest(PContentPermissionRequestParent* actor);
virtual POfflineCacheUpdateParent* AllocPOfflineCacheUpdate(
const URI& aManifestURI,
const URI& aDocumentURI,
const nsCString& aClientID,
const bool& stickDocument);
virtual bool DeallocPOfflineCacheUpdate(POfflineCacheUpdateParent* actor);
JSBool GetGlobalJSObject(JSContext* cx, JSObject** globalp);
NS_DECL_ISUPPORTS
NS_DECL_NSIAUTHPROMPTPROVIDER
NS_DECL_NSISECUREBROWSERUI
void HandleDelayedDialogs();
static TabParent *GetIMETabParent() { return mIMETabParent; }
bool HandleQueryContentEvent(nsQueryContentEvent& aEvent);
bool SendCompositionEvent(nsCompositionEvent& event);
bool SendTextEvent(nsTextEvent& event);
bool SendSelectionEvent(nsSelectionEvent& event);
protected:
bool ReceiveMessage(const nsString& aMessage,
PRBool aSync,
const nsString& aJSON,
InfallibleTArray<nsString>* aJSONRetVal = nsnull);
void ActorDestroy(ActorDestroyReason why);
nsIDOMElement* mFrameElement;
nsCOMPtr<nsIBrowserDOMWindow> mBrowserDOMWindow;
struct DelayedDialogData
{
DelayedDialogData(PContentDialogParent* aDialog, PRUint32 aType,
const nsCString& aName,
const nsCString& aFeatures,
nsIDialogParamBlock* aParams)
: mDialog(aDialog), mType(aType), mName(aName), mFeatures(aFeatures),
mParams(aParams) {}
PContentDialogParent* mDialog;
PRUint32 mType;
nsCString mName;
nsCString mFeatures;
nsCOMPtr<nsIDialogParamBlock> mParams;
};
InfallibleTArray<DelayedDialogData*> mDelayedDialogs;
PRBool ShouldDelayDialogs();
PRBool AllowContentIME();
NS_OVERRIDE
virtual PRenderFrameParent* AllocPRenderFrame();
NS_OVERRIDE
virtual bool DeallocPRenderFrame(PRenderFrameParent* aFrame);
// IME
static TabParent *mIMETabParent;
nsString mIMECacheText;
PRUint32 mIMESelectionAnchor;
PRUint32 mIMESelectionFocus;
PRPackedBool mIMEComposing;
PRPackedBool mIMECompositionEnding;
// Buffer to store composition text during ResetInputState
// Compositions in almost all cases are small enough for nsAutoString
nsAutoString mIMECompositionText;
PRUint32 mIMECompositionStart;
PRUint32 mIMESeqno;
float mDPI;
private:
already_AddRefed<nsFrameLoader> GetFrameLoader() const;
already_AddRefed<nsIWidget> GetWidget() const;
};
} // namespace dom
} // namespace mozilla
#endif
| 40.051502 | 131 | 0.681204 | [
"transform"
] |
c8ce428ce9832f0cd94f1553c88028bbb3568fe6 | 582 | h | C | editor/instancer/voxel_instancer_editor_plugin.h | harrisonvanderbyl/godot_voxel | fefb014637d25f1636734d657218e0603e477cd5 | [
"MIT"
] | null | null | null | editor/instancer/voxel_instancer_editor_plugin.h | harrisonvanderbyl/godot_voxel | fefb014637d25f1636734d657218e0603e477cd5 | [
"MIT"
] | null | null | null | editor/instancer/voxel_instancer_editor_plugin.h | harrisonvanderbyl/godot_voxel | fefb014637d25f1636734d657218e0603e477cd5 | [
"MIT"
] | null | null | null | #ifndef VOXEL_INSTANCER_EDITOR_PLUGIN_H
#define VOXEL_INSTANCER_EDITOR_PLUGIN_H
#include <editor/editor_plugin.h>
namespace zylann::voxel {
class VoxelInstancer;
class VoxelInstancerEditorPlugin : public EditorPlugin {
GDCLASS(VoxelInstancerEditorPlugin, EditorPlugin)
public:
VoxelInstancerEditorPlugin(EditorNode *p_node);
bool handles(Object *p_object) const override;
void edit(Object *p_object) override;
void make_visible(bool visible) override;
private:
VoxelInstancer *_node = nullptr;
};
} // namespace zylann::voxel
#endif // VOXEL_INSTANCER_EDITOR_PLUGIN_H
| 22.384615 | 56 | 0.814433 | [
"object"
] |
c8d1b4b26afac0b16b2f950cf18de77733d5a7e3 | 4,398 | c | C | test/ut_vec2.c | rdentato/clibutl | 2a10396dee6d6011e6fb3f8924535fb6a69427ed | [
"MIT"
] | 8 | 2015-04-09T20:28:07.000Z | 2021-12-14T22:00:53.000Z | test/ut_vec2.c | rdentato/clibutl | 2a10396dee6d6011e6fb3f8924535fb6a69427ed | [
"MIT"
] | 1 | 2018-10-26T12:01:36.000Z | 2019-02-18T15:37:46.000Z | test/ut_vec2.c | rdentato/clibutl | 2a10396dee6d6011e6fb3f8924535fb6a69427ed | [
"MIT"
] | 2 | 2017-02-12T10:27:56.000Z | 2017-09-14T16:06:03.000Z | /*
** (C) by Remo Dentato (rdentato@gmail.com)
**
** This software is distributed under the terms of the MIT license:
** https://opensource.org/licenses/MIT
**
** ___ __
** __/ /_ / )
** ___ __(_ ___) /
** / / / )/ / / /
** / (_/ // (__/ /
** (____,__/(_____(__/
** https://github.com/rdentato/clibutl
**
*/
#define UTL_MEMCHECK
#include "utl.h"
#include <math.h>
typedef struct point_s {
float x,y;
} point_t;
typedef struct {
char *k;
int v;
} mapSI_t;
int intcmp(void *a, void *b, void *aux)
{
return (*((int *)a) - *((int *)b));
}
uint32_t inthash(void *a, void *aux)
{
return utlhashint32(a);
}
uint32_t strhash(void *a, void *aux)
{
return utlhashstring(a);
}
/*
int pntcmp(void *a, void *b)
{
float delta;
point_t *a_pnt = a, *b_pnt = b;
delta = a_pnt->x - b_pnt->x;
if (delta < 0.0) return -1;
if (delta > 0.0) return 1;
delta = a_pnt->y - b_pnt->y;
if (delta < 0.0) return -1;
if (delta > 0.0) return 1;
return 0;
}
*/
void logtable(vec_t v)
{
uint8_t *p = v->vec;
uint32_t *q;
int32_t delta;
uint32_t k;
for (k=0; k<vecmax(v);k++) {
q = (uint32_t *)p;
if (q[1] == 0xFFFFFFFF) delta = -1;
else delta = k-(q[1] & (vecmax(v)-1));
logprintf("[%3d] -> h: %08X (%4d) key: %d",k,q[1],delta,q[0]);
p+=v->esz;
}
}
int main(int argc, char *argv[])
{
vec_t v;
int *pk;
int32_t *pi;
int32_t k;
int kk=-1;
/*
uint64_t *pu;
point_t p,q;
point_t *pq;
*/
logopen("l_vec2.log","w");
v=vecnew(int,intcmp);
logcheck(veccount(v) == 0);
vecadd(int,v,37);
logcheck(veccount(v) == 1);
pk=vecgetptr(v,0);
logcheck(pk && *pk == 37);
vecadd(int,v,5);
vecadd(int,v,79);
pk=vecgetptr(v,0);
logexpect(pk && *pk == 5,"[0]->%d",*pk);
pk=vecgetptr(v,1);
logexpect(pk && *pk == 37,"[1]->%d",*pk);
pk=vecgetptr(v,2);
logexpect(pk && *pk == 79,"[2]->%d",*pk);
logcheck(veccount(v) ==3);
pk = vecfirstptr(v);
logcheck(pk && *pk == 5);
pk = vecnextptr(v);
logcheck(pk && *pk == 37);
pk = vecnextptr(v);
logcheck(pk && *pk == 79);
pk = vecnextptr(v);
logcheck(!pk);
kk = vecfirst(int,v,-1);
logcheck(kk == 5);
kk = vecnext(int,v,-1);
logcheck(kk == 37);
kk = vecnext(int,v,-1);
logcheck(kk == 79);
kk = vecnext(int,v,-1);
logcheck(kk == -1);
vecfree(v);
srand(time(0));
v=vecnew(int,intcmp);
#define N 1000
vecset(int,v,N,0);
vecclear(v);
logprintf("cnt: %d max: %d",veccount(v),vecmax(v));
if (N <= 10000) {
logclock {
for (k=1;k<=N;k++)
//vecset(int,v,k-1,k);
vecadd(int,v, ((rand()&0x07) << 24) + k);
}
logcheck(veccount(v) == N);
}
logprintf("Added elements: %d",veccount(v));
#if 1
pk = vecgetptr(v,3);
if (pk) kk = *pk;
logprintf("Searching and removing %d",kk);
logcheck(vecsearch(int,v,kk));
logcheck(vecremove(int,v,kk));
logcheck(veccount(v) == (N-1));
logprintf("Current elements: %d",veccount(v));
logcheck(vecsearch(int,v,-98) == NULL);
vecfree(v);
/* * HASH * */
v = vecnew(int32_t,intcmp,inthash);
logcheck(v) ;
logprintf("cnt: %d max: %d esz:%d",veccount(v), vecmax(v), v->esz);
vecadd(int32_t,v,37);
logcheck(veccount(v) == 1) ;
vecadd(int32_t,v,493);
logcheck(veccount(v) == 2) ;
for (k = 0; k<20; k++) vecadd(int32_t,v,k ) ;
logcheck(veccount(v) == 22) ;
vecadd(int32_t,v,-1);
logcheck(veccount(v) == 23) ;
logprintf("cnt: %d max: %d esz:%d",veccount(v), vecmax(v), v->esz);
logtable(v);
pi = vecsearch(int32_t,v,12);
if (logcheck(pi && *pi==12))
logprintf("found: %d at %d",*pi,(int)((char *)pi - (char *)(v->vec))/v->esz);
pi = vecsearch(int32_t,v,98);
logcheck(!pi);
vecremove(int32_t,v,493);
logcheck(veccount(v) == 22) ;
logtable(v);
vecremove(int32_t,v,2);
logcheck(veccount(v) == 21) ;
logtable(v);
vecfree(v);
v = vecnew(int32_t,intcmp,inthash);
logcheck(v) ;
logprintf("cnt: %d max: %d esz:%d",veccount(v), vecmax(v), v->esz);
logclock {
for (k=1;k<=N;k++)
//vecset(int,v,k-1,k);
vecadd(int,v, ((rand()&0x07) << 24) + k);
}
logcheck(veccount(v) == N);
logprintf("Added elements: %d",veccount(v));
vecfree(v);
#endif
logclose();
exit(0);
}
| 19.038961 | 81 | 0.533652 | [
"3d"
] |
c8d3c16fd54932ab42bf25496375cb1db8f0e784 | 4,232 | c | C | dds/test/tinterop/main.c | brunodebus/tinq-core | f2d30a41cc629ef7a1b3aef15a9f46555e018016 | [
"curl"
] | 8 | 2015-01-28T03:26:43.000Z | 2021-04-19T21:00:34.000Z | dds/test/tinterop/main.c | ros2/tinq-core | e9cca1b1e433495616568ae6ae903322832f7b3b | [
"curl"
] | null | null | null | dds/test/tinterop/main.c | ros2/tinq-core | e9cca1b1e433495616568ae6ae903322832f7b3b | [
"curl"
] | 2 | 2015-08-14T19:54:20.000Z | 2017-04-09T02:54:15.000Z | /*
* Copyright (c) 2014 - Qeo LLC
*
* The source code form of this Qeo Open Source Project component is subject
* to the terms of the Clear BSD license.
*
* You can redistribute it and/or modify it under the terms of the Clear BSD
* License (http://directory.fsf.org/wiki/License:ClearBSD). See LICENSE file
* for more details.
*
* The Qeo Open Source Project also includes third party Open Source Software.
* See LICENSE file for more details.
*/
/* main.c -- Test program for the Type interop functionality. */
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef _WIN32
#include "win.h"
#else
#include <unistd.h>
#include <poll.h>
#endif
#include "tty.h"
#include "libx.h"
#include "dds/dds_dcps.h"
#include "dds/dds_debug.h"
#include "dds/dds_aux.h"
#include "dds/dds_xtypes.h"
#include "dds/dds_dwriter.h"
#include "dds/dds_dreader.h"
#include "static.h"
#include "dynamic.h"
unsigned domain_id = 9;
int main (int argc, const char *argv [])
{
DDS_DomainParticipant part;
unsigned sw, sr, dw, dr, i;
int error;
DDS_entity_name ("Technicolor Interop test");
printf ("Test 1: dynamic type first, then static.\r\n");
printf ("----------------------------------------\r\n");
/* Create a domain participant. */
part = DDS_DomainParticipantFactory_create_participant (
domain_id, NULL, NULL, 0);
if (!part)
fatal ("DDS_DomainParticipantFactory_create_participant () failed!");
printf ("DDS Domain Participant created.\r\n");
/* Register the dynamic shape topic type. */
register_dynamic_type (part);
printf ("DDS dynamic Topic type registered.\r\n");
/* Register the static topic type. */
register_static_type (part);
printf ("DDS static Topic type registered.\r\n");
dw = dynamic_writer_create ("Square");
dr = dynamic_reader_create ("Square");
sw = static_writer_create ("Square");
sr = static_reader_create ("Square");
for (i = 0; i < 10; i++) {
dynamic_writer_write (dw, "Red", i * 9 + 5, i * 11 + 5);
static_writer_write (sw, "Yellow", i * 10, i * 12);
usleep (100000);
}
dynamic_writer_delete (dw);
dynamic_reader_delete (dr);
static_writer_delete (sw);
static_reader_delete (sr);
unregister_dynamic_type ();
unregister_static_type ();
error = DDS_DomainParticipant_delete_contained_entities (part);
if (error)
fatal ("DDS_DomainParticipant_delete_contained_entities () failed (%s)!", DDS_error (error));
printf ("DDS Entities deleted\r\n");
error = DDS_DomainParticipantFactory_delete_participant (part);
if (error)
fatal ("DDS_DomainParticipantFactory_delete_participant () failed (%s)!", DDS_error (error));
printf ("DDS Participant deleted\r\n\r\n");
printf ("Test 2: static type first, then dynamic.\r\n");
printf ("----------------------------------------\r\n");
/* Create a domain participant. */
part = DDS_DomainParticipantFactory_create_participant (
domain_id, NULL, NULL, 0);
if (!part)
fatal ("DDS_DomainParticipantFactory_create_participant () failed!");
printf ("DDS Domain Participant created.\r\n");
/* Register the static topic type. */
register_static_type (part);
printf ("DDS static Topic type registered.\r\n");
/* Register the dynamic shape topic type. */
register_dynamic_type (part);
printf ("DDS dynamic Topic type registered.\r\n");
sw = static_writer_create ("Circle");
sr = static_reader_create ("Circle");
dw = dynamic_writer_create ("Circle");
dr = dynamic_reader_create ("Circle");
for (i = 0; i < 10; i++) {
static_writer_write (sw, "Green", i * 11, i * 13);
dynamic_writer_write (dw, "Magenta", i * 10 + 5, i * 12 + 5);
usleep (100000);
}
static_writer_delete (sw);
static_reader_delete (sr);
dynamic_writer_delete (dw);
dynamic_reader_delete (dr);
unregister_static_type ();
unregister_dynamic_type ();
error = DDS_DomainParticipant_delete_contained_entities (part);
if (error)
fatal ("DDS_DomainParticipant_delete_contained_entities () failed (%s)!", DDS_error (error));
printf ("DDS Entities deleted\r\n");
error = DDS_DomainParticipantFactory_delete_participant (part);
if (error)
fatal ("DDS_DomainParticipantFactory_delete_participant () failed (%s)!", DDS_error (error));
printf ("DDS Participant deleted\r\n\r\n");
return (0);
}
| 29.186207 | 95 | 0.699669 | [
"shape"
] |
c8d83142fe5331c98c93bba3a870376fa0d0ddb7 | 1,878 | h | C | bd/lfs_rambd.h | clren-seu/littlefs | 6463edd37b171bf2e7ab3ba456ceb58c895babe2 | [
"BSD-3-Clause"
] | null | null | null | bd/lfs_rambd.h | clren-seu/littlefs | 6463edd37b171bf2e7ab3ba456ceb58c895babe2 | [
"BSD-3-Clause"
] | null | null | null | bd/lfs_rambd.h | clren-seu/littlefs | 6463edd37b171bf2e7ab3ba456ceb58c895babe2 | [
"BSD-3-Clause"
] | null | null | null | /*
* Block device emulated in RAM
*
* Copyright (c) 2017, Arm Limited. All rights reserved.
* SPDX-License-Identifier: BSD-3-Clause
*/
#ifndef LFS_RAMBD_H
#define LFS_RAMBD_H
#include "lfs.h"
#include "lfs_util.h"
#ifdef __cplusplus
extern "C"
{
#endif
// Block device specific tracing
#ifdef LFS_RAMBD_YES_TRACE
#define LFS_RAMBD_TRACE(...) LFS_TRACE(__VA_ARGS__)
#else
#define LFS_RAMBD_TRACE(...)
#endif
// rambd config (optional)
struct lfs_rambd_config {
// 8-bit erase value to simulate erasing with. -1 indicates no erase
// occurs, which is still a valid block device
int32_t erase_value;
// Optional statically allocated buffer for the block device.
void *buffer;
};
// rambd state
typedef struct lfs_rambd {
uint8_t *buffer;
const struct lfs_rambd_config *cfg;
} lfs_rambd_t;
// Create a RAM block device using the geometry in lfs_config
int lfs_rambd_create(const struct lfs_config *cfg);
int lfs_rambd_createcfg(const struct lfs_config *cfg,
const struct lfs_rambd_config *bdcfg);
// Clean up memory associated with block device
int lfs_rambd_destroy(const struct lfs_config *cfg);
// Read a block
int lfs_rambd_read(const struct lfs_config *cfg, lfs_block_t block,
lfs_off_t off, void *buffer, lfs_size_t size);
// Program a block
//
// The block must have previously been erased.
int lfs_rambd_prog(const struct lfs_config *cfg, lfs_block_t block,
lfs_off_t off, const void *buffer, lfs_size_t size);
// Erase a block
//
// A block must be erased before being programmed. The
// state of an erased block is undefined.
int lfs_rambd_erase(const struct lfs_config *cfg, lfs_block_t block);
// Sync the block device
int lfs_rambd_sync(const struct lfs_config *cfg);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif
| 24.710526 | 73 | 0.71033 | [
"geometry"
] |
c8d8f6959fb3f94ab5d8903184a3a89e56938510 | 7,297 | h | C | lib/seismic/libseispp/slowness.h | jreyes1108/antelope_contrib | be2354605d8463d6067029eb16464a0bf432a41b | [
"BSD-2-Clause",
"MIT"
] | 30 | 2015-02-20T21:44:29.000Z | 2021-09-27T02:53:14.000Z | lib/seismic/libseispp/slowness.h | jreyes1108/antelope_contrib | be2354605d8463d6067029eb16464a0bf432a41b | [
"BSD-2-Clause",
"MIT"
] | 14 | 2015-07-07T19:17:24.000Z | 2020-12-19T19:18:53.000Z | lib/seismic/libseispp/slowness.h | jreyes1108/antelope_contrib | be2354605d8463d6067029eb16464a0bf432a41b | [
"BSD-2-Clause",
"MIT"
] | 46 | 2015-02-06T16:22:41.000Z | 2022-03-30T11:46:37.000Z | #ifndef _SLOWNESS_H_
#define _SLOWNESS_H_
#include <string>
#include "stock.h"
#include "PfStyleMetadata.h"
#ifndef NO_ANTELOPE
#include "pf.h"
#endif
namespace SEISPP
{
using namespace std;
/*! \brief Slowness vector object.
Slowness vectors are a seismology concept used to describe wave propagation.
A slowness vector points in the direction of propagation of a wave with a
magnitude equal to the slowness (1/velocity) of propagation.
\author Gary L. Pavlis
**/
class SlownessVector
{
public:
/*!
East-west component of slowness vector.
**/
double ux;
/*!
North-south component of slowness vector.
**/
double uy;
/*!
Default constructor.
**/
SlownessVector();
/*! \brief Fully parameterized constructor.
A slowness vector is defined by it's components. There is one ambiguity, however,
with a zero slowness vector. That is, normally direction of propagation is
inferred from the vector azimuth. A zero slowness vector has physical significance
(normal incidence) but presents and ambiguity in this regard. We use a defaulted
az0 parameter to specify the azimuth that should be used if the magnitude of
slowness vector is 0.
\param ux0 - set x (EW) component to this value.
\param uy0 - set y (NS) component to this value.
\param az0 - use this as azimuth (radians) if this is a zero slowness vector
(default 0.0)
*/
SlownessVector(double ux0, double uy0, double az0=0.0);
/*!
Copy constructor.
**/
SlownessVector(const SlownessVector&);
/*!
Computes the magntitude of the slowness vector.
Value returned is in units of seconds/kilometer.
**/
double mag();
/*!
Returns the propagation direction defined by a slowness vector.
Azimuth is a direction clockwise from north in the standard geographic
convention. Value returned is in radians.
**/
double azimuth();
/*!
Returns the back azimuth direction defined by a slowness vector.
A back azimuth is 180 degrees away from the direction of propagation and
points along the great circle path directed back to the source point
from a given position. The value returned is in radians.
**/
double baz();
/*! \brief Standard assignment operator. */
SlownessVector& operator=(const SlownessVector& parent);
/* \brief Standard accumulation operator. */
SlownessVector& operator+=(const SlownessVector& other);
/* \brief Standard subtract from operator. */
SlownessVector& operator-=(const SlownessVector& other);
/* \brief Standard addition operator. */
const SlownessVector operator+(const SlownessVector& other) const;
/* \brief Standard subraction operator. */
const SlownessVector operator-(const SlownessVector& other) const;
private:
double azimuth0;
};
/*! \brief This object defines a uniform grid of points in slowness space.
In array processing it is common to need a grid of feasible slowness
vectors and data are commonly stacked to define all of this family
of plane wave stacks. The object used here grids up slowness space
in uniform spacing in ux and uy components.
The gridding is defined by the lower left corner (uxlow, uylow),
spacing in EW and NS directions (dux, duy), and the number of
points in the x (EW) and y (NS) directions.
Note the grid and all methods assume units of s/km, although
this application is largely blind to units.
\author Gary L. Pavlis
**/
class RectangularSlownessGrid
{
public:
/*!
Name assigned to this grid object.
**/
string name;
/*!
Minimum ux (East-west) component of grid.
The location of the lower left corner of the grid defined by this object is
at coordinates (uxlow,uylow).
**/
double uxlow;
/*!
Minimum uy (North-south) component of grid.
The location of the lower left corner of the grid defined by this object is
at coordinates (uxlow,uylow).
**/
double uylow;
/*!
Grid size (s/km) of slowness grid in EW component.
**/
double dux;
/*!
Grid size (s/km) of slowness grid in NS component.
**/
double duy;
/*!
Number of grid points in x (EW) direction of slowness grid.
**/
int nux;
/*!
Number of grid points in y (NW) direction of slowness grid.
**/
int nuy;
/*!
Default constructor.
**/
RectangularSlownessGrid(); // generic default is defined
/*!
Fully parameterized constructor.
\param nm - name to be assigned to grid.
\param uxl - lower left corner ux.
\param uyl - lower left corner uy.
\param dux - dux (increment in x direction)
\param duy - duy (increment in y direction)
\param nx - number of grid points in x direction.
\param ny - number of grid points in y direction.
**/
RectangularSlownessGrid(string nm, double uxl, double uyl,
double dux,double duy,int nx, int ny);
#ifndef NO_ANTELOPE
/*!
Parameter file driven constructor.
The following parameters are fetched:
"Slowness_Grid_Name" (string), "uxlow" (real), "uylow" (real),
"nux" (int), "nuy" (int), "dux" (real), and "duy" (real).
They define an nux by nuy regular grid in slowness space with
spacing dux and duy respectively with the lower left corner of the
grid at (uxlow,uylow). The name is just a tag.
\param pf - Antelope pf pointer normally produced by earlier call to pfread
\param tag - name to search in pf to describe this grid object.`
The parameters to describe the object are assumed encased in an
&Arr{ } construct with this tag. This allows multiple grids to
be defined in a single parameter file with different tags.
\exception MetadataGetError (child of SeisppError) is thrown if the
required attributes are not defined in the Metadata object passed.
**/
RectangularSlownessGrid(Pf *pf,string tag);
#endif
/* \brief Metadata driven constructor.
This is similar to the Pf driven method except the data is passed
through a more generic object in SEISPP called Metadata. Keywords
defined in the Metadata object are identical to those in the pf version.
As for the pf constructor the required parameters are:
"Slowness_Grid_Name" (string), "uxlow" (real), "uylow" (real),
"nux" (int), "nuy" (int), "dux" (real), and "duy" (real).
They define an nux by nuy regular grid in slowness space with
spacing dux and duy respectively with the lower left corner of the
grid at (uxlow,uylow). The name is just a tag.
\param mdin is the Metadata object with attributes set to build this object.
\param tag - name to search in pf to describe this grid object.`
The parameters to describe the object are assumed encased in an
&Arr{ } construct with this tag. This allows multiple grids to
be defined in a single parameter file with different tags.
\exception MetadataGetError (child of SeisppError) is thrown if the
required attributes are not defined in the Metadata object passed.
*/
RectangularSlownessGrid(PfStyleMetadata& mdin,string tag);
/*!
Standard copy constructor.
**/
RectangularSlownessGrid(const RectangularSlownessGrid&);
/*!
Returns x component of slowness grid at index position i.
**/
double ux(int i) {return(uxlow+i*dux);};
/*!
Returns y component of slowness grid at index position j.
**/
double uy(int i) {return(uylow+i*duy);};
/*!
Returns a slowness grid object for grid position (i,j).
\exception SeisppError object if i and j are outside range.
**/
SlownessVector slow(int i, int j);
};
} // End SEISPP namespace declaration
#endif
| 34.098131 | 83 | 0.733589 | [
"object",
"vector"
] |
c8e1a1147b1ad99216ea9455c56cf24a765f2e0f | 6,227 | h | C | include/ed/update_request.h | tue-robotics/ed | 3ce42e4898ae3677b043d9448a47210d0b676124 | [
"BSD-2-Clause"
] | 44 | 2015-01-16T16:52:09.000Z | 2022-02-11T16:06:49.000Z | include/ed/update_request.h | tue-robotics/ed | 3ce42e4898ae3677b043d9448a47210d0b676124 | [
"BSD-2-Clause"
] | 69 | 2015-01-07T15:03:12.000Z | 2022-02-14T14:09:47.000Z | include/ed/update_request.h | tue-robotics/ed | 3ce42e4898ae3677b043d9448a47210d0b676124 | [
"BSD-2-Clause"
] | 18 | 2015-02-26T11:31:17.000Z | 2021-09-25T08:29:02.000Z | #ifndef ED_UPDATE_REQUEST_H_
#define ED_UPDATE_REQUEST_H_
#include "ed/types.h"
#include "ed/uuid.h"
#include "ed/property.h"
#include "ed/property_key.h"
#include "ed/property_key_db.h"
#include <tue/config/data_pointer.h>
#include <map>
#include <set>
#include <vector>
#include <geolib/datatypes.h>
#include "ed/convex_hull_2d.h"
#include "ed/convex_hull.h"
#include "ed/measurement_convex_hull.h"
namespace ed
{
class UpdateRequest
{
public:
UpdateRequest() : is_sync_update(false) {}
// MEASUREMENTS
std::map<UUID, std::vector<MeasurementConstPtr> > measurements;
void addMeasurement(const UUID& id, const MeasurementConstPtr& m) { measurements[id].push_back(m); flagUpdated(id); }
void addMeasurements(const UUID& id, const std::vector<MeasurementConstPtr>& measurements_)
{
if (measurements_.empty())
return;
std::vector<MeasurementConstPtr>& v = measurements[id];
v.insert(v.end(), measurements_.begin(), measurements_.end());
flagUpdated(id);
}
// SHAPES
std::map<UUID, geo::ShapeConstPtr> shapes;
void setShape(const UUID& id, const geo::ShapeConstPtr& shape) { shapes[id] = shape; flagUpdated(id); }
//VOLUMES
std::map<UUID, std::map<std::string, geo::ShapeConstPtr> > volumes_added;
void addVolume(const UUID& id, const std::string Volume_name, const geo::ShapeConstPtr& Volume_shape)
{ std::map<UUID, std::map<std::string, geo::ShapeConstPtr> >::iterator it = volumes_added.find(id);
if (it != volumes_added.end())
{
std::map<std::string, geo::ShapeConstPtr>::iterator it2 = it->second.find(Volume_name);
if (it2 != it->second.end())
it2->second = Volume_shape;
else
it->second[Volume_name] = Volume_shape;
}
else
{
std::map<std::string, geo::ShapeConstPtr> volume_map;
volume_map[Volume_name] = Volume_shape;
volumes_added[id] = volume_map;
}
flagUpdated(id);
}
std::map<UUID, std::set<std::string> > volumes_removed;
void removeVolume(const UUID& id, const std::string Volume_name) { volumes_removed[id].insert(Volume_name); flagUpdated(id); }
// CONVEX HULLS NEW
std::map<UUID, std::map<std::string, ed::MeasurementConvexHull> > convex_hulls_new;
void setConvexHullNew(const UUID& id, const ed::ConvexHull& convex_hull, const geo::Pose3D& pose, double time, std::string source = "")
{
ed::MeasurementConvexHull& m = convex_hulls_new[id][source];
m.convex_hull = convex_hull;
m.pose = pose;
m.timestamp = time;
flagUpdated(id);
}
void removeConvexHullNew(const UUID& id, const std::string& source)
{
// For now, signal that the convex hull must be removed by setting an empty chull
ed::MeasurementConvexHull& m = convex_hulls_new[id][source];
}
// TYPES
std::map<UUID, std::string> types;
void setType(const UUID& id, const std::string& type) { types[id] = type; flagUpdated(id); }
std::map<UUID, std::set<std::string> > type_sets_added;
void addType(const UUID& id, const std::string& type) { type_sets_added[id].insert(type); flagUpdated(id); }
std::map<UUID, std::set<std::string> > type_sets_removed;
void removeType(const UUID& id, const std::string& type) { type_sets_removed[id].insert(type); flagUpdated(id); }
// PROBABILITY OF EXISTENCE
std::map<UUID, double> existence_probabilities;
void setExistenceProbability(const UUID& id, double prob) { existence_probabilities[id] = prob; }
// LAST UPDATE TIMESTAMP
std::map<UUID, double> last_update_timestamps;
void setLastUpdateTimestamp(const UUID& id, double t) { last_update_timestamps[id] = t; }
// POSES
std::map<UUID, geo::Pose3D> poses;
void setPose(const UUID& id, const geo::Pose3D& pose) { poses[id] = pose; flagUpdated(id); }
// RELATIONS
std::map<UUID, std::map<UUID, RelationConstPtr> > relations;
void setRelation(const UUID& id1, const UUID& id2, const RelationConstPtr& r) { relations[id1][id2] = r; flagUpdated(id1); flagUpdated(id2);}
// DATA
std::map<UUID, tue::config::DataConstPointer> datas;
void addData(const UUID& id, const tue::config::DataConstPointer& data)
{
std::map<UUID, tue::config::DataConstPointer>::iterator it = datas.find(id);
if (it == datas.end())
{
datas[id] = data;
}
else
{
tue::config::DataPointer data_total;
data_total.add(it->second);
data_total.add(data);
it->second = data_total;
}
flagUpdated(id);
}
std::map<UUID, std::map<Idx, Property> > properties;
template<typename T>
void setProperty(const UUID& id, const PropertyKey<T>& key, const T& value)
{
if (!key.valid())
return;
Property& p = properties[id][key.idx];
p.entry = key.entry;
p.value = value;
flagUpdated(id);
}
void setProperty(const UUID& id, const PropertyKeyDBEntry* entry, const ed::Variant& v)
{
Property& p = properties[id][entry->idx];
p.entry = entry;
p.value = v;
flagUpdated(id);
}
// REMOVED ENTITIES
std::set<UUID> removed_entities;
void removeEntity(const UUID& id) { removed_entities.insert(id); flagUpdated(id); }
// FLAGS
std::map<ed::UUID, std::string> added_flags;
void setFlag(const UUID& id, const std::string& flag) { added_flags[id] = flag; flagUpdated(id); }
std::map<ed::UUID, std::string> removed_flags;
void removeFlag(const UUID& id, const std::string& flag) { removed_flags[id] = flag; flagUpdated(id); }
// UPDATED (AND REMOVED) ENTITIES
std::set<UUID> updated_entities;
bool empty() const { return updated_entities.empty(); }
// Is true if the update was created for synchronization only (used by ed_cloud)
bool is_sync_update;
void setSyncUpdate(bool b = true) { is_sync_update = b; }
private:
void flagUpdated(const ed::UUID& id) { updated_entities.insert(id); }
};
}
#endif
| 27.553097 | 145 | 0.639152 | [
"shape",
"vector"
] |
c8ead23b5b3ae8e539e1380091df7c0eb8d3229c | 5,638 | c | C | src/peach_message.c | dasfaha/sky | 4f2696e9abe54f4818f94337ed3bceae798e5a6d | [
"MIT"
] | 2 | 2018-01-16T07:26:53.000Z | 2021-12-08T03:12:40.000Z | src/peach_message.c | dasfaha/sky | 4f2696e9abe54f4818f94337ed3bceae798e5a6d | [
"MIT"
] | null | null | null | src/peach_message.c | dasfaha/sky | 4f2696e9abe54f4818f94337ed3bceae798e5a6d | [
"MIT"
] | null | null | null | #include <stdlib.h>
#include <arpa/inet.h>
#include "peach_message.h"
#include "minipack.h"
#include "mem.h"
#include "dbg.h"
#include "qip/qip.h"
#include "qip_path.h"
#include "sky_qip_module.h"
//==============================================================================
//
// Definitions
//
//==============================================================================
typedef void (*sky_qip_path_map_func)(sky_qip_path *path, qip_map *map);
typedef void (*sky_qip_result_serialize_func)(void *result, qip_serializer *serializer);
//==============================================================================
//
// Functions
//
//==============================================================================
//--------------------------------------
// Lifecycle
//--------------------------------------
// Creates an PEACH message object.
//
// Returns a new PEACH message.
sky_peach_message *sky_peach_message_create()
{
sky_peach_message *message = NULL;
message = calloc(1, sizeof(sky_peach_message)); check_mem(message);
return message;
error:
sky_peach_message_free(message);
return NULL;
}
// Frees an PEACH message object from memory.
//
// message - The message.
void sky_peach_message_free(sky_peach_message *message)
{
if(message) {
free(message);
}
}
//--------------------------------------
// Serialization
//--------------------------------------
// Calculates the total number of bytes needed to store the message.
//
// message - The message.
//
// Returns the number of bytes required to store the message.
size_t sky_peach_message_sizeof(sky_peach_message *message)
{
size_t sz = 0;
sz += minipack_sizeof_raw(blength(message->query));
sz += blength(message->query);
return sz;
}
// Serializes an PEACH message to a memory location.
//
// message - The message.
// file - The file stream to write to.
//
// Returns 0 if successful, otherwise returns -1.
int sky_peach_message_pack(sky_peach_message *message, FILE *file)
{
int rc;
check(message != NULL, "Message required");
check(file != NULL, "File stream required");
// Database name
rc = sky_minipack_fwrite_bstring(file, message->query);
check(rc == 0, "Unable to write query text");
return 0;
error:
return -1;
}
// Deserializes an PEACH message from a file stream.
//
// message - The message.
// file - The file stream to read from.
//
// Returns 0 if successful, otherwise returns -1.
int sky_peach_message_unpack(sky_peach_message *message, FILE *file)
{
int rc;
check(message != NULL, "Message required");
check(file != NULL, "File stream required");
// Query
rc = sky_minipack_fread_bstring(file, &message->query);
check(rc == 0, "Unable to read query text");
return 0;
error:
return -1;
}
//--------------------------------------
// Processing
//--------------------------------------
// Runs a PEACH query against a table.
//
// message - The message.
// table - The table to run the query against.
// output - The output stream to write to.
//
// Returns 0 if successful, otherwise returns -1.
int sky_peach_message_process(sky_peach_message *message, sky_table *table,
FILE *output)
{
int rc;
check(message != NULL, "Message required");
check(table != NULL, "Table required");
check(output != NULL, "Output stream required");
// Compile.
sky_qip_module *module = sky_qip_module_create(); check_mem(module);
module->table = table;
rc = sky_qip_module_compile(module, message->query);
check(rc == 0, "Unable to compile query");
sky_qip_path_map_func main_function = (sky_qip_path_map_func)module->main_function;
// Initialize the path iterator.
sky_path_iterator iterator;
sky_path_iterator_init(&iterator);
rc = sky_path_iterator_set_data_file(&iterator, table->data_file);
check(rc == 0, "Unable to initialze path iterator");
// Initialize QIP args.
sky_qip_path *path = sky_qip_path_create();
qip_map *map = qip_map_create();
// Iterate over each path.
uint32_t path_count = 0;
while(!iterator.eof) {
// Retrieve the path pointer.
rc = sky_path_iterator_get_ptr(&iterator, &path->path_ptr);
check(rc == 0, "Unable to retrieve the path iterator pointer");
// Execute query.
main_function(path, map);
// Move to next path.
rc = sky_path_iterator_next(&iterator);
check(rc == 0, "Unable to find next path");
path_count++;
}
//debug("Paths processed: %d", path_count);
// Retrieve Result serialization function.
struct tagbstring result_str = bsStatic("Result");
struct tagbstring serialize_str = bsStatic("serialize");
sky_qip_result_serialize_func result_serialize = NULL;
rc = qip_module_get_class_method(module->_qip_module, &result_str, &serialize_str, (void*)(&result_serialize));
check(rc == 0 && result_serialize != NULL, "Unable to find serialize() method on class 'Result'");
// Serialize.
qip_serializer *serializer = qip_serializer_create();
qip_serializer_pack_map(module->_qip_module, serializer, map->count);
int64_t i;
for(i=0; i<map->count; i++) {
result_serialize(map->elements[i], serializer);
}
// Send response to output stream.
rc = fwrite(serializer->data, serializer->length, 1, output);
check(rc == 1, "Unable to write serialized data to stream");
qip_map_free(map);
sky_qip_module_free(module);
return 0;
error:
sky_qip_module_free(module);
return -1;
} | 28.049751 | 115 | 0.607662 | [
"object"
] |
c8ee492c423b85ed415e8b2e019e419efd285268 | 57,093 | h | C | Include/10.0.20348.0/um/mftransform.h | sezero/windows-sdk-headers | e8e9d4d50769ded01a2df905c6bf4355eb3fa8b5 | [
"MIT"
] | 5 | 2020-05-29T06:22:17.000Z | 2021-11-28T08:21:38.000Z | Include/10.0.20348.0/um/mftransform.h | sezero/windows-sdk-headers | e8e9d4d50769ded01a2df905c6bf4355eb3fa8b5 | [
"MIT"
] | null | null | null | Include/10.0.20348.0/um/mftransform.h | sezero/windows-sdk-headers | e8e9d4d50769ded01a2df905c6bf4355eb3fa8b5 | [
"MIT"
] | 5 | 2020-05-30T04:15:11.000Z | 2021-11-28T08:48:56.000Z |
/* this ALWAYS GENERATED file contains the definitions for the interfaces */
/* File created by MIDL compiler version 8.01.0626 */
/* @@MIDL_FILE_HEADING( ) */
/* verify that the <rpcndr.h> version is high enough to compile this file*/
#ifndef __REQUIRED_RPCNDR_H_VERSION__
#define __REQUIRED_RPCNDR_H_VERSION__ 500
#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 __mftransform_h__
#define __mftransform_h__
#if defined(_MSC_VER) && (_MSC_VER >= 1020)
#pragma once
#endif
#ifndef DECLSPEC_XFGVIRT
#if _CONTROL_FLOW_GUARD_XFG
#define DECLSPEC_XFGVIRT(base, func) __declspec(xfg_virtual(base, func))
#else
#define DECLSPEC_XFGVIRT(base, func)
#endif
#endif
/* Forward Declarations */
#ifndef __IMFTransform_FWD_DEFINED__
#define __IMFTransform_FWD_DEFINED__
typedef interface IMFTransform IMFTransform;
#endif /* __IMFTransform_FWD_DEFINED__ */
#ifndef __IMFDeviceTransform_FWD_DEFINED__
#define __IMFDeviceTransform_FWD_DEFINED__
typedef interface IMFDeviceTransform IMFDeviceTransform;
#endif /* __IMFDeviceTransform_FWD_DEFINED__ */
#ifndef __IMFDeviceTransformCallback_FWD_DEFINED__
#define __IMFDeviceTransformCallback_FWD_DEFINED__
typedef interface IMFDeviceTransformCallback IMFDeviceTransformCallback;
#endif /* __IMFDeviceTransformCallback_FWD_DEFINED__ */
/* header files for imported files */
#include "mfobjects.h"
#ifdef __cplusplus
extern "C"{
#endif
/* interface __MIDL_itf_mftransform_0000_0000 */
/* [local] */
#include <winapifamily.h>
#pragma region Desktop or Games Family
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP | WINAPI_PARTITION_GAMES)
#endif /* WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP | WINAPI_PARTITION_GAMES) */
#pragma endregion
#pragma region Application or Games Family
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP | WINAPI_PARTITION_GAMES)
enum _MFT_INPUT_DATA_BUFFER_FLAGS
{
MFT_INPUT_DATA_BUFFER_PLACEHOLDER = 0xffffffff
} ;
enum _MFT_OUTPUT_DATA_BUFFER_FLAGS
{
MFT_OUTPUT_DATA_BUFFER_INCOMPLETE = 0x1000000,
MFT_OUTPUT_DATA_BUFFER_FORMAT_CHANGE = 0x100,
MFT_OUTPUT_DATA_BUFFER_STREAM_END = 0x200,
MFT_OUTPUT_DATA_BUFFER_NO_SAMPLE = 0x300
} ;
enum _MFT_INPUT_STATUS_FLAGS
{
MFT_INPUT_STATUS_ACCEPT_DATA = 0x1
} ;
enum _MFT_OUTPUT_STATUS_FLAGS
{
MFT_OUTPUT_STATUS_SAMPLE_READY = 0x1
} ;
enum _MFT_INPUT_STREAM_INFO_FLAGS
{
MFT_INPUT_STREAM_WHOLE_SAMPLES = 0x1,
MFT_INPUT_STREAM_SINGLE_SAMPLE_PER_BUFFER = 0x2,
MFT_INPUT_STREAM_FIXED_SAMPLE_SIZE = 0x4,
MFT_INPUT_STREAM_HOLDS_BUFFERS = 0x8,
MFT_INPUT_STREAM_DOES_NOT_ADDREF = 0x100,
MFT_INPUT_STREAM_REMOVABLE = 0x200,
MFT_INPUT_STREAM_OPTIONAL = 0x400,
MFT_INPUT_STREAM_PROCESSES_IN_PLACE = 0x800
} ;
enum _MFT_OUTPUT_STREAM_INFO_FLAGS
{
MFT_OUTPUT_STREAM_WHOLE_SAMPLES = 0x1,
MFT_OUTPUT_STREAM_SINGLE_SAMPLE_PER_BUFFER = 0x2,
MFT_OUTPUT_STREAM_FIXED_SAMPLE_SIZE = 0x4,
MFT_OUTPUT_STREAM_DISCARDABLE = 0x8,
MFT_OUTPUT_STREAM_OPTIONAL = 0x10,
MFT_OUTPUT_STREAM_PROVIDES_SAMPLES = 0x100,
MFT_OUTPUT_STREAM_CAN_PROVIDE_SAMPLES = 0x200,
MFT_OUTPUT_STREAM_LAZY_READ = 0x400,
MFT_OUTPUT_STREAM_REMOVABLE = 0x800
} ;
enum _MFT_SET_TYPE_FLAGS
{
MFT_SET_TYPE_TEST_ONLY = 0x1
} ;
enum _MFT_PROCESS_OUTPUT_FLAGS
{
MFT_PROCESS_OUTPUT_DISCARD_WHEN_NO_BUFFER = 0x1,
MFT_PROCESS_OUTPUT_REGENERATE_LAST_OUTPUT = 0x2
} ;
enum _MFT_PROCESS_OUTPUT_STATUS
{
MFT_PROCESS_OUTPUT_STATUS_NEW_STREAMS = 0x100
} ;
enum _MFT_DRAIN_TYPE
{
MFT_DRAIN_PRODUCE_TAILS = 0,
MFT_DRAIN_NO_TAILS = 0x1
} ;
#define MFT_STREAMS_UNLIMITED 0xFFFFFFFF
#define MFT_OUTPUT_BOUND_LOWER_UNBOUNDED MINLONGLONG
#define MFT_OUTPUT_BOUND_UPPER_UNBOUNDED MAXLONGLONG
typedef /* [v1_enum] */
enum _MFT_MESSAGE_TYPE
{
MFT_MESSAGE_COMMAND_FLUSH = 0,
MFT_MESSAGE_COMMAND_DRAIN = 0x1,
MFT_MESSAGE_SET_D3D_MANAGER = 0x2,
MFT_MESSAGE_DROP_SAMPLES = 0x3,
MFT_MESSAGE_COMMAND_TICK = 0x4,
MFT_MESSAGE_NOTIFY_BEGIN_STREAMING = 0x10000000,
MFT_MESSAGE_NOTIFY_END_STREAMING = 0x10000001,
MFT_MESSAGE_NOTIFY_END_OF_STREAM = 0x10000002,
MFT_MESSAGE_NOTIFY_START_OF_STREAM = 0x10000003,
MFT_MESSAGE_NOTIFY_RELEASE_RESOURCES = 0x10000004,
MFT_MESSAGE_NOTIFY_REACQUIRE_RESOURCES = 0x10000005,
MFT_MESSAGE_NOTIFY_EVENT = 0x10000006,
MFT_MESSAGE_COMMAND_SET_OUTPUT_STREAM_STATE = 0x10000007,
MFT_MESSAGE_COMMAND_FLUSH_OUTPUT_STREAM = 0x10000008,
MFT_MESSAGE_COMMAND_MARKER = 0x20000000
} MFT_MESSAGE_TYPE;
typedef struct _MFT_INPUT_STREAM_INFO
{
LONGLONG hnsMaxLatency;
DWORD dwFlags;
DWORD cbSize;
DWORD cbMaxLookahead;
DWORD cbAlignment;
} MFT_INPUT_STREAM_INFO;
typedef struct _MFT_OUTPUT_STREAM_INFO
{
DWORD dwFlags;
DWORD cbSize;
DWORD cbAlignment;
} MFT_OUTPUT_STREAM_INFO;
typedef struct _MFT_OUTPUT_DATA_BUFFER
{
DWORD dwStreamID;
IMFSample *pSample;
DWORD dwStatus;
IMFCollection *pEvents;
} MFT_OUTPUT_DATA_BUFFER;
typedef struct _MFT_OUTPUT_DATA_BUFFER *PMFT_OUTPUT_DATA_BUFFER;
//
// redefine all the method names to have MFT at the beginning so they don't class with DMO methods.
//
#ifdef MFT_UNIQUE_METHOD_NAMES
#define GetStreamLimits MFTGetStreamLimits
#define GetStreamCount MFTGetStreamCount
#define GetStreamIDs MFTGetStreamIDs
#define GetInputStreamInfo MFTGetInputStreamInfo
#define GetOutputStreamInfo MFTGetOutputStreamInfo
#define DeleteInputStream MFTDeleteInputStream
#define AddInputStreams MFTAddInputStreams
#define GetInputAvailableType MFTGetInputAvailableType
#define GetOutputAvailableType MFTGetOutputAvailableType
#define SetInputType MFTSetInputType
#define SetOutputType MFTSetOutputType
#define GetInputCurrentType MFTGetInputCurrentType
#define GetOutputCurrentType MFTGetOutputCurrentType
#define GetInputStatus MFTGetInputStatus
#define GetOutputStatus MFTGetOutputStatus
#define SetOutputBounds MFTSetOutputBounds
#define ProcessEvent MFTProcessEvent
#define ProcessMessage MFTProcessMessage
#define ProcessInput MFTProcessInput
#define ProcessOutput MFTProcessOutput
#endif
extern RPC_IF_HANDLE __MIDL_itf_mftransform_0000_0000_v0_0_c_ifspec;
extern RPC_IF_HANDLE __MIDL_itf_mftransform_0000_0000_v0_0_s_ifspec;
#ifndef __IMFTransform_INTERFACE_DEFINED__
#define __IMFTransform_INTERFACE_DEFINED__
/* interface IMFTransform */
/* [uuid][object] */
EXTERN_C const IID IID_IMFTransform;
#if defined(__cplusplus) && !defined(CINTERFACE)
MIDL_INTERFACE("bf94c121-5b05-4e6f-8000-ba598961414d")
IMFTransform : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE GetStreamLimits(
/* [out] */ __RPC__out DWORD *pdwInputMinimum,
/* [out] */ __RPC__out DWORD *pdwInputMaximum,
/* [out] */ __RPC__out DWORD *pdwOutputMinimum,
/* [out] */ __RPC__out DWORD *pdwOutputMaximum) = 0;
virtual HRESULT STDMETHODCALLTYPE GetStreamCount(
/* [out] */ __RPC__out DWORD *pcInputStreams,
/* [out] */ __RPC__out DWORD *pcOutputStreams) = 0;
virtual HRESULT STDMETHODCALLTYPE GetStreamIDs(
DWORD dwInputIDArraySize,
/* [size_is][out] */ __RPC__out_ecount_full(dwInputIDArraySize) DWORD *pdwInputIDs,
DWORD dwOutputIDArraySize,
/* [size_is][out] */ __RPC__out_ecount_full(dwOutputIDArraySize) DWORD *pdwOutputIDs) = 0;
virtual HRESULT STDMETHODCALLTYPE GetInputStreamInfo(
DWORD dwInputStreamID,
/* [out] */ __RPC__out MFT_INPUT_STREAM_INFO *pStreamInfo) = 0;
virtual HRESULT STDMETHODCALLTYPE GetOutputStreamInfo(
DWORD dwOutputStreamID,
/* [out] */ __RPC__out MFT_OUTPUT_STREAM_INFO *pStreamInfo) = 0;
virtual HRESULT STDMETHODCALLTYPE GetAttributes(
/* [out] */ __RPC__deref_out_opt IMFAttributes **pAttributes) = 0;
virtual HRESULT STDMETHODCALLTYPE GetInputStreamAttributes(
DWORD dwInputStreamID,
/* [out] */ __RPC__deref_out_opt IMFAttributes **pAttributes) = 0;
virtual HRESULT STDMETHODCALLTYPE GetOutputStreamAttributes(
DWORD dwOutputStreamID,
/* [out] */ __RPC__deref_out_opt IMFAttributes **pAttributes) = 0;
virtual HRESULT STDMETHODCALLTYPE DeleteInputStream(
DWORD dwStreamID) = 0;
virtual HRESULT STDMETHODCALLTYPE AddInputStreams(
DWORD cStreams,
/* [in] */ __RPC__in DWORD *adwStreamIDs) = 0;
virtual HRESULT STDMETHODCALLTYPE GetInputAvailableType(
DWORD dwInputStreamID,
DWORD dwTypeIndex,
/* [out] */ __RPC__deref_out_opt IMFMediaType **ppType) = 0;
virtual HRESULT STDMETHODCALLTYPE GetOutputAvailableType(
DWORD dwOutputStreamID,
DWORD dwTypeIndex,
/* [out] */ __RPC__deref_out_opt IMFMediaType **ppType) = 0;
virtual HRESULT STDMETHODCALLTYPE SetInputType(
DWORD dwInputStreamID,
/* [in] */ __RPC__in_opt IMFMediaType *pType,
DWORD dwFlags) = 0;
virtual HRESULT STDMETHODCALLTYPE SetOutputType(
DWORD dwOutputStreamID,
/* [in] */ __RPC__in_opt IMFMediaType *pType,
DWORD dwFlags) = 0;
virtual HRESULT STDMETHODCALLTYPE GetInputCurrentType(
DWORD dwInputStreamID,
/* [out] */ __RPC__deref_out_opt IMFMediaType **ppType) = 0;
virtual HRESULT STDMETHODCALLTYPE GetOutputCurrentType(
DWORD dwOutputStreamID,
/* [out] */ __RPC__deref_out_opt IMFMediaType **ppType) = 0;
virtual HRESULT STDMETHODCALLTYPE GetInputStatus(
DWORD dwInputStreamID,
/* [out] */ __RPC__out DWORD *pdwFlags) = 0;
virtual HRESULT STDMETHODCALLTYPE GetOutputStatus(
/* [out] */ __RPC__out DWORD *pdwFlags) = 0;
virtual HRESULT STDMETHODCALLTYPE SetOutputBounds(
LONGLONG hnsLowerBound,
LONGLONG hnsUpperBound) = 0;
virtual HRESULT STDMETHODCALLTYPE ProcessEvent(
DWORD dwInputStreamID,
/* [in] */ __RPC__in_opt IMFMediaEvent *pEvent) = 0;
virtual HRESULT STDMETHODCALLTYPE ProcessMessage(
MFT_MESSAGE_TYPE eMessage,
ULONG_PTR ulParam) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE ProcessInput(
DWORD dwInputStreamID,
IMFSample *pSample,
DWORD dwFlags) = 0;
virtual /* [local] */ HRESULT STDMETHODCALLTYPE ProcessOutput(
DWORD dwFlags,
DWORD cOutputBufferCount,
/* [size_is][out][in] */ MFT_OUTPUT_DATA_BUFFER *pOutputSamples,
/* [out] */ DWORD *pdwStatus) = 0;
};
#else /* C style interface */
typedef struct IMFTransformVtbl
{
BEGIN_INTERFACE
DECLSPEC_XFGVIRT(IUnknown, QueryInterface)
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
__RPC__in IMFTransform * This,
/* [in] */ __RPC__in REFIID riid,
/* [annotation][iid_is][out] */
_COM_Outptr_ void **ppvObject);
DECLSPEC_XFGVIRT(IUnknown, AddRef)
ULONG ( STDMETHODCALLTYPE *AddRef )(
__RPC__in IMFTransform * This);
DECLSPEC_XFGVIRT(IUnknown, Release)
ULONG ( STDMETHODCALLTYPE *Release )(
__RPC__in IMFTransform * This);
DECLSPEC_XFGVIRT(IMFTransform, GetStreamLimits)
HRESULT ( STDMETHODCALLTYPE *GetStreamLimits )(
__RPC__in IMFTransform * This,
/* [out] */ __RPC__out DWORD *pdwInputMinimum,
/* [out] */ __RPC__out DWORD *pdwInputMaximum,
/* [out] */ __RPC__out DWORD *pdwOutputMinimum,
/* [out] */ __RPC__out DWORD *pdwOutputMaximum);
DECLSPEC_XFGVIRT(IMFTransform, GetStreamCount)
HRESULT ( STDMETHODCALLTYPE *GetStreamCount )(
__RPC__in IMFTransform * This,
/* [out] */ __RPC__out DWORD *pcInputStreams,
/* [out] */ __RPC__out DWORD *pcOutputStreams);
DECLSPEC_XFGVIRT(IMFTransform, GetStreamIDs)
HRESULT ( STDMETHODCALLTYPE *GetStreamIDs )(
__RPC__in IMFTransform * This,
DWORD dwInputIDArraySize,
/* [size_is][out] */ __RPC__out_ecount_full(dwInputIDArraySize) DWORD *pdwInputIDs,
DWORD dwOutputIDArraySize,
/* [size_is][out] */ __RPC__out_ecount_full(dwOutputIDArraySize) DWORD *pdwOutputIDs);
DECLSPEC_XFGVIRT(IMFTransform, GetInputStreamInfo)
HRESULT ( STDMETHODCALLTYPE *GetInputStreamInfo )(
__RPC__in IMFTransform * This,
DWORD dwInputStreamID,
/* [out] */ __RPC__out MFT_INPUT_STREAM_INFO *pStreamInfo);
DECLSPEC_XFGVIRT(IMFTransform, GetOutputStreamInfo)
HRESULT ( STDMETHODCALLTYPE *GetOutputStreamInfo )(
__RPC__in IMFTransform * This,
DWORD dwOutputStreamID,
/* [out] */ __RPC__out MFT_OUTPUT_STREAM_INFO *pStreamInfo);
DECLSPEC_XFGVIRT(IMFTransform, GetAttributes)
HRESULT ( STDMETHODCALLTYPE *GetAttributes )(
__RPC__in IMFTransform * This,
/* [out] */ __RPC__deref_out_opt IMFAttributes **pAttributes);
DECLSPEC_XFGVIRT(IMFTransform, GetInputStreamAttributes)
HRESULT ( STDMETHODCALLTYPE *GetInputStreamAttributes )(
__RPC__in IMFTransform * This,
DWORD dwInputStreamID,
/* [out] */ __RPC__deref_out_opt IMFAttributes **pAttributes);
DECLSPEC_XFGVIRT(IMFTransform, GetOutputStreamAttributes)
HRESULT ( STDMETHODCALLTYPE *GetOutputStreamAttributes )(
__RPC__in IMFTransform * This,
DWORD dwOutputStreamID,
/* [out] */ __RPC__deref_out_opt IMFAttributes **pAttributes);
DECLSPEC_XFGVIRT(IMFTransform, DeleteInputStream)
HRESULT ( STDMETHODCALLTYPE *DeleteInputStream )(
__RPC__in IMFTransform * This,
DWORD dwStreamID);
DECLSPEC_XFGVIRT(IMFTransform, AddInputStreams)
HRESULT ( STDMETHODCALLTYPE *AddInputStreams )(
__RPC__in IMFTransform * This,
DWORD cStreams,
/* [in] */ __RPC__in DWORD *adwStreamIDs);
DECLSPEC_XFGVIRT(IMFTransform, GetInputAvailableType)
HRESULT ( STDMETHODCALLTYPE *GetInputAvailableType )(
__RPC__in IMFTransform * This,
DWORD dwInputStreamID,
DWORD dwTypeIndex,
/* [out] */ __RPC__deref_out_opt IMFMediaType **ppType);
DECLSPEC_XFGVIRT(IMFTransform, GetOutputAvailableType)
HRESULT ( STDMETHODCALLTYPE *GetOutputAvailableType )(
__RPC__in IMFTransform * This,
DWORD dwOutputStreamID,
DWORD dwTypeIndex,
/* [out] */ __RPC__deref_out_opt IMFMediaType **ppType);
DECLSPEC_XFGVIRT(IMFTransform, SetInputType)
HRESULT ( STDMETHODCALLTYPE *SetInputType )(
__RPC__in IMFTransform * This,
DWORD dwInputStreamID,
/* [in] */ __RPC__in_opt IMFMediaType *pType,
DWORD dwFlags);
DECLSPEC_XFGVIRT(IMFTransform, SetOutputType)
HRESULT ( STDMETHODCALLTYPE *SetOutputType )(
__RPC__in IMFTransform * This,
DWORD dwOutputStreamID,
/* [in] */ __RPC__in_opt IMFMediaType *pType,
DWORD dwFlags);
DECLSPEC_XFGVIRT(IMFTransform, GetInputCurrentType)
HRESULT ( STDMETHODCALLTYPE *GetInputCurrentType )(
__RPC__in IMFTransform * This,
DWORD dwInputStreamID,
/* [out] */ __RPC__deref_out_opt IMFMediaType **ppType);
DECLSPEC_XFGVIRT(IMFTransform, GetOutputCurrentType)
HRESULT ( STDMETHODCALLTYPE *GetOutputCurrentType )(
__RPC__in IMFTransform * This,
DWORD dwOutputStreamID,
/* [out] */ __RPC__deref_out_opt IMFMediaType **ppType);
DECLSPEC_XFGVIRT(IMFTransform, GetInputStatus)
HRESULT ( STDMETHODCALLTYPE *GetInputStatus )(
__RPC__in IMFTransform * This,
DWORD dwInputStreamID,
/* [out] */ __RPC__out DWORD *pdwFlags);
DECLSPEC_XFGVIRT(IMFTransform, GetOutputStatus)
HRESULT ( STDMETHODCALLTYPE *GetOutputStatus )(
__RPC__in IMFTransform * This,
/* [out] */ __RPC__out DWORD *pdwFlags);
DECLSPEC_XFGVIRT(IMFTransform, SetOutputBounds)
HRESULT ( STDMETHODCALLTYPE *SetOutputBounds )(
__RPC__in IMFTransform * This,
LONGLONG hnsLowerBound,
LONGLONG hnsUpperBound);
DECLSPEC_XFGVIRT(IMFTransform, ProcessEvent)
HRESULT ( STDMETHODCALLTYPE *ProcessEvent )(
__RPC__in IMFTransform * This,
DWORD dwInputStreamID,
/* [in] */ __RPC__in_opt IMFMediaEvent *pEvent);
DECLSPEC_XFGVIRT(IMFTransform, ProcessMessage)
HRESULT ( STDMETHODCALLTYPE *ProcessMessage )(
__RPC__in IMFTransform * This,
MFT_MESSAGE_TYPE eMessage,
ULONG_PTR ulParam);
DECLSPEC_XFGVIRT(IMFTransform, ProcessInput)
/* [local] */ HRESULT ( STDMETHODCALLTYPE *ProcessInput )(
IMFTransform * This,
DWORD dwInputStreamID,
IMFSample *pSample,
DWORD dwFlags);
DECLSPEC_XFGVIRT(IMFTransform, ProcessOutput)
/* [local] */ HRESULT ( STDMETHODCALLTYPE *ProcessOutput )(
IMFTransform * This,
DWORD dwFlags,
DWORD cOutputBufferCount,
/* [size_is][out][in] */ MFT_OUTPUT_DATA_BUFFER *pOutputSamples,
/* [out] */ DWORD *pdwStatus);
END_INTERFACE
} IMFTransformVtbl;
interface IMFTransform
{
CONST_VTBL struct IMFTransformVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define IMFTransform_QueryInterface(This,riid,ppvObject) \
( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) )
#define IMFTransform_AddRef(This) \
( (This)->lpVtbl -> AddRef(This) )
#define IMFTransform_Release(This) \
( (This)->lpVtbl -> Release(This) )
#define IMFTransform_GetStreamLimits(This,pdwInputMinimum,pdwInputMaximum,pdwOutputMinimum,pdwOutputMaximum) \
( (This)->lpVtbl -> GetStreamLimits(This,pdwInputMinimum,pdwInputMaximum,pdwOutputMinimum,pdwOutputMaximum) )
#define IMFTransform_GetStreamCount(This,pcInputStreams,pcOutputStreams) \
( (This)->lpVtbl -> GetStreamCount(This,pcInputStreams,pcOutputStreams) )
#define IMFTransform_GetStreamIDs(This,dwInputIDArraySize,pdwInputIDs,dwOutputIDArraySize,pdwOutputIDs) \
( (This)->lpVtbl -> GetStreamIDs(This,dwInputIDArraySize,pdwInputIDs,dwOutputIDArraySize,pdwOutputIDs) )
#define IMFTransform_GetInputStreamInfo(This,dwInputStreamID,pStreamInfo) \
( (This)->lpVtbl -> GetInputStreamInfo(This,dwInputStreamID,pStreamInfo) )
#define IMFTransform_GetOutputStreamInfo(This,dwOutputStreamID,pStreamInfo) \
( (This)->lpVtbl -> GetOutputStreamInfo(This,dwOutputStreamID,pStreamInfo) )
#define IMFTransform_GetAttributes(This,pAttributes) \
( (This)->lpVtbl -> GetAttributes(This,pAttributes) )
#define IMFTransform_GetInputStreamAttributes(This,dwInputStreamID,pAttributes) \
( (This)->lpVtbl -> GetInputStreamAttributes(This,dwInputStreamID,pAttributes) )
#define IMFTransform_GetOutputStreamAttributes(This,dwOutputStreamID,pAttributes) \
( (This)->lpVtbl -> GetOutputStreamAttributes(This,dwOutputStreamID,pAttributes) )
#define IMFTransform_DeleteInputStream(This,dwStreamID) \
( (This)->lpVtbl -> DeleteInputStream(This,dwStreamID) )
#define IMFTransform_AddInputStreams(This,cStreams,adwStreamIDs) \
( (This)->lpVtbl -> AddInputStreams(This,cStreams,adwStreamIDs) )
#define IMFTransform_GetInputAvailableType(This,dwInputStreamID,dwTypeIndex,ppType) \
( (This)->lpVtbl -> GetInputAvailableType(This,dwInputStreamID,dwTypeIndex,ppType) )
#define IMFTransform_GetOutputAvailableType(This,dwOutputStreamID,dwTypeIndex,ppType) \
( (This)->lpVtbl -> GetOutputAvailableType(This,dwOutputStreamID,dwTypeIndex,ppType) )
#define IMFTransform_SetInputType(This,dwInputStreamID,pType,dwFlags) \
( (This)->lpVtbl -> SetInputType(This,dwInputStreamID,pType,dwFlags) )
#define IMFTransform_SetOutputType(This,dwOutputStreamID,pType,dwFlags) \
( (This)->lpVtbl -> SetOutputType(This,dwOutputStreamID,pType,dwFlags) )
#define IMFTransform_GetInputCurrentType(This,dwInputStreamID,ppType) \
( (This)->lpVtbl -> GetInputCurrentType(This,dwInputStreamID,ppType) )
#define IMFTransform_GetOutputCurrentType(This,dwOutputStreamID,ppType) \
( (This)->lpVtbl -> GetOutputCurrentType(This,dwOutputStreamID,ppType) )
#define IMFTransform_GetInputStatus(This,dwInputStreamID,pdwFlags) \
( (This)->lpVtbl -> GetInputStatus(This,dwInputStreamID,pdwFlags) )
#define IMFTransform_GetOutputStatus(This,pdwFlags) \
( (This)->lpVtbl -> GetOutputStatus(This,pdwFlags) )
#define IMFTransform_SetOutputBounds(This,hnsLowerBound,hnsUpperBound) \
( (This)->lpVtbl -> SetOutputBounds(This,hnsLowerBound,hnsUpperBound) )
#define IMFTransform_ProcessEvent(This,dwInputStreamID,pEvent) \
( (This)->lpVtbl -> ProcessEvent(This,dwInputStreamID,pEvent) )
#define IMFTransform_ProcessMessage(This,eMessage,ulParam) \
( (This)->lpVtbl -> ProcessMessage(This,eMessage,ulParam) )
#define IMFTransform_ProcessInput(This,dwInputStreamID,pSample,dwFlags) \
( (This)->lpVtbl -> ProcessInput(This,dwInputStreamID,pSample,dwFlags) )
#define IMFTransform_ProcessOutput(This,dwFlags,cOutputBufferCount,pOutputSamples,pdwStatus) \
( (This)->lpVtbl -> ProcessOutput(This,dwFlags,cOutputBufferCount,pOutputSamples,pdwStatus) )
#endif /* COBJMACROS */
#endif /* C style interface */
#endif /* __IMFTransform_INTERFACE_DEFINED__ */
/* interface __MIDL_itf_mftransform_0000_0001 */
/* [local] */
#endif /* WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP | WINAPI_PARTITION_GAMES) */
#pragma endregion
typedef
enum _DeviceStreamState
{
DeviceStreamState_Stop = 0,
DeviceStreamState_Pause = ( DeviceStreamState_Stop + 1 ) ,
DeviceStreamState_Run = ( DeviceStreamState_Pause + 1 ) ,
DeviceStreamState_Disabled = ( DeviceStreamState_Run + 1 )
} DeviceStreamState;
typedef enum _DeviceStreamState *PDeviceStreamState;
EXTERN_GUID(MEDeviceStreamCreated, 0x0252a1cf, 0x3540, 0x43b4, 0x91, 0x64, 0xd7, 0x2e, 0xb4, 0x05, 0xfa, 0x40);
#if (WINVER >= _WIN32_WINNT_WIN7)
#pragma region Desktop Family
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
typedef struct _STREAM_MEDIUM
{
GUID gidMedium;
UINT32 unMediumInstance;
} STREAM_MEDIUM;
typedef struct _STREAM_MEDIUM *PSTREAM_MEDIUM;
#endif /* WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) */
#pragma endregion
#endif // (WINVER >= _WIN32_WINNT_WIN7)
#pragma region Application or Games Family
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP | WINAPI_PARTITION_GAMES)
//
// Define the MFT methods back so we don't accidentally hose the IMediaObject interface.
//
#ifdef MFT_UNIQUE_METHOD_NAMES
#undef GetStreamLimits
#undef GetStreamCount
#undef GetStreamIDs
#undef GetInputStreamInfo
#undef GetOutputStreamInfo
#undef DeleteInputStream
#undef AddInputStreams
#undef GetInputAvailableType
#undef GetOutputAvailableType
#undef SetInputType
#undef SetOutputType
#undef GetInputCurrentType
#undef GetOutputCurrentType
#undef GetInputStatus
#undef GetOutputStatus
#undef SetOutputBounds
#undef ProcessMessage
#undef ProcessInput
#undef ProcessOutput
#endif
EXTERN_C const DECLSPEC_SELECTANY PROPERTYKEY MFPKEY_CLSID = { { 0xc57a84c0, 0x1a80, 0x40a3, {0x97, 0xb5, 0x92, 0x72, 0xa4, 0x3, 0xc8, 0xae} }, 0x01 };
EXTERN_C const DECLSPEC_SELECTANY PROPERTYKEY MFPKEY_CATEGORY = { { 0xc57a84c0, 0x1a80, 0x40a3, {0x97, 0xb5, 0x92, 0x72, 0xa4, 0x3, 0xc8, 0xae} }, 0x02 };
EXTERN_C const DECLSPEC_SELECTANY PROPERTYKEY MFPKEY_EXATTRIBUTE_SUPPORTED = { { 0x456fe843, 0x3c87, 0x40c0, {0x94, 0x9d, 0x14, 0x9, 0xc9, 0x7d, 0xab, 0x2c} }, 0x01 };
EXTERN_C const DECLSPEC_SELECTANY PROPERTYKEY MFPKEY_MULTICHANNEL_CHANNEL_MASK = { { 0x58bdaf8c, 0x3224, 0x4692, { 0x86, 0xd0, 0x44, 0xd6, 0x5c, 0x5b, 0xf8, 0x2b } }, 0x01 };
EXTERN_C const DECLSPEC_SELECTANY GUID MF_SA_D3D_AWARE = { 0xeaa35c29, 0x775e, 0x488e, { 0x9b, 0x61, 0xb3, 0x28, 0x3e, 0x49, 0x58, 0x3b } };
EXTERN_C const DECLSPEC_SELECTANY GUID MF_SA_REQUIRED_SAMPLE_COUNT = { 0x18802c61, 0x324b, 0x4952, { 0xab, 0xd0, 0x17, 0x6f, 0xf5, 0xc6, 0x96, 0xff } };
EXTERN_C const DECLSPEC_SELECTANY GUID MFT_END_STREAMING_AWARE = { 0x70fbc845, 0xb07e, 0x4089, { 0xb0, 0x64, 0x39, 0x9d, 0xc6, 0x11, 0xf, 0x29 } };
EXTERN_C const DECLSPEC_SELECTANY GUID MF_SA_AUDIO_ENDPOINT_AWARE = { 0xc0381701, 0x805c, 0x42b2,{ 0xac, 0x8d, 0xe2, 0xb4, 0xbf, 0x21, 0xf4, 0xf8 } };
EXTERN_C const DECLSPEC_SELECTANY GUID MFT_AUDIO_DECODER_AUDIO_ENDPOINT_ID = { 0xc7ccdd6e, 0x5398, 0x4695,{ 0x8b, 0xe7, 0x51, 0xb3, 0xe9, 0x51, 0x11, 0xbd } };
EXTERN_C const DECLSPEC_SELECTANY GUID MFT_AUDIO_DECODER_SPATIAL_METADATA_CLIENT = { 0x5987df4, 0x1270, 0x4999,{ 0x92, 0x5f, 0x8e, 0x93, 0x9a, 0x7c, 0xa, 0xf7 } };
#endif /* WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP | WINAPI_PARTITION_GAMES) */
#pragma endregion
#if (WINVER >= _WIN32_WINNT_WINTHRESHOLD)
extern RPC_IF_HANDLE __MIDL_itf_mftransform_0000_0001_v0_0_c_ifspec;
extern RPC_IF_HANDLE __MIDL_itf_mftransform_0000_0001_v0_0_s_ifspec;
#ifndef __IMFDeviceTransform_INTERFACE_DEFINED__
#define __IMFDeviceTransform_INTERFACE_DEFINED__
/* interface IMFDeviceTransform */
/* [local][uuid][object] */
EXTERN_C const IID IID_IMFDeviceTransform;
#if defined(__cplusplus) && !defined(CINTERFACE)
MIDL_INTERFACE("D818FBD8-FC46-42F2-87AC-1EA2D1F9BF32")
IMFDeviceTransform : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE InitializeTransform(
/* [annotation][in] */
_In_ IMFAttributes *pAttributes) = 0;
virtual HRESULT STDMETHODCALLTYPE GetInputAvailableType(
/* [annotation][in] */
_In_ DWORD dwInputStreamID,
/* [annotation][in] */
_In_ DWORD dwTypeIndex,
/* [annotation][out] */
_COM_Outptr_ IMFMediaType **pMediaType) = 0;
virtual HRESULT STDMETHODCALLTYPE GetInputCurrentType(
/* [annotation][in] */
_In_ DWORD dwInputStreamID,
/* [annotation][out] */
_COM_Outptr_ IMFMediaType **pMediaType) = 0;
virtual HRESULT STDMETHODCALLTYPE GetInputStreamAttributes(
/* [annotation][in] */
_In_ DWORD dwInputStreamID,
/* [annotation][out] */
_COM_Outptr_ IMFAttributes **ppAttributes) = 0;
virtual HRESULT STDMETHODCALLTYPE GetOutputAvailableType(
/* [annotation][in] */
_In_ DWORD dwOutputStreamID,
/* [annotation][in] */
_In_ DWORD dwTypeIndex,
/* [annotation][out] */
_COM_Outptr_ IMFMediaType **pMediaType) = 0;
virtual HRESULT STDMETHODCALLTYPE GetOutputCurrentType(
/* [annotation][in] */
_In_ DWORD dwOutputStreamID,
/* [annotation][out] */
_COM_Outptr_ IMFMediaType **pMediaType) = 0;
virtual HRESULT STDMETHODCALLTYPE GetOutputStreamAttributes(
/* [annotation][in] */
_In_ DWORD dwOutputStreamID,
/* [annotation][out] */
_COM_Outptr_ IMFAttributes **ppAttributes) = 0;
virtual HRESULT STDMETHODCALLTYPE GetStreamCount(
/* [annotation][out] */
_Out_ DWORD *pcInputStreams,
/* [annotation][out] */
_Out_ DWORD *pcOutputStreams) = 0;
virtual HRESULT STDMETHODCALLTYPE GetStreamIDs(
/* [annotation][in] */
_In_ DWORD dwInputIDArraySize,
/* [annotation][out] */
_Out_ DWORD *pdwInputStreamIds,
/* [annotation][in] */
_In_ DWORD dwOutputIDArraySize,
/* [annotation][out] */
_Out_ DWORD *pdwOutputStreamIds) = 0;
virtual HRESULT STDMETHODCALLTYPE ProcessEvent(
/* [annotation][in] */
_In_ DWORD dwInputStreamID,
/* [annotation][in] */
_In_ IMFMediaEvent *pEvent) = 0;
virtual HRESULT STDMETHODCALLTYPE ProcessInput(
/* [annotation][in] */
_In_ DWORD dwInputStreamID,
/* [annotation][in] */
_In_ IMFSample *pSample,
/* [annotation][in] */
_In_ DWORD dwFlags) = 0;
virtual HRESULT STDMETHODCALLTYPE ProcessMessage(
/* [annotation][in] */
_In_ MFT_MESSAGE_TYPE eMessage,
/* [annotation][in] */
_In_ ULONG_PTR ulParam) = 0;
virtual HRESULT STDMETHODCALLTYPE ProcessOutput(
/* [annotation][in] */
_In_ DWORD dwFlags,
/* [annotation][in] */
_In_ DWORD cOutputBufferCount,
/* [size_is][annotation][out][in] */
_Inout_ MFT_OUTPUT_DATA_BUFFER *pOutputSample,
/* [annotation][out] */
_Out_ DWORD *pdwStatus) = 0;
virtual HRESULT STDMETHODCALLTYPE SetInputStreamState(
/* [annotation][in] */
_In_ DWORD dwStreamID,
/* [annotation][in] */
_In_ IMFMediaType *pMediaType,
/* [annotation][in] */
_In_ DeviceStreamState value,
/* [annotation][in] */
_In_ DWORD dwFlags) = 0;
virtual HRESULT STDMETHODCALLTYPE GetInputStreamState(
/* [annotation][in] */
_In_ DWORD dwStreamID,
/* [annotation][out] */
_Out_ DeviceStreamState *value) = 0;
virtual HRESULT STDMETHODCALLTYPE SetOutputStreamState(
/* [annotation][in] */
_In_ DWORD dwStreamID,
/* [annotation][in] */
_In_ IMFMediaType *pMediaType,
/* [annotation][in] */
_In_ DeviceStreamState value,
/* [annotation][in] */
_In_ DWORD dwFlags) = 0;
virtual HRESULT STDMETHODCALLTYPE GetOutputStreamState(
/* [annotation][in] */
_In_ DWORD dwStreamID,
/* [annotation][out] */
_Out_ DeviceStreamState *value) = 0;
virtual HRESULT STDMETHODCALLTYPE GetInputStreamPreferredState(
/* [annotation][in] */
_In_ DWORD dwStreamID,
/* [annotation][out] */
_Out_ DeviceStreamState *value,
/* [annotation][out] */
_COM_Outptr_ IMFMediaType **ppMediaType) = 0;
virtual HRESULT STDMETHODCALLTYPE FlushInputStream(
/* [annotation][in] */
_In_ DWORD dwStreamIndex,
/* [annotation][in] */
_In_ DWORD dwFlags) = 0;
virtual HRESULT STDMETHODCALLTYPE FlushOutputStream(
/* [annotation][in] */
_In_ DWORD dwStreamIndex,
/* [annotation][in] */
_In_ DWORD dwFlags) = 0;
};
#else /* C style interface */
typedef struct IMFDeviceTransformVtbl
{
BEGIN_INTERFACE
DECLSPEC_XFGVIRT(IUnknown, QueryInterface)
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
IMFDeviceTransform * This,
/* [in] */ REFIID riid,
/* [annotation][iid_is][out] */
_COM_Outptr_ void **ppvObject);
DECLSPEC_XFGVIRT(IUnknown, AddRef)
ULONG ( STDMETHODCALLTYPE *AddRef )(
IMFDeviceTransform * This);
DECLSPEC_XFGVIRT(IUnknown, Release)
ULONG ( STDMETHODCALLTYPE *Release )(
IMFDeviceTransform * This);
DECLSPEC_XFGVIRT(IMFDeviceTransform, InitializeTransform)
HRESULT ( STDMETHODCALLTYPE *InitializeTransform )(
IMFDeviceTransform * This,
/* [annotation][in] */
_In_ IMFAttributes *pAttributes);
DECLSPEC_XFGVIRT(IMFDeviceTransform, GetInputAvailableType)
HRESULT ( STDMETHODCALLTYPE *GetInputAvailableType )(
IMFDeviceTransform * This,
/* [annotation][in] */
_In_ DWORD dwInputStreamID,
/* [annotation][in] */
_In_ DWORD dwTypeIndex,
/* [annotation][out] */
_COM_Outptr_ IMFMediaType **pMediaType);
DECLSPEC_XFGVIRT(IMFDeviceTransform, GetInputCurrentType)
HRESULT ( STDMETHODCALLTYPE *GetInputCurrentType )(
IMFDeviceTransform * This,
/* [annotation][in] */
_In_ DWORD dwInputStreamID,
/* [annotation][out] */
_COM_Outptr_ IMFMediaType **pMediaType);
DECLSPEC_XFGVIRT(IMFDeviceTransform, GetInputStreamAttributes)
HRESULT ( STDMETHODCALLTYPE *GetInputStreamAttributes )(
IMFDeviceTransform * This,
/* [annotation][in] */
_In_ DWORD dwInputStreamID,
/* [annotation][out] */
_COM_Outptr_ IMFAttributes **ppAttributes);
DECLSPEC_XFGVIRT(IMFDeviceTransform, GetOutputAvailableType)
HRESULT ( STDMETHODCALLTYPE *GetOutputAvailableType )(
IMFDeviceTransform * This,
/* [annotation][in] */
_In_ DWORD dwOutputStreamID,
/* [annotation][in] */
_In_ DWORD dwTypeIndex,
/* [annotation][out] */
_COM_Outptr_ IMFMediaType **pMediaType);
DECLSPEC_XFGVIRT(IMFDeviceTransform, GetOutputCurrentType)
HRESULT ( STDMETHODCALLTYPE *GetOutputCurrentType )(
IMFDeviceTransform * This,
/* [annotation][in] */
_In_ DWORD dwOutputStreamID,
/* [annotation][out] */
_COM_Outptr_ IMFMediaType **pMediaType);
DECLSPEC_XFGVIRT(IMFDeviceTransform, GetOutputStreamAttributes)
HRESULT ( STDMETHODCALLTYPE *GetOutputStreamAttributes )(
IMFDeviceTransform * This,
/* [annotation][in] */
_In_ DWORD dwOutputStreamID,
/* [annotation][out] */
_COM_Outptr_ IMFAttributes **ppAttributes);
DECLSPEC_XFGVIRT(IMFDeviceTransform, GetStreamCount)
HRESULT ( STDMETHODCALLTYPE *GetStreamCount )(
IMFDeviceTransform * This,
/* [annotation][out] */
_Out_ DWORD *pcInputStreams,
/* [annotation][out] */
_Out_ DWORD *pcOutputStreams);
DECLSPEC_XFGVIRT(IMFDeviceTransform, GetStreamIDs)
HRESULT ( STDMETHODCALLTYPE *GetStreamIDs )(
IMFDeviceTransform * This,
/* [annotation][in] */
_In_ DWORD dwInputIDArraySize,
/* [annotation][out] */
_Out_ DWORD *pdwInputStreamIds,
/* [annotation][in] */
_In_ DWORD dwOutputIDArraySize,
/* [annotation][out] */
_Out_ DWORD *pdwOutputStreamIds);
DECLSPEC_XFGVIRT(IMFDeviceTransform, ProcessEvent)
HRESULT ( STDMETHODCALLTYPE *ProcessEvent )(
IMFDeviceTransform * This,
/* [annotation][in] */
_In_ DWORD dwInputStreamID,
/* [annotation][in] */
_In_ IMFMediaEvent *pEvent);
DECLSPEC_XFGVIRT(IMFDeviceTransform, ProcessInput)
HRESULT ( STDMETHODCALLTYPE *ProcessInput )(
IMFDeviceTransform * This,
/* [annotation][in] */
_In_ DWORD dwInputStreamID,
/* [annotation][in] */
_In_ IMFSample *pSample,
/* [annotation][in] */
_In_ DWORD dwFlags);
DECLSPEC_XFGVIRT(IMFDeviceTransform, ProcessMessage)
HRESULT ( STDMETHODCALLTYPE *ProcessMessage )(
IMFDeviceTransform * This,
/* [annotation][in] */
_In_ MFT_MESSAGE_TYPE eMessage,
/* [annotation][in] */
_In_ ULONG_PTR ulParam);
DECLSPEC_XFGVIRT(IMFDeviceTransform, ProcessOutput)
HRESULT ( STDMETHODCALLTYPE *ProcessOutput )(
IMFDeviceTransform * This,
/* [annotation][in] */
_In_ DWORD dwFlags,
/* [annotation][in] */
_In_ DWORD cOutputBufferCount,
/* [size_is][annotation][out][in] */
_Inout_ MFT_OUTPUT_DATA_BUFFER *pOutputSample,
/* [annotation][out] */
_Out_ DWORD *pdwStatus);
DECLSPEC_XFGVIRT(IMFDeviceTransform, SetInputStreamState)
HRESULT ( STDMETHODCALLTYPE *SetInputStreamState )(
IMFDeviceTransform * This,
/* [annotation][in] */
_In_ DWORD dwStreamID,
/* [annotation][in] */
_In_ IMFMediaType *pMediaType,
/* [annotation][in] */
_In_ DeviceStreamState value,
/* [annotation][in] */
_In_ DWORD dwFlags);
DECLSPEC_XFGVIRT(IMFDeviceTransform, GetInputStreamState)
HRESULT ( STDMETHODCALLTYPE *GetInputStreamState )(
IMFDeviceTransform * This,
/* [annotation][in] */
_In_ DWORD dwStreamID,
/* [annotation][out] */
_Out_ DeviceStreamState *value);
DECLSPEC_XFGVIRT(IMFDeviceTransform, SetOutputStreamState)
HRESULT ( STDMETHODCALLTYPE *SetOutputStreamState )(
IMFDeviceTransform * This,
/* [annotation][in] */
_In_ DWORD dwStreamID,
/* [annotation][in] */
_In_ IMFMediaType *pMediaType,
/* [annotation][in] */
_In_ DeviceStreamState value,
/* [annotation][in] */
_In_ DWORD dwFlags);
DECLSPEC_XFGVIRT(IMFDeviceTransform, GetOutputStreamState)
HRESULT ( STDMETHODCALLTYPE *GetOutputStreamState )(
IMFDeviceTransform * This,
/* [annotation][in] */
_In_ DWORD dwStreamID,
/* [annotation][out] */
_Out_ DeviceStreamState *value);
DECLSPEC_XFGVIRT(IMFDeviceTransform, GetInputStreamPreferredState)
HRESULT ( STDMETHODCALLTYPE *GetInputStreamPreferredState )(
IMFDeviceTransform * This,
/* [annotation][in] */
_In_ DWORD dwStreamID,
/* [annotation][out] */
_Out_ DeviceStreamState *value,
/* [annotation][out] */
_COM_Outptr_ IMFMediaType **ppMediaType);
DECLSPEC_XFGVIRT(IMFDeviceTransform, FlushInputStream)
HRESULT ( STDMETHODCALLTYPE *FlushInputStream )(
IMFDeviceTransform * This,
/* [annotation][in] */
_In_ DWORD dwStreamIndex,
/* [annotation][in] */
_In_ DWORD dwFlags);
DECLSPEC_XFGVIRT(IMFDeviceTransform, FlushOutputStream)
HRESULT ( STDMETHODCALLTYPE *FlushOutputStream )(
IMFDeviceTransform * This,
/* [annotation][in] */
_In_ DWORD dwStreamIndex,
/* [annotation][in] */
_In_ DWORD dwFlags);
END_INTERFACE
} IMFDeviceTransformVtbl;
interface IMFDeviceTransform
{
CONST_VTBL struct IMFDeviceTransformVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define IMFDeviceTransform_QueryInterface(This,riid,ppvObject) \
( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) )
#define IMFDeviceTransform_AddRef(This) \
( (This)->lpVtbl -> AddRef(This) )
#define IMFDeviceTransform_Release(This) \
( (This)->lpVtbl -> Release(This) )
#define IMFDeviceTransform_InitializeTransform(This,pAttributes) \
( (This)->lpVtbl -> InitializeTransform(This,pAttributes) )
#define IMFDeviceTransform_GetInputAvailableType(This,dwInputStreamID,dwTypeIndex,pMediaType) \
( (This)->lpVtbl -> GetInputAvailableType(This,dwInputStreamID,dwTypeIndex,pMediaType) )
#define IMFDeviceTransform_GetInputCurrentType(This,dwInputStreamID,pMediaType) \
( (This)->lpVtbl -> GetInputCurrentType(This,dwInputStreamID,pMediaType) )
#define IMFDeviceTransform_GetInputStreamAttributes(This,dwInputStreamID,ppAttributes) \
( (This)->lpVtbl -> GetInputStreamAttributes(This,dwInputStreamID,ppAttributes) )
#define IMFDeviceTransform_GetOutputAvailableType(This,dwOutputStreamID,dwTypeIndex,pMediaType) \
( (This)->lpVtbl -> GetOutputAvailableType(This,dwOutputStreamID,dwTypeIndex,pMediaType) )
#define IMFDeviceTransform_GetOutputCurrentType(This,dwOutputStreamID,pMediaType) \
( (This)->lpVtbl -> GetOutputCurrentType(This,dwOutputStreamID,pMediaType) )
#define IMFDeviceTransform_GetOutputStreamAttributes(This,dwOutputStreamID,ppAttributes) \
( (This)->lpVtbl -> GetOutputStreamAttributes(This,dwOutputStreamID,ppAttributes) )
#define IMFDeviceTransform_GetStreamCount(This,pcInputStreams,pcOutputStreams) \
( (This)->lpVtbl -> GetStreamCount(This,pcInputStreams,pcOutputStreams) )
#define IMFDeviceTransform_GetStreamIDs(This,dwInputIDArraySize,pdwInputStreamIds,dwOutputIDArraySize,pdwOutputStreamIds) \
( (This)->lpVtbl -> GetStreamIDs(This,dwInputIDArraySize,pdwInputStreamIds,dwOutputIDArraySize,pdwOutputStreamIds) )
#define IMFDeviceTransform_ProcessEvent(This,dwInputStreamID,pEvent) \
( (This)->lpVtbl -> ProcessEvent(This,dwInputStreamID,pEvent) )
#define IMFDeviceTransform_ProcessInput(This,dwInputStreamID,pSample,dwFlags) \
( (This)->lpVtbl -> ProcessInput(This,dwInputStreamID,pSample,dwFlags) )
#define IMFDeviceTransform_ProcessMessage(This,eMessage,ulParam) \
( (This)->lpVtbl -> ProcessMessage(This,eMessage,ulParam) )
#define IMFDeviceTransform_ProcessOutput(This,dwFlags,cOutputBufferCount,pOutputSample,pdwStatus) \
( (This)->lpVtbl -> ProcessOutput(This,dwFlags,cOutputBufferCount,pOutputSample,pdwStatus) )
#define IMFDeviceTransform_SetInputStreamState(This,dwStreamID,pMediaType,value,dwFlags) \
( (This)->lpVtbl -> SetInputStreamState(This,dwStreamID,pMediaType,value,dwFlags) )
#define IMFDeviceTransform_GetInputStreamState(This,dwStreamID,value) \
( (This)->lpVtbl -> GetInputStreamState(This,dwStreamID,value) )
#define IMFDeviceTransform_SetOutputStreamState(This,dwStreamID,pMediaType,value,dwFlags) \
( (This)->lpVtbl -> SetOutputStreamState(This,dwStreamID,pMediaType,value,dwFlags) )
#define IMFDeviceTransform_GetOutputStreamState(This,dwStreamID,value) \
( (This)->lpVtbl -> GetOutputStreamState(This,dwStreamID,value) )
#define IMFDeviceTransform_GetInputStreamPreferredState(This,dwStreamID,value,ppMediaType) \
( (This)->lpVtbl -> GetInputStreamPreferredState(This,dwStreamID,value,ppMediaType) )
#define IMFDeviceTransform_FlushInputStream(This,dwStreamIndex,dwFlags) \
( (This)->lpVtbl -> FlushInputStream(This,dwStreamIndex,dwFlags) )
#define IMFDeviceTransform_FlushOutputStream(This,dwStreamIndex,dwFlags) \
( (This)->lpVtbl -> FlushOutputStream(This,dwStreamIndex,dwFlags) )
#endif /* COBJMACROS */
#endif /* C style interface */
#endif /* __IMFDeviceTransform_INTERFACE_DEFINED__ */
/* interface __MIDL_itf_mftransform_0000_0002 */
/* [local] */
#endif // (WINVER >= _WIN32_WINNT_WINTHRESHOLD )
#if (WINVER >= _WIN32_WINNT_WIN10)
EXTERN_GUID( MF_DMFT_FRAME_BUFFER_INFO, 0x396CE1C9, 0x67A9, 0x454C, 0x87, 0x97, 0x95, 0xA4, 0x57, 0x99, 0xD8, 0x04);
extern RPC_IF_HANDLE __MIDL_itf_mftransform_0000_0002_v0_0_c_ifspec;
extern RPC_IF_HANDLE __MIDL_itf_mftransform_0000_0002_v0_0_s_ifspec;
#ifndef __IMFDeviceTransformCallback_INTERFACE_DEFINED__
#define __IMFDeviceTransformCallback_INTERFACE_DEFINED__
/* interface IMFDeviceTransformCallback */
/* [local][helpstring][uuid][object] */
EXTERN_C const IID IID_IMFDeviceTransformCallback;
#if defined(__cplusplus) && !defined(CINTERFACE)
MIDL_INTERFACE("6D5CB646-29EC-41FB-8179-8C4C6D750811")
IMFDeviceTransformCallback : public IUnknown
{
public:
virtual HRESULT STDMETHODCALLTYPE OnBufferSent(
/* [annotation][in] */
_In_ IMFAttributes *pCallbackAttributes,
/* [annotation][in] */
_In_ DWORD pinId) = 0;
};
#else /* C style interface */
typedef struct IMFDeviceTransformCallbackVtbl
{
BEGIN_INTERFACE
DECLSPEC_XFGVIRT(IUnknown, QueryInterface)
HRESULT ( STDMETHODCALLTYPE *QueryInterface )(
IMFDeviceTransformCallback * This,
/* [in] */ REFIID riid,
/* [annotation][iid_is][out] */
_COM_Outptr_ void **ppvObject);
DECLSPEC_XFGVIRT(IUnknown, AddRef)
ULONG ( STDMETHODCALLTYPE *AddRef )(
IMFDeviceTransformCallback * This);
DECLSPEC_XFGVIRT(IUnknown, Release)
ULONG ( STDMETHODCALLTYPE *Release )(
IMFDeviceTransformCallback * This);
DECLSPEC_XFGVIRT(IMFDeviceTransformCallback, OnBufferSent)
HRESULT ( STDMETHODCALLTYPE *OnBufferSent )(
IMFDeviceTransformCallback * This,
/* [annotation][in] */
_In_ IMFAttributes *pCallbackAttributes,
/* [annotation][in] */
_In_ DWORD pinId);
END_INTERFACE
} IMFDeviceTransformCallbackVtbl;
interface IMFDeviceTransformCallback
{
CONST_VTBL struct IMFDeviceTransformCallbackVtbl *lpVtbl;
};
#ifdef COBJMACROS
#define IMFDeviceTransformCallback_QueryInterface(This,riid,ppvObject) \
( (This)->lpVtbl -> QueryInterface(This,riid,ppvObject) )
#define IMFDeviceTransformCallback_AddRef(This) \
( (This)->lpVtbl -> AddRef(This) )
#define IMFDeviceTransformCallback_Release(This) \
( (This)->lpVtbl -> Release(This) )
#define IMFDeviceTransformCallback_OnBufferSent(This,pCallbackAttributes,pinId) \
( (This)->lpVtbl -> OnBufferSent(This,pCallbackAttributes,pinId) )
#endif /* COBJMACROS */
#endif /* C style interface */
#endif /* __IMFDeviceTransformCallback_INTERFACE_DEFINED__ */
/* interface __MIDL_itf_mftransform_0000_0003 */
/* [local] */
#endif // (WINVER >= _WIN32_WINNT_WIN10 )
#if (WINVER >= _WIN32_WINNT_WIN8)
#pragma region Application or Games Family
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP | WINAPI_PARTITION_GAMES)
EXTERN_C const DECLSPEC_SELECTANY GUID MF_SA_REQUIRED_SAMPLE_COUNT_PROGRESSIVE = { 0xb172d58e, 0xfa77, 0x4e48, { 0x8d, 0x2a, 0x1d, 0xf2, 0xd8, 0x50, 0xea, 0xc2 } };
EXTERN_C const DECLSPEC_SELECTANY GUID MF_SA_MINIMUM_OUTPUT_SAMPLE_COUNT = { 0x851745d5, 0xc3d6, 0x476d, { 0x95, 0x27, 0x49, 0x8e, 0xf2, 0xd1, 0xd, 0x18 } };
EXTERN_C const DECLSPEC_SELECTANY GUID MF_SA_MINIMUM_OUTPUT_SAMPLE_COUNT_PROGRESSIVE = { 0xf5523a5, 0x1cb2, 0x47c5, { 0xa5, 0x50, 0x2e, 0xeb, 0x84, 0xb4, 0xd1, 0x4a } };
EXTERN_C const DECLSPEC_SELECTANY GUID MFT_SUPPORT_3DVIDEO = { 0x93f81b1, 0x4f2e, 0x4631, { 0x81, 0x68, 0x79, 0x34, 0x3, 0x2a, 0x1, 0xd3 } };
typedef
enum _MF3DVideoOutputType
{
MF3DVideoOutputType_BaseView = 0,
MF3DVideoOutputType_Stereo = 1
} MF3DVideoOutputType;
EXTERN_C const DECLSPEC_SELECTANY GUID MF_ENABLE_3DVIDEO_OUTPUT = { 0xbdad7bca, 0xe5f, 0x4b10, { 0xab, 0x16, 0x26, 0xde, 0x38, 0x1b, 0x62, 0x93 } };
EXTERN_C const DECLSPEC_SELECTANY GUID MF_SA_D3D11_BINDFLAGS = { 0xeacf97ad, 0x065c, 0x4408, { 0xbe, 0xe3, 0xfd, 0xcb, 0xfd, 0x12, 0x8b, 0xe2 } };
EXTERN_C const DECLSPEC_SELECTANY GUID MF_SA_D3D11_USAGE = { 0xe85fe442, 0x2ca3, 0x486e, { 0xa9, 0xc7, 0x10, 0x9d, 0xda, 0x60, 0x98, 0x80 } };
EXTERN_C const DECLSPEC_SELECTANY GUID MF_SA_D3D11_AWARE = { 0x206b4fc8, 0xfcf9, 0x4c51, { 0xaf, 0xe3, 0x97, 0x64, 0x36, 0x9e, 0x33, 0xa0 } };
EXTERN_C const DECLSPEC_SELECTANY GUID MF_SA_D3D11_SHARED = { 0x7b8f32c3, 0x6d96, 0x4b89, { 0x92, 0x3, 0xdd, 0x38, 0xb6, 0x14, 0x14, 0xf3 } };
EXTERN_C const DECLSPEC_SELECTANY GUID MF_SA_D3D11_SHARED_WITHOUT_MUTEX = { 0x39dbd44d, 0x2e44, 0x4931, { 0xa4, 0xc8, 0x35, 0x2d, 0x3d, 0xc4, 0x21, 0x15 } };
EXTERN_C const DECLSPEC_SELECTANY GUID MF_SA_D3D11_ALLOW_DYNAMIC_YUV_TEXTURE = { 0xce06d49f, 0x613, 0x4b9d, { 0x86, 0xa6, 0xd8, 0xc4, 0xf9, 0xc1, 0x0, 0x75 } };
EXTERN_C const DECLSPEC_SELECTANY GUID MF_SA_D3D11_HW_PROTECTED = { 0x3a8ba9d9, 0x92ca, 0x4307, { 0xa3, 0x91, 0x69, 0x99, 0xdb, 0xf3, 0xb6, 0xce } };
EXTERN_C const DECLSPEC_SELECTANY GUID MF_SA_BUFFERS_PER_SAMPLE = { 0x873c5171, 0x1e3d, 0x4e25, { 0x98, 0x8d, 0xb4, 0x33, 0xce, 0x04, 0x19, 0x83 } };
EXTERN_C const DECLSPEC_SELECTANY GUID MFT_DECODER_EXPOSE_OUTPUT_TYPES_IN_NATIVE_ORDER = { 0xef80833f, 0xf8fa, 0x44d9, { 0x80, 0xd8, 0x41, 0xed, 0x62, 0x32, 0x67, 0xc } };
EXTERN_C const DECLSPEC_SELECTANY GUID MFT_DECODER_QUALITY_MANAGEMENT_CUSTOM_CONTROL = { 0xa24e30d7, 0xde25, 0x4558, { 0xbb, 0xfb, 0x71, 0x7, 0xa, 0x2d, 0x33, 0x2e } };
EXTERN_C const DECLSPEC_SELECTANY GUID MFT_DECODER_QUALITY_MANAGEMENT_RECOVERY_WITHOUT_ARTIFACTS = { 0xd8980deb, 0xa48, 0x425f, { 0x86, 0x23, 0x61, 0x1d, 0xb4, 0x1d, 0x38, 0x10 } };
EXTERN_C const DECLSPEC_SELECTANY GUID MFT_REMUX_MARK_I_PICTURE_AS_CLEAN_POINT = { 0x364e8f85, 0x3f2e, 0x436c, { 0xb2, 0xa2, 0x44, 0x40, 0xa0, 0x12, 0xa9, 0xe8} };
EXTERN_C const DECLSPEC_SELECTANY GUID MFT_DECODER_FINAL_VIDEO_RESOLUTION_HINT = { 0xdc2f8496, 0x15c4, 0x407a, { 0xb6, 0xf0, 0x1b, 0x66, 0xab, 0x5f, 0xbf, 0x53 } };
EXTERN_C const DECLSPEC_SELECTANY GUID MFT_ENCODER_SUPPORTS_CONFIG_EVENT = { 0x86a355ae, 0x3a77, 0x4ec4, { 0x9f, 0x31, 0x1, 0x14, 0x9a, 0x4e, 0x92, 0xde } };
EXTERN_C const DECLSPEC_SELECTANY GUID MFT_ENUM_HARDWARE_VENDOR_ID_Attribute = { 0x3aecb0cc, 0x35b, 0x4bcc, { 0x81, 0x85, 0x2b, 0x8d, 0x55, 0x1e, 0xf3, 0xaf } };
#endif /* WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP | WINAPI_PARTITION_GAMES) */
#pragma endregion
#endif // (WINVER >= _WIN32_WINNT_WIN8)
#if (WINVER >= _WIN32_WINNT_WIN7)
#pragma region Application or Games Family
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP | WINAPI_PARTITION_GAMES)
EXTERN_C const DECLSPEC_SELECTANY GUID MF_TRANSFORM_ASYNC = { 0xf81a699a, 0x649a, 0x497d, { 0x8c, 0x73, 0x29, 0xf8, 0xfe, 0xd6, 0xad, 0x7a } };
EXTERN_C const DECLSPEC_SELECTANY GUID MF_TRANSFORM_ASYNC_UNLOCK = { 0xe5666d6b, 0x3422, 0x4eb6, { 0xa4, 0x21, 0xda, 0x7d, 0xb1, 0xf8, 0xe2, 0x7 } };
EXTERN_C const DECLSPEC_SELECTANY GUID MF_TRANSFORM_FLAGS_Attribute = { 0x9359bb7e, 0x6275, 0x46c4, { 0xa0, 0x25, 0x1c, 0x1, 0xe4, 0x5f, 0x1a, 0x86 } };
EXTERN_C const DECLSPEC_SELECTANY GUID MF_TRANSFORM_CATEGORY_Attribute = { 0xceabba49, 0x506d, 0x4757, { 0xa6, 0xff, 0x66, 0xc1, 0x84, 0x98, 0x7e, 0x4e } };
EXTERN_C const DECLSPEC_SELECTANY GUID MFT_TRANSFORM_CLSID_Attribute = { 0x6821c42b, 0x65a4, 0x4e82, { 0x99, 0xbc, 0x9a, 0x88, 0x20, 0x5e, 0xcd, 0xc } };
EXTERN_C const DECLSPEC_SELECTANY GUID MFT_INPUT_TYPES_Attributes = { 0x4276c9b1, 0x759d, 0x4bf3, { 0x9c, 0xd0, 0xd, 0x72, 0x3d, 0x13, 0x8f, 0x96 } };
EXTERN_C const DECLSPEC_SELECTANY GUID MFT_OUTPUT_TYPES_Attributes = { 0x8eae8cf3, 0xa44f, 0x4306, { 0xba, 0x5c, 0xbf, 0x5d, 0xda, 0x24, 0x28, 0x18 } };
EXTERN_C const DECLSPEC_SELECTANY GUID MFT_ENUM_HARDWARE_URL_Attribute = { 0x2fb866ac, 0xb078, 0x4942, { 0xab, 0x6c, 0x0, 0x3d, 0x5, 0xcd, 0xa6, 0x74 } };
EXTERN_C const DECLSPEC_SELECTANY GUID MFT_FRIENDLY_NAME_Attribute = { 0x314ffbae, 0x5b41, 0x4c95, { 0x9c, 0x19, 0x4e, 0x7d, 0x58, 0x6f, 0xac, 0xe3 } };
EXTERN_C const DECLSPEC_SELECTANY GUID MFT_CONNECTED_STREAM_ATTRIBUTE = { 0x71eeb820, 0xa59f, 0x4de2, {0xbc, 0xec, 0x38, 0xdb, 0x1d, 0xd6, 0x11, 0xa4} };
EXTERN_C const DECLSPEC_SELECTANY GUID MFT_CONNECTED_TO_HW_STREAM = { 0x34e6e728, 0x6d6, 0x4491, { 0xa5, 0x53, 0x47, 0x95, 0x65, 0xd, 0xb9, 0x12 } };
EXTERN_C const DECLSPEC_SELECTANY GUID MFT_PREFERRED_OUTPUTTYPE_Attribute = { 0x7e700499, 0x396a, 0x49ee, { 0xb1, 0xb4, 0xf6, 0x28, 0x2, 0x1e, 0x8c, 0x9d } };
EXTERN_C const DECLSPEC_SELECTANY GUID MFT_PROCESS_LOCAL_Attribute = { 0x543186e4, 0x4649, 0x4e65, { 0xb5, 0x88, 0x4a, 0xa3, 0x52, 0xaf, 0xf3, 0x79 } };
EXTERN_C const DECLSPEC_SELECTANY GUID MFT_PREFERRED_ENCODER_PROFILE = { 0x53004909, 0x1ef5, 0x46d7, { 0xa1, 0x8e, 0x5a, 0x75, 0xf8, 0xb5, 0x90, 0x5f } };
EXTERN_C const DECLSPEC_SELECTANY GUID MFT_HW_TIMESTAMP_WITH_QPC_Attribute = { 0x8d030fb8, 0xcc43, 0x4258, { 0xa2, 0x2e, 0x92, 0x10, 0xbe, 0xf8, 0x9b, 0xe4 } };
EXTERN_C const DECLSPEC_SELECTANY GUID MFT_FIELDOFUSE_UNLOCK_Attribute = { 0x8ec2e9fd, 0x9148, 0x410d, { 0x83, 0x1e, 0x70, 0x24, 0x39, 0x46, 0x1a, 0x8e } };
EXTERN_C const DECLSPEC_SELECTANY GUID MFT_CODEC_MERIT_Attribute = { 0x88a7cb15, 0x7b07, 0x4a34, { 0x91, 0x28, 0xe6, 0x4c, 0x67, 0x3, 0xc4, 0xd3 } };
EXTERN_C const DECLSPEC_SELECTANY GUID MFT_ENUM_TRANSCODE_ONLY_ATTRIBUTE = { 0x111ea8cd, 0xb62a, 0x4bdb, { 0x89, 0xf6, 0x67, 0xff, 0xcd, 0xc2, 0x45, 0x8b } };
#endif /* WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP | WINAPI_PARTITION_GAMES) */
#pragma endregion
#pragma region Desktop Family
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP)
STDAPI
MFCreateTransformActivate(
_Out_ IMFActivate** ppActivate
);
#endif /* WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_DESKTOP) */
#pragma endregion
#endif // (WINVER >= _WIN32_WINNT_WIN7)
#pragma region Track Error Improvements
#if (WINVER >= _WIN32_WINNT_WINTHRESHOLD)
EXTERN_GUID( MFT_AUDIO_DECODER_DEGRADATION_INFO_ATTRIBUTE, 0x6c3386ad, 0xec20, 0x430d, 0xb2, 0xa5, 0x50, 0x5c, 0x71, 0x78, 0xd9, 0xc4);
typedef
enum MFT_AUDIO_DECODER_DEGRADATION_REASON
{
MFT_AUDIO_DECODER_DEGRADATION_REASON_NONE = 0,
MFT_AUDIO_DECODER_DEGRADATION_REASON_LICENSING_REQUIREMENT = 1
} MFT_AUDIO_DECODER_DEGRADATION_REASON;
typedef
enum MFT_AUDIO_DECODER_DEGRADATION_TYPE
{
MFT_AUDIO_DECODER_DEGRADATION_TYPE_NONE = 0,
MFT_AUDIO_DECODER_DEGRADATION_TYPE_DOWNMIX2CHANNEL = 1,
MFT_AUDIO_DECODER_DEGRADATION_TYPE_DOWNMIX6CHANNEL = 2,
MFT_AUDIO_DECODER_DEGRADATION_TYPE_DOWNMIX8CHANNEL = 3
} MFT_AUDIO_DECODER_DEGRADATION_TYPE;
typedef struct MFAudioDecoderDegradationInfo
{
MFT_AUDIO_DECODER_DEGRADATION_REASON eDegradationReason;
MFT_AUDIO_DECODER_DEGRADATION_TYPE eType;
} MFAudioDecoderDegradationInfo;
typedef struct _MFT_STREAM_STATE_PARAM
{
DWORD StreamId;
MF_STREAM_STATE State;
} MFT_STREAM_STATE_PARAM;
typedef struct _MFT_STREAM_STATE_PARAM *PMFT_STREAM_STATE_PARAM;
#endif // (WINVER >= _WIN32_WINNT_WINTHRESHOLD)
#pragma endregion
#if (NTDDI_VERSION >= NTDDI_WIN10_VB)
#pragma region Application or Games Family
#if WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP | WINAPI_PARTITION_GAMES)
EXTERN_C const DECLSPEC_SELECTANY GUID MFT_POLICY_SET_AWARE = { 0x5a633b19, 0xcc39, 0x4fa8, { 0x8c, 0xa5, 0x59, 0x98, 0x1b, 0x7a, 0x0, 0x18 } };
EXTERN_C const DECLSPEC_SELECTANY GUID MFT_USING_HARDWARE_DRM = { 0x34faa77d, 0xd79e, 0x4957, { 0xb8, 0xce, 0x36, 0x2b, 0x26, 0x84, 0x99, 0x6c } };
#endif /* WINAPI_FAMILY_PARTITION(WINAPI_PARTITION_APP | WINAPI_PARTITION_GAMES) */
#pragma endregion
#endif // (NTDDI_VERSION >= NTDDI_WIN10_VB)
extern RPC_IF_HANDLE __MIDL_itf_mftransform_0000_0003_v0_0_c_ifspec;
extern RPC_IF_HANDLE __MIDL_itf_mftransform_0000_0003_v0_0_s_ifspec;
/* Additional Prototypes for ALL interfaces */
/* end of Additional Prototypes */
#ifdef __cplusplus
}
#endif
#endif
| 41.162942 | 182 | 0.678262 | [
"object"
] |
c8efdd1b124ed07211c9c523d24b7f2e6b619e56 | 11,470 | h | C | tensorstore/kvstore/registry.h | google/tensorstore | 8df16a67553debaec098698ceaa5404eaf79634a | [
"BSD-2-Clause"
] | 106 | 2020-04-02T20:00:18.000Z | 2022-03-23T20:27:31.000Z | tensorstore/kvstore/registry.h | google/tensorstore | 8df16a67553debaec098698ceaa5404eaf79634a | [
"BSD-2-Clause"
] | 28 | 2020-04-12T02:04:47.000Z | 2022-03-23T20:27:03.000Z | tensorstore/kvstore/registry.h | google/tensorstore | 8df16a67553debaec098698ceaa5404eaf79634a | [
"BSD-2-Clause"
] | 18 | 2020-04-08T06:41:30.000Z | 2022-02-18T03:05:49.000Z | // Copyright 2020 The TensorStore 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 TENSORSTORE_KVSTORE_REGISTRY_H_
#define TENSORSTORE_KVSTORE_REGISTRY_H_
/// \file Interface for defining and registering a KeyValueStore driver that
/// supports a JSON representation.
///
/// To define a KeyValueStore driver, create a `Derived` class that inherits
/// from the CRTP base `RegisteredKeyValueStore<Derived>`, and define a global
/// constant of type `KeyValueStoreDriverRegistration<Derived>` to register it.
///
/// Refer to `memory/memory_key_value_store.cc` for an example.
#include "tensorstore/internal/context_binding.h"
#include "tensorstore/internal/json_registry.h"
#include "tensorstore/json_serialization_options.h"
#include "tensorstore/kvstore/driver.h"
#include "tensorstore/serialization/registry.h"
#include "tensorstore/serialization/serialization.h"
#include "tensorstore/util/garbage_collection/garbage_collection.h"
namespace tensorstore {
namespace internal_kvstore {
using kvstore::Driver;
using kvstore::DriverPtr;
using kvstore::DriverSpec;
using kvstore::DriverSpecPtr;
template <typename Derived>
class DriverOpenState;
struct DriverFromJsonOptions : public JsonSerializationOptions {
const std::string& path;
};
using DriverRegistry =
internal::JsonRegistry<DriverSpec, DriverFromJsonOptions,
JsonSerializationOptions,
internal::IntrusivePtr<const DriverSpec>>;
/// Returns the global KeyValueStore driver registry.
///
/// This should not be called directly by code outside this module.
DriverRegistry& GetDriverRegistry();
/// CRTP base class for KeyValueStore implementations that support a JSON
/// representation.
///
/// The `Derived` class must override all of the virtual methods of
/// `KeyValueStore`, except for the members noted as being defined automatically
/// by `RegisteredKeyValueStore`, and in addition must define the following
/// members:
///
/// - The `id` member specifies the string driver identifier:
///
/// static constexpr char id[] = "my_driver_id";
///
/// - The `SpecData` class includes as members the parameters and resources
/// necessary to create/open the driver.
///
/// It must be compatible with `ContextBindingTraits`, serialization, and
/// `EncodeCacheKey`. While it is possible to individually define a
/// `ContextBindingTraits` implementation, a `Serializer` specialization, and
/// an `EncodeCacheKeyAdl` function, in most cases all three can be defined
/// automatically simply by defining an `ApplyMembers` method.
///
/// Members of `SpecData` should be referenced in the `json_binder` and
/// `ApplyMembers` implementation, as noted below.
///
/// struct SpecData {
/// // Example members:
/// int mem1;
/// Context::Resource<SomeResource> mem2;
/// int open_option;
///
/// // For compatibility with `ContextBindingTraits`.
/// constexpr static auto ApplyMembers = [](auto& x, auto f) {
/// return f(f.mem1, f.mem2, internal::CacheKeyExcludes{open_option});
/// };
/// };
///
/// - The `json_binder` member must be a JSON object binder for `SpecData`.
/// This should handle converting each member of `SpecData` to/from the JSON
/// representation.
///
/// constexpr static auto json_binder = jb::Object(
/// jb::Member("mem1", jb::Projection(&SpecData::mem1)),
/// jb::Member("mem2", jb::Projection(&SpecData::mem2)));
///
/// - The cache key (as computed by `EncodeCacheKey`) must encode the `SpecData`
/// representation as a cache key. It will only be called after binding
/// context resources. When this is defined implicitly via `ApplyMembers`,
/// the `internal::CacheKeyExcludes` wrapper may be used to indicate members
/// that should be excluded from the cache key. Members that only affect
/// creation but not opening should normally be excluded.
///
/// - The static `Open` method is called to initiate opening the driver. This
/// is called by `kvstore::Open`. Note that `KeyValueStoreOpenState` is
/// a CRTP class template parameterized by the `Derived` driver type.
///
/// static void Open(internal_kvstore::DriverOpenState<Derived> state) {
/// // Access the context-bound `SpecData` representation as
/// `state.spec()`.
/// // Access the newly allocated `Derived` object as `state.driver()`.
/// // Report errors via `state.SetError`.
/// }
///
/// - The `GetBoundSpecData` method must set `spec` to the context-bound
/// representation of the JSON specification of the driver.
///
/// absl::Status GetBoundSpecData(SpecData& spec) const;
///
/// - The `Derived` class must be default constructible. Any required
/// initialization should be performed in the `Open` method.
///
/// Refer to `memory/memory_key_value_store.cc` for an example driver
/// implementation.
template <typename Derived, typename Parent = Driver>
class RegisteredDriver : public Parent {
private:
/// Encodes the cache key from the context-bound `SpecData` representation.
///
/// This is used by `RegisteredKeyValueStore::EncodeCacheKey` below and by
/// `RegisteredKeyValueStoreBoundSpec::EncodeCacheKey`.
///
/// The `SpecData` template parameter is always equal to
/// `typename Derived::SpecData`, but is specified as a template parameter
/// because `Derived` is incomplete when this class template is instantiated.
template <typename SpecData>
static void EncodeCacheKeyImpl(std::string* out, const SpecData& data) {
internal::EncodeCacheKey(out, typeid(Derived), data);
}
public:
void EncodeCacheKey(std::string* out) const override {
using SpecData = typename Derived::SpecData;
// Generates a cache key by obtaining the `SpecData` representation,
// then computing the cache key from that.
SpecData bound_spec_data;
if (auto status = static_cast<const Derived*>(this)->GetBoundSpecData(
bound_spec_data);
!status.ok()) {
// Could not obtain bound spec data. Just use the default implementation
// that encodes the exact object identity.
return Driver::EncodeCacheKey(out);
}
EncodeCacheKeyImpl(out, bound_spec_data);
}
Result<DriverSpecPtr> GetBoundSpec() const override {
using SpecImpl = RegisteredDriverSpec<Derived>;
internal::IntrusivePtr<SpecImpl> spec(new SpecImpl);
spec->context_binding_state_ = ContextBindingState::bound;
TENSORSTORE_RETURN_IF_ERROR(
static_cast<const Derived*>(this)->GetBoundSpecData(spec->data_));
return spec;
}
void GarbageCollectionVisit(
garbage_collection::GarbageCollectionVisitor& visitor) const override {
garbage_collection::GarbageCollectionVisit(
visitor, *static_cast<const Derived*>(this));
}
private:
template <typename>
friend class DriverRegistration;
template <typename>
friend class RegisteredDriverSpec;
};
/// Parameter type for the static `Open` method that driver types inherited from
/// `RegisteredKeyValueStore` must implement. For asynchronous open
/// implementations, this type may be copied and the copy retained until the
/// operation completes.
template <typename Derived>
class DriverOpenState {
template <typename, typename>
friend class RegisteredDriver;
template <typename>
friend class RegisteredDriverSpec;
public:
using SpecData = typename Derived::SpecData;
/// Returns the promise that must be marked ready to indicate the open has
/// completed. The result is initialized in a success state with a copy of
/// `driver()`, such that when the last reference to the `promise` is
/// released, the promise is marked ready and the open is considered to have
/// completed successfully. The result should only be changed to indicate an
/// error.
const Promise<DriverPtr>& promise() const { return promise_; }
/// Sets an error on the promise, indicating that the open failed.
void SetError(Status status) { promise_.SetResult(std::move(status)); }
/// Returns a reference to the `Driver` being opened.
Derived& driver() const { return *driver_; }
/// Returns a reference to the bound spec.
const SpecData& spec() const { return spec_->data_; }
private:
internal::IntrusivePtr<Derived> driver_;
Promise<DriverPtr> promise_;
internal::IntrusivePtr<const RegisteredDriverSpec<Derived>> spec_;
};
template <typename Derived>
class RegisteredDriverSpec : public DriverSpec {
using SpecData = typename Derived::SpecData;
public:
constexpr static std::string_view id = Derived::id;
absl::Status BindContext(const Context& context) override {
return internal::ContextBindingTraits<SpecData>::Bind(data_, context);
}
void UnbindContext(
const internal::ContextSpecBuilder& context_builder) override {
internal::ContextBindingTraits<SpecData>::Unbind(data_, context_builder);
}
void StripContext() override {
internal::ContextBindingTraits<SpecData>::Strip(data_);
}
void EncodeCacheKey(std::string* out) const override {
Derived::RegisteredDriver::EncodeCacheKeyImpl(out, data_);
}
std::string_view driver_id() const override { return Derived::id; }
DriverSpecPtr Clone() const final {
return DriverSpecPtr(new RegisteredDriverSpec(*this));
}
Future<DriverPtr> DoOpen() const override {
DriverOpenState<Derived> open_state;
open_state.spec_.reset(this);
open_state.driver_.reset(new Derived);
auto [promise, future] =
PromiseFuturePair<DriverPtr>::Make(open_state.driver_);
open_state.promise_ = std::move(promise);
Derived::Open(std::move(open_state));
return future;
}
void GarbageCollectionVisit(
garbage_collection::GarbageCollectionVisitor& visitor) const override {
garbage_collection::GarbageCollectionVisit(visitor, data_);
}
constexpr static auto ApplyMembers = [](auto&& x, auto f) {
return f(x.context_spec_, x.data_);
};
SpecData data_;
};
/// Registers a KeyValueStore driver implementation.
///
/// Example usage:
///
/// class MyDriver : public internal_kvstore::RegisteredDriver<MyDriver> {
/// // ...
/// };
///
/// const internal_kvstore::DriverRegistration<MyDriver> registration;
///
template <typename Derived>
class DriverRegistration {
public:
DriverRegistration() {
GetDriverRegistry().Register<RegisteredDriverSpec<Derived>>(
Derived::id,
internal_json_binding::Projection(&RegisteredDriverSpec<Derived>::data_,
Derived::json_binder));
serialization::Register<internal::IntrusivePtr<const DriverSpec>,
RegisteredDriverSpec<Derived>>();
}
};
} // namespace internal_kvstore
extern template serialization::Registry&
serialization::GetRegistry<internal::IntrusivePtr<const kvstore::DriverSpec>>();
} // namespace tensorstore
#endif // TENSORSTORE_KVSTORE_REGISTRY_H_
| 37.48366 | 80 | 0.719704 | [
"object"
] |
c8f0ab7984dc4bfa8081dfaf1acd96699e2bc31b | 29,003 | h | C | src/compiler.h | sota/colm | 616de43bb51102852ce9aa571e50e74a4d095d1d | [
"MIT"
] | null | null | null | src/compiler.h | sota/colm | 616de43bb51102852ce9aa571e50e74a4d095d1d | [
"MIT"
] | null | null | null | src/compiler.h | sota/colm | 616de43bb51102852ce9aa571e50e74a4d095d1d | [
"MIT"
] | null | null | null | /*
* Copyright 2001-2012 Adrian Thurston <thurston@colm.net>
*
* 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 _COLM_PARSEDATA_H
#define _COLM_PARSEDATA_H
#include <limits.h>
#include <iostream>
#include <avlmap.h>
#include <avlset.h>
#include <bstmap.h>
#include <vector.h>
#include <bstset.h>
#include <dlist.h>
#include <dlistmel.h>
#include <fsmgraph.h>
#include <compare.h>
#include "global.h"
#include "keyops.h"
#include "parsetree.h"
#include "cstring.h"
#include "pdagraph.h"
#include "pdarun.h"
#include "bytecode.h"
#include "program.h"
#include "internal.h"
using std::ostream;
struct exit_object { };
extern exit_object endp;
void operator<<( std::ostream &out, exit_object & );
extern const char *objectName;
extern bool hostAdapters;
/* Forwards. */
struct RedFsm;
struct LangEl;
struct Compiler;
struct PdaCodeGen;
struct FsmCodeGen;
#define SHIFT_CODE 0x1
#define REDUCE_CODE 0x2
#define SHIFT_REDUCE_CODE 0x3
typedef Vector<const char**> CharVectVect;
/* This is used for tracking the current stack of include file/machine pairs. It is
* is used to detect and recursive include structure. */
struct IncludeStackItem
{
IncludeStackItem( const char *fileName )
: fileName(fileName) {}
const char *fileName;
};
typedef Vector<IncludeStackItem> IncludeStack;
typedef Vector<const char *> ArgsVector;
struct DefineArg
{
DefineArg( String name, String value )
: name(name), value(value) {}
String name;
String value;
};
typedef Vector<DefineArg> DefineVector;
extern DefineVector defineArgs;
extern ArgsVector includePaths;
inline long makeReduceCode( long reduction, bool isShiftReduce )
{
return ( isShiftReduce ? SHIFT_REDUCE_CODE : REDUCE_CODE ) |
( reduction << 2 );
}
struct ProdEl;
struct ProdElList;
struct PdaLiteral;
struct Production;
/* A pointer to this is in struct pda_run, but it's specification is not known by the
* runtime code. The runtime functions that access it are defined in
* ctinput.cpp and stubbed in fsmcodegen.cpp */
struct bindings
: public Vector<parse_tree_t*>
{};
struct DefListEl { Production *prev, *next; };
struct LelDefListEl { Production *prev, *next; };
typedef Vector< LangEl* > LangElVect;
typedef Vector< ProdEl* > FactorVect;
typedef AvlMap<String, long, CmpStr> StringMap;
typedef AvlMapEl<String, long> StringMapEl;
enum PredType {
PredLeft,
PredRight,
PredNonassoc,
PredNone
};
struct PredDecl
{
PredDecl( TypeRef *typeRef, long predValue )
: typeRef(typeRef), predValue(predValue)
{}
TypeRef *typeRef;
PredType predType;
long predValue;
PredDecl *prev, *next;
};
typedef DList<PredDecl> PredDeclList;
/* Graph dictionary. */
struct Production
:
public DefListEl, public LelDefListEl
{
Production()
:
prodName(0), prodElList(0), prodCommit(false), redBlock(0),
prodId(0), prodNum(0), fsm(0), fsmLength(0), uniqueEmptyLeader(0),
isLeftRec(false), localFrame(0), lhsField(0), predOf(0) {}
static Production* cons( const InputLoc &loc, LangEl *prodName, ProdElList *prodElList,
String name, bool prodCommit, CodeBlock *redBlock, int prodId, int prodNum )
{
Production *p = new Production;
p->loc = loc;
p->prodName = prodName;
p->name = name;
p->prodElList = prodElList;
p->prodCommit = prodCommit;
p->redBlock = redBlock;
p->prodId = prodId;
p->prodNum = prodNum;
return p;
}
InputLoc loc;
LangEl *prodName;
ProdElList *prodElList;
String name;
bool prodCommit;
CodeBlock *redBlock;
int prodId;
int prodNum;
PdaGraph *fsm;
int fsmLength;
String data;
LongSet reducesTo;
LangEl *uniqueEmptyLeader;
ProdIdSet nonTermFirstSet;
AlphSet firstSet;
bool isLeftRec;
ObjectDef *localFrame;
ObjectField *lhsField;
LangEl *predOf;
UnsignedCharVect copy;
};
struct CmpDefById
{
static int compare( Production *d1, Production *d2 )
{
if ( d1->prodId < d2->prodId )
return -1;
else if ( d1->prodId > d2->prodId )
return 1;
else
return 0;
}
};
/* Map dotItems to productions. */
typedef BstMap< int, Production*, CmpOrd<int> > DotItemIndex;
typedef BstMapEl< int, Production*> DotItemIndexEl;
struct DefList
:
public DListMel<Production, DefListEl>
{};
/* A vector of production vectors. Each non terminal can have many productions. */
struct LelDefList
:
public DListMel<Production, LelDefListEl>
{};
/* A set of machines made during a closure round. */
typedef Vector< PdaGraph* > Machines;
/* List of language elements. */
typedef DList<LangEl> LelList;
typedef Vector< TokenInstance* > TokenInstanceVect;
struct UniqueType;
typedef Vector<LangEl*> LangElVect;
typedef BstSet<LangEl*> LangElSet;
/* A language element class. Can be a nonTerm or a term. */
struct LangEl : public DListEl<LangEl>
{
enum Type { Unknown, Term, NonTerm };
LangEl( Namespace *nspace, const String &name, Type type );
~LangEl();
/* The region the language element was defined in. */
Namespace *nspace;
String name;
String lit;
String fullName;
String fullLit;
/* For referencing the type. */
String refName;
/* For declaring things inside the type. */
String declName;
String xmlTag;
Type type;
long id;
String displayString;
long numAppearances;
bool commit;
bool isIgnore;
bool reduceFirst;
bool isLiteral;
bool isRepeat;
bool isList;
bool isOpt;
bool parseStop;
bool isEOF;
LangEl *repeatOf;
/* Productions from the language element if it is a non-terminal. */
LelDefList defList;
TokenDef *tokenDef;
Production *rootDef;
LangEl *termDup;
LangEl *eofLel;
PdaGraph *pdaGraph;
struct pda_tables *pdaTables;
PdaState *startState;
CodeBlock *transBlock;
ObjectDef *objectDef;
long thisSize;
long ofiOffset;
long parserId;
PredType predType;
long predValue;
StructDef *contextDef;
StructDef *contextIn;
bool noPreIgnore;
bool noPostIgnore;
bool isZero;
RegionSet *regionSet;
};
struct ProdEl
{
/* Language elements a factor node can be. */
enum Type {
LiteralType,
ReferenceType
};
/* Construct with a reference to a var def. */
ProdEl( Type type, const InputLoc &loc, ObjectField *captureField,
bool commit, TypeRef *typeRef, int priorVal )
:
type(type),
production(0),
captureField(captureField),
rhsElField(0),
commit(commit),
typeRef(typeRef),
langEl(0),
priorVal(priorVal)
{}
ProdEl( const InputLoc &loc, TypeRef *typeRef )
:
type(ReferenceType),
production(0),
captureField(0),
rhsElField(0),
commit(false),
typeRef(typeRef),
langEl(0),
priorVal(0)
{}
Type type;
Production *production;
int pos;
ObjectField *captureField;
ObjectField *rhsElField;
bool commit;
TypeRef *typeRef;
LangEl *langEl;
int priorVal;
ProdEl *prev, *next;
};
struct ProdElList : public DList<ProdEl>
{
PdaGraph *walk( Compiler *pd, Production *prod );
};
/* This should be renamed. It is a literal string in a type reference. */
struct PdaLiteral
{
PdaLiteral( const InputLoc &loc, const String &data )
: loc(loc), data(data), value(0) { }
InputLoc loc;
String data;
long value;
};
/* Nodes in the tree that use this action. */
typedef Vector<NameInst*> ActionRefs;
/* Element in list of actions. Contains the string for the code to exectute. */
struct Action
:
public DListEl<Action>,
public AvlTreeEl<Action>
{
public:
static Action *cons( const InputLoc &loc, const String &name, InlineList *inlineList )
{
Action *a = new Action;
a->loc = (loc);
a->name = (name);
a->markType = (MarkNone);
a->objField = (0);
a->markId = (-1);
a->inlineList = (inlineList);
a->actionId = (-1);
a->numTransRefs = (0);
a->numToStateRefs = (0);
a->numFromStateRefs = (0);
a->numEofRefs = (0);
a->numCondRefs = (0);
a->anyCall = (false);
a->isLmAction = (false);
return a;
}
static Action *cons( MarkType markType, long markId )
{
Action *a = new Action;
a->name = ("mark");
a->markType = (markType);
a->objField = (0);
a->markId = (markId);
a->inlineList = (InlineList::cons());
a->actionId = (-1);
a->numTransRefs = (0);
a->numToStateRefs = (0);
a->numFromStateRefs = (0);
a->numEofRefs = (0);
a->numCondRefs = (0);
a->anyCall = (false);
a->isLmAction = (false);
return a;
}
/* Key for action dictionary. */
const String &getKey() const { return name; }
/* Data collected during parse. */
InputLoc loc;
String name;
MarkType markType;
ObjectField *objField;
long markId;
InlineList *inlineList;
int actionId;
void actionName( ostream &out )
{
if ( name != 0 )
out << name;
else
out << loc.line << ":" << loc.col;
}
/* Places in the input text that reference the action. */
ActionRefs actionRefs;
/* Number of references in the final machine. */
bool numRefs()
{ return numTransRefs + numToStateRefs + numFromStateRefs + numEofRefs; }
int numTransRefs;
int numToStateRefs;
int numFromStateRefs;
int numEofRefs;
int numCondRefs;
bool anyCall;
bool isLmAction;
};
/* A list of actions. */
typedef DList<Action> ActionList;
struct VarDef;
struct LexJoin;
struct LexTerm;
struct FactorAug;
struct FactorLabel;
struct FactorRep;
struct FactorNeg;
struct Factor;
struct Literal;
struct Range;
struct RegExpr;
struct ReItem;
struct ReOrBlock;
struct ReOrItem;
struct TokenRegion;
/* tree_t of instantiated names. */
typedef BstMapEl<String, NameInst*> NameMapEl;
typedef BstMap<String, NameInst*, CmpStr> NameMap;
typedef Vector<NameInst*> NameVect;
typedef BstSet<NameInst*> NameSet;
/* Node in the tree of instantiated names. */
struct NameInst
{
NameInst( int id )
: id(id) {}
int id;
/* Pointers for the name search queue. */
NameInst *prev, *next;
};
typedef DList<NameInst> NameInstList;
/* Stack frame used in walking the name tree. */
struct NameFrame
{
NameInst *prevNameInst;
int prevNameChild;
NameInst *prevLocalScope;
};
/* Class to collect information about the machine during the
* parse of input. */
struct Compiler
{
/* Create a new parse data object. This is done at the beginning of every
* fsm specification. */
Compiler();
~Compiler();
/*
* Setting up the graph dict.
*/
void compileLiteralTokens();
void initEmptyScanners();
void initEmptyScanner( RegionSet *regionSet, TokenRegion *reg );
void initUniqueTypes();
/* Initialize a graph dict with the basic fsms. */
void initGraphDict();
void createBuiltin( const char *name, BuiltinMachine builtin );
/* Make a name id in the current name instantiation scope if it is not
* already there. */
NameInst *makeJoinNameTree( LexJoin *join );
NameInst *makeNameTree();
NameInst **makeNameIndex();
void printNameTree( NameInst *rootName );
void printNameIndex( NameInst **nameIndex );
/* Resove name references in action code and epsilon transitions. */
NameSet resolvePart( NameInst *refFrom, const char *data, bool recLabelsOnly );
void resolveFrom( NameSet &result, NameInst *refFrom,
const NameRef &nameRef, int namePos );
/* Set the alphabet type. If type types are not valid returns false. */
bool setAlphType( char *s1, char *s2 );
bool setAlphType( char *s1 );
/* Unique actions. */
void removeDups( ActionTable &actionTable );
void removeActionDups( FsmGraph *graph );
/* Dumping the name instantiation tree. */
void printNameInst( NameInst *nameInst, int level );
/* Make the graph from a graph dict node. Does minimization. */
void finishGraphBuild( FsmGraph *graph );
FsmGraph *makeAllRegions();
FsmGraph *makeScanner();
void analyzeAction( Action *action, InlineList *inlineList );
void analyzeGraph( FsmGraph *graph );
void resolvePrecedence( PdaGraph *pdaGraph );
LangEl *predOf( PdaTrans *trans, long action );
bool precedenceSwap( long action1, long action2, LangEl *l1, LangEl *l2 );
bool precedenceRemoveBoth( LangEl *l1, LangEl *l2 );
void placeFrameFields( ObjectDef *localFrame );
void placeUserFunction( Function *func, bool isUserIter );
void placeAllStructObjects();
void placeAllLanguageObjects();
void placeAllFrameObjects();
void placeAllFunctions();
void initKeyOps();
/*
* Data collected during the parse.
*/
/* List of actions. Will be pasted into a switch statement. */
ActionList actionList;
/* The id of the next priority name and label. */
int nextPriorKey, nextNameId;
/* Alphabet type. */
HostType *userAlphType;
bool alphTypeSet;
/* Element type and get key expression. */
InlineList *getKeyExpr;
InlineList *accessExpr;
InlineList *curStateExpr;
/* The alphabet range. */
char *lowerNum, *upperNum;
Key lowKey, highKey;
InputLoc rangeLowLoc, rangeHighLoc;
/* Number of errors encountered parsing the fsm spec. */
int errorCount;
/* Counting the action and priority ordering. */
int curActionOrd;
int curPriorOrd;
/* Root of the name tree. */
NameInst *curNameInst;
int curNameChild;
NameInstList nameInstList;
/* The place where resolved epsilon transitions go. These cannot go into
* the parse tree because a single epsilon op can resolve more than once
* to different nameInsts if the machine it's in is used more than once. */
NameVect epsilonResolvedLinks;
int nextEpsilonResolvedLink;
/* Root of the name tree used for doing local name searches. */
NameInst *localNameScope;
void setLmInRetLoc( InlineList *inlineList );
void initLongestMatchData();
/* Counter for assigning ids to longest match items. */
int nextTokenId;
RegionImplList regionImplList;
RegionList regionList;
RegionSetList regionSetList;
NamespaceList namespaceList;
Action *newAction( const String &name, InlineList *inlineList );
Action *setTokStart;
int setTokStartOrd;
Action *initActId;
int initActIdOrd;
Action *setTokEnd;
int setTokEndOrd;
CodeBlock *rootCodeBlock;
void beginProcessing()
{
::keyOps = &thisKeyOps;
}
KeyOps thisKeyOps;
UniqueType *mainReturnUT;
CharVectVect streamFileNames;
/* CONTEXT FREE */
ProdElList *makeProdElList( LangEl *langEl );
void wrapNonTerminals();
void makeDefinitionNames();
void noUndefindLangEls();
void declareBaseLangEls();
void makeLangElIds();
void makeStructElIds();
void makeLangElNames();
void makeTerminalWrappers();
void makeEofElements();
void makeIgnoreCollectors();
void resolvePrecedence();
void resolveReductionActions();
void findReductionActionProds();
void resolveReducers();
void declarePass();
void resolvePass();
/* Parser generation. */
void advanceReductions( PdaGraph *pdaGraph );
void sortActions( PdaGraph *pdaGraph );
void addDupTerms( PdaGraph *pdaGraph );
void linkExpansions( PdaGraph *pdaGraph );
void lalr1FollowEpsilonOp( PdaGraph *pdaGraph );
void transferCommits( PdaGraph *pdaGraph, PdaTrans *trans, PdaState *state, long prodId );
void lalr1AddFollow2( PdaGraph *pdaGraph, PdaTrans *trans, FollowToAdd &followKeys );
void lalr1AddFollow1( PdaGraph *pdaGraph, PdaState *state );
void lalr1AddFollow2( PdaGraph *pdaGraph, PdaTrans *trans, long followKey, long prior );
void lalr1AddFollow1( PdaGraph *pdaGraph, PdaTrans *trans );
void lalr1AddFollowSets( PdaGraph *pdaGraph, LangElSet &parserEls );
void lr0BringInItem( PdaGraph *pdaGraph, PdaState *dest, PdaState *prodState,
PdaTrans *expandFrom, Production *prod );
void lr0InvokeClosure( PdaGraph *pdaGraph, PdaState *state );
void lr0CloseAllStates( PdaGraph *pdaGraph );
void lalr1GenerateParser( PdaGraph *pdaGraph, LangElSet &parserEls );
void reduceActions( PdaGraph *pdaGraph );
bool makeNonTermFirstSetProd( Production *prod, PdaState *state );
void makeNonTermFirstSets();
bool makeFirstSetProd( Production *prod, PdaState *state );
void makeFirstSets();
int findIndexOff( struct pda_tables *pdaTables, PdaGraph *pdaGraph,
PdaState *state, int &currLen );
void trySetTime( PdaTrans *trans, long code, long &time );
void addRegion( PdaState *tabState, PdaTrans *pdaTrans, long pdaKey,
bool noPreIgnore, bool noPostIgnore );
PdaState *followProd( PdaState *tabState, PdaState *prodState );
void findFollow( AlphSet &result, PdaState *overTab,
PdaState *overSrc, Production *parentDef );
void pdaActionOrder( PdaGraph *pdaGraph, LangElSet &parserEls );
void pdaOrderFollow( LangEl *rootEl, PdaState *tabState,
PdaTrans *tabTrans, PdaTrans *srcTrans,
Production *parentDef, Production *definition, long &time );
void pdaOrderProd( LangEl *rootEl, PdaState *tabState,
PdaState *srcState, Production *parentDef, long &time );
void analyzeMachine( PdaGraph *pdaGraph, LangElSet &parserEls );
void makeProdFsms();
void insertUniqueEmptyProductions();
void printNonTermFirstSets();
void printFirstSets();
LangEl *makeRepeatProd( const InputLoc &loc, Namespace *nspace,
const String &repeatName, UniqueType *ut );
LangEl *makeListProd( const InputLoc &loc, Namespace *nspace,
const String &listName, UniqueType *ut );
LangEl *makeOptProd( const InputLoc &loc, Namespace *nspace,
const String &optName, UniqueType *ut );
void resolveProdEl( ProdEl *prodEl );
void resolveProductionEls();
void addMatchText( ObjectDef *frame, LangEl *lel );
void addMatchLength( ObjectDef *frame, LangEl *lel );
void addInput( ObjectDef *frame );
void addThis( ObjectDef *frame );
void addTransTokVar( ObjectDef *frame, LangEl *lel );
void addProdRHSVars( ObjectDef *localFrame, ProdElList *prodElList );
void addProdRedObjectVar( ObjectDef *localFrame, LangEl *langEl );
void addProdObjects();
void addProdRHSLoads( Production *prod, CodeVect &code, long &insertPos );
void addProdLHSLoad( Production *prod, CodeVect &code, long &insertPos );
void addPushBackLHS( Production *prod, CodeVect &code, long &insertPos );
void prepGrammar();
struct pda_run *parsePattern( program_t *prg, tree_t **sp, const InputLoc &loc,
int parserId, struct stream_impl *sourceStream );
void parsePatterns();
void collectParserEls( LangElSet &parserEls );
void makeParser( LangElSet &parserEls );
PdaGraph *makePdaGraph( BstSet<LangEl*> &parserEls );
struct pda_tables *makePdaTables( PdaGraph *pdaGraph );
void fillInPatterns( program_t *prg );
void makeRuntimeData();
/* Generate and write out the fsm. */
void generateGraphviz();
void verifyParseStopGrammar( LangEl *langEl, PdaGraph *pdaGraph );
void computeAdvanceReductions( LangEl *langEl, PdaGraph *pdaGraph );
void initListElField( GenericType *gen, const char *name, int offset );
void initListFieldEl( GenericType *gen, const char *name, int offset );
void initListFieldVal( GenericType *gen, const char *name, int offset );
void initListFields( GenericType *gen );
void initListFunctions( GenericType *gen );
void initMapElKey( GenericType *gen, const char *name, int offset );
void initMapElField( GenericType *gen, const char *name, int offset );
void initMapField( GenericType *gen, const char *name, int offset );
void initMapFields( GenericType *gen );
void initMapFunctions( GenericType *gen );
void initVectorFunctions( GenericType *gen );
void initParserField( GenericType *gen, const char *name,
int offset, TypeRef *typeRef );
void initParserFunctions( GenericType *gen );
void initParserFields( GenericType *gen );
void addStdin();
void addStdout();
void addStderr();
void addArgv();
void addError();
void addDefineArgs();
int argvOffset();
int arg0Offset();
void makeDefaultIterators();
void addLengthField( ObjectDef *objDef, code_t getLength );
ObjectDef *findObject( const String &name );
void resolveListElementOf( ObjectDef *container, ObjectDef *obj, ElementOf *elof );
void resolveMapElementOf( ObjectDef *container, ObjectDef *obj, ElementOf *elof );
void resolveElementOf( ObjectDef *obj );
void makeFuncVisible( Function *func, bool isUserIter );
void makeInHostVisible( Function *func );
void declareFunction( Function *func );
void declareReductionCode( Production *prod );
void declareTranslateBlock( LangEl *langEl );
void declarePreEof( TokenRegion *region );
void declareRootBlock();
void declareByteCode();
void resolveFunction( Function *func );
void resolveInHost( Function *func );
void resolvePreEof( TokenRegion *region );
void resolveRootBlock();
void resolveTranslateBlock( LangEl *langEl );
void resolveReductionCode( Production *prod );
void resolveParseTree();
void compileFunction( Function *func, CodeVect &code );
void compileFunction( Function *func );
void compileUserIter( Function *func, CodeVect &code );
void compileUserIter( Function *func );
void compilePreEof( TokenRegion *region );
void compileRootBlock();
void compileTranslateBlock( LangEl *langEl );
void findLocals( ObjectDef *localFrame, CodeBlock *block );
void makeProdCopies( Production *prod );
void compileReductionCode( Production *prod );
void removeNonUnparsableRepls();
void compileByteCode();
void resolveUses();
void generateOutput( long activeRealm, bool includeCommit );
void compile();
void openNameSpace( ostream &out, Namespace *nspace );
void closeNameSpace( ostream &out, Namespace *nspace );
void refNameSpace( LangEl *lel, Namespace *nspace );
void generateExports();
void generateExportsImpl();
struct local_info *makeLocalInfo( Locals &locals );
short *makeTrees( ObjectDef *objectDef, int &numTrees );
/*
* Graphviz Generation
*/
void writeTransList( PdaState *state );
void writeDotFile( PdaGraph *graph );
void writeDotFile( );
/*
* Data collected during the parse.
*/
LelList langEls;
StructElList structEls;
DefList prodList;
/* Dumping. */
DotItemIndex dotItemIndex;
PredDeclList predDeclList;
/* The name of the file the fsm is from, and the spec name. */
// EXISTS IN RL: char *fileName;
String parserName;
// EXISTS IN RL: InputLoc sectionLoc;
/* How to access the instance data. */
String access;
/* The name of the token structure. */
String tokenStruct;
GenericType *anyList;
GenericType *anyMap;
GenericType *anyVector;
LangEl *ptrLangEl;
LangEl *voidLangEl;
LangEl *strLangEl;
LangEl *anyLangEl;
LangEl *rootLangEl;
LangEl *noTokenLangEl;
LangEl *eofLangEl;
LangEl *errorLangEl;
LangEl *ignoreLangEl;
Namespace *rootNamespace;
int nextLelId;
int firstNonTermId;
LangEl **langElIndex;
PdaState *actionDestState;
DefSetSet prodSetSet;
Production **prodIdIndex;
AlphSet literalSet;
PatList patternList;
ConsList replList;
ParserTextList parserTextList;
StructDef *global;
StructEl *globalSel;
ObjectDef *globalObjectDef;
ObjectField *arg0;
ObjectField *argv;
StructDef *argvEl;
StructEl *argvElSel;
StructDef *stream;
StructEl *streamSel;
VectorTypeIdMap vectorTypeIdMap;
UniqueType *findUniqueType( enum TYPE typeId );
UniqueType *findUniqueType( enum TYPE typeId, LangEl *langEl );
UniqueType *findUniqueType( enum TYPE typeId, IterDef *iterDef );
UniqueType *findUniqueType( enum TYPE typeId, StructEl *structEl );
UniqueType *findUniqueType( enum TYPE typeId, GenericType *generic );
UniqueGeneric *findUniqueGeneric( UniqueGeneric::Type type,
UniqueType *utKey, UniqueType *utValue );
UniqueGeneric *findUniqueGeneric( UniqueGeneric::Type type,
UniqueType *utValue );
UniqueType *uniqueTypeNil;
UniqueType *uniqueTypeVoid;
UniqueType *uniqueTypePtr;
UniqueType *uniqueTypeBool;
UniqueType *uniqueTypeInt;
UniqueType *uniqueTypeStr;
UniqueType *uniqueTypeIgnore;
UniqueType *uniqueTypeAny;
UniqueType *uniqueTypeStream;
UniqueTypeMap uniqeTypeMap;
UniqueRepeatMap uniqeRepeatMap;
UniqueGenericMap uniqueGenericMap;
void declareGlobalFields();
void declareStrFields();
void declareStreamField( ObjectDef *objDef, code_t getLength );
void declareStreamFields();
void declareIntFields();
void declareTokenFields();
ObjectDef *intObj;
ObjectDef *strObj;
ObjectDef *streamObj;
struct fsm_tables *fsmTables;
struct colm_sections *runtimeData;
int nextPatConsId;
int nextGenericId;
FunctionList functionList;
FunctionList inHostList;
int nextFuncId;
int nextHostId;
enum CompileContext {
CompileTranslation,
CompileReduction,
CompileFunction,
CompileRoot
};
CompileContext compileContext;
LongVect returnJumps;
LongVect breakJumps;
Function *curFunction;
/* For stack unwinding. Used at exits, returns, iterator destroy, etc. */
CodeVect unwindCode;
ObjectField *makeDataEl();
ObjectField *makePosEl();
ObjectField *makeLineEl();
IterDef *findIterDef( IterDef::Type type, GenericType *generic );
IterDef *findIterDef( IterDef::Type type, Function *func );
IterDef *findIterDef( IterDef::Type type );
IterDefSet iterDefSet;
enum GeneratesType { GenToken, GenIgnore, GenCfl };
int nextObjectId;
GeneratesType generatesType;
bool generatesIgnore;
StringMap literalStrings;
long nextFrameId;
long nextParserId;
ObjectDef *rootLocalFrame;
bool revertOn;
RedFsm *redFsm;
PdaGraph *pdaGraph;
struct pda_tables *pdaTables;
long predValue;
long nextMatchEndNum;
TypeRef *argvTypeRef;
bool inContiguous;
int contiguousOffset;
int contiguousStretch;
void declareReVars();
void initReductionNeeds( Reduction *reduction );
void loadRefs( Reduction *reduction, Production *production,
const ReduceTextItemList &list );
void writeHostCall();
void writeNeeds();
void writeCommit();
void writeLhsRef( Production *production, ReduceTextItem *i );
void writeRhsRef( Production *production, ReduceTextItem *i );
void writeRhsLoc( Production *production, ReduceTextItem *i );
void writeHostItemList( Production *production, const ReduceTextItemList &list );
void writeCommitStub();
};
void afterOpMinimize( FsmGraph *fsm, bool lastInSeq = true );
Key makeFsmKeyHex( char *str, const InputLoc &loc, Compiler *pd );
Key makeFsmKeyDec( char *str, const InputLoc &loc, Compiler *pd );
Key makeFsmKeyNum( char *str, const InputLoc &loc, Compiler *pd );
Key makeFsmKeyChar( char c, Compiler *pd );
void makeFsmKeyArray( Key *result, char *data, int len, Compiler *pd );
void makeFsmUniqueKeyArray( KeySet &result, char *data, int len,
bool caseInsensitive, Compiler *pd );
FsmGraph *makeBuiltin( BuiltinMachine builtin, Compiler *pd );
FsmGraph *dotFsm( Compiler *pd );
FsmGraph *dotStarFsm( Compiler *pd );
void errorStateLabels( const NameSet &locations );
struct ColmParser;
typedef AvlMap<String, ColmParser *, CmpStr> ParserDict;
typedef AvlMapEl<String, ColmParser *> ParserDictEl;
LangEl *declareLangEl( Compiler *pd, Namespace *nspace,
const String &data, LangEl::Type type );
LangEl *addLangEl( Compiler *pd, Namespace *nspace,
const String &data, LangEl::Type type );
StructEl *declareStruct( Compiler *pd, Namespace *nspace,
const String &data, StructDef *context );
void declareTypeAlias( Compiler *pd, Namespace *nspace,
const String &data, TypeRef *typeRef );
LangEl *findType( Compiler *pd, Namespace *nspace, const String &data );
ObjectMethod *initFunction( UniqueType *retType, ObjectDef *obj,
const String &name, int methIdWV, int methIdWC,
bool isConst, bool useFnInstr = false, GenericType *useGeneric = 0 );
ObjectMethod *initFunction( UniqueType *retType, ObjectDef *obj,
const String &name, int methIdWV, int methIdWC,
UniqueType *arg1, bool isConst, bool useFnInstr = false,
GenericType *useGeneric = 0 );
ObjectMethod *initFunction( UniqueType *retType, ObjectDef *obj,
const String &name, int methIdWV, int methIdWC,
UniqueType *arg1, UniqueType *arg2, bool isConst,
bool useFnInstr = false, GenericType *useGeneric = 0 );
ObjectMethod *initFunction( UniqueType *retType, Namespace *nspace, ObjectDef *obj,
const String &name, int methIdWV, int methIdWC,
bool isConst, bool useFnInstr = false, GenericType *useGeneric = 0 );
ObjectMethod *initFunction( UniqueType *retType, Namespace *nspace, ObjectDef *obj,
const String &name, int methIdWV, int methIdWC,
UniqueType *arg1, bool isConst, bool useFnInstr = false,
GenericType *useGeneric = 0 );
ObjectMethod *initFunction( UniqueType *retType, Namespace *nspace, ObjectDef *obj,
const String &name, int methIdWV, int methIdWC,
UniqueType *arg1, UniqueType *arg2, bool isConst,
bool useFnInstr = false, GenericType *useGeneric = 0 );
#endif /* _COLM_PARSEDATA_H */
| 26.058401 | 91 | 0.740199 | [
"object",
"vector"
] |
c8f4a32e74cd4b3a68b13cd6f6613978a1ce3f1b | 3,704 | h | C | include/quicly/buffer.h | deweerdt/quicly | c246507710d743e5cc9b2d467b746761be035840 | [
"MIT"
] | null | null | null | include/quicly/buffer.h | deweerdt/quicly | c246507710d743e5cc9b2d467b746761be035840 | [
"MIT"
] | null | null | null | include/quicly/buffer.h | deweerdt/quicly | c246507710d743e5cc9b2d467b746761be035840 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2017 Fastly, Kazuho Oku
*
* 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 quicly_buffer_h
#define quicly_buffer_h
#include <stddef.h>
#include "picotls.h"
struct st_quicly_buffer_vec_t;
typedef void (*quicly_buffer_free_cb)(struct st_quicly_buffer_vec_t *vec);
struct st_quicly_buffer_vec_t {
/**
* pointer to next
*/
struct st_quicly_buffer_vec_t *next;
/**
* pointer to data (points to _buf if the vector is internal)
*/
uint8_t *p;
/**
* offset to where the data is stored
*/
size_t len;
/**
* callback that destroys the vec
*/
quicly_buffer_free_cb free_cb;
/**
* buffer used for internal vector
*/
uint8_t _buf[1];
};
typedef struct st_quicly_buffer_t {
/**
* references to the linked list of vec
*/
struct st_quicly_buffer_vec_t *first, **tail_ref;
/**
* amount of data available
*/
size_t len;
/**
* offset within the `first` where the data starts from
*/
size_t skip;
/**
* capacity of the last vec
*/
size_t capacity;
} quicly_buffer_t;
typedef struct st_quicly_buffer_iter_t {
struct st_quicly_buffer_vec_t *vec;
size_t vec_off;
} quicly_buffer_iter_t;
static void quicly_buffer_init(quicly_buffer_t *buf);
void quicly_buffer_dispose(quicly_buffer_t *buf);
void quicly_buffer_set_fast_external(quicly_buffer_t *buf, struct st_quicly_buffer_vec_t *vec, const void *p, size_t len);
int quicly_buffer_push(quicly_buffer_t *buf, const void *p, size_t len, quicly_buffer_free_cb free_cb);
int quicly_buffer_write(quicly_buffer_t *buf, size_t pos, const void *p, size_t len);
size_t quicly_buffer_shift(quicly_buffer_t *buf, size_t delta);
void quicly_buffer_emit(quicly_buffer_iter_t *iter, size_t nbytes, void *_dst, ptls_aead_context_t *aead);
static void quicly_buffer_init_iter(quicly_buffer_t *buf, quicly_buffer_iter_t *iter);
static void quicly_buffer_advance_iter(quicly_buffer_iter_t *iter, size_t nbytes);
/* inline definitions */
inline void quicly_buffer_init(quicly_buffer_t *buf)
{
buf->first = NULL;
buf->tail_ref = &buf->first;
buf->len = 0;
buf->skip = 0;
buf->capacity = 0;
}
inline void quicly_buffer_init_iter(quicly_buffer_t *buf, quicly_buffer_iter_t *iter)
{
iter->vec = buf->first;
iter->vec_off = buf->skip;
}
inline void quicly_buffer_advance_iter(quicly_buffer_iter_t *iter, size_t nbytes)
{
while (nbytes >= iter->vec->len - iter->vec_off) {
nbytes -= iter->vec->len - iter->vec_off;
iter->vec = iter->vec->next;
iter->vec_off = 0;
}
iter->vec_off += nbytes;
}
#endif
| 31.65812 | 122 | 0.716793 | [
"vector"
] |
c8fd10765a89b8d03241fec1c50821350860d921 | 12,628 | h | C | mindspore/ccsrc/minddata/dataset/engine/datasetops/source/coco_op.h | httpsgithu/mindspore | c29d6bb764e233b427319cb89ba79e420f1e2c64 | [
"Apache-2.0"
] | 1 | 2022-02-23T09:13:43.000Z | 2022-02-23T09:13:43.000Z | mindspore/ccsrc/minddata/dataset/engine/datasetops/source/coco_op.h | 949144093/mindspore | c29d6bb764e233b427319cb89ba79e420f1e2c64 | [
"Apache-2.0"
] | null | null | null | mindspore/ccsrc/minddata/dataset/engine/datasetops/source/coco_op.h | 949144093/mindspore | c29d6bb764e233b427319cb89ba79e420f1e2c64 | [
"Apache-2.0"
] | null | null | null | /**
* Copyright 2019-2022 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_MINDDATA_DATASET_ENGINE_DATASETOPS_SOURCE_COCO_OP_H_
#define MINDSPORE_CCSRC_MINDDATA_DATASET_ENGINE_DATASETOPS_SOURCE_COCO_OP_H_
#include <map>
#include <memory>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "minddata/dataset/core/tensor.h"
#include "minddata/dataset/engine/data_schema.h"
#include "minddata/dataset/engine/datasetops/parallel_op.h"
#include "minddata/dataset/engine/datasetops/source/mappable_leaf_op.h"
#include "minddata/dataset/engine/datasetops/source/sampler/sampler.h"
#ifndef ENABLE_ANDROID
#include "minddata/dataset/kernels/image/image_utils.h"
#else
#include "minddata/dataset/kernels/image/lite_image_utils.h"
#endif
#include "minddata/dataset/util/path.h"
#include "minddata/dataset/util/queue.h"
#include "minddata/dataset/util/status.h"
#include "minddata/dataset/util/wait_post.h"
namespace mindspore {
namespace dataset {
// Forward declares
template <typename T>
class Queue;
using CoordinateRow = std::vector<std::vector<float>>;
class CocoOp : public MappableLeafOp {
public:
enum class TaskType { Detection = 0, Stuff = 1, Panoptic = 2, Keypoint = 3, Captioning = 4 };
class Builder {
public:
// Constructor for Builder class of ImageFolderOp
// @param uint32_t numWrks - number of parallel workers
// @param dir - directory folder got ImageNetFolder
Builder();
// Destructor.
~Builder() = default;
// Setter method.
// @param const std::string & build_dir
// @return Builder setter method returns reference to the builder.
Builder &SetDir(const std::string &build_dir) {
builder_dir_ = build_dir;
return *this;
}
// Setter method.
// @param const std::string & build_file
// @return Builder setter method returns reference to the builder.
Builder &SetFile(const std::string &build_file) {
builder_file_ = build_file;
return *this;
}
// Setter method.
// @param const std::string & task_type
// @return Builder setter method returns reference to the builder.
Builder &SetTask(const std::string &task_type) {
if (task_type == "Detection") {
builder_task_type_ = TaskType::Detection;
} else if (task_type == "Stuff") {
builder_task_type_ = TaskType::Stuff;
} else if (task_type == "Panoptic") {
builder_task_type_ = TaskType::Panoptic;
} else if (task_type == "Keypoint") {
builder_task_type_ = TaskType::Keypoint;
}
return *this;
}
// Setter method.
// @param int32_t num_workers
// @return Builder setter method returns reference to the builder.
Builder &SetNumWorkers(int32_t num_workers) {
builder_num_workers_ = num_workers;
return *this;
}
// Setter method.
// @param int32_t op_connector_size
// @return Builder setter method returns reference to the builder.
Builder &SetOpConnectorSize(int32_t op_connector_size) {
builder_op_connector_size_ = op_connector_size;
return *this;
}
// Setter method.
// @param std::shared_ptr<Sampler> sampler
// @return Builder setter method returns reference to the builder.
Builder &SetSampler(std::shared_ptr<SamplerRT> sampler) {
builder_sampler_ = std::move(sampler);
return *this;
}
// Setter method.
// @param bool do_decode
// @return Builder setter method returns reference to the builder.
Builder &SetDecode(bool do_decode) {
builder_decode_ = do_decode;
return *this;
}
// Check validity of input args
// @return Status The status code returned
Status SanityCheck();
// The builder "Build" method creates the final object.
// @param std::shared_ptr<CocoOp> *op - DatasetOp
// @return Status The status code returned
Status Build(std::shared_ptr<CocoOp> *op);
private:
bool builder_decode_;
std::string builder_dir_;
std::string builder_file_;
TaskType builder_task_type_;
int32_t builder_num_workers_;
int32_t builder_op_connector_size_;
int32_t builder_rows_per_buffer_;
std::shared_ptr<SamplerRT> builder_sampler_;
std::unique_ptr<DataSchema> builder_schema_;
};
/// \brief Constructor.
/// \param[in] task_type Task type of Coco.
/// \param[in] image_folder_path Image folder path of Coco.
/// \param[in] annotation_path Annotation json path of Coco.
/// \param[in] num_workers Number of workers reading images in parallel.
/// \param[in] queue_size Connector queue size.
/// \param[in] num_samples Number of samples to read.
/// \param[in] decode Whether to decode images.
/// \param[in] data_schema The schema of the Coco dataset.
/// \param[in] sampler Sampler tells CocoOp what to read.
CocoOp(const TaskType &task_type, const std::string &image_folder_path, const std::string &annotation_path,
int32_t num_workers, int32_t queue_size, bool decode, std::unique_ptr<DataSchema> data_schema,
std::shared_ptr<SamplerRT> sampler, bool extra_metadata);
/// \brief Destructor.
~CocoOp() = default;
/// \brief A print method typically used for debugging.
/// \param[out] out The output stream to write output to.
/// \param[in] show_all A bool to control if you want to show all info or just a summary.
void Print(std::ostream &out, bool show_all) const override;
/// \param[out] count Output rows number of CocoDataset.
Status CountTotalRows(int64_t *count);
/// \brief Op name getter.
/// \return Name of the current Op.
std::string Name() const override { return "CocoOp"; }
/// \brief Gets the class indexing.
/// \return Status The status code returned.
Status GetClassIndexing(std::vector<std::pair<std::string, std::vector<int32_t>>> *output_class_indexing) override;
private:
/// \brief Load a tensor row according to image id.
/// \param[in] row_id Id for this tensor row.
/// \param[out] row Image & target read into this tensor row.
/// \return Status The status code returned.
Status LoadTensorRow(row_id_type row_id, TensorRow *row) override;
/// \brief Load a tensor row with vector which a vector to a tensor, for "Detection" task.
/// \param[in] row_id Id for this tensor row.
/// \param[in] image_id Image id.
/// \param[in] image Image tensor.
/// \param[in] coordinate Coordinate tensor.
/// \param[out] row Image & target read into this tensor row.
/// \return Status The status code returned.
Status LoadDetectionTensorRow(row_id_type row_id, const std::string &image_id, std::shared_ptr<Tensor> image,
std::shared_ptr<Tensor> coordinate, TensorRow *trow);
/// \brief Load a tensor row with vector which a vector to a tensor, for "Stuff/Keypoint" task.
/// \param[in] row_id Id for this tensor row.
/// \param[in] image_id Image id.
/// \param[in] image Image tensor.
/// \param[in] coordinate Coordinate tensor.
/// \param[out] row Image & target read into this tensor row.
/// \return Status The status code returned.
Status LoadSimpleTensorRow(row_id_type row_id, const std::string &image_id, std::shared_ptr<Tensor> image,
std::shared_ptr<Tensor> coordinate, TensorRow *trow);
/// \brief Load a tensor row with vector which a vector to multi-tensor, for "Panoptic" task.
/// \param[in] row_id Id for this tensor row.
/// \param[in] image_id Image id.
/// \param[in] image Image tensor.
/// \param[in] coordinate Coordinate tensor.
/// \param[out] row Image & target read into this tensor row.
/// \return Status The status code returned.
Status LoadMixTensorRow(row_id_type row_id, const std::string &image_id, std::shared_ptr<Tensor> image,
std::shared_ptr<Tensor> coordinate, TensorRow *trow);
/// \brief Load a tensor row with vector which a vector to multi-tensor, for "Captioning" task.
/// \param[in] row_id Id for this tensor row.
/// \param[in] image_id Image id.
/// \param[in] image Image tensor.
/// \param[in] captions Captions tensor.
/// \param[out] trow Image & target read into this tensor row.
/// \return Status The status code returned.
Status LoadCaptioningTensorRow(row_id_type row_id, const std::string &image_id, std::shared_ptr<Tensor> image,
std::shared_ptr<Tensor> captions, TensorRow *trow);
/// \param[in] path Path to the image file.
/// \param[in] col Contains tensor implementation and datatype.
/// \param[out] tensor Returned tensor.
/// \return Status The status code returned.
Status ReadImageToTensor(const std::string &path, const ColDescriptor &col, std::shared_ptr<Tensor> *tensor) const;
/// \brief Read annotation from Annotation folder.
/// \return Status The status code returned.
Status PrepareData() override;
/// \param[in] image_tree Image tree of json.
/// \param[out] image_vec Image id list of json.
/// \return Status The status code returned.
Status ImageColumnLoad(const nlohmann::json &image_tree, std::vector<std::string> *image_vec);
/// \param[in] categories_tree Categories tree of json.
/// \return Status The status code returned.
Status CategoriesColumnLoad(const nlohmann::json &categories_tree);
/// \param[in] categories_tree Categories tree of json.
/// \param[in] image_file Current image name in annotation.
/// \param[in] id Current unique id of annotation.
/// \return Status The status code returned.
Status DetectionColumnLoad(const nlohmann::json &annotation_tree, const std::string &image_file, const int32_t &id);
/// \param[in] categories_tree Categories tree of json.
/// \param[in] image_file Current image name in annotation.
/// \param[in] id Current unique id of annotation.
/// \return Status The status code returned.
Status StuffColumnLoad(const nlohmann::json &annotation_tree, const std::string &image_file, const int32_t &id);
/// \param[in] categories_tree Categories tree of json.
/// \param[in] image_file Current image name in annotation.
/// \param[in] id Current unique id of annotation.
/// \return Status The status code returned.
Status KeypointColumnLoad(const nlohmann::json &annotation_tree, const std::string &image_file, const int32_t &id);
/// \param[in] categories_tree Categories tree of json.
/// \param[in] image_file Current image name in annotation.
/// \param[in] image_id Current unique id of annotation.
/// \return Status The status code returned.
Status PanopticColumnLoad(const nlohmann::json &annotation_tree, const std::string &image_file,
const int32_t &image_id);
/// \brief Function for finding a caption in annotation_tree.
/// \param[in] annotation_tree Annotation tree of json.
/// \param[in] image_file Current image name in annotation.
/// \param[in] id Current unique id of annotation.
/// \return Status The status code returned.
Status CaptionColumnLoad(const nlohmann::json &annotation_tree, const std::string &image_file, const int32_t &id);
template <typename T>
Status SearchNodeInJson(const nlohmann::json &input_tree, std::string node_name, T *output_node);
/// \brief Private function for computing the assignment of the column name map.
/// \return Status The status code returned.
Status ComputeColMap() override;
bool decode_;
std::string image_folder_path_;
std::string annotation_path_;
TaskType task_type_;
std::unique_ptr<DataSchema> data_schema_;
bool extra_metadata_;
std::vector<std::string> image_ids_;
std::map<int32_t, std::string> image_index_;
std::vector<std::pair<std::string, std::vector<int32_t>>> label_index_;
std::map<std::string, CoordinateRow> coordinate_map_;
std::map<std::string, std::vector<uint32_t>> simple_item_map_;
std::map<std::string, std::vector<std::string>> captions_map_;
std::set<uint32_t> category_set_;
};
} // namespace dataset
} // namespace mindspore
#endif // MINDSPORE_CCSRC_MINDDATA_DATASET_ENGINE_DATASETOPS_SOURCE_COCO_OP_H_
| 41.403279 | 118 | 0.710485 | [
"object",
"vector"
] |
c8fe360bee0057a89aaeee147e5859d3593d652e | 25,050 | h | C | src/math/Functions.h | bayolau/discovar | 9e472aca13670e40ab2234b89c8afd64875c58bf | [
"MIT"
] | null | null | null | src/math/Functions.h | bayolau/discovar | 9e472aca13670e40ab2234b89c8afd64875c58bf | [
"MIT"
] | null | null | null | src/math/Functions.h | bayolau/discovar | 9e472aca13670e40ab2234b89c8afd64875c58bf | [
"MIT"
] | null | null | null | ///////////////////////////////////////////////////////////////////////////////
// SOFTWARE COPYRIGHT NOTICE AGREEMENT //
// This software and its documentation are copyright (2015) by the //
// Broad Institute. All rights are reserved. This software is supplied //
// without any warranty or guaranteed support whatsoever. The Broad //
// Institute is not responsible for its use, misuse, or functionality. //
///////////////////////////////////////////////////////////////////////////////
#ifndef FUNCTIONS
#define FUNCTIONS
#include "Vec.h"
#include "math/Arith.h"
#include <algorithm>
#include <cmath>
#include <numeric>
// ===========================================================================
//
// Min functions
//
// ==========================================================================
template <class T> inline T const& Min(const T& t1,const T& t2)
{ return (t1<t2)?t1:t2; }
template <class V> inline typename V::value_type const& Min( V const& v )
{ auto beg=v.begin(), end=v.end();
ForceAssert(beg!=end);
return *std::min_element(beg,end); }
/// Compute a vector of length last-first which represents the minimum,
/// as computed by op, in a window of size nbhd on each side, of the
/// entries of the sequence [first, last). Window entries that extend
/// outside the bounds of the input sequence are ignored. For
/// instance, MinWindow of the 8 integers 01234567 with nbhd 3 is
/// 00001234.
///
/// The op should be similar to std::less in that op(a,b)==op(b,a)
/// implies a==b.
template <class FwdIt, class OutIt, class Op>
void MinWindow(FwdIt first, FwdIt last, OutIt out, int nbhd, Op op)
{
// We consider a window [first, winLast) "centered" on center.
FwdIt winLast = first, center=first;
// w is the distance from first to center.
typename FwdIt::difference_type w=0;
// Initialize the window: initially of size nbhd+1 but of size up to
// 2*nbhd+1 when possible. *smallest is the smallest value in the
// window, according to operator<, and the leftmost such if there is
// more than one.
FwdIt smallest = first, nextSmallest = first;
for (int i=0; i<=nbhd && winLast<last; ++winLast, ++i) {
if (op(*winLast,*smallest)) {
smallest = winLast;
}
}
while (center!=last) {
// Output an entry and move on to next
*out = *smallest;
++out;
++center;
++w;
// Now move the window along, moving first and winLast as necessary
// to keep the window size as close to 2*nbhd+1 as possible while
// keeping both in bounds.
if (winLast<last) {
if (op(*winLast,*smallest)) {
smallest = winLast;
}
++winLast;
}
if (w>nbhd) {
--w;
if (smallest==first++) {
smallest = min_element(first, winLast, op);
}
}
}
}
/// Compute a vector of length last-first which represents the minimum
/// in a window of size nbhd (on each side) of the entries of the
/// sequence [first, last). Window entries that extend outside the
/// bounds of the input sequence are ignored. For instance, MinWindow
/// of the 8 integers 01234567 with nbhd 3 is 00001234.
template <class FwdIt, class OutIt>
inline void MinWindow(FwdIt first, FwdIt last, OutIt out, int nbhd)
{
MinWindow(first, last, out, nbhd,
std::less<typename std::iterator_traits<FwdIt>::value_type>());
}
// ==========================================================================
//
// Max functions
//
// ==========================================================================
template <class T> inline T const& Max(const T& t1,const T& t2)
{ return (t1<t2)?t2:t1; }
template <class V> inline typename V::value_type const& Max( V const& v )
{ auto beg=v.begin(), end=v.end();
ForceAssert(beg!=end);
return *std::max_element(beg,end); }
// MaxMax: return maximum entry in a vec<vec>.
template<class T> inline T MaxMax( const vec< vec<T> >& v )
{ Bool first = True;
T answer = 0;
for ( int i = 0; i < v.isize( ); i++ )
{ for ( int j = 0; j < v[i].isize( ); j++ )
{ if (first)
{ answer = v[i][j];
first = False; }
else answer = Max( answer, v[i][j] ); } }
if (first) FatalErr( "MaxMax called on empty vec<vec>." );
return answer; }
/// Like MinWindow but for maximum. For instance, MaxWindow
/// of the 8 integers 01234567 with nbhd 3 is 34567777.
template<class FwdIt, class OutIt>
inline void MaxWindow(FwdIt first, FwdIt last, OutIt out, int nbhd)
{
MinWindow(first, last, out, nbhd,
std::greater<typename std::iterator_traits<FwdIt>::value_type>());
}
// ===========================================================================
//
// Sum functions
//
// ===========================================================================
///Templatized sum over all the elements of a container of numeric values.
///Prerequisites: V has begin(), end(), and a value_type that is
///convertible to longlong.
template<class V>
longlong Sum (const V & v) {
longlong ret=0;
return accumulate(v.begin(), v.end(), ret);
}
///Templatized cumulative sum over all the elements of a container of numeric values.
///Prerequisites: V has begin() and end() methods that return valid STL iterators
template<class V>
void CumulativeSum (const V & in, V & out ) {
out.resize( in.size() );
partial_sum( in.begin(), in.end(), out.begin() );
}
inline int Sum( const vec<int>& v )
{ int answer = 0;
for ( unsigned int i = 0; i < v.size( ); i++ )
answer += v[i];
return answer; }
inline longlong BigSum( const vec<int>& v )
{ longlong answer = 0;
for ( unsigned int i = 0; i < v.size( ); i++ )
answer += v[i];
return answer; }
inline int Sum( const vec<unsigned int>& v )
{ int answer = 0;
for ( unsigned int i = 0; i < v.size( ); i++ )
answer += v[i];
return answer; }
inline longlong BigSum( const vec<unsigned int>& v )
{ longlong answer = 0;
for ( unsigned int i = 0; i < v.size( ); i++ )
answer += v[i];
return answer; }
inline longlong Sum( const vec<longlong>& v )
{ longlong answer = 0;
for ( unsigned int i = 0; i < v.size( ); i++ )
answer += v[i];
return answer; }
inline longlong BigSum( const vec<longlong>& v )
{ longlong answer = 0;
for ( unsigned int i = 0; i < v.size( ); i++ )
answer += v[i];
return answer; }
inline uint64_t BigSum( const vec<uint64_t>& v )
{ uint64_t answer = 0;
for ( size_t i = 0; i < v.size( ); i++ )
answer += v[i];
return answer; }
inline float Sum( const vec<float>& v )
{ float answer = 0;
for ( unsigned int i = 0; i < v.size( ); i++ )
answer += v[i];
return answer; }
inline double Sum( const vec<double>& v )
{ double answer = 0;
for ( unsigned int i = 0; i < v.size( ); i++ )
answer += v[i];
return answer; }
inline long double Sum( const vec<long double>& v )
{ long double answer = 0;
for ( unsigned int i = 0; i < v.size( ); i++ )
answer += v[i];
return answer; }
inline void CumulativeSum( const vec<double>& in, vec<double> & out )
{ double value = 0.0;
out.resize(in.size());
for ( unsigned int i = 0; i < in.size( ); i++ ) {
value += in[i];
out[i] = value;
}
}
inline int Sum( const vec<Bool>& v )
{ int answer = 0;
for ( unsigned int i = 0; i < v.size( ); i++ )
answer += v[i];
return answer; }
inline uint64_t BigSum( const vec<Bool>& v )
{ uint64_t answer = 0;
for ( size_t i = 0; i < v.size( ); i++ )
answer += v[i];
return answer; }
/// Compute a vector of length last-first which represents the sums in
/// a window of size nbhd (on each side) of the entries of the sequence
/// [first, last). Window entries that extend outside the bounds of
/// the input sequence are ignored. For instance, SumWindow of the 8
/// integers 01231011 with nbhd 3 is 67789863.
template<class FwdIt, class OutIt>
void SumWindow(FwdIt first, FwdIt last, OutIt out, int nbhd)
{
// We consider a window [first, winLast) "centered" on center.
FwdIt winLast = first, center=first;
// w is the distance from first to center.
typename FwdIt::difference_type w=0;
// Initialize the window: initially of size nbhd+1 but of size up to
// 2*nbhd+1 when possible. s is the current sum.
typename FwdIt::value_type s=0;
for (int i=0; i<=nbhd && winLast<last; ++winLast, ++i) {
s += *winLast;
}
while (center!=last) {
// Output an entry and move on to next
*out = s;
++out;
++center;
++w;
// Now move the window along, moving first and winLast as
// necessary to keep w==nbhd if possible while keeping both in
// bounds. Update s whenever either pointer changes.
if (winLast<last) {
s += *winLast;
++winLast;
}
if (w>nbhd) {
--w;
s -= *first;
++first;
}
}
}
// ===========================================================================
//
// Mean and standard deviation
//
// ===========================================================================
class NormalDistribution
{
public:
float mu_;
float sigma_;
NormalDistribution(const float mu = 0.0, const float sigma = 0.0)
: mu_(mu), sigma_(sigma) {}
inline float Zscore(const float x) const
{ return (0 == sigma_) ? 0 : (x - mu_) / sigma_; }
inline float ProbabilityDensity(const float x) const
{ if (0 == sigma_) return 0;
const float z = Zscore(x);
return exp(-0.5 * z * z) * sqrt(0.5 / M_PI) / sigma_;
}
inline float ProbabilityLT(const float x) const
{ return 0.5 * erfc(-Zscore(x) * sqrt(0.5)); }
inline float ProbabilityGT(const float x) const
{ return 1.0 - ProbabilityLT(x); }
// X += Y
inline NormalDistribution & operator+=(const NormalDistribution & Y)
{
mu_ += Y.mu_;
sigma_ = sqrt(sigma_ * sigma_ + Y.sigma_ * Y.sigma_);
return *this;
}
// X -= Y
inline NormalDistribution & operator-=(const NormalDistribution & Y)
{
mu_ -= Y.mu_;
sigma_ = sqrt(sigma_ * sigma_ + Y.sigma_ * Y.sigma_);
return *this;
}
};
// X == Y
inline bool operator==(const NormalDistribution & X,
const NormalDistribution & Y)
{ return X.mu_ == Y.mu_ && X.sigma_ == Y.sigma_; }
// X < Y
inline bool operator<(const NormalDistribution & X,
const NormalDistribution & Y)
{ return X.mu_ < Y.mu_; }
// X <= Y
inline bool operator<=(const NormalDistribution & X,
const NormalDistribution & Y)
{ return X.mu_ <= Y.mu_; }
// X > Y
inline bool operator>(const NormalDistribution & X,
const NormalDistribution & Y)
{ return X.mu_ > Y.mu_; }
// X >= Y
inline bool operator>=(const NormalDistribution & X,
const NormalDistribution & Y)
{ return X.mu_ >= Y.mu_; }
// -X
inline NormalDistribution operator-(const NormalDistribution & X)
{ return NormalDistribution(-X.mu_, X.sigma_); }
// X + dx
inline NormalDistribution operator+(const NormalDistribution & X,
const float dx)
{ return NormalDistribution(X.mu_ + dx, X.sigma_); }
// dx + X
inline NormalDistribution operator+(const float dx,
const NormalDistribution & X)
{ return NormalDistribution(dx + X.mu_, X.sigma_); }
// X - dx
inline NormalDistribution operator-(const NormalDistribution & X,
const float dx)
{ return NormalDistribution(X.mu_ - dx, X.sigma_); }
// dx - X
inline NormalDistribution operator-(const float dx,
const NormalDistribution & X)
{ return NormalDistribution(dx - X.mu_, X.sigma_); }
inline ostream & operator<<(ostream & os, const
NormalDistribution & X)
{ return os << X.mu_ << "\t" << X.sigma_ << endl; }
inline istream &operator>>( istream &in, NormalDistribution &nd ) {
in >> nd.mu_ >> nd.sigma_;
return in;
}
/* CombineNormalDistribution Filipe Ribeiro 2009-06-22
*
* When you have different measurements (normaly distributed) of the same quantity,
* you can compute the resultant normal distribution.
*
* The resultant normal distribution (mu, sigma) satisfies:
*
* 1 / sigma^2 = sum( 1 / sigma[i]^2 )
*
* mu / sigma^2 = sum( mu[i] / sigma[i]^2 )
*
*/
NormalDistribution CombineNormalDistributions(const vec<NormalDistribution> & ds,
float * score = 0);
/* ClusterNormalDistributions Filipe Ribeiro 2010-04-16
*
* Extract clusters based on overlaps of n_sigma x sigma.
*/
vec< vec<NormalDistribution> >
ClusterNormalDistributions(const vec<NormalDistribution> & ds,
const float n_sigma = 1);
///Calculate mean and stdev of a vector, return {-1,-1} if vector empty.
NormalDistribution SafeMeanStdev(const vec<float> & points);
///Calculate mean and stdev based on count, sum and sumsq.
///return {-1,-1} if vector empty.
NormalDistribution SafeMeanStdev(int count, double sum, double sumsq);
///Return optimal cutoff between distributions to minimize assignment error.
///Return nan if we cannot find one.
///ratio is the ratio of the prior probabilities: that is, we do not assume
///that both distributions have a total probability of 1. For example,
///if we know that there are 1000 items in d1 and only 100 in d2, we will
///put the cutoff closer to d1.mu_ than if there were equal numbers.
///Precondition: d1.mu_ < d2.mu_.
double OptimalCutoff(const NormalDistribution & d1,
const NormalDistribution & d2,
const double ratio = 1);
template<class V>
inline double Mean( const V & v )
{
ForceAssert ( v.size() > 0 );
double sum = 0.0;
for ( int i = 0; i < int(v.size()); i++ )
sum += v[i];
return sum / static_cast<double>(v.size());
}
template<class V>
inline double StdDev( const V & v , const double mean )
{
ForceAssert ( v.size() > 0 );
double dev, sumdevsq = 0.0;
for (int i = 0; i < int(v.size()); i++) {
dev = v[i] - mean;
sumdevsq += dev*dev;
}
return sqrt( sumdevsq/static_cast<double>(v.size()) );
}
template <class T> inline T Mean(const T& t1,const T& t2)
{ return (t1+t2)/2; }
template <class T> inline T Mean(const T& t1,const T& t2, const T& t3)
{ return (t1+t2+t3)/3; }
// ===========================================================================
//
// Weighted mean: return sum(v_i^2)/sum(v_i).
//
// ===========================================================================
template <class V>
inline Float WeightedMean( V const& v )
{ Float sum1 = 0, sum2 = 0;
for ( Float val : v )
{ sum1 += val;
sum2 += val*val; }
ForceAssert( sum1 != 0 );
return sum2 / sum1; }
/// Compute a vector of length last-first which represents the means in
/// a window of size nbhd (on each side) of the entries of the sequence
/// [first, last). Window entries that extend outside the bounds of
/// the input sequence are not included in the mean. For instance,
/// MeanWindow of the 8 integers 01231011 with nbhd 3 is the sequence
/// of doubles 6/4 7/5 7/6 8/7 9/7 8/6 6/5 3/4.
template<class FwdIt, class OutIt>
void MeanWindow(FwdIt first, FwdIt last, OutIt out, int nbhd)
{
// We consider a window [first, winLast) "centered" on center.
FwdIt winLast = first, center=first;
// w is the distance from first to center.
typename FwdIt::difference_type w=0;
// wid is the number of elements in the window.
typename FwdIt::difference_type wid=0;
// Initialize the window: initially of size nbhd+1 but of size up to
// 2*nbhd+1 when possible. s is the current sum.
typename FwdIt::value_type s=0;
for ( ; wid<=nbhd && winLast<last; ++winLast, ++wid) {
s += *winLast;
}
while (center!=last) {
// Output an entry and move on to next
*out = double(s)/wid;
++out;
++center;
++w;
// Now move the window along, moving first and winLast as
// necessary to keep w==nbhd if possible while keeping both in
// bounds. Update s whenever either pointer changes.
if (winLast<last) {
s += *winLast;
++winLast;
++wid;
}
if (w>nbhd) {
--w;
s -= *first;
++first;
--wid;
}
}
}
///Probability of n events for a Poisson dist. characterized by lambda.
double Poisson(double lambda, unsigned int n);
// Probability of at most n events for a Poisson dist. characterized by lambda.
// And long double version.
double PoissonCdf(double lambda, unsigned int n);
long double PoissonCdfLong( long double lambda, unsigned int n );
///Minimum number of events with cumulative probability greater than p
///for a Poisson dist. characterized by lambda.
int InversePoissonCdf(double lambda, double p);
// ===========================================================================
//
/// N50: given a list v of positive integers, suppose that each entry n is replaced
/// by n copies of itself. Then the median of the resulting enlarged list is the
/// "N50" of the original list.
///
/// It is assumed that v is sorted, prior to calling N50.
///
// ==========================================================================
template<class T> T N50( const vec<T>& v );
// N50_size: Returns the N50 of the vector sizes in the input vec<vec<T> >.
// Calls N50, above.
// N50_size sorts internally; it does not require that the input be sorted.
template<class T> int N50_size( const vec<vec<T> >& v );
// ===========================================================================
//
/// NStatistics: given a sorted list v of positive integers, suppose
/// that each entry n is replaced by n copies of itself, resulting in m
/// total entries. Reverse the order of this list, so that the largest
/// element comes first, and call this expanded, reversed list w..
/// Return a vector containing N10, N20, ... N90 for v, where NX is
/// the m*X/100'th element of w.
///
/// For example, if
/// v = 1, 2, 3, 4
/// then
/// w = 4, 4, 4, 4, 3, 3, 3, 2, 2, 1
/// and
/// N10 = 4
/// N20 = 4
/// N30 = 4
/// N40 = 4
/// N50 = 3
/// N60 = 3
/// N70 = 3
/// N80 = 2
/// N90 = 2
///
// ===========================================================================
template<class T> vec<T> NStatistics( const vec<T>& v );
// ===========================================================================
//
// Median
//
// Calculate the median of vector invec from invec[beg] to invec.size( )
// (class T needs operator+, operator/, and 2 to be defined).
//
// WARNING - WARNING - WARNING: Median expects (but does not check for)
// invec to be sorted.
//
// ===========================================================================
template <class T> inline T Median(const T& t1,const T& t2, const T& t3) {
if ((t1 >= t2 || t3 >= t2) && (t1 <= t2 || t3 <= t2)) return t2;
if ((t2 >= t3 || t1 >= t3) && (t2 <= t3 || t1 <= t3)) return t3;
if ((t3 >= t1 || t2 >= t1) && (t3 <= t1 || t2 <= t1)) return t1;
Assert(0==1);
}
template <class T> inline T Median( const vec<T> &v )
{ Assert( v.nonempty( ) );
return v[ v.size( )/2 ]; }
template <class T> inline T Median( const vec<T> &invec, unsigned int beg ) {
unsigned int end = invec.size( );
ForceAssert( beg < end );
if ( end - beg == 1 )
return invec[beg];
T result = 0;
if ( ( end - beg ) % 2 == 0 ) {
unsigned int posB = beg + ( ( end - beg ) / 2 );
unsigned int posA = posB - 1;
result = ( invec[posA] + invec[posB] ) / (T) 2;
}
else
result = invec[ beg + ( ( end - beg - 1 ) / 2 ) ];
return result;
}
// ===========================================================================
//
// Absolute value
//
// ===========================================================================
template <class T> inline T Abs(const T &a) { return a >= 0 ? a : -a; }
template <> inline Bool Abs<Bool>(const Bool &a) { return a; }
///round() is not declared for alpha
#if __alpha
#define round(X) nint(X)
#endif
// ===========================================================================
//
// Exclusive or
//
// ===========================================================================
template <class T> Bool Xor(T a, T b) { return a? (!(Bool)b) : ((Bool)b); }
template <class T> bool XOR(T a, T b) { return a? (!(bool)b) : ((bool)b); }
/// ===========================================================================
///
/// IntervalOverlap: Find the overlap between intervals [a,b) and [c,d), where
/// a,b,c,d are integers. Return 0 if they don't overlap.
///
/// ===========================================================================
inline int IntervalOverlap( int a, int b, int c, int d )
{ return Max( 0, Min(b, d) - Max(a, c) ); }
inline unsigned int IntervalOverlap( unsigned int a, unsigned int b,
unsigned int c, unsigned int d )
{ unsigned int m = Max(a, c), M = Min(b, d);
if ( m <= M ) return M - m;
return 0; }
inline longlong IntervalOverlap( longlong a, longlong b, longlong c, longlong d )
{ longlong m = Max(a, c), M = Min(b, d);
if ( m <= M ) return M - m;
return 0; }
inline double IntervalOverlap( double a, double b, double c, double d )
{ double m = Max(a, c), M = Min(b, d);
if ( m <= M ) return M - m;
return 0; }
/// Class to store a quadratic function.
/// operator() returns the function's value at x.
/// solutions() returns solutions to the equation (*this)(x) = 0;
struct QuadraticFunction {
double a, b, c;
QuadraticFunction(double a=0.0, double b=0.0, double c=0.0):
a(a), b(b), c(c) {}
double operator()(double x) const {
return (((a*x)+b)*x)+c; // two mults, not three
}
/// Return the solution(s) of the equation, or quiet_NaN() for both if there
/// aren't any.
pair<double,double> solutions() const;
};
inline int ifloor( double x ) { return int( floor(x) ); }
inline int iceil( double x ) { return int( ceil(x) ); }
/// Compute the cosine of the angle between two vectors [begin1,end1),
/// and [begin2,end2),
/// making sure to shrink the larger vector if the two are not the
/// same size.
/// Note that we have to put the data into a vec<double> because otherwise
/// the multiplication inside inner_product can easily overrun the limits
/// of the data type pointed to by ForwardIterX.
template<class ForwardIter1, class ForwardIter2>
float Cosine( ForwardIter1 begin1, ForwardIter1 end1,
ForwardIter2 begin2, ForwardIter2 end2) {
vec<double> d1(begin1, end1);
vec<double> d2(begin2, end2);
int size = static_cast<int>(min(d1.size(), d2.size()));
double norm1 = 0, norm2 = 0, ret = 0;
norm1 = sqrt(inner_product(d1.begin(), d1.begin() + size, d1.begin(), 0.0));
norm2 = sqrt(inner_product(d2.begin(), d2.begin() + size, d2.begin(), 0.0));
ret = inner_product(d1.begin(), d1.begin() + size, d2.begin(), 0.0)
/ (norm1*norm2);
if (ret > 1.0001) {
cerr << "cosine too high: " << ret << "\n";
for (int i=0; i != size; ++i) {
cerr << *(begin1+i) << " " << (*begin2+i) << "\n";
}
}
return static_cast<float>(ret);
}
inline int gcd( int x, int y )
{ ForceAssert( x >= 1 && y >= 1 );
if ( x > y ) swap( x, y );
if ( y % x == 0 ) return x;
return gcd( y % x, x ); }
Bool CombineMeasurements( const double g1, const double g2, const double d1,
const double d2, const double dmult, double& g, double& d );
// Inverse cdf of normal distribution
double InverseNormalCDF(double p, double mu=0.0, double sigma=1.0);
// Point-estimate of binomial parameter. That is, given the number of
// passes observed in a set of trials, determine a good single value
// for the binomial probability parameter p.
double EstProbability(int passes, int trials);
// Confidence interval for binomial parameter. That is, given the
// number of passes observed in a set of trials, determine a range of
// values for the binomial probability parameter p, such that an event
// with probability <= error must have occurred if the true
// probability is not in the returned range.
pair<double, double> BinomialConfidenceInterval(int passes, int trials, double error=0.05);
///Phred quality score, with small number correction.
float QualScoreFloat(int correct, int wrong);
///Phred quality score, with small number correction, rounded to int.
inline int QualScore(int correct, int wrong){
return int(round(QualScoreFloat(correct, wrong)));
}
/// Inlined, templatized square function.
template <class T> T Square(const T & t) { return t*t; }
/// Pow, integer power n^k.
template<class T> T IPow( T n, int k )
{ T p = 1;
for ( int i = 0; i < k; i++ )
p *= n;
return p; }
#endif
| 32.239382 | 91 | 0.571018 | [
"vector"
] |
4e003fe2663534d41b037b58a8eaf9d657fa9f74 | 10,380 | c | C | scheme/cyclone/common.c | nymacro/cyclone-bootstrap | df15f39e71e9fb4aa88e08f44fb52447eae389b9 | [
"MIT"
] | null | null | null | scheme/cyclone/common.c | nymacro/cyclone-bootstrap | df15f39e71e9fb4aa88e08f44fb52447eae389b9 | [
"MIT"
] | null | null | null | scheme/cyclone/common.c | nymacro/cyclone-bootstrap | df15f39e71e9fb4aa88e08f44fb52447eae389b9 | [
"MIT"
] | null | null | null | /**
** This file was automatically generated by the Cyclone scheme compiler
** http://justinethier.github.io/cyclone/
**
** (c) 2014-2019 Justin Ethier
** Version 0.11.6
**
**/
#define closcall1(td, clo,a1) \
if (obj_is_not_closure(clo)) { \
Cyc_apply(td, 0, (closure)(a1), clo); \
} else { \
((clo)->fn)(td, 1, clo,a1);\
}
#define return_closcall1(td, clo,a1) { \
char top; \
if (stack_overflow(&top, (((gc_thread_data *)data)->stack_limit))) { \
object buf[1]; buf[0] = a1;\
GC(td, clo, buf, 1); \
return; \
} else {\
closcall1(td, (closure) (clo),a1); \
return;\
} \
}
#define continue_or_gc1(td, clo,a1) { \
char *top = alloca(sizeof(char)); \
if (stack_overflow(top, (((gc_thread_data *)data)->stack_limit))) { \
object buf[1]; buf[0] = a1;\
GC(td, clo, buf, 1); \
return; \
} else {\
continue;\
} \
}
#define return_direct1(td, _fn,a1) { \
char top; \
if (stack_overflow(&top, (((gc_thread_data *)data)->stack_limit))) { \
object buf[1]; buf[0] = a1; \
mclosure0(c1, (function_type) _fn); \
GC(td, &c1, buf, 1); \
return; \
} else { \
(_fn)(td, 1, (closure)_fn,a1); \
}}
#define return_direct_with_clo1(td, clo, _fn,a1) { \
char top; \
if (stack_overflow(&top, (((gc_thread_data *)data)->stack_limit))) { \
object buf[1]; buf[0] = a1;\
GC(td, clo, buf, 1); \
return; \
} else { \
(_fn)(td, 1, (closure)(clo),a1); \
}}
#define closcall2(td, clo,a1,a2) \
if (obj_is_not_closure(clo)) { \
Cyc_apply(td, 1, (closure)(a1), clo,a2); \
} else { \
((clo)->fn)(td, 2, clo,a1,a2);\
}
#define return_closcall2(td, clo,a1,a2) { \
char top; \
if (stack_overflow(&top, (((gc_thread_data *)data)->stack_limit))) { \
object buf[2]; buf[0] = a1;buf[1] = a2;\
GC(td, clo, buf, 2); \
return; \
} else {\
closcall2(td, (closure) (clo),a1,a2); \
return;\
} \
}
#define continue_or_gc2(td, clo,a1,a2) { \
char *top = alloca(sizeof(char)); \
if (stack_overflow(top, (((gc_thread_data *)data)->stack_limit))) { \
object buf[2]; buf[0] = a1;buf[1] = a2;\
GC(td, clo, buf, 2); \
return; \
} else {\
continue;\
} \
}
#define return_direct2(td, _fn,a1,a2) { \
char top; \
if (stack_overflow(&top, (((gc_thread_data *)data)->stack_limit))) { \
object buf[2]; buf[0] = a1;buf[1] = a2; \
mclosure0(c1, (function_type) _fn); \
GC(td, &c1, buf, 2); \
return; \
} else { \
(_fn)(td, 2, (closure)_fn,a1,a2); \
}}
#define return_direct_with_clo2(td, clo, _fn,a1,a2) { \
char top; \
if (stack_overflow(&top, (((gc_thread_data *)data)->stack_limit))) { \
object buf[2]; buf[0] = a1;buf[1] = a2;\
GC(td, clo, buf, 2); \
return; \
} else { \
(_fn)(td, 2, (closure)(clo),a1,a2); \
}}
#include "cyclone/types.h"
object __glo_lib_91init_117schemecyclonecommon_scheme_cyclone_common = NULL;
object __glo__85c_91file_91header_91comment_85_scheme_cyclone_common = NULL;
object __glo__85Cyc_91version_91banner_85_scheme_cyclone_common = NULL;
object __glo__85version_91banner_85_scheme_cyclone_common = NULL;
object __glo__85version_85_scheme_cyclone_common = NULL;
object __glo__85version_91name_85_scheme_cyclone_common = NULL;
object __glo__85version_91number_85_scheme_cyclone_common = NULL;
#include "cyclone/runtime.h"
static void __lambda_1(void *data, int argc, closure _,object k_7315) ;
static void __lambda_2(void *data, int argc, object self_7323, object r_7322) ;
static void __lambda_3(void *data, int argc, object self_7324, object r_7321) ;
static void __lambda_4(void *data, int argc, object self_7325, object r_7320) ;
static void __lambda_1(void *data, int argc, closure _,object k_7315) {
Cyc_st_add(data, "scheme/cyclone/common.sld:lib-init:schemecyclonecommon");
closureN_type c_7330;
object e_7359 [1];
c_7330.hdr.mark = gc_color_red;
c_7330.hdr.grayed = 0;
c_7330.tag = closureN_tag;
c_7330.fn = (function_type)__lambda_2;
c_7330.num_args = 1;
c_7330.num_elements = 1;
c_7330.elements = (object *)e_7359;
c_7330.elements[0] = k_7315;
make_utf8_string_with_len(c_7363, " ", 1, 1);
make_utf8_string_with_len(c_7364, "", 0, 0);
object c_7362 = Cyc_string_append(data,(closure)&c_7330,4,__glo__85version_91number_85_scheme_cyclone_common, &c_7363, __glo__85version_91name_85_scheme_cyclone_common, &c_7364);
return_closcall1(data,(closure)&c_7330, c_7362);;
}
static void __lambda_2(void *data, int argc, object self_7323, object r_7322) {
global_set(__glo__85version_85_scheme_cyclone_common, r_7322);
closureN_type c_7333;
object e_7351 [1];
c_7333.hdr.mark = gc_color_red;
c_7333.hdr.grayed = 0;
c_7333.tag = closureN_tag;
c_7333.fn = (function_type)__lambda_3;
c_7333.num_args = 1;
c_7333.num_elements = 1;
c_7333.elements = (object *)e_7351;
c_7333.elements[0] = ((closureN)self_7323)->elements[0];
make_utf8_string_with_len(c_7355, "\n :@ \n @@@ \n @@@@: \n `@@@@@+ \n .@@@+@@@ \n @@ @@ Cyclone Scheme->C compiler\n ,@ http://justinethier.github.io/cyclone/\n '@ \n .@ (c) 2014-2019 Justin Ethier\n @@ #@ Version ", 293, 293);
make_utf8_string_with_len(c_7356, "\n `@@@#@@@.\n #@@@@@ \n +@@@+ \n @@# \n `@. \n \n", 90, 90);
object c_7354 = Cyc_string_append(data,(closure)&c_7333,3,&c_7355, __glo__85version_85_scheme_cyclone_common, &c_7356);
return_closcall1(data,(closure)&c_7333, c_7354);;;
}
static void __lambda_3(void *data, int argc, object self_7324, object r_7321) {
global_set(__glo__85version_91banner_85_scheme_cyclone_common, r_7321);global_set(__glo__85Cyc_91version_91banner_85_scheme_cyclone_common, __glo__85version_91banner_85_scheme_cyclone_common);
closureN_type c_7336;
object e_7341 [1];
c_7336.hdr.mark = gc_color_red;
c_7336.hdr.grayed = 0;
c_7336.tag = closureN_tag;
c_7336.fn = (function_type)__lambda_4;
c_7336.num_args = 1;
c_7336.num_elements = 1;
c_7336.elements = (object *)e_7341;
c_7336.elements[0] = ((closureN)self_7324)->elements[0];
make_utf8_string_with_len(c_7345, "/**\n ** This file was automatically generated by the Cyclone scheme compiler\n ** http://justinethier.github.io/cyclone/\n **\n ** (c) 2014-2019 Justin Ethier\n ** Version ", 168, 168);
make_utf8_string_with_len(c_7346, "\n **\n **/\n", 10, 10);
object c_7344 = Cyc_string_append(data,(closure)&c_7336,3,&c_7345, __glo__85version_85_scheme_cyclone_common, &c_7346);
return_closcall1(data,(closure)&c_7336, c_7344);;;
}
static void __lambda_4(void *data, int argc, object self_7325, object r_7320) {
return_closcall1(data, ((closureN)self_7325)->elements[0], global_set(__glo__85c_91file_91header_91comment_85_scheme_cyclone_common, r_7320));;
}
void c_schemecyclonecommon_inlinable_lambdas(void *data, int argc, closure _, object cont){
(((closure)cont)->fn)(data, 1, cont, NULL);
}
void c_schemecyclonecommon_entry_pt_first_lambda(data, argc, cont,value) void *data; int argc; closure cont; object value;{
Cyc_set_globals_changed((gc_thread_data *)data);
add_global((object *) &__glo_lib_91init_117schemecyclonecommon_scheme_cyclone_common);
add_global((object *) &__glo__85c_91file_91header_91comment_85_scheme_cyclone_common);
add_global((object *) &__glo__85Cyc_91version_91banner_85_scheme_cyclone_common);
add_global((object *) &__glo__85version_91banner_85_scheme_cyclone_common);
add_global((object *) &__glo__85version_85_scheme_cyclone_common);
add_global((object *) &__glo__85version_91name_85_scheme_cyclone_common);
add_global((object *) &__glo__85version_91number_85_scheme_cyclone_common);
mclosure0(c_7328, (function_type)__lambda_1);c_7328.num_args = 0;
__glo_lib_91init_117schemecyclonecommon_scheme_cyclone_common = &c_7328;
__glo__85c_91file_91header_91comment_85_scheme_cyclone_common = boolean_f;
__glo__85Cyc_91version_91banner_85_scheme_cyclone_common = boolean_f;
__glo__85version_91banner_85_scheme_cyclone_common = boolean_f;
__glo__85version_85_scheme_cyclone_common = boolean_f;
make_utf8_string_with_len(c_7327, "", 0, 0);
__glo__85version_91name_85_scheme_cyclone_common = &c_7327;
make_utf8_string_with_len(c_7326, "0.11.6", 6, 6);
__glo__85version_91number_85_scheme_cyclone_common = &c_7326;
mclosure0(clo_7366, c_schemecyclonecommon_inlinable_lambdas); make_pair(pair_7365, find_or_add_symbol("c_schemecyclonecommon_inlinable_lambdas"), &clo_7366);
make_cvar(cvar_7367, (object *)&__glo_lib_91init_117schemecyclonecommon_scheme_cyclone_common);make_pair(pair_7368, find_or_add_symbol("lib-init:schemecyclonecommon"), &cvar_7367);
make_cvar(cvar_7369, (object *)&__glo__85c_91file_91header_91comment_85_scheme_cyclone_common);make_pair(pair_7370, find_or_add_symbol("*c-file-header-comment*"), &cvar_7369);
make_cvar(cvar_7371, (object *)&__glo__85Cyc_91version_91banner_85_scheme_cyclone_common);make_pair(pair_7372, find_or_add_symbol("*Cyc-version-banner*"), &cvar_7371);
make_cvar(cvar_7373, (object *)&__glo__85version_91banner_85_scheme_cyclone_common);make_pair(pair_7374, find_or_add_symbol("*version-banner*"), &cvar_7373);
make_cvar(cvar_7375, (object *)&__glo__85version_85_scheme_cyclone_common);make_pair(pair_7376, find_or_add_symbol("*version*"), &cvar_7375);
make_cvar(cvar_7377, (object *)&__glo__85version_91name_85_scheme_cyclone_common);make_pair(pair_7378, find_or_add_symbol("*version-name*"), &cvar_7377);
make_cvar(cvar_7379, (object *)&__glo__85version_91number_85_scheme_cyclone_common);make_pair(pair_7380, find_or_add_symbol("*version-number*"), &cvar_7379);
make_pair(c_7388, &pair_7365,Cyc_global_variables);
make_pair(c_7387, &pair_7368, &c_7388);
make_pair(c_7386, &pair_7370, &c_7387);
make_pair(c_7385, &pair_7372, &c_7386);
make_pair(c_7384, &pair_7374, &c_7385);
make_pair(c_7383, &pair_7376, &c_7384);
make_pair(c_7382, &pair_7378, &c_7383);
make_pair(c_7381, &pair_7380, &c_7382);
Cyc_global_variables = &c_7381;
cont = ((closure1_type *)cont)->element;
(((closure)__glo_lib_91init_117schemecyclonecommon_scheme_cyclone_common)->fn)(data, 1, cont, cont);
}
void c_schemecyclonecommon_entry_pt(data, argc, cont,value) void *data; int argc; closure cont; object value;{
register_library("scheme_cyclone_common");
c_schemecyclonecommon_entry_pt_first_lambda(data, argc, cont,value);
}
| 41.854839 | 351 | 0.716474 | [
"object"
] |
4e1188b59b2c6b4a869eb6118f29d30fea7bc0f4 | 16,455 | h | C | VirtIO/virtio_pci.h | GoogleCloudPlatform/gce-guest-drivers-windows | 97b6f481cb49a9e9354ee05df7f77802fda9acbd | [
"BSD-3-Clause"
] | 7 | 2015-07-22T17:43:18.000Z | 2021-10-09T16:08:41.000Z | VirtIO/virtio_pci.h | GoogleCloudPlatform/gce-guest-drivers-windows | 97b6f481cb49a9e9354ee05df7f77802fda9acbd | [
"BSD-3-Clause"
] | null | null | null | VirtIO/virtio_pci.h | GoogleCloudPlatform/gce-guest-drivers-windows | 97b6f481cb49a9e9354ee05df7f77802fda9acbd | [
"BSD-3-Clause"
] | 14 | 2016-03-18T18:34:03.000Z | 2021-10-09T16:08:35.000Z | /*
* Virtio PCI driver
*
* This module allows virtio devices to be used over a virtual PCI device.
* This can be used with QEMU based VMMs like KVM or Xen.
*
* Copyright IBM Corp. 2007
*
* Authors:
* Anthony Liguori <aliguori@us.ibm.com>
*
* This header is BSD licensed so anyone can use the definitions to implement
* compatible drivers/servers.
*
* 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 IBM nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS'' AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL IBM OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
* OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
*/
#ifndef _LINUX_VIRTIO_PCI_H
#define _LINUX_VIRTIO_PCI_H
#include "linux/types.h"
#include "linux/virtio_config.h"
#ifndef VIRTIO_PCI_NO_LEGACY
/* A 32-bit r/o bitmask of the features supported by the host */
#define VIRTIO_PCI_HOST_FEATURES 0
/* A 32-bit r/w bitmask of features activated by the guest */
#define VIRTIO_PCI_GUEST_FEATURES 4
/* A 32-bit r/w PFN for the currently selected queue */
#define VIRTIO_PCI_QUEUE_PFN 8
/* A 16-bit r/o queue size for the currently selected queue */
#define VIRTIO_PCI_QUEUE_NUM 12
/* A 16-bit r/w queue selector */
#define VIRTIO_PCI_QUEUE_SEL 14
/* A 16-bit r/w queue notifier */
#define VIRTIO_PCI_QUEUE_NOTIFY 16
/* An 8-bit device status register. */
#define VIRTIO_PCI_STATUS 18
/* An 8-bit r/o interrupt status register. Reading the value will return the
* current contents of the ISR and will also clear it. This is effectively
* a read-and-acknowledge. */
#define VIRTIO_PCI_ISR 19
/* MSI-X registers: only enabled if MSI-X is enabled. */
/* A 16-bit vector for configuration changes. */
#define VIRTIO_MSI_CONFIG_VECTOR 20
/* A 16-bit vector for selected queue notifications. */
#define VIRTIO_MSI_QUEUE_VECTOR 22
/* The remaining space is defined by each driver as the per-driver
* configuration space */
#define VIRTIO_PCI_CONFIG_OFF(msix_enabled) ((msix_enabled) ? 24 : 20)
/* Deprecated: please use VIRTIO_PCI_CONFIG_OFF instead */
#define VIRTIO_PCI_CONFIG(msix_enabled) VIRTIO_PCI_CONFIG_OFF(msix_enabled)
/* How many bits to shift physical queue address written to QUEUE_PFN.
* 12 is historical, and due to x86 page size. */
#define VIRTIO_PCI_QUEUE_ADDR_SHIFT 12
/* The alignment to use between consumer and producer parts of vring.
* x86 pagesize again. */
#define VIRTIO_PCI_VRING_ALIGN 4096
#endif /* VIRTIO_PCI_NO_LEGACY */
/* The bit of the ISR which indicates a device configuration change. */
#define VIRTIO_PCI_ISR_CONFIG 0x2
/* Vector value used to disable MSI for queue */
#define VIRTIO_MSI_NO_VECTOR 0xffff
/* IDs for different capabilities. Must all exist. */
/* Common configuration */
#define VIRTIO_PCI_CAP_COMMON_CFG 1
/* Notifications */
#define VIRTIO_PCI_CAP_NOTIFY_CFG 2
/* ISR access */
#define VIRTIO_PCI_CAP_ISR_CFG 3
/* Device specific configuration */
#define VIRTIO_PCI_CAP_DEVICE_CFG 4
/* PCI configuration access */
#define VIRTIO_PCI_CAP_PCI_CFG 5
/* This is the PCI capability header: */
struct virtio_pci_cap {
__u8 cap_vndr; /* Generic PCI field: PCI_CAPABILITY_ID_VENDOR_SPECIFIC */
__u8 cap_next; /* Generic PCI field: next ptr. */
__u8 cap_len; /* Generic PCI field: capability length */
__u8 cfg_type; /* Identifies the structure. */
__u8 bar; /* Where to find it. */
__u8 padding[3]; /* Pad to full dword. */
__le32 offset; /* Offset within bar. */
__le32 length; /* Length of the structure, in bytes. */
};
struct virtio_pci_notify_cap {
struct virtio_pci_cap cap;
__le32 notify_off_multiplier; /* Multiplier for queue_notify_off. */
};
/* Fields in VIRTIO_PCI_CAP_COMMON_CFG: */
struct virtio_pci_common_cfg {
/* About the whole device. */
__le32 device_feature_select; /* read-write */
__le32 device_feature; /* read-only */
__le32 guest_feature_select; /* read-write */
__le32 guest_feature; /* read-write */
__le16 msix_config; /* read-write */
__le16 num_queues; /* read-only */
__u8 device_status; /* read-write */
__u8 config_generation; /* read-only */
/* About a specific virtqueue. */
__le16 queue_select; /* read-write */
__le16 queue_size; /* read-write, power of 2. */
__le16 queue_msix_vector; /* read-write */
__le16 queue_enable; /* read-write */
__le16 queue_notify_off; /* read-only */
__le32 queue_desc_lo; /* read-write */
__le32 queue_desc_hi; /* read-write */
__le32 queue_avail_lo; /* read-write */
__le32 queue_avail_hi; /* read-write */
__le32 queue_used_lo; /* read-write */
__le32 queue_used_hi; /* read-write */
};
#define MAX_QUEUES_PER_DEVICE_DEFAULT 8
typedef struct virtio_queue_info
{
/* the actual virtqueue */
struct virtqueue *vq;
/* the number of entries in the queue */
u16 num;
/* the virtual address of the ring queue */
void *queue;
} VirtIOQueueInfo;
typedef struct virtio_system_ops {
// device register access
u8 (*vdev_read_byte)(ULONG_PTR ulRegister);
u16 (*vdev_read_word)(ULONG_PTR ulRegister);
u32 (*vdev_read_dword)(ULONG_PTR ulRegister);
void (*vdev_write_byte)(ULONG_PTR ulRegister, u8 bValue);
void (*vdev_write_word)(ULONG_PTR ulRegister, u16 wValue);
void (*vdev_write_dword)(ULONG_PTR ulRegister, u32 ulValue);
// memory management
void *(*mem_alloc_contiguous_pages)(void *context, size_t size);
void (*mem_free_contiguous_pages)(void *context, void *virt);
ULONGLONG (*mem_get_physical_address)(void *context, void *virt);
void *(*mem_alloc_nonpaged_block)(void *context, size_t size);
void (*mem_free_nonpaged_block)(void *context, void *addr);
// PCI config space access
int (*pci_read_config_byte)(void *context, int where, u8 *bVal);
int (*pci_read_config_word)(void *context, int where, u16 *wVal);
int (*pci_read_config_dword)(void *context, int where, u32 *dwVal);
// PCI resource handling
size_t (*pci_get_resource_len)(void *context, int bar);
void *(*pci_map_address_range)(void *context, int bar, size_t offset, size_t maxlen);
// misc
u16 (*vdev_get_msix_vector)(void *context, int queue);
void (*vdev_sleep)(void *context, unsigned int msecs);
} VirtIOSystemOps;
struct virtio_device;
typedef struct virtio_device VirtIODevice;
struct virtio_device_ops
{
// read/write device config and read config generation counter
void (*get_config)(VirtIODevice *vdev, unsigned offset, void *buf, unsigned len);
void (*set_config)(VirtIODevice *vdev, unsigned offset, const void *buf, unsigned len);
u32 (*get_config_generation)(VirtIODevice *vdev);
// read/write device status byte and reset the device
u8 (*get_status)(VirtIODevice *vdev);
void (*set_status)(VirtIODevice *vdev, u8 status);
void (*reset)(VirtIODevice *vdev);
// get/set device feature bits
u64 (*get_features)(VirtIODevice *vdev);
NTSTATUS (*set_features)(VirtIODevice *vdev, u64 features);
// set config/queue MSI interrupt vector, returns the new vector
u16 (*set_config_vector)(VirtIODevice *vdev, u16 vector);
u16 (*set_queue_vector)(struct virtqueue *vq, u16 vector);
// set max queue num.
NTSTATUS (*set_max_queue_num)(VirtIODevice *vdev, unsigned index,
unsigned short max_queue_num);
// query virtual queue size and memory requirements
NTSTATUS (*query_queue_alloc)(VirtIODevice *vdev,
unsigned index, unsigned short *pNumEntries,
unsigned long *pRingSize,
unsigned long *pHeapSize);
// allocate and initialize a queue
NTSTATUS (*setup_queue)(struct virtqueue **queue,
VirtIODevice *vdev, VirtIOQueueInfo *info,
unsigned idx, u16 msix_vec);
// tear down and deallocate a queue
void (*delete_queue)(VirtIOQueueInfo *info);
};
struct virtio_device
{
// the I/O port BAR of the PCI device (legacy virtio devices only)
ULONG_PTR addr;
// true if the device uses MSI interrupts
bool msix_used;
// true if the VIRTIO_RING_F_EVENT_IDX feature flag has been negotiated
bool event_suppression_enabled;
// internal device operations, implemented separately for legacy and modern
const struct virtio_device_ops *device;
// external callbacks implemented separately by different driver model drivers
const struct virtio_system_ops *system;
// opaque context value passed as first argument to virtio_system_ops callbacks
void *DeviceContext;
// the ISR status field, reading causes the device to de-assert an interrupt
volatile u8 *isr;
// modern virtio device capabilities and related state
volatile struct virtio_pci_common_cfg *common;
volatile unsigned char *config;
volatile unsigned char *notify_base;
int notify_map_cap;
u32 notify_offset_multiplier;
size_t config_len;
size_t notify_len;
// maximum number of virtqueues that fit in the memory block pointed to by info
ULONG maxQueues;
// points to inline_info if not more than MAX_QUEUES_PER_DEVICE_DEFAULT queues
// are used, or to an external allocation otherwise
VirtIOQueueInfo *info;
VirtIOQueueInfo inline_info[MAX_QUEUES_PER_DEVICE_DEFAULT];
};
/* Driver API: device init and shutdown
* DeviceContext is a driver defined opaque value which will be passed to driver
* supplied callbacks described in pSystemOps. pSystemOps must be non-NULL and all
* its fields must be non-NULL. msix_used is true if and only if the device is
* configured with MSI support.
*/
NTSTATUS virtio_device_initialize(VirtIODevice *vdev,
const VirtIOSystemOps *pSystemOps,
void *DeviceContext,
bool msix_used);
void virtio_device_shutdown(VirtIODevice *vdev);
/* Driver API: device status manipulation
* virtio_set_status should not be called by new drivers. Device status should only
* be getting its bits set with virtio_add_status and reset all back to 0 with
* virtio_device_reset. virtio_device_ready is a special version of virtio_add_status
* which adds the VIRTIO_CONFIG_S_DRIVER_OK status bit.
*/
u8 virtio_get_status(VirtIODevice *vdev);
void virtio_set_status(VirtIODevice *vdev, u8 status);
void virtio_add_status(VirtIODevice *vdev, u8 status);
void virtio_device_reset(VirtIODevice *vdev);
void virtio_device_ready(VirtIODevice *vdev);
/* Driver API: device feature bitmap manipulation
* Features passed to virtio_set_features should be a subset of features offered by
* the device as returned from virtio_get_features. virtio_set_features sets the
* VIRTIO_CONFIG_S_FEATURES_OK status bit if it is supported by the device.
*/
#define virtio_is_feature_enabled(FeaturesList, Feature) (!!((FeaturesList) & (1ULL << (Feature))))
#define virtio_feature_enable(FeaturesList, Feature) ((FeaturesList) |= (1ULL << (Feature)))
#define virtio_feature_disable(FeaturesList, Feature) ((FeaturesList) &= ~(1ULL << (Feature)))
u64 virtio_get_features(VirtIODevice *dev);
NTSTATUS virtio_set_features(VirtIODevice *vdev, u64 features);
/* Driver API: device configuration access
* Both virtio_get_config and virtio_set_config support arbitrary values of the len
* parameter. Config items of length 1, 2, and 4 are read/written using one access,
* length 8 is broken down to two 4 bytes accesses, and any other length is read or
* written byte by byte.
*/
void virtio_get_config(VirtIODevice *vdev, unsigned offset,
void *buf, unsigned len);
void virtio_set_config(VirtIODevice *vdev, unsigned offset,
void *buf, unsigned len);
/* Driver API: virtqueue setup
* virtio_reserve_queue_memory makes VirtioLib reserve memory for its virtqueue
* bookkeeping. Drivers should call this function if they intend to set up queues
* one by one with virtio_find_queue. virtio_find_queues (plural) internally takes
* care of the reservation and virtio_reserve_queue_memory need not be called.
* Note that in addition to queue interrupt vectors, virtio_find_queues also sets
* up the device config vector as a convenience.
* Drivers should treat the returned struct virtqueue pointers as opaque handles.
*/
NTSTATUS virtio_query_queue_allocation(VirtIODevice *vdev, unsigned index,
unsigned short *pNumEntries,
unsigned long *pRingSize,
unsigned long *pHeapSize);
/* Driver API: set the max queue num.
* Function will read VIRTIO_PCI_QUEUE_NUM for queues[index] and if the
* QUEUE_NUM if larger than max_queue_num, set max_queue_num to device config.
*/
NTSTATUS virtio_set_max_queue_num(VirtIODevice *vdev, unsigned index,
unsigned short max_queue_num);
NTSTATUS virtio_reserve_queue_memory(VirtIODevice *vdev, unsigned nvqs);
NTSTATUS virtio_find_queue(VirtIODevice *vdev, unsigned index,
struct virtqueue **vq);
NTSTATUS virtio_find_queues(VirtIODevice *vdev, unsigned nvqs,
struct virtqueue *vqs[]);
/* Driver API: virtqueue shutdown
* The device must be reset and re-initialized to re-setup queues after they have
* been deleted.
*/
void virtio_delete_queue(struct virtqueue *vq);
void virtio_delete_queues(VirtIODevice *vdev);
/* Driver API: virtqueue query and manipulation
* virtio_get_queue_descriptor_size
* is useful in situations where the driver has to prepare for the memory allocation
* performed by virtio_reserve_queue_memory beforehand.
*/
u32 virtio_get_queue_size(struct virtqueue *vq);
unsigned long virtio_get_indirect_page_capacity();
ULONG __inline virtio_get_queue_descriptor_size()
{
return sizeof(VirtIOQueueInfo);
}
/* Driver API: interrupt handling
* virtio_set_config_vector and virtio_set_queue_vector set the MSI vector used for
* device configuration interrupt and queue interrupt, respectively. The driver may
* choose to either return the vector from the vdev_get_msix_vector callback (called
* as part of queue setup) or call these functions later. Note that setting the vector
* may fail which is indicated by the return value of VIRTIO_MSI_NO_VECTOR.
* virtio_read_isr_status returns the value of the ISR status register, note that it
* is not idempotent, calling the function makes the device de-assert the interrupt.
*/
u16 virtio_set_config_vector(VirtIODevice *vdev, u16 vector);
u16 virtio_set_queue_vector(struct virtqueue *vq, u16 vector);
u8 virtio_read_isr_status(VirtIODevice *vdev);
/* Driver API: miscellaneous helpers
* virtio_get_bar_index returns the corresponding BAR index given its physical address.
* This tends to be useful to all drivers since Windows doesn't provide reliable BAR
* indices as part of resource enumeration. The function returns -1 on failure.
*/
int virtio_get_bar_index(PPCI_COMMON_HEADER pPCIHeader, PHYSICAL_ADDRESS BasePA);
#endif
| 41.034913 | 100 | 0.726101 | [
"vector",
"model"
] |
4e158dd53b8fb98561d28a92def21d15c278fa71 | 2,994 | h | C | pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_aguila/com_fileformatinfo.h | quanpands/wflow | b454a55e4a63556eaac3fbabd97f8a0b80901e5a | [
"MIT"
] | null | null | null | pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_aguila/com_fileformatinfo.h | quanpands/wflow | b454a55e4a63556eaac3fbabd97f8a0b80901e5a | [
"MIT"
] | null | null | null | pcraster/pcraster-4.2.0/pcraster-4.2.0/source/pcraster_aguila/com_fileformatinfo.h | quanpands/wflow | b454a55e4a63556eaac3fbabd97f8a0b80901e5a | [
"MIT"
] | null | null | null | #ifndef INCLUDED_COM_FILEFORMATINFO
#define INCLUDED_COM_FILEFORMATINFO
// Library headers.
#include <string>
#include <vector>
// PCRaster library headers.
// Module headers.
namespace com {
// FileFormatInfo declarations.
}
namespace com {
//! The FileFormatInfo class if for information about file formats(!).
/*!
Each file format has specific information like default extension, description
and so on. This stuff is handled by this class.
\todo
add default basename for saving method/ctor
\todo Merge this class with dal::Format and remove usage of this class from
all code. dal::Format is more general.
*/
class FileFormatInfo
{
private:
//! Description.
std::string d_description;
//! Default extensions.
std::vector<std::string> d_extensions;
public:
//----------------------------------------------------------------------------
// CREATORS
//----------------------------------------------------------------------------
FileFormatInfo (const std::string& description,
const std::string& extensions);
FileFormatInfo (std::string const& description,
std::vector<std::string> const& extensions);
virtual ~FileFormatInfo ();
//----------------------------------------------------------------------------
// MANIPULATORS
//----------------------------------------------------------------------------
//----------------------------------------------------------------------------
// ACCESSORS
//----------------------------------------------------------------------------
bool equals (const FileFormatInfo& formatInfo) const;
const std::string& description () const;
const std::string& extension () const;
const std::vector<std::string>& extensions() const;
// bool matchesExtension(const std::string& extension) const;
static FileFormatInfo eps();
static FileFormatInfo png();
static FileFormatInfo csf();
static FileFormatInfo pcr();
};
//------------------------------------------------------------------------------
// INLINE FUNCIONS
//------------------------------------------------------------------------------
//------------------------------------------------------------------------------
// FREE OPERATORS
//------------------------------------------------------------------------------
bool operator== (const FileFormatInfo& lhs,
const FileFormatInfo& rhs);
bool operator!= (const FileFormatInfo& lhs,
const FileFormatInfo& rhs);
//------------------------------------------------------------------------------
// FREE FUNCTIONS
//------------------------------------------------------------------------------
} // namespace com
#endif
| 25.810345 | 84 | 0.408818 | [
"vector"
] |
4e1cf09b7fa766e01ef03f81634da89b195e2ca3 | 10,358 | h | C | include/concurrent_linked_list.h | jsukha/nabbit | 901ccf675505c099485a8568e4783a99783faf86 | [
"BSD-3-Clause"
] | 4 | 2019-06-22T04:09:44.000Z | 2020-01-04T03:43:23.000Z | include/concurrent_linked_list.h | jsukha/nabbit | 901ccf675505c099485a8568e4783a99783faf86 | [
"BSD-3-Clause"
] | 1 | 2019-07-11T00:55:12.000Z | 2019-07-16T19:47:13.000Z | include/concurrent_linked_list.h | jsukha/nabbit | 901ccf675505c099485a8568e4783a99783faf86 | [
"BSD-3-Clause"
] | 1 | 2017-01-07T00:46:02.000Z | 2017-01-07T00:46:02.000Z | /* concurrent_linked_list.h -*-C++-*-
*
*************************************************************************
*
* Copyright (c) 2010, Jim Sukha
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the authors nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS
* OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
* AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY
* WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef __CONCURRENT_LINKED_LIST_H
#define __CONCURRENT_LINKED_LIST_H
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include "nabbit_sysdep.h"
/*************************************************
* Implementing a simple concurrent linked list.
*
* The implementation is geared to support insert_if_absent
* efficiently; a concurrent delete is not implemented.
*
*************************************************/
// Possible status for a node.
typedef enum { UNINITIALIZED=0, DUMMY=1, INVALID = 4, VALID = 16, DEAD = 64 } LNodeStatus;
// Possible status values that can be returned
// for an operation.
typedef enum { OP_NULL = 0,
OP_FOUND = 1,
OP_NOT_FOUND=2,
OP_FAILED = 3,
OP_INSERTED = 4,
OP_DELETED = 5,
OP_ERROR = 6,
OP_LAST = 7 } LOpStatus;
// A node
struct ListNode {
long long hashkey;
ListNode* next;
LNodeStatus status;
void* value;
ListNode() :
hashkey(0), next(NULL), status(DUMMY), value(NULL) { }
ListNode(long long k) :
hashkey(k), next(NULL), status(INVALID), value(NULL) { }
ListNode(long long k, void* val) :
hashkey(k), next(NULL), status(VALID), value(val) { }
ListNode(long long k, void* val, ListNode* nxt) :
hashkey(k), next(nxt), status(VALID), value(val) { }
};
class ConcurrentLinkedList
{
private:
ListNode* head;
long long size_estimate;
// This field is a cache which is an (approximate) count of the
// number of elements in the list. The increment of this count
// is not done atomically, so it may be incorrect.
void delete_list_helper(ListNode* current) {
ListNode* rest = NULL;
if (current != NULL) {
bool have_rest = false;
if (current->next != NULL) {
rest = current->next;
have_rest = true;
}
delete current;
if (have_rest) {
delete_list_helper(rest);
}
}
}
public:
ConcurrentLinkedList() : size_estimate(0) {
head = new ListNode();
assert(head != NULL);
head->status = DUMMY;
head->hashkey = 0;
}
~ConcurrentLinkedList() {
delete_list_helper(head);
}
ListNode* get_list_head() {
if (head != NULL) {
return head->next;
}
return NULL;
}
void print_node(ListNode* node) {
if (node != NULL) {
printf("(%p: k=%lld, val=%p, stat=%d)",
node,
node->hashkey,
node->value,
node->status);
} else {
printf("(%p: null)",
node);
}
}
void print_list() {
ListNode* current = head->next;
printf("***********************\n");
printf("**** List %p, Size=%lld: ",
head,
size_estimate);
while (current != NULL) {
print_node(current);
printf("\n");
current = current->next;
}
printf("***********************\n");
printf("\n");
}
void update_size_estimate() {
int updated_estimate = 0;
ListNode* current = head->next;
while (current != NULL) {
updated_estimate++;
current = current->next;
}
this->size_estimate = updated_estimate;
}
long long get_size_estimate(void) {
return size_estimate;
}
void* search(long long k,
LOpStatus* status) {
int retry_count = 0;
while (retry_count < 10) {
volatile ListNode* temp_first = head->next;
ListNode* target = NULL;
// Where we store the pointer to the linked list node containing
// the value we are going to return.
ListNode* current = head->next;
// Pointer used when traversing the list.
while ((current != NULL) &&
(target == NULL)) {
if ((current->hashkey == k)
&& (current->status != DEAD)) {
target = current;
}
current = current->next;
}
if (target) {
*status = OP_FOUND;
return target->value;
}
// If the head of the list is still the same, assume that the
// element is not there.
if (temp_first == head->next) {
*status = OP_NOT_FOUND;
return NULL;
}
retry_count++;
}
*status = OP_FAILED;
return NULL;
}
/**
* Attempts to atomically insert a key value pair (k, val) into the
* linked list. The "status" argument should be a pointer to the
* location where the output code of the operation gets stored.
*
* This method can have 3 possible return codes.
*
* 1. OP_FOUND: A value for that key is already in the hash table.
* In this case, we return the "value" field of the
* element already in the table.
* 2. OP_INSERTED: A value for this key was not found.
* Create a new node with key value pair (k, val).
* Method returns "val".
* 3. OP_FAILED: The operation failed too many times because of
* contention. Returns NULL.
*/
void* insert_if_absent(long long k,
void* val,
LOpStatus* status) {
int retry_count = 10;
ListNode* temp_node = NULL;
while (retry_count > 0) {
ListNode* target = NULL;
// Where we store the pointer to the linked list node containing
// the value we are going to return.
ListNode* temp_first = head->next;
// Remembers the head of the list.
ListNode* current = head->next;
// Pointer used when traversing the list.
while ((current != NULL) &&
(target == NULL)) {
if ((current->hashkey == k)
&& (current->status != DEAD)) {
target = current;
}
current = current->next;
}
if (target) {
*status = OP_FOUND;
return target->value;
}
else {
// Allocate a new node object to insert.
if (temp_node == NULL) {
temp_node = new ListNode(k, val);
assert(temp_node != NULL);
}
temp_node->next = head->next;
// Check to make sure the first element in the list is still
// the same as the head we knew about originally. If it has
// changed, then we have already failed.
// Otherwise, we will try to CAS the old head of the list
// to the new temp node.
// Check without CAS.
if (temp_node->next == temp_first) {
// The CAS operation:
// Abstractly, this performs the assignment,
// "this->head->next = temp_node"
// assuming the head of the list doesn't change.
// The prototype for gcc's builtin CAS:
// type __sync_val_compare_and_swap (type *ptr, type oldval type newval, ...)
bool valid = false;
valid = nabbit::ptr_CAS(&this->head->next,
temp_first,
temp_node);
if (valid) {
// There is a race condition here...
// That's why it is an estimate.
this->size_estimate++;
*status = OP_INSERTED;
return temp_node->value;
}
}
}
retry_count--;
}
*status = OP_FAILED;
return NULL;
}
// Takes the current list, copies the keys of nodes in the list into
// a newly allocated array, and returns a pointer to the array.
//
// After execution, "final_size" stores the number of elements in
// the array.
long long* get_keys(int* final_size) {
int n = 0;
long long* a = NULL;
ListNode* current = this->head;
while (current->next != NULL) {
n++;
current = current->next;
}
// printf("List has %d elements\n", n);
if ( n > 0) {
a = new long long[n];
assert(a != NULL);
current = this->head;
int i = 0;
while (current->next != NULL) {
current = current->next;
a[i] = current->hashkey;
i++;
}
// printf("Array: ");
// for (i = 0; i < n; i++) {
// printf("%d ", a[i]);
// }
*final_size = n;
}
return a;
}
// Same as get_keys, except it only takes up to n
// elements.
void get_n_keys(long long* a,
long long n,
long long* final_size) {
long long k = 0;
ListNode* current = this->head;
while ((current->next != NULL) && (k < n)){
current = current->next;
a[k] = current->hashkey;
k++;
}
*final_size = k;
}
// Same as get_keys, only returns the values instead.
void** get_values(int* final_size) {
int n = 0;
void** a = NULL;
ListNode* current = this->head;
while (current->next != NULL) {
n++;
current = current->next;
}
if ( n > 0) {
a = new void* [n];
current = this->head;
int i = 0;
while (current->next != NULL) {
current = current->next;
a[i] = current->value;
i++;
}
*final_size = n;
}
return a;
}
};
#endif // __CONCURRENT_LINKED_LIST_H
| 25.325183 | 90 | 0.589013 | [
"object"
] |
4e23013e7741d4fc1b4d382688ba7de4163defb2 | 6,692 | h | C | PlugIns/BSPSceneManager/include/OgreQuake3Level.h | dawlane/ogre | 7bae21738c99b117ef2eab3fcb1412891b8c2025 | [
"MIT"
] | 2,937 | 2016-02-05T14:26:54.000Z | 2022-03-31T14:53:11.000Z | PlugIns/BSPSceneManager/include/OgreQuake3Level.h | Mu-L/ogre | 61af1367ae6a84788e205955541355176e93953c | [
"MIT"
] | 916 | 2016-01-05T23:41:21.000Z | 2022-03-26T17:40:31.000Z | PlugIns/BSPSceneManager/include/OgreQuake3Level.h | Mu-L/ogre | 61af1367ae6a84788e205955541355176e93953c | [
"MIT"
] | 976 | 2015-12-30T13:14:27.000Z | 2022-03-31T09:21:07.000Z | /*
-----------------------------------------------------------------------------
This source file is part of OGRE
(Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/
Copyright (c) 2000-2014 Torus Knot Software Ltd
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 __Quake3Level_H__
#define __Quake3Level_H__
#include "OgreBspPrerequisites.h"
#include "OgreQuake3Types.h"
#include "OgreDataStream.h"
namespace Ogre {
/** \addtogroup Plugins
* @{
*/
/** \addtogroup BSPSceneManager
* @{
*/
/** Support for loading and extracting data from a Quake3 level file.
This class implements the required methods for opening Quake3 level files
and extracting the pertinent data within. Ogre supports BSP based levels
through it's own BspLevel class, which is not specific to any file format,
so this class is here to source that data from the Quake3 format.
Quake3 levels include far more than just data for rendering - typically the
<strong>leaves</strong> of the tree are used for rendering, and <strong>brushes,</strong>
are used to define convex hulls made of planes for collision detection. There are also
<strong>entities</strong> which define non-visual elements like player start
points, triggers etc and <strong>models</strong> which are used for movable
scenery like doors and platforms. <strong>Shaders</strong> meanwhile are textures
with extra effects and 'content flags' indicating special properties like
water or lava.
I will try to support as much of this as I can in Ogre, but I won't duplicate
the structure or necessarily use the same terminology. Quake3 is designed for a very specific
purpose and code structure, whereas Ogre is designed to be more flexible,
so for example I'm likely to separate game-related properties like surface flags
from the generics of materials in my implementation.
This is a utility class only - a single call to loadFromChunk should be
enough. You should not expect the state of this object to be consistent
between calls, since it uses pointers to memory which may no longer
be valid after the original call. This is why it has no accessor methods
for reading it's internal state.
*/
class Quake3Level : public ResourceAlloc
{
public:
Quake3Level();
/** Load just the header information from a Quake3 file.
@remarks
This method loads just the header information from the
Quake3 file, in order to estimate the loading time.
*/
void loadHeaderFromStream(DataStreamPtr& inStream);
/** Reads Quake3 bsp data from a stream as read from the file.
Since ResourceManagers generally locate data in a variety of
places they typically manipulate them as a chunk of data, rather than
a file pointer since this is unsupported through compressed archives.
Quake3 files are made up of a header (which contains version info and
a table of the contents) and 17 'lumps' i.e. sections of data,
the offsets to which are kept in the table of contents. The 17 types
are predefined (You can find them in OgreQuake3Types.h)
@param inStream Stream containing Quake3 data
*/
void loadFromStream(const DataStreamPtr& inStream);
/* Extracts the embedded lightmap texture data and loads them as textures.
Calling this method makes the lightmap texture data embedded in
the .bsp file available to the renderer. Lightmaps are extracted
and loaded as Texture objects (subclass specific to RenderSystem
subclass) and are named "@lightmap1", "@lightmap2" etc.
*/
void extractLightmaps(void) const;
/** Utility function read the header and set up pointers. */
void initialise(bool headerOnly = false);
/** Utility function read the header and set up counters. */
void initialiseCounts(void);
/** Utility function read the header and set up pointers. */
void initialisePointers(void);
/** Utility function to return a pointer to a lump. */
void* getLump(int lumpType);
int getLumpSize(int lumpType);
/** Debug method. */
void dumpContents(void);
// Internal storage
// This is ALL temporary. Don't rely on it being static
MemoryDataStreamPtr mChunk;
// NB no brushes, fog or local lightvolumes yet
bsp_header_t* mHeader;
unsigned char* mLumpStart;
int* mElements; // vertex indexes for faces
int mNumElements;
void* mEntities;
int mNumEntities;
bsp_model_t* mModels;
int mNumModels;
bsp_node_t* mNodes;
int mNumNodes;
bsp_leaf_t* mLeaves;
int mNumLeaves;
int* mLeafFaces; // Indexes to face groups by leaf
int mNumLeafFaces;
bsp_plane_t* mPlanes;
int mNumPlanes;
bsp_face_t* mFaces; // Groups of faces
int mNumFaces;
bsp_vertex_t* mVertices;
int mNumVertices;
bsp_shader_t* mShaders;
int mNumShaders;
unsigned char* mLightmaps;
int mNumLightmaps;
bsp_vis_t* mVis;
bsp_brush_t* mBrushes;
int mNumBrushes;
bsp_brushside_t* mBrushSides;
int mNumBrushSides;
int* mLeafBrushes; // Groups of indexes to brushes by leaf
int mNumLeafBrushes;
};
/** @} */
/** @} */
}
#endif
| 38.24 | 97 | 0.674985 | [
"object"
] |
4e2709580bef25be6be88bf7d510f5c4fef03eac | 9,977 | h | C | ThreeDScanner-iOS/Libraries/PCL/include/pcl-1.8/pcl/features/rops_estimation.h | anwholesquare/3DScanr | 335b6fa47a86b7c121e26ad2cbde342340ec855b | [
"MIT"
] | 170 | 2016-02-01T18:58:50.000Z | 2022-03-17T05:28:01.000Z | ThreeDScanner-iOS/Libraries/PCL/include/pcl-1.8/pcl/features/rops_estimation.h | anwholesquare/3DScanr | 335b6fa47a86b7c121e26ad2cbde342340ec855b | [
"MIT"
] | 162 | 2016-01-29T17:04:29.000Z | 2022-02-10T16:25:37.000Z | ThreeDScanner-iOS/Libraries/PCL/include/pcl-1.8/pcl/features/rops_estimation.h | anwholesquare/3DScanr | 335b6fa47a86b7c121e26ad2cbde342340ec855b | [
"MIT"
] | 83 | 2016-01-28T22:49:01.000Z | 2022-03-28T03:11:24.000Z | /*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage, Inc. nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* Author : Sergey Ushakov
* Email : sergey.s.ushakov@mail.ru
*
*/
#ifndef PCL_ROPS_ESIMATION_H_
#define PCL_ROPS_ESIMATION_H_
#include <pcl/PolygonMesh.h>
#include <pcl/features/feature.h>
#include <set>
namespace pcl
{
/** \brief
* This class implements the method for extracting RoPS features presented in the article
* "Rotational Projection Statistics for 3D Local Surface Description and Object Recognition" by
* Yulan Guo, Ferdous Sohel, Mohammed Bennamoun, Min Lu and Jianwei Wan.
*/
template <typename PointInT, typename PointOutT>
class PCL_EXPORTS ROPSEstimation : public pcl::Feature <PointInT, PointOutT>
{
public:
using Feature <PointInT, PointOutT>::input_;
using Feature <PointInT, PointOutT>::indices_;
using Feature <PointInT, PointOutT>::surface_;
using Feature <PointInT, PointOutT>::tree_;
typedef typename pcl::Feature <PointInT, PointOutT>::PointCloudOut PointCloudOut;
typedef typename pcl::Feature <PointInT, PointOutT>::PointCloudIn PointCloudIn;
public:
/** \brief Simple constructor. */
ROPSEstimation ();
/** \brief Virtual destructor. */
virtual
~ROPSEstimation ();
/** \brief Allows to set the number of partition bins that is used for distribution matrix calculation.
* \param[in] number_of_bins number of partition bins
*/
void
setNumberOfPartitionBins (unsigned int number_of_bins);
/** \brief Returns the nmber of partition bins. */
unsigned int
getNumberOfPartitionBins () const;
/** \brief This method sets the number of rotations.
* \param[in] number_of_rotations number of rotations
*/
void
setNumberOfRotations (unsigned int number_of_rotations);
/** \brief returns the number of rotations. */
unsigned int
getNumberOfRotations () const;
/** \brief Allows to set the support radius that is used to crop the local surface of the point.
* \param[in] support_radius support radius
*/
void
setSupportRadius (float support_radius);
/** \brief Returns the support radius. */
float
getSupportRadius () const;
/** \brief This method sets the triangles of the mesh.
* \param[in] triangles list of triangles of the mesh
*/
void
setTriangles (const std::vector <pcl::Vertices>& triangles);
/** \brief Returns the triangles of the mesh.
* \param[out] triangles triangles of tthe mesh
*/
void
getTriangles (std::vector <pcl::Vertices>& triangles) const;
private:
/** \brief Abstract feature estimation method.
* \param[out] output the resultant features
*/
virtual void
computeFeature (PointCloudOut& output);
/** \brief This method simply builds the list of triangles for every point.
* The list of triangles for each point consists of indices of triangles it belongs to.
* The only purpose of this method is to improve perfomance of the algorithm.
*/
void
buildListOfPointsTriangles ();
/** \brief This method crops all the triangles within the given radius of the given point.
* \param[in] point point for which the local surface is computed
* \param[out] local_triangles strores the indices of the triangles that belong to the local surface
* \param[out] local_points stores the indices of the points that belong to the local surface
*/
void
getLocalSurface (const PointInT& point, std::set <unsigned int>& local_triangles, std::vector <int>& local_points) const;
/** \brief This method computes LRF (Local Reference Frame) matrix for the given point.
* \param[in] point point for which the LRF is computed
* \param[in] local_triangles list of triangles that represents the local surface of the point
* \paran[out] lrf_matrix strores computed LRF matrix for the given point
*/
void
computeLRF (const PointInT& point, const std::set <unsigned int>& local_triangles, Eigen::Matrix3f& lrf_matrix) const;
/** \brief This method calculates the eigen values and eigen vectors
* for the given covariance matrix. Note that it returns normalized eigen
* vectors that always form the right-handed coordinate system.
* \param[in] matrix covariance matrix of the cloud
* \param[out] major_axis eigen vector which corresponds to a major eigen value
* \param[out] middle_axis eigen vector which corresponds to a middle eigen value
* \param[out] minor_axis eigen vector which corresponds to a minor eigen value
*/
void
computeEigenVectors (const Eigen::Matrix3f& matrix, Eigen::Vector3f& major_axis, Eigen::Vector3f& middle_axis,
Eigen::Vector3f& minor_axis) const;
/** \brief This method translates the cloud so that the given point becomes the origin.
* After that the cloud is rotated with the help of the given matrix.
* \param[in] point point which stores the translation information
* \param[in] matrix rotation matrix
* \param[in] local_points point to transform
* \param[out] transformed_cloud stores the transformed cloud
*/
void
transformCloud (const PointInT& point, const Eigen::Matrix3f& matrix, const std::vector <int>& local_points, PointCloudIn& transformed_cloud) const;
/** \brief This method rotates the cloud around the given axis and computes AABB of the rotated cloud.
* \param[in] axis axis around which cloud must be rotated
* \param[in] angle angle in degrees
* \param[in] cloud cloud to rotate
* \param[out] rotated_cloud stores the rotated cloud
* \param[out] min stores the min point of the AABB
* \param[out] max stores the max point of the AABB
*/
void
rotateCloud (const PointInT& axis, const float angle, const PointCloudIn& cloud, PointCloudIn& rotated_cloud,
Eigen::Vector3f& min, Eigen::Vector3f& max) const;
/** \brief This method projects the local surface onto the XY, XZ or YZ plane
* and computes the distribution matrix.
* \param[in] projection represents the case of projection. 1 - XY, 2 - XZ, 3 - YZ
* \param[in] min min point of the AABB
* \param[in] max max point of the AABB
* \param[in] cloud cloud containing the points of the local surface
* \param[out] matrix stores computed distribution matrix
*/
void
getDistributionMatrix (const unsigned int projection, const Eigen::Vector3f& min, const Eigen::Vector3f& max, const PointCloudIn& cloud, Eigen::MatrixXf& matrix) const;
/** \brief This method computes the set ofcentral moments for the given matrix.
* \param[in] matrix input matrix
* \param[out] moments set of computed moments
*/
void
computeCentralMoments (const Eigen::MatrixXf& matrix, std::vector <float>& moments) const;
private:
/** \brief Stores the number of partition bins that is used for distribution matrix calculation. */
unsigned int number_of_bins_;
/** \brief Stores number of rotations. Central moments are calculated for every rotation. */
unsigned int number_of_rotations_;
/** \brief Support radius that is used to crop the local surface of the point. */
float support_radius_;
/** \brief Stores the squared support radius. Used to improve performance. */
float sqr_support_radius_;
/** \brief Stores the angle step. Step is calculated with respect to number of rotations. */
float step_;
/** \brief Stores the set of triangles reprsenting the mesh. */
std::vector <pcl::Vertices> triangles_;
/** \brief Stores the set of triangles for each point. Its purpose is to improve perfomance. */
std::vector <std::vector <unsigned int> > triangles_of_the_point_;
public:
EIGEN_MAKE_ALIGNED_OPERATOR_NEW
};
}
#define PCL_INSTANTIATE_ROPSEstimation(InT, OutT) template class pcl::ROPSEstimation<InT, OutT>;
#ifdef PCL_NO_PRECOMPILE
#include <pcl/features/impl/rops_estimation.hpp>
#endif
#endif
| 42.097046 | 174 | 0.689686 | [
"mesh",
"object",
"vector",
"transform",
"3d"
] |
4e293c285d44f7505f93453781b7c3d143c2cb48 | 30,164 | c | C | external/dbus/dbus/dbus-sysdeps-util-unix.c | ghsecuritylab/android_platform_sony_nicki | 526381be7808e5202d7865aa10303cb5d249388a | [
"Apache-2.0"
] | null | null | null | external/dbus/dbus/dbus-sysdeps-util-unix.c | ghsecuritylab/android_platform_sony_nicki | 526381be7808e5202d7865aa10303cb5d249388a | [
"Apache-2.0"
] | null | null | null | external/dbus/dbus/dbus-sysdeps-util-unix.c | ghsecuritylab/android_platform_sony_nicki | 526381be7808e5202d7865aa10303cb5d249388a | [
"Apache-2.0"
] | 1 | 2020-03-08T00:59:27.000Z | 2020-03-08T00:59:27.000Z | /* -*- mode: C; c-file-style: "gnu"; indent-tabs-mode: nil; -*- */
/* dbus-sysdeps-util-unix.c Would be in dbus-sysdeps-unix.c, but not used in libdbus
*
* Copyright (C) 2002, 2003, 2004, 2005 Red Hat, Inc.
* Copyright (C) 2003 CodeFactory AB
*
* Licensed under the Academic Free License version 2.1
*
* 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
*
*/
#include <config.h>
#include "dbus-sysdeps.h"
#include "dbus-sysdeps-unix.h"
#include "dbus-internals.h"
#include "dbus-pipe.h"
#include "dbus-protocol.h"
#include "dbus-string.h"
#define DBUS_USERDB_INCLUDES_PRIVATE 1
#include "dbus-userdb.h"
#include "dbus-test.h"
#include <sys/types.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/stat.h>
#ifdef HAVE_SYS_RESOURCE_H
#include <sys/resource.h>
#endif
#include <grp.h>
#include <sys/socket.h>
#include <dirent.h>
#include <sys/un.h>
#include <syslog.h>
#ifdef HAVE_SYS_SYSLIMITS_H
#include <sys/syslimits.h>
#endif
#ifndef O_BINARY
#define O_BINARY 0
#endif
/**
* @addtogroup DBusInternalsUtils
* @{
*/
/**
* Does the chdir, fork, setsid, etc. to become a daemon process.
*
* @param pidfile #NULL, or pidfile to create
* @param print_pid_pipe pipe to print daemon's pid to, or -1 for none
* @param error return location for errors
* @param keep_umask #TRUE to keep the original umask
* @returns #FALSE on failure
*/
dbus_bool_t
_dbus_become_daemon (const DBusString *pidfile,
DBusPipe *print_pid_pipe,
DBusError *error,
dbus_bool_t keep_umask)
{
const char *s;
pid_t child_pid;
int dev_null_fd;
_dbus_verbose ("Becoming a daemon...\n");
_dbus_verbose ("chdir to /\n");
if (chdir ("/") < 0)
{
dbus_set_error (error, DBUS_ERROR_FAILED,
"Could not chdir() to root directory");
return FALSE;
}
_dbus_verbose ("forking...\n");
switch ((child_pid = fork ()))
{
case -1:
_dbus_verbose ("fork failed\n");
dbus_set_error (error, _dbus_error_from_errno (errno),
"Failed to fork daemon: %s", _dbus_strerror (errno));
return FALSE;
break;
case 0:
_dbus_verbose ("in child, closing std file descriptors\n");
/* silently ignore failures here, if someone
* doesn't have /dev/null we may as well try
* to continue anyhow
*/
dev_null_fd = open ("/dev/null", O_RDWR);
if (dev_null_fd >= 0)
{
dup2 (dev_null_fd, 0);
dup2 (dev_null_fd, 1);
s = _dbus_getenv ("DBUS_DEBUG_OUTPUT");
if (s == NULL || *s == '\0')
dup2 (dev_null_fd, 2);
else
_dbus_verbose ("keeping stderr open due to DBUS_DEBUG_OUTPUT\n");
}
if (!keep_umask)
{
/* Get a predictable umask */
_dbus_verbose ("setting umask\n");
umask (022);
}
_dbus_verbose ("calling setsid()\n");
if (setsid () == -1)
_dbus_assert_not_reached ("setsid() failed");
break;
default:
if (!_dbus_write_pid_to_file_and_pipe (pidfile, print_pid_pipe,
child_pid, error))
{
_dbus_verbose ("pid file or pipe write failed: %s\n",
error->message);
kill (child_pid, SIGTERM);
return FALSE;
}
_dbus_verbose ("parent exiting\n");
_exit (0);
break;
}
return TRUE;
}
/**
* Creates a file containing the process ID.
*
* @param filename the filename to write to
* @param pid our process ID
* @param error return location for errors
* @returns #FALSE on failure
*/
static dbus_bool_t
_dbus_write_pid_file (const DBusString *filename,
unsigned long pid,
DBusError *error)
{
const char *cfilename;
int fd;
FILE *f;
cfilename = _dbus_string_get_const_data (filename);
fd = open (cfilename, O_WRONLY|O_CREAT|O_EXCL|O_BINARY, 0644);
if (fd < 0)
{
dbus_set_error (error, _dbus_error_from_errno (errno),
"Failed to open \"%s\": %s", cfilename,
_dbus_strerror (errno));
return FALSE;
}
if ((f = fdopen (fd, "w")) == NULL)
{
dbus_set_error (error, _dbus_error_from_errno (errno),
"Failed to fdopen fd %d: %s", fd, _dbus_strerror (errno));
_dbus_close (fd, NULL);
return FALSE;
}
if (fprintf (f, "%lu\n", pid) < 0)
{
dbus_set_error (error, _dbus_error_from_errno (errno),
"Failed to write to \"%s\": %s", cfilename,
_dbus_strerror (errno));
fclose (f);
return FALSE;
}
if (fclose (f) == EOF)
{
dbus_set_error (error, _dbus_error_from_errno (errno),
"Failed to close \"%s\": %s", cfilename,
_dbus_strerror (errno));
return FALSE;
}
return TRUE;
}
/**
* Writes the given pid_to_write to a pidfile (if non-NULL) and/or to a
* pipe (if non-NULL). Does nothing if pidfile and print_pid_pipe are both
* NULL.
*
* @param pidfile the file to write to or #NULL
* @param print_pid_pipe the pipe to write to or #NULL
* @param pid_to_write the pid to write out
* @param error error on failure
* @returns FALSE if error is set
*/
dbus_bool_t
_dbus_write_pid_to_file_and_pipe (const DBusString *pidfile,
DBusPipe *print_pid_pipe,
dbus_pid_t pid_to_write,
DBusError *error)
{
if (pidfile)
{
_dbus_verbose ("writing pid file %s\n", _dbus_string_get_const_data (pidfile));
if (!_dbus_write_pid_file (pidfile,
pid_to_write,
error))
{
_dbus_verbose ("pid file write failed\n");
_DBUS_ASSERT_ERROR_IS_SET(error);
return FALSE;
}
}
else
{
_dbus_verbose ("No pid file requested\n");
}
if (print_pid_pipe != NULL && _dbus_pipe_is_valid (print_pid_pipe))
{
DBusString pid;
int bytes;
_dbus_verbose ("writing our pid to pipe %"PRIuPTR"\n",
print_pid_pipe->fd_or_handle);
if (!_dbus_string_init (&pid))
{
_DBUS_SET_OOM (error);
return FALSE;
}
if (!_dbus_string_append_int (&pid, pid_to_write) ||
!_dbus_string_append (&pid, "\n"))
{
_dbus_string_free (&pid);
_DBUS_SET_OOM (error);
return FALSE;
}
bytes = _dbus_string_get_length (&pid);
if (_dbus_pipe_write (print_pid_pipe, &pid, 0, bytes, error) != bytes)
{
/* _dbus_pipe_write sets error only on failure, not short write */
if (error != NULL && !dbus_error_is_set(error))
{
dbus_set_error (error, DBUS_ERROR_FAILED,
"Printing message bus PID: did not write enough bytes\n");
}
_dbus_string_free (&pid);
return FALSE;
}
_dbus_string_free (&pid);
}
else
{
_dbus_verbose ("No pid pipe to write to\n");
}
return TRUE;
}
/**
* Verify that after the fork we can successfully change to this user.
*
* @param user the username given in the daemon configuration
* @returns #TRUE if username is valid
*/
dbus_bool_t
_dbus_verify_daemon_user (const char *user)
{
DBusString u;
_dbus_string_init_const (&u, user);
return _dbus_get_user_id_and_primary_group (&u, NULL, NULL);
}
/* The HAVE_LIBAUDIT case lives in selinux.c */
#ifndef HAVE_LIBAUDIT
/**
* Changes the user and group the bus is running as.
*
* @param user the user to become
* @param error return location for errors
* @returns #FALSE on failure
*/
dbus_bool_t
_dbus_change_to_daemon_user (const char *user,
DBusError *error)
{
dbus_uid_t uid;
dbus_gid_t gid;
DBusString u;
_dbus_string_init_const (&u, user);
if (!_dbus_get_user_id_and_primary_group (&u, &uid, &gid))
{
dbus_set_error (error, DBUS_ERROR_FAILED,
"User '%s' does not appear to exist?",
user);
return FALSE;
}
/* setgroups() only works if we are a privileged process,
* so we don't return error on failure; the only possible
* failure is that we don't have perms to do it.
*
* not sure this is right, maybe if setuid()
* is going to work then setgroups() should also work.
*/
if (setgroups (0, NULL) < 0)
_dbus_warn ("Failed to drop supplementary groups: %s\n",
_dbus_strerror (errno));
/* Set GID first, or the setuid may remove our permission
* to change the GID
*/
if (setgid (gid) < 0)
{
dbus_set_error (error, _dbus_error_from_errno (errno),
"Failed to set GID to %lu: %s", gid,
_dbus_strerror (errno));
return FALSE;
}
if (setuid (uid) < 0)
{
dbus_set_error (error, _dbus_error_from_errno (errno),
"Failed to set UID to %lu: %s", uid,
_dbus_strerror (errno));
return FALSE;
}
return TRUE;
}
#endif /* !HAVE_LIBAUDIT */
/**
* Attempt to ensure that the current process can open
* at least @limit file descriptors.
*
* If @limit is lower than the current, it will not be
* lowered. No error is returned if the request can
* not be satisfied.
*
* @limit Number of file descriptors
*/
void
_dbus_request_file_descriptor_limit (unsigned int limit)
{
#ifdef HAVE_SETRLIMIT
struct rlimit lim;
struct rlimit target_lim;
unsigned int current_limit;
/* No point to doing this practically speaking
* if we're not uid 0. We expect the system
* bus to use this before we change UID, and
* the session bus takes the Linux default
* of 1024 for both cur and max.
*/
if (getuid () != 0)
return;
if (getrlimit (RLIMIT_NOFILE, &lim) < 0)
return;
if (lim.rlim_cur >= limit)
return;
/* Ignore "maximum limit", assume we have the "superuser"
* privileges. On Linux this is CAP_SYS_RESOURCE.
*/
target_lim.rlim_cur = target_lim.rlim_max = limit;
/* Also ignore errors; if we fail, we will at least work
* up to whatever limit we had, which seems better than
* just outright aborting.
*
* However, in the future we should probably log this so OS builders
* have a chance to notice any misconfiguration like dbus-daemon
* being started without CAP_SYS_RESOURCE.
*/
setrlimit (RLIMIT_NOFILE, &target_lim);
#endif
}
void
_dbus_init_system_log (void)
{
#ifdef HAVE_DECL_LOG_PERROR
openlog ("dbus", LOG_PID | LOG_PERROR, LOG_DAEMON);
#else
openlog ("dbus", LOG_PID, LOG_DAEMON);
#endif
}
/**
* Log a message to the system log file (e.g. syslog on Unix).
*
* @param severity a severity value
* @param msg a printf-style format string
* @param args arguments for the format string
*
*/
void
_dbus_system_log (DBusSystemLogSeverity severity, const char *msg, ...)
{
va_list args;
va_start (args, msg);
_dbus_system_logv (severity, msg, args);
va_end (args);
}
/**
* Log a message to the system log file (e.g. syslog on Unix).
*
* @param severity a severity value
* @param msg a printf-style format string
* @param args arguments for the format string
*
* If the FATAL severity is given, this function will terminate the program
* with an error code.
*/
void
_dbus_system_logv (DBusSystemLogSeverity severity, const char *msg, va_list args)
{
int flags;
switch (severity)
{
case DBUS_SYSTEM_LOG_INFO:
flags = LOG_DAEMON | LOG_NOTICE;
break;
case DBUS_SYSTEM_LOG_SECURITY:
flags = LOG_AUTH | LOG_NOTICE;
break;
case DBUS_SYSTEM_LOG_FATAL:
flags = LOG_DAEMON|LOG_CRIT;
break;
default:
return;
}
#ifndef HAVE_DECL_LOG_PERROR
{
/* vsyslog() won't write to stderr, so we'd better do it */
va_list tmp;
DBUS_VA_COPY (tmp, args);
fprintf (stderr, "dbus[" DBUS_PID_FORMAT "]: ", _dbus_getpid ());
vfprintf (stderr, msg, tmp);
fputc ('\n', stderr);
va_end (tmp);
}
#endif
vsyslog (flags, msg, args);
if (severity == DBUS_SYSTEM_LOG_FATAL)
exit (1);
}
/** Installs a UNIX signal handler
*
* @param sig the signal to handle
* @param handler the handler
*/
void
_dbus_set_signal_handler (int sig,
DBusSignalHandler handler)
{
struct sigaction act;
sigset_t empty_mask;
sigemptyset (&empty_mask);
act.sa_handler = handler;
act.sa_mask = empty_mask;
act.sa_flags = 0;
sigaction (sig, &act, NULL);
}
/** Checks if a file exists
*
* @param file full path to the file
* @returns #TRUE if file exists
*/
dbus_bool_t
_dbus_file_exists (const char *file)
{
return (access (file, F_OK) == 0);
}
/** Checks if user is at the console
*
* @param username user to check
* @param error return location for errors
* @returns #TRUE is the user is at the consolei and there are no errors
*/
dbus_bool_t
_dbus_user_at_console (const char *username,
DBusError *error)
{
DBusString f;
dbus_bool_t result;
result = FALSE;
if (!_dbus_string_init (&f))
{
_DBUS_SET_OOM (error);
return FALSE;
}
if (!_dbus_string_append (&f, DBUS_CONSOLE_AUTH_DIR))
{
_DBUS_SET_OOM (error);
goto out;
}
if (!_dbus_string_append (&f, username))
{
_DBUS_SET_OOM (error);
goto out;
}
result = _dbus_file_exists (_dbus_string_get_const_data (&f));
out:
_dbus_string_free (&f);
return result;
}
/**
* Checks whether the filename is an absolute path
*
* @param filename the filename
* @returns #TRUE if an absolute path
*/
dbus_bool_t
_dbus_path_is_absolute (const DBusString *filename)
{
if (_dbus_string_get_length (filename) > 0)
return _dbus_string_get_byte (filename, 0) == '/';
else
return FALSE;
}
/**
* stat() wrapper.
*
* @param filename the filename to stat
* @param statbuf the stat info to fill in
* @param error return location for error
* @returns #FALSE if error was set
*/
dbus_bool_t
_dbus_stat (const DBusString *filename,
DBusStat *statbuf,
DBusError *error)
{
const char *filename_c;
struct stat sb;
_DBUS_ASSERT_ERROR_IS_CLEAR (error);
filename_c = _dbus_string_get_const_data (filename);
if (stat (filename_c, &sb) < 0)
{
dbus_set_error (error, _dbus_error_from_errno (errno),
"%s", _dbus_strerror (errno));
return FALSE;
}
statbuf->mode = sb.st_mode;
statbuf->nlink = sb.st_nlink;
statbuf->uid = sb.st_uid;
statbuf->gid = sb.st_gid;
statbuf->size = sb.st_size;
statbuf->atime = sb.st_atime;
statbuf->mtime = sb.st_mtime;
statbuf->ctime = sb.st_ctime;
return TRUE;
}
/**
* Internals of directory iterator
*/
struct DBusDirIter
{
DIR *d; /**< The DIR* from opendir() */
};
/**
* Open a directory to iterate over.
*
* @param filename the directory name
* @param error exception return object or #NULL
* @returns new iterator, or #NULL on error
*/
DBusDirIter*
_dbus_directory_open (const DBusString *filename,
DBusError *error)
{
DIR *d;
DBusDirIter *iter;
const char *filename_c;
_DBUS_ASSERT_ERROR_IS_CLEAR (error);
filename_c = _dbus_string_get_const_data (filename);
d = opendir (filename_c);
if (d == NULL)
{
dbus_set_error (error, _dbus_error_from_errno (errno),
"Failed to read directory \"%s\": %s",
filename_c,
_dbus_strerror (errno));
return NULL;
}
iter = dbus_new0 (DBusDirIter, 1);
if (iter == NULL)
{
closedir (d);
dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
"Could not allocate memory for directory iterator");
return NULL;
}
iter->d = d;
return iter;
}
/* it is never safe to retrun a size smaller than sizeof(struct dirent)
* because the libc *could* try to access the whole structure
* (for instance it could try to memset it).
* it is also incorrect to return a size bigger than that, because
* the libc would never use it.
* The only correct and safe value this function can ever return is
* sizeof(struct dirent).
*/
static dbus_bool_t
dirent_buf_size(DIR * dirp, size_t *size)
{
*size = sizeof(struct dirent);
return TRUE;
}
/**
* Get next file in the directory. Will not return "." or ".." on
* UNIX. If an error occurs, the contents of "filename" are
* undefined. The error is never set if the function succeeds.
*
* This function is not re-entrant, and not necessarily thread-safe.
* Only use it for test code or single-threaded utilities.
*
* @param iter the iterator
* @param filename string to be set to the next file in the dir
* @param error return location for error
* @returns #TRUE if filename was filled in with a new filename
*/
dbus_bool_t
_dbus_directory_get_next_file (DBusDirIter *iter,
DBusString *filename,
DBusError *error)
{
struct dirent *ent;
int err;
_DBUS_ASSERT_ERROR_IS_CLEAR (error);
again:
errno = 0;
ent = readdir (iter->d);
if (!ent)
{
err = errno;
if (err != 0)
dbus_set_error (error,
_dbus_error_from_errno (err),
"%s", _dbus_strerror (err));
return FALSE;
}
else if (ent->d_name[0] == '.' &&
(ent->d_name[1] == '\0' ||
(ent->d_name[1] == '.' && ent->d_name[2] == '\0')))
goto again;
else
{
_dbus_string_set_length (filename, 0);
if (!_dbus_string_append (filename, ent->d_name))
{
dbus_set_error (error, DBUS_ERROR_NO_MEMORY,
"No memory to read directory entry");
return FALSE;
}
else
{
return TRUE;
}
}
}
/**
* Closes a directory iteration.
*/
void
_dbus_directory_close (DBusDirIter *iter)
{
closedir (iter->d);
dbus_free (iter);
}
static dbus_bool_t
fill_user_info_from_group (struct group *g,
DBusGroupInfo *info,
DBusError *error)
{
_dbus_assert (g->gr_name != NULL);
info->gid = g->gr_gid;
info->groupname = _dbus_strdup (g->gr_name);
/* info->members = dbus_strdupv (g->gr_mem) */
if (info->groupname == NULL)
{
dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
return FALSE;
}
return TRUE;
}
static dbus_bool_t
fill_group_info (DBusGroupInfo *info,
dbus_gid_t gid,
const DBusString *groupname,
DBusError *error)
{
const char *group_c_str;
_dbus_assert (groupname != NULL || gid != DBUS_GID_UNSET);
_dbus_assert (groupname == NULL || gid == DBUS_GID_UNSET);
if (groupname)
group_c_str = _dbus_string_get_const_data (groupname);
else
group_c_str = NULL;
/* For now assuming that the getgrnam() and getgrgid() flavors
* always correspond to the pwnam flavors, if not we have
* to add more configure checks.
*/
#if defined (HAVE_POSIX_GETPWNAM_R) || defined (HAVE_NONPOSIX_GETPWNAM_R)
{
struct group *g;
int result;
size_t buflen;
char *buf;
struct group g_str;
dbus_bool_t b;
/* retrieve maximum needed size for buf */
buflen = sysconf (_SC_GETGR_R_SIZE_MAX);
/* sysconf actually returns a long, but everything else expects size_t,
* so just recast here.
* https://bugs.freedesktop.org/show_bug.cgi?id=17061
*/
if ((long) buflen <= 0)
buflen = 1024;
result = -1;
while (1)
{
buf = dbus_malloc (buflen);
if (buf == NULL)
{
dbus_set_error (error, DBUS_ERROR_NO_MEMORY, NULL);
return FALSE;
}
g = NULL;
#ifdef HAVE_POSIX_GETPWNAM_R
if (group_c_str)
result = getgrnam_r (group_c_str, &g_str, buf, buflen,
&g);
else
result = getgrgid_r (gid, &g_str, buf, buflen,
&g);
#else
g = getgrnam_r (group_c_str, &g_str, buf, buflen);
result = 0;
#endif /* !HAVE_POSIX_GETPWNAM_R */
/* Try a bigger buffer if ERANGE was returned:
https://bugs.freedesktop.org/show_bug.cgi?id=16727
*/
if (result == ERANGE && buflen < 512 * 1024)
{
dbus_free (buf);
buflen *= 2;
}
else
{
break;
}
}
if (result == 0 && g == &g_str)
{
b = fill_user_info_from_group (g, info, error);
dbus_free (buf);
return b;
}
else
{
dbus_set_error (error, _dbus_error_from_errno (errno),
"Group %s unknown or failed to look it up\n",
group_c_str ? group_c_str : "???");
dbus_free (buf);
return FALSE;
}
}
#else /* ! HAVE_GETPWNAM_R */
{
/* I guess we're screwed on thread safety here */
struct group *g;
g = getgrnam (group_c_str);
if (g != NULL)
{
return fill_user_info_from_group (g, info, error);
}
else
{
dbus_set_error (error, _dbus_error_from_errno (errno),
"Group %s unknown or failed to look it up\n",
group_c_str ? group_c_str : "???");
return FALSE;
}
}
#endif /* ! HAVE_GETPWNAM_R */
}
/**
* Initializes the given DBusGroupInfo struct
* with information about the given group name.
*
* @param info the group info struct
* @param groupname name of group
* @param error the error return
* @returns #FALSE if error is set
*/
dbus_bool_t
_dbus_group_info_fill (DBusGroupInfo *info,
const DBusString *groupname,
DBusError *error)
{
return fill_group_info (info, DBUS_GID_UNSET,
groupname, error);
}
/**
* Initializes the given DBusGroupInfo struct
* with information about the given group ID.
*
* @param info the group info struct
* @param gid group ID
* @param error the error return
* @returns #FALSE if error is set
*/
dbus_bool_t
_dbus_group_info_fill_gid (DBusGroupInfo *info,
dbus_gid_t gid,
DBusError *error)
{
return fill_group_info (info, gid, NULL, error);
}
/**
* Parse a UNIX user from the bus config file. On Windows, this should
* simply always fail (just return #FALSE).
*
* @param username the username text
* @param uid_p place to return the uid
* @returns #TRUE on success
*/
dbus_bool_t
_dbus_parse_unix_user_from_config (const DBusString *username,
dbus_uid_t *uid_p)
{
return _dbus_get_user_id (username, uid_p);
}
/**
* Parse a UNIX group from the bus config file. On Windows, this should
* simply always fail (just return #FALSE).
*
* @param groupname the groupname text
* @param gid_p place to return the gid
* @returns #TRUE on success
*/
dbus_bool_t
_dbus_parse_unix_group_from_config (const DBusString *groupname,
dbus_gid_t *gid_p)
{
return _dbus_get_group_id (groupname, gid_p);
}
/**
* Gets all groups corresponding to the given UNIX user ID. On UNIX,
* just calls _dbus_groups_from_uid(). On Windows, should always
* fail since we don't know any UNIX groups.
*
* @param uid the UID
* @param group_ids return location for array of group IDs
* @param n_group_ids return location for length of returned array
* @returns #TRUE if the UID existed and we got some credentials
*/
dbus_bool_t
_dbus_unix_groups_from_uid (dbus_uid_t uid,
dbus_gid_t **group_ids,
int *n_group_ids)
{
return _dbus_groups_from_uid (uid, group_ids, n_group_ids);
}
/**
* Checks to see if the UNIX user ID is at the console.
* Should always fail on Windows (set the error to
* #DBUS_ERROR_NOT_SUPPORTED).
*
* @param uid UID of person to check
* @param error return location for errors
* @returns #TRUE if the UID is the same as the console user and there are no errors
*/
dbus_bool_t
_dbus_unix_user_is_at_console (dbus_uid_t uid,
DBusError *error)
{
return _dbus_is_console_user (uid, error);
}
/**
* Checks to see if the UNIX user ID matches the UID of
* the process. Should always return #FALSE on Windows.
*
* @param uid the UNIX user ID
* @returns #TRUE if this uid owns the process.
*/
dbus_bool_t
_dbus_unix_user_is_process_owner (dbus_uid_t uid)
{
return uid == _dbus_geteuid ();
}
/**
* Checks to see if the Windows user SID matches the owner of
* the process. Should always return #FALSE on UNIX.
*
* @param windows_sid the Windows user SID
* @returns #TRUE if this user owns the process.
*/
dbus_bool_t
_dbus_windows_user_is_process_owner (const char *windows_sid)
{
return FALSE;
}
/** @} */ /* End of DBusInternalsUtils functions */
/**
* @addtogroup DBusString
*
* @{
*/
/**
* Get the directory name from a complete filename
* @param filename the filename
* @param dirname string to append directory name to
* @returns #FALSE if no memory
*/
dbus_bool_t
_dbus_string_get_dirname (const DBusString *filename,
DBusString *dirname)
{
int sep;
_dbus_assert (filename != dirname);
_dbus_assert (filename != NULL);
_dbus_assert (dirname != NULL);
/* Ignore any separators on the end */
sep = _dbus_string_get_length (filename);
if (sep == 0)
return _dbus_string_append (dirname, "."); /* empty string passed in */
while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
--sep;
_dbus_assert (sep >= 0);
if (sep == 0)
return _dbus_string_append (dirname, "/");
/* Now find the previous separator */
_dbus_string_find_byte_backward (filename, sep, '/', &sep);
if (sep < 0)
return _dbus_string_append (dirname, ".");
/* skip multiple separators */
while (sep > 0 && _dbus_string_get_byte (filename, sep - 1) == '/')
--sep;
_dbus_assert (sep >= 0);
if (sep == 0 &&
_dbus_string_get_byte (filename, 0) == '/')
return _dbus_string_append (dirname, "/");
else
return _dbus_string_copy_len (filename, 0, sep - 0,
dirname, _dbus_string_get_length (dirname));
}
/** @} */ /* DBusString stuff */
static void
string_squash_nonprintable (DBusString *str)
{
unsigned char *buf;
int i, len;
buf = _dbus_string_get_data (str);
len = _dbus_string_get_length (str);
for (i = 0; i < len; i++)
{
unsigned char c = (unsigned char) buf[i];
if (c == '\0')
buf[i] = ' ';
else if (c < 0x20 || c > 127)
buf[i] = '?';
}
}
/**
* Get a printable string describing the command used to execute
* the process with pid. This string should only be used for
* informative purposes such as logging; it may not be trusted.
*
* The command is guaranteed to be printable ASCII and no longer
* than max_len.
*
* @param pid Process id
* @param str Append command to this string
* @param max_len Maximum length of returned command
* @param error return location for errors
* @returns #FALSE on error
*/
dbus_bool_t
_dbus_command_for_pid (unsigned long pid,
DBusString *str,
int max_len,
DBusError *error)
{
/* This is all Linux-specific for now */
DBusString path;
DBusString cmdline;
int fd;
if (!_dbus_string_init (&path))
{
_DBUS_SET_OOM (error);
return FALSE;
}
if (!_dbus_string_init (&cmdline))
{
_DBUS_SET_OOM (error);
_dbus_string_free (&path);
return FALSE;
}
if (!_dbus_string_append_printf (&path, "/proc/%ld/cmdline", pid))
goto oom;
fd = open (_dbus_string_get_const_data (&path), O_RDONLY);
if (fd < 0)
{
dbus_set_error (error,
_dbus_error_from_errno (errno),
"Failed to open \"%s\": %s",
_dbus_string_get_const_data (&path),
_dbus_strerror (errno));
goto fail;
}
if (!_dbus_read (fd, &cmdline, max_len))
{
dbus_set_error (error,
_dbus_error_from_errno (errno),
"Failed to read from \"%s\": %s",
_dbus_string_get_const_data (&path),
_dbus_strerror (errno));
goto fail;
}
if (!_dbus_close (fd, error))
goto fail;
string_squash_nonprintable (&cmdline);
if (!_dbus_string_copy (&cmdline, 0, str, _dbus_string_get_length (str)))
goto oom;
_dbus_string_free (&cmdline);
_dbus_string_free (&path);
return TRUE;
oom:
_DBUS_SET_OOM (error);
fail:
_dbus_string_free (&cmdline);
_dbus_string_free (&path);
return FALSE;
}
| 25.519459 | 88 | 0.60854 | [
"object"
] |
4e2f9a91ab75f01601e29629508edff86d9e54a6 | 20,709 | h | C | AggRender/Graphin/src/agg/include/agg_rasterizer_outline_aa.h | isuhao/BaijieCppUILibs | 7771f225d854c69bc129d983cfcb10d672e1eacd | [
"BSD-3-Clause"
] | null | null | null | AggRender/Graphin/src/agg/include/agg_rasterizer_outline_aa.h | isuhao/BaijieCppUILibs | 7771f225d854c69bc129d983cfcb10d672e1eacd | [
"BSD-3-Clause"
] | null | null | null | AggRender/Graphin/src/agg/include/agg_rasterizer_outline_aa.h | isuhao/BaijieCppUILibs | 7771f225d854c69bc129d983cfcb10d672e1eacd | [
"BSD-3-Clause"
] | 1 | 2018-09-22T04:03:43.000Z | 2018-09-22T04:03:43.000Z | //----------------------------------------------------------------------------
// Anti-Grain Geometry - Version 2.4
// Copyright (C) 2002-2005 Maxim Shemanarev (http://www.antigrain.com)
//
// Permission to copy, use, modify, sell and distribute this software
// is granted provided this copyright notice appears in all copies.
// This software is provided "as is" without express or implied
// warranty, and with no claim as to its suitability for any purpose.
//
//----------------------------------------------------------------------------
// Contact: mcseem@antigrain.com
// mcseemagg@yahoo.com
// http://www.antigrain.com
//----------------------------------------------------------------------------
#ifndef AGG_RASTERIZER_OUTLINE_AA_INCLUDED
#define AGG_RASTERIZER_OUTLINE_AA_INCLUDED
#include "agg_basics.h"
#include "agg_line_aa_basics.h"
#include "agg_vertex_sequence.h"
namespace agg
{
//-------------------------------------------------------------------------
inline bool cmp_dist_start(int d) { return d > 0; }
inline bool cmp_dist_end(int d) { return d <= 0; }
//-----------------------------------------------------------line_aa_vertex
// Vertex (x, y) with the distance to the next one. The last vertex has
// the distance between the last and the first points
struct line_aa_vertex
{
int x;
int y;
int len;
line_aa_vertex() {}
line_aa_vertex(int x_, int y_) :
x(x_),
y(y_),
len(0)
{
}
bool operator () (const line_aa_vertex& val)
{
real dx = val.x - x;
real dy = val.y - y;
return (len = uround(SQRT(dx * dx + dy * dy))) >
(line_subpixel_scale + line_subpixel_scale / 2);
}
};
//----------------------------------------------------------outline_aa_join_e
enum outline_aa_join_e
{
outline_no_join, //-----outline_no_join
outline_miter_join, //-----outline_miter_join
outline_round_join, //-----outline_round_join
outline_miter_accurate_join //-----outline_accurate_join
};
//=======================================================rasterizer_outline_aa
template<class Renderer, class Coord=line_coord> class rasterizer_outline_aa
{
private:
//------------------------------------------------------------------------
struct draw_vars
{
unsigned idx;
int x1, y1, x2, y2;
line_parameters curr, next;
int lcurr, lnext;
int xb1, yb1, xb2, yb2;
unsigned flags;
};
void draw(draw_vars& dv, unsigned start, unsigned end);
public:
typedef line_aa_vertex vertex_type;
typedef vertex_sequence<vertex_type, 6> vertex_storage_type;
explicit rasterizer_outline_aa(Renderer& ren) :
m_ren(&ren),
m_line_join(ren.accurate_join_only() ?
outline_miter_accurate_join :
outline_round_join),
m_round_cap(false),
m_start_x(0),
m_start_y(0)
{}
void attach(Renderer& ren) { m_ren = &ren; }
//------------------------------------------------------------------------
void line_join(outline_aa_join_e join)
{
m_line_join = m_ren->accurate_join_only() ?
outline_miter_accurate_join :
join;
}
bool line_join() const { return m_line_join; }
//------------------------------------------------------------------------
void round_cap(bool v) { m_round_cap = v; }
bool round_cap() const { return m_round_cap; }
//------------------------------------------------------------------------
void move_to(int x, int y)
{
m_src_vertices.modify_last(vertex_type(m_start_x = x, m_start_y = y));
}
//------------------------------------------------------------------------
void line_to(int x, int y)
{
m_src_vertices.add(vertex_type(x, y));
}
//------------------------------------------------------------------------
void move_to_d(real x, real y)
{
move_to(Coord::conv(x), Coord::conv(y));
}
//------------------------------------------------------------------------
void line_to_d(real x, real y)
{
line_to(Coord::conv(x), Coord::conv(y));
}
//------------------------------------------------------------------------
void render(bool close_polygon);
//------------------------------------------------------------------------
void add_vertex(real x, real y, unsigned cmd)
{
if(is_move_to(cmd))
{
render(false);
move_to_d(x, y);
}
else
{
if(is_end_poly(cmd))
{
render(is_closed(cmd));
if(is_closed(cmd))
{
move_to(m_start_x, m_start_y);
}
}
else
{
line_to_d(x, y);
}
}
}
//------------------------------------------------------------------------
template<class VertexSource>
void add_path(VertexSource& vs, unsigned path_id=0)
{
real x;
real y;
unsigned cmd;
vs.rewind(path_id);
while(!is_stop(cmd = vs.vertex(&x, &y)))
{
add_vertex(x, y, cmd);
}
render(false);
}
//------------------------------------------------------------------------
template<class VertexSource, class ColorStorage, class PathId>
void render_all_paths(VertexSource& vs,
const ColorStorage& colors,
const PathId& path_id,
unsigned num_paths)
{
for(unsigned i = 0; i < num_paths; i++)
{
m_ren->color(colors[i]);
add_path(vs, path_id[i]);
}
}
//------------------------------------------------------------------------
template<class Ctrl> void render_ctrl(Ctrl& c)
{
unsigned i;
for(i = 0; i < c.num_paths(); i++)
{
m_ren->color(c.color(i));
add_path(c, i);
}
}
private:
rasterizer_outline_aa(const rasterizer_outline_aa<Renderer, Coord>&);
const rasterizer_outline_aa<Renderer, Coord>& operator =
(const rasterizer_outline_aa<Renderer, Coord>&);
Renderer* m_ren;
vertex_storage_type m_src_vertices;
outline_aa_join_e m_line_join;
bool m_round_cap;
int m_start_x;
int m_start_y;
};
//----------------------------------------------------------------------------
template<class Renderer, class Coord>
void rasterizer_outline_aa<Renderer, Coord>::draw(draw_vars& dv,
unsigned start,
unsigned end)
{
unsigned i;
const vertex_storage_type::value_type* v;
for(i = start; i < end; i++)
{
if(m_line_join == outline_round_join)
{
dv.xb1 = dv.curr.x1 + (dv.curr.y2 - dv.curr.y1);
dv.yb1 = dv.curr.y1 - (dv.curr.x2 - dv.curr.x1);
dv.xb2 = dv.curr.x2 + (dv.curr.y2 - dv.curr.y1);
dv.yb2 = dv.curr.y2 - (dv.curr.x2 - dv.curr.x1);
}
switch(dv.flags)
{
case 0: m_ren->line3(dv.curr, dv.xb1, dv.yb1, dv.xb2, dv.yb2); break;
case 1: m_ren->line2(dv.curr, dv.xb2, dv.yb2); break;
case 2: m_ren->line1(dv.curr, dv.xb1, dv.yb1); break;
case 3: m_ren->line0(dv.curr); break;
}
if(m_line_join == outline_round_join && (dv.flags & 2) == 0)
{
m_ren->pie(dv.curr.x2, dv.curr.y2,
dv.curr.x2 + (dv.curr.y2 - dv.curr.y1),
dv.curr.y2 - (dv.curr.x2 - dv.curr.x1),
dv.curr.x2 + (dv.next.y2 - dv.next.y1),
dv.curr.y2 - (dv.next.x2 - dv.next.x1));
}
dv.x1 = dv.x2;
dv.y1 = dv.y2;
dv.lcurr = dv.lnext;
dv.lnext = m_src_vertices[dv.idx].len;
++dv.idx;
if(dv.idx >= m_src_vertices.size()) dv.idx = 0;
v = &m_src_vertices[dv.idx];
dv.x2 = v->x;
dv.y2 = v->y;
dv.curr = dv.next;
dv.next = line_parameters(dv.x1, dv.y1, dv.x2, dv.y2, dv.lnext);
dv.xb1 = dv.xb2;
dv.yb1 = dv.yb2;
switch(m_line_join)
{
case outline_no_join:
dv.flags = 3;
break;
case outline_miter_join:
dv.flags >>= 1;
dv.flags |= ((dv.curr.diagonal_quadrant() ==
dv.next.diagonal_quadrant()) << 1);
if((dv.flags & 2) == 0)
{
bisectrix(dv.curr, dv.next, &dv.xb2, &dv.yb2);
}
break;
case outline_round_join:
dv.flags >>= 1;
dv.flags |= ((dv.curr.diagonal_quadrant() ==
dv.next.diagonal_quadrant()) << 1);
break;
case outline_miter_accurate_join:
dv.flags = 0;
bisectrix(dv.curr, dv.next, &dv.xb2, &dv.yb2);
break;
}
}
}
//----------------------------------------------------------------------------
template<class Renderer, class Coord>
void rasterizer_outline_aa<Renderer, Coord>::render(bool close_polygon)
{
m_src_vertices.close(close_polygon);
draw_vars dv;
const vertex_storage_type::value_type* v;
int x1;
int y1;
int x2;
int y2;
int lprev;
if(close_polygon)
{
if(m_src_vertices.size() >= 3)
{
dv.idx = 2;
v = &m_src_vertices[m_src_vertices.size() - 1];
x1 = v->x;
y1 = v->y;
lprev = v->len;
v = &m_src_vertices[0];
x2 = v->x;
y2 = v->y;
dv.lcurr = v->len;
line_parameters prev(x1, y1, x2, y2, lprev);
v = &m_src_vertices[1];
dv.x1 = v->x;
dv.y1 = v->y;
dv.lnext = v->len;
dv.curr = line_parameters(x2, y2, dv.x1, dv.y1, dv.lcurr);
v = &m_src_vertices[dv.idx];
dv.x2 = v->x;
dv.y2 = v->y;
dv.next = line_parameters(dv.x1, dv.y1, dv.x2, dv.y2, dv.lnext);
dv.xb1 = 0;
dv.yb1 = 0;
dv.xb2 = 0;
dv.yb2 = 0;
switch(m_line_join)
{
case outline_no_join:
dv.flags = 3;
break;
case outline_miter_join:
case outline_round_join:
dv.flags =
(prev.diagonal_quadrant() == dv.curr.diagonal_quadrant()) |
((dv.curr.diagonal_quadrant() == dv.next.diagonal_quadrant()) << 1);
break;
case outline_miter_accurate_join:
dv.flags = 0;
break;
}
if((dv.flags & 1) == 0 && m_line_join != outline_round_join)
{
bisectrix(prev, dv.curr, &dv.xb1, &dv.yb1);
}
if((dv.flags & 2) == 0 && m_line_join != outline_round_join)
{
bisectrix(dv.curr, dv.next, &dv.xb2, &dv.yb2);
}
draw(dv, 0, m_src_vertices.size());
}
}
else
{
switch(m_src_vertices.size())
{
case 0:
case 1:
break;
case 2:
{
v = &m_src_vertices[0];
x1 = v->x;
y1 = v->y;
lprev = v->len;
v = &m_src_vertices[1];
x2 = v->x;
y2 = v->y;
line_parameters lp(x1, y1, x2, y2, lprev);
if(m_round_cap)
{
m_ren->semidot(cmp_dist_start, x1, y1, x1 + (y2 - y1), y1 - (x2 - x1));
}
m_ren->line3(lp,
x1 + (y2 - y1),
y1 - (x2 - x1),
x2 + (y2 - y1),
y2 - (x2 - x1));
if(m_round_cap)
{
m_ren->semidot(cmp_dist_end, x2, y2, x2 + (y2 - y1), y2 - (x2 - x1));
}
}
break;
case 3:
{
int x3, y3;
int lnext;
v = &m_src_vertices[0];
x1 = v->x;
y1 = v->y;
lprev = v->len;
v = &m_src_vertices[1];
x2 = v->x;
y2 = v->y;
lnext = v->len;
v = &m_src_vertices[2];
x3 = v->x;
y3 = v->y;
line_parameters lp1(x1, y1, x2, y2, lprev);
line_parameters lp2(x2, y2, x3, y3, lnext);
if(m_round_cap)
{
m_ren->semidot(cmp_dist_start, x1, y1, x1 + (y2 - y1), y1 - (x2 - x1));
}
if(m_line_join == outline_round_join)
{
m_ren->line3(lp1, x1 + (y2 - y1), y1 - (x2 - x1),
x2 + (y2 - y1), y2 - (x2 - x1));
m_ren->pie(x2, y2, x2 + (y2 - y1), y2 - (x2 - x1),
x2 + (y3 - y2), y2 - (x3 - x2));
m_ren->line3(lp2, x2 + (y3 - y2), y2 - (x3 - x2),
x3 + (y3 - y2), y3 - (x3 - x2));
}
else
{
bisectrix(lp1, lp2, &dv.xb1, &dv.yb1);
m_ren->line3(lp1, x1 + (y2 - y1), y1 - (x2 - x1),
dv.xb1, dv.yb1);
m_ren->line3(lp2, dv.xb1, dv.yb1,
x3 + (y3 - y2), y3 - (x3 - x2));
}
if(m_round_cap)
{
m_ren->semidot(cmp_dist_end, x3, y3, x3 + (y3 - y2), y3 - (x3 - x2));
}
}
break;
default:
{
dv.idx = 3;
v = &m_src_vertices[0];
x1 = v->x;
y1 = v->y;
lprev = v->len;
v = &m_src_vertices[1];
x2 = v->x;
y2 = v->y;
dv.lcurr = v->len;
line_parameters prev(x1, y1, x2, y2, lprev);
v = &m_src_vertices[2];
dv.x1 = v->x;
dv.y1 = v->y;
dv.lnext = v->len;
dv.curr = line_parameters(x2, y2, dv.x1, dv.y1, dv.lcurr);
v = &m_src_vertices[dv.idx];
dv.x2 = v->x;
dv.y2 = v->y;
dv.next = line_parameters(dv.x1, dv.y1, dv.x2, dv.y2, dv.lnext);
dv.xb1 = 0;
dv.yb1 = 0;
dv.xb2 = 0;
dv.yb2 = 0;
switch(m_line_join)
{
case outline_no_join:
dv.flags = 3;
break;
case outline_miter_join:
case outline_round_join:
dv.flags =
(prev.diagonal_quadrant() == dv.curr.diagonal_quadrant()) |
((dv.curr.diagonal_quadrant() == dv.next.diagonal_quadrant()) << 1);
break;
case outline_miter_accurate_join:
dv.flags = 0;
break;
}
if(m_round_cap)
{
m_ren->semidot(cmp_dist_start, x1, y1, x1 + (y2 - y1), y1 - (x2 - x1));
}
if((dv.flags & 1) == 0)
{
if(m_line_join == outline_round_join)
{
m_ren->line3(prev, x1 + (y2 - y1), y1 - (x2 - x1),
x2 + (y2 - y1), y2 - (x2 - x1));
m_ren->pie(prev.x2, prev.y2,
x2 + (y2 - y1), y2 - (x2 - x1),
dv.curr.x1 + (dv.curr.y2 - dv.curr.y1),
dv.curr.y1 - (dv.curr.x2 - dv.curr.x1));
}
else
{
bisectrix(prev, dv.curr, &dv.xb1, &dv.yb1);
m_ren->line3(prev, x1 + (y2 - y1), y1 - (x2 - x1),
dv.xb1, dv.yb1);
}
}
else
{
m_ren->line1(prev,
x1 + (y2 - y1),
y1 - (x2 - x1));
}
if((dv.flags & 2) == 0 && m_line_join != outline_round_join)
{
bisectrix(dv.curr, dv.next, &dv.xb2, &dv.yb2);
}
draw(dv, 1, m_src_vertices.size() - 2);
if((dv.flags & 1) == 0)
{
if(m_line_join == outline_round_join)
{
m_ren->line3(dv.curr,
dv.curr.x1 + (dv.curr.y2 - dv.curr.y1),
dv.curr.y1 - (dv.curr.x2 - dv.curr.x1),
dv.curr.x2 + (dv.curr.y2 - dv.curr.y1),
dv.curr.y2 - (dv.curr.x2 - dv.curr.x1));
}
else
{
m_ren->line3(dv.curr, dv.xb1, dv.yb1,
dv.curr.x2 + (dv.curr.y2 - dv.curr.y1),
dv.curr.y2 - (dv.curr.x2 - dv.curr.x1));
}
}
else
{
m_ren->line2(dv.curr,
dv.curr.x2 + (dv.curr.y2 - dv.curr.y1),
dv.curr.y2 - (dv.curr.x2 - dv.curr.x1));
}
if(m_round_cap)
{
m_ren->semidot(cmp_dist_end, dv.curr.x2, dv.curr.y2,
dv.curr.x2 + (dv.curr.y2 - dv.curr.y1),
dv.curr.y2 - (dv.curr.x2 - dv.curr.x1));
}
}
break;
}
}
m_src_vertices.remove_all();
}
}
#endif
| 34.457571 | 96 | 0.349365 | [
"geometry",
"render"
] |
4e3b4473a99b4cae97cf33632290711a7688d092 | 3,185 | h | C | GIP/unused/GeoSpatialContext.h | akater320/gippy | 92f83e1107fb1b97475a427833e3a63d1644c62c | [
"Apache-2.0"
] | 89 | 2015-04-14T19:30:25.000Z | 2021-08-17T16:20:17.000Z | GIP/unused/GeoSpatialContext.h | akater320/gippy | 92f83e1107fb1b97475a427833e3a63d1644c62c | [
"Apache-2.0"
] | 85 | 2015-04-20T18:58:38.000Z | 2020-12-11T21:30:34.000Z | GIP/unused/GeoSpatialContext.h | akater320/gippy | 92f83e1107fb1b97475a427833e3a63d1644c62c | [
"Apache-2.0"
] | 23 | 2015-04-21T22:01:58.000Z | 2021-10-30T14:20:32.000Z | /*##############################################################################
# GIPPY: Geospatial Image Processing library for Python
#
# AUTHOR: Matthew Hanson
# EMAIL: matt.a.hanson@gmail.com
#
# Copyright (C) 2015 Applied Geosolutions
#
# 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 GIP_GEOSPATIALCONTEXT_H
#define GIP_GEOSPATIALCONTEXT_H
#include <gip/geometry.h>
namespace gip {
class GeoSpatialContext {
public:
/*
//! \name Constructors
GeoSpatialContext(GeoResource* resource) {
_GeoResource.reset(resource);
}
~GeoSpatialContext() {}
//! Geolocated coordinates of a point within the resource
Point<double> GeoLoc(float xloc, float yloc) const;
//! Coordinates of top left
Point<double> TopLeft() const;
//! Coordinates of lower left
Point<double> LowerLeft() const;
//! Coordinates of top right
Point<double> TopRight() const;
//! Coordinates of bottom right
Point<double> LowerRight() const;
//! Minimum Coordinates of X and Y
Point<double> MinXY() const;
//! Maximum Coordinates of X and Y
Point<double> MaxXY() const;
//! Return projection definition in Well Known Text format
string Projection() const {
return _GDALDataset->GetProjectionRef();
}
//! Set projection definition in Well Known Text format
GeoResource& SetProjection(string proj) {
_GDALDataset->SetProjection(proj.c_str());
return *this;
}
//! Return projection as OGRSpatialReference
OGRSpatialReference SRS() const;
//! Get Affine transformation
CImg<double> Affine() const {
double affine[6];
_GDALDataset->GetGeoTransform(affine);
return CImg<double>(&affine[0], 6);
}
//! Set Affine transformation
GeoResource& SetAffine(CImg<double> affine) {
_GDALDataset->SetGeoTransform(affine.data());
return *this;
}
GeoResource& SetAffine(double affine[6]) {
_GDALDataset->SetGeoTransform(affine);
return *this;
}
//! Get resolution convenience function
Point<double> Resolution() const;
//! Set coordinate system from another GeoResource
GeoResource& SetCoordinateSystem(const GeoResource& res);
private:
std::shared_ptr<GeoResource> _GeoResource;
*/
}; // class GeoSpatialContext
} // namespace gip
#endif
| 33.882979 | 80 | 0.60471 | [
"geometry"
] |
4e3c47e4897765173e81e8f21e29c36ea9c9f5a5 | 977 | h | C | ext/n7zip/controller.h | yagisumi/node-n7zip | d9648a99734115cead0c148fba6b0729a77eda1b | [
"MIT"
] | null | null | null | ext/n7zip/controller.h | yagisumi/node-n7zip | d9648a99734115cead0c148fba6b0729a77eda1b | [
"MIT"
] | 1 | 2020-10-16T17:26:54.000Z | 2020-10-16T17:26:54.000Z | ext/n7zip/controller.h | yagisumi/node-n7zip | d9648a99734115cead0c148fba6b0729a77eda1b | [
"MIT"
] | null | null | null | #pragma once
#include "common.h"
#include <condition_variable>
namespace n7zip {
class Controller : public Napi::ObjectWrap<Controller>
{
std::mutex m_mutex;
std::condition_variable m_cv;
bool m_paused;
bool m_canceled;
std::string m_task_name;
inline std::unique_lock<std::mutex> acquire_lock()
{
return std::unique_lock<std::mutex>(m_mutex);
}
public:
Controller(const Napi::CallbackInfo& info);
~Controller();
static Napi::FunctionReference constructor;
static Napi::Object Init(Napi::Env env, Napi::Object exports);
static Napi::Object New(Napi::Env, const char* task_name, bool paused);
Napi::Value TaskName(const Napi::CallbackInfo& info);
Napi::Value Cancel(const Napi::CallbackInfo& info);
Napi::Value Pause(const Napi::CallbackInfo& info);
Napi::Value Resume(const Napi::CallbackInfo& info);
void cancel();
bool is_canceled();
void pause();
bool is_paused();
void resume();
void wait();
};
} // namespace n7zip
| 23.829268 | 73 | 0.715455 | [
"object"
] |
4e40b617a10ae224f950ed52792aa27ed71f6336 | 2,573 | h | C | src/AGC/TCMarshalByValue.h | FreeAllegiance/AllegianceDX7 | 3955756dffea8e7e31d3a55fcf6184232b792195 | [
"MIT"
] | 76 | 2015-08-18T19:18:40.000Z | 2022-01-08T12:47:22.000Z | src/AGC/TCMarshalByValue.h | StudentAlleg/Allegiance | e91660a471eb4e57e9cea4c743ad43a82f8c7b18 | [
"MIT"
] | 37 | 2015-08-14T22:44:12.000Z | 2020-01-21T01:03:06.000Z | src/AGC/TCMarshalByValue.h | FreeAllegiance/Allegiance-AZ | 1d8678ddff9e2efc79ed449de6d47544989bc091 | [
"MIT"
] | 42 | 2015-08-13T23:31:35.000Z | 2022-03-17T02:20:26.000Z | #ifndef __TCMarshalByValue_h__
#define __TCMarshalByValue_h__
/////////////////////////////////////////////////////////////////////////////
// TCMarshalByValue.h | Declaration of the CTCMarshalByValue, which
// implements the CLSID_TCMarshalByValue component object.
#include "resource.h"
#include <AGC.h>
#include <..\TCLib\ObjectLock.h>
/////////////////////////////////////////////////////////////////////////////
// CTCMarshalByValue
class ATL_NO_VTABLE CTCMarshalByValue :
public IMarshal,
public CComCoClass<CTCMarshalByValue, &CLSID_TCMarshalByValue>,
public CComObjectRoot
{
// Declarations
public:
DECLARE_REGISTRY_RESOURCEID(IDR_TCMarshalByValue)
DECLARE_ONLY_AGGREGATABLE(CTCMarshalByValue)
// Category Map
public:
BEGIN_CATEGORY_MAP(CTCMarshalByValue)
IMPLEMENTED_CATEGORY(CATID_AGC)
END_CATEGORY_MAP()
// Interface Map
public:
BEGIN_COM_MAP(CTCMarshalByValue)
COM_INTERFACE_ENTRY(IMarshal)
END_COM_MAP()
// Construction / Destruction
public:
CTCMarshalByValue();
#if defined(_DEBUG) && defined(CTCMarshalByValue_DEBUG)
HRESULT CTCMarshalByValue::FinalConstruct();
void CTCMarshalByValue::FinalRelease();
#endif // defined(_DEBUG) && defined(CTCMarshalByValue_DEBUG)
// IMarshal Interface Methods
public:
STDMETHODIMP GetUnmarshalClass(REFIID riid, void* pv, DWORD dwDestContext,
void* pvDestContext, DWORD mshlflags, CLSID* pCid);
STDMETHODIMP GetMarshalSizeMax(REFIID riid, void* pv, DWORD dwDestContext,
void* pvDestContext, DWORD mshlflags, DWORD* pSize);
STDMETHODIMP MarshalInterface(IStream* pStm, REFIID riid, void* pv,
DWORD dwDestContext, void* pvDestContext, DWORD mshlflags);
STDMETHODIMP UnmarshalInterface(IStream* pStm, REFIID riid, void** ppv);
STDMETHODIMP ReleaseMarshalData(IStream* pStm);
STDMETHODIMP DisconnectObject(DWORD dwReserved);
// Implementation
protected:
HRESULT GetOuterPersistStream(IPersistStream** pps);
// Types
protected:
typedef TCObjectLock<CTCMarshalByValue> CLock;
// Data Members
protected:
DWORD m_dwEndian;
const DWORD m_dwEndianOriginal, m_dwEndianInverted;
};
/////////////////////////////////////////////////////////////////////////////
// Implementation
inline HRESULT CTCMarshalByValue::GetOuterPersistStream(IPersistStream** pps)
{
HRESULT hr = OuterQueryInterface(IID_IPersistStream, (void**)pps);
if (SUCCEEDED(hr))
return hr;
return OuterQueryInterface(IID_IPersistStreamInit, (void**)pps);
}
/////////////////////////////////////////////////////////////////////////////
#endif // !__TCMarshalByValue_h__
| 28.588889 | 77 | 0.690634 | [
"object"
] |
4e41950df9cfb51772b8c1a3553fa24a21366a84 | 10,572 | h | C | include/DG.h | vachan-potluri/MEANDG | a4a22653b5d71b186e179519b0d26a21d3faf1b5 | [
"BSD-3-Clause"
] | null | null | null | include/DG.h | vachan-potluri/MEANDG | a4a22653b5d71b186e179519b0d26a21d3faf1b5 | [
"BSD-3-Clause"
] | null | null | null | include/DG.h | vachan-potluri/MEANDG | a4a22653b5d71b186e179519b0d26a21d3faf1b5 | [
"BSD-3-Clause"
] | 4 | 2019-06-12T10:01:27.000Z | 2021-08-21T06:27:42.000Z | #ifndef DG_H
#define DG_H
#include "sysInclude.h"
#include "Point.h"
#include "Face.h"
#include "Cell.h"
#include "BoundaryConditions.h"
#include "GeometryIO.h"
#include "RefCell.h"
#include "RefFace.h"
#include "InternalFluxSolver.h"
#include "RiemannSolver.h"
class DG{
public:
// Global variables
// 0. Flags
// Flags for memory management
// Refer the destructor function of this class
// Flag returns 'true' if memory is allocated using 'new' method. Then delete is required to free the memory.
bool VariableNameFlag;
bool pointsFlag;
bool facesFlag;
bool cellsFlag;
bool bcondFlag;
bool laplaceFlag;
bool VariableSizeFlag;
bool cummulativeVariableSizeFlag;
bool variableFlag;
bool refVariableFlag;
// 1. Parameters related to geometrical data (or domain data)
/// Contains the location of the case
string path;
/// GeometryIO object for reading the data
Geometry Domain;
/// Array of points
Point* points;
/// Array of faces
Face* faces;
/// Array of cells
Cell* cells;
/// Array of boundary conditions
BoundaryConditions* bcond;
/// Number of points, faces, cells, boundaryFaces, internalFaces and boundaryConditions
int noOfPoints, noOfFaces, noOfCells, noOfBoundaryFaces, noOfBoundaryConditions, noOfInternalFaces;
/// Reference cells. Refer refCell.cpp and include/cellTypes.h for details
RefCell referenceCells[4];
/// Reference faces.
RefFace referenceFaces[2];
/// Shortest distance.
double shortestDistance;
/// Characteristic length
double charLength;
/// Characteristic speed
double charSpeed;
/// CFL number
double CFL;
// Constructor and destructor
/// Constructor function
DG(string path="/app/Tests/pitzDaily", int order=1, IntFlag::intflag intType = IntFlag::inexact);
///destructor function
~DG();
// Other functions
/// Get order of reconstruction
int getOrder()const;
/// Set order of reconstruction
void setOrder(int order);
/// Get path of the application
string getPath()const;
/// Set path of the application
void setPath(string path);
/// Setup reference cells array
void setupReferenceCellsArray();
/// Get pointer to reference cells array
RefCell* getReferenceCellsArray();
/// Setup reference faces array
void setupReferenceFacesArray();
/// Get pointer to reference faces array
RefFace* getReferenceFacesArray();
/// Set number of variables
void setNoOfVariable(int noOfVariable);
/// Get number of variables
int getNoOfVariable();
/// Setter function for name of the dependent variables
void setVariableName(string VariableName[]);
/// Setter function for the size of the variables
void setVariableSize(int VariableSize[]);
/// Set functional details
void setFunctionalDetails(int order, IntFlag::intflag intType, Solver::solver sol, System::system sys);
/// Assign system of equation. Sets the internal flux function.
void assignSystemOfEquations();
/// A function pointer for finding the internal flux. Points to the appropriate flux function specified in InternalFlux.h depending on the system of equation.
void (* findInternalFlux)(Cell *cell, int rkstep);
/// A function pointer for solving the Riemann solver. Points to the appropriate Riemann solver specified in RiemannSolvers.h depending on the system of equation and Riemann solver choice.
void (* solveRiemannProblem)(Face *face, int rkstep);
/// Assigns the appropriate Riemann solver.
void assignRiemannSolver();
/// Print all details
void printFunctionalDetails();
/// Set the time step for the simulation
void setDeltaT(double deltaT);
/// Get the time step for the simulation
double getDeltaT();
/// Set the starting time
void setStartTime(double startTime);
/// Get the starting time
double getStartTime();
/// Set the ending time
void setEndTime(double endTime);
/// Get the ending time
double getEndTime();
/// Set the time step after which data dumping is done
void setPrintTime(double printTime);
/// Get the time step after which data dumping is done
double getPrintTime();
/// Set the Integrator Type
void setIntegratorType(int integratorType);
/// Get the Integrator Type in string format
string getIntegratorType();
/// Get the numerical quadrature type (exact or inexact integration)
string getQuadratureType();
/// Total number of variables requiring time integration
void setTotNoOfVariableTimeInt(int totNoOfVariableTimeInt);
/// Get total number of variable
int getTotNoOfVariables();
/// Input all details regarding time step, time and integrator in a single function
void setTemporalDetails(double deltaT, double startTime, double endTime, double printTime, int integratorType);
/// Print all temporal details
void printTemporalDetails();
/// For calculating the total number of dependent variables if all were scalar quantitites
void addTotNoOfVariable();
// Allocating space to the 2D variable matrix
void allocateVariableArraySize();
/// Allocating space to the 2D variable matrix in boundary Element
void allocateBoundaryVariableArraySize();
/// File read from the given folder in OpenFOAM format. Default 0.
void readVariableArray(double Time = 0);
/// File written to Time folder in OpenFOAM format
void writeVariableArray(double Time);
/// File written to Time folder in OpenFOAM format
void writeVariableRefArray(double Time);
/// Assign variable to cell DOF locations
void assignVariabletoCell();
/// Integrate the cell variable over all DOF locations to get the average value of the cell variable
void integrateCellVariable();
/// A flux vector is configured for each face.
void assignFluxVectortoFace();
/// Create domain
/// Initializes arrays and fills data from the case file
void createDomain();
/// Prints the Geometry features
void printDomain();
/// Saves global (x,y,z) location for all the quadrature points for all the cells (3D)
void getQuadPointsGlobalLocation();
/// Saves global (x,y,z) location for all the DOF points for all the cells (3D)
void getDOFPointsGlobalLocation();
/// Calculate det(J) array for each cell. Stored in Cell::J
void calculateJacobian();
/// Calculate the inverse Jacobian (metric of transformation or dRST_by_dXYZ)
void calculateInverseJacobian();
/// Get global (x,y,z) location for all the quadrature points for all the faces (2D)
void getFaceQuadPointsGlobalLocation();
/// Saves global (x,y,z) location for all the DOF points for all the faces (2D)
void getFaceDOFPointsGlobalLocation();
/// Maps cell DOF points to face quadrature points (fills array mapOwner/NeighbourDOFPoints)
void mapFaceDOFPointsToCellDOFPoints();
/// Maps cell quadrature points to face quadrature points (fills array mapOwner/NeighbourQuadPoints)
void mapFaceQuadPointsToCellQuadPoints();
/// Calculate det(J) array for all the quadrature points on the face
void calculateFaceJacobian();
/// Get shortest distance
double getShortestDistance();
/// Get the characteristic length
double getCharacteristicLength();
/// Assign boundary condition functions (refer BoundaryConditions::func2bcond function pointer)
void assignBoundaryConditions();
/// Takes variable and size as input and generates space for variable vector
void generateVariableArray(int noOfVariable, string VariableName[], int VariableSize[]);
/// Assign a name for each face. If the face is one of the internal faces, then the name is "internal" else it is one of the boundary names
void assignFaceName();
/// Sets the 'noOfBoundaryFaces' in each cell. 0 for internal cells.
void assignNoOfBoundaryFacesToCells();
/// Reads variable arrays from folder 'Time'
void readData(double Time = 0.0);
/// Apply the initial conditions
void applyIC();
// Depends on the problem. For problems with IC as the reference solution, nothing is done
// since the variableRef array already stores IC.
// For problems with analytical solution avaialble, this is set to compute the error norms
void computeReferenceSolution(double time);
/// Computes L_infty, L_1 and L_2 errors between the solution and the variableRef array
void computeError();
/// Get error array
double* getError();
/// Array of errors for all the cells
double error[3];
/// Error history over time
TensorO2<double> ERROR;
/// Computes M,D,F,S matrices (and anything else that may be needed) for all cells
void computeCellMatrix();
/// Computes internal and Riemann fluxes at all the DOF locations
void computeFlux(int rkstep);
/// Computes the boundary conditions for all the faces
void computeBoundaryConditions(int rkstep);
/// Compute the flux residual (Res)
void computeRES(int rkStep);
/// Run the application (the binding function)
void runApplication();
/// Calculate the characteristic speed (for computation of CFL number)
void calculateCFL();
/// RK3 timestepping
void integratorRK3();
private:
// Variables
// 1. Control parameters
/// Order of the Interpolation method used
int order;
/// Integration type: 0=inexact, 1=exact integration.
IntFlag::intflag intType;
/// Which Riemann solver. Refer include/solvers.h
Solver::solver solverType;
/// Which system of equations. Refer include/systems.h
System::system systemType;
// 2. Parameters related to conserved (or primitive) variables
/// No of dependent variables
int noOfVariable, totNoOfVariable, totNoOfVariableTimeInt;
/// Name of dependent variables: Also serves as input files in folder 0
string* VariableName;
/// Variablesize = 1 for scalar, Variablesize > 1 for vector
TensorO1<int> VariableSize;
/// Cummulative variable size (including vector valued variables)
TensorO1<int> cummulativeVariableSize;
/// Saves all data of all dependent variables at cell centres
TensorO2<double> variable;
/// reference variable = analytical value (to compute numerical order)
// or previous time-step value (to compute residue)
TensorO2<double> variableRef;
// Analytical Sod's solution
TensorO2<double> SodAnalytical;
// 3. Temporal parameters
/// Starting time
double startTime;
/// Ending time
double endTime;
/// Delta time, timestep
double deltaT;
/// Time after which printing data is to be done
double printTime;
/// Integrator 0: Euler, 1-4: Runge Kutta
int integratorType;
};
#endif
| 31.652695 | 190 | 0.732028 | [
"geometry",
"object",
"vector",
"3d"
] |
4e42028041ce7dfd368f043f4c5d7dcd136e261d | 2,959 | h | C | saber/funcs/sroi_align.h | baajur/Anakin | 5fd68a6cc4c4620cd1a30794c1bf06eebd3f4730 | [
"Apache-2.0"
] | 533 | 2018-05-18T06:14:04.000Z | 2022-03-23T11:46:30.000Z | saber/funcs/sroi_align.h | baajur/Anakin | 5fd68a6cc4c4620cd1a30794c1bf06eebd3f4730 | [
"Apache-2.0"
] | 100 | 2018-05-26T08:32:48.000Z | 2022-03-17T03:26:25.000Z | saber/funcs/sroi_align.h | baajur/Anakin | 5fd68a6cc4c4620cd1a30794c1bf06eebd3f4730 | [
"Apache-2.0"
] | 167 | 2018-05-18T06:14:35.000Z | 2022-02-14T01:44:20.000Z | /* Copyright (c) 2018 Anakin Authors, Inc. 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 ANAKIN_SABER_FUNCS_SROI_ALIGN_H
#define ANAKIN_SABER_FUNCS_SROI_ALIGN_H
#include "saber/funcs/base.h"
#include "saber/funcs/impl/impl_base.h"
#include "saber/funcs/impl/impl_sroi_align.h"
#ifdef USE_X86_PLACE
#include "saber/funcs/impl/x86/saber_sroi_align.h"
#endif
#ifdef USE_ARM_PLACE
#include "saber/funcs/impl/arm/saber_sroi_align.h"
#endif
namespace anakin {
namespace saber {
template<typename TargetType,
DataType OpDtype>
class SRoiAlign : public BaseFunc<
TargetType,
OpDtype,
ImplBase,
SRoiAlignParam> {
public:
using BaseFunc<
TargetType,
OpDtype,
ImplBase,
SRoiAlignParam>::BaseFunc;
SRoiAlign() = default;
virtual SaberStatus compute_output_shape(
const std::vector<Tensor<TargetType> *> &input,
std::vector<Tensor<TargetType> *> &output,
SRoiAlignParam<TargetType> ¶m) override {
//input[1] is roi.
Shape output_shape = input[0]->valid_shape();
CHECK_EQ(input.size(), 2) << " input's size must be 2.";
int num_index = input[0]->num_index();
int channel_index = input[0]->channel_index();
int height_index = input[0]->height_index();
int width_index = input[0]->width_index();
output_shape[num_index] = input[1]->num();
output_shape[channel_index] = input[0]->channel();
output_shape[height_index] = param.pooled_h;
output_shape[width_index] = param.pooled_w;
return output[0]->set_shape_without_layout(output_shape);
}
virtual SaberStatus init_impl(ImplEnum implenum) override {
switch (implenum) {
case VENDER_IMPL:
this->_impl.push_back(new VenderSRoiAlign <TargetType, OpDtype>);
return SaberSuccess;
case SABER_IMPL:
this->_impl.push_back(new SaberSRoiAlign <TargetType, OpDtype>);
return SaberSuccess;
default:
return SaberUnImplError;
}
}
private:
virtual void pick_best_static() override {
this->_best_impl = this->_impl[0];
}
virtual void pick_best_specify(ImplEnum implenum) override {
this->_best_impl = this->_impl[0];
}
};
} // namespace saber
} // namespace anakin
#endif
| 29.009804 | 81 | 0.659344 | [
"shape",
"vector"
] |
4e4a178a075ee3f2c1802e06682b7bdf0ee09e5c | 15,854 | h | C | lib/Cinder/include/cinder/gl/Fbo.h | timmb/HarmonicMotion | 4ddf8ce98377260e57b6293d093a144a25ce3132 | [
"MIT"
] | 1 | 2018-07-20T03:56:15.000Z | 2018-07-20T03:56:15.000Z | lib/Cinder/include/cinder/gl/Fbo.h | timmb/HarmonicMotion | 4ddf8ce98377260e57b6293d093a144a25ce3132 | [
"MIT"
] | null | null | null | lib/Cinder/include/cinder/gl/Fbo.h | timmb/HarmonicMotion | 4ddf8ce98377260e57b6293d093a144a25ce3132 | [
"MIT"
] | null | null | null | /*
Copyright (c) 2010, The Barbarian Group
All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that
the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this list of conditions and
the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#pragma once
#include "cinder/Cinder.h"
#include "cinder/Exception.h"
#include "cinder/gl/gl.h"
#include "cinder/gl/Texture.h"
namespace cinder { namespace gl {
//! Represents an OpenGL Renderbuffer, used primarily in conjunction with FBOs. Supported on OpenGL ES but multisampling is currently ignored. \ImplShared
class Renderbuffer {
public:
//! Creates a NULL Renderbuffer
Renderbuffer() {}
//! Create a Renderbuffer \a width pixels wide and \a heigh pixels high, with an internal format of \a internalFormat, defaulting to GL_RGBA8
#if defined( CINDER_GLES )
Renderbuffer( int width, int height, GLenum internalFormat = GL_RGBA8_OES );
#else
Renderbuffer( int width, int height, GLenum internalFormat = GL_RGBA8 );
#endif
//! Create a Renderbuffer \a width pixels wide and \a heigh pixels high, with an internal format of \a internalFormat, defaulting to GL_RGBA8, MSAA samples \a msaaSamples, and CSAA samples \a coverageSamples
Renderbuffer( int width, int height, GLenum internalFormat, int msaaSamples, int coverageSamples = 0 );
//! Returns the width of the Renderbuffer in pixels
int getWidth() const { return mObj->mWidth; }
//! Returns the height of the Renderbuffer in pixels
int getHeight() const { return mObj->mHeight; }
//! Returns the size of the Renderbuffer in pixels
Vec2i getSize() const { return Vec2i( mObj->mWidth, mObj->mHeight ); }
//! Returns the bounding area of the Renderbuffer in pixels
Area getBounds() const { return Area( 0, 0, mObj->mWidth, mObj->mHeight ); }
//! Returns the aspect ratio of the Renderbuffer
float getAspectRatio() const { return mObj->mWidth / (float)mObj->mHeight; }
//! Returns the ID of the Renderbuffer
GLuint getId() const { return mObj->mId; }
//! Returns the internal format of the Renderbuffer
GLenum getInternalFormat() const { return mObj->mInternalFormat; }
//! Returns the number of samples used in MSAA-style antialiasing. Defaults to none, disabling multisampling
int getSamples() const { return mObj->mSamples; }
//! Returns the number of coverage samples used in CSAA-style antialiasing. Defaults to none.
int getCoverageSamples() const { return mObj->mCoverageSamples; }
private:
struct Obj {
Obj();
Obj( int aWidth, int aHeight, GLenum internalFormat, int msaaSamples, int coverageSamples );
~Obj();
int mWidth, mHeight;
GLuint mId;
GLenum mInternalFormat;
int mSamples, mCoverageSamples;
};
std::shared_ptr<Obj> mObj;
public:
//@{
//! Emulates shared_ptr-like behavior
typedef std::shared_ptr<Obj> Renderbuffer::*unspecified_bool_type;
operator unspecified_bool_type() const { return ( mObj.get() == 0 ) ? 0 : &Renderbuffer::mObj; }
void reset() { mObj.reset(); }
//@}
};
//! Represents an OpenGL Framebuffer Object. //! Represents an instance of a font at a point size. \ImplShared
class Fbo {
public:
struct Format;
//! Creates a NULL FBO
Fbo() {}
//! Creates an FBO \a width pixels wide and \a height pixels high, using Fbo::Format \a format
Fbo( int width, int height, Format format = Format() );
//! Creates an FBO \a width pixels wide and \a height pixels high, with an optional alpha channel, color buffer and depth buffer
Fbo( int width, int height, bool alpha, bool color = true, bool depth = true );
//! Returns the width of the FBO in pixels
int getWidth() const { return mObj->mWidth; }
//! Returns the height of the FBO in pixels
int getHeight() const { return mObj->mHeight; }
//! Returns the size of the FBO in pixels
Vec2i getSize() const { return Vec2i( mObj->mWidth, mObj->mHeight ); }
//! Returns the bounding area of the FBO in pixels
Area getBounds() const { return Area( 0, 0, mObj->mWidth, mObj->mHeight ); }
//! Returns the aspect ratio of the FBO
float getAspectRatio() const { return mObj->mWidth / (float)mObj->mHeight; }
//! Returns the Fbo::Format of this FBO
const Format& getFormat() const { return mObj->mFormat; }
//! Returns the texture target for this FBO. Typically \c GL_TEXTURE_2D or \c GL_TEXTURE_RECTANGLE_ARB
GLenum getTarget() const { return mObj->mFormat.mTarget; }
//! Returns a reference to the color texture of the FBO. \a attachment specifies which attachment in the case of multiple color buffers
Texture& getTexture( int attachment = 0 );
//! Returns a reference to the depth texture of the FBO.
Texture& getDepthTexture();
//! Binds the color texture associated with an Fbo to its target. Optionally binds to a multitexturing unit when \a textureUnit is non-zero. Optionally binds to a multitexturing unit when \a textureUnit is non-zero. \a attachment specifies which color buffer in the case of multiple attachments.
void bindTexture( int textureUnit = 0, int attachment = 0 );
//! Unbinds the texture associated with an Fbo's target
void unbindTexture();
//! Binds the depth texture associated with an Fbo to its target.
void bindDepthTexture( int textureUnit = 0 );
//! Binds the Fbo as the currently active framebuffer, meaning it will receive the results of all subsequent rendering until it is unbound
void bindFramebuffer();
//! Unbinds the Fbo as the currently active framebuffer, restoring the primary context as the target for all subsequent rendering
static void unbindFramebuffer();
//! Returns the ID of the framebuffer itself. For antialiased FBOs this is the ID of the output multisampled FBO
GLuint getId() const { return mObj->mId; }
#if ! defined( CINDER_GLES )
//! For antialiased FBOs this returns the ID of the mirror FBO designed for reading, where the multisampled render buffers are resolved to. For non-antialised, this is the equivalent to getId()
GLuint getResolveId() const { if( mObj->mResolveFramebufferId ) return mObj->mResolveFramebufferId; else return mObj->mId; }
//! Copies to FBO \a dst from \a srcArea to \a dstArea using filter \a filter. \a mask allows specification of color (\c GL_COLOR_BUFFER_BIT) and/or depth(\c GL_DEPTH_BUFFER_BIT). Calls glBlitFramebufferEXT() and is subject to its constraints and coordinate system.
void blitTo( Fbo dst, const Area &srcArea, const Area &dstArea, GLenum filter = GL_NEAREST, GLbitfield mask = GL_COLOR_BUFFER_BIT ) const;
//! Copies to the screen from Area \a srcArea to \a dstArea using filter \a filter. \a mask allows specification of color (\c GL_COLOR_BUFFER_BIT) and/or depth(\c GL_DEPTH_BUFFER_BIT). Calls glBlitFramebufferEXT() and is subject to its constraints and coordinate system.
void blitToScreen( const Area &srcArea, const Area &dstArea, GLenum filter = GL_NEAREST, GLbitfield mask = GL_COLOR_BUFFER_BIT ) const;
//! Copies from the screen from Area \a srcArea to \a dstArea using filter \a filter. \a mask allows specification of color (\c GL_COLOR_BUFFER_BIT) and/or depth(\c GL_DEPTH_BUFFER_BIT). Calls glBlitFramebufferEXT() and is subject to its constraints and coordinate system.
void blitFromScreen( const Area &srcArea, const Area &dstArea, GLenum filter = GL_NEAREST, GLbitfield mask = GL_COLOR_BUFFER_BIT );
#endif
//! Returns the maximum number of samples the graphics card is capable of using per pixel in MSAA for an Fbo
static GLint getMaxSamples();
//! Returns the maximum number of color attachments the graphics card is capable of using for an Fbo
static GLint getMaxAttachments();
struct Format {
public:
//! Default constructor, sets the target to \c GL_TEXTURE_2D with an 8-bit color+alpha, a 24-bit depth texture, and no multisampling or mipmapping
Format();
//! Set the texture target associated with the FBO. Defaults to \c GL_TEXTURE_2D, \c GL_TEXTURE_RECTANGLE_ARB is a common option as well
void setTarget( GLenum target ) { mTarget = target; }
//! Sets the GL internal format for the color buffer. Defaults to \c GL_RGBA8 (and \c GL_RGBA on OpenGL ES). Common options also include \c GL_RGB8 and \c GL_RGBA32F
void setColorInternalFormat( GLenum colorInternalFormat ) { mColorInternalFormat = colorInternalFormat; }
//! Sets the GL internal format for the depth buffer. Defaults to \c GL_DEPTH_COMPONENT24. Common options also include \c GL_DEPTH_COMPONENT16 and \c GL_DEPTH_COMPONENT32
void setDepthInternalFormat( GLenum depthInternalFormat ) { mDepthInternalFormat = depthInternalFormat; }
//! Sets the number of samples used in MSAA-style antialiasing. Defaults to none, disabling multisampling. Note that not all implementations support multisampling. Ignored on OpenGL ES.
void setSamples( int samples ) { mSamples = samples; }
//! Sets the number of coverage samples used in CSAA-style antialiasing. Defaults to none. Note that not all implementations support CSAA, and is currenlty Windows-only Nvidia. Ignored on OpenGL ES.
void setCoverageSamples( int coverageSamples ) { mCoverageSamples = coverageSamples; }
//! Enables or disables the creation of a color buffer for the FBO.. Creates multiple color attachments when \a numColorsBuffers >1, except on OpenGL ES which supports only 1.
void enableColorBuffer( bool colorBuffer = true, int numColorBuffers = 1 );
//! Enables or disables the creation of a depth buffer for the FBO. If \a asTexture the depth buffer is created as a gl::Texture, obtainable via getDepthTexture(). Not supported on OpenGL ES.
void enableDepthBuffer( bool depthBuffer = true, bool asTexture = true );
// void enableStencilBuffer( bool stencilBuffer = true ) { mStencilBuffer = stencilBuffer; }
//! Enables or disables mip-mapping for the FBO's textures
void enableMipmapping( bool enableMipmapping = true ) { mMipmapping = enableMipmapping; }
//! Sets the wrapping behavior for the FBO's textures. Possible values are \c GL_CLAMP, \c GL_REPEAT and \c GL_CLAMP_TO_EDGE. Default is \c GL_CLAMP_TO_EDGE.
void setWrap( GLenum wrapS, GLenum wrapT ) { setWrapS( wrapS ); setWrapT( wrapT ); }
/** \brief Sets the horizontal wrapping behavior for the FBO's textures. Default is \c GL_CLAMP_TO_EDGE.
Possible values are \c GL_CLAMP, \c GL_REPEAT and \c GL_CLAMP_TO_EDGE. **/
void setWrapS( GLenum wrapS ) { mWrapS = wrapS; }
/** \brief Sets the vertical wrapping behavior for the FBO's textures. Default is \c GL_CLAMP_TO_EDGE.
Possible values are \c GL_CLAMP, \c GL_REPEAT and \c GL_CLAMP_TO_EDGE. **/
void setWrapT( GLenum wrapT ) { mWrapT = wrapT; }
/** \brief Sets the minification filtering behavior for the FBO's textures. Default is \c GL_LINEAR:
* Possible values are \li \c GL_NEAREST \li \c GL_LINEAR \li \c GL_NEAREST_MIPMAP_NEAREST \li \c GL_LINEAR_MIPMAP_NEAREST \li \c GL_NEAREST_MIPMAP_LINEAR \li \c GL_LINEAR_MIPMAP_LINEAR **/
void setMinFilter( GLenum minFilter ) { mMinFilter = minFilter; }
/** Sets the magnification filtering behavior for the FBO's textures. Default is \c GL_LINEAR:
* Possible values are \li \c GL_NEAREST \li \c GL_LINEAR \li \c GL_NEAREST_MIPMAP_NEAREST \li \c GL_LINEAR_MIPMAP_NEAREST \li \c GL_NEAREST_MIPMAP_LINEAR \li \c GL_LINEAR_MIPMAP_LINEAR **/
void setMagFilter( GLenum magFilter ) { mMagFilter = magFilter; }
//! Returns the texture target associated with the FBO.
GLenum getTarget() const { return mTarget; }
//! Returns the GL internal format for the color buffer. Defaults to \c GL_RGBA8.
GLenum getColorInternalFormat() const { return mColorInternalFormat; }
//! Returns the GL internal format for the depth buffer. Defaults to \c GL_DEPTH_COMPONENT24.
GLenum getDepthInternalFormat() const { return mDepthInternalFormat; }
//! Returns the number of samples used in MSAA-style antialiasing. Defaults to none, disabling multisampling. OpenGL ES does not support multisampling.
int getSamples() const { return mSamples; }
//! Returns the number of coverage samples used in CSAA-style antialiasing. Defaults to none. OpenGL ES does not support multisampling.
int getCoverageSamples() const { return mCoverageSamples; }
//! Returns whether the FBO contains a color buffer
bool hasColorBuffer() const { return mNumColorBuffers > 0; }
//! Returns the number of color buffers
int getNumColorBuffers() const { return mNumColorBuffers; }
//! Returns whether the FBO contains a depth buffer
bool hasDepthBuffer() const { return mDepthBuffer; }
//! Returns whether the FBO contains a depth buffer implemened as a texture. Always \c false on OpenGL ES.
bool hasDepthBufferTexture() const { return mDepthBufferAsTexture; }
// bool hasStencilBuffer() const { return mStencilBuffer; }
//! Returns whether the contents of the FBO textures are mip-mapped.
bool hasMipMapping() const { return mMipmapping; }
protected:
GLenum mTarget;
GLenum mColorInternalFormat, mDepthInternalFormat;
int mSamples;
int mCoverageSamples;
bool mMipmapping;
bool mDepthBuffer, mDepthBufferAsTexture, mStencilBuffer;
int mNumColorBuffers;
GLenum mWrapS, mWrapT;
GLenum mMinFilter, mMagFilter;
friend class Fbo;
};
protected:
void init();
bool initMultisample( bool csaa );
void resolveTextures() const;
void updateMipmaps( bool bindFirst, int attachment ) const;
bool checkStatus( class FboExceptionInvalidSpecification *resultExc );
struct Obj {
Obj();
Obj( int aWidth, int aHeight );
~Obj();
int mWidth, mHeight;
Format mFormat;
GLuint mId;
GLuint mResolveFramebufferId;
std::vector<Renderbuffer> mMultisampleColorRenderbuffers;
Renderbuffer mMultisampleDepthRenderbuffer;
std::vector<Texture> mColorTextures;
Texture mDepthTexture;
Renderbuffer mDepthRenderbuffer;
mutable bool mNeedsResolve, mNeedsMipmapUpdate;
};
std::shared_ptr<Obj> mObj;
static GLint sMaxSamples, sMaxAttachments;
public:
//@{
//! Emulates shared_ptr-like behavior
typedef std::shared_ptr<Obj> Fbo::*unspecified_bool_type;
operator unspecified_bool_type() const { return ( mObj.get() == 0 ) ? 0 : &Fbo::mObj; }
void reset() { mObj.reset(); }
//@}
};
class FboException : public Exception {
};
class FboExceptionInvalidSpecification : public FboException {
public:
FboExceptionInvalidSpecification() : FboException() { mMessage[0] = 0; }
FboExceptionInvalidSpecification( const std::string &message ) throw();
virtual const char * what() const throw() { return mMessage; }
private:
char mMessage[256];
};
} } // namespace cinder::gl
| 57.028777 | 297 | 0.738615 | [
"render",
"object",
"vector"
] |
4e4eafd2079767dbd3f389d61a4fd0ddb5df7acd | 30,377 | c | C | Mavrx-DX4e/Mavrx-DX4e.c | meseta/mavrx-dx4e | f618e1e4fcabaca080f033d1a72db38828c7d2d4 | [
"Unlicense"
] | 2 | 2015-12-08T07:52:08.000Z | 2016-04-02T02:16:46.000Z | Mavrx-DX4e/Mavrx-DX4e.c | meseta/mavrx-dx4e | f618e1e4fcabaca080f033d1a72db38828c7d2d4 | [
"Unlicense"
] | null | null | null | Mavrx-DX4e/Mavrx-DX4e.c | meseta/mavrx-dx4e | f618e1e4fcabaca080f033d1a72db38828c7d2d4 | [
"Unlicense"
] | 3 | 2017-09-13T10:26:43.000Z | 2020-08-09T21:58:05.000Z | /*
* Mavrx_DX4e.c
*
* Created: 01/09/2013 23:43:32
* Author: Yuan
*/
/*
1 PD3 - Buzzer (should idle low to prevent unnecessary current drain)
2 PD4 - Trainer port detect (detects whether trainer port is plugged in, plugged in is low) active low
3 GND
4 VCC
5 GND
6 VCC
7 XTAL1
8 XTAL2
9 PD5 - BIND button (depressed is low, released is high) active low
10 PD6 - RATE switch (LO is low, HI is high)
11 PD7 - AUX switch (OFF is low, ON is high)
12 PB0 - THR REV switch (NOR is low, REV is high)
13 PB1 - AIL REV switch (NOR is low, REV is high)
14 PB2 - ELE REV switch (NOR is low, REV is high)
15 PB3 - RUD REV switch (NOR is low, REV is high), also ICSP MOSI (ensure switch is in REV position for ICSP)
16 PB4 - MIX switch (OFF is low, ON is high), also ICSP MISO (ensure switch is in ON position for ICSP)
17 PB5 - MD switch (MD-2 is low, MD-4 is high), also ICSP SCK (ensure switch is in MD-4 position for ICSP)
18 AVCC
19 ADC6 - battery voltage
20 AREF
21 GND
22 ADC7 - Throttle axis
23 PC0 - Green LED 1
24 PC1 - Green LED 2
25 PC2 - Red LED 0
26 PC3/ADC3 - Rudder axis
27 PC4/ADC4 - Elevator Axis
28 PC5/ADC5 - Aileron Axis
29 RESET
30 PD0 - Green LED 3
31 PD1/TXD - radio module
32 PD2 - trainer port (capacitor decoupled, and can be either input or output)
// battery voltage thresholds: 5.75V, 5.25V, 4.75V (brownout at 3.6V)
*/
#define F_CPU 8000000UL
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>
#define LED0On() PORTC &= ~0x04;
#define LED1On() PORTC &= ~0x01;
#define LED2On() PORTC &= ~0x02;
#define LED3On() PORTD &= ~0x01;
#define TRAINERPIN ((PIND >> 4) & 0x1)
#define BINDPIN ((PIND >> 5) & 0x1)
#define RATEPIN ((PIND >> 6) & 0x1)
#define AUXPIN ((PIND >> 7) & 0x1)
#define THROPIN ((PINB >> 0) & 0x1)
#define AILEPIN ((PINB >> 1) & 0x1)
#define ELEVPIN ((PINB >> 2) & 0x1)
#define RUDDPIN ((PINB >> 3) & 0x1)
#define MIXPIN ((PINB >> 4) & 0x1)
#define MDPIN ((PINB >> 5) & 0x1)
#define NOTE5C 239
#define NOTE5CS 225
#define NOTE5D 213
#define NOTE5DS 201
#define NOTE5E 190
#define NOTE5F 179
#define NOTE5FS 169
#define NOTE5G 159
#define NOTE5GS 150
#define NOTE5A 142
#define NOTE5AS 134
#define NOTE5B 127
#define NOTE6C 119
#define NOTE6CS 113
#define NOTE6D 106
#define NOTE6DS 100
#define NOTE6E 95
#define NOTE6F 89
#define NOTE6FS 84
#define NOTE6G 80
#define NOTE6GS 75
#define NOTE6A 71
#define NOTE6AS 67
#define NOTE6B 63
#define NOTE7C 60
#define NOTE7CS 56
#define NOTE7D 53
#define NOTE7DS 50
#define NOTE7E 47
#define NOTE7F 45
#define NOTE7FS 42
#define NOTE7G 40
#define NOTE7GS 38
#define NOTE7A 36
#define NOTE7AS 34
#define NOTE7B 32
#define NOTEPAUSE 1
#define NOTESTOP 0
#define OVERSAMPLE 10
void fastLoop(void);
void slowLoop(void);
void getADC(void);
uint8_t noteBuffer[20];
uint8_t noteCounter;
uint8_t noteInterruptable;
uint8_t LED0Duty = 0;
uint8_t LED1Duty = 0;
uint8_t LED2Duty = 0;
uint8_t LED3Duty = 0;
uint8_t battPulse;
uint16_t throVoltage;
uint16_t aileVoltage;
uint16_t elevVoltage;
uint16_t ruddVoltage;
uint8_t toggleCounter;
uint8_t rateSwitch; // 0 for LOW, 1 for HIGH, treat as active-low
uint8_t auxSwitch; // 0 for OFF, 1 for ON, treat as active-high
uint8_t bindSwitch; // 0 for pressed, treat as active-low
uint8_t throToggle; // 0 for NOR, 1 for REV, treat as active-low
uint8_t aileToggle; // 0 for NOR, 1 for REV, treat as active-low
uint8_t elevToggle; // 0 for NOR, 1 for REV, treat as active-low
uint8_t ruddToggle; // 0 for NOR, 1 for REV, treat as active-low
uint8_t mixToggle; // 0 for NOR, 1 for REV, treat as active-low
uint8_t mdToggle; // 0 for NOR, 1 for REV, treat as active-low
uint8_t mute;
uint8_t trainerPlugged;
uint8_t transmitMode; // 0 for normal, 1 for bind, 2 for trainer slave, 3 for trainer master
uint8_t uartBuffer[18];
uint8_t uartCounter;
uint8_t uartLength;
void LEDOff(void) {
PORTC |= 0x07;
PORTD |= 0x01;
}
void playNote(uint8_t note) {
if(mute == 0) {
TCCR2A = 0x12; // CTC mode toggle OC2B
if(OCR2A != note) {
OCR2A = note;
OCR2B = note;
TCNT2 = 0;
}
}
}
void stopNote(void) {
TCCR2A = 0x00; // disconnect OC2B
PORTD &= ~0x08; // set low
}
void twoTone(uint8_t note) {
if(noteInterruptable) {
noteBuffer[0] = note;
noteBuffer[1] = NOTEPAUSE;
noteBuffer[2] = note;
noteBuffer[3] = NOTESTOP;
noteCounter = 0;
noteInterruptable = 1;
}
}
void oneTone(uint8_t note) {
if(noteInterruptable) {
noteBuffer[0] = note;
noteBuffer[1] = NOTESTOP;
noteCounter = 0;
noteInterruptable = 1;
}
}
void paschaOvo(void);
int main(void) {
// Setup pins
DDRB = 0x00; // All pins inputs
DDRC = 0x07; // PC0,1,2 as outputs for the LEDs
DDRD = 0x0b; // PD0 as output for LED, PD1 for TXD, PD3 for buzzer
PORTD = 0xe0; // Pullups for switches
PORTB = 0x3f; // Pullups for switches
// LEDs
LEDOff();
// Buzzer
TCCR2B = 0x03; // prescaler at 64
stopNote();
noteBuffer[0] = NOTE6G;
noteBuffer[1] = NOTE6FS;
noteBuffer[2] = NOTE6DS;
noteBuffer[3] = NOTE5A;
noteBuffer[4] = NOTE5GS;
noteBuffer[5] = NOTE6E;
noteBuffer[6] = NOTE6GS;
noteBuffer[7] = NOTE7C;
noteBuffer[8] = NOTE7C;
noteBuffer[9] = NOTESTOP;
noteCounter = 0;
noteInterruptable = 0;
// ADC
ADMUX = 0x4f; // start off with mux on internal input
ADCSRA = 0x80; // ADC EN
DIDR0 = 0x38; // disable digital buffers on ADC pins
// Timer
TCCR0A = 0x00; // Normal mode
TCCR0B = 0x03; // prescaler at 64 results in 125kHz ticks
// UART
cli(); // disable global interrupts
UBRR0L = 3; UBRR0H = 0; // Baud at 125kbaud
UCSR0C = 0x06; // Async mode, 8N1
UCSR0B = 0x08; // TX enable
uartCounter = 0;
uartLength = 0;
// Get startup mode
trainerPlugged = TRAINERPIN;
bindSwitch = BINDPIN;
transmitMode = 0;
if(trainerPlugged == 0) transmitMode = 2;
if(bindSwitch == 0) transmitMode = 1;
// Timer loop!
static uint8_t fastScaler = 255;
static uint8_t slowScaler = 255;
while(1) {
TCNT0 = 0;
while(TCNT0 < 200) {
if(TCNT0 < 200 && TCNT0 >= 200-LED0Duty/4) LED0On(); // red LED too bright, reduce duty
if(TCNT0 < 200 && TCNT0 >= 200-LED1Duty) LED1On();
if(TCNT0 < 200 && TCNT0 >= 200-LED2Duty) LED2On();
if(TCNT0 < 200 && TCNT0 >= 200-LED3Duty) LED3On();
}
LEDOff();
// should be going at about 625Hz
getADC();
if(++fastScaler >= OVERSAMPLE) { // going at about 60Hz
fastScaler = 0;
if(++slowScaler >= 6) { // should be going at about 10Hz
slowScaler = 0;
slowLoop();
}
// this loop runs slower than 50Hz (actual time depends on how long it takes to run the code
fastLoop();
throVoltage = 0;
ruddVoltage = 0;
elevVoltage = 0;
aileVoltage = 0;
}
}
}
void getADC(void) {
// Get inputs and switches - the ADC is interleaved with switch stuff becase some delay is needed for the ADC cap to charge
ADMUX = 0x47; // select chan 7 Throttle
static uint8_t rateSwitchPrev = 3;
rateSwitch = RATEPIN;
if(rateSwitch != rateSwitchPrev) {
rateSwitchPrev = rateSwitch;
if(rateSwitch) oneTone(NOTE7C);
else twoTone(NOTE7C);
if(bindSwitch == 0) { // if bind button is held down and the rate switch toggled four times, enter range check mode
toggleCounter++;
if(toggleCounter == 4) {
noteBuffer[0] = NOTE5G;
noteBuffer[1] = NOTE5FS;
noteBuffer[2] = NOTE5F;
noteBuffer[3] = NOTE5E;
noteBuffer[4] = NOTE5DS;
noteBuffer[5] = NOTE5D;
noteBuffer[6] = NOTE5CS;
noteBuffer[7] = NOTE5C;
noteBuffer[8] = NOTESTOP;
noteCounter = 0;
noteInterruptable = 0;
}
else if(toggleCounter > 10) paschaOvo();
}
}
static uint8_t auxSwitchPrev = 3;
auxSwitch = AUXPIN;
if(auxSwitch != auxSwitchPrev) {
auxSwitchPrev = auxSwitch;
if(auxSwitch) twoTone(NOTE6E);
else oneTone(NOTE6E);
}
ADCSRA |= 0x40; // start
while(ADCSRA & 0x40); // wait for completion
throVoltage += ADC;
ADMUX = 0x43; // select chan 3 Rudder
static uint8_t bindSwitchPrev = 3;
bindSwitch = BINDPIN;
if(bindSwitch != bindSwitchPrev) {
bindSwitchPrev = bindSwitch;
if(bindSwitch) {
oneTone(NOTE6C);
toggleCounter = 0; // when releasing Bind switch, zero the toggle counter (for the range check mode)
if(transmitMode == 1) transmitMode = 0; // when releasing Bind switch, escape from bind mode
}
else oneTone(NOTE6G);
}
static uint8_t throTogglePrev = 3;
throToggle = THROPIN;
if(throToggle != throTogglePrev) {
throTogglePrev = throToggle;
if(throToggle) oneTone(NOTE5C);
else twoTone(NOTE5C);
}
ADCSRA |= 0x40; // start
while(ADCSRA & 0x40); // wait for completion
ruddVoltage += ADC;
ADMUX = 0x44; // select chan 4 Elevator
static uint8_t aileTogglePrev = 3;
aileToggle = AILEPIN;
if(aileToggle != aileTogglePrev) {
aileTogglePrev = aileToggle;
if(aileToggle) oneTone(NOTE5D);
else twoTone(NOTE5D);
}
static uint8_t elevTogglePrev = 3;
elevToggle = ELEVPIN;
if(elevToggle != elevTogglePrev) {
elevTogglePrev = elevToggle;
if(elevToggle) oneTone(NOTE5E);
else twoTone(NOTE5E);
}
static uint8_t ruddTogglePrev = 3;
ruddToggle = RUDDPIN;
if(ruddToggle != ruddTogglePrev) {
ruddTogglePrev = ruddToggle;
if(ruddToggle) oneTone(NOTE5F);
else twoTone(NOTE5F);
}
ADCSRA |= 0x40; // start
while(ADCSRA & 0x40); // wait for completion
elevVoltage += ADC;
ADMUX = 0x45; // select chan 5 Aileron
static uint8_t mixTogglePrev = 3;
mixToggle = MIXPIN;
if(mixToggle != mixTogglePrev) {
mixTogglePrev = mixToggle;
if(mixToggle) oneTone(NOTE5G);
else twoTone(NOTE5G);
}
static uint8_t mdTogglePrev = 3;
mdToggle = MDPIN; // mute
if(mdToggle != mdTogglePrev) {
mdTogglePrev = mdToggle;
if(mdToggle) mute = 1;
else {
mute = 0; // plays tone on unmute
if(noteInterruptable) {
noteBuffer[0] = NOTE6C;
noteBuffer[1] = NOTE7C;
noteBuffer[2] = NOTE7D;
noteBuffer[3] = NOTE7E;
noteBuffer[4] = NOTESTOP;
noteCounter = 0;
}
}
}
ADCSRA |= 0x40; // start
while(ADCSRA & 0x40); // wait for completion
aileVoltage += ADC;
}
void fastLoop(void) {
// Output to radio
uint16_t throV = throVoltage / OVERSAMPLE;
uint16_t aileV = 0x3ff - (aileVoltage / OVERSAMPLE);
uint16_t elevV = elevVoltage / OVERSAMPLE;
uint16_t ruddV = 0x3ff - (ruddVoltage / OVERSAMPLE);
switch(transmitMode) {
case 3: // in trainer master mode
if(rateSwitch == 0) { // rate swith in slave has control position
break;
}
// FALLTHROUGH! only falls through if rateSwitch is 1, i.e. master in control
case 0: // in normal mode
uartBuffer[0] = 0x18;
if(toggleCounter >= 4) uartBuffer[0] = 0x38; // in range check mode
uartBuffer[1] = 0x00;
uartBuffer[2] = 0x00 | ((throV >> 8) & 0x03);
uartBuffer[3] = ((throV) & 0xff);
uartBuffer[4] = 0x04 | ((aileV >> 8) & 0x03);
uartBuffer[5] = ((aileV) & 0xff);
uartBuffer[6] = 0x08 | ((elevV >> 8) & 0x03);
uartBuffer[7] = ((elevV) & 0xff);
uartBuffer[8] = 0x0c | ((ruddV >> 8) & 0x03);
uartBuffer[9] = ((ruddV) & 0xff);
if(mixToggle) { // in mix mode, send the four front switches mixed into the bind channel, and the rate switch mixed into the aux channel
uartBuffer[10] = 0x10;
if(auxSwitch == 0) uartBuffer[10] |= 0x03;
uartBuffer[11] = (rateSwitch << 4);
uartBuffer[12] = 0x14;
if(bindSwitch == 0) uartBuffer[12] |= 0x03;
uartBuffer[13] = (throToggle << 7) | (aileToggle << 6) | (elevToggle << 5) | (ruddToggle << 4);
}
else {
if(auxSwitch) {
uartBuffer[10] = 0x10;
uartBuffer[11] = 0xaa;
}
else {
uartBuffer[10] = 0x13;
uartBuffer[11] = 0x54;
}
if(bindSwitch) {
uartBuffer[12] = 0x14;
uartBuffer[13] = 0xaa;
}
else {
uartBuffer[12] = 0x17;
uartBuffer[13] = 0x54;
}
}
uartCounter = 0;
uartLength = 14;
break;
case 1: // in bind mode
uartBuffer[0] = 0x98;
uartBuffer[1] = 0x00;
uartBuffer[2] = 0x00;
uartBuffer[3] = 0x00;
uartBuffer[4] = 0x05;
uartBuffer[5] = 0xff;
uartBuffer[6] = 0x09;
uartBuffer[7] = 0xff;
uartBuffer[8] = 0x0d;
uartBuffer[9] = 0xff;
uartBuffer[10] = 0x10;
uartBuffer[11] = 0xaa;
uartBuffer[12] = 0x14;
uartBuffer[13] = 0xaa;
uartCounter = 0;
uartLength = 14;
break;
case 2: // in trainer slave mode
uartCounter = 0;
uartLength = 0;
break;
}
while(uartCounter < uartLength) {
while((UCSR0A & 0x20) == 0);
UDR0 = uartBuffer[uartCounter++];
}
// Power LED - pulses depending on battery level
static uint8_t LED0Dir = 1;
if(LED0Dir) {
if(LED0Duty > 100) LED0Dir = 0;
else LED0Duty += battPulse;
}
else {
if(LED0Duty < battPulse) LED0Dir = 1;
else LED0Duty -= battPulse;
}
// LED1 - is on for range check or bind mode (solid for range check, pulse for bind)
static uint8_t LED1Dir = 0;
if(transmitMode == 1) {// bind mode
if(LED1Dir) {
if(LED1Duty > 100) LED1Dir = 0;
else LED1Duty += 10;
}
else {
if(LED1Duty < 10) LED1Dir = 1;
else LED1Duty -= 10;
}
}
else if(toggleCounter >= 4) { // range check
LED1Dir = 1;
if(LED1Duty <= 190) LED1Duty+=10;
}
else {
LED1Dir = 0;
if(LED1Duty >= 10) LED1Duty-=10;
}
// LED2 - is on in trainer mode, pulses when slave is in control
static uint8_t LED2Dir = 0;
if(trainerPlugged) { // trainer unplugged, LED fades off
LED2Dir = 0;
if(LED2Duty >= 10) LED2Duty-=10;
}
else { // trainer plugged
if(transmitMode == 3 && rateSwitch == 0) { // LED pulses in traner master mode and slave in control
if(LED2Dir) {
if(LED2Duty > 100) LED2Dir = 0;
else LED2Duty += 10;
}
else {
if(LED2Duty < 10) LED2Dir = 1;
else LED2Duty -= 10;
}
}
else {
// LED is on (trainer slave mode, or trainer master mode but master in control)
LED2Dir = 1;
if(LED2Duty <= 190) LED2Duty+=10;
}
}
// LED3 - mode indicator for the MIX switch
static uint8_t LED3Dir = 0;
LED3Dir = mixToggle;
if(LED3Dir) {
if(LED3Duty <= 190) LED3Duty+=10;
}
else {
if(LED3Duty >= 10) LED3Duty-=10;
}
}
void slowLoop(void) {
// Read battery voltage
ADMUX = 0x46; // select chan 6
ADCSRA |= 0x40; // start
while(ADCSRA & 0x40); // wait for completion
uint8_t level = ADC >> 2; // note: level is now approx 26.1x the actual voltage
// Battery level pulse speeds
if(level > 150) battPulse = 1; // slow pulse
else if(level > 137) battPulse = 2;
else if(level > 120) battPulse = 4;
else {
battPulse = 24; // very fast pulses
if(noteBuffer[noteCounter] == 0) {
noteBuffer[0] = NOTEPAUSE;
noteBuffer[1] = NOTEPAUSE;
noteBuffer[2] = NOTEPAUSE;
noteBuffer[3] = NOTEPAUSE;
noteBuffer[4] = NOTEPAUSE;
noteBuffer[5] = NOTEPAUSE;
noteBuffer[6] = NOTEPAUSE;
noteBuffer[7] = NOTEPAUSE;
noteBuffer[8] = NOTEPAUSE;
noteBuffer[9] = NOTE5C;
noteBuffer[10] = NOTE5C;
noteBuffer[11] = NOTE5CS;
noteBuffer[12] = NOTE5CS;
noteBuffer[13] = NOTESTOP;
noteCounter = 0;
noteInterruptable = 1;
}
}
// Check trainer plug plug
static uint8_t trainerPluggedPrev;
trainerPlugged = TRAINERPIN;
if(trainerPlugged != trainerPluggedPrev) {
trainerPluggedPrev = trainerPlugged;
if(trainerPlugged) {
// Not Plugged IN
if(noteInterruptable) {
noteBuffer[0] = NOTE6C;
noteBuffer[1] = NOTE7C;
noteBuffer[2] = NOTE6C;
noteBuffer[3] = NOTESTOP;
noteCounter = 0;
}
if(transmitMode == 2 || transmitMode == 3) transmitMode = 0; // escape out of trainer mode
}
else {
// Plugged IN
noteBuffer[0] = NOTE6C; // these notes interrupt the startup tune, this is by design
noteBuffer[1] = NOTE6C;
noteBuffer[2] = NOTE7C;
noteBuffer[3] = NOTESTOP;
noteCounter = 0;
noteInterruptable = 0;
if(transmitMode == 0) transmitMode = 3; // enter trainer mode
}
}
// Beeps while toggling or binding beeps
if(toggleCounter >= 4 || transmitMode == 1) {
if(noteBuffer[noteCounter] == 0) {
noteBuffer[0] = NOTEPAUSE;
noteBuffer[1] = NOTEPAUSE;
noteBuffer[2] = NOTEPAUSE;
noteBuffer[3] = NOTEPAUSE;
noteBuffer[4] = NOTEPAUSE;
noteBuffer[5] = NOTEPAUSE;
noteBuffer[6] = NOTEPAUSE;
noteBuffer[7] = NOTEPAUSE;
noteBuffer[8] = NOTEPAUSE;
noteBuffer[9] = NOTE5C;
noteBuffer[10] = NOTESTOP;
noteCounter = 0;
noteInterruptable = 1;
}
}
// Play sounds
if(noteBuffer[noteCounter] > 0) {
if(noteBuffer[noteCounter] == NOTEPAUSE) {
stopNote();
}
else {
playNote(noteBuffer[noteCounter]);
}
noteCounter++;
}
else {
stopNote();
noteInterruptable = 1;
}
}
#define GAP 20
#define SEMIQUAVER 110
#define QUAVER 2*SEMIQUAVER
#define CROTCHET 2*QUAVER
#define MINIM 2*CROTCHET
#define BREVE 2*MINIM
#define TRIPLET CROTCHET/3
void paschaOvo(void) {
stopNote(); _delay_ms(CROTCHET);
playNote(NOTE5AS); _delay_ms(MINIM - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE5AS); _delay_ms(TRIPLET - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE5AS); _delay_ms(TRIPLET - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE5AS); _delay_ms(TRIPLET - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE5AS); _delay_ms(QUAVER + SEMIQUAVER);
playNote(NOTE5GS); _delay_ms(SEMIQUAVER);
playNote(NOTE5AS); _delay_ms(CROTCHET);
stopNote(); _delay_ms(QUAVER);
playNote(NOTE5AS); _delay_ms(TRIPLET - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE5AS); _delay_ms(TRIPLET - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE5AS); _delay_ms(TRIPLET - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE5AS); _delay_ms(QUAVER + SEMIQUAVER);
playNote(NOTE5GS); _delay_ms(SEMIQUAVER);
playNote(NOTE5AS); _delay_ms(CROTCHET);
stopNote(); _delay_ms(QUAVER);
playNote(NOTE5AS); _delay_ms(TRIPLET - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE5AS); _delay_ms(TRIPLET - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE5AS); _delay_ms(TRIPLET - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE5AS); _delay_ms(QUAVER);
playNote(NOTE5F); _delay_ms(SEMIQUAVER - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE5F); _delay_ms(SEMIQUAVER - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE5F); _delay_ms(QUAVER - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE5F); _delay_ms(QUAVER - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE5F); _delay_ms(QUAVER - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE5F); _delay_ms(QUAVER - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE5F); _delay_ms(QUAVER - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE5F); _delay_ms(QUAVER - GAP);
stopNote(); _delay_ms(GAP);
while(1) {
playNote(NOTE5AS); _delay_ms(SEMIQUAVER);
stopNote(); _delay_ms(SEMIQUAVER + QUAVER);
playNote(NOTE5F); _delay_ms(CROTCHET + QUAVER);
playNote(NOTE5AS); _delay_ms(QUAVER - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE5AS); _delay_ms(SEMIQUAVER);
playNote(NOTE6C); _delay_ms(SEMIQUAVER);
playNote(NOTE6D); _delay_ms(SEMIQUAVER);
playNote(NOTE6DS); _delay_ms(SEMIQUAVER);
playNote(NOTE6F); _delay_ms(MINIM - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE6F); _delay_ms(QUAVER - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE6F); _delay_ms(QUAVER - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE6F); _delay_ms(TRIPLET);
playNote(NOTE6FS); _delay_ms(TRIPLET);
playNote(NOTE6GS); _delay_ms(TRIPLET);
playNote(NOTE6AS); _delay_ms(MINIM + QUAVER - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE6AS); _delay_ms(QUAVER - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE6AS); _delay_ms(TRIPLET);
playNote(NOTE6GS); _delay_ms(TRIPLET);
playNote(NOTE6FS); _delay_ms(TRIPLET);
playNote(NOTE6GS); _delay_ms(QUAVER + SEMIQUAVER);
playNote(NOTE6FS); _delay_ms(SEMIQUAVER);
playNote(NOTE6F); _delay_ms(CROTCHET + QUAVER);
stopNote(); _delay_ms(QUAVER);
playNote(NOTE6F); _delay_ms(CROTCHET);
playNote(NOTE6DS); _delay_ms(SEMIQUAVER);
stopNote(); _delay_ms(SEMIQUAVER);
playNote(NOTE6DS); _delay_ms(SEMIQUAVER);
playNote(NOTE6F); _delay_ms(SEMIQUAVER);
playNote(NOTE6FS); _delay_ms(MINIM);
playNote(NOTE6F); _delay_ms(QUAVER);
playNote(NOTE6DS); _delay_ms(QUAVER);
playNote(NOTE6CS); _delay_ms(SEMIQUAVER);
stopNote(); _delay_ms(SEMIQUAVER);
playNote(NOTE6CS); _delay_ms(SEMIQUAVER);
playNote(NOTE6DS); _delay_ms(SEMIQUAVER);
playNote(NOTE6F); _delay_ms(MINIM);
playNote(NOTE6DS); _delay_ms(QUAVER);
playNote(NOTE6CS); _delay_ms(QUAVER);
playNote(NOTE6C); _delay_ms(SEMIQUAVER);
stopNote(); _delay_ms(SEMIQUAVER);
playNote(NOTE6C); _delay_ms(SEMIQUAVER);
playNote(NOTE6D); _delay_ms(SEMIQUAVER);
playNote(NOTE6E); _delay_ms(MINIM);
playNote(NOTE6G); _delay_ms(CROTCHET);
playNote(NOTE6F); _delay_ms(QUAVER);
playNote(NOTE5F); _delay_ms(SEMIQUAVER - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE5F); _delay_ms(SEMIQUAVER - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE5F); _delay_ms(QUAVER - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE5F); _delay_ms(SEMIQUAVER - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE5F); _delay_ms(SEMIQUAVER - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE5F); _delay_ms(QUAVER - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE5F); _delay_ms(SEMIQUAVER - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE5F); _delay_ms(SEMIQUAVER - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE5F); _delay_ms(QUAVER - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE5F); _delay_ms(QUAVER - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE5AS); _delay_ms(SEMIQUAVER);
stopNote(); _delay_ms(SEMIQUAVER + QUAVER);
playNote(NOTE5F); _delay_ms(CROTCHET + QUAVER);
playNote(NOTE5AS); _delay_ms(QUAVER - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE5AS); _delay_ms(SEMIQUAVER);
playNote(NOTE6C); _delay_ms(SEMIQUAVER);
playNote(NOTE6D); _delay_ms(SEMIQUAVER);
playNote(NOTE6DS); _delay_ms(SEMIQUAVER);
playNote(NOTE6F); _delay_ms(MINIM - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE6F); _delay_ms(QUAVER - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE6F); _delay_ms(QUAVER - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE6F); _delay_ms(TRIPLET);
playNote(NOTE6FS); _delay_ms(TRIPLET);
playNote(NOTE6GS); _delay_ms(TRIPLET);
playNote(NOTE6AS); _delay_ms(MINIM + CROTCHET);
playNote(NOTE7CS); _delay_ms(CROTCHET);
playNote(NOTE7C); _delay_ms(SEMIQUAVER);
stopNote(); _delay_ms(SEMIQUAVER + QUAVER);
playNote(NOTE6A); _delay_ms(MINIM);
playNote(NOTE6F); _delay_ms(CROTCHET);
playNote(NOTE6FS); _delay_ms(MINIM + CROTCHET);
playNote(NOTE6AS); _delay_ms(CROTCHET);
playNote(NOTE6A); _delay_ms(SEMIQUAVER);
stopNote(); _delay_ms(SEMIQUAVER + QUAVER);
playNote(NOTE6F); _delay_ms(MINIM - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE6F); _delay_ms(CROTCHET);
playNote(NOTE6FS); _delay_ms(MINIM + CROTCHET);
playNote(NOTE6AS); _delay_ms(CROTCHET);
playNote(NOTE6A); _delay_ms(SEMIQUAVER);
stopNote(); _delay_ms(SEMIQUAVER + QUAVER);
playNote(NOTE6F); _delay_ms(MINIM);
playNote(NOTE6D); _delay_ms(CROTCHET);
playNote(NOTE6DS); _delay_ms(MINIM + CROTCHET);
playNote(NOTE6FS); _delay_ms(CROTCHET);
playNote(NOTE6F); _delay_ms(SEMIQUAVER);
stopNote(); _delay_ms(SEMIQUAVER + QUAVER);
playNote(NOTE6CS); _delay_ms(MINIM);
playNote(NOTE5AS); _delay_ms(CROTCHET);
playNote(NOTE6C); _delay_ms(SEMIQUAVER);
stopNote(); _delay_ms(SEMIQUAVER);
playNote(NOTE6C); _delay_ms(SEMIQUAVER);
playNote(NOTE6D); _delay_ms(SEMIQUAVER);
playNote(NOTE6E); _delay_ms(MINIM);
playNote(NOTE6G); _delay_ms(CROTCHET);
playNote(NOTE6F); _delay_ms(QUAVER);
playNote(NOTE5F); _delay_ms(SEMIQUAVER - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE5F); _delay_ms(SEMIQUAVER - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE5F); _delay_ms(QUAVER - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE5F); _delay_ms(SEMIQUAVER - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE5F); _delay_ms(SEMIQUAVER - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE5F); _delay_ms(QUAVER - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE5F); _delay_ms(SEMIQUAVER - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE5F); _delay_ms(SEMIQUAVER - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE5F); _delay_ms(QUAVER - GAP);
stopNote(); _delay_ms(GAP);
playNote(NOTE5F); _delay_ms(QUAVER - GAP);
stopNote(); _delay_ms(GAP);
}
} | 34.480136 | 149 | 0.542614 | [
"solid"
] |
4e53acaa4d97f3fa38fdbe29cfbca6e16a77a699 | 3,085 | h | C | include/mgos_ade7953.h | ALLTERCO/ade7953 | b8864e9851950c65372148dc9af8055cee12978d | [
"Apache-2.0"
] | null | null | null | include/mgos_ade7953.h | ALLTERCO/ade7953 | b8864e9851950c65372148dc9af8055cee12978d | [
"Apache-2.0"
] | 3 | 2020-08-13T12:44:49.000Z | 2022-01-19T17:19:29.000Z | include/mgos_ade7953.h | ALLTERCO/ade7953 | b8864e9851950c65372148dc9af8055cee12978d | [
"Apache-2.0"
] | 2 | 2020-08-13T12:30:51.000Z | 2021-11-30T07:28:30.000Z | /*
* Copyright 2020 Pim van Pelt <pim@ipng.nl>
*
* 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
#ifdef __cplusplus
extern "C" {
#endif
#include <stdbool.h>
#include <stdint.h>
struct mgos_ade7953;
enum ade7953_pga_gain {
MGOS_ADE7953_PGA_GAIN_1 = 0x00,
MGOS_ADE7953_PGA_GAIN_2 = 0x01,
MGOS_ADE7953_PGA_GAIN_4 = 0x02,
MGOS_ADE7953_PGA_GAIN_8 = 0x03,
MGOS_ADE7953_PGA_GAIN_16 = 0x04,
MGOS_ADE7953_PGA_GAIN_22 = 0x05
};
#if MGOS_ADE7953_ENABLE_I2C
// Create an instance of the driver at the given I2C bus and address.
// Returns a pointer to the object upon success, NULL otherwise.
#include "mgos_i2c.h"
struct mgos_ade7953 *mgos_ade7953_create_i2c(struct mgos_i2c *i2c, const struct mgos_config_ade7953 *cfg);
#define mgos_ade7953_create mgos_ade7953_create_i2c
#endif
#if MGOS_ADE7953_ENABLE_SPI
#include "mgos_spi.h"
struct mgos_ade7953 *mgos_ade7953_create_spi(struct mgos_spi *spi, int cs, const struct mgos_config_ade7953 *cfg);
#endif
// Write the detected voltage in Volts RMS in the *volts pointer.
// Returns true on success, false otherwise.
bool mgos_ade7953_get_voltage(struct mgos_ade7953 *dev, float *volts);
// Write the detected line frequency in Hertz to the *hertz pointer.
// Returns true on success, false otherwise.
bool mgos_ade7953_get_frequency(struct mgos_ade7953 *dev, float *hertz);
// Write the measured RMS current for the given channel (0 or 1), in Amperes
// to the *amperes pointer.
// Returns true on success, false otherwise.
bool mgos_ade7953_get_current(struct mgos_ade7953 *dev, int channel, float *amperes);
// Write the instantaneous active power value, in Watts, to *watts.
bool mgos_ade7953_get_apower(struct mgos_ade7953 *dev, int channel, float *watts);
// Write the accumulated active energy, in watt-hours, to *wh.
// If reset is true, resets the accumulator.
bool mgos_ade7953_get_aenergy(struct mgos_ade7953 *dev, int channel, bool reset, float *wh);
// Write the measured power factor to the *pf pointer.
// Power factor is a dimensionless number in the closed interval of −1 to 1.
// Returns true on success, false otherwise.
bool mgos_ade7953_get_pf(struct mgos_ade7953 *dev, int channel, float *pf);
// Advanced usage: functions to read/write ADE7953 registers.
bool mgos_ade7953_read_reg(struct mgos_ade7953 *dev, uint16_t reg, bool is_signed, int32_t *val);
bool mgos_ade7953_write_reg(struct mgos_ade7953 *dev, uint16_t reg, int32_t val);
// Clean up the driver and return memory used for it.
bool mgos_ade7953_destroy(struct mgos_ade7953 **dev);
#ifdef __cplusplus
}
#endif
| 35.872093 | 114 | 0.774392 | [
"object"
] |
4e57b7fdf8b0b4117cf4f0c0be3e2a083df518aa | 3,267 | h | C | coh2_rgt_extractor/Rainman_src/CChunkyFile.h | tranek/coh2_rgt_extractor | dba2db9a06d3f31fb815ca865181d8f631306522 | [
"MIT"
] | 1 | 2016-09-24T14:57:56.000Z | 2016-09-24T14:57:56.000Z | coh2_rgt_extractor/Rainman_src/CChunkyFile.h | tranek/coh2_rgt_extractor | dba2db9a06d3f31fb815ca865181d8f631306522 | [
"MIT"
] | null | null | null | coh2_rgt_extractor/Rainman_src/CChunkyFile.h | tranek/coh2_rgt_extractor | dba2db9a06d3f31fb815ca865181d8f631306522 | [
"MIT"
] | null | null | null | /*
Rainman Library
Copyright (C) 2006 Corsix <corsix@gmail.com>
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 Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef _CHUNKY_FILE_H_
#define _CHUNKY_FILE_H_
#include "gnuc_defines.h"
#include "CMemoryStore.h"
#include "Exception.h"
#include <vector>
class RAINMAN_API CChunkyFile
{
public:
CChunkyFile();
~CChunkyFile();
void Load(IFileStore::IStream* pStream);
void Save(IFileStore::IOutputStream* pStream);
void New(long iVersion);
class RAINMAN_API CChunk
{
public:
CChunk();
~CChunk();
enum eTypes
{
T_Folder,
T_Data
};
// Applicable to all
eTypes GetType() const;
const char* GetName() const;
long GetVersion() const;
const char* GetDescriptor() const;
void SetVersion(long iValue);
void SetDescriptor(const char* sValue);
void SetUnknown1(long iValue);
// Only applicable to T_Data
CMemoryStore::CStream* GetData();
char* GetDataRaw();
unsigned long GetDataLength();
void SetData(CMemoryStore::COutStream* pStream);
// Only applicable to T_Folder
size_t GetChildCount() const;
CChunk* GetChild(size_t iN) const;
CChunk* GetChildByName(const char* sName, eTypes eType) const;
CChunk* AppendNew(const char* sName, CChunk::eTypes eType);
CChunk* InsertBefore(size_t iBefore, const char* sName, CChunk::eTypes eType);
void RemoveChild(size_t iN);
protected:
friend class CChunkyFile;
//! Read one chunk from file
/*!
Reads one FOLDxxxx or DATAxxxx chunk from the stream.
If it is a FOLDxxxx chunk then all the children will be read aswell,
if it is a DATAxxxx chunk then the chunk data will be read into memory.
\param[in] pStream Input stream
\return Returns true if all went well, false if the very first read operation gave an error (eg. end of stream), throws an exception for all other errors.
*/
bool _Load(IFileStore::IStream* pStream, long iChunkyVersion);
void _Save(IFileStore::IOutputStream* pStream);
unsigned long _FoldUpdateSize();
eTypes m_eType;
char m_sName[5];
char* m_sDescriptor;
long m_iVersion;
long m_iUnknown1, m_iUnknown2;
char* m_pData;
unsigned long m_iDataLength;
std::vector<CChunk*> m_vChildren;
};
long GetVersion() const;
size_t GetChildCount() const;
CChunk* GetChild(size_t iN) const;
CChunk* GetChildByName(const char* sName, CChunk::eTypes eType) const;
void RemoveChild(size_t iN);
CChunk* AppendNew(const char* sName, CChunk::eTypes eType);
protected:
char m_sHeader[17];
long m_iVersion;
long m_iUnknown1, m_iUnknown2, m_iUnknown3, m_iUnknown4;
std::vector<CChunk*> m_vChunks;
};
#endif // #ifndef _CHUNKY_FILE_H_
| 25.928571 | 157 | 0.745638 | [
"vector"
] |
4e5d4d9752e399ab4468af1edf2deb1e3d85e356 | 2,765 | h | C | vendor/chromium/mojo/public/cpp/bindings/pending_associated_receiver.h | thorium-cfx/fivem | 587eb7c12066a2ebf8631bde7bb39ee2df1b5a0c | [
"MIT"
] | 5,411 | 2017-04-14T08:57:56.000Z | 2022-03-30T19:35:15.000Z | vendor/chromium/mojo/public/cpp/bindings/pending_associated_receiver.h | thorium-cfx/fivem | 587eb7c12066a2ebf8631bde7bb39ee2df1b5a0c | [
"MIT"
] | 802 | 2017-04-21T14:18:36.000Z | 2022-03-31T21:20:48.000Z | vendor/chromium/mojo/public/cpp/bindings/pending_associated_receiver.h | thorium-cfx/fivem | 587eb7c12066a2ebf8631bde7bb39ee2df1b5a0c | [
"MIT"
] | 2,011 | 2017-04-14T09:44:15.000Z | 2022-03-31T15:40:39.000Z | // Copyright 2019 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 MOJO_PUBLIC_CPP_BINDINGS_PENDING_ASSOCIATED_RECEIVER_H_
#define MOJO_PUBLIC_CPP_BINDINGS_PENDING_ASSOCIATED_RECEIVER_H_
#include <stdint.h>
#include <utility>
#include "base/macros.h"
#include "mojo/public/cpp/bindings/associated_interface_request.h"
#include "mojo/public/cpp/bindings/scoped_interface_endpoint_handle.h"
namespace mojo {
// PendingAssociatedReceiver represents an unbound associated interface
// endpoint that will receive and queue messages. An AssociatedReceiver can
// consume this object to begin receiving method calls from a corresponding
// AssociatedRemote.
template <typename Interface>
class PendingAssociatedReceiver {
public:
PendingAssociatedReceiver() = default;
PendingAssociatedReceiver(PendingAssociatedReceiver&& other)
: handle_(std::move(other.handle_)) {}
explicit PendingAssociatedReceiver(ScopedInterfaceEndpointHandle handle)
: handle_(std::move(handle)) {}
// Temporary implicit move constructor to aid in converting from use of
// InterfaceRequest<Interface> to PendingReceiver.
PendingAssociatedReceiver(AssociatedInterfaceRequest<Interface>&& request)
: PendingAssociatedReceiver(request.PassHandle()) {}
~PendingAssociatedReceiver() = default;
PendingAssociatedReceiver& operator=(PendingAssociatedReceiver&& other) {
handle_ = std::move(other.handle_);
return *this;
}
bool is_valid() const { return handle_.is_valid(); }
explicit operator bool() const { return is_valid(); }
// Temporary implicit conversion operator to
// AssociatedInterfaceRequest<Interface> to aid in converting usage to
// PendingAssociatedReceiver.
operator AssociatedInterfaceRequest<Interface>() {
return AssociatedInterfaceRequest<Interface>(PassHandle());
}
ScopedInterfaceEndpointHandle PassHandle() { return std::move(handle_); }
const ScopedInterfaceEndpointHandle& handle() const { return handle_; }
void set_handle(ScopedInterfaceEndpointHandle handle) {
handle_ = std::move(handle);
}
// Hangs up this endpoint, invalidating the PendingAssociatedReceiver.
void reset() { handle_.reset(); }
// Similar to above but provides additional metadata in case the remote
// endpoint wants details about why this endpoint hung up.
void ResetWithReason(uint32_t custom_reason, const std::string& description) {
handle_.ResetWithReason(custom_reason, description);
}
private:
ScopedInterfaceEndpointHandle handle_;
DISALLOW_COPY_AND_ASSIGN(PendingAssociatedReceiver);
};
} // namespace mojo
#endif // MOJO_PUBLIC_CPP_BINDINGS_PENDING_ASSOCIATED_RECEIVER_H_
| 35.909091 | 80 | 0.783725 | [
"object"
] |
4e5ef6f29219ea7540e1c78c7bcbb30533cd4d72 | 138,308 | c | C | usr/src/lib/libzfs/common/libzfs_dataset.c | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | null | null | null | usr/src/lib/libzfs/common/libzfs_dataset.c | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | null | null | null | usr/src/lib/libzfs/common/libzfs_dataset.c | AsahiOS/gate | 283d47da4e17a5871d9d575e7ffb81e8f6c52e51 | [
"MIT"
] | 1 | 2020-12-30T00:04:16.000Z | 2020-12-30T00:04:16.000Z | /*
* 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 (c) 2005, 2010, Oracle and/or its affiliates. All rights reserved.
*/
/*
* Copyright (c) 2013, Joyent, Inc. All rights reserved.
* Copyright (c) 2011, 2016 by Delphix. All rights reserved.
* Copyright (c) 2012 DEY Storage Systems, Inc. All rights reserved.
* Copyright (c) 2011-2012 Pawel Jakub Dawidek. All rights reserved.
* Copyright (c) 2013 Martin Matuska. All rights reserved.
* Copyright (c) 2013 Steven Hartland. All rights reserved.
* Copyright (c) 2014 Integros [integros.com]
* Copyright 2018 Nexenta Systems, Inc.
* Copyright 2016 Igor Kozhukhov <ikozhukhov@gmail.com>
* Copyright 2017-2018 RackTop Systems.
*/
#include <ctype.h>
#include <errno.h>
#include <libintl.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <unistd.h>
#include <stddef.h>
#include <zone.h>
#include <fcntl.h>
#include <sys/mntent.h>
#include <sys/mount.h>
#include <priv.h>
#include <pwd.h>
#include <grp.h>
#include <stddef.h>
#include <ucred.h>
#include <idmap.h>
#include <aclutils.h>
#include <directory.h>
#include <time.h>
#include <sys/dnode.h>
#include <sys/spa.h>
#include <sys/zap.h>
#include <sys/dsl_crypt.h>
#include <libzfs.h>
#include <libzutil.h>
#include "zfs_namecheck.h"
#include "zfs_prop.h"
#include "libzfs_impl.h"
#include "zfs_deleg.h"
static int userquota_propname_decode(const char *propname, boolean_t zoned,
zfs_userquota_prop_t *typep, char *domain, int domainlen, uint64_t *ridp);
/*
* Given a single type (not a mask of types), return the type in a human
* readable form.
*/
const char *
zfs_type_to_name(zfs_type_t type)
{
switch (type) {
case ZFS_TYPE_FILESYSTEM:
return (dgettext(TEXT_DOMAIN, "filesystem"));
case ZFS_TYPE_SNAPSHOT:
return (dgettext(TEXT_DOMAIN, "snapshot"));
case ZFS_TYPE_VOLUME:
return (dgettext(TEXT_DOMAIN, "volume"));
case ZFS_TYPE_POOL:
return (dgettext(TEXT_DOMAIN, "pool"));
case ZFS_TYPE_BOOKMARK:
return (dgettext(TEXT_DOMAIN, "bookmark"));
default:
assert(!"unhandled zfs_type_t");
}
return (NULL);
}
/*
* Validate a ZFS path. This is used even before trying to open the dataset, to
* provide a more meaningful error message. We call zfs_error_aux() to
* explain exactly why the name was not valid.
*/
int
zfs_validate_name(libzfs_handle_t *hdl, const char *path, int type,
boolean_t modifying)
{
namecheck_err_t why;
char what;
if (entity_namecheck(path, &why, &what) != 0) {
if (hdl != NULL) {
switch (why) {
case NAME_ERR_TOOLONG:
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"name is too long"));
break;
case NAME_ERR_LEADING_SLASH:
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"leading slash in name"));
break;
case NAME_ERR_EMPTY_COMPONENT:
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"empty component in name"));
break;
case NAME_ERR_TRAILING_SLASH:
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"trailing slash in name"));
break;
case NAME_ERR_INVALCHAR:
zfs_error_aux(hdl,
dgettext(TEXT_DOMAIN, "invalid character "
"'%c' in name"), what);
break;
case NAME_ERR_MULTIPLE_DELIMITERS:
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"multiple '@' and/or '#' delimiters in "
"name"));
break;
case NAME_ERR_NOLETTER:
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"pool doesn't begin with a letter"));
break;
case NAME_ERR_RESERVED:
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"name is reserved"));
break;
case NAME_ERR_DISKLIKE:
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"reserved disk name"));
break;
default:
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"(%d) not defined"), why);
break;
}
}
return (0);
}
if (!(type & ZFS_TYPE_SNAPSHOT) && strchr(path, '@') != NULL) {
if (hdl != NULL)
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"snapshot delimiter '@' is not expected here"));
return (0);
}
if (type == ZFS_TYPE_SNAPSHOT && strchr(path, '@') == NULL) {
if (hdl != NULL)
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"missing '@' delimiter in snapshot name"));
return (0);
}
if (!(type & ZFS_TYPE_BOOKMARK) && strchr(path, '#') != NULL) {
if (hdl != NULL)
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"bookmark delimiter '#' is not expected here"));
return (0);
}
if (type == ZFS_TYPE_BOOKMARK && strchr(path, '#') == NULL) {
if (hdl != NULL)
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"missing '#' delimiter in bookmark name"));
return (0);
}
if (modifying && strchr(path, '%') != NULL) {
if (hdl != NULL)
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"invalid character %c in name"), '%');
return (0);
}
return (-1);
}
int
zfs_name_valid(const char *name, zfs_type_t type)
{
if (type == ZFS_TYPE_POOL)
return (zpool_name_valid(NULL, B_FALSE, name));
return (zfs_validate_name(NULL, name, type, B_FALSE));
}
/*
* This function takes the raw DSL properties, and filters out the user-defined
* properties into a separate nvlist.
*/
static nvlist_t *
process_user_props(zfs_handle_t *zhp, nvlist_t *props)
{
libzfs_handle_t *hdl = zhp->zfs_hdl;
nvpair_t *elem;
nvlist_t *propval;
nvlist_t *nvl;
if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0) {
(void) no_memory(hdl);
return (NULL);
}
elem = NULL;
while ((elem = nvlist_next_nvpair(props, elem)) != NULL) {
if (!zfs_prop_user(nvpair_name(elem)))
continue;
verify(nvpair_value_nvlist(elem, &propval) == 0);
if (nvlist_add_nvlist(nvl, nvpair_name(elem), propval) != 0) {
nvlist_free(nvl);
(void) no_memory(hdl);
return (NULL);
}
}
return (nvl);
}
static zpool_handle_t *
zpool_add_handle(zfs_handle_t *zhp, const char *pool_name)
{
libzfs_handle_t *hdl = zhp->zfs_hdl;
zpool_handle_t *zph;
if ((zph = zpool_open_canfail(hdl, pool_name)) != NULL) {
if (hdl->libzfs_pool_handles != NULL)
zph->zpool_next = hdl->libzfs_pool_handles;
hdl->libzfs_pool_handles = zph;
}
return (zph);
}
static zpool_handle_t *
zpool_find_handle(zfs_handle_t *zhp, const char *pool_name, int len)
{
libzfs_handle_t *hdl = zhp->zfs_hdl;
zpool_handle_t *zph = hdl->libzfs_pool_handles;
while ((zph != NULL) &&
(strncmp(pool_name, zpool_get_name(zph), len) != 0))
zph = zph->zpool_next;
return (zph);
}
/*
* Returns a handle to the pool that contains the provided dataset.
* If a handle to that pool already exists then that handle is returned.
* Otherwise, a new handle is created and added to the list of handles.
*/
static zpool_handle_t *
zpool_handle(zfs_handle_t *zhp)
{
char *pool_name;
int len;
zpool_handle_t *zph;
len = strcspn(zhp->zfs_name, "/@#") + 1;
pool_name = zfs_alloc(zhp->zfs_hdl, len);
(void) strlcpy(pool_name, zhp->zfs_name, len);
zph = zpool_find_handle(zhp, pool_name, len);
if (zph == NULL)
zph = zpool_add_handle(zhp, pool_name);
free(pool_name);
return (zph);
}
void
zpool_free_handles(libzfs_handle_t *hdl)
{
zpool_handle_t *next, *zph = hdl->libzfs_pool_handles;
while (zph != NULL) {
next = zph->zpool_next;
zpool_close(zph);
zph = next;
}
hdl->libzfs_pool_handles = NULL;
}
/*
* Utility function to gather stats (objset and zpl) for the given object.
*/
static int
get_stats_ioctl(zfs_handle_t *zhp, zfs_cmd_t *zc)
{
libzfs_handle_t *hdl = zhp->zfs_hdl;
(void) strlcpy(zc->zc_name, zhp->zfs_name, sizeof (zc->zc_name));
while (ioctl(hdl->libzfs_fd, ZFS_IOC_OBJSET_STATS, zc) != 0) {
if (errno == ENOMEM) {
if (zcmd_expand_dst_nvlist(hdl, zc) != 0) {
return (-1);
}
} else {
return (-1);
}
}
return (0);
}
/*
* Utility function to get the received properties of the given object.
*/
static int
get_recvd_props_ioctl(zfs_handle_t *zhp)
{
libzfs_handle_t *hdl = zhp->zfs_hdl;
nvlist_t *recvdprops;
zfs_cmd_t zc = { 0 };
int err;
if (zcmd_alloc_dst_nvlist(hdl, &zc, 0) != 0)
return (-1);
(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
while (ioctl(hdl->libzfs_fd, ZFS_IOC_OBJSET_RECVD_PROPS, &zc) != 0) {
if (errno == ENOMEM) {
if (zcmd_expand_dst_nvlist(hdl, &zc) != 0) {
return (-1);
}
} else {
zcmd_free_nvlists(&zc);
return (-1);
}
}
err = zcmd_read_dst_nvlist(zhp->zfs_hdl, &zc, &recvdprops);
zcmd_free_nvlists(&zc);
if (err != 0)
return (-1);
nvlist_free(zhp->zfs_recvd_props);
zhp->zfs_recvd_props = recvdprops;
return (0);
}
static int
put_stats_zhdl(zfs_handle_t *zhp, zfs_cmd_t *zc)
{
nvlist_t *allprops, *userprops;
zhp->zfs_dmustats = zc->zc_objset_stats; /* structure assignment */
if (zcmd_read_dst_nvlist(zhp->zfs_hdl, zc, &allprops) != 0) {
return (-1);
}
/*
* XXX Why do we store the user props separately, in addition to
* storing them in zfs_props?
*/
if ((userprops = process_user_props(zhp, allprops)) == NULL) {
nvlist_free(allprops);
return (-1);
}
nvlist_free(zhp->zfs_props);
nvlist_free(zhp->zfs_user_props);
zhp->zfs_props = allprops;
zhp->zfs_user_props = userprops;
return (0);
}
static int
get_stats(zfs_handle_t *zhp)
{
int rc = 0;
zfs_cmd_t zc = { 0 };
if (zcmd_alloc_dst_nvlist(zhp->zfs_hdl, &zc, 0) != 0)
return (-1);
if (get_stats_ioctl(zhp, &zc) != 0)
rc = -1;
else if (put_stats_zhdl(zhp, &zc) != 0)
rc = -1;
zcmd_free_nvlists(&zc);
return (rc);
}
/*
* Refresh the properties currently stored in the handle.
*/
void
zfs_refresh_properties(zfs_handle_t *zhp)
{
(void) get_stats(zhp);
}
/*
* Makes a handle from the given dataset name. Used by zfs_open() and
* zfs_iter_* to create child handles on the fly.
*/
static int
make_dataset_handle_common(zfs_handle_t *zhp, zfs_cmd_t *zc)
{
if (put_stats_zhdl(zhp, zc) != 0)
return (-1);
/*
* We've managed to open the dataset and gather statistics. Determine
* the high-level type.
*/
if (zhp->zfs_dmustats.dds_type == DMU_OST_ZVOL)
zhp->zfs_head_type = ZFS_TYPE_VOLUME;
else if (zhp->zfs_dmustats.dds_type == DMU_OST_ZFS)
zhp->zfs_head_type = ZFS_TYPE_FILESYSTEM;
else if (zhp->zfs_dmustats.dds_type == DMU_OST_OTHER)
return (-1);
else
abort();
if (zhp->zfs_dmustats.dds_is_snapshot)
zhp->zfs_type = ZFS_TYPE_SNAPSHOT;
else if (zhp->zfs_dmustats.dds_type == DMU_OST_ZVOL)
zhp->zfs_type = ZFS_TYPE_VOLUME;
else if (zhp->zfs_dmustats.dds_type == DMU_OST_ZFS)
zhp->zfs_type = ZFS_TYPE_FILESYSTEM;
else
abort(); /* we should never see any other types */
if ((zhp->zpool_hdl = zpool_handle(zhp)) == NULL)
return (-1);
return (0);
}
zfs_handle_t *
make_dataset_handle(libzfs_handle_t *hdl, const char *path)
{
zfs_cmd_t zc = { 0 };
zfs_handle_t *zhp = calloc(sizeof (zfs_handle_t), 1);
if (zhp == NULL)
return (NULL);
zhp->zfs_hdl = hdl;
(void) strlcpy(zhp->zfs_name, path, sizeof (zhp->zfs_name));
if (zcmd_alloc_dst_nvlist(hdl, &zc, 0) != 0) {
free(zhp);
return (NULL);
}
if (get_stats_ioctl(zhp, &zc) == -1) {
zcmd_free_nvlists(&zc);
free(zhp);
return (NULL);
}
if (make_dataset_handle_common(zhp, &zc) == -1) {
free(zhp);
zhp = NULL;
}
zcmd_free_nvlists(&zc);
return (zhp);
}
zfs_handle_t *
make_dataset_handle_zc(libzfs_handle_t *hdl, zfs_cmd_t *zc)
{
zfs_handle_t *zhp = calloc(sizeof (zfs_handle_t), 1);
if (zhp == NULL)
return (NULL);
zhp->zfs_hdl = hdl;
(void) strlcpy(zhp->zfs_name, zc->zc_name, sizeof (zhp->zfs_name));
if (make_dataset_handle_common(zhp, zc) == -1) {
free(zhp);
return (NULL);
}
return (zhp);
}
zfs_handle_t *
make_dataset_simple_handle_zc(zfs_handle_t *pzhp, zfs_cmd_t *zc)
{
zfs_handle_t *zhp = calloc(sizeof (zfs_handle_t), 1);
if (zhp == NULL)
return (NULL);
zhp->zfs_hdl = pzhp->zfs_hdl;
(void) strlcpy(zhp->zfs_name, zc->zc_name, sizeof (zhp->zfs_name));
zhp->zfs_head_type = pzhp->zfs_type;
zhp->zfs_type = ZFS_TYPE_SNAPSHOT;
zhp->zpool_hdl = zpool_handle(zhp);
return (zhp);
}
zfs_handle_t *
zfs_handle_dup(zfs_handle_t *zhp_orig)
{
zfs_handle_t *zhp = calloc(sizeof (zfs_handle_t), 1);
if (zhp == NULL)
return (NULL);
zhp->zfs_hdl = zhp_orig->zfs_hdl;
zhp->zpool_hdl = zhp_orig->zpool_hdl;
(void) strlcpy(zhp->zfs_name, zhp_orig->zfs_name,
sizeof (zhp->zfs_name));
zhp->zfs_type = zhp_orig->zfs_type;
zhp->zfs_head_type = zhp_orig->zfs_head_type;
zhp->zfs_dmustats = zhp_orig->zfs_dmustats;
if (zhp_orig->zfs_props != NULL) {
if (nvlist_dup(zhp_orig->zfs_props, &zhp->zfs_props, 0) != 0) {
(void) no_memory(zhp->zfs_hdl);
zfs_close(zhp);
return (NULL);
}
}
if (zhp_orig->zfs_user_props != NULL) {
if (nvlist_dup(zhp_orig->zfs_user_props,
&zhp->zfs_user_props, 0) != 0) {
(void) no_memory(zhp->zfs_hdl);
zfs_close(zhp);
return (NULL);
}
}
if (zhp_orig->zfs_recvd_props != NULL) {
if (nvlist_dup(zhp_orig->zfs_recvd_props,
&zhp->zfs_recvd_props, 0)) {
(void) no_memory(zhp->zfs_hdl);
zfs_close(zhp);
return (NULL);
}
}
zhp->zfs_mntcheck = zhp_orig->zfs_mntcheck;
if (zhp_orig->zfs_mntopts != NULL) {
zhp->zfs_mntopts = zfs_strdup(zhp_orig->zfs_hdl,
zhp_orig->zfs_mntopts);
}
zhp->zfs_props_table = zhp_orig->zfs_props_table;
return (zhp);
}
boolean_t
zfs_bookmark_exists(const char *path)
{
nvlist_t *bmarks;
nvlist_t *props;
char fsname[ZFS_MAX_DATASET_NAME_LEN];
char *bmark_name;
char *pound;
int err;
boolean_t rv;
(void) strlcpy(fsname, path, sizeof (fsname));
pound = strchr(fsname, '#');
if (pound == NULL)
return (B_FALSE);
*pound = '\0';
bmark_name = pound + 1;
props = fnvlist_alloc();
err = lzc_get_bookmarks(fsname, props, &bmarks);
nvlist_free(props);
if (err != 0) {
nvlist_free(bmarks);
return (B_FALSE);
}
rv = nvlist_exists(bmarks, bmark_name);
nvlist_free(bmarks);
return (rv);
}
zfs_handle_t *
make_bookmark_handle(zfs_handle_t *parent, const char *path,
nvlist_t *bmark_props)
{
zfs_handle_t *zhp = calloc(sizeof (zfs_handle_t), 1);
if (zhp == NULL)
return (NULL);
/* Fill in the name. */
zhp->zfs_hdl = parent->zfs_hdl;
(void) strlcpy(zhp->zfs_name, path, sizeof (zhp->zfs_name));
/* Set the property lists. */
if (nvlist_dup(bmark_props, &zhp->zfs_props, 0) != 0) {
free(zhp);
return (NULL);
}
/* Set the types. */
zhp->zfs_head_type = parent->zfs_head_type;
zhp->zfs_type = ZFS_TYPE_BOOKMARK;
if ((zhp->zpool_hdl = zpool_handle(zhp)) == NULL) {
nvlist_free(zhp->zfs_props);
free(zhp);
return (NULL);
}
return (zhp);
}
struct zfs_open_bookmarks_cb_data {
const char *path;
zfs_handle_t *zhp;
};
static int
zfs_open_bookmarks_cb(zfs_handle_t *zhp, void *data)
{
struct zfs_open_bookmarks_cb_data *dp = data;
/*
* Is it the one we are looking for?
*/
if (strcmp(dp->path, zfs_get_name(zhp)) == 0) {
/*
* We found it. Save it and let the caller know we are done.
*/
dp->zhp = zhp;
return (EEXIST);
}
/*
* Not found. Close the handle and ask for another one.
*/
zfs_close(zhp);
return (0);
}
/*
* Opens the given snapshot, bookmark, filesystem, or volume. The 'types'
* argument is a mask of acceptable types. The function will print an
* appropriate error message and return NULL if it can't be opened.
*/
zfs_handle_t *
zfs_open(libzfs_handle_t *hdl, const char *path, int types)
{
zfs_handle_t *zhp;
char errbuf[1024];
char *bookp;
(void) snprintf(errbuf, sizeof (errbuf),
dgettext(TEXT_DOMAIN, "cannot open '%s'"), path);
/*
* Validate the name before we even try to open it.
*/
if (!zfs_validate_name(hdl, path, types, B_FALSE)) {
(void) zfs_error(hdl, EZFS_INVALIDNAME, errbuf);
return (NULL);
}
/*
* Bookmarks needs to be handled separately.
*/
bookp = strchr(path, '#');
if (bookp == NULL) {
/*
* Try to get stats for the dataset, which will tell us if it
* exists.
*/
errno = 0;
if ((zhp = make_dataset_handle(hdl, path)) == NULL) {
(void) zfs_standard_error(hdl, errno, errbuf);
return (NULL);
}
} else {
char dsname[ZFS_MAX_DATASET_NAME_LEN];
zfs_handle_t *pzhp;
struct zfs_open_bookmarks_cb_data cb_data = {path, NULL};
/*
* We need to cut out '#' and everything after '#'
* to get the parent dataset name only.
*/
assert(bookp - path < sizeof (dsname));
(void) strncpy(dsname, path, bookp - path);
dsname[bookp - path] = '\0';
/*
* Create handle for the parent dataset.
*/
errno = 0;
if ((pzhp = make_dataset_handle(hdl, dsname)) == NULL) {
(void) zfs_standard_error(hdl, errno, errbuf);
return (NULL);
}
/*
* Iterate bookmarks to find the right one.
*/
errno = 0;
if ((zfs_iter_bookmarks(pzhp, zfs_open_bookmarks_cb,
&cb_data) == 0) && (cb_data.zhp == NULL)) {
(void) zfs_error(hdl, EZFS_NOENT, errbuf);
zfs_close(pzhp);
return (NULL);
}
if (cb_data.zhp == NULL) {
(void) zfs_standard_error(hdl, errno, errbuf);
zfs_close(pzhp);
return (NULL);
}
zhp = cb_data.zhp;
/*
* Cleanup.
*/
zfs_close(pzhp);
}
if (!(types & zhp->zfs_type)) {
(void) zfs_error(hdl, EZFS_BADTYPE, errbuf);
zfs_close(zhp);
return (NULL);
}
return (zhp);
}
/*
* Release a ZFS handle. Nothing to do but free the associated memory.
*/
void
zfs_close(zfs_handle_t *zhp)
{
if (zhp->zfs_mntopts)
free(zhp->zfs_mntopts);
nvlist_free(zhp->zfs_props);
nvlist_free(zhp->zfs_user_props);
nvlist_free(zhp->zfs_recvd_props);
free(zhp);
}
typedef struct mnttab_node {
struct mnttab mtn_mt;
avl_node_t mtn_node;
} mnttab_node_t;
static int
libzfs_mnttab_cache_compare(const void *arg1, const void *arg2)
{
const mnttab_node_t *mtn1 = (const mnttab_node_t *)arg1;
const mnttab_node_t *mtn2 = (const mnttab_node_t *)arg2;
int rv;
rv = strcmp(mtn1->mtn_mt.mnt_special, mtn2->mtn_mt.mnt_special);
if (rv == 0)
return (0);
return (rv > 0 ? 1 : -1);
}
void
libzfs_mnttab_init(libzfs_handle_t *hdl)
{
(void) mutex_init(&hdl->libzfs_mnttab_cache_lock,
LOCK_NORMAL | LOCK_ERRORCHECK, NULL);
assert(avl_numnodes(&hdl->libzfs_mnttab_cache) == 0);
avl_create(&hdl->libzfs_mnttab_cache, libzfs_mnttab_cache_compare,
sizeof (mnttab_node_t), offsetof(mnttab_node_t, mtn_node));
}
void
libzfs_mnttab_update(libzfs_handle_t *hdl)
{
struct mnttab entry;
rewind(hdl->libzfs_mnttab);
while (getmntent(hdl->libzfs_mnttab, &entry) == 0) {
mnttab_node_t *mtn;
if (strcmp(entry.mnt_fstype, MNTTYPE_ZFS) != 0)
continue;
mtn = zfs_alloc(hdl, sizeof (mnttab_node_t));
mtn->mtn_mt.mnt_special = zfs_strdup(hdl, entry.mnt_special);
mtn->mtn_mt.mnt_mountp = zfs_strdup(hdl, entry.mnt_mountp);
mtn->mtn_mt.mnt_fstype = zfs_strdup(hdl, entry.mnt_fstype);
mtn->mtn_mt.mnt_mntopts = zfs_strdup(hdl, entry.mnt_mntopts);
avl_add(&hdl->libzfs_mnttab_cache, mtn);
}
}
void
libzfs_mnttab_fini(libzfs_handle_t *hdl)
{
void *cookie = NULL;
mnttab_node_t *mtn;
while ((mtn = avl_destroy_nodes(&hdl->libzfs_mnttab_cache, &cookie))
!= NULL) {
free(mtn->mtn_mt.mnt_special);
free(mtn->mtn_mt.mnt_mountp);
free(mtn->mtn_mt.mnt_fstype);
free(mtn->mtn_mt.mnt_mntopts);
free(mtn);
}
avl_destroy(&hdl->libzfs_mnttab_cache);
(void) mutex_destroy(&hdl->libzfs_mnttab_cache_lock);
}
void
libzfs_mnttab_cache(libzfs_handle_t *hdl, boolean_t enable)
{
hdl->libzfs_mnttab_enable = enable;
}
int
libzfs_mnttab_find(libzfs_handle_t *hdl, const char *fsname,
struct mnttab *entry)
{
mnttab_node_t find;
mnttab_node_t *mtn;
int ret = ENOENT;
if (!hdl->libzfs_mnttab_enable) {
struct mnttab srch = { 0 };
if (avl_numnodes(&hdl->libzfs_mnttab_cache))
libzfs_mnttab_fini(hdl);
rewind(hdl->libzfs_mnttab);
srch.mnt_special = (char *)fsname;
srch.mnt_fstype = MNTTYPE_ZFS;
if (getmntany(hdl->libzfs_mnttab, entry, &srch) == 0)
return (0);
else
return (ENOENT);
}
mutex_enter(&hdl->libzfs_mnttab_cache_lock);
if (avl_numnodes(&hdl->libzfs_mnttab_cache) == 0)
libzfs_mnttab_update(hdl);
find.mtn_mt.mnt_special = (char *)fsname;
mtn = avl_find(&hdl->libzfs_mnttab_cache, &find, NULL);
if (mtn) {
*entry = mtn->mtn_mt;
ret = 0;
}
mutex_exit(&hdl->libzfs_mnttab_cache_lock);
return (ret);
}
void
libzfs_mnttab_add(libzfs_handle_t *hdl, const char *special,
const char *mountp, const char *mntopts)
{
mnttab_node_t *mtn;
mutex_enter(&hdl->libzfs_mnttab_cache_lock);
if (avl_numnodes(&hdl->libzfs_mnttab_cache) != 0) {
mtn = zfs_alloc(hdl, sizeof (mnttab_node_t));
mtn->mtn_mt.mnt_special = zfs_strdup(hdl, special);
mtn->mtn_mt.mnt_mountp = zfs_strdup(hdl, mountp);
mtn->mtn_mt.mnt_fstype = zfs_strdup(hdl, MNTTYPE_ZFS);
mtn->mtn_mt.mnt_mntopts = zfs_strdup(hdl, mntopts);
avl_add(&hdl->libzfs_mnttab_cache, mtn);
}
mutex_exit(&hdl->libzfs_mnttab_cache_lock);
}
void
libzfs_mnttab_remove(libzfs_handle_t *hdl, const char *fsname)
{
mnttab_node_t find;
mnttab_node_t *ret;
mutex_enter(&hdl->libzfs_mnttab_cache_lock);
find.mtn_mt.mnt_special = (char *)fsname;
if ((ret = avl_find(&hdl->libzfs_mnttab_cache, (void *)&find, NULL))
!= NULL) {
avl_remove(&hdl->libzfs_mnttab_cache, ret);
free(ret->mtn_mt.mnt_special);
free(ret->mtn_mt.mnt_mountp);
free(ret->mtn_mt.mnt_fstype);
free(ret->mtn_mt.mnt_mntopts);
free(ret);
}
mutex_exit(&hdl->libzfs_mnttab_cache_lock);
}
int
zfs_spa_version(zfs_handle_t *zhp, int *spa_version)
{
zpool_handle_t *zpool_handle = zhp->zpool_hdl;
if (zpool_handle == NULL)
return (-1);
*spa_version = zpool_get_prop_int(zpool_handle,
ZPOOL_PROP_VERSION, NULL);
return (0);
}
/*
* The choice of reservation property depends on the SPA version.
*/
static int
zfs_which_resv_prop(zfs_handle_t *zhp, zfs_prop_t *resv_prop)
{
int spa_version;
if (zfs_spa_version(zhp, &spa_version) < 0)
return (-1);
if (spa_version >= SPA_VERSION_REFRESERVATION)
*resv_prop = ZFS_PROP_REFRESERVATION;
else
*resv_prop = ZFS_PROP_RESERVATION;
return (0);
}
/*
* Given an nvlist of properties to set, validates that they are correct, and
* parses any numeric properties (index, boolean, etc) if they are specified as
* strings.
*/
nvlist_t *
zfs_valid_proplist(libzfs_handle_t *hdl, zfs_type_t type, nvlist_t *nvl,
uint64_t zoned, zfs_handle_t *zhp, zpool_handle_t *zpool_hdl,
boolean_t key_params_ok, const char *errbuf)
{
nvpair_t *elem;
uint64_t intval;
char *strval;
zfs_prop_t prop;
nvlist_t *ret;
int chosen_normal = -1;
int chosen_utf = -1;
if (nvlist_alloc(&ret, NV_UNIQUE_NAME, 0) != 0) {
(void) no_memory(hdl);
return (NULL);
}
/*
* Make sure this property is valid and applies to this type.
*/
elem = NULL;
while ((elem = nvlist_next_nvpair(nvl, elem)) != NULL) {
const char *propname = nvpair_name(elem);
prop = zfs_name_to_prop(propname);
if (prop == ZPROP_INVAL && zfs_prop_user(propname)) {
/*
* This is a user property: make sure it's a
* string, and that it's less than ZAP_MAXNAMELEN.
*/
if (nvpair_type(elem) != DATA_TYPE_STRING) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"'%s' must be a string"), propname);
(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
goto error;
}
if (strlen(nvpair_name(elem)) >= ZAP_MAXNAMELEN) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"property name '%s' is too long"),
propname);
(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
goto error;
}
(void) nvpair_value_string(elem, &strval);
if (nvlist_add_string(ret, propname, strval) != 0) {
(void) no_memory(hdl);
goto error;
}
continue;
}
/*
* Currently, only user properties can be modified on
* snapshots.
*/
if (type == ZFS_TYPE_SNAPSHOT) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"this property can not be modified for snapshots"));
(void) zfs_error(hdl, EZFS_PROPTYPE, errbuf);
goto error;
}
if (prop == ZPROP_INVAL && zfs_prop_userquota(propname)) {
zfs_userquota_prop_t uqtype;
char newpropname[128];
char domain[128];
uint64_t rid;
uint64_t valary[3];
if (userquota_propname_decode(propname, zoned,
&uqtype, domain, sizeof (domain), &rid) != 0) {
zfs_error_aux(hdl,
dgettext(TEXT_DOMAIN,
"'%s' has an invalid user/group name"),
propname);
(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
goto error;
}
if (uqtype != ZFS_PROP_USERQUOTA &&
uqtype != ZFS_PROP_GROUPQUOTA &&
uqtype != ZFS_PROP_USEROBJQUOTA &&
uqtype != ZFS_PROP_GROUPOBJQUOTA &&
uqtype != ZFS_PROP_PROJECTQUOTA &&
uqtype != ZFS_PROP_PROJECTOBJQUOTA) {
zfs_error_aux(hdl,
dgettext(TEXT_DOMAIN, "'%s' is readonly"),
propname);
(void) zfs_error(hdl, EZFS_PROPREADONLY,
errbuf);
goto error;
}
if (nvpair_type(elem) == DATA_TYPE_STRING) {
(void) nvpair_value_string(elem, &strval);
if (strcmp(strval, "none") == 0) {
intval = 0;
} else if (zfs_nicestrtonum(hdl,
strval, &intval) != 0) {
(void) zfs_error(hdl,
EZFS_BADPROP, errbuf);
goto error;
}
} else if (nvpair_type(elem) ==
DATA_TYPE_UINT64) {
(void) nvpair_value_uint64(elem, &intval);
if (intval == 0) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"use 'none' to disable "
"{user|group|project}quota"));
goto error;
}
} else {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"'%s' must be a number"), propname);
(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
goto error;
}
/*
* Encode the prop name as
* userquota@<hex-rid>-domain, to make it easy
* for the kernel to decode.
*/
(void) snprintf(newpropname, sizeof (newpropname),
"%s%llx-%s", zfs_userquota_prop_prefixes[uqtype],
(longlong_t)rid, domain);
valary[0] = uqtype;
valary[1] = rid;
valary[2] = intval;
if (nvlist_add_uint64_array(ret, newpropname,
valary, 3) != 0) {
(void) no_memory(hdl);
goto error;
}
continue;
} else if (prop == ZPROP_INVAL && zfs_prop_written(propname)) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"'%s' is readonly"),
propname);
(void) zfs_error(hdl, EZFS_PROPREADONLY, errbuf);
goto error;
}
if (prop == ZPROP_INVAL) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"invalid property '%s'"), propname);
(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
goto error;
}
if (!zfs_prop_valid_for_type(prop, type)) {
zfs_error_aux(hdl,
dgettext(TEXT_DOMAIN, "'%s' does not "
"apply to datasets of this type"), propname);
(void) zfs_error(hdl, EZFS_PROPTYPE, errbuf);
goto error;
}
if (zfs_prop_readonly(prop) &&
!(zfs_prop_setonce(prop) && zhp == NULL) &&
!(zfs_prop_encryption_key_param(prop) && key_params_ok)) {
zfs_error_aux(hdl,
dgettext(TEXT_DOMAIN, "'%s' is readonly"),
propname);
(void) zfs_error(hdl, EZFS_PROPREADONLY, errbuf);
goto error;
}
if (zprop_parse_value(hdl, elem, prop, type, ret,
&strval, &intval, errbuf) != 0)
goto error;
/*
* Perform some additional checks for specific properties.
*/
switch (prop) {
case ZFS_PROP_VERSION:
{
int version;
if (zhp == NULL)
break;
version = zfs_prop_get_int(zhp, ZFS_PROP_VERSION);
if (intval < version) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"Can not downgrade; already at version %u"),
version);
(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
goto error;
}
break;
}
case ZFS_PROP_VOLBLOCKSIZE:
case ZFS_PROP_RECORDSIZE:
{
int maxbs = SPA_MAXBLOCKSIZE;
if (zpool_hdl != NULL) {
maxbs = zpool_get_prop_int(zpool_hdl,
ZPOOL_PROP_MAXBLOCKSIZE, NULL);
}
/*
* Volumes are limited to a volblocksize of 128KB,
* because they typically service workloads with
* small random writes, which incur a large performance
* penalty with large blocks.
*/
if (prop == ZFS_PROP_VOLBLOCKSIZE)
maxbs = SPA_OLD_MAXBLOCKSIZE;
/*
* The value must be a power of two between
* SPA_MINBLOCKSIZE and maxbs.
*/
if (intval < SPA_MINBLOCKSIZE ||
intval > maxbs || !ISP2(intval)) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"'%s' must be power of 2 from 512B "
"to %uKB"), propname, maxbs >> 10);
(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
goto error;
}
break;
}
case ZFS_PROP_SPECIAL_SMALL_BLOCKS:
if (zpool_hdl != NULL) {
char state[64] = "";
/*
* Issue a warning but do not fail so that
* tests for setable properties succeed.
*/
if (zpool_prop_get_feature(zpool_hdl,
"feature@allocation_classes", state,
sizeof (state)) != 0 ||
strcmp(state, ZFS_FEATURE_ACTIVE) != 0) {
(void) fprintf(stderr, gettext(
"%s: property requires a special "
"device in the pool\n"), propname);
}
}
if (intval != 0 &&
(intval < SPA_MINBLOCKSIZE ||
intval > SPA_OLD_MAXBLOCKSIZE || !ISP2(intval))) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"invalid '%s=%d' property: must be zero or "
"a power of 2 from 512B to 128K"), propname,
intval);
(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
goto error;
}
break;
case ZFS_PROP_MLSLABEL:
{
/*
* Verify the mlslabel string and convert to
* internal hex label string.
*/
m_label_t *new_sl;
char *hex = NULL; /* internal label string */
/* Default value is already OK. */
if (strcasecmp(strval, ZFS_MLSLABEL_DEFAULT) == 0)
break;
/* Verify the label can be converted to binary form */
if (((new_sl = m_label_alloc(MAC_LABEL)) == NULL) ||
(str_to_label(strval, &new_sl, MAC_LABEL,
L_NO_CORRECTION, NULL) == -1)) {
goto badlabel;
}
/* Now translate to hex internal label string */
if (label_to_str(new_sl, &hex, M_INTERNAL,
DEF_NAMES) != 0) {
if (hex)
free(hex);
goto badlabel;
}
m_label_free(new_sl);
/* If string is already in internal form, we're done. */
if (strcmp(strval, hex) == 0) {
free(hex);
break;
}
/* Replace the label string with the internal form. */
(void) nvlist_remove(ret, zfs_prop_to_name(prop),
DATA_TYPE_STRING);
verify(nvlist_add_string(ret, zfs_prop_to_name(prop),
hex) == 0);
free(hex);
break;
badlabel:
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"invalid mlslabel '%s'"), strval);
(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
m_label_free(new_sl); /* OK if null */
goto error;
}
case ZFS_PROP_MOUNTPOINT:
{
namecheck_err_t why;
if (strcmp(strval, ZFS_MOUNTPOINT_NONE) == 0 ||
strcmp(strval, ZFS_MOUNTPOINT_LEGACY) == 0)
break;
if (mountpoint_namecheck(strval, &why)) {
switch (why) {
case NAME_ERR_LEADING_SLASH:
zfs_error_aux(hdl,
dgettext(TEXT_DOMAIN,
"'%s' must be an absolute path, "
"'none', or 'legacy'"), propname);
break;
case NAME_ERR_TOOLONG:
zfs_error_aux(hdl,
dgettext(TEXT_DOMAIN,
"component of '%s' is too long"),
propname);
break;
default:
zfs_error_aux(hdl,
dgettext(TEXT_DOMAIN,
"(%d) not defined"),
why);
break;
}
(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
goto error;
}
}
/*FALLTHRU*/
case ZFS_PROP_SHARESMB:
case ZFS_PROP_SHARENFS:
/*
* For the mountpoint and sharenfs or sharesmb
* properties, check if it can be set in a
* global/non-global zone based on
* the zoned property value:
*
* global zone non-global zone
* --------------------------------------------------
* zoned=on mountpoint (no) mountpoint (yes)
* sharenfs (no) sharenfs (yes)
* sharesmb (no) sharesmb (yes)
*
* zoned=off mountpoint (yes) N/A
* sharenfs (yes)
* sharesmb (yes)
*/
if (zoned) {
if (getzoneid() == GLOBAL_ZONEID) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"'%s' cannot be set on "
"dataset in a non-global zone"),
propname);
(void) zfs_error(hdl, EZFS_ZONED,
errbuf);
goto error;
}
} else if (getzoneid() != GLOBAL_ZONEID) {
/*
* If zoned property is 'off', this must be in
* a global zone. If not, something is wrong.
*/
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"'%s' cannot be set while dataset "
"'zoned' property is set"), propname);
(void) zfs_error(hdl, EZFS_ZONED, errbuf);
goto error;
}
/*
* At this point, it is legitimate to set the
* property. Now we want to make sure that the
* property value is valid if it is sharenfs.
*/
if ((prop == ZFS_PROP_SHARENFS ||
prop == ZFS_PROP_SHARESMB) &&
strcmp(strval, "on") != 0 &&
strcmp(strval, "off") != 0) {
zfs_share_proto_t proto;
if (prop == ZFS_PROP_SHARESMB)
proto = PROTO_SMB;
else
proto = PROTO_NFS;
/*
* Must be an valid sharing protocol
* option string so init the libshare
* in order to enable the parser and
* then parse the options. We use the
* control API since we don't care about
* the current configuration and don't
* want the overhead of loading it
* until we actually do something.
*/
if (zfs_init_libshare(hdl,
SA_INIT_CONTROL_API) != SA_OK) {
/*
* An error occurred so we can't do
* anything
*/
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"'%s' cannot be set: problem "
"in share initialization"),
propname);
(void) zfs_error(hdl, EZFS_BADPROP,
errbuf);
goto error;
}
if (zfs_parse_options(strval, proto) != SA_OK) {
/*
* There was an error in parsing so
* deal with it by issuing an error
* message and leaving after
* uninitializing the the libshare
* interface.
*/
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"'%s' cannot be set to invalid "
"options"), propname);
(void) zfs_error(hdl, EZFS_BADPROP,
errbuf);
zfs_uninit_libshare(hdl);
goto error;
}
zfs_uninit_libshare(hdl);
}
break;
case ZFS_PROP_KEYLOCATION:
if (!zfs_prop_valid_keylocation(strval, B_FALSE)) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"invalid keylocation"));
(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
goto error;
}
if (zhp != NULL) {
uint64_t crypt =
zfs_prop_get_int(zhp, ZFS_PROP_ENCRYPTION);
if (crypt == ZIO_CRYPT_OFF &&
strcmp(strval, "none") != 0) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"keylocation must be 'none' "
"for unencrypted datasets"));
(void) zfs_error(hdl, EZFS_BADPROP,
errbuf);
goto error;
} else if (crypt != ZIO_CRYPT_OFF &&
strcmp(strval, "none") == 0) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"keylocation must not be 'none' "
"for encrypted datasets"));
(void) zfs_error(hdl, EZFS_BADPROP,
errbuf);
goto error;
}
}
break;
case ZFS_PROP_PBKDF2_ITERS:
if (intval < MIN_PBKDF2_ITERATIONS) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"minimum pbkdf2 iterations is %u"),
MIN_PBKDF2_ITERATIONS);
(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
goto error;
}
break;
case ZFS_PROP_UTF8ONLY:
chosen_utf = (int)intval;
break;
case ZFS_PROP_NORMALIZE:
chosen_normal = (int)intval;
break;
default:
break;
}
/*
* For changes to existing volumes, we have some additional
* checks to enforce.
*/
if (type == ZFS_TYPE_VOLUME && zhp != NULL) {
uint64_t volsize = zfs_prop_get_int(zhp,
ZFS_PROP_VOLSIZE);
uint64_t blocksize = zfs_prop_get_int(zhp,
ZFS_PROP_VOLBLOCKSIZE);
char buf[64];
switch (prop) {
case ZFS_PROP_RESERVATION:
if (intval > volsize) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"'%s' is greater than current "
"volume size"), propname);
(void) zfs_error(hdl, EZFS_BADPROP,
errbuf);
goto error;
}
break;
case ZFS_PROP_REFRESERVATION:
if (intval > volsize && intval != UINT64_MAX) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"'%s' is greater than current "
"volume size"), propname);
(void) zfs_error(hdl, EZFS_BADPROP,
errbuf);
goto error;
}
break;
case ZFS_PROP_VOLSIZE:
if (intval % blocksize != 0) {
zfs_nicenum(blocksize, buf,
sizeof (buf));
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"'%s' must be a multiple of "
"volume block size (%s)"),
propname, buf);
(void) zfs_error(hdl, EZFS_BADPROP,
errbuf);
goto error;
}
if (intval == 0) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"'%s' cannot be zero"),
propname);
(void) zfs_error(hdl, EZFS_BADPROP,
errbuf);
goto error;
}
break;
default:
break;
}
}
/* check encryption properties */
if (zhp != NULL) {
int64_t crypt = zfs_prop_get_int(zhp,
ZFS_PROP_ENCRYPTION);
switch (prop) {
case ZFS_PROP_COPIES:
if (crypt != ZIO_CRYPT_OFF && intval > 2) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"encrypted datasets cannot have "
"3 copies"));
(void) zfs_error(hdl, EZFS_BADPROP,
errbuf);
goto error;
}
break;
default:
break;
}
}
}
/*
* If normalization was chosen, but no UTF8 choice was made,
* enforce rejection of non-UTF8 names.
*
* If normalization was chosen, but rejecting non-UTF8 names
* was explicitly not chosen, it is an error.
*/
if (chosen_normal > 0 && chosen_utf < 0) {
if (nvlist_add_uint64(ret,
zfs_prop_to_name(ZFS_PROP_UTF8ONLY), 1) != 0) {
(void) no_memory(hdl);
goto error;
}
} else if (chosen_normal > 0 && chosen_utf == 0) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"'%s' must be set 'on' if normalization chosen"),
zfs_prop_to_name(ZFS_PROP_UTF8ONLY));
(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
goto error;
}
return (ret);
error:
nvlist_free(ret);
return (NULL);
}
int
zfs_add_synthetic_resv(zfs_handle_t *zhp, nvlist_t *nvl)
{
uint64_t old_volsize;
uint64_t new_volsize;
uint64_t old_reservation;
uint64_t new_reservation;
zfs_prop_t resv_prop;
nvlist_t *props;
zpool_handle_t *zph = zpool_handle(zhp);
/*
* If this is an existing volume, and someone is setting the volsize,
* make sure that it matches the reservation, or add it if necessary.
*/
old_volsize = zfs_prop_get_int(zhp, ZFS_PROP_VOLSIZE);
if (zfs_which_resv_prop(zhp, &resv_prop) < 0)
return (-1);
old_reservation = zfs_prop_get_int(zhp, resv_prop);
props = fnvlist_alloc();
fnvlist_add_uint64(props, zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
zfs_prop_get_int(zhp, ZFS_PROP_VOLBLOCKSIZE));
if ((zvol_volsize_to_reservation(zph, old_volsize, props) !=
old_reservation) || nvlist_exists(nvl,
zfs_prop_to_name(resv_prop))) {
fnvlist_free(props);
return (0);
}
if (nvlist_lookup_uint64(nvl, zfs_prop_to_name(ZFS_PROP_VOLSIZE),
&new_volsize) != 0) {
fnvlist_free(props);
return (-1);
}
new_reservation = zvol_volsize_to_reservation(zph, new_volsize, props);
fnvlist_free(props);
if (nvlist_add_uint64(nvl, zfs_prop_to_name(resv_prop),
new_reservation) != 0) {
(void) no_memory(zhp->zfs_hdl);
return (-1);
}
return (1);
}
/*
* Helper for 'zfs {set|clone} refreservation=auto'. Must be called after
* zfs_valid_proplist(), as it is what sets the UINT64_MAX sentinal value.
* Return codes must match zfs_add_synthetic_resv().
*/
static int
zfs_fix_auto_resv(zfs_handle_t *zhp, nvlist_t *nvl)
{
uint64_t volsize;
uint64_t resvsize;
zfs_prop_t prop;
nvlist_t *props;
if (!ZFS_IS_VOLUME(zhp)) {
return (0);
}
if (zfs_which_resv_prop(zhp, &prop) != 0) {
return (-1);
}
if (prop != ZFS_PROP_REFRESERVATION) {
return (0);
}
if (nvlist_lookup_uint64(nvl, zfs_prop_to_name(prop), &resvsize) != 0) {
/* No value being set, so it can't be "auto" */
return (0);
}
if (resvsize != UINT64_MAX) {
/* Being set to a value other than "auto" */
return (0);
}
props = fnvlist_alloc();
fnvlist_add_uint64(props, zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
zfs_prop_get_int(zhp, ZFS_PROP_VOLBLOCKSIZE));
if (nvlist_lookup_uint64(nvl, zfs_prop_to_name(ZFS_PROP_VOLSIZE),
&volsize) != 0) {
volsize = zfs_prop_get_int(zhp, ZFS_PROP_VOLSIZE);
}
resvsize = zvol_volsize_to_reservation(zpool_handle(zhp), volsize,
props);
fnvlist_free(props);
(void) nvlist_remove_all(nvl, zfs_prop_to_name(prop));
if (nvlist_add_uint64(nvl, zfs_prop_to_name(prop), resvsize) != 0) {
(void) no_memory(zhp->zfs_hdl);
return (-1);
}
return (1);
}
void
zfs_setprop_error(libzfs_handle_t *hdl, zfs_prop_t prop, int err,
char *errbuf)
{
switch (err) {
case ENOSPC:
/*
* For quotas and reservations, ENOSPC indicates
* something different; setting a quota or reservation
* doesn't use any disk space.
*/
switch (prop) {
case ZFS_PROP_QUOTA:
case ZFS_PROP_REFQUOTA:
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"size is less than current used or "
"reserved space"));
(void) zfs_error(hdl, EZFS_PROPSPACE, errbuf);
break;
case ZFS_PROP_RESERVATION:
case ZFS_PROP_REFRESERVATION:
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"size is greater than available space"));
(void) zfs_error(hdl, EZFS_PROPSPACE, errbuf);
break;
default:
(void) zfs_standard_error(hdl, err, errbuf);
break;
}
break;
case EBUSY:
(void) zfs_standard_error(hdl, EBUSY, errbuf);
break;
case EROFS:
(void) zfs_error(hdl, EZFS_DSREADONLY, errbuf);
break;
case E2BIG:
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"property value too long"));
(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
break;
case ENOTSUP:
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"pool and or dataset must be upgraded to set this "
"property or value"));
(void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
break;
case ERANGE:
if (prop == ZFS_PROP_COMPRESSION ||
prop == ZFS_PROP_RECORDSIZE) {
(void) zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"property setting is not allowed on "
"bootable datasets"));
(void) zfs_error(hdl, EZFS_NOTSUP, errbuf);
} else if (prop == ZFS_PROP_CHECKSUM ||
prop == ZFS_PROP_DEDUP) {
(void) zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"property setting is not allowed on "
"root pools"));
(void) zfs_error(hdl, EZFS_NOTSUP, errbuf);
} else {
(void) zfs_standard_error(hdl, err, errbuf);
}
break;
case EINVAL:
if (prop == ZPROP_INVAL) {
(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
} else {
(void) zfs_standard_error(hdl, err, errbuf);
}
break;
case EACCES:
if (prop == ZFS_PROP_KEYLOCATION) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"keylocation may only be set on encryption roots"));
(void) zfs_error(hdl, EZFS_BADPROP, errbuf);
} else {
(void) zfs_standard_error(hdl, err, errbuf);
}
break;
case EOVERFLOW:
/*
* This platform can't address a volume this big.
*/
#ifdef _ILP32
if (prop == ZFS_PROP_VOLSIZE) {
(void) zfs_error(hdl, EZFS_VOLTOOBIG, errbuf);
break;
}
#endif
/* FALLTHROUGH */
default:
(void) zfs_standard_error(hdl, err, errbuf);
}
}
/*
* Given a property name and value, set the property for the given dataset.
*/
int
zfs_prop_set(zfs_handle_t *zhp, const char *propname, const char *propval)
{
int ret = -1;
char errbuf[1024];
libzfs_handle_t *hdl = zhp->zfs_hdl;
nvlist_t *nvl = NULL;
(void) snprintf(errbuf, sizeof (errbuf),
dgettext(TEXT_DOMAIN, "cannot set property for '%s'"),
zhp->zfs_name);
if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0 ||
nvlist_add_string(nvl, propname, propval) != 0) {
(void) no_memory(hdl);
goto error;
}
ret = zfs_prop_set_list(zhp, nvl);
error:
nvlist_free(nvl);
return (ret);
}
/*
* Given an nvlist of property names and values, set the properties for the
* given dataset.
*/
int
zfs_prop_set_list(zfs_handle_t *zhp, nvlist_t *props)
{
zfs_cmd_t zc = { 0 };
int ret = -1;
prop_changelist_t **cls = NULL;
int cl_idx;
char errbuf[1024];
libzfs_handle_t *hdl = zhp->zfs_hdl;
nvlist_t *nvl;
int nvl_len;
int added_resv = 0;
(void) snprintf(errbuf, sizeof (errbuf),
dgettext(TEXT_DOMAIN, "cannot set property for '%s'"),
zhp->zfs_name);
if ((nvl = zfs_valid_proplist(hdl, zhp->zfs_type, props,
zfs_prop_get_int(zhp, ZFS_PROP_ZONED), zhp, zhp->zpool_hdl,
B_FALSE, errbuf)) == NULL)
goto error;
/*
* We have to check for any extra properties which need to be added
* before computing the length of the nvlist.
*/
for (nvpair_t *elem = nvlist_next_nvpair(nvl, NULL);
elem != NULL;
elem = nvlist_next_nvpair(nvl, elem)) {
if (zfs_name_to_prop(nvpair_name(elem)) == ZFS_PROP_VOLSIZE &&
(added_resv = zfs_add_synthetic_resv(zhp, nvl)) == -1) {
goto error;
}
}
if (added_resv != 1 &&
(added_resv = zfs_fix_auto_resv(zhp, nvl)) == -1) {
goto error;
}
/*
* Check how many properties we're setting and allocate an array to
* store changelist pointers for postfix().
*/
nvl_len = 0;
for (nvpair_t *elem = nvlist_next_nvpair(nvl, NULL);
elem != NULL;
elem = nvlist_next_nvpair(nvl, elem))
nvl_len++;
if ((cls = calloc(nvl_len, sizeof (prop_changelist_t *))) == NULL)
goto error;
cl_idx = 0;
for (nvpair_t *elem = nvlist_next_nvpair(nvl, NULL);
elem != NULL;
elem = nvlist_next_nvpair(nvl, elem)) {
zfs_prop_t prop = zfs_name_to_prop(nvpair_name(elem));
assert(cl_idx < nvl_len);
/*
* We don't want to unmount & remount the dataset when changing
* its canmount property to 'on' or 'noauto'. We only use
* the changelist logic to unmount when setting canmount=off.
*/
if (prop != ZFS_PROP_CANMOUNT ||
(fnvpair_value_uint64(elem) == ZFS_CANMOUNT_OFF &&
zfs_is_mounted(zhp, NULL))) {
cls[cl_idx] = changelist_gather(zhp, prop, 0, 0);
if (cls[cl_idx] == NULL)
goto error;
}
if (prop == ZFS_PROP_MOUNTPOINT &&
changelist_haszonedchild(cls[cl_idx])) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"child dataset with inherited mountpoint is used "
"in a non-global zone"));
ret = zfs_error(hdl, EZFS_ZONED, errbuf);
goto error;
}
if (cls[cl_idx] != NULL &&
(ret = changelist_prefix(cls[cl_idx])) != 0)
goto error;
cl_idx++;
}
assert(cl_idx == nvl_len);
/*
* Execute the corresponding ioctl() to set this list of properties.
*/
(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
if ((ret = zcmd_write_src_nvlist(hdl, &zc, nvl)) != 0 ||
(ret = zcmd_alloc_dst_nvlist(hdl, &zc, 0)) != 0)
goto error;
ret = zfs_ioctl(hdl, ZFS_IOC_SET_PROP, &zc);
if (ret != 0) {
if (zc.zc_nvlist_dst_filled == B_FALSE) {
(void) zfs_standard_error(hdl, errno, errbuf);
goto error;
}
/* Get the list of unset properties back and report them. */
nvlist_t *errorprops = NULL;
if (zcmd_read_dst_nvlist(hdl, &zc, &errorprops) != 0)
goto error;
for (nvpair_t *elem = nvlist_next_nvpair(errorprops, NULL);
elem != NULL;
elem = nvlist_next_nvpair(errorprops, elem)) {
zfs_prop_t prop = zfs_name_to_prop(nvpair_name(elem));
zfs_setprop_error(hdl, prop, errno, errbuf);
}
nvlist_free(errorprops);
if (added_resv && errno == ENOSPC) {
/* clean up the volsize property we tried to set */
uint64_t old_volsize = zfs_prop_get_int(zhp,
ZFS_PROP_VOLSIZE);
nvlist_free(nvl);
nvl = NULL;
zcmd_free_nvlists(&zc);
if (nvlist_alloc(&nvl, NV_UNIQUE_NAME, 0) != 0)
goto error;
if (nvlist_add_uint64(nvl,
zfs_prop_to_name(ZFS_PROP_VOLSIZE),
old_volsize) != 0)
goto error;
if (zcmd_write_src_nvlist(hdl, &zc, nvl) != 0)
goto error;
(void) zfs_ioctl(hdl, ZFS_IOC_SET_PROP, &zc);
}
} else {
for (cl_idx = 0; cl_idx < nvl_len; cl_idx++) {
if (cls[cl_idx] != NULL) {
int clp_err = changelist_postfix(cls[cl_idx]);
if (clp_err != 0)
ret = clp_err;
}
}
/*
* Refresh the statistics so the new property value
* is reflected.
*/
if (ret == 0)
(void) get_stats(zhp);
}
error:
nvlist_free(nvl);
zcmd_free_nvlists(&zc);
if (cls != NULL) {
for (cl_idx = 0; cl_idx < nvl_len; cl_idx++) {
if (cls[cl_idx] != NULL)
changelist_free(cls[cl_idx]);
}
free(cls);
}
return (ret);
}
/*
* Given a property, inherit the value from the parent dataset, or if received
* is TRUE, revert to the received value, if any.
*/
int
zfs_prop_inherit(zfs_handle_t *zhp, const char *propname, boolean_t received)
{
zfs_cmd_t zc = { 0 };
int ret;
prop_changelist_t *cl;
libzfs_handle_t *hdl = zhp->zfs_hdl;
char errbuf[1024];
zfs_prop_t prop;
(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
"cannot inherit %s for '%s'"), propname, zhp->zfs_name);
zc.zc_cookie = received;
if ((prop = zfs_name_to_prop(propname)) == ZPROP_INVAL) {
/*
* For user properties, the amount of work we have to do is very
* small, so just do it here.
*/
if (!zfs_prop_user(propname)) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"invalid property"));
return (zfs_error(hdl, EZFS_BADPROP, errbuf));
}
(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
(void) strlcpy(zc.zc_value, propname, sizeof (zc.zc_value));
if (zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_INHERIT_PROP, &zc) != 0)
return (zfs_standard_error(hdl, errno, errbuf));
return (0);
}
/*
* Verify that this property is inheritable.
*/
if (zfs_prop_readonly(prop))
return (zfs_error(hdl, EZFS_PROPREADONLY, errbuf));
if (!zfs_prop_inheritable(prop) && !received)
return (zfs_error(hdl, EZFS_PROPNONINHERIT, errbuf));
/*
* Check to see if the value applies to this type
*/
if (!zfs_prop_valid_for_type(prop, zhp->zfs_type))
return (zfs_error(hdl, EZFS_PROPTYPE, errbuf));
/*
* Normalize the name, to get rid of shorthand abbreviations.
*/
propname = zfs_prop_to_name(prop);
(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
(void) strlcpy(zc.zc_value, propname, sizeof (zc.zc_value));
if (prop == ZFS_PROP_MOUNTPOINT && getzoneid() == GLOBAL_ZONEID &&
zfs_prop_get_int(zhp, ZFS_PROP_ZONED)) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"dataset is used in a non-global zone"));
return (zfs_error(hdl, EZFS_ZONED, errbuf));
}
/*
* Determine datasets which will be affected by this change, if any.
*/
if ((cl = changelist_gather(zhp, prop, 0, 0)) == NULL)
return (-1);
if (prop == ZFS_PROP_MOUNTPOINT && changelist_haszonedchild(cl)) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"child dataset with inherited mountpoint is used "
"in a non-global zone"));
ret = zfs_error(hdl, EZFS_ZONED, errbuf);
goto error;
}
if ((ret = changelist_prefix(cl)) != 0)
goto error;
if ((ret = zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_INHERIT_PROP, &zc)) != 0) {
return (zfs_standard_error(hdl, errno, errbuf));
} else {
if ((ret = changelist_postfix(cl)) != 0)
goto error;
/*
* Refresh the statistics so the new property is reflected.
*/
(void) get_stats(zhp);
}
error:
changelist_free(cl);
return (ret);
}
/*
* True DSL properties are stored in an nvlist. The following two functions
* extract them appropriately.
*/
static uint64_t
getprop_uint64(zfs_handle_t *zhp, zfs_prop_t prop, char **source)
{
nvlist_t *nv;
uint64_t value;
*source = NULL;
if (nvlist_lookup_nvlist(zhp->zfs_props,
zfs_prop_to_name(prop), &nv) == 0) {
verify(nvlist_lookup_uint64(nv, ZPROP_VALUE, &value) == 0);
(void) nvlist_lookup_string(nv, ZPROP_SOURCE, source);
} else {
verify(!zhp->zfs_props_table ||
zhp->zfs_props_table[prop] == B_TRUE);
value = zfs_prop_default_numeric(prop);
*source = "";
}
return (value);
}
static const char *
getprop_string(zfs_handle_t *zhp, zfs_prop_t prop, char **source)
{
nvlist_t *nv;
const char *value;
*source = NULL;
if (nvlist_lookup_nvlist(zhp->zfs_props,
zfs_prop_to_name(prop), &nv) == 0) {
value = fnvlist_lookup_string(nv, ZPROP_VALUE);
(void) nvlist_lookup_string(nv, ZPROP_SOURCE, source);
} else {
verify(!zhp->zfs_props_table ||
zhp->zfs_props_table[prop] == B_TRUE);
value = zfs_prop_default_string(prop);
*source = "";
}
return (value);
}
static boolean_t
zfs_is_recvd_props_mode(zfs_handle_t *zhp)
{
return (zhp->zfs_props == zhp->zfs_recvd_props);
}
static void
zfs_set_recvd_props_mode(zfs_handle_t *zhp, uint64_t *cookie)
{
*cookie = (uint64_t)(uintptr_t)zhp->zfs_props;
zhp->zfs_props = zhp->zfs_recvd_props;
}
static void
zfs_unset_recvd_props_mode(zfs_handle_t *zhp, uint64_t *cookie)
{
zhp->zfs_props = (nvlist_t *)(uintptr_t)*cookie;
*cookie = 0;
}
/*
* Internal function for getting a numeric property. Both zfs_prop_get() and
* zfs_prop_get_int() are built using this interface.
*
* Certain properties can be overridden using 'mount -o'. In this case, scan
* the contents of the /etc/mnttab entry, searching for the appropriate options.
* If they differ from the on-disk values, report the current values and mark
* the source "temporary".
*/
static int
get_numeric_property(zfs_handle_t *zhp, zfs_prop_t prop, zprop_source_t *src,
char **source, uint64_t *val)
{
zfs_cmd_t zc = { 0 };
nvlist_t *zplprops = NULL;
struct mnttab mnt;
char *mntopt_on = NULL;
char *mntopt_off = NULL;
boolean_t received = zfs_is_recvd_props_mode(zhp);
*source = NULL;
switch (prop) {
case ZFS_PROP_ATIME:
mntopt_on = MNTOPT_ATIME;
mntopt_off = MNTOPT_NOATIME;
break;
case ZFS_PROP_DEVICES:
mntopt_on = MNTOPT_DEVICES;
mntopt_off = MNTOPT_NODEVICES;
break;
case ZFS_PROP_EXEC:
mntopt_on = MNTOPT_EXEC;
mntopt_off = MNTOPT_NOEXEC;
break;
case ZFS_PROP_READONLY:
mntopt_on = MNTOPT_RO;
mntopt_off = MNTOPT_RW;
break;
case ZFS_PROP_SETUID:
mntopt_on = MNTOPT_SETUID;
mntopt_off = MNTOPT_NOSETUID;
break;
case ZFS_PROP_XATTR:
mntopt_on = MNTOPT_XATTR;
mntopt_off = MNTOPT_NOXATTR;
break;
case ZFS_PROP_NBMAND:
mntopt_on = MNTOPT_NBMAND;
mntopt_off = MNTOPT_NONBMAND;
break;
default:
break;
}
/*
* Because looking up the mount options is potentially expensive
* (iterating over all of /etc/mnttab), we defer its calculation until
* we're looking up a property which requires its presence.
*/
if (!zhp->zfs_mntcheck &&
(mntopt_on != NULL || prop == ZFS_PROP_MOUNTED)) {
libzfs_handle_t *hdl = zhp->zfs_hdl;
struct mnttab entry;
if (libzfs_mnttab_find(hdl, zhp->zfs_name, &entry) == 0) {
zhp->zfs_mntopts = zfs_strdup(hdl,
entry.mnt_mntopts);
if (zhp->zfs_mntopts == NULL)
return (-1);
}
zhp->zfs_mntcheck = B_TRUE;
}
if (zhp->zfs_mntopts == NULL)
mnt.mnt_mntopts = "";
else
mnt.mnt_mntopts = zhp->zfs_mntopts;
switch (prop) {
case ZFS_PROP_ATIME:
case ZFS_PROP_DEVICES:
case ZFS_PROP_EXEC:
case ZFS_PROP_READONLY:
case ZFS_PROP_SETUID:
case ZFS_PROP_XATTR:
case ZFS_PROP_NBMAND:
*val = getprop_uint64(zhp, prop, source);
if (received)
break;
if (hasmntopt(&mnt, mntopt_on) && !*val) {
*val = B_TRUE;
if (src)
*src = ZPROP_SRC_TEMPORARY;
} else if (hasmntopt(&mnt, mntopt_off) && *val) {
*val = B_FALSE;
if (src)
*src = ZPROP_SRC_TEMPORARY;
}
break;
case ZFS_PROP_CANMOUNT:
case ZFS_PROP_VOLSIZE:
case ZFS_PROP_QUOTA:
case ZFS_PROP_REFQUOTA:
case ZFS_PROP_RESERVATION:
case ZFS_PROP_REFRESERVATION:
case ZFS_PROP_FILESYSTEM_LIMIT:
case ZFS_PROP_SNAPSHOT_LIMIT:
case ZFS_PROP_FILESYSTEM_COUNT:
case ZFS_PROP_SNAPSHOT_COUNT:
*val = getprop_uint64(zhp, prop, source);
if (*source == NULL) {
/* not default, must be local */
*source = zhp->zfs_name;
}
break;
case ZFS_PROP_MOUNTED:
*val = (zhp->zfs_mntopts != NULL);
break;
case ZFS_PROP_NUMCLONES:
*val = zhp->zfs_dmustats.dds_num_clones;
break;
case ZFS_PROP_VERSION:
case ZFS_PROP_NORMALIZE:
case ZFS_PROP_UTF8ONLY:
case ZFS_PROP_CASE:
if (!zfs_prop_valid_for_type(prop, zhp->zfs_head_type) ||
zcmd_alloc_dst_nvlist(zhp->zfs_hdl, &zc, 0) != 0)
return (-1);
(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
if (zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_OBJSET_ZPLPROPS, &zc)) {
zcmd_free_nvlists(&zc);
return (-1);
}
if (zcmd_read_dst_nvlist(zhp->zfs_hdl, &zc, &zplprops) != 0 ||
nvlist_lookup_uint64(zplprops, zfs_prop_to_name(prop),
val) != 0) {
zcmd_free_nvlists(&zc);
return (-1);
}
nvlist_free(zplprops);
zcmd_free_nvlists(&zc);
break;
case ZFS_PROP_INCONSISTENT:
*val = zhp->zfs_dmustats.dds_inconsistent;
break;
default:
switch (zfs_prop_get_type(prop)) {
case PROP_TYPE_NUMBER:
case PROP_TYPE_INDEX:
*val = getprop_uint64(zhp, prop, source);
/*
* If we tried to use a default value for a
* readonly property, it means that it was not
* present. Note this only applies to "truly"
* readonly properties, not set-once properties
* like volblocksize.
*/
if (zfs_prop_readonly(prop) &&
!zfs_prop_setonce(prop) &&
*source != NULL && (*source)[0] == '\0') {
*source = NULL;
return (-1);
}
break;
case PROP_TYPE_STRING:
default:
zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
"cannot get non-numeric property"));
return (zfs_error(zhp->zfs_hdl, EZFS_BADPROP,
dgettext(TEXT_DOMAIN, "internal error")));
}
}
return (0);
}
/*
* Calculate the source type, given the raw source string.
*/
static void
get_source(zfs_handle_t *zhp, zprop_source_t *srctype, char *source,
char *statbuf, size_t statlen)
{
if (statbuf == NULL || *srctype == ZPROP_SRC_TEMPORARY)
return;
if (source == NULL) {
*srctype = ZPROP_SRC_NONE;
} else if (source[0] == '\0') {
*srctype = ZPROP_SRC_DEFAULT;
} else if (strstr(source, ZPROP_SOURCE_VAL_RECVD) != NULL) {
*srctype = ZPROP_SRC_RECEIVED;
} else {
if (strcmp(source, zhp->zfs_name) == 0) {
*srctype = ZPROP_SRC_LOCAL;
} else {
(void) strlcpy(statbuf, source, statlen);
*srctype = ZPROP_SRC_INHERITED;
}
}
}
int
zfs_prop_get_recvd(zfs_handle_t *zhp, const char *propname, char *propbuf,
size_t proplen, boolean_t literal)
{
zfs_prop_t prop;
int err = 0;
if (zhp->zfs_recvd_props == NULL)
if (get_recvd_props_ioctl(zhp) != 0)
return (-1);
prop = zfs_name_to_prop(propname);
if (prop != ZPROP_INVAL) {
uint64_t cookie;
if (!nvlist_exists(zhp->zfs_recvd_props, propname))
return (-1);
zfs_set_recvd_props_mode(zhp, &cookie);
err = zfs_prop_get(zhp, prop, propbuf, proplen,
NULL, NULL, 0, literal);
zfs_unset_recvd_props_mode(zhp, &cookie);
} else {
nvlist_t *propval;
char *recvdval;
if (nvlist_lookup_nvlist(zhp->zfs_recvd_props,
propname, &propval) != 0)
return (-1);
verify(nvlist_lookup_string(propval, ZPROP_VALUE,
&recvdval) == 0);
(void) strlcpy(propbuf, recvdval, proplen);
}
return (err == 0 ? 0 : -1);
}
static int
get_clones_string(zfs_handle_t *zhp, char *propbuf, size_t proplen)
{
nvlist_t *value;
nvpair_t *pair;
value = zfs_get_clones_nvl(zhp);
if (value == NULL)
return (-1);
propbuf[0] = '\0';
for (pair = nvlist_next_nvpair(value, NULL); pair != NULL;
pair = nvlist_next_nvpair(value, pair)) {
if (propbuf[0] != '\0')
(void) strlcat(propbuf, ",", proplen);
(void) strlcat(propbuf, nvpair_name(pair), proplen);
}
return (0);
}
struct get_clones_arg {
uint64_t numclones;
nvlist_t *value;
const char *origin;
char buf[ZFS_MAX_DATASET_NAME_LEN];
};
int
get_clones_cb(zfs_handle_t *zhp, void *arg)
{
struct get_clones_arg *gca = arg;
if (gca->numclones == 0) {
zfs_close(zhp);
return (0);
}
if (zfs_prop_get(zhp, ZFS_PROP_ORIGIN, gca->buf, sizeof (gca->buf),
NULL, NULL, 0, B_TRUE) != 0)
goto out;
if (strcmp(gca->buf, gca->origin) == 0) {
fnvlist_add_boolean(gca->value, zfs_get_name(zhp));
gca->numclones--;
}
out:
(void) zfs_iter_children(zhp, get_clones_cb, gca);
zfs_close(zhp);
return (0);
}
nvlist_t *
zfs_get_clones_nvl(zfs_handle_t *zhp)
{
nvlist_t *nv, *value;
if (nvlist_lookup_nvlist(zhp->zfs_props,
zfs_prop_to_name(ZFS_PROP_CLONES), &nv) != 0) {
struct get_clones_arg gca;
/*
* if this is a snapshot, then the kernel wasn't able
* to get the clones. Do it by slowly iterating.
*/
if (zhp->zfs_type != ZFS_TYPE_SNAPSHOT)
return (NULL);
if (nvlist_alloc(&nv, NV_UNIQUE_NAME, 0) != 0)
return (NULL);
if (nvlist_alloc(&value, NV_UNIQUE_NAME, 0) != 0) {
nvlist_free(nv);
return (NULL);
}
gca.numclones = zfs_prop_get_int(zhp, ZFS_PROP_NUMCLONES);
gca.value = value;
gca.origin = zhp->zfs_name;
if (gca.numclones != 0) {
zfs_handle_t *root;
char pool[ZFS_MAX_DATASET_NAME_LEN];
char *cp = pool;
/* get the pool name */
(void) strlcpy(pool, zhp->zfs_name, sizeof (pool));
(void) strsep(&cp, "/@");
root = zfs_open(zhp->zfs_hdl, pool,
ZFS_TYPE_FILESYSTEM);
(void) get_clones_cb(root, &gca);
}
if (gca.numclones != 0 ||
nvlist_add_nvlist(nv, ZPROP_VALUE, value) != 0 ||
nvlist_add_nvlist(zhp->zfs_props,
zfs_prop_to_name(ZFS_PROP_CLONES), nv) != 0) {
nvlist_free(nv);
nvlist_free(value);
return (NULL);
}
nvlist_free(nv);
nvlist_free(value);
verify(0 == nvlist_lookup_nvlist(zhp->zfs_props,
zfs_prop_to_name(ZFS_PROP_CLONES), &nv));
}
verify(nvlist_lookup_nvlist(nv, ZPROP_VALUE, &value) == 0);
return (value);
}
/*
* Accepts a property and value and checks that the value
* matches the one found by the channel program. If they are
* not equal, print both of them.
*/
void
zcp_check(zfs_handle_t *zhp, zfs_prop_t prop, uint64_t intval,
const char *strval)
{
if (!zhp->zfs_hdl->libzfs_prop_debug)
return;
int error;
char *poolname = zhp->zpool_hdl->zpool_name;
const char *program =
"args = ...\n"
"ds = args['dataset']\n"
"prop = args['property']\n"
"value, setpoint = zfs.get_prop(ds, prop)\n"
"return {value=value, setpoint=setpoint}\n";
nvlist_t *outnvl;
nvlist_t *retnvl;
nvlist_t *argnvl = fnvlist_alloc();
fnvlist_add_string(argnvl, "dataset", zhp->zfs_name);
fnvlist_add_string(argnvl, "property", zfs_prop_to_name(prop));
error = lzc_channel_program_nosync(poolname, program,
10 * 1000 * 1000, 10 * 1024 * 1024, argnvl, &outnvl);
if (error == 0) {
retnvl = fnvlist_lookup_nvlist(outnvl, "return");
if (zfs_prop_get_type(prop) == PROP_TYPE_NUMBER) {
int64_t ans;
error = nvlist_lookup_int64(retnvl, "value", &ans);
if (error != 0) {
(void) fprintf(stderr, "zcp check error: %u\n",
error);
return;
}
if (ans != intval) {
(void) fprintf(stderr,
"%s: zfs found %lld, but zcp found %lld\n",
zfs_prop_to_name(prop),
(longlong_t)intval, (longlong_t)ans);
}
} else {
char *str_ans;
error = nvlist_lookup_string(retnvl, "value", &str_ans);
if (error != 0) {
(void) fprintf(stderr, "zcp check error: %u\n",
error);
return;
}
if (strcmp(strval, str_ans) != 0) {
(void) fprintf(stderr,
"%s: zfs found %s, but zcp found %s\n",
zfs_prop_to_name(prop),
strval, str_ans);
}
}
} else {
(void) fprintf(stderr,
"zcp check failed, channel program error: %u\n", error);
}
nvlist_free(argnvl);
nvlist_free(outnvl);
}
/*
* Retrieve a property from the given object. If 'literal' is specified, then
* numbers are left as exact values. Otherwise, numbers are converted to a
* human-readable form.
*
* Returns 0 on success, or -1 on error.
*/
int
zfs_prop_get(zfs_handle_t *zhp, zfs_prop_t prop, char *propbuf, size_t proplen,
zprop_source_t *src, char *statbuf, size_t statlen, boolean_t literal)
{
char *source = NULL;
uint64_t val;
const char *str;
const char *strval;
boolean_t received = zfs_is_recvd_props_mode(zhp);
/*
* Check to see if this property applies to our object
*/
if (!zfs_prop_valid_for_type(prop, zhp->zfs_type))
return (-1);
if (received && zfs_prop_readonly(prop))
return (-1);
if (src)
*src = ZPROP_SRC_NONE;
switch (prop) {
case ZFS_PROP_CREATION:
/*
* 'creation' is a time_t stored in the statistics. We convert
* this into a string unless 'literal' is specified.
*/
{
val = getprop_uint64(zhp, prop, &source);
time_t time = (time_t)val;
struct tm t;
if (literal ||
localtime_r(&time, &t) == NULL ||
strftime(propbuf, proplen, "%a %b %e %k:%M %Y",
&t) == 0)
(void) snprintf(propbuf, proplen, "%llu", val);
}
zcp_check(zhp, prop, val, NULL);
break;
case ZFS_PROP_MOUNTPOINT:
/*
* Getting the precise mountpoint can be tricky.
*
* - for 'none' or 'legacy', return those values.
* - for inherited mountpoints, we want to take everything
* after our ancestor and append it to the inherited value.
*
* If the pool has an alternate root, we want to prepend that
* root to any values we return.
*/
str = getprop_string(zhp, prop, &source);
if (str[0] == '/') {
char buf[MAXPATHLEN];
char *root = buf;
const char *relpath;
/*
* If we inherit the mountpoint, even from a dataset
* with a received value, the source will be the path of
* the dataset we inherit from. If source is
* ZPROP_SOURCE_VAL_RECVD, the received value is not
* inherited.
*/
if (strcmp(source, ZPROP_SOURCE_VAL_RECVD) == 0) {
relpath = "";
} else {
relpath = zhp->zfs_name + strlen(source);
if (relpath[0] == '/')
relpath++;
}
if ((zpool_get_prop(zhp->zpool_hdl,
ZPOOL_PROP_ALTROOT, buf, MAXPATHLEN, NULL,
B_FALSE)) || (strcmp(root, "-") == 0))
root[0] = '\0';
/*
* Special case an alternate root of '/'. This will
* avoid having multiple leading slashes in the
* mountpoint path.
*/
if (strcmp(root, "/") == 0)
root++;
/*
* If the mountpoint is '/' then skip over this
* if we are obtaining either an alternate root or
* an inherited mountpoint.
*/
if (str[1] == '\0' && (root[0] != '\0' ||
relpath[0] != '\0'))
str++;
if (relpath[0] == '\0')
(void) snprintf(propbuf, proplen, "%s%s",
root, str);
else
(void) snprintf(propbuf, proplen, "%s%s%s%s",
root, str, relpath[0] == '@' ? "" : "/",
relpath);
} else {
/* 'legacy' or 'none' */
(void) strlcpy(propbuf, str, proplen);
}
zcp_check(zhp, prop, 0, propbuf);
break;
case ZFS_PROP_ORIGIN:
str = getprop_string(zhp, prop, &source);
if (str == NULL)
return (-1);
(void) strlcpy(propbuf, str, proplen);
zcp_check(zhp, prop, 0, str);
break;
case ZFS_PROP_CLONES:
if (get_clones_string(zhp, propbuf, proplen) != 0)
return (-1);
break;
case ZFS_PROP_QUOTA:
case ZFS_PROP_REFQUOTA:
case ZFS_PROP_RESERVATION:
case ZFS_PROP_REFRESERVATION:
if (get_numeric_property(zhp, prop, src, &source, &val) != 0)
return (-1);
/*
* If quota or reservation is 0, we translate this into 'none'
* (unless literal is set), and indicate that it's the default
* value. Otherwise, we print the number nicely and indicate
* that its set locally.
*/
if (val == 0) {
if (literal)
(void) strlcpy(propbuf, "0", proplen);
else
(void) strlcpy(propbuf, "none", proplen);
} else {
if (literal)
(void) snprintf(propbuf, proplen, "%llu",
(u_longlong_t)val);
else
zfs_nicenum(val, propbuf, proplen);
}
zcp_check(zhp, prop, val, NULL);
break;
case ZFS_PROP_FILESYSTEM_LIMIT:
case ZFS_PROP_SNAPSHOT_LIMIT:
case ZFS_PROP_FILESYSTEM_COUNT:
case ZFS_PROP_SNAPSHOT_COUNT:
if (get_numeric_property(zhp, prop, src, &source, &val) != 0)
return (-1);
/*
* If limit is UINT64_MAX, we translate this into 'none' (unless
* literal is set), and indicate that it's the default value.
* Otherwise, we print the number nicely and indicate that it's
* set locally.
*/
if (literal) {
(void) snprintf(propbuf, proplen, "%llu",
(u_longlong_t)val);
} else if (val == UINT64_MAX) {
(void) strlcpy(propbuf, "none", proplen);
} else {
zfs_nicenum(val, propbuf, proplen);
}
zcp_check(zhp, prop, val, NULL);
break;
case ZFS_PROP_REFRATIO:
case ZFS_PROP_COMPRESSRATIO:
if (get_numeric_property(zhp, prop, src, &source, &val) != 0)
return (-1);
(void) snprintf(propbuf, proplen, "%llu.%02llux",
(u_longlong_t)(val / 100),
(u_longlong_t)(val % 100));
zcp_check(zhp, prop, val, NULL);
break;
case ZFS_PROP_TYPE:
switch (zhp->zfs_type) {
case ZFS_TYPE_FILESYSTEM:
str = "filesystem";
break;
case ZFS_TYPE_VOLUME:
str = "volume";
break;
case ZFS_TYPE_SNAPSHOT:
str = "snapshot";
break;
case ZFS_TYPE_BOOKMARK:
str = "bookmark";
break;
default:
abort();
}
(void) snprintf(propbuf, proplen, "%s", str);
zcp_check(zhp, prop, 0, propbuf);
break;
case ZFS_PROP_MOUNTED:
/*
* The 'mounted' property is a pseudo-property that described
* whether the filesystem is currently mounted. Even though
* it's a boolean value, the typical values of "on" and "off"
* don't make sense, so we translate to "yes" and "no".
*/
if (get_numeric_property(zhp, ZFS_PROP_MOUNTED,
src, &source, &val) != 0)
return (-1);
if (val)
(void) strlcpy(propbuf, "yes", proplen);
else
(void) strlcpy(propbuf, "no", proplen);
break;
case ZFS_PROP_NAME:
/*
* The 'name' property is a pseudo-property derived from the
* dataset name. It is presented as a real property to simplify
* consumers.
*/
(void) strlcpy(propbuf, zhp->zfs_name, proplen);
zcp_check(zhp, prop, 0, propbuf);
break;
case ZFS_PROP_MLSLABEL:
{
m_label_t *new_sl = NULL;
char *ascii = NULL; /* human readable label */
(void) strlcpy(propbuf,
getprop_string(zhp, prop, &source), proplen);
if (literal || (strcasecmp(propbuf,
ZFS_MLSLABEL_DEFAULT) == 0))
break;
/*
* Try to translate the internal hex string to
* human-readable output. If there are any
* problems just use the hex string.
*/
if (str_to_label(propbuf, &new_sl, MAC_LABEL,
L_NO_CORRECTION, NULL) == -1) {
m_label_free(new_sl);
break;
}
if (label_to_str(new_sl, &ascii, M_LABEL,
DEF_NAMES) != 0) {
if (ascii)
free(ascii);
m_label_free(new_sl);
break;
}
m_label_free(new_sl);
(void) strlcpy(propbuf, ascii, proplen);
free(ascii);
}
break;
case ZFS_PROP_GUID:
case ZFS_PROP_CREATETXG:
/*
* GUIDs are stored as numbers, but they are identifiers.
* We don't want them to be pretty printed, because pretty
* printing mangles the ID into a truncated and useless value.
*/
if (get_numeric_property(zhp, prop, src, &source, &val) != 0)
return (-1);
(void) snprintf(propbuf, proplen, "%llu", (u_longlong_t)val);
zcp_check(zhp, prop, val, NULL);
break;
default:
switch (zfs_prop_get_type(prop)) {
case PROP_TYPE_NUMBER:
if (get_numeric_property(zhp, prop, src,
&source, &val) != 0) {
return (-1);
}
if (literal) {
(void) snprintf(propbuf, proplen, "%llu",
(u_longlong_t)val);
} else {
zfs_nicenum(val, propbuf, proplen);
}
zcp_check(zhp, prop, val, NULL);
break;
case PROP_TYPE_STRING:
str = getprop_string(zhp, prop, &source);
if (str == NULL)
return (-1);
(void) strlcpy(propbuf, str, proplen);
zcp_check(zhp, prop, 0, str);
break;
case PROP_TYPE_INDEX:
if (get_numeric_property(zhp, prop, src,
&source, &val) != 0)
return (-1);
if (zfs_prop_index_to_string(prop, val, &strval) != 0)
return (-1);
(void) strlcpy(propbuf, strval, proplen);
zcp_check(zhp, prop, 0, strval);
break;
default:
abort();
}
}
get_source(zhp, src, source, statbuf, statlen);
return (0);
}
/*
* Utility function to get the given numeric property. Does no validation that
* the given property is the appropriate type; should only be used with
* hard-coded property types.
*/
uint64_t
zfs_prop_get_int(zfs_handle_t *zhp, zfs_prop_t prop)
{
char *source;
uint64_t val;
(void) get_numeric_property(zhp, prop, NULL, &source, &val);
return (val);
}
int
zfs_prop_set_int(zfs_handle_t *zhp, zfs_prop_t prop, uint64_t val)
{
char buf[64];
(void) snprintf(buf, sizeof (buf), "%llu", (longlong_t)val);
return (zfs_prop_set(zhp, zfs_prop_to_name(prop), buf));
}
/*
* Similar to zfs_prop_get(), but returns the value as an integer.
*/
int
zfs_prop_get_numeric(zfs_handle_t *zhp, zfs_prop_t prop, uint64_t *value,
zprop_source_t *src, char *statbuf, size_t statlen)
{
char *source;
/*
* Check to see if this property applies to our object
*/
if (!zfs_prop_valid_for_type(prop, zhp->zfs_type)) {
return (zfs_error_fmt(zhp->zfs_hdl, EZFS_PROPTYPE,
dgettext(TEXT_DOMAIN, "cannot get property '%s'"),
zfs_prop_to_name(prop)));
}
if (src)
*src = ZPROP_SRC_NONE;
if (get_numeric_property(zhp, prop, src, &source, value) != 0)
return (-1);
get_source(zhp, src, source, statbuf, statlen);
return (0);
}
static int
idmap_id_to_numeric_domain_rid(uid_t id, boolean_t isuser,
char **domainp, idmap_rid_t *ridp)
{
idmap_get_handle_t *get_hdl = NULL;
idmap_stat status;
int err = EINVAL;
if (idmap_get_create(&get_hdl) != IDMAP_SUCCESS)
goto out;
if (isuser) {
err = idmap_get_sidbyuid(get_hdl, id,
IDMAP_REQ_FLG_USE_CACHE, domainp, ridp, &status);
} else {
err = idmap_get_sidbygid(get_hdl, id,
IDMAP_REQ_FLG_USE_CACHE, domainp, ridp, &status);
}
if (err == IDMAP_SUCCESS &&
idmap_get_mappings(get_hdl) == IDMAP_SUCCESS &&
status == IDMAP_SUCCESS)
err = 0;
else
err = EINVAL;
out:
if (get_hdl)
idmap_get_destroy(get_hdl);
return (err);
}
/*
* convert the propname into parameters needed by kernel
* Eg: userquota@ahrens -> ZFS_PROP_USERQUOTA, "", 126829
* Eg: userused@matt@domain -> ZFS_PROP_USERUSED, "S-1-123-456", 789
* Eg: groupquota@staff -> ZFS_PROP_GROUPQUOTA, "", 1234
* Eg: groupused@staff -> ZFS_PROP_GROUPUSED, "", 1234
* Eg: projectquota@123 -> ZFS_PROP_PROJECTQUOTA, "", 123
* Eg: projectused@789 -> ZFS_PROP_PROJECTUSED, "", 789
*/
static int
userquota_propname_decode(const char *propname, boolean_t zoned,
zfs_userquota_prop_t *typep, char *domain, int domainlen, uint64_t *ridp)
{
zfs_userquota_prop_t type;
char *cp;
boolean_t isuser;
boolean_t isgroup;
boolean_t isproject;
struct passwd *pw;
struct group *gr;
domain[0] = '\0';
/* Figure out the property type ({user|group|project}{quota|space}) */
for (type = 0; type < ZFS_NUM_USERQUOTA_PROPS; type++) {
if (strncmp(propname, zfs_userquota_prop_prefixes[type],
strlen(zfs_userquota_prop_prefixes[type])) == 0)
break;
}
if (type == ZFS_NUM_USERQUOTA_PROPS)
return (EINVAL);
*typep = type;
isuser = (type == ZFS_PROP_USERQUOTA || type == ZFS_PROP_USERUSED ||
type == ZFS_PROP_USEROBJQUOTA ||
type == ZFS_PROP_USEROBJUSED);
isgroup = (type == ZFS_PROP_GROUPQUOTA || type == ZFS_PROP_GROUPUSED ||
type == ZFS_PROP_GROUPOBJQUOTA ||
type == ZFS_PROP_GROUPOBJUSED);
isproject = (type == ZFS_PROP_PROJECTQUOTA ||
type == ZFS_PROP_PROJECTUSED || type == ZFS_PROP_PROJECTOBJQUOTA ||
type == ZFS_PROP_PROJECTOBJUSED);
cp = strchr(propname, '@') + 1;
if (isuser && (pw = getpwnam(cp)) != NULL) {
if (zoned && getzoneid() == GLOBAL_ZONEID)
return (ENOENT);
*ridp = pw->pw_uid;
} else if (isgroup && (gr = getgrnam(cp)) != NULL) {
if (zoned && getzoneid() == GLOBAL_ZONEID)
return (ENOENT);
*ridp = gr->gr_gid;
} else if (!isproject && strchr(cp, '@')) {
/*
* It's a SID name (eg "user@domain") that needs to be
* turned into S-1-domainID-RID.
*/
directory_error_t e;
char *numericsid = NULL;
char *end;
if (zoned && getzoneid() == GLOBAL_ZONEID)
return (ENOENT);
if (isuser) {
e = directory_sid_from_user_name(NULL,
cp, &numericsid);
} else {
e = directory_sid_from_group_name(NULL,
cp, &numericsid);
}
if (e != NULL) {
directory_error_free(e);
return (ENOENT);
}
if (numericsid == NULL)
return (ENOENT);
cp = numericsid;
(void) strlcpy(domain, cp, domainlen);
cp = strrchr(domain, '-');
*cp = '\0';
cp++;
errno = 0;
*ridp = strtoull(cp, &end, 10);
free(numericsid);
if (errno != 0 || *end != '\0')
return (EINVAL);
} else {
/* It's a user/group/project ID (eg "12345"). */
char *end;
uid_t id = strtoul(cp, &end, 10);
if (*end != '\0')
return (EINVAL);
if (id > MAXUID && !isproject) {
/* It's an ephemeral ID. */
idmap_rid_t rid;
char *mapdomain;
if (idmap_id_to_numeric_domain_rid(id, isuser,
&mapdomain, &rid) != 0)
return (ENOENT);
(void) strlcpy(domain, mapdomain, domainlen);
*ridp = rid;
} else {
*ridp = id;
}
}
return (0);
}
static int
zfs_prop_get_userquota_common(zfs_handle_t *zhp, const char *propname,
uint64_t *propvalue, zfs_userquota_prop_t *typep)
{
int err;
zfs_cmd_t zc = { 0 };
(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
err = userquota_propname_decode(propname,
zfs_prop_get_int(zhp, ZFS_PROP_ZONED),
typep, zc.zc_value, sizeof (zc.zc_value), &zc.zc_guid);
zc.zc_objset_type = *typep;
if (err)
return (err);
err = ioctl(zhp->zfs_hdl->libzfs_fd, ZFS_IOC_USERSPACE_ONE, &zc);
if (err)
return (err);
*propvalue = zc.zc_cookie;
return (0);
}
int
zfs_prop_get_userquota_int(zfs_handle_t *zhp, const char *propname,
uint64_t *propvalue)
{
zfs_userquota_prop_t type;
return (zfs_prop_get_userquota_common(zhp, propname, propvalue,
&type));
}
int
zfs_prop_get_userquota(zfs_handle_t *zhp, const char *propname,
char *propbuf, int proplen, boolean_t literal)
{
int err;
uint64_t propvalue;
zfs_userquota_prop_t type;
err = zfs_prop_get_userquota_common(zhp, propname, &propvalue,
&type);
if (err)
return (err);
if (literal) {
(void) snprintf(propbuf, proplen, "%llu", propvalue);
} else if (propvalue == 0 &&
(type == ZFS_PROP_USERQUOTA || type == ZFS_PROP_GROUPQUOTA ||
type == ZFS_PROP_USEROBJQUOTA || type == ZFS_PROP_GROUPOBJQUOTA ||
type == ZFS_PROP_PROJECTQUOTA || ZFS_PROP_PROJECTOBJQUOTA)) {
(void) strlcpy(propbuf, "none", proplen);
} else if (type == ZFS_PROP_USERQUOTA || type == ZFS_PROP_GROUPQUOTA ||
type == ZFS_PROP_USERUSED || type == ZFS_PROP_GROUPUSED ||
type == ZFS_PROP_PROJECTUSED || type == ZFS_PROP_PROJECTQUOTA) {
zfs_nicenum(propvalue, propbuf, proplen);
} else {
zfs_nicenum(propvalue, propbuf, proplen);
}
return (0);
}
int
zfs_prop_get_written_int(zfs_handle_t *zhp, const char *propname,
uint64_t *propvalue)
{
int err;
zfs_cmd_t zc = { 0 };
const char *snapname;
(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
snapname = strchr(propname, '@') + 1;
if (strchr(snapname, '@')) {
(void) strlcpy(zc.zc_value, snapname, sizeof (zc.zc_value));
} else {
/* snapname is the short name, append it to zhp's fsname */
char *cp;
(void) strlcpy(zc.zc_value, zhp->zfs_name,
sizeof (zc.zc_value));
cp = strchr(zc.zc_value, '@');
if (cp != NULL)
*cp = '\0';
(void) strlcat(zc.zc_value, "@", sizeof (zc.zc_value));
(void) strlcat(zc.zc_value, snapname, sizeof (zc.zc_value));
}
err = ioctl(zhp->zfs_hdl->libzfs_fd, ZFS_IOC_SPACE_WRITTEN, &zc);
if (err)
return (err);
*propvalue = zc.zc_cookie;
return (0);
}
int
zfs_prop_get_written(zfs_handle_t *zhp, const char *propname,
char *propbuf, int proplen, boolean_t literal)
{
int err;
uint64_t propvalue;
err = zfs_prop_get_written_int(zhp, propname, &propvalue);
if (err)
return (err);
if (literal) {
(void) snprintf(propbuf, proplen, "%llu", propvalue);
} else {
zfs_nicenum(propvalue, propbuf, proplen);
}
return (0);
}
/*
* Returns the name of the given zfs handle.
*/
const char *
zfs_get_name(const zfs_handle_t *zhp)
{
return (zhp->zfs_name);
}
/*
* Returns the name of the parent pool for the given zfs handle.
*/
const char *
zfs_get_pool_name(const zfs_handle_t *zhp)
{
return (zhp->zpool_hdl->zpool_name);
}
/*
* Returns the type of the given zfs handle.
*/
zfs_type_t
zfs_get_type(const zfs_handle_t *zhp)
{
return (zhp->zfs_type);
}
/*
* Is one dataset name a child dataset of another?
*
* Needs to handle these cases:
* Dataset 1 "a/foo" "a/foo" "a/foo" "a/foo"
* Dataset 2 "a/fo" "a/foobar" "a/bar/baz" "a/foo/bar"
* Descendant? No. No. No. Yes.
*/
static boolean_t
is_descendant(const char *ds1, const char *ds2)
{
size_t d1len = strlen(ds1);
/* ds2 can't be a descendant if it's smaller */
if (strlen(ds2) < d1len)
return (B_FALSE);
/* otherwise, compare strings and verify that there's a '/' char */
return (ds2[d1len] == '/' && (strncmp(ds1, ds2, d1len) == 0));
}
/*
* Given a complete name, return just the portion that refers to the parent.
* Will return -1 if there is no parent (path is just the name of the
* pool).
*/
static int
parent_name(const char *path, char *buf, size_t buflen)
{
char *slashp;
(void) strlcpy(buf, path, buflen);
if ((slashp = strrchr(buf, '/')) == NULL)
return (-1);
*slashp = '\0';
return (0);
}
int
zfs_parent_name(zfs_handle_t *zhp, char *buf, size_t buflen)
{
return (parent_name(zfs_get_name(zhp), buf, buflen));
}
/*
* If accept_ancestor is false, then check to make sure that the given path has
* a parent, and that it exists. If accept_ancestor is true, then find the
* closest existing ancestor for the given path. In prefixlen return the
* length of already existing prefix of the given path. We also fetch the
* 'zoned' property, which is used to validate property settings when creating
* new datasets.
*/
static int
check_parents(libzfs_handle_t *hdl, const char *path, uint64_t *zoned,
boolean_t accept_ancestor, int *prefixlen)
{
zfs_cmd_t zc = { 0 };
char parent[ZFS_MAX_DATASET_NAME_LEN];
char *slash;
zfs_handle_t *zhp;
char errbuf[1024];
uint64_t is_zoned;
(void) snprintf(errbuf, sizeof (errbuf),
dgettext(TEXT_DOMAIN, "cannot create '%s'"), path);
/* get parent, and check to see if this is just a pool */
if (parent_name(path, parent, sizeof (parent)) != 0) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"missing dataset name"));
return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
}
/* check to see if the pool exists */
if ((slash = strchr(parent, '/')) == NULL)
slash = parent + strlen(parent);
(void) strncpy(zc.zc_name, parent, slash - parent);
zc.zc_name[slash - parent] = '\0';
if (ioctl(hdl->libzfs_fd, ZFS_IOC_OBJSET_STATS, &zc) != 0 &&
errno == ENOENT) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"no such pool '%s'"), zc.zc_name);
return (zfs_error(hdl, EZFS_NOENT, errbuf));
}
/* check to see if the parent dataset exists */
while ((zhp = make_dataset_handle(hdl, parent)) == NULL) {
if (errno == ENOENT && accept_ancestor) {
/*
* Go deeper to find an ancestor, give up on top level.
*/
if (parent_name(parent, parent, sizeof (parent)) != 0) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"no such pool '%s'"), zc.zc_name);
return (zfs_error(hdl, EZFS_NOENT, errbuf));
}
} else if (errno == ENOENT) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"parent does not exist"));
return (zfs_error(hdl, EZFS_NOENT, errbuf));
} else
return (zfs_standard_error(hdl, errno, errbuf));
}
is_zoned = zfs_prop_get_int(zhp, ZFS_PROP_ZONED);
if (zoned != NULL)
*zoned = is_zoned;
/* we are in a non-global zone, but parent is in the global zone */
if (getzoneid() != GLOBAL_ZONEID && !is_zoned) {
(void) zfs_standard_error(hdl, EPERM, errbuf);
zfs_close(zhp);
return (-1);
}
/* make sure parent is a filesystem */
if (zfs_get_type(zhp) != ZFS_TYPE_FILESYSTEM) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"parent is not a filesystem"));
(void) zfs_error(hdl, EZFS_BADTYPE, errbuf);
zfs_close(zhp);
return (-1);
}
zfs_close(zhp);
if (prefixlen != NULL)
*prefixlen = strlen(parent);
return (0);
}
/*
* Finds whether the dataset of the given type(s) exists.
*/
boolean_t
zfs_dataset_exists(libzfs_handle_t *hdl, const char *path, zfs_type_t types)
{
zfs_handle_t *zhp;
if (!zfs_validate_name(hdl, path, types, B_FALSE))
return (B_FALSE);
/*
* Try to get stats for the dataset, which will tell us if it exists.
*/
if ((zhp = make_dataset_handle(hdl, path)) != NULL) {
int ds_type = zhp->zfs_type;
zfs_close(zhp);
if (types & ds_type)
return (B_TRUE);
}
return (B_FALSE);
}
/*
* Given a path to 'target', create all the ancestors between
* the prefixlen portion of the path, and the target itself.
* Fail if the initial prefixlen-ancestor does not already exist.
*/
int
create_parents(libzfs_handle_t *hdl, char *target, int prefixlen)
{
zfs_handle_t *h;
char *cp;
const char *opname;
/* make sure prefix exists */
cp = target + prefixlen;
if (*cp != '/') {
assert(strchr(cp, '/') == NULL);
h = zfs_open(hdl, target, ZFS_TYPE_FILESYSTEM);
} else {
*cp = '\0';
h = zfs_open(hdl, target, ZFS_TYPE_FILESYSTEM);
*cp = '/';
}
if (h == NULL)
return (-1);
zfs_close(h);
/*
* Attempt to create, mount, and share any ancestor filesystems,
* up to the prefixlen-long one.
*/
for (cp = target + prefixlen + 1;
(cp = strchr(cp, '/')) != NULL; *cp = '/', cp++) {
*cp = '\0';
h = make_dataset_handle(hdl, target);
if (h) {
/* it already exists, nothing to do here */
zfs_close(h);
continue;
}
if (zfs_create(hdl, target, ZFS_TYPE_FILESYSTEM,
NULL) != 0) {
opname = dgettext(TEXT_DOMAIN, "create");
goto ancestorerr;
}
h = zfs_open(hdl, target, ZFS_TYPE_FILESYSTEM);
if (h == NULL) {
opname = dgettext(TEXT_DOMAIN, "open");
goto ancestorerr;
}
if (zfs_mount(h, NULL, 0) != 0) {
opname = dgettext(TEXT_DOMAIN, "mount");
goto ancestorerr;
}
if (zfs_share(h) != 0) {
opname = dgettext(TEXT_DOMAIN, "share");
goto ancestorerr;
}
zfs_close(h);
}
return (0);
ancestorerr:
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"failed to %s ancestor '%s'"), opname, target);
return (-1);
}
/*
* Creates non-existing ancestors of the given path.
*/
int
zfs_create_ancestors(libzfs_handle_t *hdl, const char *path)
{
int prefix;
char *path_copy;
char errbuf[1024];
int rc = 0;
(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
"cannot create '%s'"), path);
/*
* Check that we are not passing the nesting limit
* before we start creating any ancestors.
*/
if (dataset_nestcheck(path) != 0) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"maximum name nesting depth exceeded"));
return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
}
if (check_parents(hdl, path, NULL, B_TRUE, &prefix) != 0)
return (-1);
if ((path_copy = strdup(path)) != NULL) {
rc = create_parents(hdl, path_copy, prefix);
free(path_copy);
}
if (path_copy == NULL || rc != 0)
return (-1);
return (0);
}
/*
* Create a new filesystem or volume.
*/
int
zfs_create(libzfs_handle_t *hdl, const char *path, zfs_type_t type,
nvlist_t *props)
{
int ret;
uint64_t size = 0;
uint64_t blocksize = zfs_prop_default_numeric(ZFS_PROP_VOLBLOCKSIZE);
uint8_t *wkeydata = NULL;
uint_t wkeylen = 0;
char errbuf[1024];
char parent[MAXNAMELEN];
uint64_t zoned;
enum lzc_dataset_type ost;
zpool_handle_t *zpool_handle;
(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
"cannot create '%s'"), path);
/* validate the path, taking care to note the extended error message */
if (!zfs_validate_name(hdl, path, type, B_TRUE))
return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
if (dataset_nestcheck(path) != 0) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"maximum name nesting depth exceeded"));
return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
}
/* validate parents exist */
if (check_parents(hdl, path, &zoned, B_FALSE, NULL) != 0)
return (-1);
/*
* The failure modes when creating a dataset of a different type over
* one that already exists is a little strange. In particular, if you
* try to create a dataset on top of an existing dataset, the ioctl()
* will return ENOENT, not EEXIST. To prevent this from happening, we
* first try to see if the dataset exists.
*/
if (zfs_dataset_exists(hdl, path, ZFS_TYPE_DATASET)) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"dataset already exists"));
return (zfs_error(hdl, EZFS_EXISTS, errbuf));
}
if (type == ZFS_TYPE_VOLUME)
ost = LZC_DATSET_TYPE_ZVOL;
else
ost = LZC_DATSET_TYPE_ZFS;
/* open zpool handle for prop validation */
char pool_path[ZFS_MAX_DATASET_NAME_LEN];
(void) strlcpy(pool_path, path, sizeof (pool_path));
/* truncate pool_path at first slash */
char *p = strchr(pool_path, '/');
if (p != NULL)
*p = '\0';
if ((zpool_handle = zpool_open(hdl, pool_path)) == NULL)
return (-1);
if (props && (props = zfs_valid_proplist(hdl, type, props,
zoned, NULL, zpool_handle, B_TRUE, errbuf)) == 0) {
zpool_close(zpool_handle);
return (-1);
}
zpool_close(zpool_handle);
if (type == ZFS_TYPE_VOLUME) {
/*
* If we are creating a volume, the size and block size must
* satisfy a few restraints. First, the blocksize must be a
* valid block size between SPA_{MIN,MAX}BLOCKSIZE. Second, the
* volsize must be a multiple of the block size, and cannot be
* zero.
*/
if (props == NULL || nvlist_lookup_uint64(props,
zfs_prop_to_name(ZFS_PROP_VOLSIZE), &size) != 0) {
nvlist_free(props);
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"missing volume size"));
return (zfs_error(hdl, EZFS_BADPROP, errbuf));
}
if ((ret = nvlist_lookup_uint64(props,
zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
&blocksize)) != 0) {
if (ret == ENOENT) {
blocksize = zfs_prop_default_numeric(
ZFS_PROP_VOLBLOCKSIZE);
} else {
nvlist_free(props);
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"missing volume block size"));
return (zfs_error(hdl, EZFS_BADPROP, errbuf));
}
}
if (size == 0) {
nvlist_free(props);
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"volume size cannot be zero"));
return (zfs_error(hdl, EZFS_BADPROP, errbuf));
}
if (size % blocksize != 0) {
nvlist_free(props);
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"volume size must be a multiple of volume block "
"size"));
return (zfs_error(hdl, EZFS_BADPROP, errbuf));
}
}
(void) parent_name(path, parent, sizeof (parent));
if (zfs_crypto_create(hdl, parent, props, NULL, B_TRUE,
&wkeydata, &wkeylen) != 0) {
nvlist_free(props);
return (zfs_error(hdl, EZFS_CRYPTOFAILED, errbuf));
}
/* create the dataset */
ret = lzc_create(path, ost, props, wkeydata, wkeylen);
nvlist_free(props);
if (wkeydata != NULL)
free(wkeydata);
/* check for failure */
if (ret != 0) {
switch (errno) {
case ENOENT:
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"no such parent '%s'"), parent);
return (zfs_error(hdl, EZFS_NOENT, errbuf));
case EINVAL:
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"parent '%s' is not a filesystem"), parent);
return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
case ENOTSUP:
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"pool must be upgraded to set this "
"property or value"));
return (zfs_error(hdl, EZFS_BADVERSION, errbuf));
case ERANGE:
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"invalid property value(s) specified"));
return (zfs_error(hdl, EZFS_BADPROP, errbuf));
case EACCES:
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"encryption root's key is not loaded "
"or provided"));
return (zfs_error(hdl, EZFS_CRYPTOFAILED, errbuf));
#ifdef _ILP32
case EOVERFLOW:
/*
* This platform can't address a volume this big.
*/
if (type == ZFS_TYPE_VOLUME)
return (zfs_error(hdl, EZFS_VOLTOOBIG,
errbuf));
#endif
/* FALLTHROUGH */
default:
return (zfs_standard_error(hdl, errno, errbuf));
}
}
return (0);
}
/*
* Destroys the given dataset. The caller must make sure that the filesystem
* isn't mounted, and that there are no active dependents. If the file system
* does not exist this function does nothing.
*/
int
zfs_destroy(zfs_handle_t *zhp, boolean_t defer)
{
int error;
if (zhp->zfs_type != ZFS_TYPE_SNAPSHOT && defer)
return (EINVAL);
if (zhp->zfs_type == ZFS_TYPE_BOOKMARK) {
nvlist_t *nv = fnvlist_alloc();
fnvlist_add_boolean(nv, zhp->zfs_name);
error = lzc_destroy_bookmarks(nv, NULL);
fnvlist_free(nv);
if (error != 0) {
return (zfs_standard_error_fmt(zhp->zfs_hdl, error,
dgettext(TEXT_DOMAIN, "cannot destroy '%s'"),
zhp->zfs_name));
}
return (0);
}
if (zhp->zfs_type == ZFS_TYPE_SNAPSHOT) {
nvlist_t *nv = fnvlist_alloc();
fnvlist_add_boolean(nv, zhp->zfs_name);
error = lzc_destroy_snaps(nv, defer, NULL);
fnvlist_free(nv);
} else {
error = lzc_destroy(zhp->zfs_name);
}
if (error != 0 && error != ENOENT) {
return (zfs_standard_error_fmt(zhp->zfs_hdl, errno,
dgettext(TEXT_DOMAIN, "cannot destroy '%s'"),
zhp->zfs_name));
}
remove_mountpoint(zhp);
return (0);
}
struct destroydata {
nvlist_t *nvl;
const char *snapname;
};
static int
zfs_check_snap_cb(zfs_handle_t *zhp, void *arg)
{
struct destroydata *dd = arg;
char name[ZFS_MAX_DATASET_NAME_LEN];
int rv = 0;
(void) snprintf(name, sizeof (name),
"%s@%s", zhp->zfs_name, dd->snapname);
if (lzc_exists(name))
verify(nvlist_add_boolean(dd->nvl, name) == 0);
rv = zfs_iter_filesystems(zhp, zfs_check_snap_cb, dd);
zfs_close(zhp);
return (rv);
}
/*
* Destroys all snapshots with the given name in zhp & descendants.
*/
int
zfs_destroy_snaps(zfs_handle_t *zhp, char *snapname, boolean_t defer)
{
int ret;
struct destroydata dd = { 0 };
dd.snapname = snapname;
verify(nvlist_alloc(&dd.nvl, NV_UNIQUE_NAME, 0) == 0);
(void) zfs_check_snap_cb(zfs_handle_dup(zhp), &dd);
if (nvlist_empty(dd.nvl)) {
ret = zfs_standard_error_fmt(zhp->zfs_hdl, ENOENT,
dgettext(TEXT_DOMAIN, "cannot destroy '%s@%s'"),
zhp->zfs_name, snapname);
} else {
ret = zfs_destroy_snaps_nvl(zhp->zfs_hdl, dd.nvl, defer);
}
nvlist_free(dd.nvl);
return (ret);
}
/*
* Destroys all the snapshots named in the nvlist.
*/
int
zfs_destroy_snaps_nvl(libzfs_handle_t *hdl, nvlist_t *snaps, boolean_t defer)
{
int ret;
nvlist_t *errlist = NULL;
ret = lzc_destroy_snaps(snaps, defer, &errlist);
if (ret == 0) {
nvlist_free(errlist);
return (0);
}
if (nvlist_empty(errlist)) {
char errbuf[1024];
(void) snprintf(errbuf, sizeof (errbuf),
dgettext(TEXT_DOMAIN, "cannot destroy snapshots"));
ret = zfs_standard_error(hdl, ret, errbuf);
}
for (nvpair_t *pair = nvlist_next_nvpair(errlist, NULL);
pair != NULL; pair = nvlist_next_nvpair(errlist, pair)) {
char errbuf[1024];
(void) snprintf(errbuf, sizeof (errbuf),
dgettext(TEXT_DOMAIN, "cannot destroy snapshot %s"),
nvpair_name(pair));
switch (fnvpair_value_int32(pair)) {
case EEXIST:
zfs_error_aux(hdl,
dgettext(TEXT_DOMAIN, "snapshot is cloned"));
ret = zfs_error(hdl, EZFS_EXISTS, errbuf);
break;
default:
ret = zfs_standard_error(hdl, errno, errbuf);
break;
}
}
nvlist_free(errlist);
return (ret);
}
/*
* Clones the given dataset. The target must be of the same type as the source.
*/
int
zfs_clone(zfs_handle_t *zhp, const char *target, nvlist_t *props)
{
char parent[ZFS_MAX_DATASET_NAME_LEN];
int ret;
char errbuf[1024];
libzfs_handle_t *hdl = zhp->zfs_hdl;
uint64_t zoned;
assert(zhp->zfs_type == ZFS_TYPE_SNAPSHOT);
(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
"cannot create '%s'"), target);
/* validate the target/clone name */
if (!zfs_validate_name(hdl, target, ZFS_TYPE_FILESYSTEM, B_TRUE))
return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
/* validate parents exist */
if (check_parents(hdl, target, &zoned, B_FALSE, NULL) != 0)
return (-1);
(void) parent_name(target, parent, sizeof (parent));
/* do the clone */
if (props) {
zfs_type_t type;
if (ZFS_IS_VOLUME(zhp)) {
type = ZFS_TYPE_VOLUME;
} else {
type = ZFS_TYPE_FILESYSTEM;
}
if ((props = zfs_valid_proplist(hdl, type, props, zoned,
zhp, zhp->zpool_hdl, B_TRUE, errbuf)) == NULL)
return (-1);
if (zfs_fix_auto_resv(zhp, props) == -1) {
nvlist_free(props);
return (-1);
}
}
if (zfs_crypto_clone_check(hdl, zhp, parent, props) != 0) {
nvlist_free(props);
return (zfs_error(hdl, EZFS_CRYPTOFAILED, errbuf));
}
ret = lzc_clone(target, zhp->zfs_name, props);
nvlist_free(props);
if (ret != 0) {
switch (errno) {
case ENOENT:
/*
* The parent doesn't exist. We should have caught this
* above, but there may a race condition that has since
* destroyed the parent.
*
* At this point, we don't know whether it's the source
* that doesn't exist anymore, or whether the target
* dataset doesn't exist.
*/
zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
"no such parent '%s'"), parent);
return (zfs_error(zhp->zfs_hdl, EZFS_NOENT, errbuf));
case EXDEV:
zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
"source and target pools differ"));
return (zfs_error(zhp->zfs_hdl, EZFS_CROSSTARGET,
errbuf));
default:
return (zfs_standard_error(zhp->zfs_hdl, errno,
errbuf));
}
}
return (ret);
}
/*
* Promotes the given clone fs to be the clone parent.
*/
int
zfs_promote(zfs_handle_t *zhp)
{
libzfs_handle_t *hdl = zhp->zfs_hdl;
char snapname[ZFS_MAX_DATASET_NAME_LEN];
int ret;
char errbuf[1024];
(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
"cannot promote '%s'"), zhp->zfs_name);
if (zhp->zfs_type == ZFS_TYPE_SNAPSHOT) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"snapshots can not be promoted"));
return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
}
if (zhp->zfs_dmustats.dds_origin[0] == '\0') {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"not a cloned filesystem"));
return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
}
if (!zfs_validate_name(hdl, zhp->zfs_name, zhp->zfs_type, B_TRUE))
return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
ret = lzc_promote(zhp->zfs_name, snapname, sizeof (snapname));
if (ret != 0) {
switch (ret) {
case EEXIST:
/* There is a conflicting snapshot name. */
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"conflicting snapshot '%s' from parent '%s'"),
snapname, zhp->zfs_dmustats.dds_origin);
return (zfs_error(hdl, EZFS_EXISTS, errbuf));
default:
return (zfs_standard_error(hdl, ret, errbuf));
}
}
return (ret);
}
typedef struct snapdata {
nvlist_t *sd_nvl;
const char *sd_snapname;
} snapdata_t;
static int
zfs_snapshot_cb(zfs_handle_t *zhp, void *arg)
{
snapdata_t *sd = arg;
char name[ZFS_MAX_DATASET_NAME_LEN];
int rv = 0;
if (zfs_prop_get_int(zhp, ZFS_PROP_INCONSISTENT) == 0) {
(void) snprintf(name, sizeof (name),
"%s@%s", zfs_get_name(zhp), sd->sd_snapname);
fnvlist_add_boolean(sd->sd_nvl, name);
rv = zfs_iter_filesystems(zhp, zfs_snapshot_cb, sd);
}
zfs_close(zhp);
return (rv);
}
int
zfs_remap_indirects(libzfs_handle_t *hdl, const char *fs)
{
int err;
char errbuf[1024];
(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
"cannot remap dataset '%s'"), fs);
err = lzc_remap(fs);
if (err != 0) {
switch (err) {
case ENOTSUP:
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"pool must be upgraded"));
(void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
break;
case EINVAL:
(void) zfs_error(hdl, EZFS_BADTYPE, errbuf);
break;
default:
(void) zfs_standard_error(hdl, err, errbuf);
break;
}
}
return (err);
}
/*
* Creates snapshots. The keys in the snaps nvlist are the snapshots to be
* created.
*/
int
zfs_snapshot_nvl(libzfs_handle_t *hdl, nvlist_t *snaps, nvlist_t *props)
{
int ret;
char errbuf[1024];
nvpair_t *elem;
nvlist_t *errors;
(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
"cannot create snapshots "));
elem = NULL;
while ((elem = nvlist_next_nvpair(snaps, elem)) != NULL) {
const char *snapname = nvpair_name(elem);
/* validate the target name */
if (!zfs_validate_name(hdl, snapname, ZFS_TYPE_SNAPSHOT,
B_TRUE)) {
(void) snprintf(errbuf, sizeof (errbuf),
dgettext(TEXT_DOMAIN,
"cannot create snapshot '%s'"), snapname);
return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
}
}
/*
* get pool handle for prop validation. assumes all snaps are in the
* same pool, as does lzc_snapshot (below).
*/
char pool[ZFS_MAX_DATASET_NAME_LEN];
elem = nvlist_next_nvpair(snaps, NULL);
(void) strlcpy(pool, nvpair_name(elem), sizeof (pool));
pool[strcspn(pool, "/@")] = '\0';
zpool_handle_t *zpool_hdl = zpool_open(hdl, pool);
if (props != NULL &&
(props = zfs_valid_proplist(hdl, ZFS_TYPE_SNAPSHOT,
props, B_FALSE, NULL, zpool_hdl, B_FALSE, errbuf)) == NULL) {
zpool_close(zpool_hdl);
return (-1);
}
zpool_close(zpool_hdl);
ret = lzc_snapshot(snaps, props, &errors);
if (ret != 0) {
boolean_t printed = B_FALSE;
for (elem = nvlist_next_nvpair(errors, NULL);
elem != NULL;
elem = nvlist_next_nvpair(errors, elem)) {
(void) snprintf(errbuf, sizeof (errbuf),
dgettext(TEXT_DOMAIN,
"cannot create snapshot '%s'"), nvpair_name(elem));
(void) zfs_standard_error(hdl,
fnvpair_value_int32(elem), errbuf);
printed = B_TRUE;
}
if (!printed) {
switch (ret) {
case EXDEV:
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"multiple snapshots of same "
"fs not allowed"));
(void) zfs_error(hdl, EZFS_EXISTS, errbuf);
break;
default:
(void) zfs_standard_error(hdl, ret, errbuf);
}
}
}
nvlist_free(props);
nvlist_free(errors);
return (ret);
}
int
zfs_snapshot(libzfs_handle_t *hdl, const char *path, boolean_t recursive,
nvlist_t *props)
{
int ret;
snapdata_t sd = { 0 };
char fsname[ZFS_MAX_DATASET_NAME_LEN];
char *cp;
zfs_handle_t *zhp;
char errbuf[1024];
(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
"cannot snapshot %s"), path);
if (!zfs_validate_name(hdl, path, ZFS_TYPE_SNAPSHOT, B_TRUE))
return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
(void) strlcpy(fsname, path, sizeof (fsname));
cp = strchr(fsname, '@');
*cp = '\0';
sd.sd_snapname = cp + 1;
if ((zhp = zfs_open(hdl, fsname, ZFS_TYPE_FILESYSTEM |
ZFS_TYPE_VOLUME)) == NULL) {
return (-1);
}
verify(nvlist_alloc(&sd.sd_nvl, NV_UNIQUE_NAME, 0) == 0);
if (recursive) {
(void) zfs_snapshot_cb(zfs_handle_dup(zhp), &sd);
} else {
fnvlist_add_boolean(sd.sd_nvl, path);
}
ret = zfs_snapshot_nvl(hdl, sd.sd_nvl, props);
nvlist_free(sd.sd_nvl);
zfs_close(zhp);
return (ret);
}
/*
* Destroy any more recent snapshots. We invoke this callback on any dependents
* of the snapshot first. If the 'cb_dependent' member is non-zero, then this
* is a dependent and we should just destroy it without checking the transaction
* group.
*/
typedef struct rollback_data {
const char *cb_target; /* the snapshot */
uint64_t cb_create; /* creation time reference */
boolean_t cb_error;
boolean_t cb_force;
} rollback_data_t;
static int
rollback_destroy_dependent(zfs_handle_t *zhp, void *data)
{
rollback_data_t *cbp = data;
prop_changelist_t *clp;
/* We must destroy this clone; first unmount it */
clp = changelist_gather(zhp, ZFS_PROP_NAME, 0,
cbp->cb_force ? MS_FORCE: 0);
if (clp == NULL || changelist_prefix(clp) != 0) {
cbp->cb_error = B_TRUE;
zfs_close(zhp);
return (0);
}
if (zfs_destroy(zhp, B_FALSE) != 0)
cbp->cb_error = B_TRUE;
else
changelist_remove(clp, zhp->zfs_name);
(void) changelist_postfix(clp);
changelist_free(clp);
zfs_close(zhp);
return (0);
}
static int
rollback_destroy(zfs_handle_t *zhp, void *data)
{
rollback_data_t *cbp = data;
if (zfs_prop_get_int(zhp, ZFS_PROP_CREATETXG) > cbp->cb_create) {
cbp->cb_error |= zfs_iter_dependents(zhp, B_FALSE,
rollback_destroy_dependent, cbp);
cbp->cb_error |= zfs_destroy(zhp, B_FALSE);
}
zfs_close(zhp);
return (0);
}
/*
* Given a dataset, rollback to a specific snapshot, discarding any
* data changes since then and making it the active dataset.
*
* Any snapshots and bookmarks more recent than the target are
* destroyed, along with their dependents (i.e. clones).
*/
int
zfs_rollback(zfs_handle_t *zhp, zfs_handle_t *snap, boolean_t force)
{
rollback_data_t cb = { 0 };
int err;
boolean_t restore_resv = 0;
uint64_t old_volsize = 0, new_volsize;
zfs_prop_t resv_prop;
assert(zhp->zfs_type == ZFS_TYPE_FILESYSTEM ||
zhp->zfs_type == ZFS_TYPE_VOLUME);
/*
* Destroy all recent snapshots and their dependents.
*/
cb.cb_force = force;
cb.cb_target = snap->zfs_name;
cb.cb_create = zfs_prop_get_int(snap, ZFS_PROP_CREATETXG);
(void) zfs_iter_snapshots(zhp, B_FALSE, rollback_destroy, &cb);
(void) zfs_iter_bookmarks(zhp, rollback_destroy, &cb);
if (cb.cb_error)
return (-1);
/*
* Now that we have verified that the snapshot is the latest,
* rollback to the given snapshot.
*/
if (zhp->zfs_type == ZFS_TYPE_VOLUME) {
if (zfs_which_resv_prop(zhp, &resv_prop) < 0)
return (-1);
old_volsize = zfs_prop_get_int(zhp, ZFS_PROP_VOLSIZE);
restore_resv =
(old_volsize == zfs_prop_get_int(zhp, resv_prop));
}
/*
* Pass both the filesystem and the wanted snapshot names,
* we would get an error back if the snapshot is destroyed or
* a new snapshot is created before this request is processed.
*/
err = lzc_rollback_to(zhp->zfs_name, snap->zfs_name);
if (err != 0) {
char errbuf[1024];
(void) snprintf(errbuf, sizeof (errbuf),
dgettext(TEXT_DOMAIN, "cannot rollback '%s'"),
zhp->zfs_name);
switch (err) {
case EEXIST:
zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
"there is a snapshot or bookmark more recent "
"than '%s'"), snap->zfs_name);
(void) zfs_error(zhp->zfs_hdl, EZFS_EXISTS, errbuf);
break;
case ESRCH:
zfs_error_aux(zhp->zfs_hdl, dgettext(TEXT_DOMAIN,
"'%s' is not found among snapshots of '%s'"),
snap->zfs_name, zhp->zfs_name);
(void) zfs_error(zhp->zfs_hdl, EZFS_NOENT, errbuf);
break;
case EINVAL:
(void) zfs_error(zhp->zfs_hdl, EZFS_BADTYPE, errbuf);
break;
default:
(void) zfs_standard_error(zhp->zfs_hdl, err, errbuf);
}
return (err);
}
/*
* For volumes, if the pre-rollback volsize matched the pre-
* rollback reservation and the volsize has changed then set
* the reservation property to the post-rollback volsize.
* Make a new handle since the rollback closed the dataset.
*/
if ((zhp->zfs_type == ZFS_TYPE_VOLUME) &&
(zhp = make_dataset_handle(zhp->zfs_hdl, zhp->zfs_name))) {
if (restore_resv) {
new_volsize = zfs_prop_get_int(zhp, ZFS_PROP_VOLSIZE);
if (old_volsize != new_volsize)
err = zfs_prop_set_int(zhp, resv_prop,
new_volsize);
}
zfs_close(zhp);
}
return (err);
}
/*
* Renames the given dataset.
*/
int
zfs_rename(zfs_handle_t *zhp, const char *target, boolean_t recursive,
boolean_t force_unmount)
{
int ret = 0;
zfs_cmd_t zc = { 0 };
char *delim;
prop_changelist_t *cl = NULL;
zfs_handle_t *zhrp = NULL;
char *parentname = NULL;
char parent[ZFS_MAX_DATASET_NAME_LEN];
libzfs_handle_t *hdl = zhp->zfs_hdl;
char errbuf[1024];
/* if we have the same exact name, just return success */
if (strcmp(zhp->zfs_name, target) == 0)
return (0);
(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
"cannot rename to '%s'"), target);
/* make sure source name is valid */
if (!zfs_validate_name(hdl, zhp->zfs_name, zhp->zfs_type, B_TRUE))
return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
/*
* Make sure the target name is valid
*/
if (zhp->zfs_type == ZFS_TYPE_SNAPSHOT) {
if ((strchr(target, '@') == NULL) ||
*target == '@') {
/*
* Snapshot target name is abbreviated,
* reconstruct full dataset name
*/
(void) strlcpy(parent, zhp->zfs_name,
sizeof (parent));
delim = strchr(parent, '@');
if (strchr(target, '@') == NULL)
*(++delim) = '\0';
else
*delim = '\0';
(void) strlcat(parent, target, sizeof (parent));
target = parent;
} else {
/*
* Make sure we're renaming within the same dataset.
*/
delim = strchr(target, '@');
if (strncmp(zhp->zfs_name, target, delim - target)
!= 0 || zhp->zfs_name[delim - target] != '@') {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"snapshots must be part of same "
"dataset"));
return (zfs_error(hdl, EZFS_CROSSTARGET,
errbuf));
}
}
if (!zfs_validate_name(hdl, target, zhp->zfs_type, B_TRUE))
return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
} else {
if (recursive) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"recursive rename must be a snapshot"));
return (zfs_error(hdl, EZFS_BADTYPE, errbuf));
}
if (!zfs_validate_name(hdl, target, zhp->zfs_type, B_TRUE))
return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
/* validate parents */
if (check_parents(hdl, target, NULL, B_FALSE, NULL) != 0)
return (-1);
/* make sure we're in the same pool */
verify((delim = strchr(target, '/')) != NULL);
if (strncmp(zhp->zfs_name, target, delim - target) != 0 ||
zhp->zfs_name[delim - target] != '/') {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"datasets must be within same pool"));
return (zfs_error(hdl, EZFS_CROSSTARGET, errbuf));
}
/* new name cannot be a child of the current dataset name */
if (is_descendant(zhp->zfs_name, target)) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"New dataset name cannot be a descendant of "
"current dataset name"));
return (zfs_error(hdl, EZFS_INVALIDNAME, errbuf));
}
}
(void) snprintf(errbuf, sizeof (errbuf),
dgettext(TEXT_DOMAIN, "cannot rename '%s'"), zhp->zfs_name);
if (getzoneid() == GLOBAL_ZONEID &&
zfs_prop_get_int(zhp, ZFS_PROP_ZONED)) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"dataset is used in a non-global zone"));
return (zfs_error(hdl, EZFS_ZONED, errbuf));
}
if (recursive) {
parentname = zfs_strdup(zhp->zfs_hdl, zhp->zfs_name);
if (parentname == NULL) {
ret = -1;
goto error;
}
delim = strchr(parentname, '@');
*delim = '\0';
zhrp = zfs_open(zhp->zfs_hdl, parentname, ZFS_TYPE_DATASET);
if (zhrp == NULL) {
ret = -1;
goto error;
}
} else if (zhp->zfs_type != ZFS_TYPE_SNAPSHOT) {
if ((cl = changelist_gather(zhp, ZFS_PROP_NAME, 0,
force_unmount ? MS_FORCE : 0)) == NULL)
return (-1);
if (changelist_haszonedchild(cl)) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"child dataset with inherited mountpoint is used "
"in a non-global zone"));
(void) zfs_error(hdl, EZFS_ZONED, errbuf);
ret = -1;
goto error;
}
if ((ret = changelist_prefix(cl)) != 0)
goto error;
}
if (ZFS_IS_VOLUME(zhp))
zc.zc_objset_type = DMU_OST_ZVOL;
else
zc.zc_objset_type = DMU_OST_ZFS;
(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
(void) strlcpy(zc.zc_value, target, sizeof (zc.zc_value));
zc.zc_cookie = recursive;
if ((ret = zfs_ioctl(zhp->zfs_hdl, ZFS_IOC_RENAME, &zc)) != 0) {
/*
* if it was recursive, the one that actually failed will
* be in zc.zc_name
*/
(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
"cannot rename '%s'"), zc.zc_name);
if (recursive && errno == EEXIST) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"a child dataset already has a snapshot "
"with the new name"));
(void) zfs_error(hdl, EZFS_EXISTS, errbuf);
} else if (errno == EACCES) {
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"cannot move encrypted child outside of "
"its encryption root"));
(void) zfs_error(hdl, EZFS_CRYPTOFAILED, errbuf);
} else {
(void) zfs_standard_error(zhp->zfs_hdl, errno, errbuf);
}
/*
* On failure, we still want to remount any filesystems that
* were previously mounted, so we don't alter the system state.
*/
if (cl != NULL)
(void) changelist_postfix(cl);
} else {
if (cl != NULL) {
changelist_rename(cl, zfs_get_name(zhp), target);
ret = changelist_postfix(cl);
}
}
error:
if (parentname != NULL) {
free(parentname);
}
if (zhrp != NULL) {
zfs_close(zhrp);
}
if (cl != NULL) {
changelist_free(cl);
}
return (ret);
}
nvlist_t *
zfs_get_user_props(zfs_handle_t *zhp)
{
return (zhp->zfs_user_props);
}
nvlist_t *
zfs_get_recvd_props(zfs_handle_t *zhp)
{
if (zhp->zfs_recvd_props == NULL)
if (get_recvd_props_ioctl(zhp) != 0)
return (NULL);
return (zhp->zfs_recvd_props);
}
/*
* This function is used by 'zfs list' to determine the exact set of columns to
* display, and their maximum widths. This does two main things:
*
* - If this is a list of all properties, then expand the list to include
* all native properties, and set a flag so that for each dataset we look
* for new unique user properties and add them to the list.
*
* - For non fixed-width properties, keep track of the maximum width seen
* so that we can size the column appropriately. If the user has
* requested received property values, we also need to compute the width
* of the RECEIVED column.
*/
int
zfs_expand_proplist(zfs_handle_t *zhp, zprop_list_t **plp, boolean_t received,
boolean_t literal)
{
libzfs_handle_t *hdl = zhp->zfs_hdl;
zprop_list_t *entry;
zprop_list_t **last, **start;
nvlist_t *userprops, *propval;
nvpair_t *elem;
char *strval;
char buf[ZFS_MAXPROPLEN];
if (zprop_expand_list(hdl, plp, ZFS_TYPE_DATASET) != 0)
return (-1);
userprops = zfs_get_user_props(zhp);
entry = *plp;
if (entry->pl_all && nvlist_next_nvpair(userprops, NULL) != NULL) {
/*
* Go through and add any user properties as necessary. We
* start by incrementing our list pointer to the first
* non-native property.
*/
start = plp;
while (*start != NULL) {
if ((*start)->pl_prop == ZPROP_INVAL)
break;
start = &(*start)->pl_next;
}
elem = NULL;
while ((elem = nvlist_next_nvpair(userprops, elem)) != NULL) {
/*
* See if we've already found this property in our list.
*/
for (last = start; *last != NULL;
last = &(*last)->pl_next) {
if (strcmp((*last)->pl_user_prop,
nvpair_name(elem)) == 0)
break;
}
if (*last == NULL) {
if ((entry = zfs_alloc(hdl,
sizeof (zprop_list_t))) == NULL ||
((entry->pl_user_prop = zfs_strdup(hdl,
nvpair_name(elem)))) == NULL) {
free(entry);
return (-1);
}
entry->pl_prop = ZPROP_INVAL;
entry->pl_width = strlen(nvpair_name(elem));
entry->pl_all = B_TRUE;
*last = entry;
}
}
}
/*
* Now go through and check the width of any non-fixed columns
*/
for (entry = *plp; entry != NULL; entry = entry->pl_next) {
if (entry->pl_fixed && !literal)
continue;
if (entry->pl_prop != ZPROP_INVAL) {
if (zfs_prop_get(zhp, entry->pl_prop,
buf, sizeof (buf), NULL, NULL, 0, literal) == 0) {
if (strlen(buf) > entry->pl_width)
entry->pl_width = strlen(buf);
}
if (received && zfs_prop_get_recvd(zhp,
zfs_prop_to_name(entry->pl_prop),
buf, sizeof (buf), literal) == 0)
if (strlen(buf) > entry->pl_recvd_width)
entry->pl_recvd_width = strlen(buf);
} else {
if (nvlist_lookup_nvlist(userprops, entry->pl_user_prop,
&propval) == 0) {
verify(nvlist_lookup_string(propval,
ZPROP_VALUE, &strval) == 0);
if (strlen(strval) > entry->pl_width)
entry->pl_width = strlen(strval);
}
if (received && zfs_prop_get_recvd(zhp,
entry->pl_user_prop,
buf, sizeof (buf), literal) == 0)
if (strlen(buf) > entry->pl_recvd_width)
entry->pl_recvd_width = strlen(buf);
}
}
return (0);
}
int
zfs_deleg_share_nfs(libzfs_handle_t *hdl, char *dataset, char *path,
char *resource, void *export, void *sharetab,
int sharemax, zfs_share_op_t operation)
{
zfs_cmd_t zc = { 0 };
int error;
(void) strlcpy(zc.zc_name, dataset, sizeof (zc.zc_name));
(void) strlcpy(zc.zc_value, path, sizeof (zc.zc_value));
if (resource)
(void) strlcpy(zc.zc_string, resource, sizeof (zc.zc_string));
zc.zc_share.z_sharedata = (uint64_t)(uintptr_t)sharetab;
zc.zc_share.z_exportdata = (uint64_t)(uintptr_t)export;
zc.zc_share.z_sharetype = operation;
zc.zc_share.z_sharemax = sharemax;
error = ioctl(hdl->libzfs_fd, ZFS_IOC_SHARE, &zc);
return (error);
}
void
zfs_prune_proplist(zfs_handle_t *zhp, uint8_t *props)
{
nvpair_t *curr;
/*
* Keep a reference to the props-table against which we prune the
* properties.
*/
zhp->zfs_props_table = props;
curr = nvlist_next_nvpair(zhp->zfs_props, NULL);
while (curr) {
zfs_prop_t zfs_prop = zfs_name_to_prop(nvpair_name(curr));
nvpair_t *next = nvlist_next_nvpair(zhp->zfs_props, curr);
/*
* User properties will result in ZPROP_INVAL, and since we
* only know how to prune standard ZFS properties, we always
* leave these in the list. This can also happen if we
* encounter an unknown DSL property (when running older
* software, for example).
*/
if (zfs_prop != ZPROP_INVAL && props[zfs_prop] == B_FALSE)
(void) nvlist_remove(zhp->zfs_props,
nvpair_name(curr), nvpair_type(curr));
curr = next;
}
}
static int
zfs_smb_acl_mgmt(libzfs_handle_t *hdl, char *dataset, char *path,
zfs_smb_acl_op_t cmd, char *resource1, char *resource2)
{
zfs_cmd_t zc = { 0 };
nvlist_t *nvlist = NULL;
int error;
(void) strlcpy(zc.zc_name, dataset, sizeof (zc.zc_name));
(void) strlcpy(zc.zc_value, path, sizeof (zc.zc_value));
zc.zc_cookie = (uint64_t)cmd;
if (cmd == ZFS_SMB_ACL_RENAME) {
if (nvlist_alloc(&nvlist, NV_UNIQUE_NAME, 0) != 0) {
(void) no_memory(hdl);
return (0);
}
}
switch (cmd) {
case ZFS_SMB_ACL_ADD:
case ZFS_SMB_ACL_REMOVE:
(void) strlcpy(zc.zc_string, resource1, sizeof (zc.zc_string));
break;
case ZFS_SMB_ACL_RENAME:
if (nvlist_add_string(nvlist, ZFS_SMB_ACL_SRC,
resource1) != 0) {
(void) no_memory(hdl);
return (-1);
}
if (nvlist_add_string(nvlist, ZFS_SMB_ACL_TARGET,
resource2) != 0) {
(void) no_memory(hdl);
return (-1);
}
if (zcmd_write_src_nvlist(hdl, &zc, nvlist) != 0) {
nvlist_free(nvlist);
return (-1);
}
break;
case ZFS_SMB_ACL_PURGE:
break;
default:
return (-1);
}
error = ioctl(hdl->libzfs_fd, ZFS_IOC_SMB_ACL, &zc);
nvlist_free(nvlist);
return (error);
}
int
zfs_smb_acl_add(libzfs_handle_t *hdl, char *dataset,
char *path, char *resource)
{
return (zfs_smb_acl_mgmt(hdl, dataset, path, ZFS_SMB_ACL_ADD,
resource, NULL));
}
int
zfs_smb_acl_remove(libzfs_handle_t *hdl, char *dataset,
char *path, char *resource)
{
return (zfs_smb_acl_mgmt(hdl, dataset, path, ZFS_SMB_ACL_REMOVE,
resource, NULL));
}
int
zfs_smb_acl_purge(libzfs_handle_t *hdl, char *dataset, char *path)
{
return (zfs_smb_acl_mgmt(hdl, dataset, path, ZFS_SMB_ACL_PURGE,
NULL, NULL));
}
int
zfs_smb_acl_rename(libzfs_handle_t *hdl, char *dataset, char *path,
char *oldname, char *newname)
{
return (zfs_smb_acl_mgmt(hdl, dataset, path, ZFS_SMB_ACL_RENAME,
oldname, newname));
}
int
zfs_userspace(zfs_handle_t *zhp, zfs_userquota_prop_t type,
zfs_userspace_cb_t func, void *arg)
{
zfs_cmd_t zc = { 0 };
zfs_useracct_t buf[100];
libzfs_handle_t *hdl = zhp->zfs_hdl;
int ret;
(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
zc.zc_objset_type = type;
zc.zc_nvlist_dst = (uintptr_t)buf;
for (;;) {
zfs_useracct_t *zua = buf;
zc.zc_nvlist_dst_size = sizeof (buf);
if (zfs_ioctl(hdl, ZFS_IOC_USERSPACE_MANY, &zc) != 0) {
char errbuf[1024];
if ((errno == ENOTSUP &&
(type == ZFS_PROP_USEROBJUSED ||
type == ZFS_PROP_GROUPOBJUSED ||
type == ZFS_PROP_USEROBJQUOTA ||
type == ZFS_PROP_GROUPOBJQUOTA ||
type == ZFS_PROP_PROJECTOBJUSED ||
type == ZFS_PROP_PROJECTOBJQUOTA ||
type == ZFS_PROP_PROJECTUSED ||
type == ZFS_PROP_PROJECTQUOTA)))
break;
(void) snprintf(errbuf, sizeof (errbuf),
dgettext(TEXT_DOMAIN,
"cannot get used/quota for %s"), zc.zc_name);
return (zfs_standard_error_fmt(hdl, errno, errbuf));
}
if (zc.zc_nvlist_dst_size == 0)
break;
while (zc.zc_nvlist_dst_size > 0) {
if ((ret = func(arg, zua->zu_domain, zua->zu_rid,
zua->zu_space)) != 0)
return (ret);
zua++;
zc.zc_nvlist_dst_size -= sizeof (zfs_useracct_t);
}
}
return (0);
}
struct holdarg {
nvlist_t *nvl;
const char *snapname;
const char *tag;
boolean_t recursive;
int error;
};
static int
zfs_hold_one(zfs_handle_t *zhp, void *arg)
{
struct holdarg *ha = arg;
char name[ZFS_MAX_DATASET_NAME_LEN];
int rv = 0;
(void) snprintf(name, sizeof (name),
"%s@%s", zhp->zfs_name, ha->snapname);
if (lzc_exists(name))
fnvlist_add_string(ha->nvl, name, ha->tag);
if (ha->recursive)
rv = zfs_iter_filesystems(zhp, zfs_hold_one, ha);
zfs_close(zhp);
return (rv);
}
int
zfs_hold(zfs_handle_t *zhp, const char *snapname, const char *tag,
boolean_t recursive, int cleanup_fd)
{
int ret;
struct holdarg ha;
ha.nvl = fnvlist_alloc();
ha.snapname = snapname;
ha.tag = tag;
ha.recursive = recursive;
(void) zfs_hold_one(zfs_handle_dup(zhp), &ha);
if (nvlist_empty(ha.nvl)) {
char errbuf[1024];
fnvlist_free(ha.nvl);
ret = ENOENT;
(void) snprintf(errbuf, sizeof (errbuf),
dgettext(TEXT_DOMAIN,
"cannot hold snapshot '%s@%s'"),
zhp->zfs_name, snapname);
(void) zfs_standard_error(zhp->zfs_hdl, ret, errbuf);
return (ret);
}
ret = zfs_hold_nvl(zhp, cleanup_fd, ha.nvl);
fnvlist_free(ha.nvl);
return (ret);
}
int
zfs_hold_nvl(zfs_handle_t *zhp, int cleanup_fd, nvlist_t *holds)
{
int ret;
nvlist_t *errors;
libzfs_handle_t *hdl = zhp->zfs_hdl;
char errbuf[1024];
nvpair_t *elem;
errors = NULL;
ret = lzc_hold(holds, cleanup_fd, &errors);
if (ret == 0) {
/* There may be errors even in the success case. */
fnvlist_free(errors);
return (0);
}
if (nvlist_empty(errors)) {
/* no hold-specific errors */
(void) snprintf(errbuf, sizeof (errbuf),
dgettext(TEXT_DOMAIN, "cannot hold"));
switch (ret) {
case ENOTSUP:
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"pool must be upgraded"));
(void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
break;
case EINVAL:
(void) zfs_error(hdl, EZFS_BADTYPE, errbuf);
break;
default:
(void) zfs_standard_error(hdl, ret, errbuf);
}
}
for (elem = nvlist_next_nvpair(errors, NULL);
elem != NULL;
elem = nvlist_next_nvpair(errors, elem)) {
(void) snprintf(errbuf, sizeof (errbuf),
dgettext(TEXT_DOMAIN,
"cannot hold snapshot '%s'"), nvpair_name(elem));
switch (fnvpair_value_int32(elem)) {
case E2BIG:
/*
* Temporary tags wind up having the ds object id
* prepended. So even if we passed the length check
* above, it's still possible for the tag to wind
* up being slightly too long.
*/
(void) zfs_error(hdl, EZFS_TAGTOOLONG, errbuf);
break;
case EINVAL:
(void) zfs_error(hdl, EZFS_BADTYPE, errbuf);
break;
case EEXIST:
(void) zfs_error(hdl, EZFS_REFTAG_HOLD, errbuf);
break;
default:
(void) zfs_standard_error(hdl,
fnvpair_value_int32(elem), errbuf);
}
}
fnvlist_free(errors);
return (ret);
}
static int
zfs_release_one(zfs_handle_t *zhp, void *arg)
{
struct holdarg *ha = arg;
char name[ZFS_MAX_DATASET_NAME_LEN];
int rv = 0;
nvlist_t *existing_holds;
(void) snprintf(name, sizeof (name),
"%s@%s", zhp->zfs_name, ha->snapname);
if (lzc_get_holds(name, &existing_holds) != 0) {
ha->error = ENOENT;
} else if (!nvlist_exists(existing_holds, ha->tag)) {
ha->error = ESRCH;
} else {
nvlist_t *torelease = fnvlist_alloc();
fnvlist_add_boolean(torelease, ha->tag);
fnvlist_add_nvlist(ha->nvl, name, torelease);
fnvlist_free(torelease);
}
if (ha->recursive)
rv = zfs_iter_filesystems(zhp, zfs_release_one, ha);
zfs_close(zhp);
return (rv);
}
int
zfs_release(zfs_handle_t *zhp, const char *snapname, const char *tag,
boolean_t recursive)
{
int ret;
struct holdarg ha;
nvlist_t *errors = NULL;
nvpair_t *elem;
libzfs_handle_t *hdl = zhp->zfs_hdl;
char errbuf[1024];
ha.nvl = fnvlist_alloc();
ha.snapname = snapname;
ha.tag = tag;
ha.recursive = recursive;
ha.error = 0;
(void) zfs_release_one(zfs_handle_dup(zhp), &ha);
if (nvlist_empty(ha.nvl)) {
fnvlist_free(ha.nvl);
ret = ha.error;
(void) snprintf(errbuf, sizeof (errbuf),
dgettext(TEXT_DOMAIN,
"cannot release hold from snapshot '%s@%s'"),
zhp->zfs_name, snapname);
if (ret == ESRCH) {
(void) zfs_error(hdl, EZFS_REFTAG_RELE, errbuf);
} else {
(void) zfs_standard_error(hdl, ret, errbuf);
}
return (ret);
}
ret = lzc_release(ha.nvl, &errors);
fnvlist_free(ha.nvl);
if (ret == 0) {
/* There may be errors even in the success case. */
fnvlist_free(errors);
return (0);
}
if (nvlist_empty(errors)) {
/* no hold-specific errors */
(void) snprintf(errbuf, sizeof (errbuf), dgettext(TEXT_DOMAIN,
"cannot release"));
switch (errno) {
case ENOTSUP:
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"pool must be upgraded"));
(void) zfs_error(hdl, EZFS_BADVERSION, errbuf);
break;
default:
(void) zfs_standard_error_fmt(hdl, errno, errbuf);
}
}
for (elem = nvlist_next_nvpair(errors, NULL);
elem != NULL;
elem = nvlist_next_nvpair(errors, elem)) {
(void) snprintf(errbuf, sizeof (errbuf),
dgettext(TEXT_DOMAIN,
"cannot release hold from snapshot '%s'"),
nvpair_name(elem));
switch (fnvpair_value_int32(elem)) {
case ESRCH:
(void) zfs_error(hdl, EZFS_REFTAG_RELE, errbuf);
break;
case EINVAL:
(void) zfs_error(hdl, EZFS_BADTYPE, errbuf);
break;
default:
(void) zfs_standard_error_fmt(hdl,
fnvpair_value_int32(elem), errbuf);
}
}
fnvlist_free(errors);
return (ret);
}
int
zfs_get_fsacl(zfs_handle_t *zhp, nvlist_t **nvl)
{
zfs_cmd_t zc = { 0 };
libzfs_handle_t *hdl = zhp->zfs_hdl;
int nvsz = 2048;
void *nvbuf;
int err = 0;
char errbuf[1024];
assert(zhp->zfs_type == ZFS_TYPE_VOLUME ||
zhp->zfs_type == ZFS_TYPE_FILESYSTEM);
tryagain:
nvbuf = malloc(nvsz);
if (nvbuf == NULL) {
err = (zfs_error(hdl, EZFS_NOMEM, strerror(errno)));
goto out;
}
zc.zc_nvlist_dst_size = nvsz;
zc.zc_nvlist_dst = (uintptr_t)nvbuf;
(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
if (ioctl(hdl->libzfs_fd, ZFS_IOC_GET_FSACL, &zc) != 0) {
(void) snprintf(errbuf, sizeof (errbuf),
dgettext(TEXT_DOMAIN, "cannot get permissions on '%s'"),
zc.zc_name);
switch (errno) {
case ENOMEM:
free(nvbuf);
nvsz = zc.zc_nvlist_dst_size;
goto tryagain;
case ENOTSUP:
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"pool must be upgraded"));
err = zfs_error(hdl, EZFS_BADVERSION, errbuf);
break;
case EINVAL:
err = zfs_error(hdl, EZFS_BADTYPE, errbuf);
break;
case ENOENT:
err = zfs_error(hdl, EZFS_NOENT, errbuf);
break;
default:
err = zfs_standard_error_fmt(hdl, errno, errbuf);
break;
}
} else {
/* success */
int rc = nvlist_unpack(nvbuf, zc.zc_nvlist_dst_size, nvl, 0);
if (rc) {
(void) snprintf(errbuf, sizeof (errbuf), dgettext(
TEXT_DOMAIN, "cannot get permissions on '%s'"),
zc.zc_name);
err = zfs_standard_error_fmt(hdl, rc, errbuf);
}
}
free(nvbuf);
out:
return (err);
}
int
zfs_set_fsacl(zfs_handle_t *zhp, boolean_t un, nvlist_t *nvl)
{
zfs_cmd_t zc = { 0 };
libzfs_handle_t *hdl = zhp->zfs_hdl;
char *nvbuf;
char errbuf[1024];
size_t nvsz;
int err;
assert(zhp->zfs_type == ZFS_TYPE_VOLUME ||
zhp->zfs_type == ZFS_TYPE_FILESYSTEM);
err = nvlist_size(nvl, &nvsz, NV_ENCODE_NATIVE);
assert(err == 0);
nvbuf = malloc(nvsz);
err = nvlist_pack(nvl, &nvbuf, &nvsz, NV_ENCODE_NATIVE, 0);
assert(err == 0);
zc.zc_nvlist_src_size = nvsz;
zc.zc_nvlist_src = (uintptr_t)nvbuf;
zc.zc_perm_action = un;
(void) strlcpy(zc.zc_name, zhp->zfs_name, sizeof (zc.zc_name));
if (zfs_ioctl(hdl, ZFS_IOC_SET_FSACL, &zc) != 0) {
(void) snprintf(errbuf, sizeof (errbuf),
dgettext(TEXT_DOMAIN, "cannot set permissions on '%s'"),
zc.zc_name);
switch (errno) {
case ENOTSUP:
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"pool must be upgraded"));
err = zfs_error(hdl, EZFS_BADVERSION, errbuf);
break;
case EINVAL:
err = zfs_error(hdl, EZFS_BADTYPE, errbuf);
break;
case ENOENT:
err = zfs_error(hdl, EZFS_NOENT, errbuf);
break;
default:
err = zfs_standard_error_fmt(hdl, errno, errbuf);
break;
}
}
free(nvbuf);
return (err);
}
int
zfs_get_holds(zfs_handle_t *zhp, nvlist_t **nvl)
{
int err;
char errbuf[1024];
err = lzc_get_holds(zhp->zfs_name, nvl);
if (err != 0) {
libzfs_handle_t *hdl = zhp->zfs_hdl;
(void) snprintf(errbuf, sizeof (errbuf),
dgettext(TEXT_DOMAIN, "cannot get holds for '%s'"),
zhp->zfs_name);
switch (err) {
case ENOTSUP:
zfs_error_aux(hdl, dgettext(TEXT_DOMAIN,
"pool must be upgraded"));
err = zfs_error(hdl, EZFS_BADVERSION, errbuf);
break;
case EINVAL:
err = zfs_error(hdl, EZFS_BADTYPE, errbuf);
break;
case ENOENT:
err = zfs_error(hdl, EZFS_NOENT, errbuf);
break;
default:
err = zfs_standard_error_fmt(hdl, errno, errbuf);
break;
}
}
return (err);
}
/*
* The theory of raidz space accounting
*
* The "referenced" property of RAIDZ vdevs is scaled such that a 128KB block
* will "reference" 128KB, even though it allocates more than that, to store the
* parity information (and perhaps skip sectors). This concept of the
* "referenced" (and other DMU space accounting) being lower than the allocated
* space by a constant factor is called "raidz deflation."
*
* As mentioned above, the constant factor for raidz deflation assumes a 128KB
* block size. However, zvols typically have a much smaller block size (default
* 8KB). These smaller blocks may require proportionally much more parity
* information (and perhaps skip sectors). In this case, the change to the
* "referenced" property may be much more than the logical block size.
*
* Suppose a raidz vdev has 5 disks with ashift=12. A 128k block may be written
* as follows.
*
* +-------+-------+-------+-------+-------+
* | disk1 | disk2 | disk3 | disk4 | disk5 |
* +-------+-------+-------+-------+-------+
* | P0 | D0 | D8 | D16 | D24 |
* | P1 | D1 | D9 | D17 | D25 |
* | P2 | D2 | D10 | D18 | D26 |
* | P3 | D3 | D11 | D19 | D27 |
* | P4 | D4 | D12 | D20 | D28 |
* | P5 | D5 | D13 | D21 | D29 |
* | P6 | D6 | D14 | D22 | D30 |
* | P7 | D7 | D15 | D23 | D31 |
* +-------+-------+-------+-------+-------+
*
* Above, notice that 160k was allocated: 8 x 4k parity sectors + 32 x 4k data
* sectors. The dataset's referenced will increase by 128k and the pool's
* allocated and free properties will be adjusted by 160k.
*
* A 4k block written to the same raidz vdev will require two 4k sectors. The
* blank cells represent unallocated space.
*
* +-------+-------+-------+-------+-------+
* | disk1 | disk2 | disk3 | disk4 | disk5 |
* +-------+-------+-------+-------+-------+
* | P0 | D0 | | | |
* +-------+-------+-------+-------+-------+
*
* Above, notice that the 4k block required one sector for parity and another
* for data. vdev_raidz_asize() will return 8k and as such the pool's allocated
* and free properties will be adjusted by 8k. The dataset will not be charged
* 8k. Rather, it will be charged a value that is scaled according to the
* overhead of the 128k block on the same vdev. This 8k allocation will be
* charged 8k * 128k / 160k. 128k is from SPA_OLD_MAXBLOCKSIZE and 160k is as
* calculated in the 128k block example above.
*
* Every raidz allocation is sized to be a multiple of nparity+1 sectors. That
* is, every raidz1 allocation will be a multiple of 2 sectors, raidz2
* allocations are a multiple of 3 sectors, and raidz3 allocations are a
* multiple of of 4 sectors. When a block does not fill the required number of
* sectors, skip blocks (sectors) are used.
*
* An 8k block being written to a raidz vdev may be written as follows:
*
* +-------+-------+-------+-------+-------+
* | disk1 | disk2 | disk3 | disk4 | disk5 |
* +-------+-------+-------+-------+-------+
* | P0 | D0 | D1 | S0 | |
* +-------+-------+-------+-------+-------+
*
* In order to maintain the nparity+1 allocation size, a skip block (S0) was
* added. For this 8k block, the pool's allocated and free properties are
* adjusted by 16k and the dataset's referenced is increased by 16k * 128k /
* 160k. Again, 128k is from SPA_OLD_MAXBLOCKSIZE and 160k is as calculated in
* the 128k block example above.
*
* Compression may lead to a variety of block sizes being written for the same
* volume or file. There is no clear way to reserve just the amount of space
* that will be required, so the worst case (no compression) is assumed.
* Note that metadata blocks will typically be compressed, so the reservation
* size returned by zvol_volsize_to_reservation() will generally be slightly
* larger than the maximum that the volume can reference.
*/
/*
* Derived from function of same name in uts/common/fs/zfs/vdev_raidz.c.
* Returns the amount of space (in bytes) that will be allocated for the
* specified block size. Note that the "referenced" space accounted will be less
* than this, but not necessarily equal to "blksize", due to RAIDZ deflation.
*/
static uint64_t
vdev_raidz_asize(uint64_t ndisks, uint64_t nparity, uint64_t ashift,
uint64_t blksize)
{
uint64_t asize, ndata;
ASSERT3U(ndisks, >, nparity);
ndata = ndisks - nparity;
asize = ((blksize - 1) >> ashift) + 1;
asize += nparity * ((asize + ndata - 1) / ndata);
asize = roundup(asize, nparity + 1) << ashift;
return (asize);
}
/*
* Determine how much space will be allocated if it lands on the most space-
* inefficient top-level vdev. Returns the size in bytes required to store one
* copy of the volume data. See theory comment above.
*/
static uint64_t
volsize_from_vdevs(zpool_handle_t *zhp, uint64_t nblocks, uint64_t blksize)
{
nvlist_t *config, *tree, **vdevs;
uint_t nvdevs, v;
uint64_t ret = 0;
config = zpool_get_config(zhp, NULL);
if (nvlist_lookup_nvlist(config, ZPOOL_CONFIG_VDEV_TREE, &tree) != 0 ||
nvlist_lookup_nvlist_array(tree, ZPOOL_CONFIG_CHILDREN,
&vdevs, &nvdevs) != 0) {
return (nblocks * blksize);
}
for (v = 0; v < nvdevs; v++) {
char *type;
uint64_t nparity, ashift, asize, tsize;
nvlist_t **disks;
uint_t ndisks;
uint64_t volsize;
if (nvlist_lookup_string(vdevs[v], ZPOOL_CONFIG_TYPE,
&type) != 0 || strcmp(type, VDEV_TYPE_RAIDZ) != 0 ||
nvlist_lookup_uint64(vdevs[v], ZPOOL_CONFIG_NPARITY,
&nparity) != 0 ||
nvlist_lookup_uint64(vdevs[v], ZPOOL_CONFIG_ASHIFT,
&ashift) != 0 ||
nvlist_lookup_nvlist_array(vdevs[v], ZPOOL_CONFIG_CHILDREN,
&disks, &ndisks) != 0) {
continue;
}
/* allocation size for the "typical" 128k block */
tsize = vdev_raidz_asize(ndisks, nparity, ashift,
SPA_OLD_MAXBLOCKSIZE);
/* allocation size for the blksize block */
asize = vdev_raidz_asize(ndisks, nparity, ashift, blksize);
/*
* Scale this size down as a ratio of 128k / tsize. See theory
* statement above.
*/
volsize = nblocks * asize * SPA_OLD_MAXBLOCKSIZE / tsize;
if (volsize > ret) {
ret = volsize;
}
}
if (ret == 0) {
ret = nblocks * blksize;
}
return (ret);
}
/*
* Convert the zvol's volume size to an appropriate reservation. See theory
* comment above.
*
* Note: If this routine is updated, it is necessary to update the ZFS test
* suite's shell version in reservation.shlib.
*/
uint64_t
zvol_volsize_to_reservation(zpool_handle_t *zph, uint64_t volsize,
nvlist_t *props)
{
uint64_t numdb;
uint64_t nblocks, volblocksize;
int ncopies;
char *strval;
if (nvlist_lookup_string(props,
zfs_prop_to_name(ZFS_PROP_COPIES), &strval) == 0)
ncopies = atoi(strval);
else
ncopies = 1;
if (nvlist_lookup_uint64(props,
zfs_prop_to_name(ZFS_PROP_VOLBLOCKSIZE),
&volblocksize) != 0)
volblocksize = ZVOL_DEFAULT_BLOCKSIZE;
nblocks = volsize / volblocksize;
/*
* Metadata defaults to using 128k blocks, not volblocksize blocks. For
* this reason, only the data blocks are scaled based on vdev config.
*/
volsize = volsize_from_vdevs(zph, nblocks, volblocksize);
/* start with metadnode L0-L6 */
numdb = 7;
/* calculate number of indirects */
while (nblocks > 1) {
nblocks += DNODES_PER_LEVEL - 1;
nblocks /= DNODES_PER_LEVEL;
numdb += nblocks;
}
numdb *= MIN(SPA_DVAS_PER_BP, ncopies + 1);
volsize *= ncopies;
/*
* this is exactly DN_MAX_INDBLKSHIFT when metadata isn't
* compressed, but in practice they compress down to about
* 1100 bytes
*/
numdb *= 1ULL << DN_MAX_INDBLKSHIFT;
volsize += numdb;
return (volsize);
}
| 25.499263 | 80 | 0.663758 | [
"object"
] |
bda03b68ff84d4c871b1ee7d84770bb0ab2d5783 | 2,220 | h | C | Minkowski_sum_2/include/CGAL/Polygon_convex_decomposition_2.h | ffteja/cgal | c1c7f4ad9a4cd669e33ca07a299062a461581812 | [
"CC0-1.0"
] | 3,227 | 2015-03-05T00:19:18.000Z | 2022-03-31T08:20:35.000Z | Minkowski_sum_2/include/CGAL/Polygon_convex_decomposition_2.h | ffteja/cgal | c1c7f4ad9a4cd669e33ca07a299062a461581812 | [
"CC0-1.0"
] | 5,574 | 2015-03-05T00:01:56.000Z | 2022-03-31T15:08:11.000Z | Minkowski_sum_2/include/CGAL/Polygon_convex_decomposition_2.h | ffteja/cgal | c1c7f4ad9a4cd669e33ca07a299062a461581812 | [
"CC0-1.0"
] | 1,274 | 2015-03-05T00:01:12.000Z | 2022-03-31T14:47:56.000Z | // Copyright (c) 2006 Tel-Aviv University (Israel).
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org).
//
// $URL$
// $Id$
// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-Commercial
//
// Author(s) : Ron Wein <wein_r@yahoo.com>
#ifndef CGAL_POLYGON_CONVEX_DECOMPOSITION_H
#define CGAL_POLYGON_CONVEX_DECOMPOSITION_H
#include <CGAL/license/Minkowski_sum_2.h>
#include <CGAL/Minkowski_sum_2/Decomposition_strategy_adapter.h>
#include <vector>
namespace CGAL {
/*!
* \class
* The O(n^4) optimal strategy for decomposing a polygon into convex
* sub-polygons.
*/
template <typename Kernel_,
typename Container_ = std::vector<typename Kernel_::Point_2> >
class Optimal_convex_decomposition_2 :
public Polygon_decomposition_strategy_adapter<Kernel_, Container_,
Tag_optimal_convex_parition>
{
public:
typedef Kernel_ Kernel;
typedef CGAL::Polygon_2<Kernel, Container_> Polygon_2;
typedef typename Kernel::Point_2 Point_2;
};
/*!
* \class
* Hertel and Mehlhorn's O(n) approximation strategy for decomposing a
* polygon into convex sub-polygons.
*/
template <typename Kernel_,
typename Container_ = std::vector<typename Kernel_::Point_2> >
class Hertel_Mehlhorn_convex_decomposition_2 :
public Polygon_decomposition_strategy_adapter<Kernel_, Container_,
Tag_approx_convex_parition>
{
public:
typedef Kernel_ Kernel;
typedef CGAL::Polygon_2<Kernel, Container_> Polygon_2;
typedef typename Kernel::Point_2 Point_2;
};
/*!
* \class
* Greene's O(n log(n)) approximation strategy for decomposing a polygon into
* convex sub-polygons.
*/
template <typename Kernel_,
typename Container_ = std::vector<typename Kernel_::Point_2> >
class Greene_convex_decomposition_2 :
public Polygon_decomposition_strategy_adapter<Kernel_, Container_,
Tag_Greene_convex_parition>
{
public:
typedef Kernel_ Kernel;
typedef CGAL::Polygon_2<Kernel, Container_> Polygon_2;
typedef typename Kernel::Point_2 Point_2;
};
} //namespace CGAL
#endif
| 28.831169 | 77 | 0.692342 | [
"vector"
] |
bda04e04ab5cc44f70ea39aaf4c4ff2aa99c8e67 | 2,014 | h | C | examples/lecturedemos/lecturedemotwonorm.h | Pascal-So/lehrfempp | e2716e914169eec7ee59e822ea3ab303143eacd1 | [
"MIT"
] | null | null | null | examples/lecturedemos/lecturedemotwonorm.h | Pascal-So/lehrfempp | e2716e914169eec7ee59e822ea3ab303143eacd1 | [
"MIT"
] | null | null | null | examples/lecturedemos/lecturedemotwonorm.h | Pascal-So/lehrfempp | e2716e914169eec7ee59e822ea3ab303143eacd1 | [
"MIT"
] | null | null | null | #ifndef LF_LD_TWONORM_H
#define LF_LD_TWONORM_H
/**
* @file
* @brief Conmputation of the L2-norm of a piecewise linear finite element
* function in different ways
* @author Ralf Hiptmair
* @date April 2019
* @copyright MIT License
*/
#include <cmath>
#include "lecturedemo.h"
#include "lf/mesh/test_utils/test_meshes.h"
#include "lf/mesh/utils/utils.h"
#include "lf/uscalfe/uscalfe.h"
namespace lecturedemo {
/** @brief Computation of L2-norm of a piecewise linear finite element function
* on a triangular mesh via the Galerkin mass matrix
* @parm dofh \ref DofHandler object providing the mesh and local-to-global
* indexing
* @param uvec basis expansion coefficient vector for FE function
* @return L2-norm of FE function
*/
double l2normByMassMatrix(const lf::assemble::DofHandler &dofh,
const Eigen::VectorXd &uvec);
/** @brief Computation of L2-norm of a piecewise linear finite element function
* on a triangular mesh via direct edge based quadrature.
* @parm dofh \ref DofHandler object providing the mesh and local-to-global
* indexing
* @param uvec basis expansion coefficient vector for FE function
* @return L2-norm of FE function
*/
double l2normByQuadrature(const lf::assemble::DofHandler &dofh,
const Eigen::VectorXd &uvec);
/** @brief Computation of L2-norm of a piecewise linear finite element function
* on a triangular mesh via direct edge based quadrature.
* @parm dofh \ref DofHandler object providing the mesh and local-to-global
* indexing
* @param uvec basis expansion coefficient vector for FE function
* @return L2-norm of FE function
*/
double l2normByMeshFunction(
const std::shared_ptr<lf::uscalfe::UniformScalarFESpace<double>> &fe_space,
const Eigen::VectorXd &uvec);
/**
* @brief Driver routine for demos for LehrFEM++ matrix/vector
* assembly functions
*/
void lecturedemotwonorm();
} // namespace lecturedemo
#endif
| 33.566667 | 79 | 0.712512 | [
"mesh",
"object",
"vector"
] |
bda5c4b62037825885594aa40838df9d81b2f249 | 5,871 | h | C | aws-cpp-sdk-directconnect/include/aws/directconnect/model/DeleteInterconnectResult.h | ploki/aws-sdk-cpp | 17074e3e48c7411f81294e2ee9b1550c4dde842c | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-directconnect/include/aws/directconnect/model/DeleteInterconnectResult.h | ploki/aws-sdk-cpp | 17074e3e48c7411f81294e2ee9b1550c4dde842c | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-directconnect/include/aws/directconnect/model/DeleteInterconnectResult.h | ploki/aws-sdk-cpp | 17074e3e48c7411f81294e2ee9b1550c4dde842c | [
"Apache-2.0"
] | 1 | 2019-01-18T13:03:55.000Z | 2019-01-18T13:03:55.000Z | /*
* Copyright 2010-2017 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License").
* You may not use this file except in compliance with the License.
* A copy of the License is located at
*
* http://aws.amazon.com/apache2.0
*
* or in the "license" file accompanying this file. This file is distributed
* on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
* express or implied. See the License for the specific language governing
* permissions and limitations under the License.
*/
#pragma once
#include <aws/directconnect/DirectConnect_EXPORTS.h>
#include <aws/directconnect/model/InterconnectState.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace DirectConnect
{
namespace Model
{
class AWS_DIRECTCONNECT_API DeleteInterconnectResult
{
public:
DeleteInterconnectResult();
DeleteInterconnectResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
DeleteInterconnectResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>The state of the interconnect. The following are the possible values:</p>
* <ul> <li> <p> <code>requested</code>: The initial state of an interconnect. The
* interconnect stays in the requested state until the Letter of Authorization
* (LOA) is sent to the customer.</p> </li> <li> <p> <code>pending</code>: The
* interconnect is approved, and is being initialized.</p> </li> <li> <p>
* <code>available</code>: The network link is up, and the interconnect is ready
* for use.</p> </li> <li> <p> <code>down</code>: The network link is down.</p>
* </li> <li> <p> <code>deleting</code>: The interconnect is being deleted.</p>
* </li> <li> <p> <code>deleted</code>: The interconnect is deleted.</p> </li>
* </ul>
*/
inline const InterconnectState& GetInterconnectState() const{ return m_interconnectState; }
/**
* <p>The state of the interconnect. The following are the possible values:</p>
* <ul> <li> <p> <code>requested</code>: The initial state of an interconnect. The
* interconnect stays in the requested state until the Letter of Authorization
* (LOA) is sent to the customer.</p> </li> <li> <p> <code>pending</code>: The
* interconnect is approved, and is being initialized.</p> </li> <li> <p>
* <code>available</code>: The network link is up, and the interconnect is ready
* for use.</p> </li> <li> <p> <code>down</code>: The network link is down.</p>
* </li> <li> <p> <code>deleting</code>: The interconnect is being deleted.</p>
* </li> <li> <p> <code>deleted</code>: The interconnect is deleted.</p> </li>
* </ul>
*/
inline void SetInterconnectState(const InterconnectState& value) { m_interconnectState = value; }
/**
* <p>The state of the interconnect. The following are the possible values:</p>
* <ul> <li> <p> <code>requested</code>: The initial state of an interconnect. The
* interconnect stays in the requested state until the Letter of Authorization
* (LOA) is sent to the customer.</p> </li> <li> <p> <code>pending</code>: The
* interconnect is approved, and is being initialized.</p> </li> <li> <p>
* <code>available</code>: The network link is up, and the interconnect is ready
* for use.</p> </li> <li> <p> <code>down</code>: The network link is down.</p>
* </li> <li> <p> <code>deleting</code>: The interconnect is being deleted.</p>
* </li> <li> <p> <code>deleted</code>: The interconnect is deleted.</p> </li>
* </ul>
*/
inline void SetInterconnectState(InterconnectState&& value) { m_interconnectState = std::move(value); }
/**
* <p>The state of the interconnect. The following are the possible values:</p>
* <ul> <li> <p> <code>requested</code>: The initial state of an interconnect. The
* interconnect stays in the requested state until the Letter of Authorization
* (LOA) is sent to the customer.</p> </li> <li> <p> <code>pending</code>: The
* interconnect is approved, and is being initialized.</p> </li> <li> <p>
* <code>available</code>: The network link is up, and the interconnect is ready
* for use.</p> </li> <li> <p> <code>down</code>: The network link is down.</p>
* </li> <li> <p> <code>deleting</code>: The interconnect is being deleted.</p>
* </li> <li> <p> <code>deleted</code>: The interconnect is deleted.</p> </li>
* </ul>
*/
inline DeleteInterconnectResult& WithInterconnectState(const InterconnectState& value) { SetInterconnectState(value); return *this;}
/**
* <p>The state of the interconnect. The following are the possible values:</p>
* <ul> <li> <p> <code>requested</code>: The initial state of an interconnect. The
* interconnect stays in the requested state until the Letter of Authorization
* (LOA) is sent to the customer.</p> </li> <li> <p> <code>pending</code>: The
* interconnect is approved, and is being initialized.</p> </li> <li> <p>
* <code>available</code>: The network link is up, and the interconnect is ready
* for use.</p> </li> <li> <p> <code>down</code>: The network link is down.</p>
* </li> <li> <p> <code>deleting</code>: The interconnect is being deleted.</p>
* </li> <li> <p> <code>deleted</code>: The interconnect is deleted.</p> </li>
* </ul>
*/
inline DeleteInterconnectResult& WithInterconnectState(InterconnectState&& value) { SetInterconnectState(std::move(value)); return *this;}
private:
InterconnectState m_interconnectState;
};
} // namespace Model
} // namespace DirectConnect
} // namespace Aws
| 47.731707 | 142 | 0.66854 | [
"model"
] |
bda88ed1faa14f1b274361f3347a89eb43eab3b8 | 863 | h | C | src/libgeodecomp/storage/pointerneighborhood.h | aproeme/libgeodecomp | f78899c67ad62540fd153cba132a0a363a7b3fa9 | [
"BSL-1.0"
] | 40 | 2015-03-18T16:36:25.000Z | 2020-08-19T07:35:19.000Z | src/libgeodecomp/storage/pointerneighborhood.h | aproeme/libgeodecomp | f78899c67ad62540fd153cba132a0a363a7b3fa9 | [
"BSL-1.0"
] | 72 | 2015-02-05T10:41:30.000Z | 2022-03-03T12:02:47.000Z | src/libgeodecomp/storage/pointerneighborhood.h | aproeme/libgeodecomp | f78899c67ad62540fd153cba132a0a363a7b3fa9 | [
"BSL-1.0"
] | 17 | 2015-11-22T14:49:16.000Z | 2020-01-15T19:05:04.000Z | #ifndef LIBGEODECOMP_STORAGE_POINTERNEIGHBORHOOD_H
#define LIBGEODECOMP_STORAGE_POINTERNEIGHBORHOOD_H
#include <libgeodecomp/geometry/fixedcoord.h>
#include <libgeodecomp/geometry/stencils.h>
namespace LibGeoDecomp {
/**
* provides a neighborhood which can be adressed by parameters known
* at compile time. It uses an array of pointers to access the cells,
* which makes it suitable for any topology and storage. Short-lived
* instances should be optimized away by the compiler.
*/
template<typename CELL, typename STENCIL>
class PointerNeighborhood
{
public:
explicit PointerNeighborhood(CELL **cells) :
cells(cells)
{}
template<int X, int Y, int Z>
const CELL& operator[](FixedCoord<X, Y, Z>) const
{
return cells[Stencils::OffsetHelper<STENCIL, X, Y, Z>::VALUE][0];
}
private:
CELL **cells;
};
}
#endif
| 23.972222 | 73 | 0.730012 | [
"geometry"
] |
bdb0dfe4baf602c9a44834e3aed76d77888fabbd | 3,253 | h | C | package/cpp/api/JsiSkColorFilterFactory.h | hannojg/react-native-skia | 65a3c6676eab6ebe21bdd32d5ced838fc16649f0 | [
"MIT"
] | 2 | 2021-12-18T02:54:43.000Z | 2022-03-30T06:53:23.000Z | package/cpp/api/JsiSkColorFilterFactory.h | hannojg/react-native-skia | 65a3c6676eab6ebe21bdd32d5ced838fc16649f0 | [
"MIT"
] | null | null | null | package/cpp/api/JsiSkColorFilterFactory.h | hannojg/react-native-skia | 65a3c6676eab6ebe21bdd32d5ced838fc16649f0 | [
"MIT"
] | null | null | null | #pragma once
#include "JsiSkColorFilter.h"
#include "JsiSkHostObjects.h"
#include <jsi/jsi.h>
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wdocumentation"
#include <SkColorFilter.h>
#pragma clang diagnostic pop
namespace RNSkia {
using namespace facebook;
class JsiSkColorFilterFactory : public JsiSkHostObject {
public:
JSI_HOST_FUNCTION(MakeMatrix) {
auto jsiMatrix = arguments[0].asObject(runtime).asArray(runtime);
float matrix[20];
for (int i = 0; i < 20; i++) {
if (jsiMatrix.size(runtime) > i) {
matrix[i] = jsiMatrix.getValueAtIndex(runtime, i).asNumber();
}
}
// Return the newly constructed object
return jsi::Object::createFromHostObject(
runtime, std::make_shared<JsiSkColorFilter>(
getContext(), SkColorFilters::Matrix(matrix)));
}
JSI_HOST_FUNCTION(MakeBlend) {
auto color = arguments[0].asNumber();
SkBlendMode blend = (SkBlendMode)arguments[1].asNumber();
// Return the newly constructed object
return jsi::Object::createFromHostObject(
runtime, std::make_shared<JsiSkColorFilter>(
getContext(), SkColorFilters::Blend(color, blend)));
}
JSI_HOST_FUNCTION(MakeCompose) {
auto outer = JsiSkColorFilter::fromValue(runtime, arguments[0]);
auto inner = JsiSkColorFilter::fromValue(runtime, arguments[1]);
// Return the newly constructed object
return jsi::Object::createFromHostObject(
runtime, std::make_shared<JsiSkColorFilter>(
getContext(), SkColorFilters::Compose(outer, inner)));
}
JSI_HOST_FUNCTION(MakeLerp) {
auto t = arguments[0].asNumber();
auto dst = JsiSkColorFilter::fromValue(runtime, arguments[1]);
auto src = JsiSkColorFilter::fromValue(runtime, arguments[2]);
// Return the newly constructed object
return jsi::Object::createFromHostObject(
runtime, std::make_shared<JsiSkColorFilter>(
getContext(), SkColorFilters::Lerp(t, dst, src)));
}
JSI_HOST_FUNCTION(MakeSRGBToLinearGamma) {
// Return the newly constructed object
return jsi::Object::createFromHostObject(
runtime, std::make_shared<JsiSkColorFilter>(
getContext(), SkColorFilters::SRGBToLinearGamma()));
}
JSI_HOST_FUNCTION(MakeLinearToSRGBGamma) {
// Return the newly constructed object
return jsi::Object::createFromHostObject(
runtime, std::make_shared<JsiSkColorFilter>(
getContext(), SkColorFilters::LinearToSRGBGamma()));
}
JSI_EXPORT_FUNCTIONS(JSI_EXPORT_FUNC(JsiSkColorFilterFactory, MakeMatrix),
JSI_EXPORT_FUNC(JsiSkColorFilterFactory, MakeBlend),
JSI_EXPORT_FUNC(JsiSkColorFilterFactory, MakeCompose),
JSI_EXPORT_FUNC(JsiSkColorFilterFactory, MakeLerp),
JSI_EXPORT_FUNC(JsiSkColorFilterFactory,
MakeSRGBToLinearGamma),
JSI_EXPORT_FUNC(JsiSkColorFilterFactory,
MakeLinearToSRGBGamma))
JsiSkColorFilterFactory(std::shared_ptr<RNSkPlatformContext> context)
: JsiSkHostObject(context) {}
};
} // namespace RNSkia
| 36.550562 | 77 | 0.669536 | [
"object"
] |
bdbb36958d606755e8db39da88f08606e2ae53bf | 36,692 | c | C | test/json_test/test_json.c | JoelsonCarl/flatcc | 32629a3e4aa7e3fb4b51c52fd8c1519529c8df7f | [
"Apache-2.0"
] | null | null | null | test/json_test/test_json.c | JoelsonCarl/flatcc | 32629a3e4aa7e3fb4b51c52fd8c1519529c8df7f | [
"Apache-2.0"
] | 1 | 2019-03-30T01:49:34.000Z | 2019-03-30T01:49:34.000Z | test/json_test/test_json.c | JoelsonCarl/flatcc | 32629a3e4aa7e3fb4b51c52fd8c1519529c8df7f | [
"Apache-2.0"
] | null | null | null | #include <stdio.h>
#include "monster_test_json_parser.h"
#include "monster_test_json_printer.h"
#include "monster_test_verifier.h"
#include "flatcc/support/hexdump.h"
#define UQL FLATCC_JSON_PARSE_ALLOW_UNQUOTED_LIST
#define UQ FLATCC_JSON_PARSE_ALLOW_UNQUOTED
#undef ns
#define ns(x) FLATBUFFERS_WRAP_NAMESPACE(MyGame_Example, x)
#undef nsf
#define nsf(x) FLATBUFFERS_WRAP_NAMESPACE(Fantasy, x)
struct test_scope {
const char *identifier;
flatcc_json_parser_table_f *parser;
flatcc_json_printer_table_f *printer;
flatcc_table_verifier_f *verifier;
};
static const struct test_scope Monster = {
/* The is the schema global file identifier. */
ns(Monster_identifier),
ns(Monster_parse_json_table),
ns(Monster_print_json_table),
ns(Monster_verify_table)
};
static const struct test_scope Alt = {
/* This is the type hash identifier. */
ns(Alt_type_identifier),
ns(Alt_parse_json_table),
ns(Alt_print_json_table),
ns(Alt_verify_table)
};
static const struct test_scope Movie = {
/* This is the type hash identifier. */
nsf(Movie_type_identifier),
nsf(Movie_parse_json_table),
nsf(Movie_print_json_table),
nsf(Movie_verify_table)
};
int test_json(const struct test_scope *scope, char *json,
char *expect, int expect_err,
int parse_flags, int print_flags, int line)
{
int ret = -1;
int err;
void *flatbuffer = 0;
char *buf = 0;
size_t flatbuffer_size, buf_size;
flatcc_builder_t builder, *B;
flatcc_json_parser_t parser_ctx;
flatcc_json_printer_t printer_ctx;
int i;
B = &builder;
flatcc_builder_init(B);
flatcc_json_printer_init_dynamic_buffer(&printer_ctx, 0);
flatcc_json_printer_set_flags(&printer_ctx, print_flags);
err = flatcc_json_parser_table_as_root(B, &parser_ctx, json, strlen(json), parse_flags,
scope->identifier, scope->parser);
if (err != expect_err) {
if (expect_err) {
if (err) {
fprintf(stderr, "%d: json test: parse failed with: %s\n",
line, flatcc_json_parser_error_string(err));
fprintf(stderr, "but expected to fail with: %s\n",
flatcc_json_parser_error_string(expect_err));
fprintf(stderr, "%s\n", json);
} else {
fprintf(stderr, "%d: json test: parse successful, but expected to fail with: %s\n",
line, flatcc_json_parser_error_string(expect_err));
fprintf(stderr, "%s\n", json);
}
} else {
fprintf(stderr, "%d: json test: parse failed: %s\n", line, flatcc_json_parser_error_string(err));
fprintf(stderr, "%s\n", json);
}
for (i = 0; i < parser_ctx.pos - 1; ++i) {
fprintf(stderr, " ");
}
fprintf(stderr, "^\n");
goto failed;
}
if (expect_err) {
ret = 0;
goto done;
}
flatbuffer = flatcc_builder_finalize_aligned_buffer(B, &flatbuffer_size);
if ((ret = flatcc_verify_table_as_root(flatbuffer, flatbuffer_size, scope->identifier, scope->verifier))) {
fprintf(stderr, "%s:%d: buffer verification failed: %s\n",
__FILE__, line, flatcc_verify_error_string(ret));
goto failed;
}
flatcc_json_printer_table_as_root(&printer_ctx, flatbuffer, flatbuffer_size, scope->identifier, scope->printer);
buf = flatcc_json_printer_get_buffer(&printer_ctx, &buf_size);
if (!buf || strcmp(expect, buf)) {
fprintf(stderr, "%d: json test: printed buffer not as expected, got:\n", line);
fprintf(stderr, "%s\n", buf);
fprintf(stderr, "expected:\n");
fprintf(stderr, "%s\n", expect);
goto failed;
}
ret = 0;
done:
flatcc_builder_aligned_free(flatbuffer);
flatcc_builder_clear(B);
flatcc_json_printer_clear(&printer_ctx);
return ret;
failed:
if (flatbuffer) {
hexdump("parsed buffer", flatbuffer, flatbuffer_size, stderr);
}
ret = -1;
goto done;
}
#define BEGIN_TEST(name) int ret = 0; const struct test_scope *scope = &name
#define END_TEST() return ret;
#define TEST(x, y) \
ret |= test_json(scope, (x), (y), 0, 0, 0, __LINE__);
#define TEST_ERROR(x, err) \
ret |= test_json(scope, (x), 0, err, 0, 0, __LINE__);
#define TEST_FLAGS(fparse, fprint, x, y) \
ret |= test_json(scope, (x), (y), 0, (fparse), (fprint), __LINE__);
int edge_case_tests()
{
BEGIN_TEST(Monster);
/*
* Each symbolic value is type coerced and added. One might expect
* or'ing flags together, but it doesn't work with signed values
* and floating point target values. We would either need a much
* more complicated parser or restrict the places where symbols are
* allowed.
*/
#if 0
TEST( "{ name: \"Monster\", color: \"Green Blue Red Blue\"}",
"{\"name\":\"Monster\",\"color\":\"Red Green Blue\"}");
#else
#if UQ
TEST( "{ name: \"Monster\", color: \"Green Blue Red Blue\"}",
"{\"name\":\"Monster\",\"color\":19}");
#else
TEST( "{ \"name\": \"Monster\", \"color\": \"Green Blue Red Blue\"}",
"{\"name\":\"Monster\",\"color\":19}");
#endif
#endif
/*
* If a value is stored, even if default, it is also printed.
* This option can also be flagged compile time for better performance.
*/
TEST_FLAGS(flatcc_json_parser_f_force_add, 0,
"{ \"name\": \"Monster\", \"color\": 8}",
"{\"name\":\"Monster\",\"color\":\"Blue\"}");
TEST_FLAGS(0, flatcc_json_printer_f_noenum,
"{ \"name\": \"Monster\", \"color\": \"Green\"}",
"{\"name\":\"Monster\",\"color\":2}");
TEST_FLAGS(flatcc_json_parser_f_force_add, flatcc_json_printer_f_skip_default,
"{ \"name\": \"Monster\", \"color\": 8}",
"{\"name\":\"Monster\"}");
TEST_FLAGS(0, flatcc_json_printer_f_force_default,
"{ \"name\": \"Monster\", \"testf\":3.0}",
"{\"mana\":150,\"hp\":100,\"name\":\"Monster\",\"color\":\"Blue\",\"testbool\":true,\"testhashs32_fnv1\":0,\"testhashu32_fnv1\":0,\"testhashs64_fnv1\":0,\"testhashu64_fnv1\":0,\"testhashs32_fnv1a\":0,\"testhashu32_fnv1a\":0,\"testhashs64_fnv1a\":0,\"testhashu64_fnv1a\":0,\"testf\":3,\"testf2\":3,\"testf3\":0}");
/*
* Cannot test the default of testf field because float is printed as double with
* configuration dependent precision.
*/
#if 0
TEST_FLAGS(0, flatcc_json_printer_f_force_default,
"{ \"name\": \"Monster\", \"testf3\":3.14159012}",
"{\"mana\":150,\"hp\":100,\"name\":\"Monster\",\"color\":\"Blue\",\"testbool\":true,\"testhashs32_fnv1\":0,\"testhashu32_fnv1\":0,\"testhashs64_fnv1\":0,\"testhashu64_fnv1\":0,\"testhashs32_fnv1a\":0,\"testhashu32_fnv1a\":0,\"testhashs64_fnv1a\":0,\"testhashu64_fnv1a\":0,\"testf\":3.14159,\"testf2\":3,\"testf3\":0}");
#endif
TEST_FLAGS(flatcc_json_parser_f_force_add, 0,
"{ \"name\": \"Monster\", \"color\": \"Blue\"}",
"{\"name\":\"Monster\",\"color\":\"Blue\"}");
TEST_FLAGS(flatcc_json_parser_f_skip_unknown, 0,
"{ \"name\": \"Monster\", \"xcolor\": \"Green\", \"hp\": 42}",
"{\"hp\":42,\"name\":\"Monster\"}");
TEST_FLAGS(flatcc_json_parser_f_skip_unknown, flatcc_json_printer_f_unquote,
"{ \"name\": \"Monster\", \"xcolor\": \"Green\", \"hp\": 42}",
"{hp:42,name:\"Monster\"}");
/* Also test generic parser used with unions with late type field. */
TEST_FLAGS(flatcc_json_parser_f_skip_unknown, 0,
"{ \"name\": \"Monster\", \"xcolor\": \"Green\", "
"\"foobar\": { \"a\": [1, 2.0, ], \"a1\": {}, \"b\": null, \"c\":[], }, \"hp\": 42 }",
"{\"hp\":42,\"name\":\"Monster\"}");
#if UQ
/*
* If a value is stored, even if default, it is also printed.
* This option can also be flagged compile time for better performance.
*/
TEST_FLAGS(flatcc_json_parser_f_force_add, 0,
"{ name: \"Monster\", color: 8}",
"{\"name\":\"Monster\",\"color\":\"Blue\"}");
TEST_FLAGS(0, flatcc_json_printer_f_noenum,
"{ name: \"Monster\", color: Green}",
"{\"name\":\"Monster\",\"color\":2}");
TEST_FLAGS(flatcc_json_parser_f_force_add, flatcc_json_printer_f_skip_default,
"{ name: \"Monster\", color: 8}",
"{\"name\":\"Monster\"}");
TEST_FLAGS(0, flatcc_json_printer_f_force_default,
"{ name: \"Monster\"}",
"{\"mana\":150,\"hp\":100,\"name\":\"Monster\",\"color\":\"Blue\",\"testbool\":true,\"testhashs32_fnv1\":0,\"testhashu32_fnv1\":0,\"testhashs64_fnv1\":0,\"testhashu64_fnv1\":0,\"testhashs32_fnv1a\":0,\"testhashu32_fnv1a\":0,\"testhashs64_fnv1a\":0,\"testhashu64_fnv1a\":0,\"testf\":314159,\"testf2\":3,\"testf3\":0}");
TEST_FLAGS(flatcc_json_parser_f_force_add, 0,
"{ name: \"Monster\", color: Blue}",
"{\"name\":\"Monster\",\"color\":\"Blue\"}");
TEST_FLAGS(flatcc_json_parser_f_skip_unknown, 0,
"{ name: \"Monster\", xcolor: Green, hp: 42}",
"{\"hp\":42,\"name\":\"Monster\"}");
TEST_FLAGS(flatcc_json_parser_f_skip_unknown, flatcc_json_printer_f_unquote,
"{ name: \"Monster\", xcolor: Green, hp: 42}",
"{hp:42,name:\"Monster\"}");
/* Also test generic parser used with unions with late type field. */
TEST_FLAGS(flatcc_json_parser_f_skip_unknown, 0,
"{ name: \"Monster\", xcolor: Green, "
"foobar: { a: [1, 2.0, ], a1: {}, b: null, c:[], }, hp: 42 }",
"{\"hp\":42,\"name\":\"Monster\"}");
#endif
/* Without skip unknown, we should expect failure. */
#if 0
TEST( "{ name: \"Monster\", xcolor: Green}",
"{\"name\":\"Monster\"}");
#endif
/* We do not support null. */
#if 0
TEST(
"{ name: \"Monster\", test_type: null }",
"{\"name\":\"Monster\"}");
#endif
/*
* We do not allow empty flag strings because they might mean
* either default value, or 0.
*/
#if 0
/* Questionable if this really is an error. */
TEST( "{ name: \"Monster\", color: \"\"}",
"{\"name\":\"Monster\",\"color\":0}"); // TODO: should this be color:"" ?
TEST( "{ name: \"Monster\", color: \" \"}",
"{\"name\":\"Monster\",\"color\":0}");
#endif
END_TEST();
}
int error_case_tests()
{
BEGIN_TEST(Monster);
TEST_ERROR( "{ \"nickname\": \"Monster\" }",
flatcc_json_parser_error_unknown_symbol );
TEST_ERROR( "{ \"name\": \"Monster\", \"test_type\": \"Monster\", \"test\": { \"nickname\": \"Joker\", \"color\": \"Red\" } } }",
flatcc_json_parser_error_unknown_symbol );
TEST_ERROR( "{ \"name\": \"Monster\", \"test_type\": \"Monster\", \"test\": { \"name\": \"Joker\", \"colour\": \"Red\" } } }",
flatcc_json_parser_error_unknown_symbol );
TEST_ERROR( "{ \"name\": \"Monster\", \"testarrayoftables\": [ { \"nickname\": \"Joker\", \"color\": \"Red\" } ] }",
flatcc_json_parser_error_unknown_symbol );
TEST_ERROR( "{ \"name\": \"Monster\", \"testarrayoftables\": [ { \"name\": \"Joker\", \"colour\": \"Red\" } ] }",
flatcc_json_parser_error_unknown_symbol );
TEST_ERROR( "{ \"name\": \"Monster\", \"testarrayoftables\": ["
"{ \"name\": \"Joker\", \"color\": \"Red\", \"test_type\": \"Monster\", \"test\": { \"nickname\": \"Harley\", \"color\": \"Blue\" } } ] }",
flatcc_json_parser_error_unknown_symbol );
TEST_ERROR( "{ \"name\": \"Monster\", \"testarrayoftables\": ["
"{ \"name\": \"Joker\", \"color\": \"Red\", \"test_type\": \"Monster\", \"test\": { \"name\": \"Harley\", \"colour\": \"Blue\" } } ] }",
flatcc_json_parser_error_unknown_symbol );
TEST_ERROR( "{ \"name\": \"Monster\", \"testarrayoftables\": ["
"{ \"name\": \"Joker\", \"test_type\": \"Monster\", \"test\": { \"nickname\": \"Harley\" } },"
"{ \"name\": \"Bonnie\", \"test_type\": \"Monster\", \"test\": { \"name\": \"Clyde\" } } ] }",
flatcc_json_parser_error_unknown_symbol );
TEST_ERROR( "{ \"name\": \"Monster\", \"testarrayoftables\": ["
"{ \"name\": \"Joker\", \"test_type\": \"Monster\", \"test\": { \"name\": \"Harley\" } },"
"{ \"name\": \"Bonnie\", \"test_type\": \"Monster\", \"test\": { \"nickname\": \"Clyde\" } } ] }",
flatcc_json_parser_error_unknown_symbol );
#if !UQ
TEST_ERROR( "{ nickname: \"Monster\" }",
flatcc_json_parser_error_unexpected_character );
TEST_ERROR( "{ \"name\": \"Monster\", \"color\": Green }",
flatcc_json_parser_error_unexpected_character );
TEST_ERROR( "{ \"name\": \"Monster\", \"color\": Green Red Blue }",
flatcc_json_parser_error_unexpected_character );
#endif
#if UQ
TEST_ERROR( "{ nickname: \"Monster\" }",
flatcc_json_parser_error_unknown_symbol );
TEST_ERROR( "{ name: \"Monster\", test_type: Monster, test: { nickname: \"Joker\", color: \"Red\" } } }",
flatcc_json_parser_error_unknown_symbol );
TEST_ERROR( "{ name: \"Monster\", test_type: Monster, test: { name: \"Joker\", colour: \"Red\" } } }",
flatcc_json_parser_error_unknown_symbol );
TEST_ERROR( "{ name: \"Monster\", testarrayoftables: [ { nickname: \"Joker\", color: \"Red\" } ] }",
flatcc_json_parser_error_unknown_symbol );
TEST_ERROR( "{ name: \"Monster\", testarrayoftables: [ { name: \"Joker\", colour: \"Red\" } ] }",
flatcc_json_parser_error_unknown_symbol );
TEST_ERROR( "{ name: \"Monster\", testarrayoftables: ["
"{ name: \"Joker\", color: \"Red\", test_type: Monster, test: { nickname: \"Harley\", color: \"Blue\" } } ] }",
flatcc_json_parser_error_unknown_symbol );
TEST_ERROR( "{ name: \"Monster\", testarrayoftables: ["
"{ name: \"Joker\", color: \"Red\", test_type: Monster, test: { name: \"Harley\", colour: \"Blue\" } } ] }",
flatcc_json_parser_error_unknown_symbol );
TEST_ERROR( "{ name: \"Monster\", testarrayoftables: ["
"{ name: \"Joker\", test_type: Monster, test: { nickname: \"Harley\" } },"
"{ name: \"Bonnie\", test_type: Monster, test: { name: \"Clyde\" } } ] }",
flatcc_json_parser_error_unknown_symbol );
TEST_ERROR( "{ name: \"Monster\", testarrayoftables: ["
"{ name: \"Joker\", test_type: Monster, test: { name: \"Harley\" } },"
"{ name: \"Bonnie\", test_type: Monster, test: { nickname: \"Clyde\" } } ] }",
flatcc_json_parser_error_unknown_symbol );
#endif
END_TEST();
}
#define RANDOM_BASE64 "zLOuiUjH49tz4Ap2JnmpTX5NqoiMzlD8hSw45QCS2yaSp7UYoA" \
"oE8KpY/5pKYmk+54NI40hyeyZ1zRUE4vKQT0hEdVl0iXq2fqPamkVD1AZlVvQJ1m00PaoXOSgG+64Zv+Uygw=="
#define RANDOM_BASE64_NOPAD "zLOuiUjH49tz4Ap2JnmpTX5NqoiMzlD8hSw45QCS2yaSp7UYoA" \
"oE8KpY/5pKYmk+54NI40hyeyZ1zRUE4vKQT0hEdVl0iXq2fqPamkVD1AZlVvQJ1m00PaoXOSgG+64Zv+Uygw"
#define RANDOM_BASE64URL "zLOuiUjH49tz4Ap2JnmpTX5NqoiMzlD8hSw45QCS2yaSp7UYoA" \
"oE8KpY_5pKYmk-54NI40hyeyZ1zRUE4vKQT0hEdVl0iXq2fqPamkVD1AZlVvQJ1m00PaoXOSgG-64Zv-Uygw=="
#define RANDOM_BASE64URL_NOPAD "zLOuiUjH49tz4Ap2JnmpTX5NqoiMzlD8hSw45QCS2yaSp7UYoA" \
"oE8KpY_5pKYmk-54NI40hyeyZ1zRUE4vKQT0hEdVl0iXq2fqPamkVD1AZlVvQJ1m00PaoXOSgG-64Zv-Uygw"
int base64_tests()
{
BEGIN_TEST(Monster);
/* Reference */
TEST( "{ \"name\": \"Monster\" }",
"{\"name\":\"Monster\"}");
TEST( "{ \"name\": \"Monster\", \"testbase64\":{} }",
"{\"name\":\"Monster\",\"testbase64\":{}}");
TEST( "{ \"name\": \"Monster\", \"testbase64\":{ \"data\":\"" RANDOM_BASE64 "\"} }",
"{\"name\":\"Monster\",\"testbase64\":{\"data\":\"" RANDOM_BASE64 "\"}}");
TEST( "{ \"name\": \"Monster\", \"testbase64\":{ \"urldata\":\"" RANDOM_BASE64URL "\"} }",
"{\"name\":\"Monster\",\"testbase64\":{\"urldata\":\"" RANDOM_BASE64URL "\"}}");
TEST( "{ \"name\": \"Monster\", \"testbase64\":{ \"data\":\"" RANDOM_BASE64_NOPAD "\"} }",
"{\"name\":\"Monster\",\"testbase64\":{\"data\":\"" RANDOM_BASE64 "\"}}");
TEST( "{ \"name\": \"Monster\", \"testbase64\":{ \"urldata\":\"" RANDOM_BASE64URL_NOPAD "\"} }",
"{\"name\":\"Monster\",\"testbase64\":{\"urldata\":\"" RANDOM_BASE64URL "\"}}");
TEST_ERROR( "{ \"name\": \"Monster\", \"testbase64\":{ \"data\":\"" RANDOM_BASE64URL "\"} }",
flatcc_json_parser_error_base64);
TEST_ERROR( "{ \"name\": \"Monster\", \"testbase64\":{ \"urldata\":\"" RANDOM_BASE64 "\"} }",
flatcc_json_parser_error_base64url);
/* Test case from Googles flatc implementation. */
#if UQ
TEST( "{name: \"Monster\","
"testbase64: {"
"data: \"23A/47d450+sdfx9+wRYIS09ckas/asdFBQ=\","
"urldata: \"23A_47d450-sdfx9-wRYIS09ckas_asdFBQ=\","
"nested: \"FAAAAE1PTlMMAAwAAAAEAAYACAAMAAAAAAAAAAQAAAANAAAATmVzdGVkTW9uc3RlcgAAAA==\""
"}}",
"{\"name\":\"Monster\","
"\"testbase64\":{"
"\"data\":\"23A/47d450+sdfx9+wRYIS09ckas/asdFBQ=\","
"\"urldata\":\"23A_47d450-sdfx9-wRYIS09ckas_asdFBQ=\","
"\"nested\":\"FAAAAE1PTlMMAAwAAAAEAAYACAAMAAAAAAAAAAQAAAANAAAATmVzdGVkTW9uc3RlcgAAAA==\""
"}}");
TEST( "{name: \"Monster\","
"testbase64: {"
"data: \"23A/47d450+sdfx9+wRYIS09ckas/asdFBQ\","
"urldata: \"23A_47d450-sdfx9-wRYIS09ckas_asdFBQ\","
"nested: \"FAAAAE1PTlMMAAwAAAAEAAYACAAMAAAAAAAAAAQAAAANAAAATmVzdGVkTW9uc3RlcgAAAA\""
"}}",
"{\"name\":\"Monster\","
"\"testbase64\":{"
"\"data\":\"23A/47d450+sdfx9+wRYIS09ckas/asdFBQ=\","
"\"urldata\":\"23A_47d450-sdfx9-wRYIS09ckas_asdFBQ=\","
"\"nested\":\"FAAAAE1PTlMMAAwAAAAEAAYACAAMAAAAAAAAAAQAAAANAAAATmVzdGVkTW9uc3RlcgAAAA==\""
"}}");
#endif
END_TEST();
}
int mixed_type_union_tests()
{
BEGIN_TEST(Movie);
/* Reference */
TEST( "{ \"main_character_type\": \"Rapunzel\", \"main_character\": { \"hair_length\": 19 } }",
"{\"main_character_type\":\"Rapunzel\",\"main_character\":{\"hair_length\":19}}");
TEST( "{ \"main_character_type\": \"Rapunzel\", \"main_character\": { \"hair_length\": 19 },"
" \"side_kick_type\": \"Other\", \"side_kick\": \"a donkey\"}",
"{\"main_character_type\":\"Rapunzel\",\"main_character\":{\"hair_length\":19},"
"\"side_kick_type\":\"Other\",\"side_kick\":\"a donkey\"}");
TEST( "{ \"main_character_type\": \"Rapunzel\", \"main_character\": { \"hair_length\": 19 },"
" \"side_kick_type\": \"Fantasy.Character.Other\", \"side_kick\": \"a donkey\"}}",
"{\"main_character_type\":\"Rapunzel\",\"main_character\":{\"hair_length\":19},"
"\"side_kick_type\":\"Other\",\"side_kick\":\"a donkey\"}");
TEST( "{ \"main_character_type\": \"Rapunzel\", \"main_character\": { \"hair_length\": 19 },"
" \"side_kick_type\": \"Fantasy.Character.Other\", \"side_kick\": \"a donkey\","
" \"antagonist_type\": \"MuLan\", \"antagonist\": {\"sword_attack_damage\": 42}}",
"{\"main_character_type\":\"Rapunzel\",\"main_character\":{\"hair_length\":19},"
"\"antagonist_type\":\"MuLan\",\"antagonist\":{\"sword_attack_damage\":42},"
"\"side_kick_type\":\"Other\",\"side_kick\":\"a donkey\"}");
TEST( "{ \"main_character_type\": \"Rapunzel\", \"main_character\": { \"hair_length\": 19 },"
" \"side_kick_type\": \"Fantasy.Character.Other\", \"side_kick\": \"a donkey\","
" \"antagonist_type\": \"MuLan\", \"antagonist\": {\"sword_attack_damage\": 42},"
" \"characters_type\": [], \"characters\": []}",
"{\"main_character_type\":\"Rapunzel\",\"main_character\":{\"hair_length\":19},"
"\"antagonist_type\":\"MuLan\",\"antagonist\":{\"sword_attack_damage\":42},"
"\"side_kick_type\":\"Other\",\"side_kick\":\"a donkey\","
"\"characters_type\":[],\"characters\":[]}")
TEST( "{ \"main_character_type\": \"Rapunzel\", \"main_character\": { \"hair_length\": 19 },"
" \"side_kick_type\": \"Fantasy.Character.Other\", \"side_kick\": \"a donkey\","
" \"antagonist_type\": \"MuLan\", \"antagonist\": {\"sword_attack_damage\": 42},"
" \"characters_type\": [\"Fantasy.Character.Rapunzel\", \"Other\", 0, \"MuLan\"],"
" \"characters\": [{\"hair_length\":19}, \"unattributed extras\", null, {\"sword_attack_damage\":2}]}",
"{\"main_character_type\":\"Rapunzel\",\"main_character\":{\"hair_length\":19},"
"\"antagonist_type\":\"MuLan\",\"antagonist\":{\"sword_attack_damage\":42},"
"\"side_kick_type\":\"Other\",\"side_kick\":\"a donkey\","
"\"characters_type\":[\"Rapunzel\",\"Other\",\"NONE\",\"MuLan\"],"
"\"characters\":[{\"hair_length\":19},\"unattributed extras\",null,{\"sword_attack_damage\":2}]}")
TEST( "{ \"main_character_type\": \"Rapunzel\", \"main_character\": { \"hair_length\": 19 },"
" \"side_kick_type\": \"Character.Other\", \"side_kick\": \"a donkey\"}",
"{\"main_character_type\":\"Rapunzel\",\"main_character\":{\"hair_length\":19},"
"\"side_kick_type\":\"Other\",\"side_kick\":\"a donkey\"}");
END_TEST();
}
int union_vector_tests()
{
BEGIN_TEST(Alt);
/* Union vector */
TEST( "{ \"manyany_type\": [ \"Monster\" ], \"manyany\": [{\"name\": \"Joe\"}] }",
"{\"manyany_type\":[\"Monster\"],\"manyany\":[{\"name\":\"Joe\"}]}");
TEST( "{\"manyany_type\": [ \"NONE\" ], \"manyany\": [ null ] }",
"{\"manyany_type\":[\"NONE\"],\"manyany\":[null]}");
TEST( "{\"manyany_type\": [ \"Monster\", \"NONE\" ], \"manyany\": [{\"name\": \"Joe\"}, null] }",
"{\"manyany_type\":[\"Monster\",\"NONE\"],\"manyany\":[{\"name\":\"Joe\"},null]}");
TEST( "{\"manyany_type\": [ \"Monster\" ], \"manyany\": [ { \"name\":\"Joe\", \"test_type\": \"Monster\", \"test\": { \"name\": \"any Monster\" } } ] }",
"{\"manyany_type\":[\"Monster\"],\"manyany\":[{\"name\":\"Joe\",\"test_type\":\"Monster\",\"test\":{\"name\":\"any Monster\"}}]}");
TEST( "{\"manyany\": [{\"name\": \"Joe\"}], \"manyany_type\": [ \"Monster\" ] }",
"{\"manyany_type\":[\"Monster\"],\"manyany\":[{\"name\":\"Joe\"}]}");
TEST( "{\"manyany\": [{\"manyany\":[null, null], \"manyany_type\": [\"NONE\", \"NONE\"]}], \"manyany_type\": [ \"Alt\" ] }",
"{\"manyany_type\":[\"Alt\"],\"manyany\":[{\"manyany_type\":[\"NONE\",\"NONE\"],\"manyany\":[null,null]}]}");
END_TEST();
}
/*
* Here we cover some border cases around unions and flag
* enumerations, and nested buffers.
*
* More complex objects with struct members etc. are reasonably
* covered in the printer and parser tests using the golden data
* set.
*/
int main()
{
BEGIN_TEST(Monster);
ret |= edge_case_tests();
ret |= error_case_tests();
ret |= union_vector_tests();
ret |= base64_tests();
ret |= mixed_type_union_tests();
/* Allow trailing comma. */
TEST( "{ \"name\": \"Monster\", }",
"{\"name\":\"Monster\"}");
TEST( "{\"color\": \"Red\", \"name\": \"Monster\", }",
"{\"name\":\"Monster\",\"color\":\"Red\"}");
TEST( "{ \"name\": \"Monster\", \"color\": \"Green\" }",
"{\"name\":\"Monster\",\"color\":\"Green\"}");
TEST( "{ \"name\": \"Monster\", \"color\": \"Green Red Blue\" }",
"{\"name\":\"Monster\",\"color\":\"Red Green Blue\"}");
TEST( "{ \"name\": \"Monster\", \"color\": \" Green Red Blue \" }",
"{\"name\":\"Monster\",\"color\":\"Red Green Blue\"}");
TEST( "{ \"name\": \"Monster\", \"color\": \"Red\" }",
"{\"name\":\"Monster\",\"color\":\"Red\"}");
TEST( "{ \"name\": \"Monster\", \"color\" :\"Green\" }",
"{\"name\":\"Monster\",\"color\":\"Green\"}");
/* Default value. */
TEST( "{ \"name\": \"Monster\", \"color\": \"Blue\" }",
"{\"name\":\"Monster\"}");
/* Default value. */
TEST( "{ \"name\": \"Monster\", \"color\": 8}",
"{\"name\":\"Monster\"}");
#if UQ
/* Allow trailing comma. */
TEST( "{ name: \"Monster\", }",
"{\"name\":\"Monster\"}");
TEST( "{color: \"Red\", name: \"Monster\", }",
"{\"name\":\"Monster\",\"color\":\"Red\"}");
TEST( "{ name: \"Monster\", color: \"Green\" }",
"{\"name\":\"Monster\",\"color\":\"Green\"}");
TEST( "{ name: \"Monster\", color: \"Green Red Blue\" }",
"{\"name\":\"Monster\",\"color\":\"Red Green Blue\"}");
TEST( "{ name: \"Monster\", color: \" Green Red Blue \" }",
"{\"name\":\"Monster\",\"color\":\"Red Green Blue\"}");
TEST( "{ name: \"Monster\", color: Red }",
"{\"name\":\"Monster\",\"color\":\"Red\"}");
TEST( "{ name: \"Monster\", color: Green }",
"{\"name\":\"Monster\",\"color\":\"Green\"}");
/* Default value. */
TEST( "{ name: \"Monster\", color: Blue }",
"{\"name\":\"Monster\"}");
/* Default value. */
TEST( "{ name: \"Monster\", color: 8}",
"{\"name\":\"Monster\"}");
#endif
#if UQL
TEST( "{ name: \"Monster\", color: Green Red }",
"{\"name\":\"Monster\",\"color\":\"Red Green\"}");
#endif
#if UQL
/* No leading space in unquoted flag. */
TEST( "{ name: \"Monster\", color:Green Red }",
"{\"name\":\"Monster\",\"color\":\"Red Green\"}");
TEST( "{ name: \"Monster\", color: Green Red}",
"{\"name\":\"Monster\",\"color\":\"Red Green\"}");
TEST( "{ name: \"Monster\", color:Green Blue Red }",
"{\"name\":\"Monster\",\"color\":\"Red Green Blue\"}");
#endif
TEST( "{ \"name\": \"Monster\", \"color\": 1}",
"{\"name\":\"Monster\",\"color\":\"Red\"}");
TEST( "{ \"name\": \"Monster\", \"color\": 2}",
"{\"name\":\"Monster\",\"color\":\"Green\"}");
TEST( "{ \"name\": \"Monster\", \"color\": 9}",
"{\"name\":\"Monster\",\"color\":\"Red Blue\"}");
TEST( "{ \"name\": \"Monster\", \"color\": 11}",
"{\"name\":\"Monster\",\"color\":\"Red Green Blue\"}");
TEST( "{ \"name\": \"Monster\", \"color\": 12}",
"{\"name\":\"Monster\",\"color\":12}");
TEST( "{ \"name\": \"Monster\", \"color\": 15}",
"{\"name\":\"Monster\",\"color\":15}");
TEST( "{ \"name\": \"Monster\", \"color\": 0}",
"{\"name\":\"Monster\",\"color\":0}");
TEST( "{ \"name\": \"Monster\", \"color\": \"Color.Red\"}",
"{\"name\":\"Monster\",\"color\":\"Red\"}");
TEST( "{ \"name\": \"Monster\", \"color\": \"MyGame.Example.Color.Red\"}",
"{\"name\":\"Monster\",\"color\":\"Red\"}");
TEST( "{ \"name\": \"Monster\", \"hp\": \"Color.Green\"}",
"{\"hp\":2,\"name\":\"Monster\"}");
TEST( "{ \"name\": \"Monster\", \"hp\": \"Color.Green\"}",
"{\"hp\":2,\"name\":\"Monster\"}");
TEST( "{ \"name\": \"Monster\", \"test_type\": \"Monster\", \"test\": { \"name\": \"any Monster\" } }",
"{\"name\":\"Monster\",\"test_type\":\"Monster\",\"test\":{\"name\":\"any Monster\"}}");
/* This is tricky because the test field must be reparsed after discovering the test type. */
TEST( "{ \"name\": \"Monster\", \"test\": { \"name\": \"second Monster\" }, \"test_type\": \"Monster\" }",
"{\"name\":\"Monster\",\"test_type\":\"Monster\",\"test\":{\"name\":\"second Monster\"}}");
/* Also test that parsing can continue after reparse. */
TEST( "{ \"name\": \"Monster\", \"test\": { \"name\": \"second Monster\" }, \"hp\":17, \"test_type\":\n \"Monster\", \"color\":\"Green\" }",
"{\"hp\":17,\"name\":\"Monster\",\"color\":\"Green\",\"test_type\":\"Monster\",\"test\":{\"name\":\"second Monster\"}}");
/* Test that NONE is recognized, and that we do not get a missing table error.*/
TEST( "{ \"name\": \"Monster\", \"test_type\": \"NONE\" }",
"{\"name\":\"Monster\"}");
TEST( "{ \"name\": \"Monster\", \"test_type\": 0 }",
"{\"name\":\"Monster\"}");
#if UQ
TEST( "{ name: \"Monster\", color: 1}",
"{\"name\":\"Monster\",\"color\":\"Red\"}");
TEST( "{ name: \"Monster\", color: 2}",
"{\"name\":\"Monster\",\"color\":\"Green\"}");
TEST( "{ name: \"Monster\", color: 9}",
"{\"name\":\"Monster\",\"color\":\"Red Blue\"}");
TEST( "{ name: \"Monster\", color: 11}",
"{\"name\":\"Monster\",\"color\":\"Red Green Blue\"}");
TEST( "{ name: \"Monster\", color: 12}",
"{\"name\":\"Monster\",\"color\":12}");
TEST( "{ name: \"Monster\", color: 15}",
"{\"name\":\"Monster\",\"color\":15}");
TEST( "{ name: \"Monster\", color: 0}",
"{\"name\":\"Monster\",\"color\":0}");
TEST( "{ name: \"Monster\", color: Color.Red}",
"{\"name\":\"Monster\",\"color\":\"Red\"}");
TEST( "{ name: \"Monster\", color: MyGame.Example.Color.Red}",
"{\"name\":\"Monster\",\"color\":\"Red\"}");
TEST( "{ name: \"Monster\", hp: Color.Green}",
"{\"hp\":2,\"name\":\"Monster\"}");
TEST( "{ name: \"Monster\", hp: Color.Green}",
"{\"hp\":2,\"name\":\"Monster\"}");
TEST( "{ name: \"Monster\", test_type: Monster, test: { name: \"any Monster\" } }",
"{\"name\":\"Monster\",\"test_type\":\"Monster\",\"test\":{\"name\":\"any Monster\"}}");
/* This is tricky because the test field must be reparsed after discovering the test type. */
TEST( "{ name: \"Monster\", test: { name: \"second Monster\" }, test_type: Monster }",
"{\"name\":\"Monster\",\"test_type\":\"Monster\",\"test\":{\"name\":\"second Monster\"}}");
/* Also test that parsing can continue after reparse. */
TEST( "{ name: \"Monster\", test: { name: \"second Monster\" }, hp:17, test_type:\n Monster, color:Green }",
"{\"hp\":17,\"name\":\"Monster\",\"color\":\"Green\",\"test_type\":\"Monster\",\"test\":{\"name\":\"second Monster\"}}");
/* Test that NONE is recognized, and that we do not get a missing table error.*/
TEST( "{ name: \"Monster\", test_type: NONE }",
"{\"name\":\"Monster\"}");
TEST( "{ name: \"Monster\", test_type: 0 }",
"{\"name\":\"Monster\"}");
#endif
#if UQL
/*
* Test that generic parsing handles multiple flags correctly during
* first pass before backtracking.
*/
TEST( "{ name: \"Monster\", test: { name: \"second Monster\", color: Red Green }, test_type: Monster }",
"{\"name\":\"Monster\",\"test_type\":\"Monster\",\"test\":{\"name\":\"second Monster\",\"color\":\"Red Green\"}}");
#endif
/* Ditto quoted flags. */
TEST( "{ \"name\": \"Monster\", \"test\": { \"name\": \"second Monster\", \"color\": \" Red Green \" }, \"test_type\": \"Monster\" }",
"{\"name\":\"Monster\",\"test_type\":\"Monster\",\"test\":{\"name\":\"second Monster\",\"color\":\"Red Green\"}}");
/*
* Note the '\/' becomes just '/', and that '/' also works in input.
*
* The json printer does not have a concept of \x it always uses
* unicode.
*
* We use json extension \x to inject a control 03 which extends
* to a printed unicode escape, while the \u00F8 is a valid
* character after encoding, and is thus not escaped after printing
* but rather becoems a two-byte utf-8 encoding of 'ø' which
* we use C encoding to form utf8 C3B8 == \u00F8.
*/
TEST( "{ \"name\": \"Mon\xfF\xFf\\x03s\\xC3\\xF9\\u00F8ter\\b\\f\\n\\r\\t\\\"\\\\\\/'/\", }",
"{\"name\":\"Mon\xff\xff\\u0003s\xc3\xf9\xc3\xb8ter\\b\\f\\n\\r\\t\\\"\\\\/'/\"}");
TEST( "{ \"name\": \"\\u168B\\u1691\"}",
"{\"name\":\"\xe1\x9a\x8b\xe1\x9a\x91\"}");
/* Nested flatbuffer, either is a known object, or as a vector. */
TEST( "{ \"name\": \"Monster\", \"testnestedflatbuffer\":{ \"name\": \"sub Monster\" } }",
"{\"name\":\"Monster\",\"testnestedflatbuffer\":{\"name\":\"sub Monster\"}}");
#if FLATBUFFERS_PROTOCOL_IS_LE
TEST( "{ \"name\": \"Monster\", \"testnestedflatbuffer\":"
"[" /* start of nested flatbuffer, implicit size: 40 */
"4,0,0,0," /* header: object offset = 4, no identifier */
"248,255,255,255," /* vtable offset */
"16,0,0,0," /* offset to name */
"12,0,8,0,0,0,0,0,0,0,4,0," /* vtable */
"11,0,0,0,115,117,98,32,77,111,110,115,116,101,114,0" /* name = "sub Monster" */
"]" /* end of nested flatbuffer */
"}",
"{\"name\":\"Monster\",\"testnestedflatbuffer\":{\"name\":\"sub Monster\"}}");
#else
TEST( "{ \"name\": \"Monster\", \"testnestedflatbuffer\":"
"[" /* start of nested flatbuffer, implicit size: 40 */
"0,0,0,4," /* header: object offset = 4, no identifier */
"255,255,255,248," /* vtable offset */
"0,0,0,16," /* offset to name */
"0,12,0,8,0,0,0,0,0,0,0,4," /* vtable */
"0,0,0,11,115,117,98,32,77,111,110,115,116,101,114,0" /* name = "sub Monster" */
"]" /* end of nested flatbuffer */
"}",
"{\"name\":\"Monster\",\"testnestedflatbuffer\":{\"name\":\"sub Monster\"}}");
#endif
/* Test empty table */
TEST( "{ \"name\": \"Monster\", \"testempty\": {} }",
"{\"name\":\"Monster\",\"testempty\":{}}");
/* Test empty array */
TEST( "{ \"name\": \"Monster\", \"testarrayoftables\": [] }",
"{\"name\":\"Monster\",\"testarrayoftables\":[]}");
/* Test JSON prefix parsing */
TEST( "{ \"name\": \"Monster\", \"test_type\":\"Alt\", \"test\":{\"prefix\":{"
"\"testjsonprefixparsing\": { \"aaaa\": \"test\", \"aaaa12345\": 17 } }}}",
"{\"name\":\"Monster\",\"test_type\":\"Alt\",\"test\":{\"prefix\":{"
"\"testjsonprefixparsing\":{\"aaaa\":\"test\",\"aaaa12345\":17}}}}");
/* TODO: this parses with the last to }} missing, although it does not add the broken objects. */
TEST( "{ \"name\": \"Monster\", \"test_type\":\"Alt\", \"test\":{\"prefix\":{"
"\"testjsonprefixparsing\": { \"bbbb\": \"test\", \"bbbb1234\": 19 } }",
"{\"name\":\"Monster\"}");
TEST( "{ \"name\": \"Monster\", \"test_type\":\"Alt\", \"test\":{\"prefix\":{"
"\"testjsonprefixparsing\": { \"bbbb\": \"test\", \"bbbb1234\": 19 } }}}",
"{\"name\":\"Monster\",\"test_type\":\"Alt\",\"test\":{\"prefix\":{"
"\"testjsonprefixparsing\":{\"bbbb\":\"test\",\"bbbb1234\":19}}}}");
TEST( "{ \"name\": \"Monster\", \"test_type\":\"Alt\", \"test\":{\"prefix\":{"
"\"testjsonprefixparsing\": { \"cccc\": \"test\", \"cccc1234\": 19, \"cccc12345\": 17 } }}}",
"{\"name\":\"Monster\",\"test_type\":\"Alt\",\"test\":{\"prefix\":{"
"\"testjsonprefixparsing\":{\"cccc\":\"test\",\"cccc1234\":19,\"cccc12345\":17}}}}");
TEST( "{ \"name\": \"Monster\", \"test_type\":\"Alt\", \"test\":{\"prefix\":{"
"\"testjsonprefixparsing\": { \"dddd1234\": 19, \"dddd12345\": 17 } }}}",
"{\"name\":\"Monster\",\"test_type\":\"Alt\",\"test\":{\"prefix\":{"
"\"testjsonprefixparsing\":{\"dddd1234\":19,\"dddd12345\":17}}}}");
TEST( "{ \"name\": \"Monster\", \"test_type\":\"Alt\", \"test\":{\"prefix\":{"
"\"testjsonprefixparsing2\": { \"aaaa_bbbb_steps\": 19, \"aaaa_bbbb_start_\": 17 } }}}",
"{\"name\":\"Monster\",\"test_type\":\"Alt\",\"test\":{\"prefix\":{"
"\"testjsonprefixparsing2\":{\"aaaa_bbbb_steps\":19,\"aaaa_bbbb_start_\":17}}}}");
TEST( "{ \"name\": \"Monster\", \"test_type\":\"Alt\", \"test\":{\"prefix\":{"
"\"testjsonprefixparsing3\": { \"aaaa_bbbb_steps\": 19, \"aaaa_bbbb_start_steps\": 17 } }}}",
"{\"name\":\"Monster\",\"test_type\":\"Alt\",\"test\":{\"prefix\":{"
"\"testjsonprefixparsing3\":{\"aaaa_bbbb_steps\":19,\"aaaa_bbbb_start_steps\":17}}}}");
return ret ? -1: 0;
}
| 45.298765 | 319 | 0.531642 | [
"object",
"vector"
] |
bdc258e11945eadb14194fdc0cd0e8329dac4586 | 1,819 | h | C | System/Library/PrivateFrameworks/NearbyInteraction.framework/NearbyInteraction-Structs.h | lechium/tvOS142Headers | c7696f6d760e4822f61b9f2c2adcd18749700fda | [
"MIT"
] | 1 | 2020-11-11T06:05:23.000Z | 2020-11-11T06:05:23.000Z | System/Library/PrivateFrameworks/NearbyInteraction.framework/NearbyInteraction-Structs.h | lechium/tvOS142Headers | c7696f6d760e4822f61b9f2c2adcd18749700fda | [
"MIT"
] | null | null | null | System/Library/PrivateFrameworks/NearbyInteraction.framework/NearbyInteraction-Structs.h | lechium/tvOS142Headers | c7696f6d760e4822f61b9f2c2adcd18749700fda | [
"MIT"
] | null | null | null | /*
* This header is generated by classdump-dyld 1.5
* on Tuesday, November 10, 2020 at 10:20:43 PM Mountain Standard Time
* Operating System: Version 14.2 (Build 18K57)
* Image Source: /System/Library/PrivateFrameworks/NearbyInteraction.framework/NearbyInteraction
* classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. Updated by Kevin Bradley.
*/
typedef struct opaque_pthread_mutex_t {
long long __sig;
char __opaque[56];
} opaque_pthread_mutex_t;
typedef struct mutex {
opaque_pthread_mutex_t __m_;
} mutex;
typedef struct _compressed_pair<UWBSessionInterruptionBookkeeping *, std::__1::allocator<UWBSessionInterruptionBookkeeping> > {
UWBSessionInterruptionBookkeeping __value_;
} compressed_pair<UWBSessionInterruptionBookkeeping *, std::__1::allocator<UWBSessionInterruptionBookkeeping> >;
typedef struct vector<UWBSessionInterruptionBookkeeping, std::__1::allocator<UWBSessionInterruptionBookkeeping> > {
UWBSessionInterruptionBookkeeping __begin_;
UWBSessionInterruptionBookkeeping __end_;
compressed_pair<UWBSessionInterruptionBookkeeping *, std::__1::allocator<UWBSessionInterruptionBookkeeping> > __end_cap_;
} vector<UWBSessionInterruptionBookkeeping, std::__1::allocator<UWBSessionInterruptionBookkeeping> >;
typedef struct _cxx_atomic_impl<bool, std::__1::__cxx_atomic_base_impl<bool> > {
AB __a_value;
} cxx_atomic_impl<bool, std::__1::__cxx_atomic_base_impl<bool> >;
typedef struct atomic<bool> {
cxx_atomic_impl<bool, std::__1::__cxx_atomic_base_impl<bool> > __a_;
} atomic<bool>;
typedef struct _NSZone* NSZoneRef;
typedef struct {
vector;
} SCD_Struct_NI7;
typedef struct {
unsigned field1[8];
} SCD_Struct_NI8;
| 39.543478 | 130 | 0.751512 | [
"vector"
] |
bdc345f93e291ec7eccef9563bade1e46914ceee | 4,556 | h | C | bcos-scheduler/tests/mock/MockExecutor.h | xueying4402/FISCO-BCOS | 737e08752e8904c7c24e3737f8f46bf5327ef792 | [
"Apache-2.0"
] | 1 | 2022-03-06T10:46:12.000Z | 2022-03-06T10:46:12.000Z | bcos-scheduler/tests/mock/MockExecutor.h | xueying4402/FISCO-BCOS | 737e08752e8904c7c24e3737f8f46bf5327ef792 | [
"Apache-2.0"
] | null | null | null | bcos-scheduler/tests/mock/MockExecutor.h | xueying4402/FISCO-BCOS | 737e08752e8904c7c24e3737f8f46bf5327ef792 | [
"Apache-2.0"
] | null | null | null | #pragma once
#include "Common.h"
#include "bcos-framework/interfaces/executor/ExecutionMessage.h"
#include "bcos-framework/interfaces/executor/ParallelTransactionExecutorInterface.h"
#include "bcos-framework/interfaces/protocol/ProtocolTypeDef.h"
#include <boost/core/ignore_unused.hpp>
#include <boost/test/unit_test.hpp>
namespace bcos::test
{
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-parameter"
class MockParallelExecutor : public bcos::executor::ParallelTransactionExecutorInterface
{
public:
MockParallelExecutor(const std::string& name) : m_name(name) {}
~MockParallelExecutor() override {}
const std::string& name() const { return m_name; }
void nextBlockHeader(const bcos::protocol::BlockHeader::ConstPtr& blockHeader,
std::function<void(bcos::Error::UniquePtr)> callback) override
{
SCHEDULER_LOG(TRACE) << "Receiving nextBlock: " << blockHeader->number();
m_blockNumber = blockHeader->number();
callback(nullptr); // always success
}
void executeTransaction(bcos::protocol::ExecutionMessage::UniquePtr input,
std::function<void(bcos::Error::UniquePtr, bcos::protocol::ExecutionMessage::UniquePtr)>
callback) override
{
if (input->transactionHash() == h256(10086))
{
callback(BCOS_ERROR_UNIQUE_PTR(-1, "i am an error!!!!"), nullptr);
return;
}
// Always success
BOOST_CHECK(input);
if (input->type() == bcos::protocol::ExecutionMessage::TXHASH)
{
BOOST_CHECK_NE(input->transactionHash(), bcos::crypto::HashType());
}
input->setStatus(0);
input->setMessage("");
std::string data = "Hello world!";
input->setData(bcos::bytes(data.begin(), data.end()));
input->setType(bcos::protocol::ExecutionMessage::FINISHED);
callback(nullptr, std::move(input));
}
void dagExecuteTransactions(gsl::span<bcos::protocol::ExecutionMessage::UniquePtr> inputs,
std::function<void(
bcos::Error::UniquePtr, std::vector<bcos::protocol::ExecutionMessage::UniquePtr>)>
callback) override
{
BOOST_CHECK_EQUAL(inputs.size(), 100);
std::vector<bcos::protocol::ExecutionMessage::UniquePtr> messages(inputs.size());
for (decltype(inputs)::index_type i = 0; i < inputs.size(); ++i)
{
auto [it, inserted] = m_dagHashes.emplace(inputs[i]->transactionHash());
boost::ignore_unused(it);
BOOST_TEST(inserted);
// SCHEDULER_LOG(TRACE) << "Executing: " << inputs[i].get();
BOOST_TEST(inputs[i].get());
BOOST_CHECK_EQUAL(inputs[i]->type(), protocol::ExecutionMessage::TXHASH);
messages.at(i) = std::move(inputs[i]);
if (i < 50)
{
messages[i]->setType(protocol::ExecutionMessage::SEND_BACK);
}
else
{
messages[i]->setType(protocol::ExecutionMessage::FINISHED);
std::string result = "OK!";
messages[i]->setData(bcos::bytes(result.begin(), result.end()));
}
}
callback(nullptr, std::move(messages));
}
void call(bcos::protocol::ExecutionMessage::UniquePtr input,
std::function<void(bcos::Error::UniquePtr, bcos::protocol::ExecutionMessage::UniquePtr)>
callback) override
{}
void getHash(bcos::protocol::BlockNumber number,
std::function<void(bcos::Error::UniquePtr, crypto::HashType)> callback) override
{
callback(nullptr, h256(12345));
}
void prepare(const TwoPCParams& params, std::function<void(bcos::Error::Ptr)> callback) override
{
callback(nullptr);
}
void commit(const TwoPCParams& params, std::function<void(bcos::Error::Ptr)> callback) override
{
callback(nullptr);
}
void rollback(
const TwoPCParams& params, std::function<void(bcos::Error::Ptr)> callback) override
{
callback(nullptr);
}
void getCode(std::string_view contract,
std::function<void(bcos::Error::Ptr, bcos::bytes)> callback) override
{
callback(nullptr, {});
}
void reset(std::function<void(bcos::Error::Ptr)> callback) override {}
void clear() { m_dagHashes.clear(); }
std::string m_name;
bcos::protocol::BlockNumber m_blockNumber = 0;
std::set<bcos::crypto::HashType> m_dagHashes;
};
#pragma GCC diagnostic pop
} // namespace bcos::test
| 34 | 100 | 0.630378 | [
"vector"
] |
bdc7936d942869e0f992ea7691ef7261ac2219fe | 2,576 | h | C | SmartDeviceLink/public/SDLGetFile.h | codelynx/sdl_ios | 90317e17d408426547b4afed91620bc695a3279c | [
"BSD-3-Clause"
] | 171 | 2015-01-13T14:17:29.000Z | 2022-03-18T19:55:24.000Z | SmartDeviceLink/public/SDLGetFile.h | codelynx/sdl_ios | 90317e17d408426547b4afed91620bc695a3279c | [
"BSD-3-Clause"
] | 1,524 | 2015-01-16T14:31:10.000Z | 2022-03-30T14:37:02.000Z | SmartDeviceLink/public/SDLGetFile.h | codelynx/sdl_ios | 90317e17d408426547b4afed91620bc695a3279c | [
"BSD-3-Clause"
] | 129 | 2015-01-15T19:27:18.000Z | 2021-11-26T01:49:12.000Z | //
// SDLGetFile.h
// SmartDeviceLink
//
// Created by Nicole on 2/7/19.
// Copyright © 2019 smartdevicelink. All rights reserved.
//
#import "SDLRPCRequest.h"
#import "SDLFileType.h"
NS_ASSUME_NONNULL_BEGIN
/**
* This request is sent to the module to retrieve a file.
*/
@interface SDLGetFile : SDLRPCRequest
/**
* Convenience init for required parameters.
*
* @param fileName File name that should be retrieved.
* @return A SDLGetFile object
*/
- (instancetype)initWithFileName:(NSString *)fileName;
/**
* Convenience init for sending a small file.
*
* @param fileName File name that should be retrieved.
* @param appServiceId ID of the service that should have uploaded the requested file
* @param fileType Selected file type
* @return A SDLGetFile object
*/
- (instancetype)initWithFileName:(NSString *)fileName appServiceId:(nullable NSString *)appServiceId fileType:(nullable SDLFileType)fileType;
/**
* Convenience init for sending a large file in multiple data chunks.
*
* @param fileName File name that should be retrieved.
* @param appServiceId ID of the service that should have uploaded the requested file
* @param fileType Selected file type
* @param offset Offset in bytes for resuming partial data chunks
* @param length Length in bytes for resuming partial data chunks
* @return A SDLGetFile object
*/
- (instancetype)initWithFileName:(NSString *)fileName appServiceId:(nullable NSString *)appServiceId fileType:(nullable SDLFileType)fileType offset:(UInt32)offset length:(UInt32)length;
/**
* File name that should be retrieved.
*
* String, Required, Max string length 255 chars
*/
@property (strong, nonatomic) NSString *fileName;
/**
* ID of the service that should have uploaded the requested file.
*
* String, Optional
*/
@property (nullable, strong, nonatomic) NSString *appServiceId;
/**
* Selected file type.
*
* SDLFileType, Optional
*/
@property (nullable, strong, nonatomic) SDLFileType fileType;
/**
* Optional offset in bytes for resuming partial data chunks.
*
* Integer, Optional, minvalue="0" maxvalue="2000000000"
*/
@property (nullable, strong, nonatomic) NSNumber<SDLUInt> *offset;
/**
* Optional length in bytes for resuming partial data chunks. If offset is set to 0, then length is the total length of the file to be downloaded.
*
* Integer, Optional, minvalue="0" maxvalue="2000000000"
*/
@property (nullable, strong, nonatomic) NSNumber<SDLUInt> *length;
@end
NS_ASSUME_NONNULL_END
| 29.609195 | 185 | 0.71778 | [
"object"
] |
bdd42a9c9df4118446a8fd30b241c3ac55ab5039 | 2,164 | h | C | core/src/function_space/09_function_space_find_position_base_composite.h | maierbn/opendihu | 577650e2f6b36a7306766b0f4176f8124458cbf0 | [
"MIT"
] | 17 | 2018-11-25T19:29:34.000Z | 2021-09-20T04:46:22.000Z | core/src/function_space/09_function_space_find_position_base_composite.h | maierbn/opendihu | 577650e2f6b36a7306766b0f4176f8124458cbf0 | [
"MIT"
] | 1 | 2020-11-12T15:15:58.000Z | 2020-12-29T15:29:24.000Z | core/src/function_space/09_function_space_find_position_base_composite.h | maierbn/opendihu | 577650e2f6b36a7306766b0f4176f8124458cbf0 | [
"MIT"
] | 4 | 2018-10-17T12:18:10.000Z | 2021-05-28T13:24:20.000Z | #pragma once
#include <Python.h> // has to be the first included header
#include "function_space/08_function_space_nodes.h"
namespace FunctionSpace
{
//! forward declaration for field variables
template<typename MeshType,typename BasisFunctionType>
class FunctionSpace;
/** partial specialization for composite mesh
*/
template<int D,typename BasisFunctionType>
class FunctionSpaceStructuredFindPositionBase<Mesh::CompositeOfDimension<D>,BasisFunctionType> :
public FunctionSpaceNodes<Mesh::CompositeOfDimension<D>,BasisFunctionType>
{
public:
typedef Mesh::CompositeOfDimension<D> MeshType;
//! inherit constructor
using FunctionSpaceNodes<MeshType,BasisFunctionType>::FunctionSpaceNodes;
//! store a ghost mesh which is a neighouring mesh with only one layer of elements, this will be used by pointIsInElement and findPosition
void setGhostMesh(Mesh::face_t face, const std::shared_ptr<FunctionSpace<MeshType,BasisFunctionType>> ghostMesh){}
//! get the element no and the xi value of the point, return true if the point is inside the mesh or false otherwise. Start search at given elementNo
//! ghostMeshNo: -1 means main mesh, 0-5 means ghost Mesh with respective Mesh::face_t
bool findPosition(Vec3 point, element_no_t &elementNo, int &ghostMeshNo, std::array<double,MeshType::dim()> &xi, bool startSearchInCurrentElement, double &residual, bool &searchedAllElements, double xiTolerance = 1e-4);
//! check if the point lies inside the element, if yes, return true and set xi to the value of the point, defined in 11_function_space_xi.h
virtual bool pointIsInElement(Vec3 point, element_no_t elementNo, std::array<double,MeshType::dim()> &xi, double &residual, double xiTolerance) = 0;
//! print via VLOG(1) << which ghostMesh_ variables are set
void debugOutputGhostMeshSet(){}
//! return the sub mesh no. where the last point was found by findPosition
int subMeshNoWherePointWasFound();
protected:
int subMeshNoWherePointWasFound_ = 0; //< findPositions sets this to the subMeshNo in which the point was found
};
} // namespace
#include "function_space/09_function_space_find_position_base_composite.tpp"
| 43.28 | 221 | 0.78512 | [
"mesh"
] |
bddc8610fa7b826b70f6c14dc5b2ad88a5a35ae0 | 624 | h | C | Engine/Source/Editor/Persona/Private/EditorObjectsTracker.h | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | Engine/Source/Editor/Persona/Private/EditorObjectsTracker.h | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | 2 | 2015-06-21T17:38:11.000Z | 2015-06-22T20:54:42.000Z | Engine/Source/Editor/Persona/Private/EditorObjectsTracker.h | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#pragma once
//////////////////////////////////////////////////////////////////////////
// FEditorObjectTracker
class FEditorObjectTracker : public FGCObject
{
public:
// FGCObject interface
void AddReferencedObjects( FReferenceCollector& Collector ) override;
// End of FGCObject interface
/** Returns an existing editor object for the specified class or creates one
if none exist */
UObject* GetEditorObjectForClass( UClass* EdClass );
private:
/** Tracks editor objects created for details panel */
TMap< UClass*, UObject* > EditorObjMap;
}; | 26 | 77 | 0.665064 | [
"object"
] |
bddc9acd8b1bd444434096630511196e8edab514 | 7,274 | h | C | src/Magnum/Math/Half.h | Graphics-Physics-Libraries/magnum-games-and-data-visualization | a817f55d6ff0ef0510d93b310c2ba897e4de49ee | [
"MIT"
] | null | null | null | src/Magnum/Math/Half.h | Graphics-Physics-Libraries/magnum-games-and-data-visualization | a817f55d6ff0ef0510d93b310c2ba897e4de49ee | [
"MIT"
] | null | null | null | src/Magnum/Math/Half.h | Graphics-Physics-Libraries/magnum-games-and-data-visualization | a817f55d6ff0ef0510d93b310c2ba897e4de49ee | [
"MIT"
] | 1 | 2020-03-06T08:40:45.000Z | 2020-03-06T08:40:45.000Z | #ifndef Magnum_Math_Half_h
#define Magnum_Math_Half_h
/*
This file is part of Magnum.
Copyright © 2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019
Vladimír Vondruš <mosra@centrum.cz>
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 Class @ref Magnum::Math::Half, literal @link Magnum::Math::Literals::operator""_h() @endlink
*/
#include <utility>
#include <Corrade/Utility/Utility.h>
#include "Magnum/visibility.h"
#include "Magnum/Math/Math.h"
#include "Magnum/Math/Tags.h"
namespace Magnum { namespace Math {
#ifndef DOXYGEN_GENERATING_OUTPUT
/* So we don't need to drag in the whole Packing.h */
MAGNUM_EXPORT UnsignedShort packHalf(Float value);
MAGNUM_EXPORT Float unpackHalf(UnsignedShort value);
#endif
/**
@brief Half-precision float literal
The purpose of this class is just to make specifying and printing of half-float
literals easier. By design no arithmetic operations are supported, as majority
of CPUs has no dedicated instructions for half-precision floats and thus it is
faster to just use regular single-precision @ref Magnum::Float "Float". See
[Wikipedia](https://en.wikipedia.org/wiki/Half-precision_floating-point_format)
for more information about half floats.
The class provides explicit conversion from and to @ref Magnum::Float "Float",
equality comparison with correct treatment of NaN values, promotion and
negation operator, an @link Literals::operator""_h() operator""_h() @endlink
literal and an @ref operator<<(Debug&, Half) debug operator. Internally the class uses
@ref packHalf() and @ref unpackHalf(). Example usage:
@snippet MagnumMath.cpp Half-usage
Note that it is also possible to use this type inside @ref Vector classes,
though, again, only for passing data around and converting them, without any
arithmetic operations:
@snippet MagnumMath.cpp Half-usage-vector
@see @ref Magnum::Half
*/
class Half {
public:
/**
* @brief Default constructor
*
* Equivalent to @ref Half(ZeroInitT).
*/
constexpr /*implicit*/ Half() noexcept: _data{} {}
/** @brief Construct a zero value */
constexpr explicit Half(ZeroInitT) noexcept: _data{} {}
/** @brief Construct a half value from underlying 16-bit representation */
constexpr explicit Half(UnsignedShort data) noexcept: _data{data} {}
/**
* @brief Construct a half value from a 32-bit float representation
*
* @see @ref packHalf()
*/
explicit Half(Float value) noexcept: _data{packHalf(value)} {}
/**
* @brief Construct a half value from a 64-bit float representation
*
* Present only to aid generic code so e.g. @cpp T(1.0) @ce works
* without being ambigous.
* @see @ref packHalf()
*/
explicit Half(Double value) noexcept: _data{packHalf(Float(value))} {}
/** @brief Construct without initializing the contents */
explicit Half(NoInitT) noexcept {}
/**
* @brief Equality comparison
*
* Returns `false` if one of the values is half-float representation of
* NaN, otherwise does bitwise comparison.
*/
constexpr bool operator==(Half other) const {
return ((( _data & 0x7c00) == 0x7c00 && ( _data & 0x03ff)) ||
((other._data & 0x7c00) == 0x7c00 && (other._data & 0x03ff))) ?
false : _data == other._data;
}
/**
* @brief Non-equality comparison
*
* Simply negates the result of @ref operator==().
*/
constexpr bool operator!=(Half other) const {
return !operator==(other);
}
/**
* @brief Promotion
*
* Returns the value as-is.
*/
constexpr Half operator+() const { return *this; }
/** @brief Negation */
constexpr Half operator-() const {
return Half{UnsignedShort(_data ^ (1 << 15))};
}
/**
* @brief Conversion to underlying representation
*
* @see @ref data()
*/
constexpr explicit operator UnsignedShort() const { return _data; }
/**
* @brief Conversion to 32-bit float representation
*
* @see @ref unpackHalf()
*/
explicit operator Float() const { return unpackHalf(_data); }
/**
* @brief Underlying representation
*
* @see @ref operator UnsignedShort()
*/
constexpr UnsignedShort data() const { return _data; }
private:
UnsignedShort _data;
};
namespace Literals {
/** @relatesalso Magnum::Math::Half
@brief Half-float literal
See @ref Half for more information.
*/
inline Half operator "" _h(long double value) { return Half(Float(value)); }
}
#ifndef CORRADE_NO_DEBUG
/**
@debugoperator{Half}
Prints the value with 4 significant digits.
@see @ref Corrade::Utility::Debug::operator<<(float),
@ref Corrade::Utility::Debug::operator<<(double),
@ref Corrade::Utility::Debug::operator<<(long double value)
@todoc remove `long double value` once doxygen can link to long double overloads properly
*/
MAGNUM_EXPORT Corrade::Utility::Debug& operator<<(Corrade::Utility::Debug& debug, Half value);
#endif
namespace Implementation {
template<> struct StrictWeakOrdering<Half> {
bool operator()(Half a, Half b) const {
/* Not mathematically equivalent to <, but does order */
return a.data() < b.data();
}
};
}
}}
#if !defined(CORRADE_NO_TWEAKABLE) && (defined(DOXYGEN_GENERATING_OUTPUT) || defined(CORRADE_TARGET_UNIX) || (defined(CORRADE_TARGET_WINDOWS) && !defined(CORRADE_TARGET_WINDOWS_RT)) || defined(CORRADE_TARGET_EMSCRIPTEN))
namespace Corrade { namespace Utility {
/**
@tweakableliteral{Magnum::Math::Half}
Parses the @link Magnum::Math::Literals::operator""_h @endlink literal.
*/
template<> struct MAGNUM_EXPORT TweakableParser<Magnum::Math::Half> {
TweakableParser() = delete;
/** @brief Parse the value */
static std::pair<TweakableState, Magnum::Math::Half> parse(Containers::ArrayView<const char> value);
};
}}
#endif
#endif
| 32.914027 | 220 | 0.664284 | [
"vector"
] |
bdddcf50f4f71553c3d8c55e0f5529cb91fae169 | 481 | h | C | idlesse/Classes/MeMessage/ZPMeRequestManager.h | fakepinge/idlesse | 9d021f0995f9c508db65f5c7c0fc42ee55dea6a7 | [
"MIT"
] | 2 | 2018-05-21T02:02:03.000Z | 2018-10-18T09:14:32.000Z | idlesse/Classes/MeMessage/ZPMeRequestManager.h | fakepinge/idlesse | 9d021f0995f9c508db65f5c7c0fc42ee55dea6a7 | [
"MIT"
] | null | null | null | idlesse/Classes/MeMessage/ZPMeRequestManager.h | fakepinge/idlesse | 9d021f0995f9c508db65f5c7c0fc42ee55dea6a7 | [
"MIT"
] | null | null | null | //
// ZPMeRequestManager.h
// idlesse
//
// Created by 胡知平 on 16/6/7.
// Copyright © 2016年 fakepinge. All rights reserved.
//
#import <Foundation/Foundation.h>
@class ZPUserModel;
@interface ZPMeRequestManager : NSObject
+ (instancetype) manager;
- (void) requestUserId:(NSString *)userId complete:(void(^)(ZPUserModel *model, BOOL isSuccess)) complete;
- (void) requestLogincomplete:(void(^)(NSString *token ,BOOL isSuccess))complete;
- (void) cancelAllRequest;
@end
| 19.24 | 106 | 0.719335 | [
"model"
] |
bde4eec1e7d1d2067530c22c4c7ea8e148976473 | 1,709 | h | C | platform/OSP/Web/include/Poco/OSP/Web/WebRequestHandlerFactory.h | gboyraz/macchina.io | 3e26fea95e87512459693831242b297f0780cc21 | [
"Apache-2.0"
] | 2 | 2020-11-23T23:37:00.000Z | 2020-12-22T04:02:41.000Z | platform/OSP/Web/include/Poco/OSP/Web/WebRequestHandlerFactory.h | bas524/cmake.macchina.io | 22a21d78f8075fd145b788b41a23603591e91c9f | [
"Apache-2.0"
] | null | null | null | platform/OSP/Web/include/Poco/OSP/Web/WebRequestHandlerFactory.h | bas524/cmake.macchina.io | 22a21d78f8075fd145b788b41a23603591e91c9f | [
"Apache-2.0"
] | 1 | 2020-11-23T23:37:09.000Z | 2020-11-23T23:37:09.000Z | //
// WebRequestHandlerFactory.h
//
// Library: OSP/Web
// Package: Web
// Module: WebRequestHandlerFactory
//
// Definition of the WebRequestHandlerFactory class.
//
// Copyright (c) 2007-2014, Applied Informatics Software Engineering GmbH.
// All rights reserved.
//
// SPDX-License-Identifier: Apache-2.0
//
#ifndef OSP_Web_WebRequestHandlerFactory_INCLUDED
#define OSP_Web_WebRequestHandlerFactory_INCLUDED
#include "Poco/OSP/Web/Web.h"
#include "Poco/Net/HTTPRequestHandlerFactory.h"
#include "Poco/OSP/BundleContext.h"
namespace Poco {
namespace OSP {
namespace Web {
class OSPWeb_API WebRequestHandlerFactory: public Poco::Net::HTTPRequestHandlerFactory
/// WebRequestHandlerFactory is a HTTPRequestHandlerFactory that was extended
/// to allow RequestHandlers easy access to the SessionManager and the owner's BundleContext.
{
public:
WebRequestHandlerFactory();
/// Creates the unintialized WebRequestHandlerFactory. The default constructor is called
/// by the classloader (which requires a default constructor) followed by a call to init.
~WebRequestHandlerFactory();
/// Destroys the WebRequestHandlerFactory.
void init(BundleContext::Ptr pContext);
/// Initializes the object with the given BundleContext.
protected:
BundleContext::Ptr context() const;
/// Returns the context. The pointer is guaranteed to be valid.
virtual void initImpl();
/// Add extra initialization code by overriding this method in your subclass.
private:
BundleContext::Ptr _pContext;
};
//
// inlines
//
inline BundleContext::Ptr WebRequestHandlerFactory::context() const
{
return _pContext;
}
} } } // namespace Poco::OSP::Web
#endif // OSP_Web_WebRequestHandlerFactory_INCLUDED
| 24.070423 | 94 | 0.772382 | [
"object"
] |
bdfdc916d449075e76b35c3b4f72b20ff27cbea4 | 1,340 | h | C | src/Macha/AssetRegistry.h | TableauBits/Morrigu | 5ff177609468a9adf4897290756a0d31e4852ad8 | [
"MIT"
] | 1 | 2022-03-25T03:59:23.000Z | 2022-03-25T03:59:23.000Z | src/Macha/AssetRegistry.h | TableauBits/Morrigu | 5ff177609468a9adf4897290756a0d31e4852ad8 | [
"MIT"
] | null | null | null | src/Macha/AssetRegistry.h | TableauBits/Morrigu | 5ff177609468a9adf4897290756a0d31e4852ad8 | [
"MIT"
] | null | null | null | //
// Created by Mathis Lamidey on 2021-12-23.
//
#ifndef ASSET_REGISTRY_H
#define ASSET_REGISTRY_H
#include <Morrigu.h>
#include <optional>
#include <unordered_map>
class AssetRegistry
{
public:
// When using the add functions, if a value with the same name is already present, it will be overwritten
void addTexture(MRG::Ref<MRG::Texture> newTexture);
void addTexture(const std::string& name, MRG::Ref<MRG::Texture> texture);
void addMesh(const std::string& name, MRG::Ref<MRG::Mesh<MRG::TexturedVertex>> mesh);
void addMaterial(const std::string& name, MRG::Ref<MRG::Material<MRG::TexturedVertex>> material);
void removeTexture(const std::string& name);
void removeMesh(const std::string& name);
void removeMaterial(const std::string& name);
[[nodiscard]] std::optional<MRG::Ref<MRG::Texture>> getTexture(const std::string& name);
[[nodiscard]] std::optional<MRG::Ref<MRG::Mesh<MRG::TexturedVertex>>> getMesh(const std::string& name);
[[nodiscard]] std::optional<MRG::Ref<MRG::Material<MRG::TexturedVertex>>> getMaterial(const std::string& name);
private:
std::unordered_map<std::string, MRG::Ref<MRG::Texture>> m_textures{};
std::unordered_map<std::string, MRG::Ref<MRG::Mesh<MRG::TexturedVertex>>> m_meshes{};
std::unordered_map<std::string, MRG::Ref<MRG::Material<MRG::TexturedVertex>>> m_materials{};
};
#endif
| 36.216216 | 112 | 0.735821 | [
"mesh"
] |
da003aa6e8d07a553f8c1eb4bb56c172ada4bf3a | 983 | h | C | ui-dialogs-run.h | lahol/dvb-recorder | f005084bc2b7195bcdf67cbdccd9e652c556a429 | [
"MIT"
] | 1 | 2020-07-29T10:20:35.000Z | 2020-07-29T10:20:35.000Z | ui-dialogs-run.h | lahol/dvb-recorder | f005084bc2b7195bcdf67cbdccd9e652c556a429 | [
"MIT"
] | null | null | null | ui-dialogs-run.h | lahol/dvb-recorder | f005084bc2b7195bcdf67cbdccd9e652c556a429 | [
"MIT"
] | null | null | null | #pragma once
#include <glib-object.h>
#include <gtk/gtk.h>
#include <dvbrecorder/dvbrecorder.h>
#include "video-output.h"
#include "ui-dialog-scan.h"
#include "favourites-dialog.h"
#include "ui-recorder-settings-dialog.h"
#include "video-settings-dialog.h"
#include "ui-channel-properties-dialog.h"
#include "ui-add-scheduled-event-dialog.h"
#include "ui-scheduled-events-dialog.h"
GtkResponseType ui_dialog_scan_show(GtkWidget *parent, DVBRecorder *recorder);
void favourites_dialog_show(GtkWidget *parent, DVBRecorder *recorder, guint32 list_id,
CHANNEL_FAVOURITES_DIALOG_UPDATE_NOTIFY notify_cb, gpointer userdata);
void ui_recorder_settings_dialog_show(GtkWidget *parent, DVBRecorder *recorder);
void video_settings_dialog_show(GtkWidget *parent, VideoOutput *vo);
gboolean ui_add_scheduled_event_dialog_show(GtkWidget *parent, DVBRecorder *recorder, guint event_id);
void ui_scheduled_events_dialog_show(GtkWidget *parent, DVBRecorder *recorder);
| 42.73913 | 102 | 0.796541 | [
"object"
] |
da03f4cc535dbb2d8f82a783bb591b7a667ecfb3 | 2,196 | h | C | CGALWrapper/Meshing/ConformingTriangulation2_EEK.h | unitycoder/CGALDotNet | 90682724a55aec2818847500047d4785aa7e1d67 | [
"MIT"
] | null | null | null | CGALWrapper/Meshing/ConformingTriangulation2_EEK.h | unitycoder/CGALDotNet | 90682724a55aec2818847500047d4785aa7e1d67 | [
"MIT"
] | null | null | null | CGALWrapper/Meshing/ConformingTriangulation2_EEK.h | unitycoder/CGALDotNet | 90682724a55aec2818847500047d4785aa7e1d67 | [
"MIT"
] | null | null | null | #pragma once
#include "../CGALWrapper.h"
#include "../Geometry/Geometry2.h"
#include "ConformingTriangulation2.h"
extern "C"
{
CGALWRAPPER_API void* ConformingTriangulation2_EEK_Create();
CGALWRAPPER_API void ConformingTriangulation2_EEK_Release(void* ptr);
CGALWRAPPER_API void ConformingTriangulation2_EEK_Clear(void* ptr);
CGALWRAPPER_API void* ConformingTriangulation2_EEK_Copy(void* ptr);
CGALWRAPPER_API int ConformingTriangulation2_EEK_VertexCount(void* ptr);
CGALWRAPPER_API int ConformingTriangulation2_EEK_FaceCount(void* ptr);
CGALWRAPPER_API void ConformingTriangulation2_EEK_InsertPoint(void* ptr, Point2d point);
CGALWRAPPER_API void ConformingTriangulation2_EEK_InsertPoints(void* ptr, Point2d* points, int count);
CGALWRAPPER_API void ConformingTriangulation2_EEK_InsertPolygon(void* triPtr, void* polyPtr);
CGALWRAPPER_API void ConformingTriangulation2_EEK_InsertPolygonWithHoles(void* triPtr, void* pwhPtr);
CGALWRAPPER_API void ConformingTriangulation2_EEK_GetPoints(void* ptr, Point2d* points, int count);
CGALWRAPPER_API void ConformingTriangulation2_EEK_GetIndices(void* ptr, int* indices, int count);
CGALWRAPPER_API void ConformingTriangulation2_EEK_Transform(void* ptr, Point2d translation, double rotation, double scale);
CGALWRAPPER_API void ConformingTriangulation2_EEK_InsertSegmentConstraint(void* ptr, Point2d a, Point2d b);
CGALWRAPPER_API void ConformingTriangulation2_EEK_InsertSegmentConstraints(void* ptr, Segment2d* segments, int count);
CGALWRAPPER_API void ConformingTriangulation2_EEK_InsertPolygonConstraint(void* triPtr, void* polyPtr);
CGALWRAPPER_API void ConformingTriangulation2_EEK_InsertPolygonWithHolesConstraint(void* triPtr, void* pwhPtr);
CGALWRAPPER_API void ConformingTriangulation2_EEK_MakeDelaunay(void* ptr);
CGALWRAPPER_API void ConformingTriangulation2_EEK_MakeGabriel(void* ptr);
CGALWRAPPER_API void Conformingriangulation2_EEK_RefineAndOptimize(void* ptr, int iterations, double angleBounds, double lengthBounds);
CGALWRAPPER_API void ConformingTriangulation2_EEK_RefineAndOptimizeWithSeeds(void* ptr, int iterations, double angleBounds, double lengthBounds, Point2d* points, int count);
}
| 42.230769 | 174 | 0.84745 | [
"geometry"
] |
fffc4b53c8d866e1083dbbf685f2716e8cbcdd53 | 23,903 | h | C | src/dpct/dpl_extras/vector.h | abagusetty/Librett | 63e6b76f52309cd6e3da31ea8e57a81b27964c78 | [
"MIT"
] | null | null | null | src/dpct/dpl_extras/vector.h | abagusetty/Librett | 63e6b76f52309cd6e3da31ea8e57a81b27964c78 | [
"MIT"
] | null | null | null | src/dpct/dpl_extras/vector.h | abagusetty/Librett | 63e6b76f52309cd6e3da31ea8e57a81b27964c78 | [
"MIT"
] | null | null | null | //==---- vector.h ---------------------------------*- C++ -*----------------==//
//
// Copyright (C) 2019 - 2021 Intel Corporation
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
// See https://llvm.org/LICENSE.txt for license information.
//
//===----------------------------------------------------------------------===//
#ifndef __DPCT_VECTOR_H__
#define __DPCT_VECTOR_H__
#include <oneapi/dpl/algorithm>
#include <oneapi/dpl/execution>
#include <CL/sycl.hpp>
#include "memory.h"
#include <algorithm>
#include <iterator>
#include <vector>
#include "../device.hpp"
namespace dpct {
namespace sycl = cl::sycl;
namespace internal {
template <typename Iter, typename Void = void> // for non-iterators
struct is_iterator : std::false_type {};
template <typename Iter> // For iterators
struct is_iterator<
Iter,
typename std::enable_if<
!std::is_void<typename Iter::iterator_category>::value, void>::type>
: std::true_type {};
template <typename T> // For pointers
struct is_iterator<T *> : std::true_type {};
} // end namespace internal
#ifndef DPCT_USM_LEVEL_NONE
template <typename T,
typename Allocator = sycl::usm_allocator<T, sycl::usm::alloc::shared>>
class device_vector {
public:
using iterator = device_iterator<T>;
using const_iterator = const iterator;
using reference = device_reference<T>;
using const_reference = const reference;
using value_type = T;
using pointer = T *;
using const_pointer = const T *;
using difference_type =
typename std::iterator_traits<iterator>::difference_type;
using size_type = std::size_t;
private:
Allocator _alloc;
size_type _size;
size_type _capacity;
pointer _storage;
size_type _min_capacity() const { return size_type(1); }
public:
template <typename OtherA> operator const std::vector<T, OtherA>() & {
auto __tmp = std::vector<T, OtherA>(this->size());
std::copy(oneapi::dpl::execution::make_device_policy(get_default_queue()),
this->begin(), this->end(), __tmp.begin());
return __tmp;
}
device_vector()
: _alloc(get_default_queue()), _size(0), _capacity(_min_capacity()) {
_storage = _alloc.allocate(_capacity);
}
~device_vector() /*= default*/ { _alloc.deallocate(_storage, _capacity); };
explicit device_vector(size_type n) : _alloc(get_default_queue()), _size(n) {
_capacity = 2 * _size;
_storage = _alloc.allocate(_capacity);
}
explicit device_vector(size_type n, const T &value)
: _alloc(get_default_queue()), _size(n) {
_capacity = 2 * _size;
_storage = _alloc.allocate(_capacity);
std::fill(oneapi::dpl::execution::make_device_policy(get_default_queue()),
begin(), end(), T(value));
}
device_vector(const device_vector &other) : _alloc(get_default_queue()) {
_size = other.size();
_capacity = other.capacity();
_storage = _alloc.allocate(_capacity);
std::copy(oneapi::dpl::execution::make_device_policy(get_default_queue()),
other.begin(), other.end(), begin());
}
device_vector(device_vector &&other)
: _alloc(get_default_queue()), _size(other.size()),
_capacity(other.capacity()) {}
template <typename InputIterator>
device_vector(
InputIterator first,
typename std::enable_if<internal::is_iterator<InputIterator>::value &&
!std::is_pointer<InputIterator>::value,
InputIterator>::type last)
: _alloc(get_default_queue()) {
_size = std::distance(first, last);
_capacity = 2 * _size;
_storage = _alloc.allocate(_capacity);
std::copy(oneapi::dpl::execution::make_device_policy(get_default_queue()),
first, last, begin());
}
template <typename InputIterator>
device_vector(InputIterator first,
typename std::enable_if<std::is_pointer<InputIterator>::value,
InputIterator>::type last)
: _alloc(get_default_queue()) {
_size = std::distance(first, last);
_capacity = 2 * _size;
_storage = _alloc.allocate(_capacity);
auto ptr_type = sycl::get_pointer_type(first, get_default_context());
if (ptr_type != sycl::usm::alloc::host &&
ptr_type != sycl::usm::alloc::unknown) {
std::copy(oneapi::dpl::execution::make_device_policy(get_default_queue()),
first, last, begin());
} else {
sycl::buffer<T, 1> buf(first, last);
auto buf_first = oneapi::dpl::begin(buf);
auto buf_last = oneapi::dpl::end(buf);
std::copy(oneapi::dpl::execution::make_device_policy(get_default_queue()),
buf_first, buf_last, begin());
}
}
template <typename OtherAllocator>
device_vector(const device_vector<T, OtherAllocator> &v)
: _alloc(get_default_queue()), _storage(v.real_begin()), _size(v.size()),
_capacity(v.capacity()) {}
template <typename OtherAllocator>
device_vector(std::vector<T, OtherAllocator> &v)
: _alloc(get_default_queue()), _size(v.size()) {
_capacity = 2 * _size;
_storage = _alloc.allocate(_capacity);
std::copy(oneapi::dpl::execution::make_device_policy(get_default_queue()),
v.begin(), v.end(), this->begin());
}
template <typename OtherAllocator>
device_vector &operator=(const std::vector<T, OtherAllocator> &v) {
resize(v.size());
std::copy(oneapi::dpl::execution::make_device_policy(get_default_queue()),
v.begin(), v.end(), begin());
return *this;
}
device_vector &operator=(const device_vector &other) {
// Copy assignment operator:
resize(other.size());
std::copy(oneapi::dpl::execution::make_device_policy(get_default_queue()),
other.begin(), other.end(), begin());
return *this;
}
device_vector &operator=(device_vector &&other) {
// Move assignment operator:
this->_size = std::move(other._size);
this->_capacity = std::move(other._capacity);
this->_storage = std::move(other._storage);
return *this;
}
size_type size() const { return _size; }
iterator begin() noexcept { return device_iterator<T>(_storage, 0); }
iterator end() { return device_iterator<T>(_storage, size()); }
const_iterator begin() const noexcept {
return device_iterator<T>(_storage, 0);
}
const_iterator cbegin() const noexcept { return begin(); }
const_iterator end() const { return device_iterator<T>(_storage, size()); }
const_iterator cend() const { return end(); }
T *real_begin() { return _storage; }
const T *real_begin() const { return _storage; }
void swap(device_vector &v) {
auto temp = std::move(v._storage);
v._storage = std::move(this->_storage);
this->_storage = std::move(temp);
std::swap(_size, v._size);
std::swap(_capacity, v._capacity);
}
reference operator[](size_type n) { return _storage[n]; }
const_reference operator[](size_type n) const { return _storage[n]; }
void reserve(size_type n) {
if (n > capacity()) {
// allocate buffer for new size
auto tmp = _alloc.allocate(2 * n);
// copy content (old buffer to new buffer)
std::copy(oneapi::dpl::execution::make_device_policy(get_default_queue()),
begin(), end(), tmp);
// deallocate old memory
_alloc.deallocate(_storage, _capacity);
_storage = tmp;
_capacity = 2 * n;
}
}
void resize(size_type new_size, const T &x = T()) {
reserve(new_size);
_size = new_size;
}
size_type max_size(void) const {
return std::numeric_limits<size_type>::max() / sizeof(T);
}
size_type capacity() const { return _capacity; }
const_reference front() const { return *begin(); }
reference front() { return *begin(); }
const_reference back(void) const { return *(end() - 1); }
reference back(void) { return *(end() - 1); }
pointer data(void) { return _storage; }
const_pointer data(void) const { return _storage; }
void shrink_to_fit(void) {
if (_size != capacity()) {
auto tmp = _alloc.allocate(_size);
std::copy(oneapi::dpl::execution::make_device_policy(get_default_queue()),
begin(), end(), tmp);
_alloc.deallocate(_storage, _capacity);
_storage = tmp;
_capacity = _size;
}
}
void assign(size_type n, const T &x) {
resize(n);
std::fill(oneapi::dpl::execution::make_device_policy(get_default_queue()),
begin(), begin() + n, x);
}
template <typename InputIterator>
void
assign(InputIterator first,
typename std::enable_if<internal::is_iterator<InputIterator>::value,
InputIterator>::type last) {
auto n = std::distance(first, last);
resize(n);
std::copy(oneapi::dpl::execution::make_device_policy(get_default_queue()),
first, last, begin());
}
void clear(void) { _size = 0; }
bool empty(void) const { return (size() == 0); }
void push_back(const T &x) { insert(end(), size_type(1), x); }
void pop_back(void) {
if (_size > 0)
--_size;
}
iterator erase(iterator first, iterator last) {
auto n = std::distance(first, last);
if (last == end()) {
_size = _size - n;
return end();
}
auto m = std::distance(last, end());
auto tmp = _alloc.allocate(m);
// copy remainder to temporary buffer.
std::copy(oneapi::dpl::execution::make_device_policy(get_default_queue()),
last, end(), tmp);
// override (erase) subsequence in storage.
std::copy(oneapi::dpl::execution::make_device_policy(get_default_queue()),
tmp, tmp + m, first);
_alloc.deallocate(tmp, m);
_size -= n;
return begin() + first.get_idx() + n;
}
iterator erase(iterator pos) { return erase(pos, pos + 1); }
iterator insert(iterator position, const T &x) {
auto n = std::distance(begin(), position);
insert(position, size_type(1), x);
return begin() + n;
}
void insert(iterator position, size_type n, const T &x) {
if (position == end()) {
resize(size() + n);
std::fill(oneapi::dpl::execution::make_device_policy(get_default_queue()),
end() - n, end(), x);
} else {
auto i_n = std::distance(begin(), position);
// allocate temporary storage
auto m = std::distance(position, end());
auto tmp = _alloc.allocate(m);
// copy remainder
std::copy(oneapi::dpl::execution::make_device_policy(get_default_queue()),
position, end(), tmp);
resize(size() + n);
// resizing might invalidate position
position = begin() + position.get_idx();
std::fill(oneapi::dpl::execution::make_device_policy(get_default_queue()),
position, position + n, x);
std::copy(oneapi::dpl::execution::make_device_policy(get_default_queue()),
tmp, tmp + m, position + n);
_alloc.deallocate(tmp, m);
}
}
template <typename InputIterator>
void
insert(iterator position, InputIterator first,
typename std::enable_if<internal::is_iterator<InputIterator>::value,
InputIterator>::type last) {
auto n = std::distance(first, last);
if (position == end()) {
resize(size() + n);
std::copy(oneapi::dpl::execution::make_device_policy(get_default_queue()),
first, last, end());
} else {
auto m = std::distance(position, end());
auto tmp = _alloc.allocate(m);
std::copy(oneapi::dpl::execution::make_device_policy(get_default_queue()),
position, end(), tmp);
resize(size() + n);
// resizing might invalidate position
position = begin() + position.get_idx();
std::copy(oneapi::dpl::execution::make_device_policy(get_default_queue()),
first, last, position);
std::copy(oneapi::dpl::execution::make_device_policy(get_default_queue()),
tmp, tmp + m, position + n);
_alloc.deallocate(tmp, m);
}
}
Allocator get_allocator() const { return _alloc; }
};
#else
template <typename T, typename Allocator = cl::sycl::buffer_allocator>
class device_vector {
static_assert(
std::is_same<Allocator, cl::sycl::buffer_allocator>::value,
"device_vector doesn't support custom allocator when USM is not used.");
public:
using iterator = device_iterator<T>;
using const_iterator = const iterator;
using reference = device_reference<T>;
using const_reference = const reference;
using value_type = T;
using pointer = T *;
using const_pointer = const T *;
using difference_type =
typename std::iterator_traits<iterator>::difference_type;
using size_type = std::size_t;
private:
using Buffer = sycl::buffer<T, 1>;
using Range = sycl::range<1>;
// Using mem_mgr to handle memory allocation
void *_storage;
size_type _size;
size_type _min_capacity() const { return size_type(1); }
void *alloc_store(size_type num_bytes) {
return detail::mem_mgr::instance().mem_alloc(num_bytes);
}
public:
template <typename OtherA> operator const std::vector<T, OtherA>() & {
auto __tmp = std::vector<T, OtherA>(this->size());
std::copy(oneapi::dpl::execution::dpcpp_default, this->begin(), this->end(),
__tmp.begin());
return __tmp;
}
device_vector()
: _storage(alloc_store(_min_capacity() * sizeof(T))), _size(0) {}
~device_vector() = default;
explicit device_vector(size_type n)
: _storage(alloc_store(std::max(n, _min_capacity()) * sizeof(T))),
_size(n) {}
explicit device_vector(size_type n, const T &value)
: _storage(alloc_store(std::max(n, _min_capacity()) * sizeof(T))),
_size(n) {
auto buf = get_buffer();
std::fill(oneapi::dpl::execution::dpcpp_default, oneapi::dpl::begin(buf),
oneapi::dpl::begin(buf) + n, T(value));
}
device_vector(const device_vector &other)
: _storage(other._storage), _size(other.size()) {}
device_vector(device_vector &&other)
: _storage(std::move(other._storage)), _size(other.size()) {}
template <typename InputIterator>
device_vector(
InputIterator first,
typename std::enable_if<internal::is_iterator<InputIterator>::value,
InputIterator>::type last)
: _storage(alloc_store(std::distance(first, last) * sizeof(T))),
_size(std::distance(first, last)) {
auto buf = get_buffer();
auto dst = oneapi::dpl::begin(buf);
std::copy(oneapi::dpl::execution::make_device_policy(get_default_queue()),
first, last, dst);
}
template <typename OtherAllocator>
device_vector(const device_vector<T, OtherAllocator> &v)
: _storage(alloc_store(v.size() * sizeof(T))), _size(v.size()) {
auto buf = get_buffer();
auto dst = oneapi::dpl::begin(buf);
std::copy(oneapi::dpl::execution::make_device_policy(get_default_queue()),
v.real_begin(), v.real_begin() + v.size(), dst);
}
template <typename OtherAllocator>
device_vector(std::vector<T, OtherAllocator> &v)
: _storage(alloc_store(v.size() * sizeof(T))), _size(v.size()) {
std::copy(oneapi::dpl::execution::dpcpp_default, v.begin(), v.end(),
oneapi::dpl::begin(get_buffer()));
}
device_vector &operator=(const device_vector &other) {
// Copy assignment operator:
_size = other.size();
void *tmp = alloc_store(_size * sizeof(T));
auto tmp_buf =
detail::mem_mgr::instance()
.translate_ptr(tmp)
.buffer.template reinterpret<T, 1>(sycl::range<1>(_size));
std::copy(oneapi::dpl::execution::dpcpp_default,
oneapi::dpl::begin(other.get_buffer()),
oneapi::dpl::end(other.get_buffer()),
oneapi::dpl::begin(tmp_buf));
detail::mem_mgr::instance().mem_free(_storage);
_storage = tmp;
return *this;
}
device_vector &operator=(device_vector &&other) {
// Move assignment operator:
_size = other.size();
this->_storage = std::move(other._storage);
return *this;
}
template <typename OtherAllocator>
device_vector &operator=(const std::vector<T, OtherAllocator> &v) {
Buffer data(v.begin(), v.end());
_size = v.size();
void *tmp = alloc_store(_size * sizeof(T));
auto tmp_buf =
detail::mem_mgr::instance()
.translate_ptr(tmp)
.buffer.template reinterpret<T, 1>(sycl::range<1>(_size));
std::copy(oneapi::dpl::execution::dpcpp_default, oneapi::dpl::begin(data),
oneapi::dpl::end(data), oneapi::dpl::begin(tmp_buf));
detail::mem_mgr::instance().mem_free(_storage);
_storage = tmp;
return *this;
}
Buffer get_buffer() const {
return detail::mem_mgr::instance()
.translate_ptr(_storage)
.buffer.template reinterpret<T, 1>(sycl::range<1>(capacity()));
}
size_type size() const { return _size; }
iterator begin() noexcept { return device_iterator<T>(get_buffer(), 0); }
iterator end() { return device_iterator<T>(get_buffer(), _size); }
const_iterator begin() const noexcept {
return device_iterator<T>(get_buffer(), 0);
}
const_iterator cbegin() const noexcept { return begin(); }
const_iterator end() const { return device_iterator<T>(get_buffer(), _size); }
const_iterator cend() const { return end(); }
T *real_begin() {
return (detail::mem_mgr::instance()
.translate_ptr(_storage)
.buffer.template get_access<sycl::access::mode::read_write>())
.get_pointer();
}
const T *real_begin() const {
return const_cast<device_vector *>(this)
->detail::mem_mgr::instance()
.translate_ptr(_storage)
.buffer.template get_access<sycl::access::mode::read_write>()
.get_pointer();
}
void swap(device_vector &v) {
void *temp = v._storage;
v._storage = this->_storage;
this->_storage = temp;
std::swap(_size, v._size);
}
reference operator[](size_type n) { return *(begin() + n); }
const_reference operator[](size_type n) const { return *(begin() + n); }
void reserve(size_type n) {
if (n > capacity()) {
// create new buffer (allocate for new size)
void *a = alloc_store(n * sizeof(T));
// copy content (old buffer to new buffer)
if (_storage != nullptr) {
auto tmp = detail::mem_mgr::instance()
.translate_ptr(a)
.buffer.template reinterpret<T, 1>(sycl::range<1>(n));
auto src_buf = get_buffer();
std::copy(oneapi::dpl::execution::dpcpp_default,
oneapi::dpl::begin(src_buf), oneapi::dpl::end(src_buf),
oneapi::dpl::begin(tmp));
// deallocate old memory
detail::mem_mgr::instance().mem_free(_storage);
}
_storage = a;
}
}
void resize(size_type new_size, const T &x = T()) {
reserve(new_size);
_size = new_size;
}
size_type max_size(void) const {
return std::numeric_limits<size_type>::max() / sizeof(T);
}
size_type capacity() const {
return _storage != nullptr ? detail::mem_mgr::instance()
.translate_ptr(_storage)
.buffer.get_count() /
sizeof(T)
: 0;
}
const_reference front() const { return *begin(); }
reference front() { return *begin(); }
const_reference back(void) const { return *(end() - 1); }
reference back(void) { return *(end() - 1); }
pointer data(void) {
return reinterpret_cast<pointer>(_storage);
}
const_pointer data(void) const {
return reinterpret_cast<const_pointer>(_storage);
}
void shrink_to_fit(void) {
if (_size != capacity()) {
void *a = alloc_store(_size * sizeof(T));
auto tmp = detail::mem_mgr::instance()
.translate_ptr(a)
.buffer.template reinterpret<T, 1>(sycl::range<1>(_size));
std::copy(oneapi::dpl::execution::dpcpp_default,
oneapi::dpl::begin(get_buffer()),
oneapi::dpl::end(get_buffer()), oneapi::dpl::begin(tmp));
detail::mem_mgr::instance().mem_free(_storage);
_storage = a;
}
}
void assign(size_type n, const T &x) {
resize(n);
std::fill(oneapi::dpl::execution::dpcpp_default, begin(), begin() + n, x);
}
template <typename InputIterator>
void
assign(InputIterator first,
typename std::enable_if<internal::is_iterator<InputIterator>::value,
InputIterator>::type last) {
auto n = std::distance(first, last);
resize(n);
if (internal::is_iterator<InputIterator>::value &&
!std::is_pointer<InputIterator>::value)
std::copy(oneapi::dpl::execution::dpcpp_default, first, last, begin());
else {
Buffer tmp(first, last);
std::copy(oneapi::dpl::execution::dpcpp_default, oneapi::dpl::begin(tmp),
oneapi::dpl::end(tmp), begin());
}
}
void clear(void) {
_size = 0;
detail::mem_mgr::instance().mem_free(_storage);
_storage = nullptr;
}
bool empty(void) const { return (size() == 0); }
void push_back(const T &x) { insert(end(), size_type(1), x); }
void pop_back(void) {
if (_size > 0)
--_size;
}
iterator erase(iterator first, iterator last) {
auto n = std::distance(first, last);
if (last == end()) {
_size = _size - n;
return end();
}
Buffer tmp{Range(std::distance(last, end()))};
// copy remainder to temporary buffer.
std::copy(oneapi::dpl::execution::dpcpp_default, last, end(),
oneapi::dpl::begin(tmp));
// override (erase) subsequence in storage.
std::copy(oneapi::dpl::execution::dpcpp_default, oneapi::dpl::begin(tmp),
oneapi::dpl::end(tmp), first);
resize(_size - n);
return begin() + first.get_idx() + n;
}
iterator erase(iterator pos) { return erase(pos, pos + 1); }
iterator insert(iterator position, const T &x) {
auto n = std::distance(begin(), position);
insert(position, size_type(1), x);
return begin() + n;
}
void insert(iterator position, size_type n, const T &x) {
if (position == end()) {
resize(size() + n);
std::fill(oneapi::dpl::execution::dpcpp_default, end() - n, end(), x);
} else {
auto i_n = std::distance(begin(), position);
// allocate temporary storage
Buffer tmp{Range(std::distance(position, end()))};
// copy remainder
std::copy(oneapi::dpl::execution::dpcpp_default, position, end(),
oneapi::dpl::begin(tmp));
resize(size() + n);
// resizing might invalidate position
position = begin() + position.get_idx();
std::fill(oneapi::dpl::execution::dpcpp_default, position, position + n,
x);
std::copy(oneapi::dpl::execution::dpcpp_default, oneapi::dpl::begin(tmp),
oneapi::dpl::end(tmp), position + n);
}
}
template <typename InputIterator>
void
insert(iterator position, InputIterator first,
typename std::enable_if<internal::is_iterator<InputIterator>::value,
InputIterator>::type last) {
auto n = std::distance(first, last);
if (position == end()) {
resize(size() + n);
std::copy(oneapi::dpl::execution::dpcpp_default, first, last, end());
} else {
Buffer tmp{Range(std::distance(position, end()))};
std::copy(oneapi::dpl::execution::dpcpp_default, position, end(),
oneapi::dpl::begin(tmp));
resize(size() + n);
// resizing might invalidate position
position = begin() + position.get_idx();
std::copy(oneapi::dpl::execution::dpcpp_default, first, last, position);
std::copy(oneapi::dpl::execution::dpcpp_default, oneapi::dpl::begin(tmp),
oneapi::dpl::end(tmp), position + n);
}
}
};
#endif
} // end namespace dpct
#endif
| 36.271624 | 80 | 0.622098 | [
"vector"
] |
0802ca922a5065c6cb4b18878695b511ae936cb9 | 3,703 | h | C | src/Game.h | RioSuzuki/CIS29_Group_Project | 49589e3edc463d4b90cde230af190fcd8ec19274 | [
"MIT"
] | null | null | null | src/Game.h | RioSuzuki/CIS29_Group_Project | 49589e3edc463d4b90cde230af190fcd8ec19274 | [
"MIT"
] | null | null | null | src/Game.h | RioSuzuki/CIS29_Group_Project | 49589e3edc463d4b90cde230af190fcd8ec19274 | [
"MIT"
] | null | null | null | #ifndef GAME_H
#define GAME_H
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <vector>
#include "Projectile.h"
#include "Player.h"
#include "Enemy.h"
#include "ToolBar.hpp"
#include "Menu.h"
#include "Options.h"
#include "ShipSelection.hpp"
#include "Boss.hpp"
#include "Projectile.h"
#include "Endscreen.h"
#include "InputHighscore.h"
class Game
{
bool GAME_PAUSED = 0;
// frequency of how often can a player shoot
// Sprites
sf::Sprite shieldSprite;
sf::Sprite bossSprite;
sf::Sprite GameBackground;
sf::Sprite ToolBarBackground;
//background music
sf::SoundBuffer backgroundBuffer;
sf::SoundBuffer titleThemeBuffer;
sf::Sound backgroundMusic;
sf::SoundBuffer laserSoundBuffer;
sf::Sound laserSound;
sf::SoundBuffer powerupSoundBuffer;
sf::Sound powerupSound;
sf::SoundBuffer enemyHurtSoundBuffer;
sf::Sound enemyHurtSound;
sf::Texture SPACE_TEXTURE;
// background texture
sf::Texture BackgroundTexture;
sf::Texture ToolBarBackgroundTexture;
// shield
sf::IntRect SHIELD_RECT = sf::IntRect(132, 0, 47, 46);
sf::RenderWindow* window;
std::vector<Projectile*> playerProjectileArray;
std::vector<Projectile*> enemyProjectileArray;
std::vector<Projectile*> bossProjectileArray;
std::vector<Enemy*> enemyArr;
std::vector<PowerUp*> powerUpArr;
std::vector<sf::IntRect> enemyRectArr;
// Objects
Player* player;
Boss* boss;
ToolBar* tool;
Menu* menu;
Options* options;
Endscreen* endscreen;
InputHighscore* inputHighscore;
ShipSelection* shipSelect;
// Clocks
sf::Clock genPowerUpClock;
sf::Clock genEnemyClock;
// States
int shipNum;
int numEnemy;
int randomEnemy;
int bossHp;
bool BossShown = false;
bool BackdoorTriggered = false;
bool InfinityHpTriggered = false;
bool BiggerProjTriggered = false;
sf::Vector2f initialPos; //where should the layout start
sf::Vector2f direction; //they all move in the same direction
public:
Game();
~Game();
void resetGame();
void gameLoop();
void handleKeyInput();
void handleBackdoorKeyInput(sf::Keyboard::Key code);
void generatePowerUp();
//void initEnemy(const sf::Vector2u, unsigned int, unsigned int);
void loadAllMusic();
void updateGame();
void drawGame();
void pauseGame();
// Menu stuff
bool menuHandleKeyboard(sf::Event& event);
bool menuHandleMouseClicked(sf::Event& event);
bool menuHandleMouseMove(sf::Event& event);
bool displayMenu();
//void loadEnemyRectArray();
template<class T>
void updateGameObjectArray(std::vector<T*>& arr);
template<class T>
void drawGameObjectArray(std::vector<T*>& arr);
// void updateProjectile(std::vector<Projectile*>&);
// collision detections
void collisionPlayerProjAndBoss();
void collisionBossProjAndPlayer();
void collisionPlayerProjAndEnemy();
void collisionEnemyProjAndShield();
void collisionBossProjAndShield();
// Collision between enemyProjectile and player
void collisionEnemyProjAndPlayer();
// Check colliision between enemy and player
void collisionEnemyAndPlayer();
// Check colliision between powerup and player
void collisionPowerUpAndPlayer();
// Enemy Generations
void generateEnemy();
int generateDiagonalEnemy(int n, sf::Vector2f initialPos, sf::Vector2f direction);
int generateSquqreEnemy( int row, int col, sf::Vector2f initialPos, sf::Vector2f direction);
// for demonstration
// enemy shoot
void enemyRandomShoot();
void bossRandomShoot();
};
#endif
| 27.029197 | 96 | 0.692952 | [
"vector"
] |
080e03dd46fd31a9b87ee655e547c7cf24cb5131 | 14,669 | c | C | extsrc/mesa/src/gallium/auxiliary/draw/draw_pt.c | MauroArgentino/RSXGL | bd206e11894f309680f48740346c17efe49755ba | [
"BSD-2-Clause"
] | 28 | 2015-07-11T17:11:12.000Z | 2022-03-26T04:14:16.000Z | extsrc/mesa/src/gallium/auxiliary/draw/draw_pt.c | MauroArgentino/RSXGL | bd206e11894f309680f48740346c17efe49755ba | [
"BSD-2-Clause"
] | 2 | 2019-05-26T19:02:24.000Z | 2021-05-27T14:15:04.000Z | extsrc/mesa/src/gallium/auxiliary/draw/draw_pt.c | MauroArgentino/RSXGL | bd206e11894f309680f48740346c17efe49755ba | [
"BSD-2-Clause"
] | 9 | 2019-07-04T12:54:29.000Z | 2022-02-09T13:04:38.000Z | /**************************************************************************
*
* Copyright 2007 Tungsten Graphics, Inc., Cedar Park, Texas.
* All Rights Reserved.
*
* 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, sub license, 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 (including the
* next paragraph) 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 NON-INFRINGEMENT.
* IN NO EVENT SHALL TUNGSTEN GRAPHICS AND/OR ITS SUPPLIERS 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.
*
**************************************************************************/
/*
* Authors:
* Keith Whitwell <keith@tungstengraphics.com>
*/
#include "draw/draw_context.h"
#include "draw/draw_gs.h"
#include "draw/draw_private.h"
#include "draw/draw_pt.h"
#include "draw/draw_vs.h"
#include "tgsi/tgsi_dump.h"
#include "util/u_math.h"
#include "util/u_prim.h"
#include "util/u_format.h"
#include "util/u_draw.h"
DEBUG_GET_ONCE_BOOL_OPTION(draw_fse, "DRAW_FSE", FALSE)
DEBUG_GET_ONCE_BOOL_OPTION(draw_no_fse, "DRAW_NO_FSE", FALSE)
/* Overall we split things into:
* - frontend -- prepare fetch_elts, draw_elts - eg vsplit
* - middle -- fetch, shade, cliptest, viewport
* - pipeline -- the prim pipeline: clipping, wide lines, etc
* - backend -- the vbuf_render provided by the driver.
*/
static boolean
draw_pt_arrays(struct draw_context *draw,
unsigned prim,
unsigned start,
unsigned count)
{
struct draw_pt_front_end *frontend = NULL;
struct draw_pt_middle_end *middle = NULL;
unsigned opt = 0;
/* Sanitize primitive length:
*/
{
unsigned first, incr;
draw_pt_split_prim(prim, &first, &incr);
count = draw_pt_trim_count(count, first, incr);
if (count < first)
return TRUE;
}
if (!draw->force_passthrough) {
unsigned gs_out_prim = (draw->gs.geometry_shader ?
draw->gs.geometry_shader->output_primitive :
prim);
if (!draw->render) {
opt |= PT_PIPELINE;
}
if (draw_need_pipeline(draw,
draw->rasterizer,
gs_out_prim)) {
opt |= PT_PIPELINE;
}
if ((draw->clip_xy ||
draw->clip_z ||
draw->clip_user) && !draw->pt.test_fse) {
opt |= PT_CLIPTEST;
}
opt |= PT_SHADE;
}
if (draw->pt.middle.llvm) {
middle = draw->pt.middle.llvm;
} else {
if (opt == 0)
middle = draw->pt.middle.fetch_emit;
else if (opt == PT_SHADE && !draw->pt.no_fse)
middle = draw->pt.middle.fetch_shade_emit;
else
middle = draw->pt.middle.general;
}
frontend = draw->pt.front.vsplit;
frontend->prepare( frontend, prim, middle, opt );
frontend->run(frontend, start, count);
frontend->finish( frontend );
return TRUE;
}
boolean draw_pt_init( struct draw_context *draw )
{
draw->pt.test_fse = debug_get_option_draw_fse();
draw->pt.no_fse = debug_get_option_draw_no_fse();
draw->pt.front.vsplit = draw_pt_vsplit(draw);
if (!draw->pt.front.vsplit)
return FALSE;
draw->pt.middle.fetch_emit = draw_pt_fetch_emit( draw );
if (!draw->pt.middle.fetch_emit)
return FALSE;
draw->pt.middle.fetch_shade_emit = draw_pt_middle_fse( draw );
if (!draw->pt.middle.fetch_shade_emit)
return FALSE;
draw->pt.middle.general = draw_pt_fetch_pipeline_or_emit( draw );
if (!draw->pt.middle.general)
return FALSE;
#if HAVE_LLVM
if (draw->llvm)
draw->pt.middle.llvm = draw_pt_fetch_pipeline_or_emit_llvm( draw );
#endif
return TRUE;
}
void draw_pt_destroy( struct draw_context *draw )
{
if (draw->pt.middle.llvm) {
draw->pt.middle.llvm->destroy( draw->pt.middle.llvm );
draw->pt.middle.llvm = NULL;
}
if (draw->pt.middle.general) {
draw->pt.middle.general->destroy( draw->pt.middle.general );
draw->pt.middle.general = NULL;
}
if (draw->pt.middle.fetch_emit) {
draw->pt.middle.fetch_emit->destroy( draw->pt.middle.fetch_emit );
draw->pt.middle.fetch_emit = NULL;
}
if (draw->pt.middle.fetch_shade_emit) {
draw->pt.middle.fetch_shade_emit->destroy( draw->pt.middle.fetch_shade_emit );
draw->pt.middle.fetch_shade_emit = NULL;
}
if (draw->pt.front.vsplit) {
draw->pt.front.vsplit->destroy( draw->pt.front.vsplit );
draw->pt.front.vsplit = NULL;
}
}
/**
* Debug- print the first 'count' vertices.
*/
static void
draw_print_arrays(struct draw_context *draw, uint prim, int start, uint count)
{
uint i;
debug_printf("Draw arrays(prim = %u, start = %u, count = %u)\n",
prim, start, count);
for (i = 0; i < count; i++) {
uint ii = 0;
uint j;
if (draw->pt.user.eltSize) {
const char *elts;
/* indexed arrays */
elts = (const char *) draw->pt.user.elts;
elts += draw->pt.index_buffer.offset;
switch (draw->pt.user.eltSize) {
case 1:
{
const ubyte *elem = (const ubyte *) elts;
ii = elem[start + i];
}
break;
case 2:
{
const ushort *elem = (const ushort *) elts;
ii = elem[start + i];
}
break;
case 4:
{
const uint *elem = (const uint *) elts;
ii = elem[start + i];
}
break;
default:
assert(0);
return;
}
ii += draw->pt.user.eltBias;
debug_printf("Element[%u + %u] + %i -> Vertex %u:\n", start, i,
draw->pt.user.eltBias, ii);
}
else {
/* non-indexed arrays */
ii = start + i;
debug_printf("Vertex %u:\n", ii);
}
for (j = 0; j < draw->pt.nr_vertex_elements; j++) {
uint buf = draw->pt.vertex_element[j].vertex_buffer_index;
ubyte *ptr = (ubyte *) draw->pt.user.vbuffer[buf];
if (draw->pt.vertex_element[j].instance_divisor) {
ii = draw->instance_id / draw->pt.vertex_element[j].instance_divisor;
}
ptr += draw->pt.vertex_buffer[buf].buffer_offset;
ptr += draw->pt.vertex_buffer[buf].stride * ii;
ptr += draw->pt.vertex_element[j].src_offset;
debug_printf(" Attr %u: ", j);
switch (draw->pt.vertex_element[j].src_format) {
case PIPE_FORMAT_R32_FLOAT:
{
float *v = (float *) ptr;
debug_printf("R %f @ %p\n", v[0], (void *) v);
}
break;
case PIPE_FORMAT_R32G32_FLOAT:
{
float *v = (float *) ptr;
debug_printf("RG %f %f @ %p\n", v[0], v[1], (void *) v);
}
break;
case PIPE_FORMAT_R32G32B32_FLOAT:
{
float *v = (float *) ptr;
debug_printf("RGB %f %f %f @ %p\n", v[0], v[1], v[2], (void *) v);
}
break;
case PIPE_FORMAT_R32G32B32A32_FLOAT:
{
float *v = (float *) ptr;
debug_printf("RGBA %f %f %f %f @ %p\n", v[0], v[1], v[2], v[3],
(void *) v);
}
break;
case PIPE_FORMAT_B8G8R8A8_UNORM:
{
ubyte *u = (ubyte *) ptr;
debug_printf("BGRA %d %d %d %d @ %p\n", u[0], u[1], u[2], u[3],
(void *) u);
}
break;
default:
debug_printf("other format %s (fix me)\n",
util_format_name(draw->pt.vertex_element[j].src_format));
}
}
}
}
/** Helper code for below */
#define PRIM_RESTART_LOOP(elements) \
do { \
for (i = start; i < end; i++) { \
if (elements[i] == info->restart_index) { \
if (cur_count > 0) { \
/* draw elts up to prev pos */ \
draw_pt_arrays(draw, prim, cur_start, cur_count); \
} \
/* begin new prim at next elt */ \
cur_start = i + 1; \
cur_count = 0; \
} \
else { \
cur_count++; \
} \
} \
if (cur_count > 0) { \
draw_pt_arrays(draw, prim, cur_start, cur_count); \
} \
} while (0)
/**
* For drawing prims with primitive restart enabled.
* Scan for restart indexes and draw the runs of elements/vertices between
* the restarts.
*/
static void
draw_pt_arrays_restart(struct draw_context *draw,
const struct pipe_draw_info *info)
{
const unsigned prim = info->mode;
const unsigned start = info->start;
const unsigned count = info->count;
const unsigned end = start + count;
unsigned i, cur_start, cur_count;
assert(info->primitive_restart);
if (draw->pt.user.elts) {
/* indexed prims (draw_elements) */
cur_start = start;
cur_count = 0;
switch (draw->pt.user.eltSize) {
case 1:
{
const ubyte *elt_ub = (const ubyte *) draw->pt.user.elts;
PRIM_RESTART_LOOP(elt_ub);
}
break;
case 2:
{
const ushort *elt_us = (const ushort *) draw->pt.user.elts;
PRIM_RESTART_LOOP(elt_us);
}
break;
case 4:
{
const uint *elt_ui = (const uint *) draw->pt.user.elts;
PRIM_RESTART_LOOP(elt_ui);
}
break;
default:
assert(0 && "bad eltSize in draw_arrays()");
}
}
else {
/* Non-indexed prims (draw_arrays).
* Primitive restart should have been handled in the state tracker.
*/
draw_pt_arrays(draw, prim, start, count);
}
}
/**
* Non-instanced drawing.
* \sa draw_arrays_instanced
*/
void
draw_arrays(struct draw_context *draw, unsigned prim,
unsigned start, unsigned count)
{
draw_arrays_instanced(draw, prim, start, count, 0, 1);
}
/**
* Instanced drawing.
* \sa draw_vbo
*/
void
draw_arrays_instanced(struct draw_context *draw,
unsigned mode,
unsigned start,
unsigned count,
unsigned startInstance,
unsigned instanceCount)
{
struct pipe_draw_info info;
util_draw_init_info(&info);
info.mode = mode;
info.start = start;
info.count = count;
info.start_instance = startInstance;
info.instance_count = instanceCount;
info.indexed = (draw->pt.user.elts != NULL);
if (!info.indexed) {
info.min_index = start;
info.max_index = start + count - 1;
}
draw_vbo(draw, &info);
}
/**
* Draw vertex arrays.
* This is the main entrypoint into the drawing module. If drawing an indexed
* primitive, the draw_set_index_buffer() and draw_set_mapped_index_buffer()
* functions should have already been called to specify the element/index
* buffer information.
*/
void
draw_vbo(struct draw_context *draw,
const struct pipe_draw_info *info)
{
unsigned reduced_prim = u_reduced_prim(info->mode);
unsigned instance;
unsigned index_limit;
assert(info->instance_count > 0);
if (info->indexed)
assert(draw->pt.user.elts);
draw->pt.user.eltSize =
(info->indexed) ? draw->pt.index_buffer.index_size : 0;
draw->pt.user.eltBias = info->index_bias;
draw->pt.user.min_index = info->min_index;
draw->pt.user.max_index = info->max_index;
if (reduced_prim != draw->reduced_prim) {
draw_do_flush(draw, DRAW_FLUSH_STATE_CHANGE);
draw->reduced_prim = reduced_prim;
}
if (0)
debug_printf("draw_vbo(mode=%u start=%u count=%u):\n",
info->mode, info->start, info->count);
if (0)
tgsi_dump(draw->vs.vertex_shader->state.tokens, 0);
if (0) {
unsigned int i;
debug_printf("Elements:\n");
for (i = 0; i < draw->pt.nr_vertex_elements; i++) {
debug_printf(" %u: src_offset=%u inst_div=%u vbuf=%u format=%s\n",
i,
draw->pt.vertex_element[i].src_offset,
draw->pt.vertex_element[i].instance_divisor,
draw->pt.vertex_element[i].vertex_buffer_index,
util_format_name(draw->pt.vertex_element[i].src_format));
}
debug_printf("Buffers:\n");
for (i = 0; i < draw->pt.nr_vertex_buffers; i++) {
debug_printf(" %u: stride=%u offset=%u ptr=%p\n",
i,
draw->pt.vertex_buffer[i].stride,
draw->pt.vertex_buffer[i].buffer_offset,
draw->pt.user.vbuffer[i]);
}
}
if (0)
draw_print_arrays(draw, info->mode, info->start, MIN2(info->count, 20));
index_limit = util_draw_max_index(draw->pt.vertex_buffer,
draw->pt.nr_vertex_buffers,
draw->pt.vertex_element,
draw->pt.nr_vertex_elements,
info);
if (index_limit == 0) {
/* one of the buffers is too small to do any valid drawing */
debug_warning("draw: VBO too small to draw anything\n");
return;
}
draw->pt.max_index = index_limit - 1;
/*
* TODO: We could use draw->pt.max_index to further narrow
* the min_index/max_index hints given by the state tracker.
*/
for (instance = 0; instance < info->instance_count; instance++) {
draw->instance_id = instance + info->start_instance;
if (info->primitive_restart) {
draw_pt_arrays_restart(draw, info);
}
else {
draw_pt_arrays(draw, info->mode, info->start, info->count);
}
}
}
| 29.047525 | 84 | 0.561797 | [
"render"
] |
080fca256f7eee17e8810258beb930036cb93cbd | 2,551 | h | C | TEveEventDisplay/src/dict_classes/GeomUtils.h | knoepfel/Offline | bb0e52f2e6627abe223e8adaf6fe326cead595df | [
"Apache-2.0"
] | null | null | null | TEveEventDisplay/src/dict_classes/GeomUtils.h | knoepfel/Offline | bb0e52f2e6627abe223e8adaf6fe326cead595df | [
"Apache-2.0"
] | null | null | null | TEveEventDisplay/src/dict_classes/GeomUtils.h | knoepfel/Offline | bb0e52f2e6627abe223e8adaf6fe326cead595df | [
"Apache-2.0"
] | null | null | null | #ifndef GeomUtils_h
#define GeomUtils_h
// Math
#include "DataProducts/inc/XYZVec.hh"
#include "ConfigTools/inc/SimpleConfig.hh"
#include "GeometryService/inc/GeomHandle.hh"
#include "CalorimeterGeom/inc/Calorimeter.hh"
#include "TrackerGeom/inc/Tracker.hh"
#include "GeometryService/inc/DetectorSystem.hh"
//C++
#include <vector>
using namespace CLHEP;
namespace mu2e{
inline double pointmmTocm(double mm){ return mm/10; };
inline void hep3vectorTocm(CLHEP::Hep3Vector &vector){vector.set(vector.x()/10, vector.y()/10, vector.z()/10);}
inline void XYZVecTocm(XYZVec &vector){ vector.SetXYZ(vector.x()/10, vector.y()/10, vector.z()/10);}
inline CLHEP::Hep3Vector GetTrackerCenter(){
std::string filename("Mu2eG4/geom/geom_common_current.txt");
SimpleConfig GeomConfig(filename);
double zCenter = GeomConfig.getDouble("mu2e.detectorSystemZ0");
double xCenter = -GeomConfig.getDouble("mu2e.solenoidOffset");
CLHEP::Hep3Vector c(xCenter, 0, zCenter);
return c;
}
inline CLHEP::Hep3Vector GetCaloCenter(int nDisk){
std::string calfilename("Mu2eG4/geom/calorimeter_CsI.txt");
SimpleConfig CalConfig(calfilename);
double zCenter = 0;
if(nDisk==0) zCenter = CalConfig.getDouble("calorimeter.caloMotherZ0") + 100;
if(nDisk==1) zCenter = CalConfig.getDouble("calorimeter.caloMotherZ1") - 600;
std::string geomfilename("Mu2eG4/geom/geom_common_current.txt");
SimpleConfig GeomConfig(geomfilename);
double xCenter = -GeomConfig.getDouble("mu2e.solenoidOffset");
CLHEP::Hep3Vector c(xCenter, 0, zCenter);
return c;
}
inline CLHEP::Hep3Vector PointToCalo( CLHEP::Hep3Vector point, int nDisk){
CLHEP::Hep3Vector Mu2eCaloOrigin = GetCaloCenter(nDisk);
CLHEP::Hep3Vector PointToCalo(point.x() + Mu2eCaloOrigin.x(), point.y()+Mu2eCaloOrigin.y(), point.z() + Mu2eCaloOrigin.z());
return PointToCalo;
}
inline double TrackerLength(){
GeomHandle<Tracker> trkr;
TubsParams envelope(trkr->g4Tracker()->getInnerTrackerEnvelopeParams());
double dz{(envelope.zHalfLength())};
std::cout<<"Length "<<dz*2<<std::endl;
return (dz*2);
}
inline CLHEP::Hep3Vector NewCenter(){
GeomHandle<Tracker> trkr;
GeomHandle<DetectorSystem> det;
CLHEP::Hep3Vector origin = trkr->origin();
CLHEP::Hep3Vector InMu2e = det->toMu2e(origin);
return InMu2e;
}
inline double CaloLength(){
//Not used anymore....
return 320;
}
}
#endif
| 36.442857 | 130 | 0.689142 | [
"vector"
] |
081c01b2d35f3191b6c178dafe46490b853699fd | 2,993 | h | C | modules/perception/camera/lib/motion_service/motion_service.h | seeclong/apollo | 99c8afb5ebcae2a3c9359a156a957ff03944b27b | [
"Apache-2.0"
] | 27 | 2019-04-06T02:27:14.000Z | 2021-11-27T13:47:06.000Z | modules/perception/camera/lib/motion_service/motion_service.h | seeclong/apollo | 99c8afb5ebcae2a3c9359a156a957ff03944b27b | [
"Apache-2.0"
] | 5 | 2021-10-06T22:57:52.000Z | 2022-02-27T14:04:05.000Z | modules/perception/camera/lib/motion_service/motion_service.h | seeclong/apollo | 99c8afb5ebcae2a3c9359a156a957ff03944b27b | [
"Apache-2.0"
] | 38 | 2019-04-15T10:58:37.000Z | 2022-01-27T08:52:39.000Z | /******************************************************************************
* Copyright 2019 The Apollo 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 <Eigen/Core>
#include <list>
#include <memory>
#include <mutex>
#include <string>
#include <vector>
#include "cyber/component/component.h"
#include "modules/drivers/proto/sensor_image.pb.h"
#include "modules/localization/proto/localization.pb.h"
#include "modules/perception/camera/common/camera_frame.h"
#include "modules/perception/camera/lib/motion/plane_motion.h"
#include "modules/perception/lib/registerer/registerer.h"
#include "modules/perception/onboard/proto/motion_service.pb.h"
#include "modules/perception/proto/motion_service.pb.h"
namespace apollo {
namespace perception {
namespace camera {
typedef std::shared_ptr<apollo::drivers::Image> ImageMsgType;
typedef std::shared_ptr<localization::LocalizationEstimate> LocalizationMsgType;
class MotionService : public apollo::cyber::Component<> {
public:
MotionService() = default;
virtual ~MotionService() { delete vehicle_planemotion_; }
bool Init() override;
bool GetMotionInformation(double timestamp, base::VehicleStatus *vs);
base::MotionBuffer GetMotionBuffer();
double GetLatestTimestamp();
private:
void OnLocalization(const LocalizationMsgType &localization);
void OnReceiveImage(const ImageMsgType &message,
const std::string &camera_name);
void PublishEvent(const double timestamp);
void ConvertVehicleMotionToMsgOut(
base::VehicleStatus vs, apollo::perception::VehicleStatus *v_status_msg);
PlaneMotion *vehicle_planemotion_ = nullptr;
std::string device_id_;
double pre_azimuth = 0; // a invalid value
double pre_timestamp_ = 0;
double pre_camera_timestamp_ = 0;
double camera_timestamp_ = 0;
bool start_flag_ = false;
const int motion_buffer_size_ = 100;
double timestamp_offset_ = 0.0;
std::vector<std::string> camera_names_; // camera sensor names
std::vector<std::string> input_camera_channel_names_;
std::mutex mutex_;
// std::mutex image_mutex_;
std::mutex motion_mutex_;
std::shared_ptr<apollo::cyber::Writer<apollo::perception::Motion_Service>>
writer_;
DISALLOW_COPY_AND_ASSIGN(MotionService);
};
CYBER_REGISTER_COMPONENT(MotionService);
} // namespace camera
} // namespace perception
} // namespace apollo
| 35.630952 | 80 | 0.722018 | [
"vector"
] |
081cd79bf8dcc3b2364d6c52aed98dae03c12ec1 | 14,145 | h | C | src/brpc/policy/http2_rpc_protocol.h | zyearn/brpc | 2240d34cf24005abdb0a8c2a54f9f4cf83332f8d | [
"Apache-2.0"
] | 3 | 2018-05-16T06:36:33.000Z | 2021-03-13T12:29:17.000Z | src/brpc/policy/http2_rpc_protocol.h | zyearn/brpc | 2240d34cf24005abdb0a8c2a54f9f4cf83332f8d | [
"Apache-2.0"
] | null | null | null | src/brpc/policy/http2_rpc_protocol.h | zyearn/brpc | 2240d34cf24005abdb0a8c2a54f9f4cf83332f8d | [
"Apache-2.0"
] | null | null | null | // Copyright (c) 2014 Baidu, 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.
// Authors: Ge,Jun (gejun@baidu.com)
// Jiashun Zhu(zhujiashun@baidu.com)
#ifndef BAIDU_RPC_POLICY_HTTP2_RPC_PROTOCOL_H
#define BAIDU_RPC_POLICY_HTTP2_RPC_PROTOCOL_H
#include "brpc/policy/http_rpc_protocol.h" // HttpContext
#include "brpc/input_message_base.h"
#include "brpc/protocol.h"
#include "brpc/details/hpack.h"
#include "brpc/stream_creator.h"
#include "brpc/controller.h"
#ifndef NDEBUG
#include "bvar/bvar.h"
#endif
namespace brpc {
namespace policy {
class H2StreamContext;
class H2ParseResult {
public:
explicit H2ParseResult(H2Error err, int stream_id)
: _msg(NULL), _err(err), _stream_id(stream_id) {}
explicit H2ParseResult(H2StreamContext* msg)
: _msg(msg), _err(H2_NO_ERROR), _stream_id(0) {}
// Return H2_NO_ERROR when the result is successful.
H2Error error() const { return _err; }
const char* error_str() const { return H2ErrorToString(_err); }
bool is_ok() const { return error() == H2_NO_ERROR; }
int stream_id() const { return _stream_id; }
// definitely NULL when result is failed.
H2StreamContext* message() const { return _msg; }
private:
H2StreamContext* _msg;
H2Error _err;
int _stream_id;
};
inline H2ParseResult MakeH2Error(H2Error err, int stream_id)
{ return H2ParseResult(err, stream_id); }
inline H2ParseResult MakeH2Error(H2Error err)
{ return H2ParseResult(err, 0); }
inline H2ParseResult MakeH2Message(H2StreamContext* msg)
{ return H2ParseResult(msg); }
class H2Context;
enum H2FrameType {
H2_FRAME_DATA = 0x0,
H2_FRAME_HEADERS = 0x1,
H2_FRAME_PRIORITY = 0x2,
H2_FRAME_RST_STREAM = 0x3,
H2_FRAME_SETTINGS = 0x4,
H2_FRAME_PUSH_PROMISE = 0x5,
H2_FRAME_PING = 0x6,
H2_FRAME_GOAWAY = 0x7,
H2_FRAME_WINDOW_UPDATE = 0x8,
H2_FRAME_CONTINUATION = 0x9,
// ============================
H2_FRAME_TYPE_MAX = 0x9
};
// https://tools.ietf.org/html/rfc7540#section-4.1
struct H2FrameHead {
// The length of the frame payload expressed as an unsigned 24-bit integer.
// Values greater than H2Settings.max_frame_size MUST NOT be sent
uint32_t payload_size;
// The 8-bit type of the frame. The frame type determines the format and
// semantics of the frame. Implementations MUST ignore and discard any
// frame that has a type that is unknown.
H2FrameType type;
// An 8-bit field reserved for boolean flags specific to the frame type.
// Flags are assigned semantics specific to the indicated frame type.
// Flags that have no defined semantics for a particular frame type
// MUST be ignored and MUST be left unset (0x0) when sending.
uint8_t flags;
// A stream identifier (see Section 5.1.1) expressed as an unsigned 31-bit
// integer. The value 0x0 is reserved for frames that are associated with
// the connection as a whole as opposed to an individual stream.
int stream_id;
};
enum H2StreamState {
H2_STREAM_IDLE = 0,
H2_STREAM_RESERVED_LOCAL,
H2_STREAM_RESERVED_REMOTE,
H2_STREAM_OPEN,
H2_STREAM_HALF_CLOSED_LOCAL,
H2_STREAM_HALF_CLOSED_REMOTE,
H2_STREAM_CLOSED,
};
const char* H2StreamState2Str(H2StreamState);
#ifndef NDEBUG
struct Http2Bvars {
bvar::Adder<int> h2_unsent_request_count;
bvar::Adder<int> h2_stream_context_count;
Http2Bvars()
: h2_unsent_request_count("h2_unsent_request_count")
, h2_stream_context_count("h2_stream_context_count") {
}
};
inline Http2Bvars* get_http2_bvars() {
return butil::get_leaky_singleton<Http2Bvars>();
}
#endif
class H2UnsentRequest : public SocketMessage, public StreamUserData {
friend void PackH2Request(butil::IOBuf*, SocketMessage**,
uint64_t, const google::protobuf::MethodDescriptor*,
Controller*, const butil::IOBuf&, const Authenticator*);
public:
static H2UnsentRequest* New(Controller* c);
void Describe(butil::IOBuf*) const;
int AddRefManually()
{ return _nref.fetch_add(1, butil::memory_order_relaxed); }
void RemoveRefManually() {
if (_nref.fetch_sub(1, butil::memory_order_release) == 1) {
butil::atomic_thread_fence(butil::memory_order_acquire);
Destroy();
}
}
// @SocketMessage
butil::Status AppendAndDestroySelf(butil::IOBuf* out, Socket*) override;
size_t EstimatedByteSize() override;
// @StreamUserData
void DestroyStreamUserData(SocketUniquePtr& sending_sock,
Controller* cntl,
int error_code,
bool end_of_rpc) override;
private:
std::string& push(const std::string& name)
{ return (new (&_list[_size++]) HPacker::Header(name))->value; }
void push(const std::string& name, const std::string& value)
{ new (&_list[_size++]) HPacker::Header(name, value); }
H2UnsentRequest(Controller* c)
: _nref(1)
, _size(0)
, _stream_id(0)
, _cntl(c) {
#ifndef NDEBUG
get_http2_bvars()->h2_unsent_request_count << 1;
#endif
}
~H2UnsentRequest() {
#ifndef NDEBUG
get_http2_bvars()->h2_unsent_request_count << -1;
#endif
}
H2UnsentRequest(const H2UnsentRequest&);
void operator=(const H2UnsentRequest&);
void Destroy();
private:
butil::atomic<int> _nref;
uint32_t _size;
int _stream_id;
mutable butil::Mutex _mutex;
Controller* _cntl;
std::unique_ptr<H2StreamContext> _sctx;
HPacker::Header _list[0];
};
class H2UnsentResponse : public SocketMessage {
public:
static H2UnsentResponse* New(Controller* c, int stream_id);
void Destroy();
void Describe(butil::IOBuf*) const;
// @SocketMessage
butil::Status AppendAndDestroySelf(butil::IOBuf* out, Socket*) override;
size_t EstimatedByteSize() override;
private:
std::string& push(const std::string& name)
{ return (new (&_list[_size++]) HPacker::Header(name))->value; }
void push(const std::string& name, const std::string& value)
{ new (&_list[_size++]) HPacker::Header(name, value); }
H2UnsentResponse(Controller* c, int stream_id)
: _size(0)
, _stream_id(stream_id)
, _http_response(c->release_http_response()) {
_data.swap(c->response_attachment());
}
~H2UnsentResponse() {}
H2UnsentResponse(const H2UnsentResponse&);
void operator=(const H2UnsentResponse&);
private:
uint32_t _size;
uint32_t _stream_id;
std::unique_ptr<HttpHeader> _http_response;
butil::IOBuf _data;
HPacker::Header _list[0];
};
// Used in http_rpc_protocol.cpp
class H2StreamContext : public HttpContext {
public:
H2StreamContext();
~H2StreamContext();
void Init(H2Context* conn_ctx, int stream_id);
H2StreamContext(H2Context* conn_ctx, int stream_id);
// Decode headers in HPACK from *it and set into this->header(). The input
// does not need to complete.
// Returns 0 on success, -1 otherwise.
int ConsumeHeaders(butil::IOBufBytesIterator& it);
H2ParseResult EndRemoteStream();
H2ParseResult OnData(butil::IOBufBytesIterator&, const H2FrameHead&,
uint32_t frag_size, uint8_t pad_length);
H2ParseResult OnHeaders(butil::IOBufBytesIterator&, const H2FrameHead&,
uint32_t frag_size, uint8_t pad_length);
H2ParseResult OnContinuation(butil::IOBufBytesIterator&, const H2FrameHead&);
H2ParseResult OnResetStream(H2Error h2_error, const H2FrameHead&);
uint64_t correlation_id() const { return _correlation_id; }
void set_correlation_id(uint64_t cid) { _correlation_id = cid; }
size_t parsed_length() const { return this->_parsed_length; }
int stream_id() const { return _stream_id; }
int64_t ReleaseDeferredWindowUpdate() {
if (_deferred_window_update.load(butil::memory_order_relaxed) == 0) {
return 0;
}
return _deferred_window_update.exchange(0, butil::memory_order_relaxed);
}
bool ConsumeWindowSize(int64_t size);
#if defined(BRPC_H2_STREAM_STATE)
H2StreamState state() const { return _state; }
void SetState(H2StreamState state);
#endif
friend class H2Context;
H2Context* _conn_ctx;
#if defined(BRPC_H2_STREAM_STATE)
H2StreamState _state;
#endif
int _stream_id;
bool _stream_ended;
butil::atomic<int64_t> _remote_window_left;
butil::atomic<int64_t> _deferred_window_update;
uint64_t _correlation_id;
butil::IOBuf _remaining_header_fragment;
};
StreamCreator* get_h2_global_stream_creator();
ParseResult ParseH2Message(butil::IOBuf *source, Socket *socket,
bool read_eof, const void *arg);
void PackH2Request(butil::IOBuf* buf,
SocketMessage** user_message_out,
uint64_t correlation_id,
const google::protobuf::MethodDescriptor* method,
Controller* controller,
const butil::IOBuf& request,
const Authenticator* auth);
class H2GlobalStreamCreator : public StreamCreator {
protected:
StreamUserData* OnCreatingStream(SocketUniquePtr* inout, Controller* cntl) override;
void DestroyStreamCreator(Controller* cntl) override;
};
enum H2ConnectionState {
H2_CONNECTION_UNINITIALIZED,
H2_CONNECTION_READY,
H2_CONNECTION_GOAWAY,
};
void SerializeFrameHead(void* out_buf,
uint32_t payload_size, H2FrameType type,
uint8_t flags, uint32_t stream_id);
size_t SerializeH2Settings(const H2Settings& in, void* out);
const size_t FRAME_HEAD_SIZE = 9;
// Contexts of a http2 connection
class H2Context : public Destroyable, public Describable {
public:
typedef H2ParseResult (H2Context::*FrameHandler)(
butil::IOBufBytesIterator&, const H2FrameHead&);
// main_socket: the socket owns this object as parsing_context
// server: NULL means client-side
H2Context(Socket* main_socket, const Server* server);
~H2Context();
// Must be called before usage.
int Init();
H2ConnectionState state() const { return _conn_state; }
ParseResult Consume(butil::IOBufBytesIterator& it, Socket*);
void ClearAbandonedStreams();
void AddAbandonedStream(uint32_t stream_id);
//@Destroyable
void Destroy() override { delete this; }
int AllocateClientStreamId();
bool RunOutStreams() const;
// Try to map stream_id to ctx if stream_id does not exist before
// Returns 0 on success, -1 on exist, 1 on goaway.
int TryToInsertStream(int stream_id, H2StreamContext* ctx);
size_t VolatilePendingStreamSize() const { return _pending_streams.size(); }
HPacker& hpacker() { return _hpacker; }
const H2Settings& remote_settings() const { return _remote_settings; }
const H2Settings& local_settings() const { return _local_settings; }
bool is_client_side() const { return _socket->CreatedByConnect(); }
bool is_server_side() const { return !is_client_side(); }
void Describe(std::ostream& os, const DescribeOptions&) const;
void DeferWindowUpdate(int64_t);
int64_t ReleaseDeferredWindowUpdate();
private:
friend class H2StreamContext;
friend class H2UnsentRequest;
friend class H2UnsentResponse;
friend void InitFrameHandlers();
ParseResult ConsumeFrameHead(butil::IOBufBytesIterator&, H2FrameHead*);
H2ParseResult OnData(butil::IOBufBytesIterator&, const H2FrameHead&);
H2ParseResult OnHeaders(butil::IOBufBytesIterator&, const H2FrameHead&);
H2ParseResult OnPriority(butil::IOBufBytesIterator&, const H2FrameHead&);
H2ParseResult OnResetStream(butil::IOBufBytesIterator&, const H2FrameHead&);
H2ParseResult OnSettings(butil::IOBufBytesIterator&, const H2FrameHead&);
H2ParseResult OnPushPromise(butil::IOBufBytesIterator&, const H2FrameHead&);
H2ParseResult OnPing(butil::IOBufBytesIterator&, const H2FrameHead&);
H2ParseResult OnGoAway(butil::IOBufBytesIterator&, const H2FrameHead&);
H2ParseResult OnWindowUpdate(butil::IOBufBytesIterator&, const H2FrameHead&);
H2ParseResult OnContinuation(butil::IOBufBytesIterator&, const H2FrameHead&);
H2StreamContext* RemoveStream(int stream_id);
void RemoveGoAwayStreams(int goaway_stream_id, std::vector<H2StreamContext*>* out_streams);
H2StreamContext* FindStream(int stream_id);
void ClearAbandonedStreamsImpl();
// True if the connection is established by client, otherwise it's
// accepted by server.
Socket* _socket;
butil::atomic<int64_t> _remote_window_left;
H2ConnectionState _conn_state;
int _last_server_stream_id;
uint32_t _last_client_stream_id;
int _goaway_stream_id;
H2Settings _remote_settings;
H2Settings _local_settings;
H2Settings _unack_local_settings;
HPacker _hpacker;
mutable butil::Mutex _abandoned_streams_mutex;
std::vector<uint32_t> _abandoned_streams;
typedef butil::FlatMap<int, H2StreamContext*> StreamMap;
mutable butil::Mutex _stream_mutex;
StreamMap _pending_streams;
butil::atomic<int64_t> _deferred_window_update;
};
inline int H2Context::AllocateClientStreamId() {
if (RunOutStreams()) {
return -1;
}
const int id = _last_client_stream_id;
_last_client_stream_id += 2;
return id;
}
inline bool H2Context::RunOutStreams() const {
return (_last_client_stream_id > 0x7FFFFFFF);
}
} // namespace policy
} // namespace brpc
#endif // BAIDU_RPC_POLICY_HTTP2_RPC_PROTOCOL_H
| 33.839713 | 95 | 0.70357 | [
"object",
"vector"
] |
081dca05a59f458d70499677ea2e35549c4d7de7 | 1,786 | h | C | src/lockTracer.h | simon04/async-profiler | d6de5417991e5bcfc06e1f600cfc11e37ce1c16a | [
"Apache-2.0"
] | null | null | null | src/lockTracer.h | simon04/async-profiler | d6de5417991e5bcfc06e1f600cfc11e37ce1c16a | [
"Apache-2.0"
] | null | null | null | src/lockTracer.h | simon04/async-profiler | d6de5417991e5bcfc06e1f600cfc11e37ce1c16a | [
"Apache-2.0"
] | null | null | null | /*
* Copyright 2017 Andrei Pangin
*
* 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 _LOCKTRACER_H
#define _LOCKTRACER_H
#include <jvmti.h>
#include "arch.h"
#include "engine.h"
typedef void (JNICALL *UnsafeParkFunc)(JNIEnv*, jobject, jboolean, jlong);
class LockTracer : public Engine {
private:
static jlong _threshold;
static jlong _start_time;
static jclass _LockSupport;
static jmethodID _getBlocker;
static jobject getParkBlocker(jvmtiEnv* jvmti, JNIEnv* env);
static char* getLockName(jvmtiEnv* jvmti, JNIEnv* env, jobject lock);
static bool isConcurrentLock(const char* lock_name);
static void recordContendedLock(int event_type, u64 start_time, u64 end_time,
const char* lock_name, jobject lock, jlong timeout);
static void bindUnsafePark(UnsafeParkFunc entry);
public:
Error start(Arguments& args);
void stop();
static void JNICALL MonitorContendedEnter(jvmtiEnv* jvmti, JNIEnv* env, jthread thread, jobject object);
static void JNICALL MonitorContendedEntered(jvmtiEnv* jvmti, JNIEnv* env, jthread thread, jobject object);
static void JNICALL UnsafeParkTrap(JNIEnv* env, jobject instance, jboolean isAbsolute, jlong time);
};
#endif // _LOCKTRACER_H
| 35.019608 | 110 | 0.734043 | [
"object"
] |
0830a9bd4fdf04af2ef68e113fbb429da1e034d8 | 12,064 | h | C | aws-cpp-sdk-ds/include/aws/ds/model/SchemaExtensionInfo.h | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-ds/include/aws/ds/model/SchemaExtensionInfo.h | Neusoft-Technology-Solutions/aws-sdk-cpp | 88c041828b0dbee18a297c3cfe98c5ecd0706d0b | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-ds/include/aws/ds/model/SchemaExtensionInfo.h | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-12-30T04:25:33.000Z | 2021-12-30T04:25:33.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/ds/DirectoryService_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/ds/model/SchemaExtensionStatus.h>
#include <aws/core/utils/DateTime.h>
#include <utility>
namespace Aws
{
namespace Utils
{
namespace Json
{
class JsonValue;
class JsonView;
} // namespace Json
} // namespace Utils
namespace DirectoryService
{
namespace Model
{
/**
* <p>Information about a schema extension.</p><p><h3>See Also:</h3> <a
* href="http://docs.aws.amazon.com/goto/WebAPI/ds-2015-04-16/SchemaExtensionInfo">AWS
* API Reference</a></p>
*/
class AWS_DIRECTORYSERVICE_API SchemaExtensionInfo
{
public:
SchemaExtensionInfo();
SchemaExtensionInfo(Aws::Utils::Json::JsonView jsonValue);
SchemaExtensionInfo& operator=(Aws::Utils::Json::JsonView jsonValue);
Aws::Utils::Json::JsonValue Jsonize() const;
/**
* <p>The identifier of the directory to which the schema extension is applied.</p>
*/
inline const Aws::String& GetDirectoryId() const{ return m_directoryId; }
/**
* <p>The identifier of the directory to which the schema extension is applied.</p>
*/
inline bool DirectoryIdHasBeenSet() const { return m_directoryIdHasBeenSet; }
/**
* <p>The identifier of the directory to which the schema extension is applied.</p>
*/
inline void SetDirectoryId(const Aws::String& value) { m_directoryIdHasBeenSet = true; m_directoryId = value; }
/**
* <p>The identifier of the directory to which the schema extension is applied.</p>
*/
inline void SetDirectoryId(Aws::String&& value) { m_directoryIdHasBeenSet = true; m_directoryId = std::move(value); }
/**
* <p>The identifier of the directory to which the schema extension is applied.</p>
*/
inline void SetDirectoryId(const char* value) { m_directoryIdHasBeenSet = true; m_directoryId.assign(value); }
/**
* <p>The identifier of the directory to which the schema extension is applied.</p>
*/
inline SchemaExtensionInfo& WithDirectoryId(const Aws::String& value) { SetDirectoryId(value); return *this;}
/**
* <p>The identifier of the directory to which the schema extension is applied.</p>
*/
inline SchemaExtensionInfo& WithDirectoryId(Aws::String&& value) { SetDirectoryId(std::move(value)); return *this;}
/**
* <p>The identifier of the directory to which the schema extension is applied.</p>
*/
inline SchemaExtensionInfo& WithDirectoryId(const char* value) { SetDirectoryId(value); return *this;}
/**
* <p>The identifier of the schema extension.</p>
*/
inline const Aws::String& GetSchemaExtensionId() const{ return m_schemaExtensionId; }
/**
* <p>The identifier of the schema extension.</p>
*/
inline bool SchemaExtensionIdHasBeenSet() const { return m_schemaExtensionIdHasBeenSet; }
/**
* <p>The identifier of the schema extension.</p>
*/
inline void SetSchemaExtensionId(const Aws::String& value) { m_schemaExtensionIdHasBeenSet = true; m_schemaExtensionId = value; }
/**
* <p>The identifier of the schema extension.</p>
*/
inline void SetSchemaExtensionId(Aws::String&& value) { m_schemaExtensionIdHasBeenSet = true; m_schemaExtensionId = std::move(value); }
/**
* <p>The identifier of the schema extension.</p>
*/
inline void SetSchemaExtensionId(const char* value) { m_schemaExtensionIdHasBeenSet = true; m_schemaExtensionId.assign(value); }
/**
* <p>The identifier of the schema extension.</p>
*/
inline SchemaExtensionInfo& WithSchemaExtensionId(const Aws::String& value) { SetSchemaExtensionId(value); return *this;}
/**
* <p>The identifier of the schema extension.</p>
*/
inline SchemaExtensionInfo& WithSchemaExtensionId(Aws::String&& value) { SetSchemaExtensionId(std::move(value)); return *this;}
/**
* <p>The identifier of the schema extension.</p>
*/
inline SchemaExtensionInfo& WithSchemaExtensionId(const char* value) { SetSchemaExtensionId(value); return *this;}
/**
* <p>A description of the schema extension.</p>
*/
inline const Aws::String& GetDescription() const{ return m_description; }
/**
* <p>A description of the schema extension.</p>
*/
inline bool DescriptionHasBeenSet() const { return m_descriptionHasBeenSet; }
/**
* <p>A description of the schema extension.</p>
*/
inline void SetDescription(const Aws::String& value) { m_descriptionHasBeenSet = true; m_description = value; }
/**
* <p>A description of the schema extension.</p>
*/
inline void SetDescription(Aws::String&& value) { m_descriptionHasBeenSet = true; m_description = std::move(value); }
/**
* <p>A description of the schema extension.</p>
*/
inline void SetDescription(const char* value) { m_descriptionHasBeenSet = true; m_description.assign(value); }
/**
* <p>A description of the schema extension.</p>
*/
inline SchemaExtensionInfo& WithDescription(const Aws::String& value) { SetDescription(value); return *this;}
/**
* <p>A description of the schema extension.</p>
*/
inline SchemaExtensionInfo& WithDescription(Aws::String&& value) { SetDescription(std::move(value)); return *this;}
/**
* <p>A description of the schema extension.</p>
*/
inline SchemaExtensionInfo& WithDescription(const char* value) { SetDescription(value); return *this;}
/**
* <p>The current status of the schema extension.</p>
*/
inline const SchemaExtensionStatus& GetSchemaExtensionStatus() const{ return m_schemaExtensionStatus; }
/**
* <p>The current status of the schema extension.</p>
*/
inline bool SchemaExtensionStatusHasBeenSet() const { return m_schemaExtensionStatusHasBeenSet; }
/**
* <p>The current status of the schema extension.</p>
*/
inline void SetSchemaExtensionStatus(const SchemaExtensionStatus& value) { m_schemaExtensionStatusHasBeenSet = true; m_schemaExtensionStatus = value; }
/**
* <p>The current status of the schema extension.</p>
*/
inline void SetSchemaExtensionStatus(SchemaExtensionStatus&& value) { m_schemaExtensionStatusHasBeenSet = true; m_schemaExtensionStatus = std::move(value); }
/**
* <p>The current status of the schema extension.</p>
*/
inline SchemaExtensionInfo& WithSchemaExtensionStatus(const SchemaExtensionStatus& value) { SetSchemaExtensionStatus(value); return *this;}
/**
* <p>The current status of the schema extension.</p>
*/
inline SchemaExtensionInfo& WithSchemaExtensionStatus(SchemaExtensionStatus&& value) { SetSchemaExtensionStatus(std::move(value)); return *this;}
/**
* <p>The reason for the <code>SchemaExtensionStatus</code>.</p>
*/
inline const Aws::String& GetSchemaExtensionStatusReason() const{ return m_schemaExtensionStatusReason; }
/**
* <p>The reason for the <code>SchemaExtensionStatus</code>.</p>
*/
inline bool SchemaExtensionStatusReasonHasBeenSet() const { return m_schemaExtensionStatusReasonHasBeenSet; }
/**
* <p>The reason for the <code>SchemaExtensionStatus</code>.</p>
*/
inline void SetSchemaExtensionStatusReason(const Aws::String& value) { m_schemaExtensionStatusReasonHasBeenSet = true; m_schemaExtensionStatusReason = value; }
/**
* <p>The reason for the <code>SchemaExtensionStatus</code>.</p>
*/
inline void SetSchemaExtensionStatusReason(Aws::String&& value) { m_schemaExtensionStatusReasonHasBeenSet = true; m_schemaExtensionStatusReason = std::move(value); }
/**
* <p>The reason for the <code>SchemaExtensionStatus</code>.</p>
*/
inline void SetSchemaExtensionStatusReason(const char* value) { m_schemaExtensionStatusReasonHasBeenSet = true; m_schemaExtensionStatusReason.assign(value); }
/**
* <p>The reason for the <code>SchemaExtensionStatus</code>.</p>
*/
inline SchemaExtensionInfo& WithSchemaExtensionStatusReason(const Aws::String& value) { SetSchemaExtensionStatusReason(value); return *this;}
/**
* <p>The reason for the <code>SchemaExtensionStatus</code>.</p>
*/
inline SchemaExtensionInfo& WithSchemaExtensionStatusReason(Aws::String&& value) { SetSchemaExtensionStatusReason(std::move(value)); return *this;}
/**
* <p>The reason for the <code>SchemaExtensionStatus</code>.</p>
*/
inline SchemaExtensionInfo& WithSchemaExtensionStatusReason(const char* value) { SetSchemaExtensionStatusReason(value); return *this;}
/**
* <p>The date and time that the schema extension started being applied to the
* directory.</p>
*/
inline const Aws::Utils::DateTime& GetStartDateTime() const{ return m_startDateTime; }
/**
* <p>The date and time that the schema extension started being applied to the
* directory.</p>
*/
inline bool StartDateTimeHasBeenSet() const { return m_startDateTimeHasBeenSet; }
/**
* <p>The date and time that the schema extension started being applied to the
* directory.</p>
*/
inline void SetStartDateTime(const Aws::Utils::DateTime& value) { m_startDateTimeHasBeenSet = true; m_startDateTime = value; }
/**
* <p>The date and time that the schema extension started being applied to the
* directory.</p>
*/
inline void SetStartDateTime(Aws::Utils::DateTime&& value) { m_startDateTimeHasBeenSet = true; m_startDateTime = std::move(value); }
/**
* <p>The date and time that the schema extension started being applied to the
* directory.</p>
*/
inline SchemaExtensionInfo& WithStartDateTime(const Aws::Utils::DateTime& value) { SetStartDateTime(value); return *this;}
/**
* <p>The date and time that the schema extension started being applied to the
* directory.</p>
*/
inline SchemaExtensionInfo& WithStartDateTime(Aws::Utils::DateTime&& value) { SetStartDateTime(std::move(value)); return *this;}
/**
* <p>The date and time that the schema extension was completed.</p>
*/
inline const Aws::Utils::DateTime& GetEndDateTime() const{ return m_endDateTime; }
/**
* <p>The date and time that the schema extension was completed.</p>
*/
inline bool EndDateTimeHasBeenSet() const { return m_endDateTimeHasBeenSet; }
/**
* <p>The date and time that the schema extension was completed.</p>
*/
inline void SetEndDateTime(const Aws::Utils::DateTime& value) { m_endDateTimeHasBeenSet = true; m_endDateTime = value; }
/**
* <p>The date and time that the schema extension was completed.</p>
*/
inline void SetEndDateTime(Aws::Utils::DateTime&& value) { m_endDateTimeHasBeenSet = true; m_endDateTime = std::move(value); }
/**
* <p>The date and time that the schema extension was completed.</p>
*/
inline SchemaExtensionInfo& WithEndDateTime(const Aws::Utils::DateTime& value) { SetEndDateTime(value); return *this;}
/**
* <p>The date and time that the schema extension was completed.</p>
*/
inline SchemaExtensionInfo& WithEndDateTime(Aws::Utils::DateTime&& value) { SetEndDateTime(std::move(value)); return *this;}
private:
Aws::String m_directoryId;
bool m_directoryIdHasBeenSet;
Aws::String m_schemaExtensionId;
bool m_schemaExtensionIdHasBeenSet;
Aws::String m_description;
bool m_descriptionHasBeenSet;
SchemaExtensionStatus m_schemaExtensionStatus;
bool m_schemaExtensionStatusHasBeenSet;
Aws::String m_schemaExtensionStatusReason;
bool m_schemaExtensionStatusReasonHasBeenSet;
Aws::Utils::DateTime m_startDateTime;
bool m_startDateTimeHasBeenSet;
Aws::Utils::DateTime m_endDateTime;
bool m_endDateTimeHasBeenSet;
};
} // namespace Model
} // namespace DirectoryService
} // namespace Aws
| 36.44713 | 169 | 0.691893 | [
"model"
] |
08339c0d65d748599be66894a713464ebec4bd1f | 2,114 | h | C | src/src/lib/geneial/utility/ThreadedExecutionManager.h | geneial/geneial | 5e525c32b7c1e1e88788644e448e9234c93b55e2 | [
"MIT"
] | 5 | 2015-08-25T15:40:09.000Z | 2020-03-15T19:33:22.000Z | src/src/lib/geneial/utility/ThreadedExecutionManager.h | geneial/geneial | 5e525c32b7c1e1e88788644e448e9234c93b55e2 | [
"MIT"
] | null | null | null | src/src/lib/geneial/utility/ThreadedExecutionManager.h | geneial/geneial | 5e525c32b7c1e1e88788644e448e9234c93b55e2 | [
"MIT"
] | 3 | 2019-01-24T13:14:51.000Z | 2022-01-03T07:30:20.000Z | #pragma once
#include <geneial/utility/ExecutionManager.h>
#include <iostream>
#include <deque>
#include <memory>
#include <functional>
#include <chrono>
#include <thread>
#include <mutex>
#include <condition_variable>
#include <future>
#include <list>
geneial_private_namespace(geneial)
{
geneial_private_namespace(utility)
{
geneial_export_namespace
{
class ThreadedExecutionManager: public BaseExecutionManager
{
private:
std::deque<std::function<void()>> _tasks;
int _activeTasks = 0;
std::vector<std::shared_ptr<std::thread>> _threads;
std::mutex _mutex;
std::condition_variable _condEntry;
std::condition_variable _condExit;
bool _finish;
void inline executor();
void inline initializeThreads(const unsigned int amountThreads);
unsigned int _amountPerThread = 1;
public:
explicit ThreadedExecutionManager(const unsigned int amountThreads) :
_tasks(), _threads(), _mutex(), _condEntry(), _finish(false),_amountPerThread(1)
{
initializeThreads(amountThreads);
}
ThreadedExecutionManager() :
_tasks(), _threads(), _mutex(), _condEntry(), _finish(false),_amountPerThread(1)
{
initializeThreads(
std::max(static_cast<unsigned int>(1),
static_cast<unsigned int>(std::thread::hardware_concurrency() - 1)));
}
virtual ~ThreadedExecutionManager()
{
joinAll();
}
virtual inline void addTask(std::function<void()> const &task) override;
virtual inline void waitForTasks() override;
void inline joinAll();
unsigned int getAmountPerThread() const
{
return _amountPerThread;
}
/**
* Determines the work bucket size for one thread,
* i.e. how much work does one thread do until the thread syncs again.
*/
void setAmountPerThread(unsigned int amountPerThread = 1)
{
_amountPerThread = amountPerThread;
}
};
} /* geneial_export_namespace */
} /* private namespace utility */
} /* private namespace geneial */
#include <geneial/utility/ThreadedExecutionManager.hpp>
| 22.489362 | 93 | 0.683065 | [
"vector"
] |
083b1bc3d67b6f0570ea0e177e406043d4c1f2ff | 51,352 | c | C | cas/client.c | yatin-mahajan/cortx-motr-1 | edf4b0e8adf9aabbeb9f8e723e6d9eaa4f7c1391 | [
"Apache-2.0"
] | 1 | 2022-03-12T04:54:49.000Z | 2022-03-12T04:54:49.000Z | cas/client.c | mbcortx/cortx-motr | 8d45476d627d0f82047e88dff317db64cc142f58 | [
"Apache-2.0"
] | null | null | null | cas/client.c | mbcortx/cortx-motr | 8d45476d627d0f82047e88dff317db64cc142f58 | [
"Apache-2.0"
] | null | null | null | /* -*- C -*- */
/*
* Copyright (c) 2016-2020 Seagate Technology LLC and/or its Affiliates
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* For any questions about this software or licensing,
* please email opensource@seagate.com or cortx-questions@seagate.com.
*
*/
#define M0_TRACE_SUBSYSTEM M0_TRACE_SUBSYS_CAS
#include "lib/trace.h"
#include "lib/vec.h"
#include "lib/misc.h" /* M0_IN */
#include "lib/memory.h"
#include "sm/sm.h"
#include "fid/fid.h" /* m0_fid */
#include "rpc/item.h"
#include "rpc/rpc.h" /* m0_rpc_post */
#include "rpc/session.h" /* m0_rpc_session */
#include "rpc/conn.h" /* m0_rpc_conn */
#include "fop/fop.h"
#include "fop/fom_generic.h"
#include "cas/cas.h"
#include "cas/cas_xc.h"
#include "cas/client.h"
#include "lib/finject.h"
#include "cas/cas_addb2.h"
#include "dtm0/dtx.h" /* struct m0_dtm0_dtx */
/**
* @addtogroup cas-client
* @{
*/
/**
* Iterator to walk over responses for CUR request.
*
* On every iteration two values are updated:
* - Response record (creq_niter::cni_rep).
* - Request record (creq_niter::cni_req) containing starting key related to
* response record.
*
* Usually there are several response records for one request record.
* See m0_cas_rec::cr_rc for more information about CUR reply format.
*/
struct creq_niter {
/** Current iteration values accessible by user. */
struct m0_cas_rec *cni_req;
struct m0_cas_rec *cni_rep;
/** Private fields. */
struct m0_cas_recv *cni_reqv;
struct m0_cas_recv *cni_repv;
uint64_t cni_req_i;
uint64_t cni_rep_i;
uint64_t cni_kpos;
};
#define CASREQ_FOP_DATA(fop) ((struct m0_cas_op *)m0_fop_data(fop))
static void cas_req_replied_cb(struct m0_rpc_item *item);
static const struct m0_rpc_item_ops cas_item_ops = {
.rio_sent = NULL,
.rio_replied = cas_req_replied_cb
};
static void creq_asmbl_replied_cb(struct m0_rpc_item *item);
static const struct m0_rpc_item_ops asmbl_item_ops = {
.rio_sent = NULL,
.rio_replied = creq_asmbl_replied_cb
};
static struct m0_sm_state_descr cas_req_states[] = {
[CASREQ_INIT] = {
.sd_flags = M0_SDF_INITIAL | M0_SDF_FINAL,
.sd_name = "init",
.sd_allowed = M0_BITS(CASREQ_SENT, CASREQ_FRAGM_SENT)
},
[CASREQ_SENT] = {
.sd_name = "request-sent",
.sd_allowed = M0_BITS(CASREQ_FINAL, CASREQ_FAILURE,
CASREQ_ASSEMBLY),
},
[CASREQ_FRAGM_SENT] = {
.sd_name = "request-fragment-sent",
.sd_allowed = M0_BITS(CASREQ_FINAL, CASREQ_FAILURE,
CASREQ_ASSEMBLY),
},
[CASREQ_ASSEMBLY] = {
.sd_name = "assembly",
.sd_allowed = M0_BITS(CASREQ_FRAGM_SENT, CASREQ_FINAL,
CASREQ_FAILURE),
},
[CASREQ_FINAL] = {
.sd_name = "final",
.sd_flags = M0_SDF_TERMINAL,
},
[CASREQ_FAILURE] = {
.sd_name = "failure",
.sd_flags = M0_SDF_TERMINAL | M0_SDF_FAILURE
}
};
static struct m0_sm_trans_descr cas_req_trans[] = {
{ "send-over-rpc", CASREQ_INIT, CASREQ_SENT },
{ "send-fragm-over-rpc", CASREQ_INIT, CASREQ_FRAGM_SENT },
{ "rpc-failure", CASREQ_SENT, CASREQ_FAILURE },
{ "assembly", CASREQ_SENT, CASREQ_ASSEMBLY },
{ "req-processed", CASREQ_SENT, CASREQ_FINAL },
{ "rpc-failure", CASREQ_FRAGM_SENT, CASREQ_FAILURE },
{ "fragm-assembly", CASREQ_FRAGM_SENT, CASREQ_ASSEMBLY },
{ "req-processed", CASREQ_FRAGM_SENT, CASREQ_FINAL },
{ "assembly-fail", CASREQ_ASSEMBLY, CASREQ_FAILURE },
{ "assembly-done", CASREQ_ASSEMBLY, CASREQ_FINAL },
{ "assembly-fragm", CASREQ_ASSEMBLY, CASREQ_FRAGM_SENT },
};
struct m0_sm_conf cas_req_sm_conf = {
.scf_name = "cas_req",
.scf_nr_states = ARRAY_SIZE(cas_req_states),
.scf_state = cas_req_states,
.scf_trans_nr = ARRAY_SIZE(cas_req_trans),
.scf_trans = cas_req_trans
};
static int cas_req_fragmentation(struct m0_cas_req *req);
static int cas_req_fragment_continue(struct m0_cas_req *req,
struct m0_cas_op *op);
static void creq_recv_fini(struct m0_cas_recv *recv, bool op_is_meta);
static void cas_to_rpc_map(const struct m0_cas_req *creq,
const struct m0_rpc_item *item)
{
uint64_t cid = m0_sm_id_get(&creq->ccr_sm);
uint64_t iid = m0_sm_id_get(&item->ri_sm);
M0_ADDB2_ADD(M0_AVI_CAS_TO_RPC, cid, iid);
}
static bool fid_is_meta(struct m0_fid *fid)
{
M0_PRE(fid != NULL);
return m0_fid_eq(fid, &m0_cas_meta_fid);
}
static int creq_op_alloc(uint64_t recs_nr,
struct m0_cas_op **out)
{
struct m0_cas_op *op;
struct m0_cas_rec *rec;
M0_PRE(recs_nr > 0);
if (M0_FI_ENABLED("cas_alloc_fail"))
return M0_ERR(-ENOMEM);
M0_ALLOC_PTR(op);
M0_ALLOC_ARR(rec, recs_nr);
if (op == NULL || rec == NULL) {
m0_free(op);
m0_free(rec);
return M0_ERR(-ENOMEM);
} else {
op->cg_rec.cr_nr = recs_nr;
op->cg_rec.cr_rec = rec;
m0_dtm0_tx_desc_init_none(&op->cg_txd);
*out = op;
}
return M0_RC(0);
}
static void creq_op_free(struct m0_cas_op *op)
{
if (op != NULL) {
m0_dtm0_tx_desc_fini(&op->cg_txd);
m0_free(op->cg_rec.cr_rec);
m0_free(op);
}
}
M0_INTERNAL void m0_cas_req_init(struct m0_cas_req *req,
struct m0_rpc_session *sess,
struct m0_sm_group *grp)
{
M0_ENTRY();
M0_PRE(sess != NULL);
M0_PRE(M0_IS0(req));
req->ccr_sess = sess;
m0_sm_init(&req->ccr_sm, &cas_req_sm_conf, CASREQ_INIT, grp);
m0_sm_addb2_counter_init(&req->ccr_sm);
M0_LEAVE();
}
static struct m0_rpc_conn *creq_rpc_conn(const struct m0_cas_req *req)
{
return req->ccr_sess->s_conn;
}
static struct m0_rpc_machine *creq_rpc_mach(const struct m0_cas_req *req)
{
return creq_rpc_conn(req)->c_rpc_machine;
}
static struct m0_sm_group *cas_req_smgrp(const struct m0_cas_req *req)
{
return req->ccr_sm.sm_grp;
}
M0_INTERNAL void m0_cas_req_lock(struct m0_cas_req *req)
{
M0_ENTRY();
m0_sm_group_lock(cas_req_smgrp(req));
}
M0_INTERNAL void m0_cas_req_unlock(struct m0_cas_req *req)
{
M0_ENTRY();
m0_sm_group_unlock(cas_req_smgrp(req));
}
M0_INTERNAL bool m0_cas_req_is_locked(const struct m0_cas_req *req)
{
return m0_mutex_is_locked(&cas_req_smgrp(req)->s_lock);
}
static void cas_req_state_set(struct m0_cas_req *req,
enum m0_cas_req_state state)
{
M0_LOG(M0_DEBUG, "CAS req: %p, state change:[%s -> %s]\n",
req, m0_sm_state_name(&req->ccr_sm, req->ccr_sm.sm_state),
m0_sm_state_name(&req->ccr_sm, state));
m0_sm_state_set(&req->ccr_sm, state);
}
static void cas_req_reply_fini(struct m0_cas_req *req)
{
struct m0_cas_recv *recv = &req->ccr_reply.cgr_rep;
uint64_t i;
for (i = 0; i < recv->cr_nr; i++) {
m0_rpc_at_fini(&recv->cr_rec[i].cr_key);
m0_rpc_at_fini(&recv->cr_rec[i].cr_val);
}
m0_free(req->ccr_reply.cgr_rep.cr_rec);
}
static void cas_req_fini(struct m0_cas_req *req)
{
uint32_t cur_state = req->ccr_sm.sm_state;
M0_ENTRY();
M0_PRE(m0_cas_req_is_locked(req));
M0_PRE(M0_IN(cur_state, (CASREQ_INIT, CASREQ_FINAL, CASREQ_FAILURE)));
if (cur_state == CASREQ_FAILURE) {
if (req->ccr_reply_item != NULL)
m0_rpc_item_put_lock(req->ccr_reply_item);
if (req->ccr_fop != NULL) {
req->ccr_fop->f_data.fd_data = NULL;
m0_fop_put_lock(req->ccr_fop);
}
}
if (req->ccr_req_op != NULL) {
/* Restore records vector for proper freeing. */
req->ccr_req_op->cg_rec = req->ccr_rec_orig;
creq_recv_fini(&req->ccr_rec_orig, req->ccr_is_meta);
creq_op_free(req->ccr_req_op);
}
cas_req_reply_fini(req);
m0_free(req->ccr_asmbl_ikeys);
m0_sm_fini(&req->ccr_sm);
M0_LEAVE();
}
M0_INTERNAL void m0_cas_req_fini(struct m0_cas_req *req)
{
M0_PRE(m0_cas_req_is_locked(req));
cas_req_fini(req);
M0_SET0(req);
}
M0_INTERNAL void m0_cas_req_fini_lock(struct m0_cas_req *req)
{
M0_ENTRY();
m0_cas_req_lock(req);
cas_req_fini(req);
m0_cas_req_unlock(req);
M0_SET0(req);
M0_LEAVE();
}
/**
* Assigns pointers to record key/value to NULL, so they are not
* deallocated during RPC AT buffer finalisation. User is responsible for
* their deallocation.
*/
static void creq_kv_hold_down(struct m0_cas_rec *rec)
{
struct m0_rpc_at_buf *key = &rec->cr_key;
struct m0_rpc_at_buf *val = &rec->cr_val;
M0_ENTRY();
M0_PRE(!m0_rpc_at_is_set(key) ||
M0_IN(key->ab_type, (M0_RPC_AT_INLINE, M0_RPC_AT_BULK_SEND)));
if (m0_rpc_at_is_set(key))
m0_rpc_at_detach(key);
if (m0_rpc_at_is_set(val))
m0_rpc_at_detach(val);
M0_LEAVE();
}
/**
* Finalises CAS record vector that is intended to be sent as part of the
* CAS request.
*/
static void creq_recv_fini(struct m0_cas_recv *recv, bool op_is_meta)
{
struct m0_cas_rec *rec;
struct m0_cas_kv *kv;
uint64_t i;
uint64_t k;
for (i = 0; i < recv->cr_nr; i++) {
rec = &recv->cr_rec[i];
/*
* CAS client does not copy keys/values provided by user if
* it works with non-meta index, otherwise it encodes keys
* and places them in buffers allocated by itself.
* Save keys/values in memory in the first case, free in
* the second.
*/
if (!op_is_meta)
creq_kv_hold_down(rec);
m0_rpc_at_fini(&rec->cr_key);
m0_rpc_at_fini(&rec->cr_val);
for (k = 0; k < rec->cr_kv_bufs.cv_nr; k++) {
kv = &rec->cr_kv_bufs.cv_rec[k];
m0_rpc_at_fini(&kv->ck_key);
m0_rpc_at_fini(&kv->ck_val);
}
}
}
static void creq_fop_destroy(struct m0_cas_req *req)
{
struct m0_fop *fop = req->ccr_fop;
fop->f_data.fd_data = NULL;
m0_fop_fini(fop);
m0_free(fop);
req->ccr_fop = NULL;
}
static void creq_fop_release(struct m0_ref *ref)
{
struct m0_fop *fop;
M0_ENTRY();
M0_PRE(ref != NULL);
fop = container_of(ref, struct m0_fop, f_ref);
m0_fop_fini(fop);
m0_free(fop);
M0_LEAVE();
}
static void creq_asmbl_fop_release(struct m0_ref *ref)
{
struct m0_fop *fop;
struct m0_cas_op *op;
M0_ENTRY();
M0_PRE(ref != NULL);
fop = container_of(ref, struct m0_fop, f_ref);
op = CASREQ_FOP_DATA(fop);
creq_recv_fini(&op->cg_rec, fid_is_meta(&op->cg_id.ci_fid));
m0_fop_fini(fop);
M0_LEAVE();
}
static int creq_fop_create(struct m0_cas_req *req,
struct m0_fop_type *ftype,
struct m0_cas_op *op)
{
struct m0_fop *fop;
M0_ENTRY();
M0_ALLOC_PTR(fop);
if (fop == NULL)
return M0_ERR(-ENOMEM);
m0_fop_init(fop, ftype, (void *)op, creq_fop_release);
fop->f_opaque = req;
req->ccr_fop = fop;
req->ccr_ftype = ftype;
M0_LEAVE("cas_req=%p fop=%p", req, fop);
return 0;
}
static int creq_fop_create_and_prepare(struct m0_cas_req *req,
struct m0_fop_type *ftype,
struct m0_cas_op *op,
enum m0_cas_req_state *next_state)
{
int rc;
M0_ENTRY();
rc = creq_fop_create(req, ftype, op);
if (rc == 0) {
*next_state = CASREQ_SENT;
/*
* Check whether original fop payload does not exceed
* max rpc item payload.
*/
if (m0_rpc_item_max_payload_exceeded(
&req->ccr_fop->f_item,
req->ccr_sess)) {
*next_state = CASREQ_FRAGM_SENT;
rc = cas_req_fragmentation(req);
}
if (rc != 0)
creq_fop_destroy(req);
}
return M0_RC(rc);
}
static struct m0_cas_req *item_to_cas_req(struct m0_rpc_item *item)
{
struct m0_fop *fop = M0_AMB(fop, item, f_item);
return (struct m0_cas_req *)fop->f_opaque;
}
static struct m0_rpc_item *cas_req_to_item(const struct m0_cas_req *req)
{
return &req->ccr_fop->f_item;
}
static struct m0_cas_rep *cas_rep(struct m0_rpc_item *reply)
{
return m0_fop_data(m0_rpc_item_to_fop(reply));
}
M0_INTERNAL int m0_cas_req_generic_rc(const struct m0_cas_req *req)
{
struct m0_fop *req_fop = req->ccr_fop;
struct m0_rpc_item *reply;
int rc;
M0_PRE(M0_IN(req->ccr_sm.sm_state, (CASREQ_FINAL, CASREQ_FAILURE)));
reply = req_fop != NULL ? cas_req_to_item(req)->ri_reply : NULL;
rc = req->ccr_sm.sm_rc;
if (rc == 0 && reply != NULL)
rc = m0_rpc_item_generic_reply_rc(reply);
if (rc == 0)
rc = req->ccr_reply.cgr_rc;
return M0_RC(rc);
}
static bool cas_rep_val_is_valid(struct m0_rpc_at_buf *val,
struct m0_fid *idx_fid)
{
return m0_rpc_at_is_set(val) == !fid_is_meta(idx_fid);
}
static int cas_rep__validate(const struct m0_fop_type *ftype,
struct m0_cas_op *op,
struct m0_cas_rep *rep)
{
struct m0_cas_rec *rec;
uint64_t sum;
uint64_t i;
if (ftype == &cas_cur_fopt) {
sum = 0;
for (i = 0; i < op->cg_rec.cr_nr; i++)
sum += op->cg_rec.cr_rec[i].cr_rc;
if (rep->cgr_rep.cr_nr > sum)
return M0_ERR(-EPROTO);
for (i = 0; i < rep->cgr_rep.cr_nr; i++) {
rec = &rep->cgr_rep.cr_rec[i];
if ((int32_t)rec->cr_rc > 0 &&
(!m0_rpc_at_is_set(&rec->cr_key) ||
!cas_rep_val_is_valid(&rec->cr_val,
&op->cg_id.ci_fid)))
rec->cr_rc = M0_ERR(-EPROTO);
}
} else {
M0_ASSERT(M0_IN(ftype, (&cas_get_fopt, &cas_put_fopt,
&cas_del_fopt)));
/*
* CAS service guarantees equal number of records in request and
* response for GET,PUT, DEL operations. Otherwise, it's not
* possible to match requested records with the ones in reply,
* because keys in reply are absent.
*/
if (op->cg_rec.cr_nr != rep->cgr_rep.cr_nr)
return M0_ERR(-EPROTO);
/*
* Successful GET reply for ordinary index should always contain
* non-empty value.
*/
if (ftype == &cas_get_fopt)
for (i = 0; i < rep->cgr_rep.cr_nr; i++) {
rec = &rep->cgr_rep.cr_rec[i];
if (rec->cr_rc == 0 &&
!cas_rep_val_is_valid(&rec->cr_val,
&op->cg_id.ci_fid))
rec->cr_rc = M0_ERR(-EPROTO);
}
}
return M0_RC(0);
}
static int cas_rep_validate(const struct m0_cas_req *req)
{
const struct m0_fop *rfop = req->ccr_fop;
struct m0_cas_op *op = m0_fop_data(rfop);
struct m0_cas_rep *rep = cas_rep(cas_req_to_item(req)->ri_reply);
return rep->cgr_rc ?: cas_rep__validate(rfop->f_type, op, rep);
}
static void cas_req_failure(struct m0_cas_req *req, int32_t rc)
{
M0_PRE(rc != 0);
m0_sm_fail(&req->ccr_sm, CASREQ_FAILURE, rc);
}
static void cas_req_failure_ast(struct m0_sm_group *grp, struct m0_sm_ast *ast)
{
struct m0_cas_req *req = container_of(ast, struct m0_cas_req,
ccr_failure_ast);
int32_t rc = (long)ast->sa_datum;
M0_PRE(rc != 0);
cas_req_failure(req, M0_ERR(rc));
}
static void cas_req_failure_ast_post(struct m0_cas_req *req, int32_t rc)
{
M0_ENTRY();
req->ccr_failure_ast.sa_cb = cas_req_failure_ast;
req->ccr_failure_ast.sa_datum = (void *)(long)rc;
m0_sm_ast_post(cas_req_smgrp(req), &req->ccr_failure_ast);
M0_LEAVE();
}
static void creq_item_prepare(const struct m0_cas_req *req,
struct m0_rpc_item *item,
const struct m0_rpc_item_ops *ops)
{
item->ri_rmachine = creq_rpc_mach(req);
item->ri_ops = ops;
item->ri_session = req->ccr_sess;
item->ri_prio = M0_RPC_ITEM_PRIO_MID;
item->ri_deadline = M0_TIME_IMMEDIATELY;
}
static void cas_fop_send(struct m0_cas_req *req)
{
struct m0_cas_op *op = m0_fop_data(req->ccr_fop);
struct m0_rpc_item *item;
int rc;
M0_ENTRY();
M0_PRE(m0_cas_req_is_locked(req));
req->ccr_sent_recs_nr += op->cg_rec.cr_nr;
item = cas_req_to_item(req);
creq_item_prepare(req, item, &cas_item_ops);
rc = m0_rpc_post(item);
cas_to_rpc_map(req, item);
M0_LOG(M0_NOTICE, "RPC post returned %d", rc);
}
static int creq_kv_buf_add(const struct m0_cas_req *req,
const struct m0_bufvec *kv,
uint32_t idx,
struct m0_rpc_at_buf *buf)
{
M0_PRE(req != NULL);
M0_PRE(kv != NULL);
M0_PRE(buf != NULL);
M0_PRE(idx < kv->ov_vec.v_nr);
return m0_rpc_at_add(buf, &M0_BUF_INIT(kv->ov_vec.v_count[idx],
kv->ov_buf[idx]),
creq_rpc_conn(req));
}
static void creq_asmbl_fop_init(struct m0_cas_req *req,
struct m0_fop_type *ftype,
struct m0_cas_op *op)
{
m0_fop_init(&req->ccr_asmbl_fop, ftype, (void *)op,
creq_asmbl_fop_release);
}
/**
* Fills outgoing record 'rec' that is a part of an assembly FOP.
*
* Key/value data is assigned from original GET request. Indices of records in
* original and assembly requests may be different, 'idx' is an index of a
* record in assembly request and 'orig_idx' is an index of a record in original
* GET request that should be re-requested.
*/
static int greq_asmbl_add(struct m0_cas_req *req,
struct m0_cas_rec *rec,
uint64_t idx,
uint64_t orig_idx,
uint64_t vlen)
{
int rc;
m0_rpc_at_init(&rec->cr_key);
m0_rpc_at_init(&rec->cr_val);
rc = creq_kv_buf_add(req, req->ccr_keys, orig_idx, &rec->cr_key) ?:
m0_rpc_at_recv(&rec->cr_val, creq_rpc_conn(req), vlen, true);
if (rc == 0) {
req->ccr_asmbl_ikeys[idx] = orig_idx;
} else {
m0_rpc_at_detach(&rec->cr_key);
m0_rpc_at_fini(&rec->cr_key);
m0_rpc_at_fini(&rec->cr_val);
}
return M0_RC(rc);
}
/**
* Returns number of records that should be re-requested via assembly request.
*/
static uint64_t greq_asmbl_count(const struct m0_cas_req *req)
{
const struct m0_fop *rfop = req->ccr_fop;
struct m0_cas_op *req_op = m0_fop_data(rfop);
struct m0_cas_rep *rep = cas_rep(cas_req_to_item(req)->ri_reply);
struct m0_cas_rec *rcvd;
struct m0_cas_rec *sent;
struct m0_buf buf;
uint64_t len;
uint64_t ret = 0;
uint64_t i;
int rc;
M0_PRE(rfop->f_type == &cas_get_fopt);
for (i = 0; i < rep->cgr_rep.cr_nr; i++) {
rcvd = &rep->cgr_rep.cr_rec[i];
sent = &req_op->cg_rec.cr_rec[i];
rc = m0_rpc_at_rep_get(&sent->cr_val, &rcvd->cr_val, &buf);
if (rc != 0 && m0_rpc_at_rep_is_bulk(&rcvd->cr_val, &len))
ret++;
}
return ret;
}
static int greq_asmbl_fill(struct m0_cas_req *req, struct m0_cas_op *op)
{
const struct m0_fop *rfop = req->ccr_fop;
struct m0_cas_op *req_op = m0_fop_data(rfop);
struct m0_cas_rep *rep = cas_rep(cas_req_to_item(req)->ri_reply);
struct m0_cas_rec *rcvd;
struct m0_cas_rec *sent;
struct m0_buf buf;
struct m0_cas_recv *recv;
uint64_t len;
uint64_t i;
uint64_t k = 0;
int rc = 0;
M0_PRE(op != NULL);
M0_PRE(rfop->f_type == &cas_get_fopt);
recv = &op->cg_rec;
op->cg_id = req_op->cg_id;
for (i = 0; i < rep->cgr_rep.cr_nr; i++) {
rcvd = &rep->cgr_rep.cr_rec[i];
sent = &req_op->cg_rec.cr_rec[i];
rc = m0_rpc_at_rep_get(&sent->cr_val, &rcvd->cr_val, &buf);
if (rc != 0 && m0_rpc_at_rep_is_bulk(&rcvd->cr_val, &len)) {
M0_PRE(k < recv->cr_nr);
rc = greq_asmbl_add(req, &recv->cr_rec[k], k, i, len);
if (rc != 0)
goto err;
k++;
}
}
err:
if (rc != 0) {
/* Finalise all already initialised records. */
recv->cr_nr = k;
creq_recv_fini(recv, fid_is_meta(&op->cg_id.ci_fid));
}
return M0_RC(rc);
}
static bool greq_asmbl_post(struct m0_cas_req *req)
{
struct m0_cas_op *op = NULL;
struct m0_rpc_item *item = &req->ccr_asmbl_fop.f_item;
uint64_t asmbl_count;
bool ret = false;
int rc = 0;
asmbl_count = greq_asmbl_count(req);
if (asmbl_count > 0) {
M0_ALLOC_ARR(req->ccr_asmbl_ikeys, asmbl_count);
if (req->ccr_asmbl_ikeys == NULL) {
rc = M0_ERR(-ENOMEM);
goto err;
}
rc = creq_op_alloc(asmbl_count, &op) ?:
greq_asmbl_fill(req, op);
if (rc == 0) {
creq_asmbl_fop_init(req, &cas_get_fopt, op);
creq_item_prepare(req, item, &asmbl_item_ops);
rc = m0_rpc_post(item);
cas_to_rpc_map(req, item);
if (rc != 0)
m0_fop_put_lock(&req->ccr_asmbl_fop);
else
ret = true;
}
}
err:
if (rc != 0) {
m0_free(req->ccr_asmbl_ikeys);
creq_op_free(op);
}
return ret;
}
static bool creq_niter_invariant(struct creq_niter *it)
{
return it->cni_req_i <= it->cni_reqv->cr_nr &&
it->cni_rep_i <= it->cni_repv->cr_nr;
}
static void creq_niter_init(struct creq_niter *it,
struct m0_cas_op *op,
struct m0_cas_rep *rep)
{
it->cni_reqv = &op->cg_rec;
it->cni_repv = &rep->cgr_rep;
it->cni_req_i = 0;
it->cni_rep_i = 0;
it->cni_kpos = -1;
it->cni_req = NULL;
it->cni_rep = NULL;
}
static int creq_niter_next(struct creq_niter *it)
{
int rc = 0;
M0_PRE(creq_niter_invariant(it));
if (it->cni_rep_i == it->cni_repv->cr_nr)
rc = -ENOENT;
if (rc == 0) {
it->cni_rep = &it->cni_repv->cr_rec[it->cni_rep_i++];
it->cni_kpos++;
if (it->cni_rep->cr_rc == 1 ||
((int32_t)it->cni_rep->cr_rc <= 0 && it->cni_req_i == 0) ||
it->cni_kpos == it->cni_req->cr_rc) {
/** @todo Validate it. */
M0_PRE(it->cni_req_i < it->cni_reqv->cr_nr);
it->cni_req = &it->cni_reqv->cr_rec[it->cni_req_i];
it->cni_req_i++;
it->cni_kpos = 0;
}
}
M0_POST(creq_niter_invariant(it));
return M0_RC(rc);
}
static void creq_niter_fini(struct creq_niter *it)
{
M0_SET0(it);
}
/**
* Sets starting keys and allocates space for key/values AT buffers expected in
* reply.
*/
static int nreq_asmbl_prep(struct m0_cas_req *req, struct m0_cas_op *op)
{
struct m0_cas_op *orig = m0_fop_data(req->ccr_fop);
struct m0_cas_rec *rec;
uint64_t i;
int rc = 0;
M0_PRE(op->cg_rec.cr_nr == orig->cg_rec.cr_nr);
op->cg_id = orig->cg_id;
for (i = 0; i < orig->cg_rec.cr_nr; i++) {
rec = &op->cg_rec.cr_rec[i];
M0_ASSERT(M0_IS0(rec));
rec->cr_rc = orig->cg_rec.cr_rec[i].cr_rc;
m0_rpc_at_init(&rec->cr_key);
rc = creq_kv_buf_add(req, req->ccr_keys, i, &rec->cr_key);
if (rc != 0)
goto err;
M0_ALLOC_ARR(rec->cr_kv_bufs.cv_rec, rec->cr_rc);
if (op->cg_rec.cr_rec[i].cr_kv_bufs.cv_rec == NULL) {
rc = M0_ERR(-ENOMEM);
goto err;
}
}
err:
if (rc != 0) {
/* Finalise all already initialised records. */
op->cg_rec.cr_nr = i + 1;
creq_recv_fini(&op->cg_rec, fid_is_meta(&op->cg_id.ci_fid));
}
return M0_RC(rc);
}
static int nreq_asmbl_fill(struct m0_cas_req *req, struct m0_cas_op *op)
{
const struct m0_fop *rfop = req->ccr_fop;
struct m0_cas_rep *reply = cas_rep(cas_req_to_item(req)->ri_reply);
struct m0_cas_rec *rep;
struct m0_cas_rec *rec;
struct m0_rpc_at_buf *key;
struct m0_rpc_at_buf *val;
struct creq_niter iter;
uint64_t klen;
uint64_t vlen;
bool bulk_key;
bool bulk_val;
int rc = 0;
uint64_t i;
M0_PRE(rfop->f_type == &cas_cur_fopt);
rc = nreq_asmbl_prep(req, op);
if (rc != 0)
return M0_ERR(rc);
/*
* 'op' is a copy of original request relative to starting keys,
* so iterator will iterate over 'op' the same way as with original
* request.
*/
creq_niter_init(&iter, op, reply);
while (creq_niter_next(&iter) != -ENOENT) {
rep = iter.cni_rep;
rec = iter.cni_req;
i = rec->cr_kv_bufs.cv_nr;
bulk_key = m0_rpc_at_rep_is_bulk(&rep->cr_key, &klen);
bulk_val = m0_rpc_at_rep_is_bulk(&rep->cr_val, &vlen);
key = &rec->cr_kv_bufs.cv_rec[i].ck_key;
val = &rec->cr_kv_bufs.cv_rec[i].ck_val;
m0_rpc_at_init(key);
m0_rpc_at_init(val);
rc = m0_rpc_at_recv(val, creq_rpc_conn(req), vlen, bulk_val) ?:
m0_rpc_at_recv(key, creq_rpc_conn(req), klen, bulk_key);
if (rc == 0) {
rec->cr_kv_bufs.cv_nr++;
} else {
m0_rpc_at_fini(key);
m0_rpc_at_fini(val);
break;
}
}
creq_niter_fini(&iter);
if (rc != 0)
creq_recv_fini(&op->cg_rec, fid_is_meta(&op->cg_id.ci_fid));
return M0_RC(rc);
}
static bool nreq_asmbl_post(struct m0_cas_req *req)
{
const struct m0_fop *rfop = req->ccr_fop;
struct m0_cas_op *req_op = m0_fop_data(rfop);
struct m0_cas_rep *rep = cas_rep(cas_req_to_item(req)->ri_reply);
struct m0_rpc_item *item = &req->ccr_asmbl_fop.f_item;
struct m0_cas_rec *rcvd;
struct m0_cas_rec *sent;
bool bulk = false;
struct m0_buf buf;
struct m0_cas_op *op;
int rc;
uint64_t len;
struct creq_niter iter;
creq_niter_init(&iter, req_op, rep);
while ((rc = creq_niter_next(&iter)) != -ENOENT) {
rcvd = iter.cni_rep;
sent = iter.cni_req;
M0_ASSERT(sent->cr_kv_bufs.cv_nr == 0);
rc = m0_rpc_at_rep_get(NULL, &rcvd->cr_key, &buf) ?:
m0_rpc_at_rep_get(NULL, &rcvd->cr_val, &buf);
if (rc != 0 && !bulk)
bulk = m0_rpc_at_rep_is_bulk(&rcvd->cr_key, &len) ||
m0_rpc_at_rep_is_bulk(&rcvd->cr_val, &len);
}
creq_niter_fini(&iter);
/*
* If at least one key/value requires bulk transmission, then
* resend the whole request, requesting bulk transmission as necessary.
*/
if (bulk) {
rc = creq_op_alloc(req_op->cg_rec.cr_nr, &op);
if (rc == 0) {
rc = nreq_asmbl_fill(req, op);
if (rc == 0) {
creq_asmbl_fop_init(req, &cas_cur_fopt, op);
creq_item_prepare(req, item, &asmbl_item_ops);
rc = m0_rpc_post(item);
cas_to_rpc_map(req, item);
if (rc != 0)
m0_fop_put_lock(&req->ccr_asmbl_fop);
} else {
creq_op_free(op);
bulk = false;
}
}
}
return bulk;
}
static void creq_rep_override(struct m0_cas_rec *orig,
struct m0_cas_rec *new)
{
M0_ENTRY();
m0_rpc_at_fini(&orig->cr_key);
m0_rpc_at_fini(&orig->cr_val);
*orig = *new;
/*
* Key/value data buffers are now attached to both records.
* Detach buffers from 'new' record to avoid double free.
*/
m0_rpc_at_detach(&new->cr_key);
m0_rpc_at_detach(&new->cr_val);
M0_LEAVE();
}
static void nreq_asmbl_accept(struct m0_cas_req *req)
{
struct m0_fop *fop = &req->ccr_asmbl_fop;
struct m0_rpc_item *item = &fop->f_item;
struct m0_cas_rep *crep = cas_rep(cas_req_to_item(req)->ri_reply);
struct m0_cas_rep *rep = m0_fop_data(m0_rpc_item_to_fop(
item->ri_reply));
struct m0_cas_rec *rcvd;
struct m0_cas_rec *sent;
struct m0_cas_op *op = m0_fop_data(fop);
struct m0_cas_kv *kv;
struct creq_niter iter;
uint64_t i;
int rc;
i = 0;
creq_niter_init(&iter, op, rep);
while (creq_niter_next(&iter) != -ENOENT) {
rcvd = iter.cni_rep;
sent = iter.cni_req;
if ((int32_t)rcvd->cr_rc > 0) {
/** @todo validate it */
M0_PRE(rcvd->cr_rc <= sent->cr_kv_bufs.cv_nr);
kv = &sent->cr_kv_bufs.cv_rec[rcvd->cr_rc - 1];
rc = m0_rpc_at_rep2inline(&kv->ck_key, &rcvd->cr_key) ?:
m0_rpc_at_rep2inline(&kv->ck_val, &rcvd->cr_val);
if (rc == 0)
creq_rep_override(&crep->cgr_rep.cr_rec[i],
rcvd);
}
i++;
}
creq_niter_fini(&iter);
}
static void greq_asmbl_accept(struct m0_cas_req *req)
{
struct m0_fop *fop = &req->ccr_asmbl_fop;
struct m0_rpc_item *item = &fop->f_item;
struct m0_cas_rep *crep = cas_rep(cas_req_to_item(req)->ri_reply);
struct m0_cas_rep *rep = m0_fop_data(m0_rpc_item_to_fop(
item->ri_reply));
struct m0_cas_rec *rec;
struct m0_cas_op *op = m0_fop_data(fop);
uint64_t i;
uint64_t orig_i;
int rc;
for (i = 0; i < rep->cgr_rep.cr_nr; i++) {
rec = &rep->cgr_rep.cr_rec[i];
if (rec->cr_rc == 0) {
rc = m0_rpc_at_rep2inline(&op->cg_rec.cr_rec[i].cr_val,
&rec->cr_val);
if (rc == 0) {
orig_i = req->ccr_asmbl_ikeys[i];
creq_rep_override(&crep->cgr_rep.cr_rec[orig_i],
rec);
}
}
}
}
/**
* Gets transacation identifier information from returned reply fop
* of an `UPDATE` op.
*/
static void cas_req_fsync_remid_copy(struct m0_cas_req *req)
{
struct m0_cas_rep *rep;
M0_PRE(req != NULL);
M0_PRE(req->ccr_fop != NULL);
rep = cas_rep(cas_req_to_item(req)->ri_reply);
M0_ASSERT(rep != NULL);
req->ccr_remid = rep->cgr_mod_rep.fmr_remid;
}
static int cas_req_reply_handle(struct m0_cas_req *req,
bool *fragm_continue)
{
struct m0_cas_rep *reply = &req->ccr_reply;
struct m0_cas_rep *rcvd_reply = cas_rep(req->ccr_reply_item);
struct m0_fop *req_fop = req->ccr_fop;
struct m0_cas_op *op = m0_fop_data(req_fop);
uint64_t i;
uint64_t reply_seed;
int rc = 0;
M0_ASSERT(req_fop->f_type == req->ccr_ftype);
M0_ASSERT(req->ccr_sent_recs_nr <= req->ccr_rec_orig.cr_nr);
M0_ASSERT(reply->cgr_rep.cr_nr + rcvd_reply->cgr_rep.cr_nr <=
req->ccr_max_replies_nr);
*fragm_continue = false;
/* Copy tx remid before fop and rpc item in `req` are set to NULL*/
cas_req_fsync_remid_copy(req);
/*
* Place reply buffers locally (without copying of actual data), zero
* them in reply fop to avoid their freeing during reply fop destroying.
*/
reply_seed = reply->cgr_rep.cr_nr;
for (i = 0; i < rcvd_reply->cgr_rep.cr_nr; i++) {
reply->cgr_rep.cr_rec[reply_seed + i] =
rcvd_reply->cgr_rep.cr_rec[i];
/* Detach buffers to avoid double-freeing of received data. */
creq_kv_hold_down(&rcvd_reply->cgr_rep.cr_rec[i]);
}
reply->cgr_rep.cr_nr += rcvd_reply->cgr_rep.cr_nr;
/* Roger, reply item is not needed anymore. */
m0_rpc_item_put_lock(req->ccr_reply_item);
req->ccr_reply_item = NULL;
/*
* Null fop data pointer to avoid cas_op freeing during fop finalisation
* as cas_op is going to be reused for the rest fragments sending.
*/
req_fop->f_data.fd_data = NULL;
m0_fop_put_lock(req_fop);
req->ccr_fop = NULL;
if (req->ccr_sent_recs_nr < req->ccr_rec_orig.cr_nr) {
/* Continue fragmentation. */
rc = cas_req_fragment_continue(req, op);
if (rc == 0)
*fragm_continue = true;
}
return rc;
}
static void creq_asmbl_replied_ast(struct m0_sm_group *grp,
struct m0_sm_ast *ast)
{
struct m0_cas_req *req = container_of(ast, struct m0_cas_req,
ccr_replied_ast);
struct m0_fop *fop = &req->ccr_asmbl_fop;
struct m0_rpc_item *item = &fop->f_item;
struct m0_rpc_item *reply = item->ri_reply;
bool fragm_continue;
int rc;
rc = m0_rpc_item_error(item) ?:
cas_rep(reply)->cgr_rc ?:
cas_rep__validate(fop->f_type, m0_fop_data(fop), cas_rep(reply));
if (rc == 0) {
M0_ASSERT(M0_IN(fop->f_type, (&cas_get_fopt, &cas_cur_fopt)));
if (fop->f_type == &cas_get_fopt)
greq_asmbl_accept(req);
else
nreq_asmbl_accept(req);
}
/*
* On assembly request error, just continue request processing.
* All records that were requested via assembly request already
* have error status code.
*/
rc = cas_req_reply_handle(req, &fragm_continue);
if (rc == 0)
cas_req_state_set(req, !fragm_continue ?
CASREQ_FINAL : CASREQ_FRAGM_SENT);
else
cas_req_failure(req, M0_ERR(rc));
m0_rpc_item_put_lock(item);
}
static void creq_asmbl_replied_cb(struct m0_rpc_item *item)
{
struct m0_cas_req *req = container_of(m0_rpc_item_to_fop(item),
struct m0_cas_req,
ccr_asmbl_fop);
M0_ENTRY();
req->ccr_replied_ast.sa_cb = creq_asmbl_replied_ast;
m0_sm_ast_post(cas_req_smgrp(req), &req->ccr_replied_ast);
M0_LEAVE();
}
static void cas_req_replied_ast(struct m0_sm_group *grp, struct m0_sm_ast *ast)
{
struct m0_cas_req *req = container_of(ast, struct m0_cas_req,
ccr_replied_ast);
struct m0_fop_type *req_fop_type = req->ccr_fop->f_type;
bool assembly_wait = false;
bool suppress_err_msg;
bool fragm_continue;
int rc;
req->ccr_reply.cgr_rc = cas_rep(req->ccr_reply_item)->cgr_rc;
rc = cas_rep_validate(req);
if (rc == 0) {
if (M0_IN(req_fop_type, (&cas_cur_fopt, &cas_get_fopt)) &&
!req->ccr_is_meta) {
assembly_wait = (req_fop_type == &cas_get_fopt) ?
greq_asmbl_post(req) : nreq_asmbl_post(req);
if (assembly_wait)
cas_req_state_set(req, CASREQ_ASSEMBLY);
}
if (!assembly_wait) {
rc = cas_req_reply_handle(req, &fragm_continue);
if (rc == 0 && !fragm_continue)
cas_req_state_set(req, CASREQ_FINAL);
}
}
if (rc != 0) {
/*
* For now CROW flag is commonly used for PUT operations. In
* this case indices are physically created only on the nodes
* where keys are presented. But NEXT queries are sent to all
* the nodes, so some of them may return -ENOENT (index does
* not exist). It is not critical, suppress these errors not
* to irritate the user.
*/
suppress_err_msg = !req->ccr_is_meta &&
req_fop_type == &cas_cur_fopt && rc == -ENOENT;
cas_req_failure(req, suppress_err_msg ? rc : M0_ERR(rc));
}
}
static void cas_req_replied_cb(struct m0_rpc_item *item)
{
struct m0_cas_req *req = item_to_cas_req(item);
M0_ENTRY();
if (M0_FI_ENABLED("send-failure"))
item->ri_error = -ENOTCONN;
if (item->ri_error == 0) {
M0_ASSERT(item->ri_reply != NULL);
req->ccr_reply_item = item->ri_reply;
/*
* Get additional reference to reply item to copy reply buffers
* in replied ast call.
*/
m0_rpc_item_get(item->ri_reply);
req->ccr_replied_ast.sa_cb = cas_req_replied_ast;
m0_sm_ast_post(cas_req_smgrp(req), &req->ccr_replied_ast);
} else
cas_req_failure_ast_post(req, item->ri_error);
M0_LEAVE();
}
static int cas_index_op_prepare(const struct m0_cas_req *req,
const struct m0_cas_id *cids,
uint64_t cids_nr,
bool recv_val,
uint32_t flags,
struct m0_cas_op **out)
{
struct m0_cas_op *op;
struct m0_cas_rec *rec;
int rc;
uint64_t i;
M0_ENTRY();
rc = creq_op_alloc(cids_nr, &op);
if (rc != 0)
return M0_ERR(rc);
op->cg_id.ci_fid = m0_cas_meta_fid;
op->cg_flags = flags;
rec = op->cg_rec.cr_rec;
for (i = 0; i < cids_nr; i++) {
struct m0_buf buf;
m0_rpc_at_init(&rec[i].cr_key);
/* Xcode the key to get continuous buffer for sending. */
rc = m0_xcode_obj_enc_to_buf(
&M0_XCODE_OBJ(m0_cas_id_xc,
/*
* Cast to avoid 'discard const' compile
* error, in fact cas id element is not
* changed during encoding.
*/
(struct m0_cas_id *)&cids[i]),
&buf.b_addr, &buf.b_nob);
if (rc == 0) {
rc = m0_rpc_at_add(&rec[i].cr_key,
&buf,
creq_rpc_conn(req));
if (rc != 0)
m0_buf_free(&buf);
else if (recv_val) {
m0_rpc_at_init(&rec[i].cr_val);
rc = m0_rpc_at_recv(&rec[i].cr_val,
creq_rpc_conn(req),
sizeof(struct m0_fid),
false);
}
}
if (rc != 0)
break;
}
if (rc != 0) {
op->cg_rec.cr_nr = i + 1;
creq_recv_fini(&op->cg_rec, fid_is_meta(&op->cg_id.ci_fid));
creq_op_free(op);
return M0_ERR(rc);
}
*out = op;
return M0_RC(rc);
}
static void addb2_add_cas_req_attrs(const struct m0_cas_req *req)
{
uint64_t sm_id = m0_sm_id_get(&req->ccr_sm);
M0_ADDB2_ADD(M0_AVI_ATTR, sm_id,
M0_AVI_CAS_REQ_ATTR_IS_META, !!req->ccr_is_meta);
if (req->ccr_req_op != NULL)
M0_ADDB2_ADD(M0_AVI_ATTR, sm_id, M0_AVI_CAS_REQ_ATTR_REC_NR,
req->ccr_req_op->cg_rec.cr_nr);
}
static int cas_index_req_prepare(struct m0_cas_req *req,
const struct m0_cas_id *cids,
uint64_t cids_nr,
uint64_t max_replies_nr,
bool recv_val,
uint32_t flags,
struct m0_cas_op **op)
{
struct m0_cas_recv *reply_recv;
int rc;
reply_recv = &req->ccr_reply.cgr_rep;
M0_ALLOC_ARR(reply_recv->cr_rec, max_replies_nr);
if (reply_recv->cr_rec == NULL)
return M0_ERR(-ENOMEM);
/* Set to 0 initially, will be increased when reply is received. */
reply_recv->cr_nr = 0;
req->ccr_max_replies_nr = max_replies_nr;
req->ccr_is_meta = true;
rc = cas_index_op_prepare(req, cids, cids_nr, recv_val, flags, op);
if (rc == 0) {
req->ccr_rec_orig = (*op)->cg_rec;
req->ccr_req_op = *op;
addb2_add_cas_req_attrs(req);
}
if (rc != 0) {
m0_free(reply_recv->cr_rec);
reply_recv->cr_nr = 0;
reply_recv->cr_rec = NULL;
}
return M0_RC(rc);
}
M0_INTERNAL uint64_t m0_cas_req_nr(const struct m0_cas_req *req)
{
return req->ccr_reply.cgr_rep.cr_nr;
}
M0_INTERNAL int m0_cas_req_wait(struct m0_cas_req *req, uint64_t states,
m0_time_t to)
{
M0_ENTRY();
M0_PRE(m0_cas_req_is_locked(req));
return M0_RC(m0_sm_timedwait(&req->ccr_sm, states, to));
}
M0_INTERNAL int m0_cas_index_create(struct m0_cas_req *req,
const struct m0_cas_id *cids,
uint64_t cids_nr,
struct m0_dtx *dtx)
{
struct m0_cas_op *op;
enum m0_cas_req_state next_state;
int rc;
M0_ENTRY();
M0_PRE(req->ccr_sess != NULL);
M0_PRE(m0_cas_req_is_locked(req));
M0_PRE(m0_forall(i, cids_nr, m0_cas_id_invariant(&cids[i])));
(void)dtx;
rc = cas_index_req_prepare(req, cids, cids_nr, cids_nr, false, 0, &op);
if (rc != 0)
return M0_ERR(rc);
rc = creq_fop_create_and_prepare(req, &cas_put_fopt, op, &next_state);
if (rc == 0) {
cas_fop_send(req);
cas_req_state_set(req, next_state);
}
return M0_RC(rc);
}
static void cas_rep_copy(const struct m0_cas_req *req,
uint64_t idx,
struct m0_cas_rec_reply *rep)
{
const struct m0_cas_recv *recv = &req->ccr_reply.cgr_rep;
M0_ASSERT(idx < m0_cas_req_nr(req));
rep->crr_rc = recv->cr_rec[idx].cr_rc;
rep->crr_hint = recv->cr_rec[idx].cr_hint;
}
M0_INTERNAL void m0_cas_index_create_rep(const struct m0_cas_req *req,
uint64_t idx,
struct m0_cas_rec_reply *rep)
{
M0_ENTRY();
cas_rep_copy(req, idx, rep);
M0_LEAVE();
}
M0_INTERNAL int m0_cas_index_delete(struct m0_cas_req *req,
const struct m0_cas_id *cids,
uint64_t cids_nr,
struct m0_dtx *dtx,
uint32_t flags)
{
struct m0_cas_op *op;
enum m0_cas_req_state next_state;
int rc;
M0_ENTRY();
M0_PRE(req->ccr_sess != NULL);
M0_PRE(m0_cas_req_is_locked(req));
M0_PRE(m0_forall(i, cids_nr, m0_cas_id_invariant(&cids[i])));
M0_PRE((flags & ~(COF_CROW | COF_DEL_LOCK | COF_SKIP_LAYOUT)) == 0);
(void)dtx;
rc = cas_index_req_prepare(req, cids, cids_nr, cids_nr, false, flags,
&op);
if (rc != 0)
return M0_ERR(rc);
rc = creq_fop_create_and_prepare(req, &cas_del_fopt, op, &next_state);
if (rc == 0) {
cas_fop_send(req);
cas_req_state_set(req, CASREQ_SENT);
}
return M0_RC(rc);
}
M0_INTERNAL void m0_cas_index_delete_rep(const struct m0_cas_req *req,
uint64_t idx,
struct m0_cas_rec_reply *rep)
{
M0_ENTRY();
cas_rep_copy(req, idx, rep);
M0_LEAVE();
}
M0_INTERNAL int m0_cas_index_lookup(struct m0_cas_req *req,
const struct m0_cas_id *cids,
uint64_t cids_nr)
{
struct m0_cas_op *op;
enum m0_cas_req_state next_state;
int rc;
M0_ENTRY();
M0_PRE(req->ccr_sess != NULL);
M0_PRE(m0_cas_req_is_locked(req));
M0_PRE(m0_forall(i, cids_nr, m0_cas_id_invariant(&cids[i])));
rc = cas_index_req_prepare(req, cids, cids_nr, cids_nr, true, 0, &op);
if (rc != 0)
return M0_ERR(rc);
rc = creq_fop_create_and_prepare(req, &cas_get_fopt, op, &next_state);
if (rc == 0) {
cas_fop_send(req);
cas_req_state_set(req, next_state);
}
return M0_RC(rc);
}
M0_INTERNAL void m0_cas_index_lookup_rep(const struct m0_cas_req *req,
uint64_t idx,
struct m0_cas_rec_reply *rep)
{
M0_ENTRY();
cas_rep_copy(req, idx, rep);
M0_LEAVE();
}
M0_INTERNAL int m0_cas_index_list(struct m0_cas_req *req,
const struct m0_fid *start_fid,
uint32_t indices_nr,
uint32_t flags)
{
struct m0_cas_op *op;
struct m0_cas_id cid = { .ci_fid = *start_fid };
enum m0_cas_req_state next_state;
int rc;
M0_ENTRY();
M0_PRE(start_fid != NULL);
M0_PRE(req->ccr_sess != NULL);
M0_PRE(m0_cas_req_is_locked(req));
M0_PRE((flags & ~(COF_SLANT | COF_EXCLUDE_START_KEY)) == 0);
rc = cas_index_req_prepare(req, &cid, 1, indices_nr, false, flags, &op);
if (rc != 0)
return M0_ERR(rc);
op->cg_rec.cr_rec[0].cr_rc = indices_nr;
rc = creq_fop_create_and_prepare(req, &cas_cur_fopt, op, &next_state);
if (rc == 0) {
cas_fop_send(req);
cas_req_state_set(req, next_state);
}
return M0_RC(rc);
}
static int cas_next_rc(int64_t service_rc)
{
int rc;
/*
* Zero return code means some error on service side.
* Service place sequence number of record starting from 1 in cr_rc on
* success.
*/
if (service_rc == 0)
/*
* Don't use M0_ERR() here to not pollute trace log.
* Service places zero return code in all records following the
* record having negative return code. It can happen in a
* totally valid case when client requests more records than
* available in a catalogue.
*/
rc = -EPROTO;
else if (service_rc < 0)
rc = service_rc;
else
rc = 0;
return M0_RC(rc);
}
M0_INTERNAL void m0_cas_index_list_rep(struct m0_cas_req *req,
uint32_t idx,
struct m0_cas_ilist_reply *rep)
{
struct m0_cas_recv *recv = &req->ccr_reply.cgr_rep;
struct m0_cas_rec *rec;
struct m0_buf fid;
M0_ENTRY();
M0_PRE(idx < m0_cas_req_nr(req));
rec = &recv->cr_rec[idx];
rep->clr_rc = cas_next_rc(rec->cr_rc) ?:
m0_rpc_at_rep_get(NULL, &rec->cr_key, &fid);
if (rep->clr_rc == 0) {
rep->clr_fid = *(struct m0_fid *)fid.b_addr;
rep->clr_hint = recv->cr_rec[idx].cr_hint;
}
M0_LEAVE();
}
static int cas_req_fragmentation(struct m0_cas_req *req)
{
struct m0_cas_op *op = m0_fop_data(req->ccr_fop);
int rc = 0;
if (M0_FI_ENABLED("fragm_error"))
return -E2BIG;
M0_PRE(req->ccr_rec_orig.cr_nr != 0 &&
req->ccr_rec_orig.cr_rec != NULL);
M0_PRE(req->ccr_sent_recs_nr < req->ccr_rec_orig.cr_nr);
/*
* Flush records counter and reset records pointer to the first record
* to be sent.
*/
op->cg_rec.cr_nr = 0;
op->cg_rec.cr_rec = &req->ccr_rec_orig.cr_rec[req->ccr_sent_recs_nr];
do {
op->cg_rec.cr_nr++;
if (m0_rpc_item_max_payload_exceeded(&req->ccr_fop->f_item,
req->ccr_sess)) {
/*
* Found the number of records when item payload exceeds
* max rpc item payload, chose previous number of
* records (current - 1) for sending.
*/
op->cg_rec.cr_nr--;
break;
}
} while (req->ccr_sent_recs_nr + op->cg_rec.cr_nr <
req->ccr_rec_orig.cr_nr);
if (op->cg_rec.cr_nr == 0)
rc = -E2BIG; /* Almost impossible case. */
if (rc != 0)
/*
* Restore original records vector in case of error for proper
* finalisation of data structures.
*/
op->cg_rec = req->ccr_rec_orig;
return M0_RC(rc);
}
static int cas_req_fragment_continue(struct m0_cas_req *req,
struct m0_cas_op *op)
{
int rc;
rc = creq_fop_create(req, req->ccr_ftype, op);
if (rc != 0)
return M0_ERR(rc);
rc = cas_req_fragmentation(req);
if (rc == 0)
cas_fop_send(req);
else
creq_fop_destroy(req);
return M0_RC(rc);
}
static int cas_records_op_prepare(const struct m0_cas_req *req,
const struct m0_cas_id *index,
const struct m0_bufvec *keys,
const struct m0_bufvec *values,
uint32_t flags,
struct m0_cas_op **out)
{
struct m0_cas_op *op;
struct m0_cas_rec *rec;
uint32_t keys_nr = keys->ov_vec.v_nr;
uint64_t i;
int rc;
M0_ENTRY();
rc = creq_op_alloc(keys_nr, &op);
if (rc != 0)
return M0_ERR(rc);
op->cg_id = *index;
rec = op->cg_rec.cr_rec;
for (i = 0; i < keys_nr; i++) {
m0_rpc_at_init(&rec[i].cr_key);
rc = creq_kv_buf_add(req, keys, i, &rec[i].cr_key);
if (rc == 0 && values != NULL) {
m0_rpc_at_init(&rec[i].cr_val);
rc = creq_kv_buf_add(req, values, i, &rec[i].cr_val);
}
if (rc != 0)
break;
}
if (rc != 0) {
op->cg_rec.cr_nr = i + 1;
creq_recv_fini(&op->cg_rec, fid_is_meta(&op->cg_id.ci_fid));
creq_op_free(op);
return M0_ERR(rc);
}
op->cg_flags = flags;
*out = op;
return M0_RC(rc);
}
static int cas_req_prep(struct m0_cas_req *req,
const struct m0_cas_id *index,
const struct m0_bufvec *keys,
const struct m0_bufvec *values,
uint64_t max_replies_nr,
uint32_t flags,
struct m0_cas_op **op)
{
struct m0_cas_recv *reply_recv;
int rc;
M0_ENTRY();
reply_recv = &req->ccr_reply.cgr_rep;
M0_ALLOC_ARR(reply_recv->cr_rec, max_replies_nr);
if (reply_recv->cr_rec == NULL)
return M0_ERR(-ENOMEM);
/* Set to 0 initially, will be increased when reply is received. */
reply_recv->cr_nr = 0;
req->ccr_max_replies_nr = max_replies_nr;
req->ccr_is_meta = false;
rc = cas_records_op_prepare(req, index, keys, values, flags, op);
if (rc == 0) {
req->ccr_rec_orig = (*op)->cg_rec;
req->ccr_req_op = *op;
addb2_add_cas_req_attrs(req);
}
if (rc != 0) {
m0_free(reply_recv->cr_rec);
reply_recv->cr_nr = 0;
reply_recv->cr_rec = NULL;
}
return M0_RC(rc);
}
M0_INTERNAL int m0_cas_put(struct m0_cas_req *req,
struct m0_cas_id *index,
const struct m0_bufvec *keys,
const struct m0_bufvec *values,
struct m0_dtx *dtx,
uint32_t flags)
{
struct m0_cas_op *op;
enum m0_cas_req_state next_state;
int rc;
M0_ENTRY();
M0_PRE(keys != NULL);
M0_PRE(values != NULL);
M0_PRE(keys->ov_vec.v_nr == values->ov_vec.v_nr);
M0_PRE(m0_cas_req_is_locked(req));
/* Create and overwrite flags can't be specified together. */
M0_PRE(!(flags & COF_CREATE) || !(flags & COF_OVERWRITE));
/*
* Only create, overwrite, crow, sync_wait, and skip_layout flags
* are allowed.
*/
M0_PRE((flags &
~(COF_CREATE | COF_OVERWRITE | COF_CROW | COF_SYNC_WAIT |
COF_SKIP_LAYOUT)) == 0);
M0_PRE(m0_cas_id_invariant(index));
rc = cas_req_prep(req, index, keys, values, keys->ov_vec.v_nr, flags,
&op);
if (rc != 0)
return M0_ERR(rc);
rc = m0_dtx0_txd_copy(dtx, &op->cg_txd);
if (rc != 0)
return M0_ERR(rc);
rc = creq_fop_create_and_prepare(req, &cas_put_fopt, op, &next_state);
if (rc == 0) {
cas_fop_send(req);
cas_req_state_set(req, next_state);
}
return M0_RC(rc);
}
M0_INTERNAL void m0_cas_put_rep(struct m0_cas_req *req,
uint64_t idx,
struct m0_cas_rec_reply *rep)
{
M0_ENTRY();
M0_PRE(req->ccr_ftype == &cas_put_fopt);
cas_rep_copy(req, idx, rep);
M0_LEAVE();
}
M0_INTERNAL int m0_cas_get(struct m0_cas_req *req,
struct m0_cas_id *index,
const struct m0_bufvec *keys)
{
struct m0_cas_op *op;
int rc;
struct m0_rpc_at_buf *ab;
enum m0_cas_req_state next_state;
uint32_t i;
M0_ENTRY();
M0_PRE(keys != NULL);
M0_PRE(m0_cas_req_is_locked(req));
M0_PRE(m0_cas_id_invariant(index));
rc = cas_req_prep(req, index, keys, NULL, keys->ov_vec.v_nr, 0, &op);
if (rc != 0)
return M0_ERR(rc);
for (i = 0; i < keys->ov_vec.v_nr; i++) {
ab = &op->cg_rec.cr_rec[i].cr_val;
m0_rpc_at_init(ab);
rc = m0_rpc_at_recv(ab, creq_rpc_conn(req),
M0_RPC_AT_UNKNOWN_LEN, false);
if (rc != 0) {
m0_rpc_at_fini(ab);
break;
}
}
if (rc != 0) {
op->cg_rec.cr_nr = i;
creq_recv_fini(&op->cg_rec, fid_is_meta(&op->cg_id.ci_fid));
creq_op_free(op);
} else {
req->ccr_keys = keys;
rc = creq_fop_create_and_prepare(req, &cas_get_fopt, op,
&next_state);
if (rc == 0) {
cas_fop_send(req);
cas_req_state_set(req, next_state);
}
}
return M0_RC(rc);
}
M0_INTERNAL void m0_cas_get_rep(const struct m0_cas_req *req,
uint64_t idx,
struct m0_cas_get_reply *rep)
{
const struct m0_cas_rep *cas_rep = &req->ccr_reply;
struct m0_cas_rec *sent;
struct m0_cas_rec *rcvd;
M0_ENTRY();
M0_PRE(idx < m0_cas_req_nr(req));
M0_PRE(req->ccr_ftype == &cas_get_fopt);
rcvd = &cas_rep->cgr_rep.cr_rec[idx];
sent = &req->ccr_rec_orig.cr_rec[idx];
rep->cge_rc = rcvd->cr_rc;
if (rep->cge_rc == 0)
m0_rpc_at_rep_get(&sent->cr_val, &rcvd->cr_val, &rep->cge_val);
M0_LEAVE();
}
M0_INTERNAL int m0_cas_next(struct m0_cas_req *req,
struct m0_cas_id *index,
struct m0_bufvec *start_keys,
uint32_t *recs_nr,
uint32_t flags)
{
struct m0_cas_op *op;
enum m0_cas_req_state next_state;
uint64_t max_replies_nr = 0;
uint32_t i;
int rc;
M0_ENTRY();
M0_PRE(start_keys != NULL);
M0_PRE(m0_cas_req_is_locked(req));
M0_PRE(m0_cas_id_invariant(index));
/* Only slant and exclude start key flags are allowed. */
M0_PRE((flags & ~(COF_SLANT | COF_EXCLUDE_START_KEY)) == 0);
for (i = 0; i < start_keys->ov_vec.v_nr; i++)
max_replies_nr += recs_nr[i];
rc = cas_req_prep(req, index, start_keys, NULL, max_replies_nr, flags,
&op);
if (rc != 0)
return M0_ERR(rc);
for (i = 0; i < start_keys->ov_vec.v_nr; i++)
op->cg_rec.cr_rec[i].cr_rc = recs_nr[i];
req->ccr_keys = start_keys;
rc = creq_fop_create_and_prepare(req, &cas_cur_fopt, op,
&next_state);
if (rc == 0) {
cas_fop_send(req);
cas_req_state_set(req, next_state);
}
return M0_RC(rc);
}
M0_INTERNAL void m0_cas_rep_mlock(const struct m0_cas_req *req,
uint64_t idx)
{
const struct m0_cas_rep *cas_rep = &req->ccr_reply;
M0_PRE(M0_IN(req->ccr_ftype, (&cas_get_fopt, &cas_cur_fopt)));
creq_kv_hold_down(&cas_rep->cgr_rep.cr_rec[idx]);
}
M0_INTERNAL void m0_cas_next_rep(const struct m0_cas_req *req,
uint32_t idx,
struct m0_cas_next_reply *rep)
{
const struct m0_cas_rep *cas_rep = &req->ccr_reply;
struct m0_cas_rec *rcvd;
M0_ENTRY();
M0_PRE(idx < m0_cas_req_nr(req));
M0_PRE(req->ccr_ftype == &cas_cur_fopt);
rcvd = &cas_rep->cgr_rep.cr_rec[idx];
rep->cnp_rc = cas_next_rc(rcvd->cr_rc) ?:
m0_rpc_at_rep_get(NULL, &rcvd->cr_key, &rep->cnp_key) ?:
m0_rpc_at_rep_get(NULL, &rcvd->cr_val, &rep->cnp_val);
}
M0_INTERNAL int m0_cas_del(struct m0_cas_req *req,
struct m0_cas_id *index,
struct m0_bufvec *keys,
struct m0_dtx *dtx,
uint32_t flags)
{
struct m0_cas_op *op;
enum m0_cas_req_state next_state;
int rc;
M0_ENTRY();
M0_PRE(keys != NULL);
M0_PRE(m0_cas_req_is_locked(req));
M0_PRE(m0_cas_id_invariant(index));
M0_PRE(M0_IN(flags, (0, COF_DEL_LOCK, COF_SYNC_WAIT)));
rc = cas_req_prep(req, index, keys, NULL, keys->ov_vec.v_nr, flags,
&op);
if (rc != 0)
return M0_ERR(rc);
rc = m0_dtx0_txd_copy(dtx, &op->cg_txd);
if (rc != 0)
return M0_ERR(rc);
rc = creq_fop_create_and_prepare(req, &cas_del_fopt, op, &next_state);
if (rc == 0) {
cas_fop_send(req);
cas_req_state_set(req, next_state);
}
return M0_RC(rc);
}
M0_INTERNAL void m0_cas_del_rep(struct m0_cas_req *req,
uint64_t idx,
struct m0_cas_rec_reply *rep)
{
M0_ENTRY();
M0_PRE(req->ccr_ftype == &cas_del_fopt);
cas_rep_copy(req, idx, rep);
M0_LEAVE();
}
M0_INTERNAL int m0_cas_sm_conf_init(void)
{
m0_sm_conf_init(&cas_req_sm_conf);
return m0_sm_addb2_init(&cas_req_sm_conf,
M0_AVI_CAS_SM_REQ,
M0_AVI_CAS_SM_REQ_COUNTER);
}
M0_INTERNAL void m0_cas_sm_conf_fini(void)
{
m0_sm_addb2_fini(&cas_req_sm_conf);
m0_sm_conf_fini(&cas_req_sm_conf);
}
#undef M0_TRACE_SUBSYSTEM
/** @} end of cas-client group */
/*
* Local variables:
* c-indentation-style: "K&R"
* c-basic-offset: 8
* tab-width: 8
* fill-column: 80
* scroll-step: 1
* End:
*/
/*
* vim: tabstop=8 shiftwidth=8 noexpandtab textwidth=80 nowrap
*/
| 27.156002 | 80 | 0.663148 | [
"vector"
] |
083d4478cc824bb31385ec11d3f70d8c828dbd94 | 11,911 | h | C | graphics/SoRenderArea.h | cvilas/grape-old | d8e9b184fff396982be8d230214a1f66a7a8fcc9 | [
"BSD-3-Clause"
] | null | null | null | graphics/SoRenderArea.h | cvilas/grape-old | d8e9b184fff396982be8d230214a1f66a7a8fcc9 | [
"BSD-3-Clause"
] | 4 | 2018-06-04T08:18:21.000Z | 2018-07-13T14:36:03.000Z | graphics/SoRenderArea.h | cvilas/grape-old | d8e9b184fff396982be8d230214a1f66a7a8fcc9 | [
"BSD-3-Clause"
] | null | null | null | //==============================================================================
// Project : Grape
// Module : Graphics
// File : SoRenderArea.h
// Brief : top level interface to Coin Open-Inventor library
//
// Note : This file is a derivative work of 'SoViewer' library available at
// http://code.google.com/p/openinventorviewer/.
//
// Copyright (c) 2012, Vilas Chitrakaran
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR ITS CONTRIBUTORS
// BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//==============================================================================
#ifndef GRAPE_SORENDERAREA_H
#define GRAPE_SORENDERAREA_H
#include "SoQtg.h"
#include <Inventor/nodes/SoNode.h>
#include <Inventor/SoRenderManager.h>
#include <Inventor/SoEventManager.h>
#include <Inventor/events/SoKeyboardEvent.h>
#include <Inventor/events/SoLocation2Event.h>
#include <Inventor/events/SoMouseButtonEvent.h>
namespace grape
{
class SoWheelEvent;
/// \class SoRenderArea
/// \ingroup graphics
/// \brief Top-level interface to Coin Open-Inventor library.
///
/// This is the base class that provides an interface to the Coin Open-Inventor
/// library. Methods for scenegraph management and event handling are implemented
/// here. Application programmers will use only derived classes directly.
///
/// This and it's daughter classes are derivative work of SoViewer library available
/// here: http://code.google.com/p/openinventorviewer/
///
/// Example program:
/// See examples in /examples/Inventor
class GRAPEGRAPHICS_DLL_API SoRenderArea
{
public:
/// Initialize the Coin system. This needs to be done as the first thing
/// before you start using the library, or you'll probably see an early crash.
static void init();
/// Sets the scene graph to be rendered in the view window.
/// \param pScene (input) Pointer to open-inventor scene graph.
virtual void setSceneGraph(SoNode *pScene);
/// Get the scene graph, including any additional lights and camera that
/// may be added by derived classes.
/// \return Pointer to open-inventor scene graph.
virtual SoNode* getSceneGraph() const { return _pRenderManager->getSceneGraph(); }
/// Sets the camera to be used.
virtual void setCamera (SoCamera* pCamera) { _pEventManager->setCamera(pCamera); }
/// Access the active camera.
/// \return Pointer to the current camera.
virtual SoCamera* getCamera() const { return _pEventManager->getCamera(); }
/// Set viewport region to use for rendering.
/// \param region (input) View port region.
void setViewportRegion(const SbViewportRegion& region);
/// Gets current viewport region in use for rendering.
/// \return current view port region
const SbViewportRegion& getViewportRegion() const { return _pEventManager->getViewportRegion(); }
/// Sets the background color for this window. Default is black (0,0,0).
/// \param color (input) Background color.
inline void setBackgroundColor(const SbColor4f& color);
/// Gets the background color for this window.
/// \return Background color.
const SbColor4f& getBackgroundColor() const { return _pRenderManager->getBackgroundColor(); }
/// Set the action to use for rendering. Overrides any defaukt action.
/// \param pRA (input) OpenGL rendering action.
inline void setGLRenderAction(SoGLRenderAction* const pRA);
/// Access the OpenGL render action.
/// \return Pointer to render action.
SoGLRenderAction* getGLRenderAction() const { return _pRenderManager->getGLRenderAction(); }
/// Set mode of rendering of primitives.
inline virtual void setRenderMode (const SoRenderManager::RenderMode mode);
/// Get the render mode for primitives.
/// \return current mode of rendering of primitives.
SoRenderManager::RenderMode getRenderMode () const { return _pRenderManager->getRenderMode(); }
/// Set mode of rendering of stereoscopic images
inline virtual void setStereoMode (const SoRenderManager::StereoMode mode);
/// Get the current stereo rendering mode.
/// \return current mode of rendering stereo.
SoRenderManager::StereoMode getStereoMode () const{ return _pRenderManager->getStereoMode(); }
/// Set offset when doing stereo rendering.
inline virtual void setStereoOffset (const float offset);
/// Get the stereo rendering offset.
/// \return current stereo offset.
float getStereoOffset(void) const { return _pRenderManager->getStereoOffset(); }
/// Turn anti-aliasing on/off
/// \param smoothing (input) Set to true to smooth jagged edges. (See SoGLRenderAction::setSmoothing()).
/// \param numPasses (input) Set the number of rendering passes. Anything greater than the default
/// of 1 will enable antialiasing through the use of OpenGL accumulation buffer.
inline virtual void setAntialiasing (const SbBool smoothing, const int numPasses);
/// Returns rendering pass information. See setAntialisasing().
void getAntialiasing (SbBool &smoothing, int &numPasses) const { _pRenderManager->getAntialiasing(smoothing, numPasses); }
/// Tell scene manager that double buffering is being used.
inline virtual void setDoubleBuffer(const SbBool enable);
/// Check whether double buffering is being used.
/// \return true if double buffering is used.
virtual SbBool isDoubleBuffer() const { return _pRenderManager->isDoubleBuffer(); }
/// Tell the scene manager to enable automatic redraws of the scene upon detecting
/// changes in the scenegraph. The default is on.
virtual void setAutoRedraw(SbBool enable);
/// \return true if the scene manager automatically redraws the scene upon detecting changes in the
/// scenegraph.
virtual SbBool isAutoRedraw (void) const { return _pRenderManager->isAutoRedraw(); }
/*
/// Sets strategy for adjusting camera clipping plane
inline virtual void setAutoClipping(SoRenderManager::AutoClippingStrategy autoClipping);
/// This method returns the current autoclipping strategy.
SoRenderManager::AutoClippingStrategy getAutoClipping() const { return _pRenderManager->getAutoClipping(); }
*/
/// Activate rendering and event handling. The default is 'off' until setSceneGraph() is called.
virtual void activate() { _pRenderManager->activate(); }
/// Deactivate rendering and event handling.
virtual void deactivate() { _pRenderManager->deactivate(); }
/// Re-initialize after parameters affecting the OpenGL context has changed.
virtual void reinitialize() { _pRenderManager->reinitialize(); }
protected:
SoRenderArea();
virtual ~SoRenderArea();
virtual void soKeyPressEvent( SoKeyboardEvent *pEvent);
virtual void soKeyReleaseEvent( SoKeyboardEvent *pEvent );
virtual void soMouseMoveEvent( SoLocation2Event *pEvent );
virtual void soMousePressEvent( SoMouseButtonEvent *pEvent );
virtual void soMouseReleaseEvent( SoMouseButtonEvent *pEvent );
virtual void soWheelEvent( SoWheelEvent *pEvent );
virtual void soResizeEvent(int width, int height);
virtual void soPaintEvent();
virtual void soRenderCallback() = 0;
private:
static void renderCallback(void *pUserData, SoRenderManager *pManager);
protected:
SoEventManager* _pEventManager;
SoRenderManager* _pRenderManager;
SoWheelEvent* _pWheelEvent;
SoKeyboardEvent* _pKeyboardEvent;
SoMouseButtonEvent* _pMouseButtonEvent;
SoLocation2Event* _pLocation2Event;
}; //SoRenderArea
/// \class SoWheelEvent
/// \ingroup graphics
/// \brief Describes a mouse wheel event
class GRAPEGRAPHICS_DLL_API SoWheelEvent : public SoEvent
{
SO_EVENT_HEADER();
public:
SoWheelEvent(){}
void setDelta(int delta){ _delta = delta; }
int getDelta() const{ return _delta; }
private:
int _delta;
};
//==============================================================================
void SoRenderArea::setBackgroundColor(const SbColor4f& color)
//==============================================================================
{
_pRenderManager->setBackgroundColor(color);
_pRenderManager->scheduleRedraw();
}
//------------------------------------------------------------------------------
void SoRenderArea::setGLRenderAction(SoGLRenderAction* const pRA)
//------------------------------------------------------------------------------
{
_pRenderManager->setGLRenderAction(pRA);
_pRenderManager->scheduleRedraw();
}
//------------------------------------------------------------------------------
void SoRenderArea::setRenderMode (const SoRenderManager::RenderMode mode)
//------------------------------------------------------------------------------
{
_pRenderManager->setRenderMode(mode);
_pRenderManager->scheduleRedraw();
}
//------------------------------------------------------------------------------
void SoRenderArea::setStereoMode (const SoRenderManager::StereoMode mode)
//------------------------------------------------------------------------------
{
_pRenderManager->setStereoMode(mode);
_pRenderManager->scheduleRedraw();
}
//------------------------------------------------------------------------------
void SoRenderArea::setStereoOffset (const float offset)
//------------------------------------------------------------------------------
{
_pRenderManager->setStereoOffset(offset);
_pRenderManager->scheduleRedraw();
}
//------------------------------------------------------------------------------
void SoRenderArea::setAntialiasing (const SbBool smoothing, const int numPasses)
//------------------------------------------------------------------------------
{
_pRenderManager->setAntialiasing(smoothing, numPasses);
_pRenderManager->scheduleRedraw();
}
//------------------------------------------------------------------------------
void SoRenderArea::setDoubleBuffer(const SbBool enable)
//------------------------------------------------------------------------------
{
_pRenderManager->setDoubleBuffer(enable);
_pRenderManager->scheduleRedraw();
}
/*
//------------------------------------------------------------------------------
void SoRenderArea::setAutoClipping(SoRenderManager::AutoClippingStrategy autoClipping)
//------------------------------------------------------------------------------
{
_pRenderManager->setAutoClipping(autoClipping);
}
*/
} // grape
#endif // GRAPE_SORENDERAREA_H
| 41.940141 | 126 | 0.650491 | [
"render"
] |
08414c3d58e6b9367d8898065d7e08d9ebab38f7 | 2,981 | h | C | gst/elements/gvawatermark/renderer/cpu/renderer_cpu.h | MisterArslan/dlstreamer_gst | ff6d0bc138f372bb988baf368af4a3693b808e16 | [
"MIT"
] | 125 | 2020-09-18T10:50:27.000Z | 2022-02-10T06:20:59.000Z | gst/elements/gvawatermark/renderer/cpu/renderer_cpu.h | MisterArslan/dlstreamer_gst | ff6d0bc138f372bb988baf368af4a3693b808e16 | [
"MIT"
] | 155 | 2020-09-10T23:32:29.000Z | 2022-02-05T07:10:26.000Z | gst/elements/gvawatermark/renderer/cpu/renderer_cpu.h | MisterArslan/dlstreamer_gst | ff6d0bc138f372bb988baf368af4a3693b808e16 | [
"MIT"
] | 41 | 2020-09-15T08:49:17.000Z | 2022-01-24T10:39:36.000Z | /*******************************************************************************
* Copyright (C) 2020-2021 Intel Corporation
*
* SPDX-License-Identifier: MIT
******************************************************************************/
#pragma once
#include "renderer.h"
class RendererCPU : public Renderer {
public:
RendererCPU(std::shared_ptr<ColorConverter> color_converter, InferenceBackend::MemoryType memory_type)
: Renderer(color_converter, memory_type) {
}
protected:
void buffer_map(GstBuffer *buffer, InferenceBackend::Image &image, BufferMapContext &map_context,
GstVideoInfo *info) override;
void buffer_unmap(BufferMapContext &map_context) override;
};
class RendererYUV : public RendererCPU {
public:
RendererYUV(std::shared_ptr<ColorConverter> color_converter, InferenceBackend::MemoryType memory_type)
: RendererCPU(color_converter, memory_type) {
}
protected:
void draw_backend(std::vector<cv::Mat> &image_planes, std::vector<gapidraw::Prim> &prims, uint64_t) override;
virtual void draw_rectangle(std::vector<cv::Mat> &mats, gapidraw::Rect rect) = 0;
virtual void draw_circle(std::vector<cv::Mat> &mats, gapidraw::Circle circle) = 0;
virtual void draw_text(std::vector<cv::Mat> &mats, gapidraw::Text text) = 0;
virtual void draw_line(std::vector<cv::Mat> &mats, gapidraw::Line line) = 0;
void draw_rect_y_plane(cv::Mat &y, cv::Point2i pt1, cv::Point2i pt2, double color, int thick);
};
class RendererI420 : public RendererYUV {
public:
RendererI420(std::shared_ptr<ColorConverter> color_converter, InferenceBackend::MemoryType memory_type)
: RendererYUV(color_converter, memory_type) {
}
protected:
void draw_rectangle(std::vector<cv::Mat> &mats, gapidraw::Rect rect) override;
void draw_circle(std::vector<cv::Mat> &mats, gapidraw::Circle circle) override;
void draw_text(std::vector<cv::Mat> &mats, gapidraw::Text text) override;
void draw_line(std::vector<cv::Mat> &mats, gapidraw::Line line) override;
};
class RendererNV12 : public RendererYUV {
public:
RendererNV12(std::shared_ptr<ColorConverter> color_converter, InferenceBackend::MemoryType memory_type)
: RendererYUV(color_converter, memory_type) {
}
protected:
void draw_rectangle(std::vector<cv::Mat> &mats, gapidraw::Rect rect) override;
void draw_circle(std::vector<cv::Mat> &mats, gapidraw::Circle circle) override;
void draw_text(std::vector<cv::Mat> &mats, gapidraw::Text text) override;
void draw_line(std::vector<cv::Mat> &mats, gapidraw::Line line) override;
};
class RendererBGR : public RendererCPU {
public:
RendererBGR(std::shared_ptr<ColorConverter> color_converter, InferenceBackend::MemoryType memory_type)
: RendererCPU(color_converter, memory_type) {
}
protected:
void draw_backend(std::vector<cv::Mat> &image_planes, std::vector<gapidraw::Prim> &prims, uint64_t) override;
}; | 40.283784 | 113 | 0.686011 | [
"vector"
] |
0844df1942f017e2caeea5a2c84564aef26eca55 | 3,354 | h | C | win/devkit/plug-ins/polyX3DExporter/polyWriter.h | leegoonz/Maya-devkit | b81fe799b58e854e4ef16435426d60446e975871 | [
"ADSL"
] | 10 | 2018-03-30T16:09:02.000Z | 2021-12-07T07:29:19.000Z | win/devkit/plug-ins/polyX3DExporter/polyWriter.h | leegoonz/Maya-devkit | b81fe799b58e854e4ef16435426d60446e975871 | [
"ADSL"
] | null | null | null | win/devkit/plug-ins/polyX3DExporter/polyWriter.h | leegoonz/Maya-devkit | b81fe799b58e854e4ef16435426d60446e975871 | [
"ADSL"
] | 9 | 2018-06-02T09:18:49.000Z | 2021-12-20T09:24:35.000Z | //-
// ==========================================================================
// Copyright 1995,2006,2008 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 __POLYWRITER_H
#define __POLYWRITER_H
// polyWriter.h
// *****************************************************************************
//
// CLASS: polyWriter
//
// *****************************************************************************
//
// CLASS DESCRIPTION (polyWriter)
//
// polyWriter is a class used for creating polygonal mesh exporter plugins. Its
// purpose is to output polygonal mesh data in the format required.
//
// To use this class, derive a new class and begin by adding the following *.h
// files:
// #include <maya/MFStream.h>
//
// The following functions must be implemented:
// constructor - which takes in MDagPath and MStatus object addresses
// destructor - which destroys any objects created in the constructor
// writeToFile() - which performs the actual data export
// outputSingleSet() - which performs the export of a particular polygonal set
// on the mesh
//
// The extractGeometry() function may be overridden to extract more data that
// it is doing currently, but be sure to call this class' extractGeometry()
// method as its first operation so that essential data is extracted.
//
// It is recommended that smaller helper functions are added to any derived
// classes, to export and format specific data about the mesh.
//
// Once the derived class has been defined, create and return a new object of
// this type in the createPolyWriter() function that must be defined in any
// class derived from the polyExporter class.
//
// For examples, see the classes polyRawWriter and polyX3DWriter
//
// *****************************************************************************
#include <maya/MFnMesh.h>
#include <maya/MPointArray.h>
#include <maya/MFloatVectorArray.h>
#include <maya/MFloatArray.h>
class polyWriter {
public:
polyWriter (MDagPath dagPath, MStatus& status);
virtual ~polyWriter ();
virtual MStatus extractGeometry ();
virtual MStatus writeToFile (ostream & os) = 0;
protected:
//Methods
//
MObject findShader (const MObject& setNode);
virtual MStatus outputSets (ostream& os);
virtual MStatus outputSingleSet (ostream& os,
MString setName,
MIntArray faces,
MString textureName) = 0;
static void outputTabs (ostream & os, unsigned int tabCount);
//Data Members
//
//the current UV set's name
//
MString fCurrentUVSetName;
//for storing general mesh information
//
MPointArray fVertexArray;
MColorArray fColorArray;
MFloatVectorArray fNormalArray;
MFloatVectorArray fTangentArray;
MFloatVectorArray fBinormalArray;
//for storing DAG objects
//
MFnMesh* fMesh;
MDagPath* fDagPath;
MObjectArray fPolygonSets;
MObjectArray fPolygonComponents;
};
#endif /*__POLYWRITER_H*/
| 32.882353 | 81 | 0.616577 | [
"mesh",
"object"
] |
08468157eff061bdf937180291e80c64fdb9e848 | 10,283 | h | C | mopen/include/alibabacloud/mopen/MoPenClient.h | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | mopen/include/alibabacloud/mopen/MoPenClient.h | iamzken/aliyun-openapi-cpp-sdk | 3c991c9ca949b6003c8f498ce7a672ea88162bf1 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | mopen/include/alibabacloud/mopen/MoPenClient.h | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud 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 ALIBABACLOUD_MOPEN_MOPENCLIENT_H_
#define ALIBABACLOUD_MOPEN_MOPENCLIENT_H_
#include <future>
#include <alibabacloud/core/AsyncCallerContext.h>
#include <alibabacloud/core/EndpointProvider.h>
#include <alibabacloud/core/RpcServiceClient.h>
#include "MoPenExport.h"
#include "model/MoPenAddGroupMemberRequest.h"
#include "model/MoPenAddGroupMemberResult.h"
#include "model/MoPenBindIsvRequest.h"
#include "model/MoPenBindIsvResult.h"
#include "model/MoPenCreateDeviceRequest.h"
#include "model/MoPenCreateDeviceResult.h"
#include "model/MoPenDeleteGroupRequest.h"
#include "model/MoPenDeleteGroupResult.h"
#include "model/MoPenDeleteGroupMemberRequest.h"
#include "model/MoPenDeleteGroupMemberResult.h"
#include "model/MoPenDoRecognizeRequest.h"
#include "model/MoPenDoRecognizeResult.h"
#include "model/MoPenFindGroupRequest.h"
#include "model/MoPenFindGroupResult.h"
#include "model/MoPenQueryCanvasRequest.h"
#include "model/MoPenQueryCanvasResult.h"
#include "model/MoPenSendMqttMessageRequest.h"
#include "model/MoPenSendMqttMessageResult.h"
#include "model/MopenCreateGroupRequest.h"
#include "model/MopenCreateGroupResult.h"
namespace AlibabaCloud
{
namespace MoPen
{
class ALIBABACLOUD_MOPEN_EXPORT MoPenClient : public RpcServiceClient
{
public:
typedef Outcome<Error, Model::MoPenAddGroupMemberResult> MoPenAddGroupMemberOutcome;
typedef std::future<MoPenAddGroupMemberOutcome> MoPenAddGroupMemberOutcomeCallable;
typedef std::function<void(const MoPenClient*, const Model::MoPenAddGroupMemberRequest&, const MoPenAddGroupMemberOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> MoPenAddGroupMemberAsyncHandler;
typedef Outcome<Error, Model::MoPenBindIsvResult> MoPenBindIsvOutcome;
typedef std::future<MoPenBindIsvOutcome> MoPenBindIsvOutcomeCallable;
typedef std::function<void(const MoPenClient*, const Model::MoPenBindIsvRequest&, const MoPenBindIsvOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> MoPenBindIsvAsyncHandler;
typedef Outcome<Error, Model::MoPenCreateDeviceResult> MoPenCreateDeviceOutcome;
typedef std::future<MoPenCreateDeviceOutcome> MoPenCreateDeviceOutcomeCallable;
typedef std::function<void(const MoPenClient*, const Model::MoPenCreateDeviceRequest&, const MoPenCreateDeviceOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> MoPenCreateDeviceAsyncHandler;
typedef Outcome<Error, Model::MoPenDeleteGroupResult> MoPenDeleteGroupOutcome;
typedef std::future<MoPenDeleteGroupOutcome> MoPenDeleteGroupOutcomeCallable;
typedef std::function<void(const MoPenClient*, const Model::MoPenDeleteGroupRequest&, const MoPenDeleteGroupOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> MoPenDeleteGroupAsyncHandler;
typedef Outcome<Error, Model::MoPenDeleteGroupMemberResult> MoPenDeleteGroupMemberOutcome;
typedef std::future<MoPenDeleteGroupMemberOutcome> MoPenDeleteGroupMemberOutcomeCallable;
typedef std::function<void(const MoPenClient*, const Model::MoPenDeleteGroupMemberRequest&, const MoPenDeleteGroupMemberOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> MoPenDeleteGroupMemberAsyncHandler;
typedef Outcome<Error, Model::MoPenDoRecognizeResult> MoPenDoRecognizeOutcome;
typedef std::future<MoPenDoRecognizeOutcome> MoPenDoRecognizeOutcomeCallable;
typedef std::function<void(const MoPenClient*, const Model::MoPenDoRecognizeRequest&, const MoPenDoRecognizeOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> MoPenDoRecognizeAsyncHandler;
typedef Outcome<Error, Model::MoPenFindGroupResult> MoPenFindGroupOutcome;
typedef std::future<MoPenFindGroupOutcome> MoPenFindGroupOutcomeCallable;
typedef std::function<void(const MoPenClient*, const Model::MoPenFindGroupRequest&, const MoPenFindGroupOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> MoPenFindGroupAsyncHandler;
typedef Outcome<Error, Model::MoPenQueryCanvasResult> MoPenQueryCanvasOutcome;
typedef std::future<MoPenQueryCanvasOutcome> MoPenQueryCanvasOutcomeCallable;
typedef std::function<void(const MoPenClient*, const Model::MoPenQueryCanvasRequest&, const MoPenQueryCanvasOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> MoPenQueryCanvasAsyncHandler;
typedef Outcome<Error, Model::MoPenSendMqttMessageResult> MoPenSendMqttMessageOutcome;
typedef std::future<MoPenSendMqttMessageOutcome> MoPenSendMqttMessageOutcomeCallable;
typedef std::function<void(const MoPenClient*, const Model::MoPenSendMqttMessageRequest&, const MoPenSendMqttMessageOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> MoPenSendMqttMessageAsyncHandler;
typedef Outcome<Error, Model::MopenCreateGroupResult> MopenCreateGroupOutcome;
typedef std::future<MopenCreateGroupOutcome> MopenCreateGroupOutcomeCallable;
typedef std::function<void(const MoPenClient*, const Model::MopenCreateGroupRequest&, const MopenCreateGroupOutcome&, const std::shared_ptr<const AsyncCallerContext>&)> MopenCreateGroupAsyncHandler;
MoPenClient(const Credentials &credentials, const ClientConfiguration &configuration);
MoPenClient(const std::shared_ptr<CredentialsProvider> &credentialsProvider, const ClientConfiguration &configuration);
MoPenClient(const std::string &accessKeyId, const std::string &accessKeySecret, const ClientConfiguration &configuration);
~MoPenClient();
MoPenAddGroupMemberOutcome moPenAddGroupMember(const Model::MoPenAddGroupMemberRequest &request)const;
void moPenAddGroupMemberAsync(const Model::MoPenAddGroupMemberRequest& request, const MoPenAddGroupMemberAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const;
MoPenAddGroupMemberOutcomeCallable moPenAddGroupMemberCallable(const Model::MoPenAddGroupMemberRequest& request) const;
MoPenBindIsvOutcome moPenBindIsv(const Model::MoPenBindIsvRequest &request)const;
void moPenBindIsvAsync(const Model::MoPenBindIsvRequest& request, const MoPenBindIsvAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const;
MoPenBindIsvOutcomeCallable moPenBindIsvCallable(const Model::MoPenBindIsvRequest& request) const;
MoPenCreateDeviceOutcome moPenCreateDevice(const Model::MoPenCreateDeviceRequest &request)const;
void moPenCreateDeviceAsync(const Model::MoPenCreateDeviceRequest& request, const MoPenCreateDeviceAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const;
MoPenCreateDeviceOutcomeCallable moPenCreateDeviceCallable(const Model::MoPenCreateDeviceRequest& request) const;
MoPenDeleteGroupOutcome moPenDeleteGroup(const Model::MoPenDeleteGroupRequest &request)const;
void moPenDeleteGroupAsync(const Model::MoPenDeleteGroupRequest& request, const MoPenDeleteGroupAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const;
MoPenDeleteGroupOutcomeCallable moPenDeleteGroupCallable(const Model::MoPenDeleteGroupRequest& request) const;
MoPenDeleteGroupMemberOutcome moPenDeleteGroupMember(const Model::MoPenDeleteGroupMemberRequest &request)const;
void moPenDeleteGroupMemberAsync(const Model::MoPenDeleteGroupMemberRequest& request, const MoPenDeleteGroupMemberAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const;
MoPenDeleteGroupMemberOutcomeCallable moPenDeleteGroupMemberCallable(const Model::MoPenDeleteGroupMemberRequest& request) const;
MoPenDoRecognizeOutcome moPenDoRecognize(const Model::MoPenDoRecognizeRequest &request)const;
void moPenDoRecognizeAsync(const Model::MoPenDoRecognizeRequest& request, const MoPenDoRecognizeAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const;
MoPenDoRecognizeOutcomeCallable moPenDoRecognizeCallable(const Model::MoPenDoRecognizeRequest& request) const;
MoPenFindGroupOutcome moPenFindGroup(const Model::MoPenFindGroupRequest &request)const;
void moPenFindGroupAsync(const Model::MoPenFindGroupRequest& request, const MoPenFindGroupAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const;
MoPenFindGroupOutcomeCallable moPenFindGroupCallable(const Model::MoPenFindGroupRequest& request) const;
MoPenQueryCanvasOutcome moPenQueryCanvas(const Model::MoPenQueryCanvasRequest &request)const;
void moPenQueryCanvasAsync(const Model::MoPenQueryCanvasRequest& request, const MoPenQueryCanvasAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const;
MoPenQueryCanvasOutcomeCallable moPenQueryCanvasCallable(const Model::MoPenQueryCanvasRequest& request) const;
MoPenSendMqttMessageOutcome moPenSendMqttMessage(const Model::MoPenSendMqttMessageRequest &request)const;
void moPenSendMqttMessageAsync(const Model::MoPenSendMqttMessageRequest& request, const MoPenSendMqttMessageAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const;
MoPenSendMqttMessageOutcomeCallable moPenSendMqttMessageCallable(const Model::MoPenSendMqttMessageRequest& request) const;
MopenCreateGroupOutcome mopenCreateGroup(const Model::MopenCreateGroupRequest &request)const;
void mopenCreateGroupAsync(const Model::MopenCreateGroupRequest& request, const MopenCreateGroupAsyncHandler& handler, const std::shared_ptr<const AsyncCallerContext>& context = nullptr) const;
MopenCreateGroupOutcomeCallable mopenCreateGroupCallable(const Model::MopenCreateGroupRequest& request) const;
private:
std::shared_ptr<EndpointProvider> endpointProvider_;
};
}
}
#endif // !ALIBABACLOUD_MOPEN_MOPENCLIENT_H_
| 80.968504 | 220 | 0.835846 | [
"model"
] |
08470c24608b4550800c7ce11642df1b58fee2fa | 3,540 | h | C | libs/poco/include/Poco/DOM/Notation.h | creatologist/openFrameworks0084 | aa74f188f105b62fbcecb7baf2b41d56d97cf7bc | [
"MIT"
] | 50 | 2015-01-07T01:54:54.000Z | 2021-01-15T00:41:48.000Z | libs/poco/include/Poco/DOM/Notation.h | nmbakfm/club_projection_mapping | 95dd0d7604fce397fcdf058d09085fb32b184257 | [
"MIT"
] | 27 | 2015-01-06T05:45:55.000Z | 2020-01-29T21:40:22.000Z | libs/poco/include/Poco/DOM/Notation.h | nmbakfm/club_projection_mapping | 95dd0d7604fce397fcdf058d09085fb32b184257 | [
"MIT"
] | 39 | 2015-01-07T02:03:15.000Z | 2021-01-15T00:41:50.000Z | //
// Notation.h
//
// $Id: //poco/1.4/XML/include/Poco/DOM/Notation.h#1 $
//
// Library: XML
// Package: DOM
// Module: DOM
//
// Definition of the DOM Notation class.
//
// Copyright (c) 2004-2006, Applied Informatics Software Engineering GmbH.
// and Contributors.
//
// Permission is hereby granted, free of charge, to any person or organization
// obtaining a copy of the software and accompanying documentation covered by
// this license (the "Software") to use, reproduce, display, distribute,
// execute, and transmit the Software, and to prepare derivative works of the
// Software, and to permit third-parties to whom the Software is furnished to
// do so, all subject to the following:
//
// The copyright notices in the Software and this entire statement, including
// the above license grant, this restriction and the following disclaimer,
// must be included in all copies of the Software, in whole or in part, and
// all derivative works of the Software, unless such copies or derivative
// works are solely in the form of machine-executable object code generated by
// a source language processor.
//
// 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, TITLE AND NON-INFRINGEMENT. IN NO EVENT
// SHALL THE COPYRIGHT HOLDERS OR ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE
// FOR ANY DAMAGES OR OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE,
// ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
//
#ifndef DOM_Notation_INCLUDED
#define DOM_Notation_INCLUDED
#include "Poco/XML/XML.h"
#include "Poco/DOM/AbstractNode.h"
#include "Poco/XML/XMLString.h"
namespace Poco {
namespace XML {
class XML_API Notation: public AbstractNode
/// This interface represents a notation declared in the DTD. A notation either
/// declares, by name, the format of an unparsed entity (see section 4.7 of
/// the XML 1.0 specification <http://www.w3.org/TR/2004/REC-xml-20040204/>),
/// or is used for formal declaration of processing
/// instruction targets (see section 2.6 of the XML 1.0 specification).
/// The nodeName attribute inherited from Node is set to the declared name of
/// the notation.
///
/// The DOM Level 1 does not support editing Notation nodes; they are therefore
/// readonly.
///
/// A Notation node does not have any parent.
{
public:
const XMLString& publicId() const;
/// Returns the public identifier of this notation.
/// If not specified, this is an empty string (and not null,
/// as in the DOM specification).
const XMLString& systemId() const;
/// Returns the system identifier of this notation.
/// If not specified, this is an empty string (and not null,
/// as in the DOM specification).
// Node
const XMLString& nodeName() const;
unsigned short nodeType() const;
protected:
Notation(Document* pOwnerDocument, const XMLString& name, const XMLString& publicId, const XMLString& systemId);
Notation(Document* pOwnerDocument, const Notation& notation);
~Notation();
Node* copyNode(bool deep, Document* pOwnerDocument) const;
private:
XMLString _name;
XMLString _publicId;
XMLString _systemId;
friend class Document;
};
//
// inlines
//
inline const XMLString& Notation::publicId() const
{
return _publicId;
}
inline const XMLString& Notation::systemId() const
{
return _systemId;
}
} } // namespace Poco::XML
#endif // DOM_Notation_INCLUDED
| 30.517241 | 113 | 0.738418 | [
"object"
] |
084729e545a2fce298c39996e6f17fbea414c617 | 1,965 | h | C | escos/src/mmitss/libSieMmitss/Performance.h | OSADP/MMITSS_THEA | 53ef55d0622f230002c75046db6af295592dbf0a | [
"Apache-2.0"
] | null | null | null | escos/src/mmitss/libSieMmitss/Performance.h | OSADP/MMITSS_THEA | 53ef55d0622f230002c75046db6af295592dbf0a | [
"Apache-2.0"
] | null | null | null | escos/src/mmitss/libSieMmitss/Performance.h | OSADP/MMITSS_THEA | 53ef55d0622f230002c75046db6af295592dbf0a | [
"Apache-2.0"
] | null | null | null | //**********************************************************************************
//
// © 2015 Arizona Board of Regents on behalf of the University of Arizona with rights
// granted for USDOT OSADP distribution with the Apache 2.0 open source license.
//
//**********************************************************************************
#pragma once
#include <vector>
class Performance
{
public:
int LQV[8][5]; // Last Queued Vehicle in which we are interested!!
int LQV_stop_flag[8][5]; // the stop flag of last queued vehicle
double maximum_estimation[8][5]; // Estimation of the distance to the last queued vehicle
double maximum_estimation2[8][5]; // Estimation of the distance to the second last queued
// vehicle
int queue_counter[8][5]; // Number of Vehicles in the queue
double LQV_discharging[8][5]; // Last Queued Vehicle Start time of discharging
std::map<int, std::map<int, int>> vehicle_count;
float App_Ext_Tardity[12]; // Extended Tardity value for each approach
int App_Ext_counter[12]; // To count the number of vehicles for each approach in Extended
// Tardity
float vehicle_tardity[12]; // Tardity value for each vehicle
float total_distance[12]; // Summation of all distances traveled by vehicles used in tardity
// function
int num_observation[12]; // Number of observations of the vehicles that completed their trip
// within the range
float App_TT[12]; // Approach TT as follows: 0:NB, 1:EB, 2:SB, 3:WB, 4:NBLT, 5:NBRT, 6:EBLT,
// 7:EBRT, 8:SBLT, 9:SBRT, 10:WBLT, 11:WBRT
float App_Delay[12]; // Approach Delay as follows: 0:NB, 1:EB, 2:SB, 3:WB
float App_numstops[12]; // Average number of stops per vehicle per approach
int App_throughput[12]; // vehicle throughput
};
| 50.384615 | 99 | 0.583715 | [
"vector"
] |
08485e04f9603174c8580560f126314d56864ddf | 2,709 | h | C | 3es-core/3esplanegeom.h | data61/3es-core | 597f25aa604cb446dcc1f08b9d3bc8f89f3043b9 | [
"Zlib"
] | 2 | 2020-06-11T04:16:08.000Z | 2020-06-20T19:57:10.000Z | 3es-core/3esplanegeom.h | csiro-robotics/3es-core | 597f25aa604cb446dcc1f08b9d3bc8f89f3043b9 | [
"Zlib"
] | null | null | null | 3es-core/3esplanegeom.h | csiro-robotics/3es-core | 597f25aa604cb446dcc1f08b9d3bc8f89f3043b9 | [
"Zlib"
] | null | null | null | //
// author: Kazys Stepanas
//
#ifndef _3ESPLANE_H_
#define _3ESPLANE_H_
#include "3esvector4.h"
namespace tes
{
/// Plane geometry functions.
///
/// A plane is defined by a @c Vector4 where the xyz components are the normal and the w component is the
/// plane distance.
namespace planegeom
{
/// Point classification results.
enum PlaneClassification
{
PC_Behind = -1, ///< Behind the plane.
PC_On = 0, ///< On or part of the plane.
PC_InFront = 1 ///< In front of the plane.
};
/// Create a plane from a normal and distance (D) value.
/// @param normal The plane normal. Must be normalised.
/// @param distance the plane D component.
/// @return The plane equation.
template <typename T>
inline Vector4<T> create(const Vector3<T> &normal, T distance)
{
return Vector4f(normal, distance);
}
/// Create a plane from a normal and a point on the plane.
/// @param normal The plane normal. Must be normalised.
/// @param pointOnPlane An arbitrary point on the plane.
/// @return The plane equation.
template <typename T>
Vector4<T> fromNormalAndPoint(const Vector3<T> &normal, const Vector3<T> &pointOnPlane)
{
const T distance = -normal.dot(pointOnPlane);
return Vector4<T>(normal, distance);
}
/// Calculate the signed distance between the @p plane and @p point.
/// Positive is in front, negative behind and zero on.
/// @param plane The plane equation.
/// @param point The point of interest.
/// @return The shorted distance from @p point to the plane (signed).
template <typename T>
inline T signedDistanceToPoint(const Vector4<T> &plane, const Vector3<T> &point)
{
return plane.xyz().dot(point) + plane.w;
}
/// Project a @p point onto a @p plane.
/// @param plane The plane equation.
/// @param point The point of interest.
/// @return The closest point on the plane to @p point.
template <typename T>
inline Vector3<T> projectPoint(const Vector4<T> &plane, const Vector3<T> &point)
{
const T signedDistance = signedDistanceToPoint(plane, point);
return point - plane.xyz() * signedDistance;
}
/// Classify a point with respect to a plane (see @c PlaneClassification).
/// @param plane The plane equation.
/// @param point The point of interest.
/// @param epsilon Epsilon value used as a tolerance for @c PC_On results.
/// @return The point's @c PlaneClassification.
template <typename T>
inline int classifyPoint(const Vector4<T> &plane, const Vector3<T> &point, T epsilon = 0)
{
const T signedDistance = signedDistanceToPoint(plane, point);
if (signedDistance < -epsilon)
{
return PC_Behind;
}
if (signedDistance > epsilon)
{
return PC_InFront;
}
return PC_On;
}
} // namespace planegeom
} // namespace tes
#endif // _3ESSPLANE_H_
| 28.515789 | 105 | 0.710594 | [
"geometry"
] |
085016c3588d426912c7c0723b7cc3f4a149eeac | 4,585 | h | C | src/Processors/Pipe.h | amosnothing/ClickHouse | cf49a839806290c41a3a1ccd5808687d7ccaca78 | [
"Apache-2.0"
] | 2 | 2020-06-08T04:11:50.000Z | 2020-06-24T12:27:37.000Z | src/Processors/Pipe.h | amosnothing/ClickHouse | cf49a839806290c41a3a1ccd5808687d7ccaca78 | [
"Apache-2.0"
] | 3 | 2020-02-18T14:59:34.000Z | 2020-02-19T10:42:18.000Z | src/Processors/Pipe.h | amosnothing/ClickHouse | cf49a839806290c41a3a1ccd5808687d7ccaca78 | [
"Apache-2.0"
] | 2 | 2021-01-04T06:43:51.000Z | 2021-05-14T03:17:13.000Z | #pragma once
#include <Processors/IProcessor.h>
#include <Processors/Sources/SourceWithProgress.h>
namespace DB
{
class Pipe;
using Pipes = std::vector<Pipe>;
class IStorage;
using StoragePtr = std::shared_ptr<IStorage>;
/// Pipe is a set of processors which represents the part of pipeline with single output.
/// All processors in pipe are connected. All ports are connected except the output one.
class Pipe
{
public:
/// Create from source. It must have no input ports and single output.
explicit Pipe(ProcessorPtr source);
/// Connect several pipes together with specified transform.
/// Transform must have the number of inputs equals to the number of pipes. And single output.
/// Will connect pipes outputs with transform inputs automatically.
Pipe(Pipes && pipes, ProcessorPtr transform);
/// Create pipe from output port. If pipe was created that way, it possibly will not have tree shape.
explicit Pipe(OutputPort * port);
Pipe(const Pipe & other) = delete;
Pipe(Pipe && other) = default;
Pipe & operator=(const Pipe & other) = delete;
Pipe & operator=(Pipe && other) = default;
/// Append processors to pipe. After this, it possibly will not have tree shape.
void addProcessors(const Processors & processors_);
OutputPort & getPort() const { return *output_port; }
const Block & getHeader() const { return output_port->getHeader(); }
/// Add transform to pipe. It must have single input and single output (is checked).
/// Input will be connected with current output port, output port will be updated.
void addSimpleTransform(ProcessorPtr transform);
Processors detachProcessors() && { return std::move(processors); }
/// Specify quotas and limits for every ISourceWithProgress.
void setLimits(const SourceWithProgress::LocalLimits & limits);
void setQuota(const std::shared_ptr<const EnabledQuota> & quota);
/// Set information about preferred executor number for sources.
void pinSources(size_t executor_number);
void enableQuota();
/// Totals and extremes port.
void setTotalsPort(OutputPort * totals_) { totals = totals_; }
void setExtremesPort(OutputPort * extremes_) { extremes = extremes_; }
OutputPort * getTotalsPort() const { return totals; }
OutputPort * getExtremesPort() const { return extremes; }
size_t maxParallelStreams() const { return max_parallel_streams; }
/// Do not allow to change the table while the processors of pipe are alive.
/// TODO: move it to pipeline.
void addTableLock(const TableLockHolder & lock) { table_locks.push_back(lock); }
/// This methods are from QueryPipeline. Needed to make conversion from pipeline to pipe possible.
void addInterpreterContext(std::shared_ptr<Context> context) { interpreter_context.emplace_back(std::move(context)); }
void addStorageHolder(StoragePtr storage) { storage_holders.emplace_back(std::move(storage)); }
const std::vector<TableLockHolder> & getTableLocks() const { return table_locks; }
const std::vector<std::shared_ptr<Context>> & getContexts() const { return interpreter_context; }
const std::vector<StoragePtr> & getStorageHolders() const { return storage_holders; }
private:
Processors processors;
OutputPort * output_port = nullptr;
OutputPort * totals = nullptr;
OutputPort * extremes = nullptr;
/// It is the max number of processors which can be executed in parallel for each step. See QueryPipeline::Streams.
size_t max_parallel_streams = 0;
std::vector<TableLockHolder> table_locks;
/// Some processors may implicitly use Context or temporary Storage created by Interpreter.
/// But lifetime of Streams is not nested in lifetime of Interpreters, so we have to store it here,
/// because QueryPipeline is alive until query is finished.
std::vector<std::shared_ptr<Context>> interpreter_context;
std::vector<StoragePtr> storage_holders;
/// This private constructor is used only from QueryPipeline.
/// It is not public, because QueryPipeline checks that processors are connected and have single output,
/// and therefore we can skip those checks.
/// Note that Pipe represents a tree if it was created using public interface. But this constructor can't assert it.
/// So, it's possible that TreeExecutorBlockInputStream could be unable to convert such Pipe to IBlockInputStream.
explicit Pipe(Processors processors_, OutputPort * output_port, OutputPort * totals, OutputPort * extremes);
friend class QueryPipeline;
};
}
| 44.95098 | 122 | 0.732388 | [
"shape",
"vector",
"transform"
] |
08529aae4ff6cc98d9e7b4ae5893500b33e1760c | 4,281 | h | C | src/include/metrics/metrics_manager.h | ScottLiao920/noisepage | 4ffb238529645efcaae99255f84d002f8d7fdf7d | [
"MIT"
] | 971 | 2020-09-13T10:24:02.000Z | 2022-03-31T07:02:51.000Z | src/include/metrics/metrics_manager.h | ScottLiao920/noisepage | 4ffb238529645efcaae99255f84d002f8d7fdf7d | [
"MIT"
] | 1,019 | 2018-07-20T23:11:10.000Z | 2020-09-10T06:41:42.000Z | src/include/metrics/metrics_manager.h | ScottLiao920/noisepage | 4ffb238529645efcaae99255f84d002f8d7fdf7d | [
"MIT"
] | 318 | 2018-07-23T16:48:16.000Z | 2020-09-07T09:46:31.000Z | #pragma once
#include <bitset>
#include <memory>
#include <thread> // NOLINT
#include <unordered_map>
#include <vector>
#include "common/managed_pointer.h"
#include "common/spin_latch.h"
#include "common/thread_context.h"
#include "metrics/abstract_raw_data.h"
#include "metrics/metrics_store.h"
namespace noisepage::settings {
class Callbacks;
}
namespace noisepage::task {
class TaskManager;
}
namespace noisepage::metrics {
/**
* Background thread that periodically collects data from thread level collectors
*/
class MetricsManager {
public:
MetricsManager();
/**
* Aggregate metrics from all threads which have collected stats, combine with what was previously collected
*
* @warning this method should be called before manipulating the worker pool, especially if
* some of the worker threads are reassigned to tasks other than execution.
*/
void Aggregate();
/**
* Called by the thread to get a MetricsStore object
*/
void RegisterThread();
/**
* Should be called by the thread when it is guaranteed to no longer be collecting any more metrics, otherwise,
* segfault could happen when the unique_ptr releases the MetricsStore
*/
void UnregisterThread();
/**
* @return the MetricsManager's aggregated metrics. Currently used in tests
*/
std::array<std::unique_ptr<AbstractRawData>, NUM_COMPONENTS> &AggregatedMetrics() { return aggregated_metrics_; }
/**
* @param component to be tested
* @return true if metrics are enabled for this component, false otherwise
*/
bool ComponentEnabled(const MetricsComponent component) {
return enabled_metrics_.test(static_cast<uint8_t>(component));
}
/**
* Output aggregated metrics.
*/
void ToOutput(common::ManagedPointer<task::TaskManager> task_manager) const;
/**
* @param component to be enabled
*/
void EnableMetric(const MetricsComponent component) {
common::SpinLatch::ScopedSpinLatch guard(&latch_);
NOISEPAGE_ASSERT(!ComponentEnabled(component), "Metric is already enabled.");
ResetMetric(component);
enabled_metrics_.set(static_cast<uint8_t>(component), true);
}
/**
* @param component to update
* @param sample_rate sampling rate of 0 to 100, expressed as a percentage of data points. 100 means all data, 0 none
*/
void SetMetricSampleRate(MetricsComponent component, uint8_t sample_rate);
/**
* @param component to be disabled
*/
void DisableMetric(const MetricsComponent component) {
common::SpinLatch::ScopedSpinLatch guard(&latch_);
NOISEPAGE_ASSERT(ComponentEnabled(component), "Metric is already disabled.");
enabled_metrics_.set(static_cast<uint8_t>(component), false);
aggregated_metrics_[static_cast<uint8_t>(component)].reset(nullptr);
}
/**
* Updates the output type of a specific metric component
* @param component to change
* @param output of the component
*/
void SetMetricOutput(const MetricsComponent component, MetricsOutput output) {
common::SpinLatch::ScopedSpinLatch guard(&latch_);
metrics_output_[static_cast<uint8_t>(component)] = output;
}
/**
* Retrieves the output type of a specific metric component
* @param component whose output to retrieve
* @return output type of the specified component
*/
metrics::MetricsOutput GetMetricOutput(const MetricsComponent component) {
common::SpinLatch::ScopedSpinLatch guard(&latch_);
return metrics_output_[static_cast<uint8_t>(component)];
}
private:
/**
* Dump aggregated metrics to CSV files.
*/
void ToCSV(uint8_t component) const;
/**
* Dump aggregated metrics to internal tables.
*/
void ToDB(uint8_t component, common::ManagedPointer<task::TaskManager> task_manager) const;
void ResetMetric(MetricsComponent component) const;
mutable common::SpinLatch latch_;
std::unordered_map<std::thread::id, std::unique_ptr<MetricsStore>> stores_map_;
std::array<std::unique_ptr<AbstractRawData>, NUM_COMPONENTS> aggregated_metrics_;
std::bitset<NUM_COMPONENTS> enabled_metrics_ = 0x0;
std::array<std::vector<bool>, NUM_COMPONENTS> samples_mask_; // std::vector<bool> may use a bitset for efficiency
std::array<MetricsOutput, NUM_COMPONENTS> metrics_output_;
};
} // namespace noisepage::metrics
| 30.361702 | 119 | 0.736977 | [
"object",
"vector"
] |
08565b8a92cde6060b17f15fa5af6c2746bf9569 | 1,294 | h | C | myvision.h | ids-imaging/ids-nxt-vision-app-multi-cnn-classifier | 894488306a883e981cfc44ca30ad19a27c2109fa | [
"Apache-2.0"
] | null | null | null | myvision.h | ids-imaging/ids-nxt-vision-app-multi-cnn-classifier | 894488306a883e981cfc44ca30ad19a27c2109fa | [
"Apache-2.0"
] | null | null | null | myvision.h | ids-imaging/ids-nxt-vision-app-multi-cnn-classifier | 894488306a883e981cfc44ca30ad19a27c2109fa | [
"Apache-2.0"
] | null | null | null | #ifndef MYVISION_H
#define MYVISION_H
#include "cnnmanager_v2.h"
#include <configurableroi.h>
#include <vision.h>
#include <QImage>
/**
* @brief The app-specific vision object
*/
class MyVision : public IDS::NXT::Vision {
Q_OBJECT
public:
/**
* @brief Helper class for the assignment of a CNN to a ROI
*/
class RoiCnn {
public:
QRect roi;
QString roiName;
IDS::NXT::CNNv2::CnnData cnnData;
bool operator<(const RoiCnn& rhs) const {
return roiName < rhs.roiName;
}
};
using RoiCnnList = QList<RoiCnn>;
using RoiCnnResultMap = std::map<RoiCnn, std::unique_ptr<IDS::NXT::CNNv2::MultiBuffer>>;
/**
* @brief Constructor
*/
MyVision() = default;
/**
* @brief Start the image processing
*/
void process() override;
/**
* @brief Abort the image processing
*/
void abort() override;
/**
* @brief Getter for the vision result
* @return Result
*/
RoiCnnResultMap result();
/**
* @brief Setter for ROI/CNN configuration
* @param roiCnnConfig Configuration object
*/
void setCnnData(const RoiCnnList& roiCnnConfig);
private:
RoiCnnResultMap _result;
RoiCnnList _cnnData;
};
#endif // MYVISION_H
| 19.606061 | 92 | 0.611283 | [
"object"
] |
086c907c0ee559dc06e413c7290055c69557dbe9 | 1,655 | h | C | src/ComplexNets/GraphGenerator.h | joseignaciosg/complexnets2014 | 5bde4ce11ea4593c5bc1908b082cba967a9230bb | [
"AFL-3.0"
] | null | null | null | src/ComplexNets/GraphGenerator.h | joseignaciosg/complexnets2014 | 5bde4ce11ea4593c5bc1908b082cba967a9230bb | [
"AFL-3.0"
] | null | null | null | src/ComplexNets/GraphGenerator.h | joseignaciosg/complexnets2014 | 5bde4ce11ea4593c5bc1908b082cba967a9230bb | [
"AFL-3.0"
] | null | null | null | // This toolbox is licensed under the Academic Free License 3.0.
// Instituto Tecnológico de Buenos Aires (ITBA).
// Last modification: December 19th, 2012.
#ifndef GRAPH_GENERATOR_H
#define GRAPH_GENERATOR_H
#include "../ComplexNets/typedefs.h"
#include "../ComplexNets/MolloyReedGraphReader.h"
using namespace std;
class GraphGenerator {
private:
typedef struct PolarPosition { double r; double theta; } PolarPosition;
GraphGenerator();
static GraphGenerator *instance;
float distanceBetweenVertex(unsigned int vertex1Id, unsigned int vertex2Id);
void addVertexPosition();
void addEdges(Graph* graph, Vertex* vertex, map<float, unsigned int> distance, unsigned int quant, vector<unsigned int>* vertexIndexes);
inline double hiperbolicDistance(PolarPosition p1, PolarPosition p2);
inline double getMaxRadius(int i, float a, float c);
inline PolarPosition getRandomHyperbolicCoordinates( float a, double maxr );
public:
static GraphGenerator *getInstance();
Graph *generateGraphFromFile(string path, bool directed, bool multigraph);
DirectedGraph *generateDirectedGraphFromFile(string path, bool multigraph);
WeightedGraph *generateWeightedGraphFromFile(string path, bool directed, bool multigraph);
Graph* generateErdosRenyiGraph(unsigned int n, float p);
Graph* generateBarabasiAlbertGraph(unsigned int m_0, unsigned int m, unsigned int n);
Graph* generateHotExtendedGraph(unsigned int m, unsigned int n, float xi, unsigned int q, float r);
Graph* generateMolloyReedGraph(string path);
Graph* generateHiperbolicGraph(unsigned int n, float a, float c);
double getExpectedAvgNodeDeg(unsigned int n, float a, float c);
};
#endif
| 41.375 | 137 | 0.795166 | [
"vector"
] |
086de6ec60171594b577e759963859d61414d47f | 1,282 | c | C | tst_shp.c | BTNRH/sigpro | df35c6cd7d87545676bc2a516ab7f5d1f0e6a960 | [
"CC-BY-3.0"
] | 3 | 2018-07-16T19:36:54.000Z | 2021-08-29T19:42:30.000Z | tst_shp.c | BTNRH/sigpro | df35c6cd7d87545676bc2a516ab7f5d1f0e6a960 | [
"CC-BY-3.0"
] | null | null | null | tst_shp.c | BTNRH/sigpro | df35c6cd7d87545676bc2a516ab7f5d1f0e6a960 | [
"CC-BY-3.0"
] | 4 | 2018-06-29T16:46:48.000Z | 2020-06-12T17:52:25.000Z | // tst_shp.c - test frequency-shaping functions
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include "sigpro.h"
#define NT 6
#define NF 250
#define NP 2040
void
wr_spec(float *x, int n, double fs, char *fn)
{
float *f, *y;
int i, n1;
FILE *fp;
n1 = n / 2 + 1;
f = (float *) calloc(n + 2, sizeof(float));
y = (float *) calloc(n + 2, sizeof(float));
sp_linspace(f, n1, 0, fs / 2);
sp_copy(x, y, n);
sp_rcfft(y, n);
sp_cdb(y, y, n1);
fp = fopen(fn, "wt");
fprintf(fp, "; %s\n", fn);
for (i = 0; i < n1; i++) {
fprintf(fp, "%12.4g %12.4g\n", f[i], y[i]);
}
fclose(fp);
free(f);
free(y);
}
int
main(int ac, char **av)
{
static double fs = 20000;
static float x[NP+2];
static float fr[NT] = {0, 2000, 4000, 6000, 8000, 10000};
static float at[NT] = {0, 0, 40, 40, 0, 0};
// frequency-shape FIR
sp_firdb(x, NF, fs, fr, at, NT);
wr_spec(x, NF, fs, "spec1.txt");
// white noise wave form
sp_randflat(x, NP);
wr_spec(x, NP, fs, "spec2.txt");
// filtered waveform
sp_frqshp(x, x, NP, NF, fs, fr, at, NT, 1);
wr_spec(x, NP, fs, "spec3.txt");
return(0);
}
| 20.349206 | 62 | 0.49844 | [
"shape"
] |
08726959ef559a6f1bbb717f9d8c341bad670138 | 4,681 | h | C | aws-cpp-sdk-forecast/include/aws/forecast/model/ListExplainabilitiesResult.h | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-02-12T08:09:30.000Z | 2022-02-12T08:09:30.000Z | aws-cpp-sdk-forecast/include/aws/forecast/model/ListExplainabilitiesResult.h | perfectrecall/aws-sdk-cpp | fb8cbebf2fd62720b65aeff841ad2950e73d8ebd | [
"Apache-2.0"
] | 1 | 2022-01-03T23:59:37.000Z | 2022-01-03T23:59:37.000Z | aws-cpp-sdk-forecast/include/aws/forecast/model/ListExplainabilitiesResult.h | ravindra-wagh/aws-sdk-cpp | 7d5ff01b3c3b872f31ca98fb4ce868cd01e97696 | [
"Apache-2.0"
] | 1 | 2021-12-30T04:25:33.000Z | 2021-12-30T04:25:33.000Z | /**
* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#pragma once
#include <aws/forecast/ForecastService_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/core/utils/memory/stl/AWSString.h>
#include <aws/forecast/model/ExplainabilitySummary.h>
#include <utility>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace ForecastService
{
namespace Model
{
class AWS_FORECASTSERVICE_API ListExplainabilitiesResult
{
public:
ListExplainabilitiesResult();
ListExplainabilitiesResult(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
ListExplainabilitiesResult& operator=(const Aws::AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
/**
* <p>An array of objects that summarize the properties of each Explainability
* resource.</p>
*/
inline const Aws::Vector<ExplainabilitySummary>& GetExplainabilities() const{ return m_explainabilities; }
/**
* <p>An array of objects that summarize the properties of each Explainability
* resource.</p>
*/
inline void SetExplainabilities(const Aws::Vector<ExplainabilitySummary>& value) { m_explainabilities = value; }
/**
* <p>An array of objects that summarize the properties of each Explainability
* resource.</p>
*/
inline void SetExplainabilities(Aws::Vector<ExplainabilitySummary>&& value) { m_explainabilities = std::move(value); }
/**
* <p>An array of objects that summarize the properties of each Explainability
* resource.</p>
*/
inline ListExplainabilitiesResult& WithExplainabilities(const Aws::Vector<ExplainabilitySummary>& value) { SetExplainabilities(value); return *this;}
/**
* <p>An array of objects that summarize the properties of each Explainability
* resource.</p>
*/
inline ListExplainabilitiesResult& WithExplainabilities(Aws::Vector<ExplainabilitySummary>&& value) { SetExplainabilities(std::move(value)); return *this;}
/**
* <p>An array of objects that summarize the properties of each Explainability
* resource.</p>
*/
inline ListExplainabilitiesResult& AddExplainabilities(const ExplainabilitySummary& value) { m_explainabilities.push_back(value); return *this; }
/**
* <p>An array of objects that summarize the properties of each Explainability
* resource.</p>
*/
inline ListExplainabilitiesResult& AddExplainabilities(ExplainabilitySummary&& value) { m_explainabilities.push_back(std::move(value)); return *this; }
/**
* <p>Returns this token if the response is truncated. To retrieve the next set of
* results, use the token in the next request.</p>
*/
inline const Aws::String& GetNextToken() const{ return m_nextToken; }
/**
* <p>Returns this token if the response is truncated. To retrieve the next set of
* results, use the token in the next request.</p>
*/
inline void SetNextToken(const Aws::String& value) { m_nextToken = value; }
/**
* <p>Returns this token if the response is truncated. To retrieve the next set of
* results, use the token in the next request.</p>
*/
inline void SetNextToken(Aws::String&& value) { m_nextToken = std::move(value); }
/**
* <p>Returns this token if the response is truncated. To retrieve the next set of
* results, use the token in the next request.</p>
*/
inline void SetNextToken(const char* value) { m_nextToken.assign(value); }
/**
* <p>Returns this token if the response is truncated. To retrieve the next set of
* results, use the token in the next request.</p>
*/
inline ListExplainabilitiesResult& WithNextToken(const Aws::String& value) { SetNextToken(value); return *this;}
/**
* <p>Returns this token if the response is truncated. To retrieve the next set of
* results, use the token in the next request.</p>
*/
inline ListExplainabilitiesResult& WithNextToken(Aws::String&& value) { SetNextToken(std::move(value)); return *this;}
/**
* <p>Returns this token if the response is truncated. To retrieve the next set of
* results, use the token in the next request.</p>
*/
inline ListExplainabilitiesResult& WithNextToken(const char* value) { SetNextToken(value); return *this;}
private:
Aws::Vector<ExplainabilitySummary> m_explainabilities;
Aws::String m_nextToken;
};
} // namespace Model
} // namespace ForecastService
} // namespace Aws
| 35.462121 | 159 | 0.703482 | [
"vector",
"model"
] |
087659d0555e5cd9b0d32e0c4414d1eb3bc4a4ed | 88,910 | c | C | test/monster_test/monster_test.c | JoelsonCarl/flatcc | 32629a3e4aa7e3fb4b51c52fd8c1519529c8df7f | [
"Apache-2.0"
] | null | null | null | test/monster_test/monster_test.c | JoelsonCarl/flatcc | 32629a3e4aa7e3fb4b51c52fd8c1519529c8df7f | [
"Apache-2.0"
] | null | null | null | test/monster_test/monster_test.c | JoelsonCarl/flatcc | 32629a3e4aa7e3fb4b51c52fd8c1519529c8df7f | [
"Apache-2.0"
] | null | null | null | #include <stdio.h>
#include "monster_test_builder.h"
#include "monster_test_verifier.h"
#include "flatcc/support/hexdump.h"
#include "flatcc/support/elapsed.h"
#include "../../config/config.h"
/*
* Convenience macro to deal with long namespace names,
* and to make code reusable with other namespaces.
*
* Note: we could also use
*
* #define ns(x) MyGame_Example_ ## x
*
* but it wouldn't doesn't handled nested ns calls.
*
* For historic reason some of this test does not use the ns macro
* and some avoid nesting ns calls by placing parenthesis differently
* although this isn't required with this wrapper macro.
*/
#undef ns
#define ns(x) FLATBUFFERS_WRAP_NAMESPACE(MyGame_Example, x)
#undef nsf
#define nsf(x) FLATBUFFERS_WRAP_NAMESPACE(Fantasy, x)
/*
* Wrap the common namespace (flatbuffers_). Many operations in the
* common namespace such as `flatbuffers_string_create` are also mapped
* to member fields such as `MyGame_Example_Monster_name_create` and
* this macro provides a consistent interface to namespaces with
* `nsc(string_create)` similar to `ns(Monster_name_create)`.
*/
#undef nsc
#define nsc(x) FLATBUFFERS_WRAP_NAMESPACE(flatbuffers, x)
/* A helper to simplify creating buffers vectors from C-arrays. */
#define c_vec_len(V) (sizeof(V)/sizeof((V)[0]))
static const char zero_pad[100];
int verify_empty_monster(void *buffer)
{
/* Proper id given. */
ns(Monster_table_t) monster = ns(Monster_as_root_with_identifier)(buffer, ns(Monster_identifier));
/* Invalid id. */
ns(Monster_table_t) monster2 = ns(Monster_as_root_with_identifier(buffer, "1234"));
/* `with_id` can also mean ignore id when given a null argument. */
ns(Monster_table_t) monster3 = ns(Monster_as_root_with_identifier(buffer, 0));
/* Excessive text in identifier is ignored. */
ns(Monster_table_t) monster4 = ns(Monster_as_root_with_identifier(buffer, "MONSX"));
/* Default id should match proper id. */
ns(Monster_table_t) monster5 = ns(Monster_as_root(buffer));
if (!monster) {
printf("Monster not available\n");
return -1;
}
if (monster2) {
printf("Monster should not accept invalid identifier\n");
return -1;
}
if (monster3 != monster) {
printf("Monster should ignore identifier when given a null id\n");
return -1;
}
if (monster4 != monster) {
printf("Monster should accept a string as valid identifier");
return -1;
}
if (monster5 != monster) {
printf("Monster with default id should be accepted");
return -1;
}
if (ns(Monster_hp(monster)) != 100) {
printf("Health points are not as expected\n");
return -1;
}
if (ns(Monster_hp_is_present(monster))) {
printf("Health Points should default\n");
return -1;
}
if (ns(Monster_pos_is_present(monster))) {
printf("Position should be present\n");
return -1;
}
if (ns(Monster_pos(monster)) != 0) {
printf("Position shouldn't be available\n");
return -1;
}
return 0;
}
int test_enums(flatcc_builder_t *B)
{
if (ns(neg_enum_neg1) != -12) {
printf("neg_enum_neg1 should be -12, was %d\n", ns(neg_enum_neg1));
return -1;
}
if (ns(neg_enum_neg2) != -11) {
printf("neg_enum_neg1 should be -11, was %d\n", ns(neg_enum_neg2));
return -1;
}
if (ns(int_enum_int1) != 2) {
printf("int_enum_int1 should be 2\n");
return -1;
}
if (ns(int_enum_int2) != 42) {
printf("int_enum_int2 should be 42\n");
return -1;
}
if (ns(hex_enum_hexneg) != -2) {
printf("enum hexneg should be -2\n");
return -1;
}
if (ns(hex_enum_hex1) != 3) {
printf("hex_enum_hex1 should be 3\n");
return -1;
}
if (ns(hex_enum_hex2) != INT32_C(0x7eafbeaf)) {
printf("hex_enum_hex2 should be 0x7eafbeaf\n");
return -1;
}
return 0;
}
int test_type_aliases(flatcc_builder_t *B)
{
int ret = 0;
void *buffer = 0;
size_t size;
ns(TypeAliases_table_t) ta;
flatbuffers_uint8_vec_ref_t v8_ref;
flatbuffers_double_vec_ref_t vf64_ref;
flatcc_builder_reset(B);
v8_ref = flatbuffers_uint8_vec_create(B, 0, 0);
vf64_ref = flatbuffers_double_vec_create(B, 0, 0);
ns(TypeAliases_create_as_root(B,
INT8_MIN, UINT8_MAX, INT16_MIN, UINT16_MAX,
INT32_MIN, UINT32_MAX, INT64_MIN, UINT64_MAX, 2.3f, 2.3, v8_ref, vf64_ref));
buffer = flatcc_builder_finalize_aligned_buffer(B, &size);
if ((ret = ns(TypeAliases_verify_as_root(buffer, size)))) {
hexdump("TypeAliases buffer", buffer, size, stderr);
printf("could not verify TypeAliases table, got %s\n", flatcc_verify_error_string(ret));
goto done;
}
ta = ns(TypeAliases_as_root(buffer));
if (ns(TypeAliases_i8(ta)) != INT8_MIN) goto failed;
if (ns(TypeAliases_i16(ta)) != INT16_MIN) goto failed;
if (ns(TypeAliases_i32(ta)) != INT32_MIN) goto failed;
if (ns(TypeAliases_i64(ta)) != INT64_MIN) goto failed;
if (ns(TypeAliases_u8(ta)) != UINT8_MAX) goto failed;
if (ns(TypeAliases_u16(ta)) != UINT16_MAX) goto failed;
if (ns(TypeAliases_u32(ta)) != UINT32_MAX) goto failed;
if (ns(TypeAliases_u64(ta)) != UINT64_MAX) goto failed;
if (ns(TypeAliases_f32(ta)) != 2.3f) goto failed;
if (ns(TypeAliases_f64(ta)) != 2.3) goto failed;
if (sizeof(ns(TypeAliases_i8(ta))) != 1) goto failed;
if (sizeof(ns(TypeAliases_i16(ta))) != 2) goto failed;
if (sizeof(ns(TypeAliases_i32(ta))) != 4) goto failed;
if (sizeof(ns(TypeAliases_i64(ta))) != 8) goto failed;
if (sizeof(ns(TypeAliases_u8(ta))) != 1) goto failed;
if (sizeof(ns(TypeAliases_u16(ta))) != 2) goto failed;
if (sizeof(ns(TypeAliases_u32(ta))) != 4) goto failed;
if (sizeof(ns(TypeAliases_u64(ta))) != 8) goto failed;
if (sizeof(ns(TypeAliases_f32(ta))) != 4) goto failed;
if (sizeof(ns(TypeAliases_f64(ta))) != 8) goto failed;
done:
flatcc_builder_aligned_free(buffer);
return ret;
failed:
ret = -1;
printf("Scalar type alias has unexpected value or size\n");
goto done;
}
int test_empty_monster(flatcc_builder_t *B)
{
int ret;
ns(Monster_ref_t) root;
void *buffer;
size_t size;
flatcc_builder_reset(B);
flatbuffers_buffer_start(B, ns(Monster_identifier));
ns(Monster_start(B));
/* Cannot make monster empty as name is required. */
ns(Monster_name_create_str(B, "MyMonster"));
root = ns(Monster_end(B));
flatbuffers_buffer_end(B, root);
buffer = flatcc_builder_finalize_aligned_buffer(B, &size);
hexdump("empty monster table", buffer, size, stderr);
if ((ret = verify_empty_monster(buffer))) {
goto done;
}
if ((ret = ns(Monster_verify_as_root_with_identifier(buffer, size, ns(Monster_identifier))))) {
printf("could not verify empty monster, got %s\n", flatcc_verify_error_string(ret));
return -1;
}
/*
* Note: this will assert if the verifier is set to assert during
* debugging. Also not that a buffer size - 1 is not necessarily
* invalid, but because we pack vtables tight at the end, we expect
* failure in this case.
*/
if (flatcc_verify_ok == ns(Monster_verify_as_root(
buffer, size - 1))) {
printf("Monster verify failed to detect short buffer\n");
return -1;
}
done:
flatcc_builder_aligned_free(buffer);
return ret;
}
int test_typed_empty_monster(flatcc_builder_t *B)
{
int ret = -1;
ns(Monster_ref_t) root;
void *buffer;
size_t size;
flatbuffers_fid_t fid = { 0 };
flatcc_builder_reset(B);
flatbuffers_buffer_start(B, ns(Monster_type_identifier));
ns(Monster_start(B));
/* Cannot make monster empty as name is required. */
ns(Monster_name_create_str(B, "MyMonster"));
root = ns(Monster_end(B));
flatbuffers_buffer_end(B, root);
buffer = flatcc_builder_finalize_aligned_buffer(B, &size);
hexdump("empty typed monster table", buffer, size, stderr);
if (flatbuffers_get_type_hash(buffer) != flatbuffers_type_hash_from_name("MyGame.Example.Monster")) {
printf("Monster does not have the expected type, got %lx\n", (unsigned long)flatbuffers_get_type_hash(buffer));
goto done;
}
if (!flatbuffers_has_type_hash(buffer, ns(Monster_type_hash))) {
printf("Monster does not have the expected type\n");
goto done;
}
if (!flatbuffers_has_type_hash(buffer, 0x330ef481)) {
printf("Monster does not have the expected type\n");
goto done;
}
if (!verify_empty_monster(buffer)) {
printf("typed empty monster should not verify with default identifier\n");
goto done;
}
if ((ret = ns(Monster_verify_as_root_with_identifier(buffer, size, ns(Monster_type_identifier))))) {
printf("could not verify typed empty monster, got %s\n", flatcc_verify_error_string(ret));
goto done;
}
if ((ret = ns(Monster_verify_as_typed_root(buffer, size)))) {
printf("could not verify typed empty monster, got %s\n", flatcc_verify_error_string(ret));
goto done;
}
if ((ret = ns(Monster_verify_as_root_with_type_hash(buffer, size, ns(Monster_type_hash))))) {
printf("could not verify empty monster with type hash, got %s\n", flatcc_verify_error_string(ret));
goto done;
}
if ((ret = ns(Monster_verify_as_root_with_type_hash(buffer, size, flatbuffers_type_hash_from_name("MyGame.Example.Monster"))))) {
printf("could not verify empty monster with explicit type hash, got %s\n", flatcc_verify_error_string(ret));
goto done;
}
flatbuffers_identifier_from_type_hash(0x330ef481, fid);
if ((ret = ns(Monster_verify_as_root_with_identifier(buffer, size, fid)))) {
printf("could not verify typed empty monster, got %s\n", flatcc_verify_error_string(ret));
goto done;
}
if (!ns(Monster_verify_as_root(buffer, size))) {
printf("should not have verified with the original identifier since we use types\n");
goto done;
}
ret = 0;
done:
flatcc_builder_aligned_free(buffer);
return ret;
}
/*
* C standard does not provide support for empty structs,
* but they do exist in FlatBuffers. We can use most operations
* but we cannot declare an instance of not can we take the size of.
* The mytype_size() funciton is provided and returns 0 for empty
* structs.
*
* GCC provides support for empty structs, but it isn't portable,
* and compilers may define sizeof such structs differently.
*/
int verify_table_with_emptystruct(void *buffer)
{
ns(with_emptystruct_table_t) withempty;
const ns(emptystruct_t *) empty;
withempty = ns(with_emptystruct_as_root(buffer));
if (!withempty) {
printf("table with emptystruct not available\n");
return -1;
}
empty = ns(with_emptystruct_empty)(withempty);
if (!empty) {
printf("empty member not available\n");
return -1;
}
// sizeof empty won't compile since it is a void.
//if (sizeof(*empty)) {
if (ns(emptystruct__size())) {
printf("empty isn't really empty\n");
return -1;
}
return 0;
}
int test_table_with_emptystruct(flatcc_builder_t *B)
{
int ret;
ns(emptystruct_t) *empty = 0; /* empty structs cannot instantiated. */
void *buffer;
size_t size;
flatcc_builder_reset(B);
ns(with_emptystruct_create_as_root)(B, empty);
buffer = flatcc_builder_finalize_aligned_buffer(B, &size);
/*
* We should expect an empty table with a vtable holding
* a single entry pointing to the end of the table.
* We could also drop the entry from the vtable, but then what
* would be the point of having an empty struct at all? Here
* we can use it as a cheap presence flag.
*/
hexdump("table with empty struct", buffer, size, stderr);
ret = verify_table_with_emptystruct(buffer);
flatcc_builder_aligned_free(buffer);
return ret;
}
int test_typed_table_with_emptystruct(flatcc_builder_t *B)
{
int ret = 0;
ns(emptystruct_t) *empty = 0; /* empty structs cannot instantiated. */
void *buffer;
size_t size;
flatcc_builder_reset(B);
ns(with_emptystruct_create_as_typed_root(B, empty));
buffer = flatcc_builder_get_direct_buffer(B, &size);
/*
* We should expect an empty table with a vtable holding
* a single entry pointing to the end of the table.
* We could also drop the entry from the vtable, but then what
* would be the point of having an empty struct at all? Here
* we can use it as a cheap presence flag.
*/
hexdump("typed table with empty struct", buffer, size, stderr);
if (flatcc_verify_ok != ns(with_emptystruct_verify_as_root_with_identifier(buffer, size, ns(with_emptystruct_type_identifier)))) {
printf("explicit verify_as_root failed\n");
return -1;
}
if (flatcc_verify_ok != ns(with_emptystruct_verify_as_typed_root(buffer, size))) {
printf("typed verify_as_root failed\n");
return -1;
}
if (flatcc_verify_ok != ns(with_emptystruct_verify_as_root_with_type_hash(buffer, size, ns(with_emptystruct_type_hash)))) {
printf("verify_as_root_with_type_hash failed\n");
return -1;
}
#if 0
flatcc_builder_reset(B);
ns(with_emptystruct_start_as_typed_root(B));
ns(with_emptystruct_end_as_typed_root(B));
buffer = flatcc_builder_get_direct_buffer(B, &size);
#endif
if (!buffer) {
printf("failed to create buffer\n");
return -1;
}
if (!flatbuffers_has_type_hash(buffer, ns(with_emptystruct_type_hash))) {
printf("has_type failed\n");
return -1;
}
if (!flatbuffers_has_type_hash(buffer, 0)) {
printf("null type failed\n");
return -1;
}
if (flatbuffers_has_type_hash(buffer, 1)) {
printf("wrong has type unexpected succeeed\n");
return -1;
}
if (!flatbuffers_has_identifier(buffer, 0)) {
printf("has identifier failed for null id\n");
return -1;
}
if (!flatbuffers_has_identifier(buffer, "\xb6\x37\xdd\xb0")) {
printf("has identifier failed for explicit string\n");
return -1;
}
if (ns(with_emptystruct_as_root(buffer))) {
printf("as_root unexpctedly succeeded\n");
return -1;
}
if (ns(with_emptystruct_as_root_with_type_hash(buffer, 1))) {
printf("with wrong type unexptedly succeeded\n");
return -1;
}
if (!ns(with_emptystruct_as_root_with_identifier(buffer, ns(with_emptystruct_type_identifier)))) {
printf("as_root_with_identifier failed to match type_identifier\n");
return -1;
}
if (!ns(with_emptystruct_as_typed_root(buffer))) {
printf("as_typed_root_failed\n");
return -1;
}
if (!ns(with_emptystruct_as_root_with_type_hash(buffer, 0))) {
printf("with ignored type failed\n");
return -1;
}
return ret;
}
int verify_monster(void *buffer)
{
ns(Monster_table_t) monster, mon, mon2;
ns(Monster_vec_t) monsters;
ns(Any_union_type_t) test_type;
ns(Any_union_t) test_union;
/* This is an encoded struct pointer. */
ns(Vec3_struct_t) vec;
const char *name;
/* This is a more precise type as there is a length field prefix. */
nsc(string_t) name2;
/* This is a native struct type. */
ns(Vec3_t) v;
ns(Test_vec_t) testvec;
ns(Test_t) testvec_data[] = {
{0x10, 0x20}, {0x30, 0x40}, {0x50, 0x60}, {0x70, (int8_t)0x80}, {0x191, (int8_t)0x91}
};
ns(Test_struct_t) test;
nsc(string_vec_t) strings;
nsc(string_t) s;
nsc(bool_vec_t) bools;
ns(Stat_table_t) stat;
int booldata[] = { 0, 1, 1, 0 };
const uint8_t *inv;
size_t i;
if (!nsc(has_identifier(buffer, 0))) {
printf("wrong monster identifier (when ignoring)\n");
return -1;
}
if (!nsc(has_identifier(buffer, "MONS"))) {
printf("wrong monster identifier (when explicit)\n");
return -1;
}
if (!nsc(has_identifier(buffer, "MONSTER"))) {
printf("extra characters in identifier should be ignored\n");
return -1;
}
if (nsc(has_identifier(buffer, "MON1"))) {
printf("accepted wrong monster identifier (when explicit)\n");
return -1;
}
if (!nsc(has_identifier(buffer, ns(Monster_identifier)))) {
printf("wrong monster identifier (via defined identifier)\n");
return -1;
}
if (!(monster = ns(Monster_as_root(buffer)))) {
printf("Monster not available\n");
return -1;
}
if (ns(Monster_hp(monster)) != 80) {
printf("Health points are not as expected\n");
return -1;
}
if (!(vec = ns(Monster_pos(monster)))) {
printf("Position is absent\n");
return -1;
}
if ((size_t)vec & 15) {
printf("Force align of Vec3 struct not correct\n");
}
/* -3.2f is actually -3.20000005 and not -3.2 due to representation loss. */
if (ns(Vec3_z(vec)) != -3.2f) {
printf("Position failing on z coordinate\n");
return -1;
}
if (nsc(is_native_pe())) {
if (vec->x != 1.0f || vec->y != 2.0f || vec->z != -3.2f) {
printf("Position is incorrect\n");
return -1;
}
}
/*
* NOTE: copy_from_pe and friends are provided in the builder
* interface, not the read only interface, but for advanced uses
* these may also be used for read operations.
* Also note that if we want the target struct fully null padded
* the struct must be zeroed first. The _clear operation is one way
* to achieve this - but it is not required for normal read access.
* See common_builder for more details. These operations can
* actually be very useful in their own right, disregarding any
* other flatbuffer logic when dealing with struct endian
* conversions in other protocols.
*/
ns(Vec3_clear(&v)); /* Not strictly needed here. */
ns(Vec3_copy_from_pe(&v, vec));
if (v.x != 1.0f || v.y != 2.0f || v.z != -3.2f) {
printf("Position is incorrect after copy\n");
return -1;
}
if (vec->test1 != 0 || vec->test1 != 0 ||
memcmp(&vec->test3, zero_pad, sizeof(vec->test3)) != 0) {
printf("Zero default not correct for struct\n");
return -1;
}
name = ns(Monster_name(monster));
if (!name || strcmp(name, "MyMonster")) {
printf("Name is not correct\n");
return -1;
}
name2 = ns(Monster_name(monster));
if (nsc(string_len(name)) != 9 || nsc(string_len(name2)) != 9) {
printf("Name length is not correct\n");
return -1;
}
if (ns(Monster_color(monster)) != ns(Color_Green)) {
printf("Monster isn't a green monster\n");
return -1;
}
if (strcmp(ns(Color_name)(ns(Color_Green)), "Green")) {
printf("Enum name map does not have a green solution\n");
return -1;
}
/*
* This is bit tricky because Color is a bit flag, so we can have
* combinations that are expected, but that we do not know. The
* known value logic does not accomodate for that.
*/
if (!ns(Color_is_known_value(ns(Color_Green)))) {
printf("Color enum does not recognize the value of the Green flag\n");
return -1;
}
if (!ns(Color_is_known_value(1))) {
printf("Color enum does not recognize the value of the Red flag\n");
return -1;
}
if (ns(Color_is_known_value(4))) {
printf("Color enum recognizes a value it shouldn't\n");
return -1;
}
if (!ns(Color_is_known_value(8))) {
printf("Color enum does not recognize the value of the Blue flag\n");
return -1;
}
if (ns(Color_is_known_value(9))) {
printf("Color enum recognizes a value it shouldn't\n");
return -1;
}
if (!ns(Any_is_known_type(ns(Any_Monster)))) {
printf("Any type does not accept Monster\n");
return -1;
}
if (ns(Any_is_known_type(42))) {
printf("Any type recognizes unexpected type\n");
return -1;
}
inv = ns(Monster_inventory(monster));
if ((nsc(uint8_vec_len(inv))) != 10) {
printf("Inventory length unexpected\n");
return -1;
}
for (i = 0; i < nsc(uint8_vec_len(inv)); ++i) {
if (nsc(uint8_vec_at(inv, i)) != i) {
printf("inventory item #%d is wrong\n", (int)i);
return -1;
}
}
if (ns(Monster_mana(monster) != 150)) {
printf("Mana not default\n");
return -1;
}
if (ns(Monster_mana_is_present(monster))) {
printf("Mana should default\n");
return -1;
}
if (!ns(Monster_hp_is_present(monster))) {
printf("Health points should be present\n");
return -1;
}
if (!ns(Monster_pos_is_present(monster))) {
printf("Position should be present\n");
return -1;
}
testvec = ns(Monster_test4(monster));
if (ns(Test_vec_len(testvec)) != 5) {
printf("Test4 vector is not the right length.\n");
return -1;
}
/*
* This particular test requires that the in-memory
* array layout matches the array layout in the buffer.
*/
if (flatbuffers_is_native_pe()) {
for (i = 0; i < 5; ++i) {
test = ns(Test_vec_at(testvec, i));
if (testvec_data[i].a != ns(Test_a(test))) {
printf("Test4 vec failed at index %d, member a\n", (int)i);
return -1;
}
if (testvec_data[i].b != ns(Test_b(test))) {
printf("Test4 vec failed at index %d, member a\n", (int)i);
return -1;
}
}
} else {
printf("SKIPPING DIRECT VECTOR ACCESS WITH NON-NATIVE ENDIAN PROTOCOL\n");
}
monsters = ns(Monster_testarrayoftables(monster));
if (ns(Monster_vec_len(monsters)) != 8) {
printf("unexpected monster vector length\n");
return -1;
}
mon = ns(Monster_vec_at(monsters, 5));
assert(mon);
name = ns(Monster_name(mon));
if (strcmp(name, "TwoFace")) {
printf("monster 5 isn't TwoFace");
return -1;
}
mon2 = ns(Monster_vec_at(monsters, 1));
if (mon2 != mon) {
printf("DAG test failed, monster[5] != monster[1] as pointer\n");
return -1;
}
name = ns(Monster_name(mon2));
if (strcmp(name, "TwoFace")) {
printf("monster 1 isn't Joker, it is: %s\n", name);
return -1;
}
mon = ns(Monster_vec_at(monsters, 2));
name = ns(Monster_name(mon));
if (strcmp(name, "Joker")) {
printf("monster 2 isn't Joker, it is: %s\n", name);
return -1;
}
mon = ns(Monster_vec_at(monsters, 0));
name = ns(Monster_name(mon));
if (strcmp(name, "Gulliver")) {
printf("monster 0 isn't Gulliver, it is: %s\n", name);
return -1;
}
mon = ns(Monster_vec_at(monsters, 3));
name = ns(Monster_name(mon));
if (strcmp(name, "TwoFace")) {
printf("monster 3 isn't TwoFace, it is: %s\n", name);
return -1;
}
mon = ns(Monster_vec_at(monsters, 4));
name = ns(Monster_name(mon));
if (strcmp(name, "Joker")) {
printf("monster 4 isn't Joker, it is: %s\n", name);
return -1;
}
mon = ns(Monster_vec_at(monsters, 6));
name = ns(Monster_name(mon));
if (strcmp(name, "Gulliver")) {
printf("monster 6 isn't Gulliver, it is: %s\n", name);
return -1;
}
mon = ns(Monster_vec_at(monsters, 7));
name = ns(Monster_name(mon));
if (strcmp(name, "Joker")) {
printf("monster 7 isn't Gulliver, it is: %s\n", name);
return -1;
}
strings = ns(Monster_testarrayofstring(monster));
if (nsc(string_vec_len(strings) != 3)) {
printf("Monster array of strings has wrong length\n");
return -1;
}
if (strcmp(nsc(string_vec_at(strings, 0)), "Hello")) {
printf("string elem 0 is wrong\n");
return -1;
}
s = nsc(string_vec_at(strings, 1));
if (nsc(string_len(s)) != 2) {
printf("string 1 has wrong length");
return -1;
}
if (memcmp(s, ",\0", 2)) {
printf("string elem 1 has wrong content\n");
return -1;
}
if (strcmp(nsc(string_vec_at(strings, 2)), "world!")) {
printf("string elem 2 is wrong\n");
return -1;
}
if (!ns(Monster_testarrayofbools_is_present(monster))) {
printf("array of bools is missing\n");
return -1;
}
bools = ns(Monster_testarrayofbools(monster));
if (nsc(bool_vec_len(bools) != 4)) {
printf("bools have wrong vector length\n");
return -1;
}
if (sizeof(bools[0]) != 1) {
printf("bools have wrong element size\n");
return -1;
}
for (i = 0; i < 4; ++i) {
if (nsc(bool_vec_at(bools, i) != booldata[i])) {
printf("bools vector elem %d is wrong\n", (int)i);
return -1;
}
}
test_type = ns(Monster_test_type(monster));
if (test_type != ns(Any_Monster)) {
printf("the monster test type is not Any_Monster\n");
return -1;
}
mon = ns(Monster_test(monster));
if (strcmp(ns(Monster_name(mon)), "TwoFace")) {
printf("the test monster is not TwoFace\n");
return -1;
}
mon = ns(Monster_enemy(monster));
if (strcmp(ns(Monster_name(mon)), "the enemy")) {
printf("the monster is not the enemy\n");
return -1;
}
if (ns(Monster_test_type(mon)) != ns(Any_NONE)) {
printf("the enemy test type is not Any_NONE\n");
return -1;
}
test_union = ns(Monster_test_union(monster));
if (test_union.type != test_type) {
printf("the monster test union type is not Any_Monster\n");
return -1;
}
if (test_union.value != ns(Monster_test(monster))) {
printf("the union monster has gone awol\n");
return -1;
}
monsters = ns(Monster_testarrayoftables(mon));
i = ns(Monster_vec_len(monsters));
mon = ns(Monster_vec_at(monsters, i - 1));
if (ns(Monster_test_type)(mon) != ns(Any_Monster)) {
printf("The monster variant added with value, type methods is not working\n");
return -1;
}
mon = ns(Monster_test(mon));
if (strcmp(ns(Monster_name(mon)), "TwoFace")) {
printf("The monster variant added with value method is incorrect\n");
return -1;
}
if (ns(Monster_testbool(monster))) {
printf("testbool should not\n");
return -1;
}
if (!ns(Monster_testempty_is_present(monster))) {
printf("The empty table isn't present\n");
return -1;
}
stat = ns(Monster_testempty(monster));
if (ns(Stat_id_is_present(stat))
|| ns(Stat_val_is_present(stat))
|| ns(Stat_count_is_present(stat))) {
printf("empty table isn't empty\n");
return -1;
}
return 0;
}
int gen_monster(flatcc_builder_t *B, int with_size)
{
uint8_t inv[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
ns(Vec3_t) *vec;
ns(Test_t) *test, x;
ns(Monster_ref_t) mon, mon2, monsters[2];
ns(Monster_ref_t) *aoft;
nsc(string_ref_t) name;
nsc(string_ref_t) strings[3];
nsc(bool_t)bools[] = { 0, 1, 1, 0 };
flatcc_builder_reset(B);
/*
* Some FlatBuffer language interfaces require a string and other
* non-embeddable objects to be created before the table storing it
* is being created. This is not necessary (but possible) here
* because the flatcc_builder maintains an internal stack.
*/
if (with_size) {
ns(Monster_start_as_root_with_size(B));
} else {
ns(Monster_start_as_root(B));
}
ns(Monster_hp_add(B, 80));
vec = ns(Monster_pos_start(B));
vec->x = 1, vec->y = 2, vec->z = -3.2f;
/* _end call converts to protocol endian format. */
ns(Monster_pos_end(B));
/*
* NOTE: Monster_name_add requires a reference to an
* already created string - adding a string directly
* will compile with a warning but fail badly. Instead
* create the string first, or do it in-place with
* the helper function `Monster_name_create_str`, or
* with one of several other options.
*
* Wrong: ns(Monster_name_add(B, "MyMonster"));
*/
ns(Monster_name_create_str(B, "MyMonster"));
ns(Monster_color_add)(B, ns(Color_Green));
ns(Monster_inventory_create(B, inv, c_vec_len(inv)));
/* The vector is built in native endian format. */
ns(Monster_test4_start(B));
test = ns(Monster_test4_extend(B, 1));
test->a = 0x10;
test->b = 0x20;
test = ns(Monster_test4_extend(B, 2));
test->a = 0x30;
test->b = 0x40;
test[1].a = 0x50;
test[1].b = 0x60;
ns(Monster_test4_push_create(B, 0x70, (int8_t)0x80));
x.a = 0x190; /* This is a short. */
x.b = (int8_t)0x91; /* This is a byte. */
ns(Monster_test4_push(B, &x));
ns(Monster_test4_push(B, &x));
/* We can use either field mapped push or push on the type. */
ns(Test_vec_push(B, &x));
/*
* `_reserved_len` is similar to the `_vec_len` function in the
* reader interface but `_vec_len` would not work here.
*/
assert(ns(Monster_test4_reserved_len(B)) == 7);
ns(Monster_test4_truncate(B, 2));
assert(ns(Monster_test4_reserved_len(B)) == 5);
/* It is not valid to dereference old pointers unless we call edit first. */
test = ns(Monster_test4_edit(B));
test[4].a += 1; /* 0x191 */
/* Each vector element is converted to protocol endian format at end. */
ns(Monster_test4_end(B));
/* Test creating object before containing vector. */
ns(Monster_start(B));
name = nsc(string_create(B, "TwoFace", 7));
ns(Monster_name_add(B, name));
mon = ns(Monster_end(B));
/*
* Here we create several monsters with only a name - this also
* tests reuse of vtables.
*/
ns(Monster_testarrayoftables_start(B));
aoft = ns(Monster_testarrayoftables_extend(B, 2));
/*
* It is usually not ideal to update reference vectors directly and
* there must not be any unassigned elements (null) when the array
* ends. Normally a push_start ... push_end, or a push_create
* operation is preferable.
*/
aoft[0] = mon;
/*
* But we can do things not otherwise possible - like constructing a
* DAG. Note that reference values (unlike pointers) are stable as
* long as the buffer is open for write, also past this vector.
*/
aoft[1] = mon;
ns(Monster_testarrayoftables_push_start(B));
ns(Monster_name_create_strn(B, "Joker", 30));
mon2 = *ns(Monster_testarrayoftables_push_end(B));
aoft = ns(Monster_testarrayoftables_extend(B, 3));
aoft[0] = mon;
aoft[1] = mon2;
ns(Monster_testarrayoftables_truncate(B, 1));
assert(ns(Monster_testarrayoftables_reserved_len(B)) == 5);
ns(Monster_testarrayoftables_push_start(B));
ns(Monster_name_create_strn(B, "Gulliver at the Big Endians", 8));
/* We cannot call reserved_len while a monster is still open, */
monsters[0] = *ns(Monster_testarrayoftables_push_end(B));
/* but here the vector is on top of the stack again. */
assert(ns(Monster_testarrayoftables_reserved_len(B)) == 6);
/* Swap monsters[0] and monsters[5] */
aoft = ns(Monster_testarrayoftables_edit(B));
mon2 = aoft[5];
monsters[1] = aoft[2];
aoft[5] = mon;
aoft[0] = mon2;
ns(Monster_testarrayoftables_append(B, monsters, 2));
/*
* The end call converts the reference array into an endian encoded
* offset vector.
*/
ns(Monster_testarrayoftables_end(B));
strings[0] = nsc(string_create_str(B, "Hello"));
/* Test embedded null character.
* Note _strn is at most n, or up to 0 termination:
* wrong: strings[1] = nsc(string_create_strn(B, ",\0", 2));
*/
strings[1] = nsc(string_create(B, ",\0", 2));
strings[2] = nsc(string_create_str(B, "world!"));
ns(Monster_testarrayofstring_create(B, strings, 3));
assert(c_vec_len(bools) == 4);
ns(Monster_testarrayofbools_start(B));
ns(Monster_testarrayofbools_append(B, bools, 1));
ns(Monster_testarrayofbools_append(B, bools + 1, 3));
ns(Monster_testarrayofbools_end(B));
/*
* This is using a constructor argument list where a union
* is a single argument, unlike the C++ interface.
* A union is given a type and a table reference.
*
* We are not verifying the result as this is only to stress
* the type system of the builder - except: the last array
* element is tested to ensure add_value is getting through.
*/
ns(Monster_test_add)(B, ns(Any_as_Monster(mon)));
ns(Monster_enemy_start(B));
ns(Monster_name_create_str(B, "the enemy"));
/* Create array of monsters to test various union constructors. */
ns(Monster_testarrayoftables_start(B));
ns(Monster_vec_push_start(B));
ns(Monster_test_add)(B, ns(Any_as_Monster(mon)));
/* Name is required. */
ns(Monster_name_create_str(B, "any name"));
ns(Monster_testarrayoftables_push_end(B));
ns(Monster_testarrayoftables_push_start(B));
ns(Monster_test_Monster_add(B, mon));
ns(Monster_name_create_str(B, "any name"));
ns(Monster_vec_push_end(B));
/*
* `push_start`: We can use the field specific method, or the type specific method
* that the field maps to.
*/
ns(Monster_testarrayoftables_push_start(B));
/*
* This is mostly for internal use in create methods so the type
* can be added last and pack better in the table.
* `add_value` still takes union_ref because it is a NOP if
* the union type is NONE.
*/
ns(Monster_test_add_value(B, ns(Any_as_Monster(mon))));
ns(Monster_name_create_str(B, "any name"));
ns(Monster_test_add_type(B, ns(Any_Monster)));
ns(Monster_testarrayoftables_push_end(B));
ns(Monster_testarrayoftables_end(B));
ns(Monster_enemy_end(B));
ns(Monster_testbool_add(B, 0));
ns(Monster_testempty_start(B));
ns(Monster_testempty_end(B));
ns(Monster_end_as_root(B));
return 0;
}
int test_monster(flatcc_builder_t *B)
{
void *buffer;
size_t size;
int ret;
gen_monster(B, 0);
buffer = flatcc_builder_finalize_aligned_buffer(B, &size);
hexdump("monster table", buffer, size, stderr);
if ((ret = ns(Monster_verify_as_root(buffer, size)))) {
printf("Monster buffer failed to verify, got: %s\n", flatcc_verify_error_string(ret));
return -1;
}
ret = verify_monster(buffer);
flatcc_builder_aligned_free(buffer);
return ret;
}
int test_monster_with_size(flatcc_builder_t *B)
{
void *buffer, *frame;
size_t size, size2, esize;
int ret;
gen_monster(B, 1);
frame = flatcc_builder_finalize_aligned_buffer(B, &size);
hexdump("monster table with size", frame, size, stderr);
if (((size_t)frame & 15)) {
printf("Platform did not provide 16 byte aligned allocation and needs special attention.");
printf("buffer address: %x\n", (flatbuffers_uoffset_t)(size_t)frame);
return -1;
}
buffer = flatbuffers_read_size_prefix(frame, &size2);
esize = size - sizeof(flatbuffers_uoffset_t);
if (size2 != esize) {
printf("Size prefix has unexpected size, got %i, expected %i\n", (int)size2, (int)esize);
return -1;
}
if ((ret = ns(Monster_verify_as_root(buffer, size2)))) {
printf("Monster buffer with size prefix failed to verify, got: %s\n", flatcc_verify_error_string(ret));
return -1;
}
ret = verify_monster(buffer);
flatcc_builder_aligned_free(frame);
return ret;
}
int test_cloned_monster(flatcc_builder_t *B)
{
void *buffer;
void *cloned_buffer;
size_t size;
int ret;
flatcc_refmap_t refmap, *refmap_old;
flatcc_refmap_init(&refmap);
gen_monster(B, 0);
buffer = flatcc_builder_finalize_aligned_buffer(B, &size);
hexdump("monster table", buffer, size, stderr);
if ((ret = ns(Monster_verify_as_root(buffer, size)))) {
printf("Monster buffer failed to verify, got: %s\n", flatcc_verify_error_string(ret));
return -1;
}
if (verify_monster(buffer)) {
return -1;
}
flatcc_builder_reset(B);
/*
* Clone works without setting a refmap - but then shared references
* get expanded - and then the verify monster check fails on a DAG
* test.
*/
refmap_old = flatcc_builder_set_refmap(B, &refmap);
if (!ns(Monster_clone_as_root(B, ns(Monster_as_root(buffer))))) {
printf("Cloned Monster didn't actually clone.");
return -1;
};
/*
* Restoring old refmap (or zeroing) is optional if we cleared the
* buffer in this scope, but we don't so we must detach and clean up
* the refmap manually. refmap_old is likely just null, but this
* way we do not interfere with caller.
*/
flatcc_builder_set_refmap(B, refmap_old);
cloned_buffer = flatcc_builder_finalize_aligned_buffer(B, &size);
hexdump("cloned monster table", cloned_buffer, size, stderr);
if ((ret = ns(Monster_verify_as_root(cloned_buffer, size)))) {
printf("Cloned Monster buffer failed to verify, got: %s\n", flatcc_verify_error_string(ret));
return -1;
}
if (verify_monster(cloned_buffer)) {
printf("Cloned Monster did not have the expected content.");
return -1;
}
flatcc_refmap_clear(&refmap);
flatcc_builder_aligned_free(buffer);
flatcc_builder_aligned_free(cloned_buffer);
return ret;
}
int test_string(flatcc_builder_t *B)
{
ns(Monster_table_t) mon;
void *buffer;
char *s;
flatcc_builder_reset(B);
ns(Monster_start_as_root(B));
ns(Monster_name_start(B));
s = ns(Monster_name_extend(B, 3));
s[0] = '1';
s[1] = '2';
s[2] = '3';
ns(Monster_name_append_str(B, "4"));
assert(ns(Monster_name_reserved_len(B)) == 4);
ns(Monster_name_append_strn(B, "5678", 30));
assert(ns(Monster_name_reserved_len(B)) == 8);
ns(Monster_name_append(B, "90", 2));
assert(ns(Monster_name_reserved_len(B)) == 10);
ns(Monster_name_truncate(B, 3));
assert(ns(Monster_name_reserved_len(B)) == 7);
s = ns(Monster_name_edit(B));
s[4] = '.';
ns(Monster_name_end(B));
ns(Monster_end_as_root(B));
/* Only with small buffers and the default emitter. */
buffer = flatcc_builder_get_direct_buffer(B, 0);
assert(buffer);
mon = ns(Monster_as_root(buffer));
if (strcmp(ns(Monster_name(mon)), "1234.67")) {
printf("string test failed\n");
return -1;
}
return 0;
}
int test_sort_find(flatcc_builder_t *B)
{
size_t pos;
ns(Monster_table_t) mon;
ns(Monster_vec_t) monsters;
ns(Monster_mutable_vec_t) mutable_monsters;
void *buffer;
size_t size;
int ret = -1;
flatcc_builder_reset(B);
ns(Monster_start_as_root(B));
ns(Monster_name_create_str(B, "MyMonster"));
ns(Monster_testarrayoftables_start(B));
ns(Monster_testarrayoftables_push_start(B));
ns(Monster_name_create_str(B, "TwoFace"));
ns(Monster_testarrayoftables_push_end(B));
ns(Monster_testarrayoftables_push_start(B));
ns(Monster_name_create_str(B, "Joker"));
ns(Monster_testarrayoftables_push_end(B));
ns(Monster_testarrayoftables_push_start(B));
ns(Monster_name_create_str(B, "Gulliver"));
ns(Monster_testarrayoftables_push_end(B));
ns(Monster_testarrayoftables_push_start(B));
ns(Monster_name_create_str(B, "Alice"));
ns(Monster_testarrayoftables_push_end(B));
ns(Monster_testarrayoftables_push_start(B));
ns(Monster_name_create_str(B, "Gulliver"));
ns(Monster_testarrayoftables_push_end(B));
ns(Monster_testarrayoftables_end(B));
ns(Monster_end_as_root(B));
buffer = flatcc_builder_finalize_aligned_buffer(B, &size);
hexdump("unsorted monster buffer", buffer, size, stderr);
mon = ns(Monster_as_root(buffer));
monsters = ns(Monster_testarrayoftables(mon));
assert(monsters);
mutable_monsters = (ns(Monster_mutable_vec_t))monsters;
ns(Monster_vec_sort_by_name(mutable_monsters));
hexdump("sorted monster buffer", buffer, size, stderr);
if (ns(Monster_vec_len(monsters)) != 5) {
printf("Sorted monster vector has wrong length\n");
goto done;
}
if (strcmp(ns(Monster_name(ns(Monster_vec_at(monsters, 0)))), "Alice")) {
printf("sort isn't working at elem 0\n");
goto done;
}
if (strcmp(ns(Monster_name(ns(Monster_vec_at(monsters, 1)))), "Gulliver")) {
printf("sort isn't working at elem 1\n");
goto done;
}
if (strcmp(ns(Monster_name(ns(Monster_vec_at(monsters, 2)))), "Gulliver")) {
printf("sort isn't working at elem 2\n");
goto done;
}
if (strcmp(ns(Monster_name(ns(Monster_vec_at(monsters, 3)))), "Joker")) {
printf("sort isn't working at elem 3\n");
goto done;
}
if (strcmp(ns(Monster_name(ns(Monster_vec_at(monsters, 4)))), "TwoFace")) {
printf("sort isn't working at elem 4\n");
goto done;
}
/*
* The heap sort isn't stable, but it should keep all elements
* unique. Note that we could still have identical objects if we
* actually stored the same object twice in DAG structure.
*/
if (ns(Monster_vec_at(monsters, 1)) == ns(Monster_vec_at(monsters, 2))) {
printf("Two identical sort keys should not be identical objects (in this case)\n");
goto done;
}
if (3 != ns(Monster_vec_find(monsters, "Joker"))) {
printf("find by default key did not find the Joker\n");
goto done;
}
if (3 != ns(Monster_vec_find_n(monsters, "Joker2", 5))) {
printf("find by default key did not find the Joker with n\n");
goto done;
}
/*
* We can have multiple keys on a table or struct by naming the sort
* and find operations.
*/
if (3 != ns(Monster_vec_find_by_name(monsters, "Joker"))) {
printf("find did not find the Joker\n");
goto done;
}
if (3 != ns(Monster_vec_find_n_by_name(monsters, "Joker3", 5))) {
printf("find did not find the Joker with n\n");
goto done;
}
if (nsc(not_found) != ns(Monster_vec_find_by_name(monsters, "Jingle"))) {
printf("not found not working\n");
goto done;
}
if (0 != ns(Monster_vec_find_by_name(monsters, "Alice"))) {
printf("Alice not found\n");
goto done;
}
/*
* The search, unlike sort, is stable and should return the first
* index of repeated keys.
*/
if (1 != (pos = ns(Monster_vec_find_by_name(monsters, "Gulliver")))) {
printf("Gulliver not found\n");
printf("got %d\n", (int)pos);
goto done;
}
if (4 != (pos = ns(Monster_vec_find_by_name(monsters, "TwoFace")))) {
printf("TwoFace not found\n");
printf("got %d\n", (int)pos);
goto done;
}
/*
* Just make sure the default key has a sort method - it is the same
* as sort_by_name for the monster schema.
*/
ns(Monster_vec_sort(mutable_monsters));
ret = 0;
done:
flatcc_builder_aligned_free(buffer);
return ret;
}
static size_t count_monsters(ns(Monster_vec_t) monsters, const char *name)
{
size_t i;
size_t count = 0;
for (i = ns(Monster_vec_scan)(monsters, name);
i != nsc(not_found);
i = ns(Monster_vec_scan_ex)(monsters, i + 1, nsc(end), name)) {
++count;
}
return count;
}
int test_scan(flatcc_builder_t *B)
{
size_t pos;
ns(Monster_table_t) mon;
ns(Monster_vec_t) monsters;
nsc(uint8_vec_t) inv;
nsc(string_vec_t) strings;
void *buffer;
size_t size;
uint8_t invdata[] = { 6, 7, 1, 3, 4, 3, 2 };
int ret = -1;
flatcc_builder_reset(B);
ns(Monster_start_as_root(B));
ns(Monster_name_create_str(B, "MyMonster"));
ns(Monster_inventory_create(B, invdata, c_vec_len(invdata)));
ns(Monster_testarrayofstring_start(B));
ns(Monster_testarrayofstring_end(B));
ns(Monster_testarrayoftables_start(B));
ns(Monster_testarrayoftables_push_start(B));
ns(Monster_name_create_str(B, "TwoFace"));
ns(Monster_testarrayoftables_push_end(B));
ns(Monster_testarrayoftables_push_start(B));
ns(Monster_name_create_str(B, "Joker"));
ns(Monster_testarrayoftables_push_end(B));
ns(Monster_testarrayoftables_push_start(B));
ns(Monster_name_create_str(B, "Gulliver"));
ns(Monster_testarrayoftables_push_end(B));
ns(Monster_testarrayoftables_push_start(B));
ns(Monster_name_create_str(B, "Alice"));
ns(Monster_testarrayoftables_push_end(B));
ns(Monster_testarrayoftables_push_start(B));
ns(Monster_name_create_str(B, "Gulliver"));
ns(Monster_testarrayoftables_push_end(B));
ns(Monster_testarrayoftables_end(B));
ns(Monster_end_as_root(B));
buffer = flatcc_builder_finalize_aligned_buffer(B, &size);
mon = ns(Monster_as_root(buffer));
monsters = ns(Monster_testarrayoftables(mon));
assert(monsters);
inv = ns(Monster_inventory(mon));
assert(inv);
strings = ns(Monster_testarrayofstring(mon));
assert(strings);
if (1 != ns(Monster_vec_scan(monsters, "Joker"))) {
printf("scan_by did not find the Joker\n");
goto done;
}
if (1 != ns(Monster_vec_rscan(monsters, "Joker"))) {
printf("rscan_by did not find the Joker\n");
goto done;
}
if (1 != ns(Monster_vec_scan_n(monsters, "Joker3", 5))) {
printf("scan_by did not find the Joker with n\n");
goto done;
}
if (1 != ns(Monster_vec_rscan_n(monsters, "Joker3", 5))) {
printf("scan_by did not find the Joker with n\n");
goto done;
}
if (nsc(not_found) != ns(Monster_vec_scan_ex(monsters, 2, nsc(end), "Joker"))) {
printf("scan_from found Joker past first occurence\n");
goto done;
}
if (nsc(not_found) != ns(Monster_vec_scan(monsters, "Jingle"))) {
printf("not found not working\n");
goto done;
}
if (0 != ns(Monster_vec_scan(monsters, "TwoFace"))) {
printf("TwoFace not found\n");
goto done;
}
if (2 != ns(Monster_vec_scan_by_name(monsters, "Gulliver"))) {
printf("Gulliver not found\n");
goto done;
}
if (4 != ns(Monster_vec_rscan_by_name(monsters, "Gulliver"))) {
printf("Gulliver not found\n");
goto done;
}
if (4 != ns(Monster_vec_rscan_n_by_name(monsters, "Gulliver42", 8))) {
printf("Gulliver not found with n\n");
goto done;
}
if (2 != ns(Monster_vec_rscan_ex_n_by_name(monsters, 1, 3, "Gulliver42", 8))) {
printf("Gulliver not found with n\n");
goto done;
}
if (2 != ns(Monster_vec_scan_ex_by_name(monsters, 2, nsc(end), "Gulliver"))) {
printf("Gulliver not found starting from Gulliver\n");
goto done;
}
if (2 != ns(Monster_vec_scan_ex_n_by_name(monsters, 2, nsc(end), "Gulliver42", 8))) {
printf("Gulliver not found starting from Gulliver\n");
goto done;
}
if (4 != ns(Monster_vec_scan_ex_by_name(monsters, 3, nsc(end), "Gulliver"))) {
printf("Another Gulliver not found\n");
goto done;
}
if (nsc(not_found) != ns(Monster_vec_scan_ex(monsters, 1, 3, "Jingle"))) {
printf("not found in subrange not working\n");
goto done;
}
if (nsc(not_found) != ns(Monster_vec_scan_ex(monsters, 1, 3, "TwoFace"))) {
printf("subrange doesn't limit low bound\n");
goto done;
}
if (1 != ns(Monster_vec_scan_ex(monsters, 1, 3, "Joker"))) {
printf("scan in subrange did not find Joker\n");
goto done;
}
if (2 != ns(Monster_vec_scan_ex_by_name(monsters, 1, 3, "Gulliver"))) {
printf("scan in subrange did not find Gulliver\n");
goto done;
}
if (nsc(not_found) != ns(Monster_vec_scan_ex_by_name(monsters, 1, 3, "Alice"))) {
printf("subrange doesn't limit upper bound in scan\n");
goto done;
}
if (nsc(not_found) != ns(Monster_vec_rscan_ex(monsters, 1, 3, "Jingle"))) {
printf("not found in subrange not working with rscan\n");
goto done;
}
if (nsc(not_found) != ns(Monster_vec_rscan_ex(monsters, 1, 3, "TwoFace"))) {
printf("subrange doesn't limit lower bound in rscan\n");
goto done;
}
if (1 != ns(Monster_vec_rscan_ex(monsters, 1, 3, "Joker"))) {
printf("rscan in subrange did not find Joker\n");
goto done;
}
if (2 != ns(Monster_vec_rscan_ex_by_name(monsters, 1, 3, "Gulliver"))) {
printf("rscan in subrange did not find Gulliver\n");
goto done;
}
if (nsc(not_found) != ns(Monster_vec_rscan_ex_by_name(monsters, 1, 3, "Alice"))) {
printf("subrange doesn't limit upper bound in rscan\n");
goto done;
}
if (nsc(not_found) != ns(Monster_vec_scan_ex(monsters, 0, 0, "TwoFace"))) {
printf("TwoFace is found in empty range\n");
goto done;
}
if (nsc(not_found) != ns(Monster_vec_scan_ex(monsters, 0, 0, "Joker"))) {
printf("Joker is found in empty range\n");
goto done;
}
if (nsc(not_found) != ns(Monster_vec_scan_ex(monsters, 1, 1, "Joker"))) {
printf("Joker is found in another empty range\n");
goto done;
}
if (nsc(not_found) != ns(Monster_vec_scan_ex(monsters, ns(Monster_vec_len(monsters)), nsc(end), "TwoFace"))) {
printf("TwoFace is found in empty range in the end\n");
goto done;
}
if (nsc(not_found) != ns(Monster_vec_rscan_ex(monsters, 0, 0, "TwoFace"))) {
printf("TwoFace is found in empty range\n");
goto done;
}
if (nsc(not_found) != ns(Monster_vec_rscan_ex(monsters, 0, 0, "Joker"))) {
printf("Joker is found in empty range\n");
goto done;
}
if (nsc(not_found) != ns(Monster_vec_rscan_ex(monsters, 1, 1, "Joker"))) {
printf("Joker is found in another empty range\n");
goto done;
}
if (nsc(not_found) != ns(Monster_vec_rscan_ex(monsters, ns(Monster_vec_len(monsters)), nsc(end), "TwoFace"))) {
printf("TwoFace is found in empty range in the end\n");
goto done;
}
if (1 != count_monsters(monsters, "Joker")) {
printf("number of Jokers is not 1\n");
goto done;
}
if (0 != count_monsters(monsters, "Jingle")) {
printf("number of Jingles is not 0\n");
goto done;
}
if (1 != count_monsters(monsters, "TwoFace")) {
printf("number of TwoFace is not 1\n");
goto done;
}
if (2 != count_monsters(monsters, "Gulliver")) {
printf("number of Gullivers is not 2\n");
goto done;
}
if (0 != (pos = nsc(uint8_vec_scan(inv, 6)))) {
printf("scan not working on first item of inventory\n");
goto done;
}
if (2 != (pos = nsc(uint8_vec_scan(inv, 1)))) {
printf("scan not working on middle item of inventory\n");
goto done;
}
if (nsc(not_found) != (pos = nsc(uint8_vec_scan_ex(inv, 3, nsc(end), 1)))) {
printf("scan_ex(item+1) not working on middle item of inventory\n");
goto done;
}
if (nsc(not_found) != (pos = nsc(uint8_vec_scan(inv, 5)))) {
printf("scan not working for repeating item of inventory\n");
goto done;
}
if (6 != (pos = nsc(uint8_vec_scan(inv, 2)))) {
printf("scan not working on last item of inventory\n");
goto done;
}
if (3 != (pos = nsc(uint8_vec_scan(inv, 3)))) {
printf("scan not working for repeating item of inventory\n");
goto done;
}
if (3 != (pos = nsc(uint8_vec_scan_ex(inv, 3, nsc(end), 3)))) {
printf("scan_ex(item) not working for repeating item of inventory\n");
goto done;
}
if (5 != (pos = nsc(uint8_vec_scan_ex(inv, 4, nsc(end), 3)))) {
printf("scan_ex(item+1) not working for repeating item of inventory\n");
goto done;
}
if (5 != (pos = nsc(uint8_vec_rscan(inv, 3)))) {
printf("rscan not working for repeating item of inventory\n");
goto done;
}
if (3 != (pos = nsc(uint8_vec_rscan_ex(inv, 1, 4, 3)))) {
printf("rscan_ex not working for repeating item of inventory\n");
goto done;
}
/* Test that all scan functions are generated for string arrays */
nsc(string_vec_scan(strings, "Hello"));
nsc(string_vec_scan_ex(strings, 0, nsc(end), "Hello"));
nsc(string_vec_scan_n(strings, "Hello", 4));
nsc(string_vec_scan_ex_n(strings, 0, nsc(end), "Hello", 4));
nsc(string_vec_rscan(strings, "Hello"));
nsc(string_vec_rscan_ex(strings, 0, nsc(end), "Hello"));
nsc(string_vec_rscan_n(strings, "Hello", 4));
nsc(string_vec_rscan_ex_n(strings, 0, nsc(end), "Hello", 4));
#if FLATCC_ALLOW_SCAN_FOR_ALL_FIELDS
/* Check for presence of scan for non-key fields */
ns(Monster_vec_scan_by_hp(monsters, 13));
ns(Monster_vec_scan_ex_by_hp(monsters, 1, nsc(end), 42));
ns(Monster_vec_rscan_by_hp(monsters, 1));
ns(Monster_vec_rscan_ex_by_hp(monsters, 0, 2, 42));
#endif
ret = 0;
done:
flatcc_builder_aligned_free(buffer);
return ret;
}
int test_basic_sort(flatcc_builder_t *B)
{
ns(Monster_table_t) mon;
nsc(uint8_vec_t) inv;
nsc(uint8_mutable_vec_t) minv;
void *buffer;
size_t size;
uint8_t invdata[] = { 6, 7, 1, 3, 4, 3, 2 };
uint8_t sortedinvdata[] = { 1, 2, 3, 3, 4, 6, 7 };
uint8_t v, i;
flatcc_builder_reset(B);
ns(Monster_start_as_root(B));
ns(Monster_name_create_str(B, "MyMonster"));
ns(Monster_inventory_create(B, invdata, c_vec_len(invdata)));
ns(Monster_end_as_root(B));
buffer = flatcc_builder_get_direct_buffer(B, &size);
mon = ns(Monster_as_root(buffer));
inv = ns(Monster_inventory(mon));
minv = (nsc(uint8_mutable_vec_t))inv;
nsc(uint8_vec_sort(minv));
assert(nsc(uint8_vec_len(inv) == c_vec_len(invdata)));
for (i = 0; i < nsc(uint8_vec_len(inv)); ++i) {
v = nsc(uint8_vec_at(inv, i));
if (v != sortedinvdata[i]) {
printf("inventory not sorted\n");
return -1;
}
if (nsc(uint8_vec_find(inv, v) != (i == 3 ? 2 : i))) {
printf("find not working on inventory\n");
return -1;
}
}
return 0;
}
int test_clone_slice(flatcc_builder_t *B)
{
ns(Monster_table_t) mon, mon2;
nsc(string_vec_t) strings;
nsc(bool_vec_t) bools;
nsc(string_t) name;
ns(Monster_ref_t) monster_ref;
ns(Test_t) *t;
ns(Test_struct_t) test4;
ns(Test_struct_t) elem4;
void *buffer, *buf2;
size_t size;
int ret = -1;
uint8_t booldata[] = { 0, 1, 0, 0, 1, 0, 0 };
flatcc_builder_reset(B);
ns(Monster_start_as_root(B));
ns(Monster_name_create_str(B, "The Source"));
ns(Monster_testarrayofbools_create(B, booldata, c_vec_len(booldata)));
ns(Monster_test4_start(B));
t = ns(Monster_test4_extend(B, 2));
t[0].a = 22;
t[1].a = 44;
ns(Monster_test4_end(B));
ns(Monster_pos_start(B))->x = -42.3f;
ns(Monster_end_as_root(B));
buffer = flatcc_builder_finalize_aligned_buffer(B, &size);
hexdump("clone slice source buffer", buffer, size, stderr);
mon = ns(Monster_as_root(buffer));
flatcc_builder_reset(B);
ns(Monster_start_as_root(B));
name = ns(Monster_name(mon));
assert(name);
bools = ns(Monster_testarrayofbools(mon));
assert(bools);
test4 = ns(Monster_test4(mon));
assert(test4);
ns(Monster_name_clone(B, name));
ns(Monster_testarrayofstring_start(B));
ns(Monster_testarrayofstring_push_clone(B, name));
ns(Monster_testarrayofstring_push_slice(B, name, 4, 20));
ns(Monster_testarrayofstring_push_slice(B, name, 0, 3));
ns(Monster_testarrayofstring_end(B));
ns(Monster_start(B));
ns(Monster_name_slice(B, name, 2, 20));
ns(Monster_testarrayofbools_clone(B, bools));
ns(Monster_test4_slice(B, test4, 1, 2));
monster_ref = ns(Monster_end(B));
ns(Monster_test_add(B, ns(Any_as_Monster(monster_ref))));
ns(Monster_testarrayofbools_slice(B, bools, 3, (size_t)-1));
ns(Monster_pos_clone(B, ns(Monster_pos(mon))));
ns(Monster_test4_clone(B, test4));
ns(Monster_end_as_root(B));
buf2 = flatcc_builder_get_direct_buffer(B, &size);
hexdump("target buffer of clone", buf2, size, stderr);
mon2 = ns(Monster_as_root(buf2));
if (strcmp(ns(Monster_name(mon2)), "The Source")) {
printf("The Source was not cloned\n");
goto done;
}
strings = ns(Monster_testarrayofstring(mon2));
if (strcmp(nsc(string_vec_at(strings, 0)), "The Source")) {
printf("Push clone failed The Source\n");
goto done;
}
if (nsc(string_len(nsc(string_vec_at(strings, 1)))) != 6) {
printf("Push slice failed Sourcee on length\n");
goto done;
}
if (strcmp(nsc(string_vec_at(strings, 1)), "Source")) {
printf("Push slice failed Source\n");
goto done;
}
if (nsc(string_len(nsc(string_vec_at(strings, 2)))) != 3) {
printf("Push slice failed The on length\n");
goto done;
}
if (strcmp(nsc(string_vec_at(strings, 2)), "The")) {
printf("Push slice failed The\n");
goto done;
}
mon = ns(Monster_test(mon2));
assert(mon);
if (strcmp(ns(Monster_name(mon)), "e Source")) {
printf("name_slice did not shorten The Source correctly");
goto done;
}
bools = ns(Monster_testarrayofbools(mon));
if (nsc(bool_vec_len(bools)) != 7) {
printf("clone bool has wrong length\n");
goto done;
}
if (memcmp(bools, booldata, 7)) {
printf("cloned bool has wrong content\n");
goto done;
}
bools = ns(Monster_testarrayofbools(mon2));
if (nsc(bool_vec_len(bools)) != 4) {
printf("slice bool has wrong length\n");
goto done;
}
if (memcmp(bools, booldata + 3, 4)) {
printf("sliced bool has wrong content\n");
goto done;
}
if (ns(Monster_pos(mon2)->x != -42.3f)) {
printf("cloned pos struct failed\n");
goto done;
};
test4 = ns(Monster_test4(mon2));
if (ns(Test_vec_len(test4)) != 2) {
printf("struct vector test4 not cloned with correct length\n");
goto done;
}
elem4 = ns(Test_vec_at(test4, 0));
if (ns(Test_a(elem4)) != 22) {
printf("elem 0 of test4 not cloned\n");
goto done;
}
if (flatbuffers_is_native_pe() && ns(Test_vec_at(test4, 0))->a != 22) {
printf("elem 0 of test4 not cloned, direct access\n");
goto done;
}
elem4 = ns(Test_vec_at(test4, 1));
if (ns(Test_a(elem4)) != 44) {
printf("elem 1 of test4 not cloned\n");
goto done;
}
test4 = ns(Monster_test4(mon));
if (ns(Test_vec_len(test4)) != 1) {
printf("sliced struct vec not sliced\n");
goto done;
}
elem4 = ns(Test_vec_at(test4, 0));
if (ns(Test_a(elem4)) != 44) {
printf("sliced struct vec has wrong element\n");
goto done;
}
/*
* There is no push clone of structs because it becomes messy when
* the vector has to be ended using end_pe or alternative do double
* conversion with unclear semantics.
*/
ret = 0;
done:
flatcc_builder_aligned_free(buffer);
return ret;
}
int test_create_add_field(flatcc_builder_t *B)
{
void *buffer;
size_t size;
int ret = -1;
ns(Monster_table_t) mon;
ns(Stat_table_t) stat;
flatcc_builder_reset(B);
ns(Monster_start_as_root(B));
ns(Monster_name_create_str(B, "MyMonster"));
ns(Monster_testempty_create(B, nsc(string_create_str(B, "hello")), -100, 2));
ns(Monster_enemy_add(B, 0));
ns(Monster_end_as_root(B));
buffer = flatcc_builder_finalize_aligned_buffer(B, &size);
mon = ns(Monster_as_root(buffer));
if (ns(Monster_enemy_is_present(mon))) {
printf("enemy should not be present when adding null\n");
goto done;
}
stat = ns(Monster_testempty(mon));
if (!(ns(Stat_val(stat)) == -100)) {
printf("Stat didn't happen\n");
goto done;
}
ret = 0;
done:
flatcc_builder_aligned_free(buffer);
return ret;
}
int verify_union_vector(void *buffer, size_t size)
{
int ret = -1;
size_t n;
int color;
ns(Monster_table_t) mon;
ns(Stat_table_t) stat;
ns(TestSimpleTableWithEnum_table_t) kermit;
flatbuffers_generic_vec_t anyvec;
ns(Any_vec_t) anyvec_type;
ns(Any_union_vec_t) anyvec_union;
ns(Any_union_t) anyelem;
ns(Alt_table_t) alt;
if ((ret = ns(Monster_verify_as_root(buffer, size)))) {
printf("Monster buffer with union vector failed to verify, got: %s\n", flatcc_verify_error_string(ret));
return -1;
}
mon = ns(Monster_as_root(buffer));
if (ns(Monster_test_type(mon)) != ns(Any_Alt)) {
printf("test field does not have Alt type");
goto done;
}
alt = ns(Monster_test(mon));
if (!alt || ns(Alt_manyany_is_present(alt))) {
printf("manyany union vector should be present.\n");
goto done;
}
anyvec_type = ns(Alt_manyany_type(alt));
anyvec = ns(Alt_manyany(alt));
n = ns(Any_vec_len(anyvec_type));
if (n != 1) {
printf("manyany union vector has wrong length.\n");
goto done;
}
if (nsc(union_type_vec_at(anyvec_type, 0)) != ns(Any_TestSimpleTableWithEnum)) {
printf("manyany union vector has wrong element type.\n");
goto done;
}
kermit = flatbuffers_generic_vec_at(anyvec, 0);
if (!kermit) {
printf("Kermit is lost.\n");
goto done;
}
color = ns(TestSimpleTableWithEnum_color(kermit));
if (color != ns(Color_Green)) {
printf("Kermit has wrong color: %i.\n", (int)color);
goto done;
}
anyvec_union = ns(Alt_manyany_union(alt));
if (ns(Any_union_vec_len(anyvec_union)) != 1) {
printf("manyany union vector has wrong length from a different perspective.\n");
goto done;
}
anyelem = ns(Any_union_vec_at(anyvec_union, 0));
if (anyelem.type != nsc(union_type_vec_at(anyvec_type, 0))) {
printf("Kermit is now different.\n");
goto done;
}
if (anyelem.value != kermit) {
printf("Kermit is incoherent.\n");
goto done;
}
ret = 0;
done:
return ret;
}
int test_union_vector(flatcc_builder_t *B)
{
void *buffer = 0, *cloned_buffer = 0;
size_t size;
int ret = -1;
flatcc_refmap_t refmap, *refmap_old;
ns(TestSimpleTableWithEnum_ref_t) kermit_ref;
ns(Any_union_vec_ref_t) anyvec_ref;
flatcc_refmap_init(&refmap);
flatcc_builder_reset(B);
ns(Monster_start_as_root(B));
ns(Monster_name_create_str(B, "Kermit"));
kermit_ref = ns(TestSimpleTableWithEnum_create(B,
ns(Color_Green), ns(Color_Green),
ns(Color_Green), ns(Color_Green)));
ns(Any_vec_start(B));
ns(Any_vec_push(B, ns(Any_as_TestSimpleTableWithEnum(kermit_ref))));
anyvec_ref = ns(Any_vec_end(B));
ns(Monster_test_Alt_start(B));
ns(Alt_manyany_add(B, anyvec_ref));
ns(Monster_test_Alt_end(B));
ns(Monster_end_as_root(B));
buffer = flatcc_builder_finalize_aligned_buffer(B, &size);
if (verify_union_vector(buffer, size)) {
printf("Union vector Monster didn't verify.\n");
goto done;
}
flatcc_builder_reset(B);
refmap_old = flatcc_builder_set_refmap(B, &refmap);
if (!ns(Monster_clone_as_root(B, ns(Monster_as_root(buffer))))) {
printf("Cloned union vector Monster didn't actually clone.\n");
goto done;
};
flatcc_builder_set_refmap(B, refmap_old);
cloned_buffer = flatcc_builder_finalize_aligned_buffer(B, &size);
if (verify_union_vector(buffer, size)) {
printf("Cloned union vector Monster didn't verify.\n");
goto done;
}
ret = 0;
done:
flatcc_refmap_clear(&refmap);
flatcc_builder_aligned_free(buffer);
flatcc_builder_aligned_free(cloned_buffer);
return ret;
}
int test_mixed_type_union(flatcc_builder_t *B)
{
void *buffer;
size_t size;
size_t n;
int ret = -1;
/* Builder */
nsf(Character_union_ref_t) ut;
nsf(Rapunzel_ref_t) cameo_ref;
nsf(Attacker_ref_t) attacker_ref;
nsf(BookReader_ref_t) br_ref;
nsf(BookReader_t *) pbr;
nsf(Movie_table_t) mov;
/* Reader */
nsf(Character_union_vec_t) characters;
nsf(Character_union_t) character;
nsf(Rapunzel_struct_t) rapunzel;
nsf(Attacker_table_t) attacker;
nsc(string_t) text;
flatcc_builder_reset(B);
nsf(Movie_start_as_root(B));
br_ref = nsf(BookReader_create(B, 10));
cameo_ref = nsf(Rapunzel_create(B, 22));
ut = nsf(Character_as_Rapunzel(cameo_ref));
nsf(Movie_main_character_Rapunzel_create(B, 19));
nsf(Movie_cameo_Rapunzel_add(B, cameo_ref));
attacker_ref = nsf(Attacker_create(B, 42));
nsf(Movie_antagonist_MuLan_add(B, attacker_ref));
nsf(Movie_side_kick_Other_create_str(B, "Nemo"));
nsf(Movie_characters_start(B));
nsf(Movie_characters_push(B, ut));
nsf(Movie_characters_MuLan_push(B, attacker_ref));
nsf(Movie_characters_MuLan_push_create(B, 1));
nsf(Character_vec_push(B, nsf(Character_as_Other(nsc(string_create_str(B, "other"))))));
nsf(Movie_characters_Belle_push(B, br_ref));
pbr = nsf(Movie_characters_Belle_push_start(B));
pbr->books_read = 3;
nsf(Movie_characters_Belle_push_end(B));
nsf(Movie_characters_Belle_push(B, nsf(BookReader_create(B, 1))));
nsf(Movie_characters_Belle_push_create(B, 2));
nsf(Movie_characters_Other_push(B, nsc(string_create_str(B, "another"))));
nsf(Movie_characters_Other_push_create_str(B, "yet another"));
nsf(Movie_characters_end(B));
nsf(Movie_end_as_root(B));
buffer = flatcc_builder_finalize_aligned_buffer(B, &size);
hexdump("Movie buffer", buffer, size, stderr);
if ((ret = nsf(Movie_verify_as_root(buffer, size)))) {
printf("Movie buffer with mixed type union and union vector failed to verify, got: %s\n", flatcc_verify_error_string(ret));
return -1;
}
ret = -1;
mov = nsf(Movie_as_root(buffer));
if (!nsf(Movie_main_character_is_present(mov))) {
printf("Main_charactery union should be present.\n");
goto done;
}
if (!nsf(Movie_characters_is_present(mov))) {
printf("Characters union vector should be present.\n");
goto done;
}
character = nsf(Movie_main_character_union(mov));
if (character.type != nsf(Character_Rapunzel)) {
printf("Unexpected main character.\n");
goto done;
};
/*
* Tables and structs can cast by void pointer assignment while
* strings require an explicit cast.
*/
rapunzel = character.value;
if (!rapunzel) {
printf("Rapunzel has gone AWOL\n");
}
if (nsf(Rapunzel_hair_length(rapunzel)) > 19) {
printf("Rapunzel's hair has grown unexpectedly\n");
goto done;
}
if (nsf(Rapunzel_hair_length(rapunzel)) < 19) {
printf("Rapunzel's hair has been trimmed unexpectedly\n");
goto done;
}
if (nsf(Movie_cameo_type(mov)) != nsf(Character_Rapunzel)) {
printf("Rapunzel did was not selected for cameo appearance.\n");
goto done;
}
rapunzel = nsf(Movie_cameo(mov));
if (!rapunzel) {
printf("Rapunzel did not show up for cameo appearance.\n");
goto done;
}
if (nsf(Rapunzel_hair_length(rapunzel)) != 22) {
printf("Rapunzel didn't style her hair for cameo role.\n");
goto done;
}
if (nsf(Movie_antagonist_type(mov)) != nsf(Character_MuLan)) {
printf("Unexpected antagonist.\n");
goto done;
}
attacker = nsf(Movie_antagonist(mov));
if (!attacker || nsf(Attacker_sword_attack_damage(attacker)) != 42) {
printf("Unexpected sword attack damamage.\n");
goto done;
}
if (nsf(Movie_side_kick_type(mov)) != nsf(Character_Other)) {
printf("Unexpected side kick.\n");
goto done;
}
/*
* We need to cast because generic pointers refer to the start
* of the memory block which is the string length, not the first
* character in the string.
*/
text = nsc(string_cast_from_generic(nsf(Movie_side_kick(mov))));
if (!text) {
printf("missing side kick string.\n");
goto done;
}
if (strcmp(text, "Nemo")) {
printf("unexpected side kick string: '%s'.\n", text);
goto done;
}
text = nsf(Movie_side_kick_as_string(mov));
if (!text) {
printf("missing side kick string.\n");
goto done;
}
if (strcmp(text, "Nemo")) {
printf("unexpected side kick string (take 2): '%s'.\n", text);
goto done;
}
character = nsf(Movie_side_kick_union(mov));
text = nsc(string_cast_from_union(character));
if (strcmp(text, "Nemo")) {
printf("unexpected side kick string (take 3): '%s'.\n", text);
goto done;
}
characters = nsf(Movie_characters_union(mov));
character = nsf(Character_union_vec_at(characters, 0));
if (character.type != nsf(Character_Rapunzel)) {
printf("The first character is not Rapunzel.");
goto done;
};
character = nsf(Character_union_vec_at(characters, 1));
if (character.type != nsf(Character_MuLan)) {
printf("The second character is not MuLan.");
goto done;
};
attacker = character.value;
if (nsf(Attacker_sword_attack_damage(attacker) != 42)) {
printf("The second character has unexpected sword damage.");
goto done;
}
character = nsf(Character_union_vec_at(characters, 2));
if (character.type != nsf(Character_MuLan)) {
printf("The third character is not MuLan.");
goto done;
};
attacker = character.value;
if (nsf(Attacker_sword_attack_damage(attacker) != 1)) {
printf("The third character has unexpected sword damage.");
goto done;
}
if (nsc(union_type_vec_at(nsf(Movie_characters_type(mov)), 3)) != nsf(Character_Other)) {
printf("The fourth character was not of type 'Other'!\n");
goto done;
}
text = nsf(Character_union_vec_at_as_string(characters, 3));
if (!text || strcmp(text, "other")) {
printf("The fourth character was not described as 'other'.\n");
goto done;
}
character = nsf(Character_union_vec_at(characters, 3));
if (character.type != nsf(Character_Other)) {
printf("The fourth character is not of type 'Other' (take two).");
goto done;
};
text = nsc(string_cast_from_union(character));
if (!text || strcmp(text, "other")) {
printf("The fourth character was not described as 'other' (take two).\n");
goto done;
}
character = nsf(Character_union_vec_at(characters, 4));
if (character.type != nsf(Character_Belle)) {
printf("The fifth character is not Belle.");
goto done;
};
character = nsf(Character_union_vec_at(characters, 5));
if (character.type != nsf(Character_Belle)) {
printf("The sixth character is not Belle.");
goto done;
};
character = nsf(Character_union_vec_at(characters, 6));
if (character.type != nsf(Character_Belle)) {
printf("The seventh character is not Belle.");
goto done;
};
character = nsf(Character_union_vec_at(characters, 7));
if (character.type != nsf(Character_Belle)) {
printf("The eighth character is not Belle.");
goto done;
};
character = nsf(Character_union_vec_at(characters, 8));
if (character.type != nsf(Character_Other)) {
printf("The ninth character is not of type 'Other'.");
goto done;
};
character = nsf(Character_union_vec_at(characters, 9));
if (character.type != nsf(Character_Other)) {
printf("The ninth character is not of type 'Other'.");
goto done;
};
if (nsf(Character_union_vec_len(characters) != 10)) {
printf("The 11'th character should not exist.");
goto done;
};
ret = 0;
done:
flatcc_builder_aligned_free(buffer);
return ret;
}
int test_add_set_defaults(flatcc_builder_t *B)
{
void *buffer;
size_t size;
ns(Monster_table_t) mon;
flatcc_builder_reset(B);
ns(Monster_start_as_root(B));
ns(Monster_name_create_str(B, "MyMonster"));
ns(Monster_hp_add(B, 100));
ns(Monster_mana_add(B, 100));
ns(Monster_color_add(B, ns(Color_Blue)));
ns(Monster_end_as_root(B));
buffer = flatcc_builder_get_direct_buffer(B, &size);
mon = ns(Monster_as_root(buffer));
if (ns(Monster_hp_is_present(mon))) {
printf("default should not be present for hp field\n");
return -1;
}
if (!ns(Monster_mana_is_present(mon))) {
printf("non-default should be present for mana field\n");
return -1;
}
if (ns(Monster_color_is_present(mon))) {
printf("default should not be present for color field\n");
return -1;
}
flatcc_builder_reset(B);
ns(Monster_start_as_root(B));
ns(Monster_name_create_str(B, "MyMonster"));
ns(Monster_hp_force_add(B, 100));
ns(Monster_mana_force_add(B, 100));
ns(Monster_color_force_add(B, ns(Color_Blue)));
ns(Monster_end_as_root(B));
buffer = flatcc_builder_get_direct_buffer(B, &size);
mon = ns(Monster_as_root(buffer));
if (!ns(Monster_hp_is_present(mon))) {
printf("default should be present for hp field when forced\n");
return -1;
}
if (!ns(Monster_mana_is_present(mon))) {
printf("non-default should be present for mana field, also when forced\n");
return -1;
}
if (!ns(Monster_color_is_present(mon))) {
printf("default should be present for color field when forced\n");
return -1;
}
return 0;
}
int test_nested_buffer(flatcc_builder_t *B)
{
void *buffer;
size_t size;
ns(Monster_table_t) mon, nested;
flatcc_builder_reset(B);
ns(Monster_start_as_root(B));
ns(Monster_name_create_str(B, "MyMonster"));
/*
* Note:
* ns(Monster_testnestedflatbuffer_start(B));
* would start a raw ubyte array so we use start_as_root.
*/
ns(Monster_testnestedflatbuffer_start_as_root(B));
ns(Monster_name_create_str(B, "MyNestedMonster"));
ns(Monster_testnestedflatbuffer_end_as_root(B));
ns(Monster_hp_add(B, 10));
ns(Monster_end_as_root(B));
buffer = flatcc_builder_get_direct_buffer(B, &size);
hexdump("nested flatbuffer", buffer, size, stderr);
mon = ns(Monster_as_root(buffer));
if (strcmp(ns(Monster_name(mon)), "MyMonster")) {
printf("got the wrong root monster\n");
return -1;
}
/*
* Note:
* nested = ns(Monster_testnestedflatbuffer(mon));
* would return a raw ubyte vector not a monster.
*/
nested = ns(Monster_testnestedflatbuffer_as_root(mon));
if (ns(Monster_hp(mon)) != 10) {
printf("health points wrong at root monster\n");
return -1;
}
assert(ns(Monster_name(nested)));
if (strcmp(ns(Monster_name(nested)), "MyNestedMonster")) {
printf("got the wrong nested monster\n");
return -1;
}
return 0;
}
int test_nested_buffer_first(flatcc_builder_t *B)
{
void *buffer;
size_t size;
ns(Monster_table_t) mon, nested;
flatcc_builder_reset(B);
ns(Monster_start_as_root(B));
/*
* Note:
* ns(Monster_testnestedflatbuffer_start(B));
* would start a raw ubyte array so we use start_as_root.
*
* Here we create the nested buffer first, and the parent
* string after so the emitter sees the nested buffer first.
*/
ns(Monster_testnestedflatbuffer_start_as_root(B));
ns(Monster_name_create_str(B, "MyNestedMonster"));
ns(Monster_testnestedflatbuffer_end_as_root(B));
ns(Monster_hp_add(B, 10));
ns(Monster_name_create_str(B, "MyMonster"));
ns(Monster_end_as_root(B));
buffer = flatcc_builder_get_direct_buffer(B, &size);
hexdump("nested flatbuffer", buffer, size, stderr);
mon = ns(Monster_as_root(buffer));
if (strcmp(ns(Monster_name(mon)), "MyMonster")) {
printf("got the wrong root monster\n");
return -1;
}
/*
* Note:
* nested = ns(Monster_testnestedflatbuffer(mon));
* would return a raw ubyte vector not a monster.
*/
nested = ns(Monster_testnestedflatbuffer_as_root(mon));
if (ns(Monster_hp(mon)) != 10) {
printf("health points wrong at root monster\n");
return -1;
}
assert(ns(Monster_name(nested)));
if (strcmp(ns(Monster_name(nested)), "MyNestedMonster")) {
printf("got the wrong nested monster\n");
return -1;
}
return 0;
}
int test_nested_buffer_using_nest(flatcc_builder_t *B)
{
void *buffer;
uint8_t nested_buffer[1024];
size_t size, nested_size;
ns(Monster_table_t) mon, nested;
flatcc_builder_reset(B);
ns(Monster_start_as_root(B));
ns(Monster_name_create_str(B, "MyNestedMonster"));
ns(Monster_mana_add(B, 42));
ns(Monster_end_as_root(B));
nested_size = flatcc_builder_get_buffer_size(B);
if (!flatcc_builder_copy_buffer(B, nested_buffer, sizeof(nested_buffer))) {
printf("nested buffer copy failed\n");
return -1;
}
flatcc_builder_reset(B);
ns(Monster_start_as_root(B));
ns(Monster_testnestedflatbuffer_nest(B, nested_buffer, nested_size, 0));
ns(Monster_hp_add(B, 10));
ns(Monster_name_create_str(B, "MyMonster"));
ns(Monster_end_as_root(B));
buffer = flatcc_builder_get_direct_buffer(B, &size);
hexdump("nested flatbuffer [using _nest()]", buffer, size, stderr);
mon = ns(Monster_as_root(buffer));
if (strcmp(ns(Monster_name(mon)), "MyMonster")) {
printf("got the wrong root monster\n");
return -1;
}
/*
* Note:
* nested = ns(Monster_testnestedflatbuffer(mon));
* would return a raw ubyte vector not a monster.
*/
nested = ns(Monster_testnestedflatbuffer_as_root(mon));
if (ns(Monster_hp(mon)) != 10) {
printf("health points wrong at root monster\n");
return -1;
}
assert(ns(Monster_name(nested)));
if (strcmp(ns(Monster_name(nested)), "MyNestedMonster")) {
printf("got the wrong nested monster\n");
return -1;
}
if (ns(Monster_mana(nested)) != 42) {
printf("mana points wrong in nested monster\n");
return -1;
}
return 0;
}
int verify_include(void *buffer)
{
if (MyGame_OtherNameSpace_FromInclude_Foo != 17) {
printf("Unexpected enum value `Foo` from included schema\n");
return -1;
}
if (MyGame_OtherNameSpace_FromInclude_IncludeVal != 0) {
printf("Unexpected enum value `IncludeVal` from included schema\n");
return -1;
}
return 0;
}
int test_struct_buffer(flatcc_builder_t *B)
{
uint8_t buffer[100];
size_t size;
ns(Vec3_t) *v;
ns(Vec3_struct_t) vec3;
flatcc_builder_reset(B);
ns(Vec3_create_as_root(B, 1, 2, 3, 4.2, ns(Color_Blue), 2730, -17));
size = flatcc_builder_get_buffer_size(B);
assert(size == 48);
printf("dbg: struct buffer size: %d\n", (int)size);
assert(flatcc_emitter_get_buffer_size(flatcc_builder_get_emit_context(B)) == size);
if (!flatcc_builder_copy_buffer(B, buffer, 100)) {
printf("Copy failed\n");
return -1;
}
hexdump("Vec3 struct buffer", buffer, size, stderr);
if (!nsc(has_identifier(buffer, "MONS"))) {
printf("wrong Vec3 identifier (explicit)\n");
return -1;
}
if (nsc(has_identifier(buffer, "mons"))) {
printf("accepted wrong Vec3 identifier (explicit)\n");
return -1;
}
if (!nsc(has_identifier(buffer, ns(Vec3_identifier)))) {
printf("wrong Vec3 identifier (via define)\n");
return -1;
}
vec3 = ns(Vec3_as_root(buffer));
/* Convert buffer to native in place - a nop on native platform. */
v = (ns(Vec3_t) *)vec3;
ns(Vec3_from_pe(v));
if (v->x != 1.0f || v->y != 2.0f || v->z != 3.0f
|| v->test1 != 4.2 || v->test2 != ns(Color_Blue)
|| v->test3.a != 2730 || v->test3.b != -17
) {
printf("struct buffer not valid\n");
return -1;
}
assert(ns(Color_Red) == 1 << 0);
assert(ns(Color_Green) == 1 << 1);
assert(ns(Color_Blue) == 1 << 3);
assert(sizeof(ns(Color_Blue) == 1));
return 0;
}
int test_typed_struct_buffer(flatcc_builder_t *B)
{
uint8_t buffer[100];
size_t size;
ns(Vec3_t) *v;
ns(Vec3_struct_t) vec3;
flatcc_builder_reset(B);
ns(Vec3_create_as_typed_root(B, 1, 2, 3, 4.2, ns(Color_Blue), 2730, -17));
size = flatcc_builder_get_buffer_size(B);
assert(size == 48);
printf("dbg: struct buffer size: %d\n", (int)size);
assert(flatcc_emitter_get_buffer_size(flatcc_builder_get_emit_context(B)) == size);
if (!flatcc_builder_copy_buffer(B, buffer, 100)) {
printf("Copy failed\n");
return -1;
}
hexdump("typed Vec3 struct buffer", buffer, size, stderr);
if (!nsc(has_identifier(buffer, "\xd2\x3e\xf5\xa8"))) {
printf("wrong Vec3 identifier (explicit)\n");
return -1;
}
if (nsc(has_identifier(buffer, "mons"))) {
printf("accepted wrong Vec3 identifier (explicit)\n");
return -1;
}
if (!nsc(has_identifier(buffer, ns(Vec3_type_identifier)))) {
printf("wrong Vec3 identifier (via define)\n");
return -1;
}
if (!ns(Vec3_as_root_with_type_hash(buffer, ns(Vec3_type_hash)))) {
printf("wrong Vec3 type identifier (via define)\n");
return -1;
}
if (flatcc_verify_ok != ns(Vec3_verify_as_root_with_type_hash(buffer, size, ns(Vec3_type_hash)))) {
printf("verify failed with Vec3 type hash\n");
return -1;
}
vec3 = ns(Vec3_as_typed_root(buffer));
if (!vec3) {
printf("typed Vec3 could not be read\n");
return -1;
}
if (flatcc_verify_ok != ns(Vec3_verify_as_typed_root(buffer, size))) {
printf("verify failed with Vec3 as typed root\n");
return -1;
}
/* Convert buffer to native in place - a nop on native platform. */
v = (ns(Vec3_t) *)vec3;
ns(Vec3_from_pe(v));
if (v->x != 1.0f || v->y != 2.0f || v->z != 3.0f
|| v->test1 != 4.2 || v->test2 != ns(Color_Blue)
|| v->test3.a != 2730 || v->test3.b != -17
) {
printf("struct buffer not valid\n");
return -1;
}
assert(ns(Color_Red) == 1 << 0);
assert(ns(Color_Green) == 1 << 1);
assert(ns(Color_Blue) == 1 << 3);
assert(sizeof(ns(Color_Blue) == 1));
return 0;
}
/* A stable test snapshot for reference. */
int gen_monster_benchmark(flatcc_builder_t *B)
{
uint8_t inv[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
ns(Vec3_t) *vec;
ns(Test_t) *test, x;
flatcc_builder_reset(B);
ns(Monster_start_as_root(B));
ns(Monster_hp_add(B, 80));
vec = ns(Monster_pos_start(B));
vec->x = 1, vec->y = 2, vec->z = -3.2f;
ns(Monster_pos_end(B));
ns(Monster_name_create_str(B, "MyMonster"));
ns(Monster_inventory_create(B, inv, c_vec_len(inv)));
ns(Monster_test4_start(B));
test = ns(Monster_test4_extend(B, 1));
test->a = 0x10;
test->b = 0x20;
test = ns(Monster_test4_extend(B, 2));
test->a = 0x30;
test->b = 0x40;
test[1].a = 0x50;
test[1].b = 0x60;
ns(Monster_test4_push_create(B, 0x70, (int8_t)0x80));
x.a = 0x191; /* This is a short. */
x.b = (int8_t)0x91; /* This is a byte. */
ns(Monster_test4_push(B, &x));
ns(Monster_test4_end(B));
ns(Monster_end_as_root(B));
return 0;
}
int time_monster(flatcc_builder_t *B)
{
double t1, t2;
const int rep = 1000000;
size_t size;
int i;
printf("start timing ...\n");
t1 = elapsed_realtime();
for (i = 0; i < rep; ++i) {
gen_monster_benchmark(B);
}
size = flatcc_builder_get_buffer_size(B);
t2 = elapsed_realtime();
show_benchmark("encode monster buffer", t1, t2, size, rep, "million");
return 0;
}
int gen_struct_buffer_benchmark(flatcc_builder_t *B)
{
void *buffer;
ns(Vec3_t) *v;
ns(Vec3_struct_t) vec3;
flatcc_builder_reset(B);
ns(Vec3_create_as_root(B, 1, 2, 3, 4.2, ns(Color_Blue), 2730, -17));
buffer = flatcc_builder_get_direct_buffer(B, 0);
if (!buffer) {
return -1;
}
vec3 = ns(Vec3_as_root_with_identifier(buffer, 0));
/* Convert buffer to native in place - a nop on native platform. */
v = (ns(Vec3_t) *)vec3;
ns(Vec3_from_pe(v));
if (v->x != 1.0f || v->y != 2.0f || v->z != 3.0f
|| v->test1 != 4.2 || v->test2 != ns(Color_Blue)
|| v->test3.a != 2730 || v->test3.b != -17
) {
return -1;
}
return 0;
}
int time_struct_buffer(flatcc_builder_t *B)
{
double t1, t2;
const int rep = 1000000;
size_t size;
int i;
int ret = 0;
printf("start timing ...\n");
t1 = elapsed_realtime();
for (i = 0; i < rep; ++i) {
ret |= gen_struct_buffer_benchmark(B);
}
t2 = elapsed_realtime();
size = flatcc_builder_get_buffer_size(B);
if (ret) {
printf("struct not valid\n");
}
show_benchmark("encode, decode and access Vec struct buffers", t1, t2, size, rep, "million");
return ret;
}
int main(int argc, char *argv[])
{
flatcc_builder_t builder, *B;
(void)argc;
(void)argv;
B = &builder;
flatcc_builder_init(B);
#ifdef NDEBUG
printf("running optimized monster test\n");
#else
printf("running debug monster test\n");
#endif
#if 1
if (test_table_with_emptystruct(B)) {
printf("TEST FAILED\n");
return -1;
}
#endif
#if 1
if (test_enums(B)) {
printf("TEST FAILED\n");
return -1;
}
#endif
#if 1
if (test_empty_monster(B)) {
printf("TEST FAILED\n");
return -1;
}
#endif
#if 1
if (test_monster(B)) {
printf("TEST FAILED\n");
return -1;
}
#endif
#if 1
if (test_monster_with_size(B)) {
printf("TEST FAILED\n");
return -1;
}
#endif
#if 1
if (test_string(B)) {
printf("TEST FAILED\n");
return -1;
}
#endif
#if 1
if (test_struct_buffer(B)) {
printf("TEST FAILED\n");
return -1;
}
#endif
#if 1
if (test_typed_empty_monster(B)) {
printf("TEST FAILED\n");
return -1;
}
#endif
#if 1
if (test_typed_table_with_emptystruct(B)) {
printf("TEST FAILED\n");
return -1;
}
#endif
#if 1
if (test_typed_struct_buffer(B)) {
printf("TEST FAILED\n");
return -1;
}
#endif
#if 1
if (test_clone_slice(B)) {
printf("TEST FAILED\n");
return -1;
}
#endif
#if 1
if (test_add_set_defaults(B)) {
printf("TEST FAILED\n");
return -1;
}
#endif
#if 1
if (test_create_add_field(B)) {
printf("TEST FAILED\n");
return -1;
}
#endif
#if 1
if (test_union_vector(B)) {
printf("TEST FAILED\n");
return -1;
}
#endif
#if 1
if (test_basic_sort(B)) {
printf("TEST FAILED\n");
return -1;
}
#endif
#if 1
if (test_sort_find(B)) {
printf("TEST FAILED\n");
return -1;
}
#endif
#if 1
if (test_scan(B)) {
printf("TEST FAILED\n");
return -1;
}
#endif
#if 1
if (test_nested_buffer(B)) {
printf("TEST FAILED\n");
return -1;
}
#endif
#if 1
if (test_nested_buffer_first(B)) {
printf("TEST FAILED\n");
return -1;
}
#endif
#if 1
if (test_nested_buffer_using_nest(B)) {
printf("TEST FAILED\n");
return -1;
}
#endif
#if 1
if (test_cloned_monster(B)) {
printf("TEST FAILED\n");
return -1;
}
#endif
#if 1
if (verify_include(B)) {
printf("TEST FAILED\n");
return -1;
}
#endif
#if 1
if (test_type_aliases(B)) {
printf("TEST FAILED\n");
return -1;
}
#endif
#if 1
if (test_mixed_type_union(B)) {
printf("TEST FAILED\n");
return -1;
}
#endif
#ifdef FLATBUFFERS_BENCHMARK
time_monster(B);
time_struct_buffer(B);
#endif
flatcc_builder_clear(B);
return 0;
}
| 31.742235 | 134 | 0.626397 | [
"object",
"vector"
] |
08769264c946b5070cabb76984251efbfad31caf | 335 | h | C | Engine/Source/Runtime/Engine/Classes/Particles/Color/ParticleModuleColorBase.h | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | Engine/Source/Runtime/Engine/Classes/Particles/Color/ParticleModuleColorBase.h | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | 2 | 2015-06-21T17:38:11.000Z | 2015-06-22T20:54:42.000Z | Engine/Source/Runtime/Engine/Classes/Particles/Color/ParticleModuleColorBase.h | PopCap/GameIdea | 201e1df50b2bc99afc079ce326aa0a44b178a391 | [
"BSD-2-Clause"
] | null | null | null | // Copyright 1998-2015 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "Particles/ParticleModule.h"
#include "ParticleModuleColorBase.generated.h"
UCLASS(editinlinenew, hidecategories=Object, abstract, meta=(DisplayName = "Color"))
class UParticleModuleColorBase : public UParticleModule
{
GENERATED_UCLASS_BODY()
};
| 22.333333 | 84 | 0.791045 | [
"object"
] |
087ae356e0584b3b1001706e52215193d22e73b4 | 22,518 | h | C | iked/ikev2.h | jhjgithub/racoon2 | fa95b391ecf11cea71e6b8c9565f86a4e210baac | [
"BSD-3-Clause"
] | 17 | 2018-06-27T02:55:47.000Z | 2022-01-12T03:18:30.000Z | iked/ikev2.h | jhjgithub/racoon2 | fa95b391ecf11cea71e6b8c9565f86a4e210baac | [
"BSD-3-Clause"
] | 8 | 2019-01-10T22:13:21.000Z | 2022-03-07T09:04:27.000Z | iked/ikev2.h | jhjgithub/racoon2 | fa95b391ecf11cea71e6b8c9565f86a4e210baac | [
"BSD-3-Clause"
] | 11 | 2018-07-29T18:02:29.000Z | 2021-06-30T02:58:49.000Z | /* $Id: ikev2.h,v 1.38 2010/01/28 10:52:58 fukumoto Exp $ */
/*
* Copyright (C) 2004 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.
*/
/*
* (RFC4306)
* http://www.iana.org/assignments/ikev2-parameters
*/
#ifndef __IKEV2_H_
#define __IKEV2_H_
#define PACKED __attribute__((__packed__))
/*
* 2 IKE Protocol Details and Variations
*/
#define IKEV2_UDP_PORT PORT_ISAKMP
#define IKEV2_UDP_PORT_NATT PORT_ISAKMP_NATT
#define IKEV2_MUST_SUPPORT_PACKET_SIZE 1280
#define IKEV2_SHOULD_SUPPORT_PACKET_SIZE 3000
/*
* 2.15 Authentication of the IKE_SA
*/
#define IKEV2_SHAREDSECRET_KEYPAD "Key Pad for IKEv2"
#define IKEV2_SHAREDSECRET_KEYPADLEN (sizeof(IKEV2_SHAREDSECRET_KEYPAD) - 1)
/*
* 3.1 The IKE Header
*/
#define IKEV2_MAJOR_VERSION 2
#define IKEV2_MINOR_VERSION 0
#if 0
struct isakmp_cookie {
uint8_t bytes[8];
} PACKED; /* Cookie in IKEv1. SPI in IKEv2 */
typedef struct isakmp_cookie isakmp_cookie_t;
#endif
#if 0
typedef struct isakmp_index {
isakmp_cookie_t i_ck;
isakmp_cookie_t r_ck;
} PACKED isakmp_index_t;
#endif
struct ikev2_header {
isakmp_cookie_t initiator_spi;
isakmp_cookie_t responder_spi;
uint8_t next_payload;
uint8_t version;
uint8_t exchange_type;
uint8_t flags;
uint32_t message_id;
uint32_t length;
} PACKED;
#ifndef ISAKMP_GETMAJORV
#define ISAKMP_GETMAJORV(v) (((v) & 0xf0) >> 4)
#define ISAKMP_GETMINORV(v) ((v) & 0x0f)
#endif
#define IKEV2_VERSION ((IKEV2_MAJOR_VERSION << 4) | IKEV2_MINOR_VERSION)
/* Exchange Types */
/* RESERVED 0-33 */
#define IKEV2EXCH_IKE_SA_INIT 34
#define IKEV2EXCH_IKE_AUTH 35
#define IKEV2EXCH_CREATE_CHILD_SA 36
#define IKEV2EXCH_INFORMATIONAL 37
#define IKEV2EXCH_IKE_SESSION_RESUME 38 /* (RFC5723) */
/* Reserved for IKEv2+ 39-239 */
#define IKEV2EXCH_PRIVATE 240
/* Reserved for private use 240-255 */
/* !!! Flags .... The bits are defined LSB first */
#define IKEV2FLAG_INITIATOR 0x08
#define IKEV2FLAG_VERSION 0x10
#define IKEV2FLAG_RESPONSE 0x20
#define IKEV2FLAG_RESERVED 0xC7
/*
* 3.2 Generic Payload Header
*/
struct ikev2_payload_header {
uint8_t next_payload;
uint8_t header_byte_2;
uint16_t payload_length;
} PACKED;
#define get_payload_length(p_) (get_uint16(&((struct ikev2_payload_header *)(p_))->payload_length))
#define get_payload_data_length(p_) (get_payload_length(p_) - sizeof(struct ikev2_payload_header))
#define POINT_NEXT_PAYLOAD(p_, t_) ( \
(t_) = (p_)->next_payload, \
(p_) = (struct ikev2_payload_header *)(((uint8_t *)(p_)) + get_payload_length((p_))) \
)
#define payload_is_critical(p_) ((p_)->header_byte_2 & IKEV2PAYL_FLAG_CRITICAL)
#define set_payload_header(p_, np_, len_) do { \
(p_)->next_payload = (np_); \
(p_)->header_byte_2 = 0; \
put_uint16(&(p_)->payload_length, (len_)); \
} while (0)
#define IKEV2PAYL_FLAG_CRITICAL 0x80
#define IKEV2_NO_NEXT_PAYLOAD 0
#define IKEV2_PAYLOAD_SA 33
#define IKEV2_PAYLOAD_KE 34
#define IKEV2_PAYLOAD_ID_I 35
#define IKEV2_PAYLOAD_ID_R 36
#define IKEV2_PAYLOAD_CERT 37
#define IKEV2_PAYLOAD_CERTREQ 38
#define IKEV2_PAYLOAD_AUTH 39
#define IKEV2_PAYLOAD_NONCE 40
#define IKEV2_PAYLOAD_NOTIFY 41
#define IKEV2_PAYLOAD_DELETE 42
#define IKEV2_PAYLOAD_VENDOR_ID 43
#define IKEV2_PAYLOAD_TS_I 44 /* Traffic Selector - Initiator */
#define IKEV2_PAYLOAD_TS_R 45 /* Traffic Selector - Responder */
#define IKEV2_PAYLOAD_ENCRYPTED 46
#define IKEV2_PAYLOAD_CONFIG 47
#define IKEV2_PAYLOAD_EAP 48
/* Reserved to IANA 49 - 127 */
#define IKEV2_PAYLOAD_PRIVATE 128
/* Private use 128 - 255 */
/*
* 3.3 Security Association Payload
*/
struct ikev2payl_sa {
struct ikev2_payload_header header;
/* followed by Proposals */
} PACKED;
/* 3.3.1 Proposal Substructure */
struct ikev2proposal {
uint8_t more;
uint8_t reserved;
uint16_t proposal_length;
uint8_t proposal_number;
uint8_t protocol_id;
uint8_t spi_size;
uint8_t num_transforms;
/* SPI (variable) */
/* followed by Transforms */
} PACKED;
/* values for "more" field */
#define IKEV2PROPOSAL_LAST 0
#define IKEV2PROPOSAL_MORE 2
/* values for "Protocol ID" field */
#define IKEV2PROPOSAL_IKE 1
#define IKEV2PROPOSAL_AH 2
#define IKEV2PROPOSAL_ESP 3
#define IKEV2PROPOSAL_FC_ESP_HEADER 4 /* (RFC4595) */
#define IKEV2PROPOSAL_FC_CT_AUTHENTICATION 5 /* (RFC4595) */
/* reserved to IANA 6-200 */
/* private use 201-255 */
/* 3.3.2 Transform Substructure */
struct ikev2transform {
uint8_t more;
uint8_t reserved1;
uint16_t transform_length;
uint8_t transform_type;
uint8_t reserved2;
uint16_t transform_id;
/* followed by Transform Attributes */
} PACKED;
/* values for "more" field */
#define IKEV2TRANSFORM_LAST 0
#define IKEV2TRANSFORM_MORE 3
/* values for "transform type" field */
#define IKEV2TRANSFORM_TYPE_ENCR 1
#define IKEV2TRANSFORM_TYPE_PRF 2
#define IKEV2TRANSFORM_TYPE_INTEGR 3 /* Integrity Algorithm */
#define IKEV2TRANSFORM_TYPE_DH 4 /* Diffie-Hellman Group */
#define IKEV2TRANSFORM_TYPE_ESN 5 /* Extended Sequence Numbers */
/* Reserved to IANA 6-240 */
#define IKEV2TRANSFORM_TYPE_PRIVATE 241
/* Private use 241-255 */
/* If the initiator wishes to make use of the transform optional to
the responder, she includes a transform substructure with transform
ID = 0 as one of the options. */
#define IKEV2TRANSF_ID_OPTIONAL 0
/* Transform IDs for Transform Type 1 (Encryption Algorithm) */
#define IKEV2TRANSF_ENCR_DES_IV64 1 /* (RFC1827) */
#define IKEV2TRANSF_ENCR_DES 2 /* (RFC2405) */
#define IKEV2TRANSF_ENCR_3DES 3 /* (RFC2451) */
#define IKEV2TRANSF_ENCR_RC5 4 /* (RFC2451) */
#define IKEV2TRANSF_ENCR_IDEA 5 /* (RFC2451) */
#define IKEV2TRANSF_ENCR_CAST 6 /* (RFC2451) */
#define IKEV2TRANSF_ENCR_BLOWFISH 7 /* (RFC2451) */
#define IKEV2TRANSF_ENCR_3IDEA 8 /* (RFC2451) */
#define IKEV2TRANSF_ENCR_DES_IV32 9
/* RESERVED 10 */
#define IKEV2TRANSF_ENCR_NULL 11 /* (RFC2410) */
#define IKEV2TRANSF_ENCR_AES_CBC 12 /* (RFC3602) */
#define IKEV2TRANSF_ENCR_AES_CTR 13 /* (RFC3686) */
#define IKEV2TRANSF_ENCR_AES_CCM_8 14 /* (RFC4309) */
#define IKEV2TRANSF_ENCR_AES_CCM_12 15 /* (RFC4309) */
#define IKEV2TRANSF_ENCR_AES_CCM_16 16 /* (RFC4309) */
/* Unassigned 17 */
#define IKEV2TRANSF_ENCR_AES_GCM_ICV8 18 /* (RFC4106) */
#define IKEV2TRANSF_ENCR_AES_GCM_ICV12 19 /* (RFC4106) */
#define IKEV2TRANSF_ENCR_AES_GCM_ICV16 20 /* (RFC4106) */
#define IKEV2TRANSF_ENCR_NULL_AUTH_AES_GMAC 21 /* (RFC4543) */
#define IKEV2TRANSF_ENCR_IEEE_P1619_XTS_AES 22
#define IKEV2TRANSF_ENCR_CAMELLIA_CBC 23 /* (RFC5529) */
#define IKEV2TRANSF_ENCR_CAMELLIA_CTR 24 /* (RFC5529) */
#define IKEV2TRANSF_ENCR_CAMELLIA_CCM_ICV8 25 /* (RFC5529) */
#define IKEV2TRANSF_ENCR_CAMELLIA_CCM_ICV12 26 /* (RFC5529) */
#define IKEV2TRANSF_ENCR_CAMELLIA_CCM_ICV16 27 /* (RFC5529) */
/* Reserved to IANA 28-1023 */
#define IKEV2TRANSF_ENCR_PRIVATE 1024
/* Private use 1024-65535 */
/* Transform IDs for Transform Type 2 (Pseudo-random Function) */
#define IKEV2TRANSF_PRF_HMAC_MD5 1 /* (RFC2104) */
#define IKEV2TRANSF_PRF_HMAC_SHA1 2 /* (RFC2104) */
#define IKEV2TRANSF_PRF_HMAC_TIGER 3 /* (RFC2104) */
#define IKEV2TRANSF_PRF_AES128_XCBC 4 /* (RFC4434) */
#define IKEV2TRANSF_PRF_HMAC_SHA2_256 5 /* (RFC4868) */
#define IKEV2TRANSF_PRF_HMAC_SHA2_384 6 /* (RFC4868) */
#define IKEV2TRANSF_PRF_HMAC_SHA2_512 7 /* (RFC4868) */
#define IKEV2TRANSF_PRF_AES128_CMAC 8 /* (RFC4615) */
/* Reserved to IANA 9-1023 */
#define IKEV2_PRF_PRIVATE 1024
/* Private use 1024-65535 */
/* Transform IDs for Transform Type 3 (Integrity Algorithm) */
#define IKEV2TRANSF_AUTH_HMAC_MD5_96 1 /* (RFC2403) */
#define IKEV2TRANSF_AUTH_HMAC_SHA1_96 2 /* (RFC2404) */
#define IKEV2TRANSF_AUTH_DES_MAC 3
#define IKEV2TRANSF_AUTH_KPDK_MD5 4 /* (RFC1826) */
#define IKEV2TRANSF_AUTH_AES_XCBC_96 5 /* (RFC3566) */
#define IKEV2TRANSF_AUTH_HMAC_MD5_128 6 /* (RFC4595) */
#define IKEV2TRANSF_AUTH_HMAC_SHA1_160 7 /* (RFC4595) */
#define IKEV2TRANSF_AUTH_AES_CMAC_96 8 /* (RFC4494) */
#define IKEV2TRANSF_AUTH_AES_128_GMAC 9 /* (RFC4543) */
#define IKEV2TRANSF_AUTH_AES_192_GMAC 10 /* (RFC4543) */
#define IKEV2TRANSF_AUTH_AES_256_GMAC 11 /* (RFC4543) */
#define IKEV2TRANSF_AUTH_HMAC_SHA2_256_128 12 /* (RFC4868) */
#define IKEV2TRANSF_AUTH_HMAC_SHA2_384_192 13 /* (RFC4868) */
#define IKEV2TRANSF_AUTH_HMAC_SHA2_512_256 14 /* (RFC4868) */
/* Reserved to IANA 15-1023 */
/* Private use 1024-65535 */
/* Transform IDs for Transform Type 4 (Diffie-Hellman Group) */
#define IKEV2TRANSF_DH_MODP768 1 /* Appendix B */
#define IKEV2TRANSF_DH_MODP1024 2
/* #define IKEV2TRANSF_DH_EC2N155 3 */
/* #define IKEV2TRANSF_DH_EC2N185 4 */
#define IKEV2TRANSF_DH_MODP1536 5 /* (RFC3526) */
/* Reserved to IANA 6-13 */
#define IKEV2TRANSF_DH_MODP2048 14 /* (RFC3526) */
#define IKEV2TRANSF_DH_MODP3072 15 /* (RFC3526) */
#define IKEV2TRANSF_DH_MODP4096 16 /* (RFC3526) */
#define IKEV2TRANSF_DH_MODP6144 17 /* (RFC3526) */
#define IKEV2TRANSF_DH_MODP8192 18 /* (RFC3526) */
#define IKEV2TRANSF_DH_ECP256 19 /* (RFC4753) */
#define IKEV2TRANSF_DH_ECP384 20 /* (RFC4753) */
#define IKEV2TRANSF_DH_ECP521 21 /* (RFC4753) */
#define IKEV2TRANSF_DH_MODP1024_160POS 22 /* (RFC5114) */
#define IKEV2TRANSF_DH_MODP2048_224POS 23 /* (RFC5114) */
#define IKEV2TRANSF_DH_MODP2048_256POS 24 /* (RFC5114) */
#define IKEV2TRANSF_DH_ECP192 25 /* (RFC5114) */
#define IKEV2TRANSF_DH_ECP224 26 /* (RFC5114) */
/* Reserved 27-1023 */
#define IKEV2TRANSF_DH_PRIVATE 1024
/* Private use 1024-65535 */
/* Transform IDs for Transform Type 5 (Extended Sequence Numbers) */
#define IKEV2TRANSF_ESN_NO 0
#define IKEV2TRANSF_ESN_YES 1 /* default choice */
/* Reserved 2-65535 */
/* 3.3.5 Transform Attributes */
struct ikev2attrib {
uint16_t type;
uint16_t l_or_v; /* length or value */
} PACKED;
#define IKEV2ATTRIB_SHORT 0x8000
#define IKEV2ATTRIB_IS_SHORT(_a) ((_a) & IKEV2_ATTRIB_SHORT)
/* Attribute Types */
/* RESERVED 0-13 */
#define IKEV2ATTRIB_KEY_LENGTH 14 /* (TV) */
#define IKEV2ATTRIB_PRIVATE 16384
/* Private use 16384-32767 */
#define IKEV2ATTRIB_VALUE_SHORT(_a) (get_uint16(&(_a)->l_or_v))
#define IKEV2ATTRIB_VALUE_LONG(_a) (&((_a)->l_or_v))
/* Long format to be defined */
/*
* 3.4 Key Exchange Payload
*/
struct ikev2payl_ke_h {
uint16_t dh_group_id;
uint16_t reserved;
} PACKED;
struct ikev2payl_ke {
struct ikev2_payload_header header;
struct ikev2payl_ke_h ke_h;
/* followed by Key Exchange Data */
} PACKED;
/*
* 3.5 Identification Payloads
*/
struct ikev2payl_ident_h {
uint8_t id_type;
uint8_t reserved[3];
} PACKED;
struct ikev2payl_ident {
struct ikev2_payload_header header;
struct ikev2payl_ident_h id_h;
/* followed by Identification Data */
} PACKED;
#define IKEV2_ID_IPV4_ADDR 1
#define IKEV2_ID_FQDN 2
#define IKEV2_ID_RFC822_ADDR 3
/* unspecified 4 */
#define IKEV2_ID_IPV6_ADDR 5
/* unspecified 6-8 */
#define IKEV2_ID_DER_ASN1_DN 9
#define IKEV2_ID_DER_ASN1_GN 10
#define IKEV2_ID_KEY_ID 11
#define IKEV2_ID_FC_NAME 12 /* (RFC4595) */
/* Reserved to IANA 13-200 */
#define IKEV2_ID_PRIVATE 201
/* Private use 201-255 */
/*
* 3.6 Certificate Payload
*/
struct ikev2payl_cert {
struct ikev2_payload_header header;
uint8_t encoding;
/* followed by Certificate Data */
} PACKED;
#define IKEV2_CERT_PKCS7 1
#define IKEV2_CERT_PGP 2
#define IKEV2_CERT_DNS 3
#define IKEV2_CERT_X509_SIGN 4
/* reserved 5 */
#define IKEV2_CERT_KERBEROS 6
#define IKEV2_CERT_CRL 7
#define IKEV2_CERT_ARL 8
#define IKEV2_CERT_SPKI 9
#define IKEV2_CERT_X509_ATTR 10
#define IKEV2_CERT_RAW_RSA 11
#define IKEV2_CERT_HASH_X509CERT 12
#define IKEV2_CERT_HASH_X509BUNDLE 13
#define IKEV2_CERT_OCSP_CONTENT 14 /* (RFC4806) */
/* Reserved to IANA 15-200 */
#define IKEV2_CERT_PRIVATE 201
/* Private use 201-255 */
/*
* 3.7 Certificate Request Payload
*/
struct ikev2payl_certreq {
struct ikev2_payload_header header;
uint8_t cert_encoding;
/* followed by Certification Authority */
} PACKED;
/*
* 3.8 Authentication Payload
*/
struct ikev2payl_auth_h {
uint8_t auth_method;
uint8_t reserved[3];
} PACKED;
struct ikev2payl_auth {
struct ikev2_payload_header header;
struct ikev2payl_auth_h ah;
/* followed by Authentication Data */
} PACKED;
#define IKEV2_AUTH_RSASIG 1
#define IKEV2_AUTH_SHARED_KEY 2
#define IKEV2_AUTH_DSS 3
/* Reserved 4-8 */
#define IKEV2_AUTH_ECDSA_SHA256_P256 9
#define IKEV2_AUTH_ECDSA_SHA384_P384 10
#define IKEV2_AUTH_ECDSA_SHA512_P521 11
/* Reserved 12-200 */
#define IKEV2_AUTH_PRIVATE 201
/* Private use 201-255 */
/*
* 3.9 Nonce Payload
*/
struct ikev2payl_nonce {
struct ikev2_payload_header header;
/* followed by Nonce Data */
} PACKED;
#define IKEV2_NONCE_SIZE_MIN 16
#define IKEV2_NONCE_SIZE_MAX 256
/*
* 3.10 Notify Payload
*/
struct ikev2payl_notify_h {
uint8_t protocol_id;
uint8_t spi_size;
uint16_t notify_message_type;
} PACKED;
struct ikev2payl_notify {
struct ikev2_payload_header header;
struct ikev2payl_notify_h nh;
/* followed by Security Parameter Index (SPI) */
/* followed by Notification Data */
} PACKED;
#define get_notify_type(n_) (get_uint16(&(n_)->nh.notify_message_type))
#define get_notify_data(n_) ((uint8_t *)((n_) + 1) + (n_)->nh.spi_size)
#define IKEV2_NOTIFY_PROTO_NONE 0
#define IKEV2_NOTIFY_PROTO_IKE 1
#define IKEV2_NOTIFY_PROTO_AH 2
#define IKEV2_NOTIFY_PROTO_ESP 3
#define IKEV2_UNSUPPORTED_CRITICAL_PAYLOAD 1
/* Reserved 2-3 */
#define IKEV2_INVALID_IKE_SPI 4
#define IKEV2_INVALID_MAJOR_VERSION 5
/* Reserved 6 */
#define IKEV2_INVALID_SYNTAX 7
/* Reserved 8 */
#define IKEV2_INVALID_MESSAGE_ID 9
/* Reserved 10 */
#define IKEV2_INVALID_SPI 11
/* Reserved 12-13 */
#define IKEV2_NO_PROPOSAL_CHOSEN 14
/* Reserved 15-16 */
#define IKEV2_INVALID_KE_PAYLOAD 17
/* Reserved 18-23 */
#define IKEV2_AUTHENTICATION_FAILED 24
/* Reserved 25-33 */
#define IKEV2_SINGLE_PAIR_REQUIRED 34
#define IKEV2_NO_ADDITIONAL_SAS 35
#define IKEV2_INTERNAL_ADDRESS_FAILURE 36
#define IKEV2_FAILED_CP_REQUIRED 37
#define IKEV2_TS_UNACCEPTABLE 38
#define IKEV2_INVALID_SELECTORS 39
#define IKEV2_UNACCEPTABLE_ADDRESSES 40 /* (RFC4555) */
#define IKEV2_UNEXPECTED_NAT_DETECTED 41 /* (RFC4555) */
#define IKEV2_USE_ASSIGNED_HoA 42 /* (RFC5026) */
/* RESERVED TO IANA - Error types 43 - 8191 */
/* Private Use - Errors 8192 - 16383 */
#define IKEV2_NOTIFYTYPE_ERROR_MAX 16383
#define IKEV2_INITIAL_CONTACT 16384
#define IKEV2_SET_WINDOW_SIZE 16385
#define IKEV2_ADDITIONAL_TS_POSSIBLE 16386
#define IKEV2_IPCOMP_SUPPORTED 16387
# define IKEV2_IPCOMP_OUI 1
# define IKEV2_IPCOMP_DEFLATE 2 /* RFC 2394 */
# define IKEV2_IPCOMP_LZS 3 /* RFC 2395 */
# define IKEV2_IPCOMP_LZJH 4 /* RFC 3051 */
/* reserved to IANA 5-240 */
/* private use 241-255 */
#define IKEV2_NAT_DETECTION_SOURCE_IP 16388
#define IKEV2_NAT_DETECTION_DESTINATION_IP 16389
#define IKEV2_COOKIE 16390
#define IKEV2_USE_TRANSPORT_MODE 16391
#define IKEV2_HTTP_CERT_LOOKUP_SUPPORTED 16392
#define IKEV2_REKEY_SA 16393
#define IKEV2_ESP_TFC_PADDING_NOT_SUPPORTED 16394 /* (draft13) */
#define IKEV2_NON_FIRST_FRAGMENTS_ALSO 16395 /* (draft14) */
#define IKEV2_MOBIKE_SUPPORTED 16396 /* (RFC4555) */
#define IKEV2_ADDITIONAL_IP4_ADDRESS 16397 /* (RFC4555) */
#define IKEV2_ADDITIONAL_IP6_ADDRESS 16398 /* (RFC4555) */
#define IKEV2_NO_ADDITIONAL_ADDRESSES 16399 /* (RFC4555) */
#define IKEV2_UPDATE_SA_ADDRESSES 16400 /* (RFC4555) */
#define IKEV2_COOKIE2 16401 /* (RFC4555) */
#define IKEV2_NO_NATS_ALLOWED 16402 /* (RFC4555) */
#define IKEV2_AUTH_LIFETIME 16403 /* (RFC4478) */
#define IKEV2_MULTIPLE_AUTH_SUPPORTED 16404 /* (RFC4739) */
#define IKEV2_ANOTHER_AUTH_FOLLOWS 16405 /* (RFC4739) */
#define IKEV2_REDIRECT_SUPPORTED 16406 /* (RFC5685) */
#define IKEV2_REDIRECT 16407 /* (RFC5685) */
#define IKEV2_REDIRECT_FROM 16408 /* (RFC5685) */
#define IKEV2_TICKET_LT_OPAQUE 16409 /* (RFC5723) */
#define IKEV2_TICKET_REQUEST 16410 /* (RFC5723) */
#define IKEV2_TICKET_ACK 16411 /* (RFC5723) */
#define IKEV2_TICKET_NACK 16412 /* (RFC5723) */
#define IKEV2_TICKET_OPAQUE 16413 /* (RFC5723) */
#define IKEV2_LINK_ID 16414 /* (draft-ietf-ipsecme-ikev2-ipv6-config-03) */
#define IKEV2_USE_WESP_MODE 16415 /* (draft-ietf-ipsecme-traffic-visibility-12.txt) */
/* RESERVED TO IANA - STATUS TYPES 16416 - 40959 */
/* Private Use - STATUS TYPES 40960 - 65535 */
/*
* 3.11 Delete Payload
*/
struct ikev2payl_delete_h {
uint8_t protocol_id;
uint8_t spi_size;
uint16_t num_spi;
} PACKED;
struct ikev2payl_delete {
struct ikev2_payload_header header;
struct ikev2payl_delete_h dh;
/* followed by Security Parameter Index(es) (SPI) */
} PACKED;
/* Protocol ID field */
#define IKEV2_DELETE_PROTO_IKE 1
#define IKEV2_DELETE_PROTO_AH 2
#define IKEV2_DELETE_PROTO_ESP 3
#define IKEV2_DELETE_PROTO_FC_ESP_HEADER 4 /* (RFC4595) */
#define IKEV2_DELETE_PROTO_FC_CT_AUTHENTICATION 5 /* (RFC4595) */
/* RESERVED TO IANA 6-200 */
/* PRIVATE USE 201-255 */
/*
* 3.12 Vendor ID Payload
*/
/* is a payload header followed by vendor ID and data */
/*
* 3.13 Traffic Selector Payload
*/
struct ikev2payl_ts_h {
uint8_t num_ts;
uint8_t reserved[3];
} PACKED;
struct ikev2payl_traffic_selector {
struct ikev2_payload_header header;
struct ikev2payl_ts_h tsh;
/* followed by Traffic Selectors */
} PACKED;
/* 3.13.1 Traffic Selector */
struct ikev2_traffic_selector {
uint8_t ts_type;
uint8_t protocol_id;
uint16_t selector_length;
uint16_t start_port;
uint16_t end_port;
/* followed by Starting Address */
/* followed by Ending Address */
} PACKED;
/* Reserved 0-6 */
#define IKEV2_TS_IPV4_ADDR_RANGE 7
#define IKEV2_TS_IPV6_ADDR_RANGE 8
#define IKEV2_TS_FC_ADDR_RANGE 9 /* (RFC4595) */
/* Reserved to IANA 10-240 */
/* Private use 241-255 */
#define IKEV2_TS_PROTO_ANY 0
#define IKEV2_TS_PORT_MIN 0
#define IKEV2_TS_PORT_MAX 65535
#define IKEV2_TS_PORT_IS_ANY(s_, e_) ((s_)==IKEV2_TS_PORT_MIN && (e_)==IKEV2_TS_PORT_MAX)
#define IKEV2_TS_PORT_IS_OPAQUE(s_, e_) ((s_)==IKEV2_TS_PORT_MAX && (e_)==IKEV2_TS_PORT_MIN)
/*
* (RFC4301)
* OPAQUE and ANY
*
* For each selector in an SPD entry, in addition to the literal
* values that define a match, there are two special values: ANY
* and OPAQUE. ANY is a wildcard that matches any value in the
* corresponding field of the packet, or that matches packets
* where that field is not present or is obscured. OPAQUE
* indicates that the corresponding selector field is not
* available for examination because it may not be present in a
* fragment, it does not exist for the given Next Layer Protocol,
* or prior application of IPsec may have encrypted the value.
* The ANY value encompasses the OPAQUE value.
*/
/*
* 3.14 Encrypted Payload
*/
/* is a payload header followed by IV and encrypted data */
/*
* 3.15 Configuration Payload
*/
struct ikev2payl_config_h {
uint8_t cfg_type;
uint8_t reserved[3];
};
struct ikev2payl_config {
struct ikev2_payload_header header;
struct ikev2payl_config_h cfgh;
/* followed by Configuration Attributes */
} PACKED;
#define IKEV2_CFG_REQUEST 1
#define IKEV2_CFG_REPLY 2
#define IKEV2_CFG_SET 3
#define IKEV2_CFG_ACK 4
/* reserved to IANA 5-127 */
/* private use 128-255 */
/* 3.15.1 Configuration Attributes */
/* this is similar to struct ikev2attrib but different enough to require separate definition */
struct ikev2cfg_attrib {
uint16_t type;
uint16_t length;
} PACKED;
#define IKEV2CFG_ATTR_RESERVED 0x8000
#define IKEV2CFG_ATTR_TYPE_MASK 0x7FFF
#define IKEV2CFG_ATTR_TYPE(a_) (get_uint16(&(a_)->type) & IKEV2CFG_ATTR_TYPE_MASK)
#define IKEV2CFG_ATTR_LENGTH(a_) (get_uint16(&(a_)->length))
#define IKEV2CFG_ATTR_TOTALLENGTH(a_) (sizeof(struct ikev2cfg_attrib) + IKEV2CFG_ATTR_LENGTH(a_))
#define IKEV2CFG_ATTR_VALUE(a_) ((uint8_t *)((struct ikev2cfg_attrib*)(a_) + 1))
#define IKEV2CFG_ATTR_NEXT(a_) ((struct ikev2cfg_attrib *)((uint8_t *)(a_) + IKEV2CFG_ATTR_TOTALLENGTH(a_)))
#define IKEV2_CFG_INTERNAL_IP4_ADDRESS 1
#define IKEV2_CFG_INTERNAL_IP4_NETMASK 2
#define IKEV2_CFG_INTERNAL_IP4_DNS 3
#define IKEV2_CFG_INTERNAL_IP4_NBNS 4
#define IKEV2_CFG_INTERNAL_ADDRESS_EXPIRY 5
#define IKEV2_CFG_INTERNAL_IP4_DHCP 6
#define IKEV2_CFG_APPLICATION_VERSION 7
#define IKEV2_CFG_INTERNAL_IP6_ADDRESS 8
/* reserved 9 */
#define IKEV2_CFG_INTERNAL_IP6_DNS 10
#define IKEV2_CFG_INTERNAL_IP6_NBNS 11
#define IKEV2_CFG_INTERNAL_IP6_DHCP 12
#define IKEV2_CFG_INTERNAL_IP4_SUBNET 13
#define IKEV2_CFG_SUPPORTED_ATTRIBUTES 14
#define IKEV2_CFG_INTERNAL_IP6_SUBNET 15
#define IKEV2_CFG_MIP6_HOME_PREFIX 16 /* (RFC5026) */
#define IKEV2_CFG_INTERNAL_IP6_LINK 17 /* (ikev2-ipv6-config-03) */
#define IKEV2_CFG_IP6_PREFIX 18 /* (ikev2-ipv6-config-03) */
/* reserved 19-16383 */
/* private use 16384-32767 */
struct ikev2cfg_ip6addr {
uint8_t addr[16];
uint8_t prefixlen;
} PACKED;
struct ikev2cfg_mip6prefix {
uint32_t prefix_lifetime;
uint8_t addr[16];
uint8_t prefixlen;
} PACKED;
/*
* 3.16 Extended Authentication Protocol (EAP) Payload
*/
/* is a payload header followed by EAP Message */
#endif /* __IKEV2_H__ */
| 31.985795 | 108 | 0.755973 | [
"transform"
] |
0883ece8e05d83bf3f3cd1b81d3c89aa48148c49 | 1,866 | h | C | edas/include/alibabacloud/edas/model/ListPublishedServicesResult.h | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-02-02T03:54:39.000Z | 2021-12-13T01:32:55.000Z | edas/include/alibabacloud/edas/model/ListPublishedServicesResult.h | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 89 | 2018-03-14T07:44:54.000Z | 2021-11-26T07:43:25.000Z | edas/include/alibabacloud/edas/model/ListPublishedServicesResult.h | aliyun/aliyun-openapi-cpp-sdk | 0cf5861ece17dfb0bb251f13bf3fbdb39c0c6e36 | [
"Apache-2.0"
] | 69 | 2018-01-22T09:45:52.000Z | 2022-03-28T07:58:38.000Z | /*
* Copyright 2009-2017 Alibaba Cloud 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 ALIBABACLOUD_EDAS_MODEL_LISTPUBLISHEDSERVICESRESULT_H_
#define ALIBABACLOUD_EDAS_MODEL_LISTPUBLISHEDSERVICESRESULT_H_
#include <string>
#include <vector>
#include <utility>
#include <alibabacloud/core/ServiceResult.h>
#include <alibabacloud/edas/EdasExport.h>
namespace AlibabaCloud
{
namespace Edas
{
namespace Model
{
class ALIBABACLOUD_EDAS_EXPORT ListPublishedServicesResult : public ServiceResult
{
public:
struct ListPublishedServices
{
std::string group2Ip;
std::string type;
std::string appId;
std::string version;
bool dockerApplication;
std::vector<std::string> groups;
std::vector<std::string> ips;
std::string name;
};
ListPublishedServicesResult();
explicit ListPublishedServicesResult(const std::string &payload);
~ListPublishedServicesResult();
std::string getMessage()const;
std::vector<ListPublishedServices> getPublishedServicesList()const;
int getCode()const;
protected:
void parse(const std::string &payload);
private:
std::string message_;
std::vector<ListPublishedServices> publishedServicesList_;
int code_;
};
}
}
}
#endif // !ALIBABACLOUD_EDAS_MODEL_LISTPUBLISHEDSERVICESRESULT_H_ | 28.272727 | 84 | 0.738478 | [
"vector",
"model"
] |
0885d53117be35e3ff4d671cc6c51e0708147c2d | 5,420 | h | C | TOPasscodeViewController/Views/Main/TOPasscodeView.h | SlaveMast3r/TOPasscodeViewController | ec7455a52b62a456b44c352451232044031a2f46 | [
"MIT"
] | 19 | 2021-04-10T02:33:37.000Z | 2022-02-08T00:40:30.000Z | TOPasscodeViewController/Views/Main/TOPasscodeView.h | SlaveMast3r/TOPasscodeViewController | ec7455a52b62a456b44c352451232044031a2f46 | [
"MIT"
] | null | null | null | TOPasscodeViewController/Views/Main/TOPasscodeView.h | SlaveMast3r/TOPasscodeViewController | ec7455a52b62a456b44c352451232044031a2f46 | [
"MIT"
] | 8 | 2021-06-18T07:54:50.000Z | 2022-02-11T03:31:48.000Z | //
// TOPasscodeView.h
//
// Copyright 2017 Timothy Oliver. All rights reserved.
//
// 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.
#import <UIKit/UIKit.h>
#import "TOPasscodeViewControllerConstants.h"
NS_ASSUME_NONNULL_BEGIN
@class TOPasscodeCircleButton;
@class TOPasscodeInputField;
@class TOPasscodeKeypadView;
@class TOPasscodeViewContentLayout;
/**
The passcode view is the primary content view for the passcode view controller.
On iPad, every view except the background view is a subview of this view.
On iPhone, the auxiliary buttons ('Touch ID', 'Cancel') are managed by the view controller.
*/
@interface TOPasscodeView : UIView
/* The visual style of the view */
@property (nonatomic, assign) TOPasscodeViewStyle style;
/* The type of passcode being managed by it */
@property (nonatomic, readonly) TOPasscodeType passcodeType;
/* Whether the content is laid out vertically or horizontally (iPhone only) */
@property (nonatomic, assign) BOOL horizontalLayout;
/* The text in the title view (Default is 'Enter Passcode') */
@property (nonatomic, copy) NSString *titleText;
/* Customizable Accessory Views */
@property (nonatomic, strong, nullable) UIView *titleView;
@property (nonatomic, strong, nullable) UIButton *leftButton;
@property (nonatomic, strong, nullable) UIButton *rightButton;
/* The default views always shown in this view */
@property (nonatomic, readonly) UILabel *titleLabel;
@property (nonatomic, readonly) TOPasscodeInputField *inputField;
@property (nonatomic, readonly) TOPasscodeKeypadView *keypadView;
/* Overrides for theming the various elements. */
@property (nonatomic, strong, nullable) UIColor *titleLabelColor;
@property (nonatomic, strong, nullable) UIColor *inputProgressViewTintColor;
@property (nonatomic, strong, nullable) UIColor *keypadButtonBackgroundColor;
@property (nonatomic, strong, nullable) UIColor *keypadButtonTextColor;
@property (nonatomic, strong, nullable) UIColor *keypadButtonHighlightedTextColor;
/* Horizontal inset from edge of keypad view to button center */
@property (nonatomic, readonly) CGFloat keypadButtonInset;
/* An animatable property for animating the non-translucent subviews */
@property (nonatomic, assign) CGFloat contentAlpha;
/* The passcode currently entered into this view */
@property (nonatomic, copy, nullable) NSString *passcode;
/* The default layout object controlling the
sizing and placement of all this view's child elements. */
@property (nonatomic, strong, null_resettable) TOPasscodeViewContentLayout *defaultContentLayout;
/* As needed, additional layout objects that will be checked and used in priority over the default content layout. */
@property (nonatomic, strong, nullable) NSArray<TOPasscodeViewContentLayout *> *contentLayouts;
/* Callback triggered each time the user taps a key */
@property (nonatomic, copy, nullable) void (^passcodeDigitEnteredHandler)(void);
/* Callback triggered when the user has finished entering the passcode */
@property (nonatomic, copy, nullable) void (^passcodeCompletedHandler)(NSString *passcode);
/*
Create a new instance with one of the style types
@param style The visual style of the passcode view.
@param type The type of passcode to accept.
*/
- (instancetype)initWithStyle:(TOPasscodeViewStyle)style passcodeType:(TOPasscodeType)type;
/*
Resize the view and all subviews for the optimum size to fit a super view of the suplied width.
@param size The size of the view to which this view.
*/
- (void)sizeToFitSize:(CGSize)size;
/*
Reset the passcode to nil and optionally play animation / vibration to match
@param animated Play a shaking animation to reset the passcode.
@param impact On supported devices, play a small reset vibration as well.
*/
- (void)resetPasscodeAnimated:(BOOL)animated playImpact:(BOOL)impact;
/*
Delete the last character from the passcode
@param animated Whether the delete operation is animated or not.
*/
- (void)deleteLastPasscodeCharacterAnimated:(BOOL)animated;
/*
Animate the transition between horizontal and vertical layouts
@param horizontalLayout Whether to lay out the content vertically or horizontally.
@param animated Whether the transition is animated or not.
@param duration The duration of the animation
*/
- (void)setHorizontalLayout:(BOOL)horizontalLayout animated:(BOOL)animated duration:(CGFloat)duration;
@end
NS_ASSUME_NONNULL_END
| 40.75188 | 117 | 0.779151 | [
"object"
] |
088b1ec013ffea9b6052d64cf1e4b2719873812f | 10,207 | h | C | src/cdi/payload.h | kierank/aws-cdi-sdk | db3becf6bb1e95b356277d1d936b2c42589d9916 | [
"BSD-2-Clause"
] | null | null | null | src/cdi/payload.h | kierank/aws-cdi-sdk | db3becf6bb1e95b356277d1d936b2c42589d9916 | [
"BSD-2-Clause"
] | null | null | null | src/cdi/payload.h | kierank/aws-cdi-sdk | db3becf6bb1e95b356277d1d936b2c42589d9916 | [
"BSD-2-Clause"
] | null | null | null | // -------------------------------------------------------------------------------------------
// Copyright Amazon.com Inc. or its affiliates. All Rights Reserved.
// This file is part of the AWS CDI-SDK, licensed under the BSD 2-Clause "Simplified" License.
// License details at: https://github.com/aws/aws-cdi-sdk/blob/mainline/LICENSE
// -------------------------------------------------------------------------------------------
/**
* @file
* @brief
* The declarations in this header file correspond to the definitions in payload.c.
*/
#ifndef CDI_PAYLOAD_H__
#define CDI_PAYLOAD_H__
#include <stdbool.h>
#include <stdint.h>
#include "private_avm.h"
#include "cdi_core_api.h"
#include "cdi_pool_api.h"
//*********************************************************************************************************************
//***************************************** START OF DEFINITIONS AND TYPES ********************************************
//*********************************************************************************************************************
/**
* @brief Enumeration used to maintain payload state.
*/
typedef enum {
kPayloadIdle = 0, ///< Payload state is not in use.
kPayloadPacketZeroPending, ///< Payload is waiting for packet 0.
kPayloadInProgress, ///< Payload is in progress.
kPayloadError, ///< Payload received an error and has not yet been sent; transition to Ignore when sent.
kPayloadIgnore, ///< Error payload has been sent and we now ignore packets for it.
kPayloadComplete, ///< Payload has completed but has not been sent; transition to Idle when sent.
} CdiPayloadState;
/**
* @brief Enumeration used to identify packet type.
*/
typedef enum {
kPayloadTypeData = 0, ///< Payload contains application payload data.
kPayloadTypeDataOffset, ///< Payload contains application payload data with data offset field in each packet.
kPayloadTypeProbe, ///< Payload contains probe data.
kPayloadTypeKeepAlive, ///< Payload is being used for keeping the connection alive (don't use app payload
/// callbacks).
} CdiPayloadType;
// --------------------------------------------------------------------
// All structures in the block below are byte packed (no byte padding).
// --------------------------------------------------------------------
#pragma pack(push, 1)
/**
* @brief CDI header for payload packets that don't use data offset values (payload type is not
* kPayloadTypeDataOffset).
*/
typedef struct {
uint8_t payload_type; ///< Payload type from CdiPayloadType.
uint16_t packet_sequence_num; ///< Packet sequence number for the payload.
uint8_t payload_num; ///< Payload number this CDI packet is associated with.
} CdiCDIPacketCommonHeader;
/**
* @brief CDI header for payload packets that contains a data offset value (payload type is kPayloadTypeDataOffset).
*/
typedef struct {
CdiCDIPacketCommonHeader hdr; ///< Header that is common to all packets that contain a CDI header.
uint32_t payload_data_offset; ///< Current offset of payload data.
} CdiCDIPacketDataOffsetHeader;
/**
* @brief CDI header for payload packet #0. This packet never uses payload_data_offset, since it is always zero.
*/
typedef struct {
CdiCDIPacketCommonHeader hdr; ///< Header that is common to all packets that contain a CDI header.
uint32_t total_payload_size; ///< Total size of payload in bytes.
uint64_t max_latency_microsecs; ///< Maximum latency payload in microseconds.
/// Origination RTP timestamp provided by transmitter that is related to the payload.
CdiPtpTimestamp origination_ptp_timestamp;
uint64_t payload_user_data; ///< User data provided by transmitter that is related to the payload.
uint16_t extra_data_size; ///< Size of additional header data in bytes. The data bytes immediately follow
///< this structure.
} CdiCDIPacketNum0Header;
/**
* @brief Union of payload cdi headers. Use to reserve memory that can be used to hold any type of CDI packet
* header.
*/
typedef struct {
union {
CdiCDIPacketNum0Header num0_hdr; ///< Header of CDI packet number 0 header.
CdiCDIPacketCommonHeader common_hdr; ///< Header of non data offset cdi packets.
CdiCDIPacketDataOffsetHeader offset_hdr; ///< Header of data offset cdi packets.
};
uint8_t extra_data[MAX_CDI_PACKET_EXTRA_DATA]; ///< Optional extra data.
} CdiCDIPacketHeaderUnion;
#pragma pack(pop)
// --------------------------------------------------------------------
// End of byte packed structures (no byte padding).
// --------------------------------------------------------------------
/**
* @brief Structure used to hold state data for a single payload.
*/
typedef struct {
CdiPayloadType payload_type; ///< Payload type (application or keep alive).
uint16_t maximum_packet_byte_size; ///< Maximum size of packets in bytes.
uint8_t maximum_tx_sgl_entries; ///< Maximum number of SGL entries for a packet.
uint8_t payload_num; ///< Payload number. Value is unique for each Tx connection and increments by 1
/// for each payload transmitted.
uint16_t packet_sequence_num; ///< Current CDI packet sequence number.
uint16_t packet_payload_data_size; ///< Size in bytes of payload data in current CDI packet.
const CdiSglEntry* source_entry_ptr; ///< Current source payload SGL entry being used.
int source_entry_address_offset; ///< Current source entry address offset of entry being used. Only used if the
/// data size of the source SGL entry is larger than the CDI packet data
/// size (the SGL entry spans more than 1 CDI packet).
uint32_t payload_data_offset; ///< Current offset of payload data.
} CdiPayloadCDIPacketState;
/// Forward reference of structure to create pointers later.
typedef struct CdiConnectionState CdiConnectionState;
/// Forward reference of structure to create pointers later.
typedef struct TxPayloadState TxPayloadState;
/// An opaque type for the packetizer to keep track of its progress in case it must be suspended for lack of resources.
typedef struct CdiPacketizerState* CdiPacketizerStateHandle;
//*********************************************************************************************************************
//******************************************* START OF PUBLIC FUNCTIONS ***********************************************
//*********************************************************************************************************************
/**
* Initialize an CdiPayloadCDIPacketState structure before using CdiPayloadGetPacket() to split the payload into
* packets. NOTE: If an error occurs, caller is responsible for freeing the pool buffers that it allocates.
*
* @param con_state_ptr ///< Pointer to connection state data.
* @param source_sgl_ptr ///< Pointer to Tx Payload source SGL list.
* @param payload_state_ptr ///< Pointer to payload state data.
*
* @return true if successful, otherwise an error occurred.
*/
bool CdiPayloadInit(CdiConnectionState* con_state_ptr, const CdiSgList* source_sgl_ptr,
TxPayloadState* payload_state_ptr);
/**
* Creates a packetizer state object. This must be destroyed with CdiPacketizerStateDestroy() when the connection is
* closed.
*
* @return Handle for the created packetizer state or NULL if the creation failed.
*/
CdiPacketizerStateHandle CdiPacketizerStateCreate();
/**
* Frees the memory previously allocated for a packetizer state object through CdiPacketizerStateCreate().
*
* @param packetizer_state_handle The handle of the packetizer state to be destroyed.
*/
void CdiPacketizerStateDestroy(CdiPacketizerStateHandle packetizer_state_handle);
/**
* Initializes a packetizer state object. This function should be called before calling CdiPayloadGetPacket() the first
* time for a given payload.
*
* @param packetizer_state_handle Handle of packetizer object.
*/
void CdiPacketizerStateInit(CdiPacketizerStateHandle packetizer_state_handle);
/// Forward reference of structure to allow pointer creation.
typedef struct TxPayloadState TxPayloadState;
/**
* Get the next packet for a payload. Must use CdiPacketizerStateInit() for a new payload before using this function. If
* false is returned, one of the pools from which required resources are taken is dry so this function should be called
* again until it returns true.
*
* NOTE: All the pools used in this function are not thread-safe, so must ensure that only one thread is accessing them
* at a time.
*
* @param packetizer_state_handle ///< Handle of the packetizer state for this connection.
* @param hdr_union_ptr ///< Pointer to the header data structure to be filled in for the new packet.
* @param packet_sgl_entry_pool_handle ///< CDI packet SGL list entry pool.
* @param payload_state_ptr ///< Pointer to payload state data.
* @param packet_sgl_ptr ///< Pointer to returned packet SGL list
* @param ret_is_last_packet_ptr ///< Pointer to returned last packet state. True if last packet, otherwise false.
*
* @return true if packet returned, otherwise a pool was empty so false is returned.
*/
bool CdiPayloadGetPacket(CdiPacketizerStateHandle packetizer_state_handle, CdiCDIPacketHeaderUnion *hdr_union_ptr,
CdiPoolHandle packet_sgl_entry_pool_handle, TxPayloadState* payload_state_ptr,
CdiSgList* packet_sgl_ptr, bool* ret_is_last_packet_ptr);
/**
* Return the CDI common header of a CDI packet #0.
*
* @param packet_sgl_ptr Pointer to CDI packet SGL list.
*
* @return CdiCDIPacketCommonHeader* Pointer to CDI packet common header. If NULL, then an error occurred.
*/
CdiCDIPacketCommonHeader* CdiPayloadParseCDIPacket(const CdiSgList* packet_sgl_ptr);
#endif // CDI_PAYLOAD_H__
| 48.604762 | 120 | 0.639169 | [
"object"
] |
0892fb89081c66810c345adc01a1fb172b5fec42 | 45,706 | h | C | src/intensity/script_engine_embedding.h | kripken/intensityengine | 9ae352b4f526ecb180004ae4968db7f64f140762 | [
"MIT"
] | 31 | 2015-01-18T20:27:31.000Z | 2021-07-03T03:58:47.000Z | src/intensity/script_engine_embedding.h | JamesLinus/intensityengine | 9ae352b4f526ecb180004ae4968db7f64f140762 | [
"MIT"
] | 4 | 2015-07-05T21:09:37.000Z | 2019-09-06T14:34:59.000Z | src/intensity/script_engine_embedding.h | JamesLinus/intensityengine | 9ae352b4f526ecb180004ae4968db7f64f140762 | [
"MIT"
] | 11 | 2015-02-03T19:24:10.000Z | 2019-09-20T10:59:50.000Z |
/*
*=============================================================================
* Copyright (C) 2008 Alon Zakai ('Kripken') kripkensteiner@gmail.com
*
* This file is part of the Intensity Engine project,
* http://www.intensityengine.com
*
* The Intensity Engine is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* The Intensity Engine 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with the Intensity Engine. If not, see
* http://www.gnu.org/licenses/
* http://www.gnu.org/licenses/agpl-3.0.html
*=============================================================================
*/
#include <cmath>
#ifndef WIN32
#define ISNAN(x) std::isnan(x)
#else
#define ISNAN(x) _isnan(x)
#endif
#ifdef CLIENT
#include "client_engine_additions.h"
#include "intensity_gui.h"
#include "intensity_texture.h"
#endif
#ifdef SERVER
#include "NPC.h"
#endif
#include "intensity_physics.h"
#define MAKE_VECTOR3(scriptvec, sauervec) \
scriptvec = ScriptEngineManager::getGlobal()->call("__new__", \
ScriptValueArgs().append(ScriptEngineManager::getGlobal()->getProperty("Vector3")) \
.append(sauervec.x) \
.append(sauervec.y) \
.append(sauervec.z) \
); \
#define RETURN_VECTOR3(sauervec) \
ScriptValuePtr __ret; \
MAKE_VECTOR3(__ret, sauervec) \
V8_RETURN_VALUE(__ret);
//! "CubeScript 'sudo'": lets you change map vars etc. from script API calls,
//! as if you were running this script during the map script loading.
//! Note that we save the old value - as we may actually be during map load
//! now.
#define CSSUDO(script) \
{ \
bool old = overrideidents; \
overrideidents = true; \
execute(script); \
overrideidents = old; \
}
// Worldsystem
extern void removeentity(extentity* entity);
extern void addentity(extentity* entity);
// Embedded functions. We do the wrapping in this way, so it is fast (no
// unnecessary runtime conversions). This is still quite abstracted,
// however, and easy to switch to another engine from.
// XXX XXX XXX This file contains embedded functions, i.e., the interface
// between trusted and untrusted code. It must be thoroughly and often
// audited for security, as well as functions it calls! XXX XXX XXX
// Logging - NOTE: This is not in the *_impl.h file, we do it manually.
// That is because logging is done before anything else - it is important
// during initialization
V8_FUNC_is(__script__log, { Logging::log_noformat(arg1, arg2); } );
//
// Normal CAPI
//
// General
V8_FUNC_NOPARAM(__script__currTime, { V8_RETURN_DOUBLE( Utility::SystemInfo::currTime() ); });
// Entity attribs
V8_FUNC_T(__script__setAnimation, i, { self.get()->setAnimation(arg2); } );
V8_FUNC_T(__script__getStartTime, , {
V8_RETURN_INT( self.get()->getStartTime() );
});
V8_FUNC_T(__script__setModelName, s, {
Logging::log(Logging::DEBUG, "__script__setModelName(%s)\r\n", arg2);
self.get()->setModel(arg2);
} );
V8_FUNC_T(__script__setAttachments_raw, s, { self.get()->setAttachments(arg2); } );
V8_FUNC_T(__script__getAttachmentPosition, s, {
vec& vposition = self->getAttachmentPosition(arg2);
RETURN_VECTOR3(vposition);
});
V8_FUNC_T(__script__setCanMove, i, { self.get()->setCanMove(arg2); } );
// Entity management
//V8_FUNC_i(__script__registerLogicEntityNonSauer, { LogicSystem::registerLogicEntityNonSauer(arg1); } ); DEPRECATED
V8_FUNC_i(__script__unregisterLogicEntity, { LogicSystem::unregisterLogicEntityByUniqueId(arg1); } );
V8_FUNC_ii(__script__placeInWorld, { WorldSystem::placeInWorld(arg1, arg2); } );
V8_FUNC_Z(__script__setupExtent, idddiiii, { LogicSystem::setupExtent(self, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9); } );
V8_FUNC_Z(__script__setupCharacter, , { LogicSystem::setupCharacter(self); } );
V8_FUNC_Z(__script__setupNonSauer, , { LogicSystem::setupNonSauer(self); } );
V8_FUNC_Z(__script__dismantleExtent, , { LogicSystem::dismantleExtent(self); } );
V8_FUNC_Z(__script__dismantleCharacter, , { LogicSystem::dismantleCharacter(self); } );
// Sounds
#ifdef CLIENT
V8_FUNC_sdddi(__script_playSoundByName, {
vec loc(arg2, arg3, arg4);
if (loc.x || loc.y || loc.z)
playsoundname(arg1, &loc, arg5);
else
playsoundname(arg1);
});
#endif
#ifdef CLIENT
V8_FUNC_s(__script__music, {
assert( Utility::validateAlphaNumeric(arg1, "._/") );
std::string command = "music \"";
command += arg1;
command += "\" [ run_script \"Sound.musicCallback()\" ]";
CSSUDO(command.c_str());
});
#else
V8_FUNC_s(__script__music, {
arg1 = arg1; // warning otherwise
});
#endif
VAR(tempNewSound, 0, 0, 65535);
#ifdef CLIENT
extern int preload_sound(char *name, int vol);
V8_FUNC_si(__script__preloadSound, {
std::string str = "preloading sound '";
str += arg1;
str += "'...";
renderprogress(0, str.c_str());
arg2 = min(arg2, 100); // Do not let scripts set high volumes for griefing
V8_RETURN_INT(preload_sound((char*)arg1, arg2));
});
#else
V8_FUNC_si(__script__preloadSound, {
arg1 = arg1; arg2 = arg2; // warning otherwise
});
#endif
#ifdef CLIENT
V8_FUNC_i(__script__playSound, {
playsound(arg1); // TODO: Sound position
});
#else
V8_FUNC_i(__script__playSound, {
MessageSystem::send_SoundToClients(
-1,
arg1,
-1
);
});
#endif
// Extents
#define EXTENT_ACCESSORS(getterName, setterName, attribName) \
V8_FUNC_T(__script__##getterName, , { \
extentity* e = self.get()->staticEntity; \
assert(e); \
V8_RETURN_INT(e->attribName); \
}); \
\
V8_FUNC_T(__script__##setterName, i, { \
extentity* e = self.get()->staticEntity; \
assert(e); \
if (!WorldSystem::loadingWorld) removeentity(e); /* Need to remove, then add, to the world on each change, if not during load. */ \
e->attribName = arg2; \
if (!WorldSystem::loadingWorld) addentity(e); \
}); \
\
V8_FUNC_T(__script__FAST_##setterName, i, { /* Fast version - no removeentity/addentity. Use with care! */ \
extentity* e = self.get()->staticEntity; \
assert(e); \
e->attribName = arg2; \
});
EXTENT_ACCESSORS(getAttr1, setAttr1, attr1);
EXTENT_ACCESSORS(getAttr2, setAttr2, attr2);
EXTENT_ACCESSORS(getAttr3, setAttr3, attr3);
EXTENT_ACCESSORS(getAttr4, setAttr4, attr4);
#define EXTENT_LE_ACCESSORS(getterName, setterName, attribName) \
V8_FUNC_T(__script__##getterName, , { \
V8_RETURN_DOUBLE(self->attribName); \
}); \
\
V8_FUNC_T(__script__##setterName, d, { \
Logging::log(Logging::DEBUG, "ACCESSOR: Setting %s to %d\r\n", #setterName, arg2); \
assert(self->staticEntity); \
if (!WorldSystem::loadingWorld) removeentity(self->staticEntity); /* Need to remove, then add, to the octa world on each change. */ \
self->attribName = arg2; \
if (!WorldSystem::loadingWorld) addentity(self->staticEntity); \
});
EXTENT_LE_ACCESSORS(getCollisionRadiusWidth, setCollisionRadiusWidth, collisionRadiusWidth);
EXTENT_LE_ACCESSORS(getCollisionRadiusHeight, setCollisionRadiusHeight, collisionRadiusHeight);
//Add 'FAST' versions of accessors - no addeneity/removeentity. Good to change e.g. particle parameters
V8_FUNC_T(__script__getExtentO_raw, i, {
extentity* e = self.get()->staticEntity;
assert(e);
assert(arg2 >= 0 && arg2 <= 2);
Logging::log(Logging::INFO, "__script__getExtentO_raw(%d): %f\r\n", arg2, e->o[arg2]);
V8_RETURN_DOUBLE(e->o[arg2]);
});
V8_FUNC_T(__script__setExtentO_raw, ddd, {
extentity* e = self.get()->staticEntity;
assert(e);
removeentity(e); /* Need to remove, then add, to the octa world on each change. */
e->o.x = arg2;
e->o.y = arg3;
e->o.z = arg4;
addentity(e);
});
// Dynents
#define DYNENT_ACCESSORS(getterName, setterName, type_code, type_BOLD, attribName) \
V8_FUNC_T(__script__##getterName, , { \
fpsent* e = (fpsent*)(self.get()->dynamicEntity); \
assert(e); \
V8_RETURN_##type_BOLD(e->attribName); \
}); \
\
V8_FUNC_T(__script__##setterName, type_code, { \
fpsent* e = dynamic_cast<fpsent*>(self.get()->dynamicEntity); \
assert(e); \
e->attribName = arg2; \
});
DYNENT_ACCESSORS(getMaxSpeed, setMaxSpeed, d, DOUBLE, maxspeed);
DYNENT_ACCESSORS(getRadius, setRadius, d, DOUBLE, radius);
DYNENT_ACCESSORS(getEyeHeight, setEyeHeight, d, DOUBLE, eyeheight);
DYNENT_ACCESSORS(getAboveeye, setAboveeye, d, DOUBLE, aboveeye);
DYNENT_ACCESSORS(getYaw, setYaw, d, DOUBLE, yaw);
DYNENT_ACCESSORS(getPitch, setPitch, d, DOUBLE, pitch);
DYNENT_ACCESSORS(getMove, setMove, i, INT, move);
DYNENT_ACCESSORS(getStrafe, setStrafe, i, INT, strafe);
DYNENT_ACCESSORS(getYawing, setYawing, i, INT, turn_move);
DYNENT_ACCESSORS(getPitching, setPitching, i, INT, look_updown_move);
DYNENT_ACCESSORS(getJumping, setJumping, b, BOOL, jumping);
DYNENT_ACCESSORS(getBlocked, setBlocked, b, BOOL, blocked);
DYNENT_ACCESSORS(getMapDefinedPositionData, setMapDefinedPositionData, i, INT, mapDefinedPositionData); // XXX Should be unsigned
DYNENT_ACCESSORS(getClientState, setClientState, i, INT, state);
DYNENT_ACCESSORS(getPhysicalState, setPhysicalState, i, INT, physstate);
DYNENT_ACCESSORS(getInWater, setInWater, i, INT, inwater);
DYNENT_ACCESSORS(getTimeInAir, setTimeInAir, i, INT, timeinair);
// For dynents, 'o' is at their head, not their feet like static entities. We make this uniform by
// letting scripting specify a feet position, and we work relative to their height - add to
// assignments, subtract from readings
V8_FUNC_T(__script__getDynentO_raw, i, {
fpsent* d = dynamic_cast<fpsent*>(self.get()->dynamicEntity);
assert(d);
assert(arg2 >= 0 && arg2 <= 2);
if (arg2 != 2) {
V8_RETURN_DOUBLE(d->o[arg2]);
} else {
V8_RETURN_DOUBLE(d->o.z - d->eyeheight);// - d->aboveeye);
}
});
V8_FUNC_T(__script__setDynentO_raw, ddd, {
fpsent* d = dynamic_cast<fpsent*>(self.get()->dynamicEntity);
assert(d);
d->o.x = arg2;
d->o.y = arg3;
d->o.z = arg4 + d->eyeheight;// + d->aboveeye;
// Also set 'newpos', otherwise this change may get overwritten
d->newpos = d->o;
d->resetinterp(); // No need to interpolate to last position - just jump
Logging::log(Logging::INFO, "(%d).setDynentO(%f, %f, %f)\r\n", d->uniqueId, d->o.x, d->o.y, d->o.z);
});
V8_FUNC_T(__script__getDynentVel_raw, i, {
fpsent* d = (fpsent*)(self.get()->dynamicEntity);
assert(d);
assert(arg2 >= 0 && arg2 <= 2);
V8_RETURN_DOUBLE(d->vel[arg2]);
});
V8_FUNC_T(__script__setDynentVel_raw, ddd, {
fpsent* d = dynamic_cast<fpsent*>(self.get()->dynamicEntity);
assert(d);
d->vel.x = arg2;
d->vel.y = arg3;
d->vel.z = arg4;
});
V8_FUNC_T(__script__getDynentFalling_raw, i, {
fpsent* d = (fpsent*)(self.get()->dynamicEntity);
assert(d);
assert(arg2 >= 0 && arg2 <= 2);
V8_RETURN_DOUBLE(d->falling[arg2]);
});
V8_FUNC_T(__script__setDynentFalling_raw, ddd, {
fpsent* d = dynamic_cast<fpsent*>(self.get()->dynamicEntity);
assert(d);
d->falling.x = arg2;
d->falling.y = arg3;
d->falling.z = arg4;
});
// Geometry utilities
V8_FUNC_dddddd(__script__rayLos, {
vec a(arg1, arg2, arg3);
vec b(arg4, arg5, arg6);
vec target;
bool ret = raycubelos(a, b, target);
V8_RETURN_BOOL(ret);
});
V8_FUNC_ddddddd(__script__rayPos, {
vec o(arg1, arg2, arg3);
vec ray(arg4, arg5, arg6);
vec hitpos(0);
V8_RETURN_DOUBLE(raycubepos(o, ray, hitpos, arg7, RAY_CLIPMAT|RAY_POLY));
});
V8_FUNC_dddd(__script__rayFloor, {
vec o(arg1, arg2, arg3);
vec floor(0);
V8_RETURN_DOUBLE(rayfloor(o, floor, 0, arg4));
});
// Effects
#ifdef CLIENT
V8_FUNC_idddddddiiii(__script__addDecal, {
vec center(arg2, arg3, arg4);
vec surface(arg5, arg6, arg7);
bvec color(arg9, arg10, arg11);
adddecal(arg1, center, surface, arg8, color, arg12);
});
VARP(blood, 0, 1, 1);
V8_FUNC_iiidddidii(__script__particleSplash, {
if (arg1 == PART_BLOOD && !blood) V8_RETURN_NULL;
vec p(arg4, arg5, arg6);
particle_splash(arg1, arg2, arg3, p, arg7, arg8, arg9, arg10);
});
V8_FUNC_ddddiiid(__script__particleFireball, {
vec dest(arg1, arg2, arg3);
particle_fireball(dest, arg4, arg5, arg6, arg7, arg8);
});
V8_FUNC_ddddddiiid(__script__particleFlare, {
vec p(arg1, arg2, arg3);
vec dest(arg4, arg5, arg6);
particle_flare(p, dest, arg7, arg8, arg9, arg10);
});
V8_FUNC_iiddddddidi(__script__particleTrail, {
vec from(arg3, arg4, arg5);
vec to(arg6, arg7, arg8);
particle_trail(arg1, arg2, from, to, arg9, arg10, arg11);
});
extern void regularflame(int type, const vec &p, float radius, float height, int color, int density = 3, float scale = 2.0f, float speed = 200.0f, float fade = 600.0f, int gravity = -15);
V8_FUNC_idddddiidddi(__script__particleFlame, {
regularflame(arg1, vec(arg2, arg3, arg4), arg5, arg6, arg7, arg8, arg9, arg10, arg11, arg12);
});
V8_FUNC_dddddddiiidddd(__script__addDynlight, {
vec o(arg1, arg2, arg3);
vec color(float(arg5)/255.0, float(arg6)/255.0, float(arg7)/255.0);
vec initcolor(float(arg12)/255.0, float(arg13)/255.0, float(arg14)/255.0);
LightControl::queueDynamicLight(o, arg4, color, arg8, arg9, arg10, arg11, initcolor, NULL);
});
V8_FUNC_idddidddi(__script__spawnDebris, {
vec v(arg2, arg3, arg4);
vec debrisvel(arg6, arg7, arg8);
LogicEntityPtr owner = LogicSystem::getLogicEntity(arg9);
assert(owner->dynamicEntity);
FPSClientInterface::spawnDebris(arg1, v, arg5, debrisvel, (dynent*)(owner->dynamicEntity));
});
V8_FUNC_ddddii(__script__particleMeter, {
vec s(arg1, arg2, arg3);
particle_meter(s, arg4, arg5, arg6);
});
V8_FUNC_dddsiiidi(__script__particleText, {
vec s(arg1, arg2, arg3);
std::string safeString = std::string("@") + arg4; // Make sauer copy this, as it will not persist
particle_text(s, safeString.c_str(), arg5, arg6, arg7, arg8, arg9);
});
V8_FUNC_ii(__script__clientDamageEffect, {
dynamic_cast<fpsent*>(player)->damageroll(arg1);
damageblend(arg2);
});
V8_FUNC_ddddi(__script__showHUDRect, { ClientSystem::addHUDRect(arg1, arg2, arg3, arg4, arg5); });
V8_FUNC_sdddd(__script__showHUDImage, { ClientSystem::addHUDImage(arg1, arg2, arg3, arg4, arg5); });
V8_FUNC_sdddi(__script__showHUDText, {
// text, x, y, scale, color
ClientSystem::addHUDText(arg1, arg2, arg3, arg4, arg5);
});
#endif // CLIENT
// Messages
using namespace MessageSystem;
V8_FUNC_iiss(__script__PersonalServerMessage, { send_PersonalServerMessage(arg1, arg2, arg3, arg4); });
V8_FUNC_iiiiddd(__script__ParticleSplashToClients, { send_ParticleSplashToClients(arg1, arg2, arg3, arg4, arg5, arg6, arg7); });
V8_FUNC_idddsi(__script__SoundToClientsByName, { send_SoundToClientsByName(arg1, arg2, arg3, arg4, arg5, arg6); });
V8_FUNC_iis(__script__StateDataChangeRequest, { send_StateDataChangeRequest(arg1, arg2, arg3); });
V8_FUNC_iis(__script__UnreliableStateDataChangeRequest, { send_UnreliableStateDataChangeRequest(arg1, arg2, arg3); });
V8_FUNC_ii(__script__NotifyNumEntities, { send_NotifyNumEntities(arg1, arg2); });
V8_FUNC_iiiss(__script__LogicEntityCompleteNotification, { send_LogicEntityCompleteNotification(arg1, arg2, arg3, arg4, arg5); });
V8_FUNC_ii(__script__LogicEntityRemoval, { send_LogicEntityRemoval(arg1, arg2); });
V8_FUNC_iiisi(__script__StateDataUpdate, { send_StateDataUpdate(arg1, arg2, arg3, arg4, arg5); });
V8_FUNC_iiisi(__script__UnreliableStateDataUpdate, { send_UnreliableStateDataUpdate(arg1, arg2, arg3, arg4, arg5); });
V8_FUNC_iidddi(__script__DoClick, { send_DoClick(arg1, arg2, arg3, arg4, arg5, arg6); });
V8_FUNC_iissdddiiii(__script__ExtentCompleteNotification, { send_ExtentCompleteNotification(arg1, arg2, arg3,arg4, arg5, arg6, arg7, arg8, arg9, arg10, arg11); });
// TODO
// Projectiles
/*
// Consider doing this entirely in Scripting. Need a way to do position updates in scripting, i.e.,
// to supress the normal updates for an entity.
void shootv_helper(int gun, float ox, float oy, float oz, float dx, float dy, float dz, python::object onHit, int addr)
{
vec origin(ox, oy, oz), destination(dx, dy, dz);
// The following is the algorithm from weapon.h, or close to it. The idea is that, since world geometry doesn't change,
// we can calculate IN ADVANCE whether the proejctile will hit the world. This is fine, but is *wrong* for dynamic
// per-frame mapmodels. So perhaps TODO work out a fix for that.
vec unitv;
float dist = destination.dist(origin, unitv);
unitv.div(dist);
float barrier = raycube(origin, unitv, dist, RAY_CLIPMAT|RAY_ALPHAPOLY);
if(barrier < dist)
{
destination = unitv;
destination.mul(barrier);
destination.add(origin);
}
#ifdef CLIENT // from to
FPSClientInterface::shootV(gun, origin, destination, (dynent*)addr, false, onHit);
#else // SERVER
FPSClientInterface::shootV(gun, origin, destination, (dynent*)addr, true, onHit);
#endif
}
*/
// File access
V8_FUNC_s(__script__readFile, {
try
{
REFLECT_PYTHON( read_file_safely );
boost::python::object data = read_file_safely(arg1);
std::string text = boost::python::extract<std::string>(data);
V8_RETURN_STRING( text.c_str() );
}
catch(boost::python::error_already_set const &)
{
printf("Error in Python execution of embedded read_file_safely\r\n");
PyErr_Print();
assert(0 && "Halting on Python error");
}
});
// Mapping
extern void texturereset(int *n);
V8_FUNC_NOPARAM(__script__textureReset, {
int num = 0;
texturereset(&num);
});
extern void texture(char *type, char *name, int *rot, int *xoffset, int *yoffset, float *scale, int *forcedindex);
V8_FUNC_ssiiidi(__script__texture, {
float arg6f = arg6;
// XXX: arg7 may not be given, in which case it is undefined, and turns into 0.
texture((char*)arg1, (char*)arg2, &arg3, &arg4, &arg5, &arg6f, &arg7);
});
extern void mapmodelreset();
V8_FUNC_NOPARAM(__script__mapmodelReset, {
mapmodelreset();
});
extern void mmodel(char *name);
V8_FUNC_s(__script__mapmodel, {
mmodel((char*)arg1);
});
extern void autograss(char *name);
V8_FUNC_s(__script__autograss, {
autograss((char*)arg1);
});
extern void texlayer(int *layer, char *name, int *mode, float *scale);
#ifdef CLIENT
V8_FUNC_i(__script__texLayer, {
int dummy1 = 0;
float dummy2 = 0;
texlayer(&arg1, (char*)"", &dummy1, &dummy2);
});
#else
V8_FUNC_i(__script__texLayer, {
arg1 = arg1; // warning otherwise
});
#endif
#ifdef CLIENT
V8_FUNC_s(__script__setShader, {
std::string command = "setshader ";
command += arg1;
assert( Utility::validateAlphaNumeric(arg1) );
CSSUDO(command.c_str());
});
#else
V8_FUNC_s(__script__setShader, {
arg1 = arg1; // warning otherwise
});
#endif
#ifdef CLIENT
V8_FUNC_sdddd(__script__setShaderParam, {
std::string command = "setshaderparam ";
command += arg1;
assert( Utility::validateAlphaNumeric(arg1) );
command += " " + Utility::toString((float)arg2);
command += " " + Utility::toString((float)arg3);
command += " " + Utility::toString((float)arg4);
command += " " + Utility::toString((float)arg5);
CSSUDO(command.c_str());
});
#else
V8_FUNC_sdddd(__script__setShaderParam, {
arg1 = arg1; // warning otherwise
arg2 = arg2; // warning otherwise
arg3 = arg3; // warning otherwise
arg4 = arg4; // warning otherwise
arg5 = arg5; // warning otherwise
});
#endif
extern void materialreset();
V8_FUNC_NOPARAM(__script__materialReset, {
materialreset();
});
#ifdef CLIENT
V8_FUNC_s(__script__loadSky, {
std::string command = "loadsky ";
command += arg1;
assert( Utility::validateAlphaNumeric(arg1, "/_<>:.,") );
CSSUDO(command.c_str());
});
#else
V8_FUNC_s(__script__loadSky, {
arg1 = arg1; // warning otherwise
});
#endif
#ifdef CLIENT
V8_FUNC_s(__script__fogColor, {
std::string command = "fogcolour ";
command += arg1;
assert( Utility::validateAlphaNumeric(arg1) );
CSSUDO(command.c_str());
});
#else
V8_FUNC_s(__script__fogColor, {
arg1 = arg1; // warning otherwise
});
#endif
#ifdef CLIENT
V8_FUNC_i(__script__fog, {
std::string command = "fog ";
command += Utility::toString(arg1);
CSSUDO(command.c_str());
});
#else
V8_FUNC_i(__script__fog, {
arg1 = arg1; // warning otherwise
});
#endif
#ifdef CLIENT
V8_FUNC_i(__script__waterFog, {
std::string command = "waterfog ";
command += Utility::toString(arg1);
CSSUDO(command.c_str());
});
#else
V8_FUNC_i(__script__waterFog, {
arg1 = arg1; // warning otherwise
});
#endif
#ifdef CLIENT
V8_FUNC_iii(__script__waterColor, {
std::string command = "watercolour ";
command += Utility::toString(arg1) + " ";
command += Utility::toString(arg2) + " ";
command += Utility::toString(arg3) + " ";
CSSUDO(command.c_str());
});
#else
V8_FUNC_iii(__script__waterColor, {
arg1 = arg1; arg2 = arg2; arg3 = arg3; // warning otherwise
});
#endif
#ifdef CLIENT
V8_FUNC_d(__script__spinSky, {
std::string command = "spinsky ";
command += Utility::toString(arg1);
CSSUDO(command.c_str());
});
#else
V8_FUNC_d(__script__spinSky, {
arg1 = arg1; // warning otherwise
});
#endif
#ifdef CLIENT
V8_FUNC_s(__script__cloudLayer, {
std::string command = "cloudlayer ";
assert(Utility::validateRelativePath(arg1));
command += Utility::toString(arg1);
CSSUDO(command.c_str());
});
#else
V8_FUNC_s(__script__cloudLayer, {
arg1 = arg1; // warning otherwise
});
#endif
#ifdef CLIENT
V8_FUNC_d(__script__cloudScrollX, {
std::string command = "cloudscrollx ";
command += Utility::toString(arg1);
CSSUDO(command.c_str());
});
#else
V8_FUNC_d(__script__cloudScrollX, {
arg1 = arg1; // warning otherwise
});
#endif
#ifdef CLIENT
V8_FUNC_d(__script__cloudScrollY, {
std::string command = "cloudscrolly ";
command += Utility::toString(arg1);
CSSUDO(command.c_str());
});
#else
V8_FUNC_d(__script__cloudScrollY, {
arg1 = arg1; // warning otherwise
});
#endif
#ifdef CLIENT
V8_FUNC_d(__script__cloudScale, {
std::string command = "cloudscale ";
command += Utility::toString(arg1);
CSSUDO(command.c_str());
});
#else
V8_FUNC_d(__script__cloudScale, {
arg1 = arg1; // warning otherwise
});
#endif
#ifdef CLIENT
V8_FUNC_i(__script__skyTexture, {
std::string command = "skytexture ";
command += Utility::toString(arg1);
CSSUDO(command.c_str());
});
#else
V8_FUNC_i(__script__skyTexture, {
arg1 = arg1; // warning otherwise
});
#endif
#ifdef CLIENT
V8_FUNC_dd(__script__texScroll, {
std::string command = "texscroll ";
command += Utility::toString(arg1) + " ";
command += Utility::toString(arg2);
CSSUDO(command.c_str());
});
#else
V8_FUNC_dd(__script__texScroll, {
arg1 = arg1; arg2 = arg2; // warning otherwise
});
#endif
#ifdef CLIENT
V8_FUNC_i(__script__shadowmapAngle, {
std::string command = "shadowmapangle ";
command += Utility::toString(arg1);
CSSUDO(command.c_str());
});
#else
V8_FUNC_i(__script__shadowmapAngle, {
arg1 = arg1; // warning otherwise
});
#endif
#ifdef CLIENT
V8_FUNC_s(__script__shadowmapAmbient, {
assert( Utility::validateAlphaNumeric(arg1, "x") ); // Allow e.g. 0xFFA033
std::string command = "shadowmapambient ";
command += arg1;
CSSUDO(command.c_str());
});
#else
V8_FUNC_s(__script__shadowmapAmbient, {
arg1 = arg1; // warning otherwise
});
#endif
#ifdef CLIENT
V8_FUNC_iii(__script__skylight, {
std::string command = "skylight ";
command += Utility::toString(arg1) + " " + Utility::toString(arg2) + " " + Utility::toString(arg3);
CSSUDO(command.c_str());
});
#else
V8_FUNC_iii(__script__skylight, {
arg1 = arg1; // warning otherwise
arg2 = arg2; // warning otherwise
arg3 = arg3; // warning otherwise
});
#endif
#ifdef CLIENT
V8_FUNC_i(__script__blurSkylight, {
std::string command = "blurskylight ";
command += Utility::toString(arg1);
CSSUDO(command.c_str());
});
#else
V8_FUNC_i(__script__blurSkylight, {
arg1 = arg1; // warning otherwise
});
#endif
#ifdef CLIENT
V8_FUNC_i(__script__ambient, {
std::string command = "ambient ";
command += Utility::toString(arg1);
CSSUDO(command.c_str());
});
#else
V8_FUNC_i(__script__ambient, {
arg1 = arg1; // warning otherwise
});
#endif
V8_FUNC_s(__script__preloadModel, { preloadmodel(arg1); });
V8_FUNC_s(__script__reloadModel, {
extern void clearmodel(char *name);
clearmodel((char*)arg1);
try
{
loadmodel((char*)arg1);
} catch (ScriptException& error)
{
ScriptValuePtr ret = ScriptEngineManager::createScriptObject();
ret->setProperty("error", error.text);
V8_RETURN_VALUE(ret);
}
});
#ifdef USE_JPEG2000
#ifdef CLIENT
V8_FUNC_ss(__script__convertJP2toPNG, {
assert(Utility::validateRelativePath(arg1));
assert(Utility::validateRelativePath(arg2));
IntensityTexture::convertJP2toPNG(arg1, arg2);
});
#else
V8_FUNC_ss(__script__convertJP2toPNG, {
arg1 = arg1; arg2 = arg2; // warning otherwise
});
#endif
#endif
#ifdef CLIENT
V8_FUNC_ss(__script__convertPNGtoDDS, {
assert(Utility::validateRelativePath(arg1));
assert(Utility::validateRelativePath(arg2));
IntensityTexture::convertPNGtoDDS(arg1, arg2);
});
#else
V8_FUNC_ss(__script__convertPNGtoDDS, {
arg1 = arg1; arg2 = arg2; // warning otherwise
});
#endif
#ifdef CLIENT
V8_FUNC_sss(__script__combineImages, {
assert(Utility::validateRelativePath(arg1));
assert(Utility::validateRelativePath(arg2));
assert(Utility::validateRelativePath(arg3));
IntensityTexture::combineImages(arg1, arg2, arg3);
});
#else
V8_FUNC_sss(__script__combineImages, {
arg1 = arg1; arg2 = arg2; arg3 = arg3; // warning otherwise
});
#endif
// HUD
#ifdef CLIENT
V8_FUNC_NOPARAM(__script__getTargetPosition, {
TargetingControl::determineMouseTarget(true); // Force a determination, if needed
RETURN_VECTOR3(TargetingControl::targetPosition);
});
V8_FUNC_NOPARAM(__script__getTargetEntity, {
TargetingControl::determineMouseTarget(true); // Force a determination, if needed
if (TargetingControl::targetLogicEntity.get() && !TargetingControl::targetLogicEntity->isNone())
{
V8_RETURN_VALUE(TargetingControl::targetLogicEntity->scriptEntity);
} else {
V8_RETURN_NULL;
}
});
#endif
// World
V8_FUNC_ddddi(__script__isColliding, {
vec position(arg1, arg2, arg3);
V8_RETURN_BOOL( PhysicsManager::getEngine()->isColliding(
position,
arg4,
arg5 != -1 ? LogicSystem::getLogicEntity(arg5).get() : NULL)
); // TODO: Make faster, avoid this lookup
});
V8_FUNC_d(__script__setGravity, {
if (PhysicsManager::hasEngine())
{
PhysicsManager::getEngine()->setGravity(arg1);
} else {
Logging::log(Logging::DEBUG, "Setting gravity using sauer system, as no physics engine\r\n");
extern float GRAVITY;
GRAVITY = arg1;
}
});
V8_FUNC_ddd(__script__getMaterial, {
V8_RETURN_INT(lookupmaterial(vec(arg1, arg2, arg3)));
});
// NPCs/bots
#ifdef SERVER
V8_FUNC_s(__script__addNPC, {
ScriptValuePtr ret = NPC::add(arg1);
V8_RETURN_VALUE(ret);
});
V8_FUNC_T(__script__removeNPC, , {
fpsent* fpsEntity = (fpsent*)self->dynamicEntity;
NPC::remove(fpsEntity->clientnum);
});
#endif
// Rendering
#ifdef CLIENT
VARP(ragdoll, 0, 1, 1);
static int oldThirdperson = -1;
void prepareRagdoll(int& anim, LogicEntityPtr self)
{
if (anim&ANIM_RAGDOLL)
{
// if (!ragdoll || loadmodel(mdl);
fpsent* fpsEntity = (fpsent*)self->dynamicEntity;
if (fpsEntity->clientnum == ClientSystem::playerNumber)
{
if (oldThirdperson == -1 && thirdperson == 0)
{
oldThirdperson = thirdperson;
thirdperson = 1;
}
}
if (fpsEntity->ragdoll || !ragdoll || !PhysicsManager::getEngine()->prepareRagdoll(self))
{
anim &= ~ANIM_RAGDOLL;
self->scriptEntity->call("setLocalAnimation", anim); // Set new animation locally - in state data and C++
}
} else {
if (self->dynamicEntity)
{
fpsent* fpsEntity = (fpsent*)self->dynamicEntity;
if (fpsEntity->clientnum == ClientSystem::playerNumber && oldThirdperson != -1)
{
thirdperson = oldThirdperson;
oldThirdperson = -1;
}
}
}
}
fpsent* getProxyFpsEntity(LogicEntityPtr self)
{
if (self->scriptEntity->hasProperty("renderingHashHint"))
{
static bool initialized = false;
static fpsent* fpsEntitiesForRendering[1024];
if (!initialized)
{
for (int i = 0; i < 1024; i++)
fpsEntitiesForRendering[i] = new fpsent;
initialized = true;
}
int renderingHashHint = self->scriptEntity->getPropertyInt("renderingHashHint");
renderingHashHint = renderingHashHint & 1023;
assert(renderingHashHint >= 0 && renderingHashHint < 1024);
return fpsEntitiesForRendering[renderingHashHint];
} else
return NULL;
}
#define PREP_RENDER_MODEL \
int anim = arg3; \
prepareRagdoll(anim, self); \
vec o(arg4, arg5, arg6); \
fpsent *fpsEntity = NULL; \
if (self->dynamicEntity) \
fpsEntity = dynamic_cast<fpsent*>(self->dynamicEntity); \
else \
fpsEntity = getProxyFpsEntity(self);
V8_FUNC_T(__script__renderModel2, siddddddii, {
PREP_RENDER_MODEL
rendermodel(NULL, arg2, anim, o, self, arg7, arg8, arg9, arg10, fpsEntity, self->attachments, arg11);
});
V8_FUNC_T(__script__renderModel3, siddddddiidddd, {
PREP_RENDER_MODEL
quat rotation(arg12, arg13, arg14, arg15);
rendermodel(NULL, arg2, anim, o, self, arg7, arg8, arg9, arg10, fpsEntity, self->attachments, arg11, 0, 1, rotation);
});
#endif
// GUI
#ifdef CLIENT
V8_FUNC_s(__script__showMessage__, {
IntensityGUI::showMessage("Script message", arg1);
});
V8_FUNC_s(__script__showInputDialog__, {
IntensityGUI::showInputDialog("Script input", arg1);
});
V8_FUNC_i(__script__setDefaultThirdpersonMode, {
// Only allow this to be done once
if (ScriptEngineManager::engineParameters.count("setDefaultThirdpersonMode") == 0)
{
ScriptEngineManager::engineParameters["setDefaultThirdpersonMode"] = "set";
thirdperson = arg1;
} else
Logging::log(Logging::WARNING, "Can only set default thirdperson mode once per map\r\n");
});
#endif
// Network
#ifdef CLIENT
V8_FUNC_si(__script__connect__, {
ClientSystem::connect(arg1, arg2);
});
#endif
// Camera
#ifdef CLIENT
V8_FUNC_ddddddd(__script__forceCamera__, {
vec position(arg1, arg2, arg3);
CameraControl::forceCamera(position, arg4, arg5, arg6, arg7);
});
V8_FUNC_NOPARAM(__script__getCamera__, {
physent *camera = CameraControl::getCamera();
ScriptValuePtr ret = ScriptEngineManager::createScriptObject();
ret->setProperty("position", ScriptEngineManager::getGlobal()->call("__new__",
ScriptValueArgs().append(ScriptEngineManager::getGlobal()->getProperty("Vector3"))
.append(camera->o.x)
.append(camera->o.y)
.append(camera->o.z)
));
ret->setProperty("yaw", camera->yaw);
ret->setProperty("pitch", camera->pitch);
ret->setProperty("roll", camera->roll);
V8_RETURN_VALUE(ret);
});
#endif
// Code
V8_FUNC_ss(__script__compile__, {
ScriptEngineManager::runScriptNoReturn(arg1, arg2);
});
// Components
V8_FUNC_ss(__script__signalComponent__, {
try
{
REFLECT_PYTHON( signal_signal_component );
boost::python::object data = signal_signal_component(arg1, arg2);
std::string stringData = boost::python::extract<std::string>(data);
V8_RETURN_STRING( stringData.c_str() );
} catch(boost::python::error_already_set const &)
{
printf("Error in signalling python component initialization\r\n");
PyErr_Print();
assert(0 && "Halting on Python error");
}
});
// Models
#define ADD_CS_d(arg) \
command += Utility::toString(arg); \
command += " ";
#define ADD_CS_s(arg) \
assert( Utility::validateAlphaNumeric(arg, "._/<>-:") ); \
command += "\""; \
command += arg; \
command += "\" ";
#define CUBESCRIPT_i(name, cmd) \
V8_FUNC_i(__script__##name, { \
std::string command = #cmd; \
command += " "; \
ADD_CS_d(arg1); \
CSSUDO(command.c_str()); \
});
#define CUBESCRIPT_ii(name, cmd) \
V8_FUNC_ii(__script__##name, { \
std::string command = #cmd; \
command += " "; \
ADD_CS_d(arg1); \
ADD_CS_d(arg2); \
CSSUDO(command.c_str()); \
});
#define CUBESCRIPT_iii(name, cmd) \
V8_FUNC_iii(__script__##name, { \
std::string command = #cmd; \
command += " "; \
ADD_CS_d(arg1); \
ADD_CS_d(arg2); \
ADD_CS_d(arg3); \
CSSUDO(command.c_str()); \
});
#define CUBESCRIPT_iiiii(name, cmd) \
V8_FUNC_iiiii(__script__##name, { \
std::string command = #cmd; \
command += " "; \
ADD_CS_d(arg1); \
ADD_CS_d(arg2); \
ADD_CS_d(arg3); \
ADD_CS_d(arg4); \
ADD_CS_d(arg5); \
CSSUDO(command.c_str()); \
});
#define CUBESCRIPT_d(name, cmd) \
V8_FUNC_d(__script__##name, { \
std::string command = #cmd; \
command += " "; \
ADD_CS_d(arg1); \
CSSUDO(command.c_str()); \
});
#define CUBESCRIPT_dd(name, cmd) \
V8_FUNC_dd(__script__##name, { \
std::string command = #cmd; \
command += " "; \
ADD_CS_d(arg1); \
ADD_CS_d(arg2); \
CSSUDO(command.c_str()); \
});
#define CUBESCRIPT_iid(name, cmd) \
V8_FUNC_iid(__script__##name, { \
std::string command = #cmd; \
command += " "; \
ADD_CS_d(arg1); \
ADD_CS_d(arg2); \
ADD_CS_d(arg3); \
CSSUDO(command.c_str()); \
});
#define CUBESCRIPT_ddd(name, cmd) \
V8_FUNC_ddd(__script__##name, { \
std::string command = #cmd; \
command += " "; \
ADD_CS_d(arg1); \
ADD_CS_d(arg2); \
ADD_CS_d(arg3); \
CSSUDO(command.c_str()); \
});
#define CUBESCRIPT_s(name, cmd) \
V8_FUNC_s(__script__##name, { \
std::string command = #cmd; \
command += " "; \
ADD_CS_s(arg1); \
CSSUDO(command.c_str()); \
});
#define CUBESCRIPT_sd(name, cmd) \
V8_FUNC_sd(__script__##name, { \
std::string command = #cmd; \
command += " "; \
ADD_CS_s(arg1); \
ADD_CS_d(arg2); \
CSSUDO(command.c_str()); \
});
#define CUBESCRIPT_ss(name, cmd) \
V8_FUNC_ss(__script__##name, { \
std::string command = #cmd; \
command += " "; \
ADD_CS_s(arg1); \
ADD_CS_s(arg2); \
CSSUDO(command.c_str()); \
});
#define CUBESCRIPT_ssdd(name, cmd) \
V8_FUNC_ssdd(__script__##name, { \
std::string command = #cmd; \
command += " "; \
ADD_CS_s(arg1); \
ADD_CS_s(arg2); \
ADD_CS_d(arg3); \
ADD_CS_d(arg4); \
CSSUDO(command.c_str()); \
});
#define CUBESCRIPT_sssdd(name, cmd) \
V8_FUNC_sssdd(__script__##name, { \
std::string command = #cmd; \
command += " "; \
ADD_CS_s(arg1); \
ADD_CS_s(arg2); \
ADD_CS_s(arg3); \
ADD_CS_d(arg4); \
ADD_CS_d(arg5); \
CSSUDO(command.c_str()); \
});
#define CUBESCRIPT_sdddd(name, cmd) \
V8_FUNC_sdddd(__script__##name, { \
std::string command = #cmd; \
command += " "; \
ADD_CS_s(arg1); \
ADD_CS_d(arg2); \
ADD_CS_d(arg3); \
ADD_CS_d(arg4); \
ADD_CS_d(arg5); \
CSSUDO(command.c_str()); \
});
#define CUBESCRIPT_iiddddd(name, cmd) \
V8_FUNC_iiddddd(__script__##name, { \
std::string command = #cmd; \
command += " "; \
ADD_CS_d(arg1); \
ADD_CS_d(arg2); \
ADD_CS_d(arg3); \
ADD_CS_d(arg4); \
ADD_CS_d(arg5); \
ADD_CS_d(arg6); \
ADD_CS_d(arg7); \
CSSUDO(command.c_str()); \
});
CUBESCRIPT_i(modelShadow, mdlshadow);
CUBESCRIPT_i(modelCollide, mdlcollide);
CUBESCRIPT_i(modelPerEntityCollisionBoxes, mdlperentitycollisionboxes);
CUBESCRIPT_i(modelEllipseCollide, mdlellipsecollide);
CUBESCRIPT_s(objLoad, objload);
CUBESCRIPT_ss(objSkin, objskin);
CUBESCRIPT_ss(objBumpmap, objbumpmap);
CUBESCRIPT_ss(objEnvmap, objenvmap);
CUBESCRIPT_ss(objSpec, objspec);
CUBESCRIPT_d(mdlAlphatest, mdlalphatest);
CUBESCRIPT_ii(mdlBb, mdlbb);
CUBESCRIPT_i(mdlScale, mdlscale);
CUBESCRIPT_i(mdlSpec, mdlspec);
CUBESCRIPT_i(mdlGlow, mdlglow);
CUBESCRIPT_dd(mdlGlare, mdlglare);
CUBESCRIPT_i(mdlAmbient, mdlambient);
CUBESCRIPT_s(mdlShader, mdlshader);
CUBESCRIPT_i(mdlCollisionsOnlyForTriggering, mdlcollisionsonlyfortriggering);
CUBESCRIPT_ddd(mdlTrans, mdltrans);
CUBESCRIPT_s(md5Dir, md5dir);
CUBESCRIPT_ss(md5Load, md5load);
CUBESCRIPT_sssdd(md5Skin, md5skin);
CUBESCRIPT_ss(md5Bumpmap, md5bumpmap);
CUBESCRIPT_ss(md5Envmap, md5envmap);
CUBESCRIPT_sd(md5Alphatest, md5alphatest);
CUBESCRIPT_d(modelYaw, mdlyaw);
CUBESCRIPT_d(modelPitch, mdlpitch);
CUBESCRIPT_ss(md5Tag, md5tag);
CUBESCRIPT_ssdd(md5Anim, md5anim);
CUBESCRIPT_s(md5Animpart, md5animpart);
CUBESCRIPT_sdddd(md5Pitch, md5pitch);
CUBESCRIPT_ddd(rdVert, rdvert);
CUBESCRIPT_iii(rdTri, rdtri);
CUBESCRIPT_iiiii(rdJoint, rdjoint);
CUBESCRIPT_iid(rdLimitDist, rdlimitdist);
CUBESCRIPT_iiddddd(rdLimitRot, rdlimitrot);
CUBESCRIPT_dd(mdlEnvmap, mdlenvmap);
#define RETURN_CENTER_RADIUS \
ScriptValuePtr ret = ScriptEngineManager::createScriptObject(); \
ret->setProperty("center", ScriptEngineManager::getGlobal()->call("__new__", \
ScriptValueArgs().append(ScriptEngineManager::getGlobal()->getProperty("Vector3")) \
.append(center.x) \
.append(center.y) \
.append(center.z) \
)); \
ret->setProperty("radius", ScriptEngineManager::getGlobal()->call("__new__", \
ScriptValueArgs().append(ScriptEngineManager::getGlobal()->getProperty("Vector3")) \
.append(radius.x) \
.append(radius.y) \
.append(radius.z) \
)); \
V8_RETURN_VALUE(ret);
V8_FUNC_s(__script__modelBoundingBox, {
model* theModel = loadmodel(arg1);
if (!theModel) V8_RETURN_NULL;
vec center;
vec radius;
theModel->boundbox(0, center, radius);
RETURN_CENTER_RADIUS;
});
V8_FUNC_s(__script__modelCollisionBox, {
model* theModel = loadmodel(arg1);
if (!theModel) V8_RETURN_NULL;
vec center;
vec radius;
theModel->collisionbox(0, center, radius);
RETURN_CENTER_RADIUS;
});
V8_FUNC_s(__script__modelMesh, {
model* theModel = loadmodel(arg1);
if (!theModel) V8_RETURN_NULL;
vector<BIH::tri> tris2[2];
theModel->gentris(0, tris2);
vector<BIH::tri>& tris = tris2[0];
ScriptValuePtr ret = ScriptEngineManager::createScriptObject();
ret->setProperty("length", tris.length());
for (int i = 0; i < tris.length(); i++)
{
BIH::tri& bt = tris[i];
ScriptValuePtr t = ScriptEngineManager::createScriptObject();
ScriptValuePtr a;
ScriptValuePtr b;
ScriptValuePtr c;
MAKE_VECTOR3(a, bt.a);
MAKE_VECTOR3(b, bt.b);
MAKE_VECTOR3(c, bt.c);
t->setProperty("a", a);
t->setProperty("b", b);
t->setProperty("c", c);
ret->setProperty(Utility::toString(i), t);
}
V8_RETURN_VALUE(ret);
});
// Physics
V8_FUNC_s(__script__physicsCreateEngine, {
PhysicsManager::createEngine(arg1);
});
V8_FUNC_dd(__script__physicsAddSphere, {
physicsHandle ret = PhysicsManager::getEngine()->addSphere(arg1, arg2);
V8_RETURN_INT(ret);
});
V8_FUNC_dddd(__script__physicsAddBox, {
physicsHandle ret = PhysicsManager::getEngine()->addBox(arg1, arg2, arg3, arg4);
V8_RETURN_INT(ret);
});
V8_FUNC_ddd(__script__physicsAddCapsule, {
physicsHandle ret = PhysicsManager::getEngine()->addCapsule(arg1, arg2, arg3);
V8_RETURN_INT(ret);
});
#define GET_VEC(letter, v) \
scriptVec = scriptTris->getProperty(Utility::toString(i))->getProperty(letter); \
v = vec(scriptVec->getPropertyFloat("x"), scriptVec->getPropertyFloat("y"), scriptVec->getPropertyFloat("z"));
V8_FUNC_do(__script__physicsAddMesh, {
ScriptValuePtr scriptTris(new V8Value(ScriptEngineManager::getEngine(), arg2));
std::vector<triangle> tris;
int num = scriptTris->getPropertyInt("length");
for (int i = 0; i < num; i++)
{
ScriptValuePtr scriptVec;
vec a; vec b; vec c;
GET_VEC("a", a);
GET_VEC("b", b);
GET_VEC("c", c);
triangle t(a, b, c);
tris.push_back(t);
}
physicsHandle ret = PhysicsManager::getEngine()->addMesh(arg1, tris);
V8_RETURN_INT(ret);
});
V8_FUNC_i(__script__physicsRemoveBody, {
PhysicsManager::getEngine()->removeBody(arg1);
});
V8_FUNC_ii(__script__physicsSetBodyEntity, {
PhysicsManager::getEngine()->setBodyEntity(arg1, LogicSystem::getLogicEntity(arg2).get());
});
V8_FUNC_iddd(__script__physicsSetBodyPosition, {
PhysicsManager::getEngine()->setBodyPosition(arg1, vec(arg2, arg3, arg4));
});
V8_FUNC_idddd(__script__physicsSetBodyRotation, {
PhysicsManager::getEngine()->setBodyRotation(arg1, quat(arg2, arg3, arg4, arg5));
});
V8_FUNC_iddd(__script__physicsSetBodyVelocity, {
PhysicsManager::getEngine()->setBodyVelocity(arg1, vec(arg2, arg3, arg4));
});
V8_FUNC_iddd(__script__physicsSetBodyAngularVelocity, {
PhysicsManager::getEngine()->setBodyAngularVelocity(arg1, vec(arg2, arg3, arg4));
});
V8_FUNC_iddd(__script__physicsAddBodyImpulse, {
PhysicsManager::getEngine()->addBodyImpulse(arg1, vec(arg2, arg3, arg4));
});
V8_FUNC_i(__script__physicsGetBodyPosition, {
vec position;
PhysicsManager::getEngine()->getBodyPosition(arg1, position);
float ret[3];
ret[0] = position.x;
ret[1] = position.y;
ret[2] = position.z;
V8_RETURN_FARRAY(ret, 3);
});
V8_FUNC_i(__script__physicsGetBodyRotation, {
quat rotation;
PhysicsManager::getEngine()->getBodyRotation(arg1, rotation);
float ret[4];
ret[0] = rotation.x;
ret[1] = rotation.y;
ret[2] = rotation.z;
ret[3] = rotation.w;
V8_RETURN_FARRAY(ret, 4);
});
V8_FUNC_i(__script__physicsGetBodyVelocity, {
vec velocity;
PhysicsManager::getEngine()->getBodyVelocity(arg1, velocity);
float ret[3];
ret[0] = velocity.x;
ret[1] = velocity.y;
ret[2] = velocity.z;
V8_RETURN_FARRAY(ret, 3);
});
V8_FUNC_i(__script__physicsGetBodyAngularVelocity, {
vec angularVelocity;
PhysicsManager::getEngine()->getBodyAngularVelocity(arg1, angularVelocity);
float ret[3];
ret[0] = angularVelocity.x;
ret[1] = angularVelocity.y;
ret[2] = angularVelocity.z;
V8_RETURN_FARRAY(ret, 3);
});
V8_FUNC_iddd(__script__physicsSetLinearFactor, {
vec factor(arg2, arg3, arg4);
PhysicsManager::getEngine()->setLinearFactor(arg1, factor);
});
V8_FUNC_iddd(__script__physicsSetAngularFactor, {
vec factor(arg2, arg3, arg4);
PhysicsManager::getEngine()->setAngularFactor(arg1, factor);
});
V8_FUNC_iidddddd(__script__physicsAddConstraintP2P, {
vec pivotA(arg3, arg4, arg5);
vec pivotB(arg6, arg7, arg8);
int ret = PhysicsManager::getEngine()->addConstraintP2P(arg1, arg2, pivotA, pivotB);
V8_RETURN_INT(ret);
});
V8_FUNC_i(__script__physicsRemoveConstraint, {
PhysicsManager::getEngine()->removeConstraint(arg1);
});
// Editing
#include "editing_system.h"
V8_FUNC_NOPARAM(__script__editing_getWorldSize, { V8_RETURN_INT(EditingSystem::getWorldSize()); });
V8_FUNC_NOPARAM(__script__editing_getGridSize, { V8_RETURN_INT(1<<getvar("gridpower")); });
V8_FUNC_NOPARAM(__script__editing_eraseGeometry, { EditingSystem::eraseGeometry(); });
V8_FUNC_iiii(__script__editing_createCube, { EditingSystem::createCube(arg1, arg2, arg3, arg4); });
V8_FUNC_iiii(__script__editing_deleteCube, { EditingSystem::deleteCube(arg1, arg2, arg3, arg4); });
V8_FUNC_iiiiii(__script__editing_setCubeTexture, { EditingSystem::setCubeTexture(arg1, arg2, arg3, arg4, arg5, arg6); });
V8_FUNC_iiiii(__script__editing_setCubeMaterial, { EditingSystem::setCubeMaterial(arg1, arg2, arg3, arg4, arg5); });
V8_FUNC_iiiiiii(__script__editing_pushCubeCorner, { EditingSystem::pushCubeCorner(arg1, arg2, arg3, arg4, arg5, arg6, arg7); });
V8_FUNC_NOPARAM(__script__editing_getSelectedEntity, {
LogicEntityPtr ret = EditingSystem::getSelectedEntity();
if (ret.get())
{
V8_RETURN_VALUE(ret->scriptEntity);
} else {
V8_RETURN_NULL;
}
});
V8_FUNC_ds(__script__renderProgress, {
renderprogress(arg1, arg2);
});
| 29.093571 | 191 | 0.667746 | [
"geometry",
"object",
"vector",
"model"
] |
ec4ea69fbec898c685ee89bb997a149d8d8cf8ae | 9,719 | c | C | test/random_unit.c | williamcroberts/tpm2-abrmd | 221784228f5d0d479a0de8153a452b10ab546bc8 | [
"BSD-2-Clause"
] | null | null | null | test/random_unit.c | williamcroberts/tpm2-abrmd | 221784228f5d0d479a0de8153a452b10ab546bc8 | [
"BSD-2-Clause"
] | null | null | null | test/random_unit.c | williamcroberts/tpm2-abrmd | 221784228f5d0d479a0de8153a452b10ab546bc8 | [
"BSD-2-Clause"
] | null | null | null | /*
* Copyright (c) 2017, Intel Corporation
* 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.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <glib.h>
#include <stdlib.h>
#include <setjmp.h>
#include <cmocka.h>
#include "random.h"
typedef struct test_data {
Random *random;
} test_data_t;
/* Setup function to allocate our Random gobject. */
static void
random_setup (void **state)
{
test_data_t *data;
data = calloc (1, sizeof (test_data_t));
data->random = RANDOM (random_new ());
*state = data;
}
/* Teardown function to deallocate the Random object. */
static void
random_teardown (void **state)
{
test_data_t *data = *state;
g_object_unref (data->random);
free (data);
}
/* wrap function for the 'open' system call */
int
__wrap_open(const char *pathname,
int flags,
mode_t mode)
{
return ((int)mock ());
}
/* wrap function for the 'read' system call */
ssize_t
__wrap_read (int fd,
void *buf,
size_t count)
{
return ((ssize_t)mock ());
}
/* wrap function for the 'close' system call */
int
__wrap_close (int fd)
{
return ((int)mock ());
}
/* Simple test to test type checking macros. */
static void
random_type_test (void **state)
{
test_data_t *data = *state;
assert_true (G_IS_OBJECT (data->random));
assert_true (IS_RANDOM (data->random));
}
/*
* Seed the Random object from a file source. The file will never actually
* be opened or read. All syscalls are wrapped. The wrap functions are
* prepared such that the random_seed_from_file function executes the
* common / success code path.
*/
static void
random_seed_from_file_success_test (void **state)
{
test_data_t *data = *state;
int ret;
will_return (__wrap_open, 5);
will_return (__wrap_read, sizeof (long int));
will_return (__wrap_close, 0);
ret = random_seed_from_file (data->random, RANDOM_ENTROPY_FILE_DEFAULT);
assert_int_equal (ret, 0);
}
/*
* Test a failure condition for the random_seed_from_file function. We
* cause the 'open' system call to fail and we ensure that the function
* under test returns an integer indicating the error.
*/
static void
random_seed_from_file_open_fail_test (void **state)
{
test_data_t *data = *state;
int ret;
will_return (__wrap_open, -1);
ret = random_seed_from_file (data->random, RANDOM_ENTROPY_FILE_DEFAULT);
assert_int_equal (ret, -1);
}
/*
* Test a failure condition for the random_seed_from_file function. We
* cause the 'read' system call to fail and we ensure that the function
* under test returns an integer indicating the error. Additionally we must
* mock a successful call to 'open' first, and the 'close' as well.
*/
static void
random_seed_from_file_read_fail_test (void **state)
{
test_data_t *data = *state;
int ret;
will_return (__wrap_open, 5);
will_return (__wrap_read, -1);
will_return (__wrap_close, 0);
ret = random_seed_from_file (data->random, RANDOM_ENTROPY_FILE_DEFAULT);
assert_int_equal (ret, -1);
}
/*
* Test a success condition for the random_seed_from_file function, but
* force the 'close' system call to fail. In this case we've successfully
* opened and read from the entropy source we just weren't able to close
* the file. The response code from the function should still indicate
* sucess since we got all of the data we need. A warning message will
* however be output.
*/
static void
random_seed_from_file_close_fail_test (void **state)
{
test_data_t *data = *state;
int ret;
will_return (__wrap_open, 5);
will_return (__wrap_read, sizeof (long int));
will_return (__wrap_close, -1);
ret = random_seed_from_file (data->random, RANDOM_ENTROPY_FILE_DEFAULT);
assert_int_equal (ret, 0);
}
/*
* Test a failure condition for the random_seed_from_file_function. In
* this case both the 'read' and 'close' functions fail. The function under
* test should then return -1.
*/
static void
random_seed_from_file_read_close_fail_test (void **state)
{
test_data_t *data = *state;
int ret;
will_return (__wrap_open, 5);
will_return (__wrap_read, -1);
will_return (__wrap_close, -1);
ret = random_seed_from_file (data->random, RANDOM_ENTROPY_FILE_DEFAULT);
assert_int_equal (ret, -1);
}
/*
* Test a failure condition for the random_seed_from_file function. In
* this case the 'read' function succeeds but reads less data than
* requested / necessary. This should result in the function under test
* returning an error indicator.
*/
static void
random_seed_from_file_read_short_test (void **state)
{
test_data_t *data = *state;
int ret;
will_return (__wrap_open, 5);
will_return (__wrap_read, sizeof (long int) - 1);
will_return (__wrap_close, 0);
ret = random_seed_from_file (data->random, RANDOM_ENTROPY_FILE_DEFAULT);
assert_int_equal (ret, -1);
}
static void
random_get_bytes_setup (void **state)
{
test_data_t *data;
int ret;
random_setup (state);
data = *state;
will_return (__wrap_open, 5);
will_return (__wrap_read, sizeof (long int));
will_return (__wrap_close, 0);
ret = random_seed_from_file (data->random, RANDOM_ENTROPY_FILE_DEFAULT);
assert_int_equal (ret, 0);
}
/*
* Test a successful call to the random_get_bytes function.
*/
static void
random_get_bytes_success_test (void **state)
{
test_data_t *data = *state;
int ret;
uint8_t dest[sizeof (long int) * 3 - 3] = { 0, };
ret = random_get_bytes (data->random, dest, sizeof (dest));
assert_int_equal (ret, sizeof (long int) * 3 - 3);
}
/* Test case to execute a successful call to random_get_uint64. */
static void
random_get_uint64_success_test (void **state)
{
test_data_t *data = *state;
uint64_t dest = 0;
dest = random_get_uint64 (data->random);
assert_true (dest >= 0 && dest <= UINT64_MAX);
}
/* Test case to execute a successful call to random_get_uint32. */
static void
random_get_uint32_success_test (void **state)
{
test_data_t *data = *state;
uint32_t dest;
dest = random_get_uint32 (data->random);
assert_true (dest >= 0 && dest <= UINT32_MAX);
}
/**/
static void
random_get_uint32_range_success_test (void **state)
{
test_data_t *data = *state;
uint32_t dest, low = 6, high = 20;
dest = random_get_uint32_range (data->random, high, low);
assert_true (low < dest);
assert_true (dest < high);
}
gint
main (gint argc,
gchar *argv[])
{
const UnitTest tests[] = {
unit_test_setup_teardown (random_type_test,
random_setup,
random_teardown),
unit_test_setup_teardown (random_seed_from_file_success_test,
random_setup,
random_teardown),
unit_test_setup_teardown (random_seed_from_file_open_fail_test,
random_setup,
random_teardown),
unit_test_setup_teardown (random_seed_from_file_read_fail_test,
random_setup,
random_teardown),
unit_test_setup_teardown (random_seed_from_file_close_fail_test,
random_setup,
random_teardown),
unit_test_setup_teardown (random_seed_from_file_read_close_fail_test,
random_setup,
random_teardown),
unit_test_setup_teardown (random_seed_from_file_read_short_test,
random_setup,
random_teardown),
unit_test_setup_teardown (random_get_bytes_success_test,
random_get_bytes_setup,
random_teardown),
unit_test_setup_teardown (random_get_uint64_success_test,
random_get_bytes_setup,
random_teardown),
unit_test_setup_teardown (random_get_uint32_success_test,
random_get_bytes_setup,
random_teardown),
unit_test_setup_teardown (random_get_uint32_range_success_test,
random_get_bytes_setup,
random_teardown),
NULL,
};
return run_tests (tests);
}
| 32.614094 | 79 | 0.668587 | [
"object"
] |
ec4f3737efba6cec68ddbbe89d19a3eea8b9708a | 369 | h | C | include/dart/buffer/buffer.h | Cfretz244/libdart | 987b01aa1f11455ac6aaf89f8e60825e92e6ec25 | [
"Apache-2.0"
] | 85 | 2019-05-09T19:12:25.000Z | 2021-02-07T16:31:55.000Z | include/dart/buffer/buffer.h | Cfretz244/libdart | 987b01aa1f11455ac6aaf89f8e60825e92e6ec25 | [
"Apache-2.0"
] | 10 | 2019-05-09T22:37:27.000Z | 2020-03-29T03:25:16.000Z | include/dart/buffer/buffer.h | Cfretz244/libdart | 987b01aa1f11455ac6aaf89f8e60825e92e6ec25 | [
"Apache-2.0"
] | 10 | 2019-05-11T08:05:10.000Z | 2020-06-11T11:05:17.000Z | #ifndef DART_BUFFER_H
#define DART_BUFFER_H
/*----- Project Includes -----*/
// General purpose public API functions
#include "api.tcc"
// Internal API functions
#include "detail.tcc"
// Iteration API functions
#include "iterator.tcc"
// Type-specific API functions
#include "object.tcc"
#include "array.tcc"
#include "string.tcc"
#include "primitive.tcc"
#endif
| 16.772727 | 39 | 0.726287 | [
"object"
] |
ec6151830f672bfec347c2533cc02f9db16c75a5 | 913 | h | C | src/bindings/v8serviceworker/webstreams/underlying_source.h | fuxiaohei/xiaohei-worker | 2c6a6357f86a06880d296ecbba2e3f88d3dbd1b5 | [
"Apache-2.0"
] | null | null | null | src/bindings/v8serviceworker/webstreams/underlying_source.h | fuxiaohei/xiaohei-worker | 2c6a6357f86a06880d296ecbba2e3f88d3dbd1b5 | [
"Apache-2.0"
] | null | null | null | src/bindings/v8serviceworker/webstreams/underlying_source.h | fuxiaohei/xiaohei-worker | 2c6a6357f86a06880d296ecbba2e3f88d3dbd1b5 | [
"Apache-2.0"
] | null | null | null | /*
* Copyright (c) 2022 fuxiaohei. All rights reserved.
* Licensed under the Apache 2.0 License. See License file in the project root for
* license information.
*/
#pragma once
#include <common/heap.h>
#include <v8.h>
namespace v8serviceworker {
class UnderlyingSource : public common::HeapObject {
public:
static UnderlyingSource* setup(v8::Local<v8::Object> object);
public:
v8::Local<v8::Promise> call_start(v8::Local<v8::Object> controller);
v8::Local<v8::Promise> call_pull(v8::Local<v8::Object> controller);
private:
v8::Local<v8::Promise> call_algorithm(v8::Local<v8::Object> controller, const std::string& name);
private:
v8::Eternal<v8::Function> cancelAlgorithm_;
v8::Eternal<v8::Function> pullAlgorithm_;
v8::Eternal<v8::Function> startAlgorithm_;
private:
friend class common::Heap;
UnderlyingSource() {}
~UnderlyingSource() {}
};
} // namespace v8serviceworker
| 24.675676 | 99 | 0.723987 | [
"object"
] |
ec6ad31451a369874c4a8cb8aca6e2c203473e93 | 5,702 | h | C | src/Layers/xrRender/ParticleEffectDef.h | acidicMercury8/xray-1.6 | 52fba7348a93a52ff9694f2c9dd40c0d090e791e | [
"Linux-OpenIB"
] | 1 | 2022-03-26T17:00:16.000Z | 2022-03-26T17:00:16.000Z | src/Layers/xrRender/ParticleEffectDef.h | acidicMercury8/xray-1.6 | 52fba7348a93a52ff9694f2c9dd40c0d090e791e | [
"Linux-OpenIB"
] | null | null | null | src/Layers/xrRender/ParticleEffectDef.h | acidicMercury8/xray-1.6 | 52fba7348a93a52ff9694f2c9dd40c0d090e791e | [
"Linux-OpenIB"
] | 1 | 2022-01-31T18:58:31.000Z | 2022-01-31T18:58:31.000Z | //---------------------------------------------------------------------------
#ifndef ParticleEffectDefH
#define ParticleEffectDefH
#include "Shader.h"
namespace PAPI
{
struct Particle;
struct ParticleEffect;
struct PAHeader;
struct ParticleAction;
using PAVec = xr_vector<ParticleAction*>;
using PAVecIt = PAVec::iterator;
}
struct EParticleAction;
namespace PS
{
class CParticleEffect;
typedef BOOL ( * CollisionCallback)(CParticleEffect* E, PAPI::Particle& P, const Fvector& pt, const Fvector& norm); // TRUE-continue collision exec
typedef void ( * DestroyCallback) (CParticleEffect* E, PAPI::Particle& P);
class PFunction;
struct SFrame
{
Fvector2 m_fTexSize;
Fvector2 reserved;
int m_iFrameDimX;
int m_iFrameCount;
float m_fSpeed;
void InitDefault()
{
m_fTexSize.set (32.f/256.f,64.f/128.f);
m_iFrameDimX = 8;
m_iFrameCount = 16;
m_fSpeed = 24.f;
}
IC void CalculateTC(int frame, Fvector2& lt, Fvector2& rb)
{
lt.x = (frame%m_iFrameDimX)*m_fTexSize.x;
lt.y = (frame/m_iFrameDimX)*m_fTexSize.y;
rb.x = lt.x+m_fTexSize.x;
rb.y = lt.y+m_fTexSize.y;
}
};
class ECORE_API CPEDef
{
public:
enum{
dfSprite = (1<<0),
// dfObject = (1<<1),
dfFramed = (1<<10),
dfAnimated = (1<<11),
dfRandomFrame = (1<<12),
dfRandomPlayback= (1<<13),
dfTimeLimit = (1<<14),
dfAlignToPath = (1<<15),
dfCollision = (1<<16),
dfCollisionDel = (1<<17),
dfVelocityScale = (1<<18),
dfCollisionDyn = (1<<19),
dfWorldAlign = (1<<20),
dfFaceAlign = (1<<21),
dfCulling = (1<<22),
dfCullCCW = (1<<23),
};
shared_str m_Name;
Flags32 m_Flags;
// texture
shared_str m_ShaderName;
shared_str m_TextureName;
ref_shader m_CachedShader;
SFrame m_Frame;
// compiled actions
CMemoryWriter m_Actions;
// def
float m_fTimeLimit; // time limit
int m_MaxParticles; // max particle count
Fvector m_VelocityScale; // velocity scale
Fvector m_APDefaultRotation; // align to path
// collision
float m_fCollideOneMinusFriction;
float m_fCollideResilience;
float m_fCollideSqrCutoff;
public:
BOOL SaveActionList (IWriter& F);
BOOL LoadActionList (IReader& F);
// execute
void ExecuteAnimate (PAPI::Particle *particles, u32 p_cnt, float dt);
void ExecuteCollision (PAPI::Particle *particles, u32 p_cnt, float dt, CParticleEffect* owner, CollisionCallback cb);
public:
CPEDef ();
~CPEDef ();
void SetName (LPCSTR name);
IC LPCSTR Name ()const{return *m_Name;}
void CreateShader ();
void DestroyShader ();
void Save (IWriter& F);
BOOL Load (IReader& F);
void Save2 (CInifile& ini);
BOOL Load2 (CInifile& ini);
#ifdef _EDITOR
// change Copy&Equal if variables changed
public:
using EPAVec = xr_vector<EParticleAction*>;
using EPAVecIt = EPAVec::iterator;
EPAVec m_EActionList;
public:
void __stdcall FindActionByName (LPCSTR new_name, bool& res);
bool __stdcall NameOnAfterEdit (PropValue* sender, shared_str& edit_val);
bool __stdcall CollisionFrictionOnAfterEdit (PropValue* sender, float& edit_val);
void __stdcall CollisionFrictionOnBeforeEdit (PropValue* sender, float& edit_val);
void __stdcall CollisionFrictionOnDraw (PropValue* sender, xr_string& draw_val);
bool __stdcall CollisionCutoffOnAfterEdit (PropValue* sender, float& edit_val);
void __stdcall CollisionCutoffOnBeforeEdit (PropValue* sender, float& edit_val);
void __stdcall CollisionCutoffOnDraw (PropValue* sender, xr_string& draw_val);
void __stdcall OnActionEditClick (ButtonValue* sender, bool& bDataModified, bool& bSafe);
void __stdcall OnFrameResize (PropValue* sender);
void __stdcall OnShaderChange (PropValue* sender);
void __stdcall OnFlagChange (PropValue* sender);
void __stdcall OnControlClick (ButtonValue* sender, bool& bDataModified, bool& bSafe);
void __stdcall OnActionsClick (ButtonValue* sender, bool& bDataModified, bool& bSafe);
bool __stdcall OnAfterActionNameEdit(PropValue* sender, shared_str& edit_val);
void FillProp (LPCSTR pref, ::PropItemVec& items, ::ListItem* owner);
void Copy (const CPEDef& src);
BOOL Equal (const CPEDef* pe);
void Render (const Fmatrix& parent);
static PFunction* FindCommandPrototype(LPCSTR src, LPCSTR& dest);
void __stdcall FillActionList (ChooseItemVec& items, void* param);
bool Validate (bool bMsg);
void Compile (EPAVec& v);
#endif
};
};
#define PED_VERSION 0x0001
#define PED_CHUNK_VERSION 0x0001
#define PED_CHUNK_NAME 0x0002
#define PED_CHUNK_EFFECTDATA 0x0003
#define PED_CHUNK_ACTIONLIST 0x0004
#define PED_CHUNK_FLAGS 0x0005
#define PED_CHUNK_FRAME 0x0006
#define PED_CHUNK_SPRITE 0x0007
#define PED_CHUNK_TIMELIMIT 0x0008
#define PED_CHUNK_TIMELIMIT2 0x0009
#define PED_CHUNK_SOURCETEXT_ 0x0020 // obsolete
#define PED_CHUNK_COLLISION 0x0021
#define PED_CHUNK_VEL_SCALE 0x0022
#define PED_CHUNK_EDATA 0x0024
#define PED_CHUNK_ALIGN_TO_PATH 0x0025
//---------------------------------------------------------------------------
#endif
| 34.557576 | 149 | 0.624518 | [
"render"
] |
ec6c75679be403e4604751a0308724ed3276816c | 3,437 | h | C | windows/feime/kor/ime2k/fecommon/include/cpadsvrc.h | npocmaka/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 17 | 2020-11-13T13:42:52.000Z | 2021-09-16T09:13:13.000Z | windows/feime/kor/ime2k/fecommon/include/cpadsvrc.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 2 | 2020-10-19T08:02:06.000Z | 2020-10-19T08:23:18.000Z | windows/feime/kor/ime2k/fecommon/include/cpadsvrc.h | sancho1952007/Windows-Server-2003 | 5c6fe3db626b63a384230a1aa6b92ac416b0765f | [
"Unlicense"
] | 14 | 2020-11-14T09:43:20.000Z | 2021-08-28T08:59:57.000Z | //////////////////////////////////////////////////////////////////
// File : cpadsvrc.h
// Purpose : CImePadServer for COM(Component Object Model) interface.
// (ImePad executable COM server)
//
//
// Date : Fri Apr 16 14:34:49 1999
// Author : ToshiaK
//
// Copyright(c) 1995-1999, Microsoft Corp. All rights reserved
//////////////////////////////////////////////////////////////////
#ifndef __C_IMEPAD_SERVER_COM_H__
#define __C_IMEPAD_SERVER_COM_H__
#include "cpadsvr.h"
interface IImePadServer;
//----------------------------------------------------------------
// CLASS: CImePadSvrCom
//
// This is simple wrapper class for IImePadLocal COM interface.
// dot IME can use this class to access/control ImePad without
// using COM API directly.
// And this class also wraps 16bit/32bit difference.
// As you know, we cannot use COM API in 16bit Application.
// So, Client does not need to care if it work in 16bit/32bit.
//----------------------------------------------------------------
class CImePadSvrCOM;
typedef CImePadSvrCOM* LPCImePadSvrCOM;
class CImePadSvrCOM:public CImePadSvr
{
public:
CImePadSvrCOM(VOID);
~CImePadSvrCOM(VOID);
virtual BOOL IsAvailable (VOID);
virtual BOOL OnIMEPadClose (VOID);
virtual INT Initialize (LANGID imeLangID, DWORD dwImeInputID, LPVOID lpVoid);
virtual INT Terminate (LPVOID lpVoid);
virtual INT ForceDisConnect (VOID);
virtual INT ShowUI (BOOL fShow);
virtual INT IsVisible (BOOL *pfVisible);
virtual INT ActivateApplet (UINT activateID, DWORD dwActParam,LPWSTR lpwstr1,LPWSTR lpwstr2);
virtual INT Notify (INT id, WPARAM wParam, LPARAM lParam);
virtual INT GetAppletInfoList (INT *pCountApplet, LPVOID *pList);
virtual IUnknown* SetIUnkIImeIPoint (IUnknown *pIUnk);
virtual IUnknown* SetIUnkIImeCallback (IUnknown *pIUnk);
virtual IUnknown* GetIUnkIImeIPoint (VOID);
virtual IUnknown* GetIUnkIImeCallback (VOID);
private:
BOOL IsCoInitialized(VOID);
//----------------------------------------------------------------
//private methods.
//----------------------------------------------------------------
static LRESULT CALLBACK InterfaceWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
LRESULT RealWndProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
LRESULT MsgCopyData(HWND hwnd, WPARAM wParam, LPARAM lParam);
LRESULT MsgTimer (HWND hwnd, WPARAM wParam, LPARAM lParam);
LRESULT MsgUser (HWND hwnd, WPARAM wParam, LPARAM lParam);
HWND CreateIFHWND (VOID);
BOOL DestroyIFHWND (BOOL fReserved);
//----------------------------------------------------------------
//private member
//----------------------------------------------------------------
BOOL m_fShowReqStatus; //Save ShowUI()'s bool value.
BOOL m_fLastActiveCtx; //Save IMEPADNOTIFY_ACTIVATECONTEXT
HWND m_hwndIF; //Internal I/F Window handle.
IUnknown* m_lpIUnkIImeIPoint; //IImeIPoint I/F pointer as IUnknown.
IUnknown* m_lpIUnkIImeCallback; //IImeCallback I/F pointer as IUnknown.
IImePadServer* m_lpIImePadServer; //IImePadServer I/F pointer.
LPCImePadCallback m_lpCImePadCallback; //CImePadCallback instance pointer.
DWORD m_dwRegAdvise; //Callbacck interface connect cookie.
BOOL m_fCoInitSuccess; //Flag for CoInitialize() successed or not.
};
#endif //__C_IMEPAD_SERVER_COM_H__
| 41.914634 | 98 | 0.617399 | [
"object",
"model"
] |
ec6edfb475e4cd7c82feb3e091cc0122473b37fa | 88,271 | c | C | Sources/utils/sdss-apps/readAtlasImages-v5_4_11/phSpanUtil.c | RaySSharma/RealSim | 5646802235f3fe6998ca4be20c13710d3dc753c1 | [
"MIT"
] | 9 | 2019-07-12T03:42:17.000Z | 2022-01-13T02:57:06.000Z | Sources/utils/sdss-apps/readAtlasImages-v5_4_11/phSpanUtil.c | RaySSharma/RealSim | 5646802235f3fe6998ca4be20c13710d3dc753c1 | [
"MIT"
] | null | null | null | Sources/utils/sdss-apps/readAtlasImages-v5_4_11/phSpanUtil.c | RaySSharma/RealSim | 5646802235f3fe6998ca4be20c13710d3dc753c1 | [
"MIT"
] | 2 | 2019-10-27T22:01:28.000Z | 2021-02-18T13:46:27.000Z | /*
* <INTRO>
* Utilities to handle masks made from SPANs
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <alloca.h>
#include "dervish.h"
#include "phConsts.h"
#include "phSpanUtil.h"
#if !defined(STAND_ALONE)
# include "phUtils.h"
#endif
#ifndef MAXSHORT
# define MAXSHORT MAX_S16
#endif
#if !defined(STAND_ALONE)
/*
* Because SPAN.y and SPAN.x1 are both less than 16 bits, we can generate
* a 32-bit sort key SORTKEY(x,y) by putting y in the upper 16 bits, and
* x1 in the lower; if the spans are sorted on this they are sorted first
* by y and then by x1. This fails if x < 0, so add an x-bias of 10000
*/
#define SORTKEY(X,Y) (((Y) << 16) | (10000 + X))
static void heap_sort(SPAN *s, unsigned int n);
static void insertion_sort(SPAN *s, unsigned int n);
static int is_canonical_objmaskChain(const CHAIN *chain);
#endif
static TYPE objmask_type = UNKNOWN; /* == shTypeGetFromName("OBJMASK") */
/*****************************************************************************/
/*
* MUST be called before calling any SPAN/OBJMASK routines
*/
void
initSpanObjmask(void)
{
objmask_type = shTypeGetFromName("OBJMASK");
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
* Make a new OBJMASK
*/
OBJMASK *
phObjmaskNew(
int nspans /* number of spans */
)
{
static int id = 0;
OBJMASK *new;
new = shMalloc(sizeof(OBJMASK));
*(int *)&new->id = id++;
new->refcntr = 1;
new->s = (nspans == 0) ? NULL : shMalloc(nspans*sizeof(SPAN));
new->size = nspans;
new->nspan = 0;
new->row0 = new->col0 = 0;
new->rmin = new->rmax = 0;
new->cmin = new->cmax = 0;
new->npix = -1; new->sum = 0.0;
new->data = NULL;
new->user = NULL;
return(new);
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
* Grab more memory for a OBJMASK
*
* Return sv
*/
OBJMASK *
phObjmaskRealloc(OBJMASK *sv, /* Old Spanvec; may be NULL */
int nspans) /* new number of spans */
{
if(sv == NULL) {
sv = phObjmaskNew(nspans);
} else {
sv->s = shRealloc(sv->s, nspans*sizeof(SPAN));
sv->size = nspans;
if(sv->nspan > nspans) {
sv->nspan = nspans;
}
}
return(sv);
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
* Delete a OBJMASK
*/
void
phObjmaskDel(OBJMASK *sv)
{
if(sv == NULL) return;
if(--sv->refcntr > 0) { /* still referenced somewhere */
return;
}
if(p_shMemRefCntrGet(sv) > 0) { /* still referenced somewhere */
p_shMemRefCntrDecr(sv);
return;
}
shFree(sv->s);
shFree(sv->data);
shFree(sv);
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
* Delete a OBJMASK chain
*/
void
phObjmaskChainDel(CHAIN *mask)
{
OBJMASK *sv;
if(mask == NULL) return;
shAssert(mask->type == objmask_type);
while((sv = shChainElementRemByPos(mask, 0)) != NULL) {
phObjmaskDel(sv);
}
shChainDel(mask);
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
* Make a copy of a OBJMASK (doesn't copy OBJMASK->data)
*/
OBJMASK *
phObjmaskCopy(const OBJMASK *sv, /* OBJMASK to be copied */
float fdr, float fdc /* shift by this much */
)
{
OBJMASK *new;
int dr, dc;
if(sv == NULL) {
return(NULL);
}
new = phObjmaskNew(sv->nspan);
dr = (fdr < 0) ? -(-fdr + 0.5) : fdr + 0.5;
dc = (fdc < 0) ? -(-fdc + 0.5) : fdc + 0.5;
new->nspan = sv->nspan;
new->row0 = sv->row0;
new->col0 = sv->col0;
new->npix = sv->npix;
if(dr == 0 && dc == 0) {
memcpy(new->s,sv->s,sv->nspan*sizeof(SPAN));
new->cmin = sv->cmin;
new->rmin = sv->rmin;
new->cmax = sv->cmax;
new->rmax = sv->rmax;
} else {
int i, n = sv->nspan;
SPAN *const snew = new->s, *s = sv->s;
for(i = 0;i < n;i++) {
snew[i].y = s[i].y + dr;
snew[i].x1 = s[i].x1 + dc;
snew[i].x2 = s[i].x2 + dc;
}
new->cmin = sv->cmin + dc;
new->rmin = sv->rmin + dr;
new->cmax = sv->cmax + dc;
new->rmax = sv->rmax + dr;
}
return new;
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
* Make a copy of a complete OBJMASK CHAIN
*/
CHAIN *
phObjmaskChainCopy(const CHAIN *chain, /* chain to copy */
float dr, float dc) /* shifted by this amount */
{
int i;
int len; /* length of chain */
CHAIN *om;
char *cobjmask_type = (char *)objmask_type;
OBJMASK *obj, *nobj;
shAssert(chain != NULL && chain->type == objmask_type);
om = shChainNew(cobjmask_type);
len = chain->nElements;
for(i = 0; i < len; i++) {
obj = shChainElementGetByPos(chain, i);
nobj = phObjmaskCopy(obj, dr, dc);
shChainElementAddByPos(om, nobj, cobjmask_type, TAIL, AFTER);
}
return(om);
}
#if !defined(STAND_ALONE)
/*****************************************************************************/
/*
* <AUTO EXTRACT>
*
* Grow an OBJMASK out by <n> pixels in all directions.
*
* Note that this grow routine isn't very good; it grows correctly along
* the rows, and grows the very topmost and bottommost spans properly in
* the row direction, but it doesn't do a full isotropic grow.
*
* This may or may not matter; let us leave it for now (it's fine for objects
* with only a few pixels).
*/
OBJMASK *
phObjmaskGrow(const OBJMASK *om, /* OBJMASK to grow */
const REGION *reg, /* REGION that om lives in */
int n) /* by how many pixels to grow */
{
int i,j,k;
int nrmin, nrmax; /* number of spans at the top and
bottom of obj respectively */
int ngmin, ngmax; /* number of spans to grow obj by
for each top or bottom input span */
int nspan; /* == om->nspan */
OBJMASK *onew; /* == onew->sv[0] */
int r_rmin, r_rmax, r_cmin, r_cmax; /* bounding box for reg */
int x1, x2, y;
shAssert(om != NULL && om->nspan > 0);
shAssert(phObjmaskIsCanonical(om));
shAssert(n >= 0);
shAssert(reg != NULL);
nspan = om->nspan;
r_rmin = reg->row0;
r_rmax = r_rmin + reg->nrow - 1;
r_cmin = reg->col0;
r_cmax = r_cmin + reg->ncol - 1;
shAssert(om->rmin >= r_rmin && om->rmax <= r_rmax);
/*
* we expect to have to add n levels at the top and bottom of the mask,
* so let us face up to the memcpy involved. This is one reason why this
* routine doesn't grow the OBJECT in place -- it wouldn't be appreciably more
* efficient
*
* See how many new SPANs we'll need (if merging occurs this is an
* overestimate, but not by much).
*/
y = om->rmin;
for(i = 0;i < nspan;i++) {
if(om->s[i].y != y) {
break;
}
}
nrmin = i; /* number of spans with y == rmin */
ngmin = (y - r_rmin > n ? n : y - r_rmin);
y = om->rmax;
for(i = nspan - 1;i >= 0;i--) {
if(om->s[i].y != y) {
break;
}
}
nrmax = nspan - 1 - i; /* number of spans with y == rmax */
ngmax = (r_rmax - y > n) ? n : r_rmax - y; /* number of spans to add */
shAssert(ngmin >= 0 && ngmax >= 0);
/*
* OK, time to make the output mask
*/
onew = phObjmaskNew(nspan + nrmin*ngmin + nrmax*ngmax);
onew->row0 = om->row0; onew->col0 = om->col0;
/*
* Grow the objmask down below rmin
*/
y = om->rmin;
for(i = j = 0;i < nrmin;i++) {
for(k = ngmin;k > 0;k--) {
x1 = om->s[i].x1 - (n - k + 1);
if(x1 < r_cmin) x1 = r_cmin;
x2 = om->s[i].x2 + (n - k + 1);
if(x2 > r_cmax) x2 = r_cmax;
onew->s[j].y = y - k;
onew->s[j].x1 = x1;
onew->s[j].x2 = x2;
j++;
}
}
/*
* Grow the easy spans that already exist
*/
for(i = 0;i < nspan;i++) {
x1 = om->s[i].x1 - n;
if(x1 < r_cmin) x1 = r_cmin;
x2 = om->s[i].x2 + n;
if(x2 > r_cmax) x2 = r_cmax;
onew->s[j].y = om->s[i].y;
onew->s[j].x1 = x1;
onew->s[j].x2 = x2;
j++;
}
/*
* and grow up above rmax
*/
y = om->rmax;
for(i = nspan - 1;i > nspan - nrmax - 1;i--) {
for(k = 1;k <= ngmax;k++) {
x1 = om->s[i].x1 - (n - k + 1);
if(x1 < r_cmin) x1 = r_cmin;
x2 = om->s[i].x2 + (n - k + 1);
if(x2 > r_cmax) x2 = r_cmax;
onew->s[j].y = y + k;
onew->s[j].x1 = x1;
onew->s[j].x2 = x2;
j++;
}
}
onew->nspan = j;
/*
* some of those new spans may overlap
*/
phCanonizeObjmask(onew, 1);
return(onew);
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
*
* Grow a chain of OBJMASKs, merging those that grow into each other.
*/
void
phObjmaskChainGrow(CHAIN *chain, /* the chain of OBJMASKs to grow */
const REGION *reg, /* REGION that objects live in */
int n) /* by how many pixels to grow */
{
CURSOR_T curs1, curs2; /* cursors for chain */
int i;
OBJMASK *om1; /* OBJMASK to grow */
OBJMASK *om2; /* another OBJMASK on the chain */
OBJMASK *uni; /* union of om1 and om2 */
char *objmask_type = (char *)shTypeGetFromName("OBJMASK");
shAssert(chain != NULL && chain->type == (TYPE)objmask_type);
shAssert(reg != NULL && reg->type == TYPE_PIX);
for(i = shChainSize(chain) - 1; i >= 0; i--) {
om1 = shChainElementGetByPos(chain, i);
om2 = phObjmaskGrow(om1, reg, n);
(void)shChainElementChangeByPos(chain, i, om2);
phObjmaskDel(om1);
}
/*
* We've grown all of the objmasks, now try merging them
*/
curs1 = shChainCursorNew(chain);
curs2 = shChainCursorNew(chain);
while((om1 = shChainWalk(chain,curs1,NEXT)) != NULL) {
shChainCursorSet(chain, curs2, HEAD);
while((om2 = shChainWalk(chain,curs2,NEXT)) != om1) {
if(phObjmaskIntersect(om1, om2, 0, 0)) {
/*
* The two overlap. Replace om1 by union of objmasks, and delete om2
*/
uni = phObjmaskUnion(om1, om2);
(void)shChainElementChangeByCursor(chain, curs1, uni);
phObjmaskDel(om1);
(void)shChainElementRemByCursor(chain, curs2);
phObjmaskDel(om2);
om1 = uni;
}
}
}
shChainCursorDel(chain, curs1);
shChainCursorDel(chain, curs2);
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
* Set the bounding box for an OBJMASK; we update npix while we are about it
*/
void
phObjmaskBBSet(OBJMASK *om)
{
int i;
int npix;
int nspans = om->nspan;
int xmin, xmax;
SPAN *spans = om->s;
int x1, x2; /* unpacked from spans */
npix = 0;
xmin = MAXSHORT;
xmax = -MAXSHORT;
for(i = 0; i < nspans; i++) {
x1 = spans[i].x1;
x2 = spans[i].x2;
if(x1 < xmin) xmin = x1;
if(x2 > xmax) xmax = x2;
npix += x2 - x1 + 1;
}
om->npix = npix;
if(nspans > 0) {
om->cmin = xmin;
om->rmin = spans[0].y;
om->cmax = xmax;
om->rmax = spans[nspans-1].y;
} else {
om->rmin = 0;
om->cmin = 0;
om->rmax = 0;
om->cmax = 0;
}
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
* Make an Objmask given the LL and UR corners (x == col, y == row)
*/
OBJMASK *
phObjmaskFromRect(int x1, int y1, int x2, int y2)
{
int nspan = y2 - y1 + 1;
OBJMASK *om;
int i;
shAssert(x1 <= x2);
shAssert(y1 <= y2);
om = phObjmaskNew(nspan);
for(i = 0;i < nspan;i++) {
om->s[i].y = y1 + i;
om->s[i].x1 = x1;
om->s[i].x2 = x2;
}
om->nspan = nspan;
om->cmin = x1; om->cmax = x2;
om->rmin = y1; om->rmax = y2;
om->npix = (y2 - y1 + 1)*(x2 - x1 + 1);
return(om);
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
* Make an circular Objmask given the centre and radius (x == col, y == row)
*/
OBJMASK *
phObjmaskFromCircle(int yc, int xc, int r)
{
int npix = 0; /* number of pixels in OBJMASK */
int nspan = 2*r + 1;
OBJMASK *om;
const int r2 = r*r;
int i;
int hlen; /* half-length of chord */
om = phObjmaskNew(nspan);
npix = 0;
for(i = 0;i <= r;i++) {
hlen = sqrt(r2 - i*i);
om->s[r + i].y = yc + i;
om->s[r + i].x1 = xc - hlen;
om->s[r + i].x2 = xc + hlen;
om->s[r - i].y = yc - i;
om->s[r - i].x1 = xc - hlen;
om->s[r - i].x2 = xc + hlen;
npix += 2*(2*hlen + 1);
}
om->nspan = nspan;
om->cmin = xc - r; om->cmax = xc + r;
om->rmin = yc - r; om->rmax = yc + r;
om->npix = npix;
return(om);
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
*
* Fill out the OBJMASK->data field of an OBJMASK from a region; the
* OBJMASK may be NULL in which case nothing is set
*/
void
phObjmaskSetFromRegion(OBJMASK *om, /* the OBJMASK to set */
const REGION *reg) /* the region wherein it dwells */
{
int i;
int npix; /* number of pixels in OBJMASK */
PIX *ptr; /* pointer to allocated space */
SPAN *sp; /* == om->s[i] */
#if !defined(NDEBUG)
int nrow, ncol; /* == reg->n{row,col} */
#endif
if(om == NULL) return;
shAssert(om->npix >= 0);
shAssert(reg != NULL && reg->type == TYPE_PIX);
#if !defined(NDEBUG)
nrow = reg->nrow; ncol = reg->ncol;
#endif
/*
* allocate space for data
*/
if(om->data != NULL) {
shFree(om->data);
}
om->data = shMalloc(om->npix*sizeof(PIX));
/*
* and fill that space from the region
*/
ptr = om->data;
for(i = 0;i < om->nspan;i++) {
sp = &om->s[i];
npix = sp->x2 - sp->x1 + 1;
shAssert(sp->y >= 0 && sp->y < nrow && sp->x1 >= 0 && sp->x2 < ncol);
memcpy(ptr,®->ROWS[sp->y][sp->x1],npix*sizeof(PIX));
ptr += npix;
}
shAssert(ptr == om->data + om->npix);
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
*
* Set pixels in a REGION from an OBJMASK. The OBJMASK may be NULL
*/
void
phRegionSetFromObjmask(REGION *reg, /* the region to set */
const OBJMASK *om) /* and the OBJMASK */
{
int i;
int npix; /* number of pixels in SPAN */
PIX *ptr; /* pointer to OBJMASK's data */
SPAN *sp; /* == om->s[i] */
#if !defined(NDEBUG)
int nrow, ncol; /* == reg->n{row,col} */
#endif
if(om == NULL) return;
shAssert(om->nspan == 0 || om->data != NULL);
shAssert(reg != NULL && reg->type == TYPE_PIX);
#if !defined(NDEBUG)
nrow = reg->nrow; ncol = reg->ncol;
#endif
/*
* Set values in the region
*/
ptr = om->data;
for(i = 0;i < om->nspan;i++) {
sp = &om->s[i];
npix = sp->x2 - sp->x1 + 1;
shAssert(sp->y >= 0 && sp->y < nrow && sp->x1 >= 0 && sp->x2 < ncol);
memcpy(®->ROWS[sp->y][sp->x1],ptr,npix*sizeof(PIX));
ptr += npix;
}
shAssert(ptr == om->data + om->npix);
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
*
* Set pixels in a REGION to a scalar <val> wherever an OBJMASK has pixels;
* the OBJMASK may be NULL
*/
void
phRegionSetValFromObjmask(REGION *reg, /* the region to set */
const OBJMASK *om, /* the OBJMASK defining pixels */
int val) /* to set to this value */
{
int i,j;
PIX *row; /* pointer to row of REGION */
SPAN *sp; /* == om->s[i] */
int nrow, ncol; /* == reg->n{row,col} */
int row0, col0; /* == reg->{row,col}0 */
int y, x1, x2; /* == sp->{y, x1, x2} */
if(om == NULL) return;
shAssert(reg != NULL && reg->type == TYPE_PIX);
nrow = reg->nrow; ncol = reg->ncol;
row0 = reg->row0; col0 = reg->col0;
/*
* Set values in the region
*/
for(i = 0;i < om->nspan;i++) {
sp = &om->s[i];
y = sp->y;
if(y < row0 || y >= row0 + nrow) {
continue;
}
x1 = sp->x1; x2 = sp->x2;
if(x1 < col0) { x1 = col0; }
if(x2 >= col0 + ncol) { x2 = col0 + ncol - 1; }
row = ®->ROWS[y - row0][x1 - col0];
for(j = x2 - x1;j >= 0;j--) {
row[j] = val;
}
}
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
*
* Set pixels in a REGION to a scalar <val> wherever an OBJMASK on the
* CHAIN objmasks has pixels
*/
void
phRegionSetValFromObjmaskChain(REGION *reg, /* the region to set */
const CHAIN *chain, /* the CHAIN of OBJMASKs
specifying pixels */
int val) /* to set to this value */
{
int i;
const OBJMASK *om; /* an OBJMASK from chain */
int rmin, rmax, cmin, cmax; /* bounding box for region */
int size; /* number of elements in chain */
shAssert(reg != NULL && reg->type == TYPE_PIX);
shAssert(chain != NULL && chain->type == objmask_type);
rmin = reg->row0; rmax = reg->row0 + reg->nrow - 1;
cmin = reg->col0; cmax = reg->col0 + reg->ncol - 1;
size = shChainSize(chain);
for(i = 0; i < size; i++) {
om = shChainElementGetByPos(chain, i);
if(om->rmax < rmin || om->cmax < cmin ||
om->rmin > rmax || om->cmin > cmax) {
continue; /* no overlap */
}
phRegionSetValFromObjmask(reg, om, val);
}
}
#endif /* !defined(STAND_ALONE) */
/*****************************************************************************/
/*
* Make a SPANMASK but don't allocate chains.
*/
static SPANMASK *
make_spanmask(void)
{
SPANMASK *sm = shMalloc(sizeof(*sm));
sm->cookie = SPAN_COOKIE;
*(SPANMASK **)(&sm->parent) = NULL;
sm->nchild = 0;
return(sm);
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
* Create a complete SPANMASK, corresponding to an nrow*ncol bitmask
*/
SPANMASK *
phSpanmaskNew(int nrow, int ncol)
{
SPANMASK *sm;
int im;
char *cobjmask_type = (char *)objmask_type;
shAssert(NMASK_TYPES == (int)S_NMASK_TYPES);
sm = make_spanmask();
sm->nrow = nrow; sm->ncol = ncol;
for(im = 0; im < NMASK_TYPES; im++)
sm->masks[im] = shChainNew(cobjmask_type);
return sm;
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
* Make a sub-SPANMASK (currently, simply return the whole mask)
*/
SPANMASK *
phSubSpanmaskNew(
const SPANMASK *ism
)
{
int i;
SPANMASK *sm = make_spanmask();
((SPANMASK *)ism)->nchild++;
sm->parent = ism;
for(i = 0;i < NMASK_TYPES;i++) {
sm->masks[i] = ism->masks[i];
}
return(sm);
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
* Make a copy of a complete SPANMASK
*/
SPANMASK *
phSpanmaskCopy(
const SPANMASK *ism, /* original mask */
float drow, float dcol /* shift of new wrt old mask */
)
{
SPANMASK *sm;
int im;
if(ism == NULL) {
return(NULL);
}
sm = make_spanmask();
for(im = 0; im < NMASK_TYPES; im++) {
sm->masks[im] = phObjmaskChainCopy(ism->masks[im], drow, dcol);
}
return sm;
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
* Delete a complete SPANMASK
*/
void
phSpanmaskDel(
SPANMASK *mask
)
{
int im;
if(mask == NULL) return;
shAssert(mask->cookie == SPAN_COOKIE);
if(mask->parent != NULL) {
((SPANMASK *)mask->parent)->nchild--; /* we don't own the OBJMASKs,
so don't free them */
} else {
if(mask->nchild != 0) {
shError("Attempt to delete SPANMASK with live children\n");
} else {
for(im = 0; im < NMASK_TYPES; im++) {
phObjmaskChainDel(mask->masks[im]);
}
}
}
shFree(mask);
}
#if !defined(STAND_ALONE)
/*****************************************************************************/
/*
* <AUTO EXTRACT>
*
* Add an OBJMASK to a specified plane of a SPANMASK, ensuring that the
* SPANMASK remains canonical
*/
void
phObjmaskAddToSpanmask(const OBJMASK *om, /* OBJMASK to be added */
SPANMASK *smask, /* SPANMASK to be augmented */
S_MASKTYPE which) /* desired plane of smask */
{
CURSOR_T curs; /* cursor for chain */
CHAIN *mask; /* a plane of smask */
OBJMASK *sv; /* an OBJMASK on the mask CHAIN */
int rmin, cmin; /* unpacked from om */
shAssert(om != NULL && smask != NULL && which >=0 && which < S_NMASK_TYPES);
mask = smask->masks[which];
curs = shChainCursorNew(mask);
rmin = om->rmin; cmin = om->cmin;
while((sv = shChainWalk(mask,curs,NEXT)) != NULL) {
if(sv->rmin >= rmin) {
if(sv->rmin > rmin || sv->cmin > cmin) {
break;
}
}
}
if(sv == NULL) {
shChainElementAddByPos(mask, (void *)om,
(char *)objmask_type, TAIL, AFTER);
} else {
shChainElementAddByCursor(mask, (void *)om,
(char *)objmask_type, curs, BEFORE);
}
shChainCursorDel(mask, curs);
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
* Create a chain for a SPANMASK from a rectangle.
*/
CHAIN *
phSpanmaskFromRect(
int x1,
int y1,
int x2,
int y2
)
{
CHAIN *mask;
char *cobjmask_type = (char *)objmask_type;
mask = shChainNew(cobjmask_type);
(void)shChainElementAddByPos(mask,
phObjmaskFromRect(x1,y1,x2,y2),
cobjmask_type,TAIL,AFTER);
return mask;
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
* Change row0, col0, bounding box, and spans so that SPANMASK
* looks more like a submask.
*/
SPANMASK *
phSpanmaskResetCorner(
SPANMASK *mask, /* mask to change */
int row0, /* desired value of row0 */
int col0 /* and of col0 */
)
{
int i;
CURSOR_T curs; /* cursor for chain */
CHAIN *chain; /* a chain of OBJMASKs */
OBJMASK *obj; /* one of the OBJMASKs */
for(i = 0;i < NMASK_TYPES;i++) {
chain = mask->masks[i];
curs = shChainCursorNew(chain);
while((obj = shChainWalk(chain,curs,NEXT)) != NULL) {
phObjmaskResetCorner(obj, row0, col0);
}
shChainCursorDel(chain, curs);
}
return(mask);
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
* Change row0, col0, bounding box, and spans so that OBJMASK
* looks more like a submask.
*/
OBJMASK *
phObjmaskResetCorner(
OBJMASK *mask,
int row0,
int col0
)
{
int i,drow, dcol;
SPAN *spans;
shAssert(row0 >= 0);
shAssert(col0 >= 0);
if ((row0 != mask->row0) || (col0 != mask->col0)) {
drow = row0 - mask->row0;
dcol = col0 - mask->col0;
spans = mask->s;
for (i=0; i<mask->nspan; i++) {
spans[i].y -= drow;
spans[i].x1 -= dcol;
spans[i].x2 -= dcol;
}
mask->rmin -= drow;
mask->rmax -= drow;
mask->cmin -= dcol;
mask->cmax -= dcol;
mask->row0 = row0;
mask->col0 = col0;
}
return(mask);
}
/*****************************************************************************/
/*
* Find the span in an OBJMASK that contains pixel (rc, cc)
*/
int
phObjmaskFindSpan(const OBJMASK *om, /* the mask */
int rc, int cc, /* desired pixel */
int i0) /* initial guess for index, or -1 */
{
int i;
const int cmin = (om == NULL) ? -1 : om->cmin;
const int cmax = (om == NULL) ? -1 : om->cmax;
const int rmin = (om == NULL) ? -1 : om->rmin;
const int rmax = (om == NULL) ? -1 : om->rmax;
const int nspan = (om == NULL) ? -1 : om->nspan;
const SPAN *s = (om == NULL) ? NULL : om->s;
/*
* Is position above/below top/bottom boundary of mask?
*/
if(om == NULL || nspan == 0 ||
rc < rmin || rc > rmax || cc < cmin || cc > cmax) {
return(-1);
}
/*
* find the first span corresponding to the position
*/
if(i0 < 0) {
i0 = (rc - rmin)*nspan/(float)(rmax - rmin + 1);
}
if(i0 < 0) i0 = 0;
if(i0 >= nspan) i0 = nspan - 1;
i = i0; /* initial guess */
if(s[i].y >= rc) {
for(; i >= 0 && s[i].y >= rc; i--) continue;
if(i < 0 || s[i].y < rc) i++;
} else if(s[i].y < rc) {
for(; i < nspan && s[i].y < rc; i++) continue;
if(i >= nspan) i--;
}
/*
* index i should now give the first span with y == rc
*
* Find a span that includes cc
*/
shAssert(i >= 0 && i < nspan);
for(; i < nspan && s[i].y == rc; i++) {
if(cc >= s[i].x1 && cc <= s[i].x2) {
break;
}
}
if(i == nspan || s[i].y != rc) {
return(-1); /* no overlap */
}
return(i);
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
*
* return an OBJMASK's transpose
*/
OBJMASK *
phObjmaskTranspose(const OBJMASK *om)
{
int cmin; /* == om->cmin */
int i;
int id; /* a span's ID == (index in st) + 1 */
int *id0; /* transposed span ids for this */
int *idm; /* and previous row */
int onspan; /* == om->nspan */
int tnspan; /* == trans->nspan */
SPAN *so, *st; /* == {om,trans}->s */
OBJMASK *trans; /* the required transpose */
int width; /* == om->cmax - om->cmin + 1 */
int x; /* counter in x */
int x1, x2; /* == so[].x[12] - cmin */
int y, ym; /* y for this and previous row */
if(om == NULL) {
return(NULL);
} else if(om->nspan == 0) {
return(phObjmaskNew(0));
}
cmin = om->cmin;
width = om->cmax - om->cmin + 1; /* width of bounding box */
trans = phObjmaskNew(width + 3);
so = om->s; st = trans->s;
onspan = om->nspan; tnspan = trans->nspan;
id0 = alloca(2*width*sizeof(int));
idm = id0 + width;
memset(id0, '\0', width*sizeof(int));
/*
* Now go through om looking at each span creating transposed spans.
* If a pixel is in the same column as one in the previous span simply
* increment the proper (transposed) spans's x2 value, otherwise start
* a new (transposed) span. The arrays id0 and idm contain the ids for
* the transposed spans for this and the previous row, which are one
* more than the spans' indices in trans->s
*/
ym = so[0].y - 1;
for(i = 0; i < onspan; i++) {
y = so[i].y;
x1 = so[i].x1 - cmin; x2 = so[i].x2 - cmin;
if(y != ym) { /* switch id0 and idm */
int *tmp = id0; id0 = idm; idm = tmp;
memset(id0, '\0', width*sizeof(int));
}
for(x = x1; x <= x2; x++) {
if((id = idm[x]) == 0) {
id0[x] = ++tnspan;
if(tnspan >= trans->size) {
phObjmaskRealloc(trans, 1.5*trans->size + 1);
st = trans->s;
}
st[tnspan - 1].y = x + cmin;
st[tnspan - 1].x1 = st[tnspan - 1].x2 = y;
} else {
st[id - 1].x2++;
id0[x] = id;
}
}
}
trans->nspan = tnspan;
phCanonizeObjmask(trans, 1);
return(trans);
}
/*****************************************************************************/
/*
* comparison function for qsort
*/
static int
compar(const void *pa, const void *pb)
{
const OBJMASK *a = *(OBJMASK **)pa;
const OBJMASK *b = *(OBJMASK **)pb;
if(a->rmin < b->rmin) {
return(-1);
} else if(a->rmin == b->rmin) {
return(a->cmin - b->cmin);
} else {
return(1);
}
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
*
* Put a SPANMASK into canonical form, namely sorted by LL corner of
* bounding box.
*
* If canonize_objmasks is true, first ensure that each OBJMASK is canonical
* (sort in y, sort in x, find overlaps, find the bounding box).
*
* If nearly_sorted is true, use an algorithm that assumes that the
* SPANMASK is almost in proper order
*/
void
phCanonizeObjmaskChain(CHAIN *chain, /* CHAIN of OBJMASKs to work on */
int canonize_objmasks, /* canonize each OBJMASK too? */
int nearly_sorted) /* are OBJMASKs almost sorted? */
{
CURSOR_T crsr; /* cursor for crChain */
OBJMASK *om; /* an OBJMASK from the chain */
shAssert(chain != NULL && chain->type == objmask_type);
if(canonize_objmasks) {
crsr = shChainCursorNew(chain);
while((om = shChainWalk(chain, crsr, NEXT)) != NULL) {
phCanonizeObjmask(om, nearly_sorted);
}
shChainCursorDel(chain, crsr);
}
/*
* Sort by the lower-left corner of the bounding box, in Y then X
*/
shChainQsort(chain, compar);
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
* Put a OBJMASK into canonical form: sort in y, sort in x, find
* overlaps, find the bounding box.
*
* (Yes, we know that it should be "canonicalize", not canonise)
*/
void
phCanonizeObjmask(
OBJMASK *sv, /* OBJMASK to work on */
int nearly_sorted /* is sv almost sorted already? */
)
{
SPAN *spans; /* Array of spans */
int total_spans;
int i;
int npix; /* number of pixels in mask */
int y, x1, x2; /* unpacked from spans[i].{y,x1,x2} */
int ymin, ymax, xmin, xmax;
int nspans;
SPAN *s1;
shAssert(sv != NULL);
shAssert(sv->nspan <= sv->size);
spans = sv->s;
/*
* Sort in Y and X
*
* Don't use the system qsort, as naive quick sort (which qsort often is)
* has an N^2 worst-case running time; also heap_sort is simple enough that
* the comparison can be coded inline. In addition, if the list is nearly
* sorted, it's still better to use an insertion sort (with linear time and
* a small coefficient for sorted lists).
*/
if(nearly_sorted) {
insertion_sort(spans, sv->nspan);
} else {
heap_sort(spans, sv->nspan);
}
/* Uniquify spans */
i = 0;
while(i < sv->nspan) {
s1 = &spans[i++];
if(s1->x1 > s1->x2) { /* empty span */
s1->y = -MAXSHORT + 1; /* tag as invalid */
continue;
}
while(i < sv->nspan &&
s1->y == spans[i].y && s1->x2 >= spans[i].x1 - 1) {
spans[i].y = -MAXSHORT + 1; /* tag as invalid */
if(spans[i].x2 > s1->x2)
s1->x2 = spans[i].x2;
i++;
}
}
/* Compress; and find bounding box and npix */
ymin = MAXSHORT;
ymax = -MAXSHORT;
xmin = MAXSHORT;
xmax = -MAXSHORT;
nspans = sv->nspan;
npix = 0;
for(total_spans = 0, i = 0; i < nspans; i++) {
if(spans[i].y == -MAXSHORT + 1)
continue;
spans[total_spans++] = spans[i];
y = spans[i].y;
x1 = spans[i].x1;
x2 = spans[i].x2;
if(y < ymin) ymin = y;
if(y > ymax) ymax = y;
if(x1 < xmin) xmin = x1;
if(x2 > xmax) xmax = x2;
npix += (x2 - x1 + 1);
}
if(nspans > 0) {
sv->npix = npix;
sv->rmin = ymin;
sv->rmax = ymax;
sv->cmin = xmin;
sv->cmax = xmax;
} else {
sv->npix = 0;
sv->rmin = 0;
sv->rmax = 0;
sv->cmin = 0;
sv->cmax = 0;
}
sv->nspan = total_spans; /* Should I realloc? Probably a waste */
/* of time. */
/* We now have St. OBJMASK */
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
* Determine if two OBJMASKs overlap.
*/
int
phObjmaskIntersect(const OBJMASK *sv1,
const OBJMASK *sv2,
float fdy, /* offset to be applied to sv2 */
float fdx)
{
const int dx = (fdx < 0) ? -(-fdx + 0.5) : fdx + 0.5;
const int dy = (fdy < 0) ? -(-fdy + 0.5) : fdy + 0.5;
int irow1, irow2;
int xoff1, xoff2, yoff1, yoff2;
SPAN *s1, *s2;
if(sv2->cmax + dx < sv1->cmin /* check bounding box */
|| sv1->cmax < sv2->cmin + dx
|| sv2->rmax + dy < sv1->rmin
|| sv1->rmax < sv2->rmin + dy)
return 0;
xoff1 = sv1->col0;
xoff2 = sv2->col0 + dx;
yoff1 = sv1->row0;
yoff2 = sv2->row0 + dy;
s1 = sv1->s;
s2 = sv2->s;
irow1 = 0;
irow2 = 0;
while(irow1 < sv1->nspan && irow2 < sv2->nspan) {
int icol1, icol2;
/* find a span with a common y */
if(s1[irow1].y + yoff1 < s2[irow2].y + yoff2) {
irow1++;
continue;
}
if(s2[irow2].y + yoff2 < s1[irow1].y + yoff1) {
irow2++;
continue;
}
/* loop over spans with this y */
for(icol1 = irow1, icol2 = irow2;
icol1 < sv1->nspan && s1[icol1].y == s1[irow1].y
&& s2[icol2].y == s2[irow2].y; icol1++) {
while(icol2 < sv2->nspan && s2[icol2].y == s2[irow2].y
&& s2[icol2].x1 + xoff2 <= s1[icol1].x2 + xoff1) {
if(s2[icol2].x2 + xoff2 >= s1[icol1].x1 + xoff1) {
return 1;
}
icol2++;
}
}
/*
* No intersection at this y value; proceed to next spans
*/
irow1 = icol1; irow2 = icol2;
}
return 0;
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
* Merge the second OBJMASK into the first; if the first is NULL, it
* will be allocated
*
* It is asserted that the OBJMASKs have the same col0 and row0
*
* The return value is sv1, possible as allocated
*/
OBJMASK *
phObjmaskMerge(OBJMASK *sv1, /* target OBJMASK */
const OBJMASK *sv2, /* input OBJMASK */
float fdy, /* Shift sv2 by this amount */
float fdx) /* before merging */
{
const int dx = (fdx < 0) ? -(-fdx + 0.5) : fdx + 0.5;
const int dy = (fdy < 0) ? -(-fdy + 0.5) : fdy + 0.5;
int i;
int i1, i2; /* counters for sv1, sv2 */
long k1, k2; /* keys in sort; >= 32bits */
SPAN *new_spans; /* the output SPANs */
int nspan;
const int nspan1 = (sv1 == NULL) ? 0 : sv1->nspan; /* unalias them */
const int nspan2 = (sv2 == NULL) ? 0 : sv2->nspan;
shAssert(sv2 != NULL);
if(sv1 != NULL) {
shAssert(sv1->col0 == sv2->col0 && sv1->row0 == sv2->row0);
}
nspan = nspan1 + nspan2;
/*
* special case one OBJMASK being empty
*/
if(nspan2 == 0) {
return(sv1);
} else if(nspan1 == 0) {
sv1 = phObjmaskRealloc(sv1, nspan2);
sv1->row0 = sv2->row0;
sv1->col0 = sv2->col0;
sv1->rmin = sv2->rmin + dy;
sv1->rmax = sv2->rmax + dy;
sv1->cmin = sv2->cmin + dx;
sv1->cmax = sv2->cmax + dx;
sv1->npix = sv2->npix;
for(i = 0; i < nspan2; i++) {
SPAN *s1 = &sv1->s[i]; /* unalias them */
SPAN *s2 = &sv2->s[i];
s1->y = s2->y + dy;
s1->x1 = s2->x1 + dx;
s1->x2 = s2->x2 + dx;
}
sv1->nspan = nspan;
return(sv1);
}
/*
* neither is empty, we have real work to do. Go through both OBJMASKs,
* inserting them into the output in sorted order
*/
new_spans = shMalloc(nspan*sizeof(SPAN));
i1 = i2 = 0;
k1 = SORTKEY(sv1->s[i1].x1, sv1->s[i1].y);
k2 = SORTKEY(sv2->s[i2].x1 + dx, sv2->s[i2].y + dy);
i = 0;
for(;;) {
if(k1 < k2) {
new_spans[i++] = sv1->s[i1++];
if(i1 == nspan1) {
while(i2 < nspan2) {
SPAN *s1 = &new_spans[i++]; /* unalias them */
SPAN *s2 = &sv2->s[i2++];
s1->y = s2->y + dy;
s1->x1 = s2->x1 + dx;
s1->x2 = s2->x2 + dx;
}
break;
}
k1 = SORTKEY(sv1->s[i1].x1, sv1->s[i1].y);
} else {
SPAN *s1 = &new_spans[i++]; /* unalias them */
SPAN *s2 = &sv2->s[i2++];
s1->y = s2->y + dy;
s1->x1 = s2->x1 + dx;
s1->x2 = s2->x2 + dx;
if(i2 == nspan2) {
while(i1 < nspan1) {
new_spans[i++] = sv1->s[i1++];
}
break;
}
k2 = SORTKEY(sv2->s[i2].x1 + dx, sv2->s[i2].y + dy);
}
}
shFree(sv1->s);
sv1->s = new_spans;
sv1->nspan = sv1->size = nspan;
phCanonizeObjmask(sv1,1);
return(sv1);
}
/*****************************************************************************/
/*
* Set a circular patch in an OBJMASK, which is then returned.
*
* If the OBJMASK is NULL it will be created.
*/
OBJMASK *
phObjmaskMergeWithCircle(OBJMASK *om, /* mask to set (or create if NULL) */
float rowc, float colc, /* centre of circle */
float r) /* radius */
{
OBJMASK *disk = phObjmaskFromCircle(rowc, colc, r);
if(om == NULL) {
return(disk);
} else {
phObjmaskMerge(om, disk, 0, 0);
phObjmaskDel(disk);
return(om);
}
}
/*****************************************************************************/
/*
* Clear a circular patch in an OBJMASK
*/
void
phObjmaskClearWithCircle(OBJMASK *om, /* mask to clear part of */
float rowc, float colc, /* centre of circle */
float r) /* radius */
{
OBJMASK *disk = phObjmaskFromCircle(rowc, colc, r);
if(om != NULL) {
phObjmaskAndNotObjmask(om, disk);
phObjmaskDel(disk);
}
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
* Merge a chain of OBJMASKs into a single OBJMASK.
* We assert that the chain is canonical (i.e. sorted in y-then-x, and with
* row0,col0 the same for OBJMASKs)
*/
OBJMASK *
phMergeObjmaskChain(
const CHAIN *chain /* array of OBJMASK */
)
{
CURSOR_T curs; /* cursor for chain */
OBJMASK *sv; /* OBJMASKs within chain */
OBJMASK *merge; /* Merged OBJMASK */
SPAN *mspans;
int ispan;
int total_spans; /* total spans in merged spanvec */
shAssert(chain != NULL && chain->type == objmask_type);
shAssert(is_canonical_objmaskChain(chain));
if(chain->nElements == 0) {
merge = phObjmaskNew(1);
merge->npix = merge->nspan = 0;
return(merge);
}
curs = shChainCursorNew(chain);
total_spans = 0;
while((sv = shChainWalk(chain,curs,NEXT)) != NULL) {
total_spans += sv->nspan;
}
merge = phObjmaskNew(total_spans);
merge->nspan = total_spans;
sv = (OBJMASK *)shChainElementGetByPos((CHAIN *)chain,HEAD);
merge->row0 = sv->row0; merge->col0 = sv->col0;
mspans = merge->s;
ispan = 0;
(void)shChainCursorSet(chain, curs, HEAD);
while((sv = shChainWalk(chain,curs,NEXT)) != NULL) {
int i;
const int sv_nspan = sv->nspan; /* unalias them */
SPAN *sv_s = sv->s;
for(i = 0; i < sv_nspan; i++) {
mspans[ispan++] = sv_s[i];
}
}
shChainCursorDel(chain, curs);
phCanonizeObjmask(merge,0);
return merge;
}
/*
* <AUTO EXTRACT>
* Merge two chains of OBJMASKs into a single chain. Note that both
* of the chains are destroyed
*
* In the resulting CHAIN, it is guaranteed that the OBJMASKs are sorted
*/
CHAIN *
phObjmaskChainMerge(
CHAIN *c1, /* array of OBJMASK */
CHAIN *c2 /* array of OBJMASK */
)
{
CURSOR_T cursj; /* cursor for join */
CURSOR_T curs1, curs2; /* cursor for c1 and c2 */
OBJMASK *el1, *el2; /* elements of c1 and c2 */
CHAIN *join; /* result */
long k1, k2; /* keys in sort; >= 32bits */
const char *cobjmask_type = (char *)objmask_type;
shAssert(c1 != NULL);
shAssert(c2 != NULL);
shAssert(c1->type == objmask_type);
shAssert(shChainTypeGet(c1) == shChainTypeGet(c2));
if(shChainSize(c1) == 0) {
shChainDel(c1);
return(c2);
} else if(shChainSize(c2) == 0) {
shChainDel(c2);
return(c1);
}
/*
* OK, we have to do some work as we have two non-empty chains
*/
shAssert(is_canonical_objmaskChain(c1));
shAssert(is_canonical_objmaskChain(c2));
/*
* Build a sorted list
*/
join = shChainNew(cobjmask_type);
cursj = shChainCursorNew(join);
curs1 = shChainCursorNew(c1);
curs2 = shChainCursorNew(c2);
el1 = shChainWalk(c1,curs1,NEXT); /* we know that size >= 1 */
el2 = shChainWalk(c2,curs2,NEXT); /* " " " " " " */
k1 = SORTKEY(el1->cmin, el1->rmin);
k2 = SORTKEY(el2->cmin, el2->rmin);
for(;;) {
if(k1 < k2) {
shChainElementAddByPos(join, el1, cobjmask_type, TAIL, AFTER);
if((el1 = shChainWalk(c1,curs1,NEXT)) == NULL) {
do {
shChainElementAddByPos(join, el2, cobjmask_type, TAIL, AFTER);
shChainElementRemByCursor(c2, curs2);
} while((el2 = shChainWalk(c2,curs2,NEXT)) != NULL);
break;
}
k1 = SORTKEY(el1->cmin, el1->rmin);
} else {
shChainElementAddByPos(join, el2, cobjmask_type, TAIL, AFTER);
if((el2 = shChainWalk(c2,curs2,NEXT)) == NULL) {
do {
shChainElementAddByPos(join, el1, cobjmask_type, TAIL, AFTER);
shChainElementRemByCursor(c1, curs1);
} while((el1 = shChainWalk(c1,curs1,NEXT)) != NULL);
break;
}
k2 = SORTKEY(el2->cmin, el2->rmin);
}
}
shChainCursorDel(c1,curs1); shChainDel(c1);
shChainCursorDel(c2,curs2); shChainDel(c2);
shChainCursorDel(join,cursj);
shAssert(is_canonical_objmaskChain(join));
return(join);
}
/*****************************************************************************/
/*
* Find the inclusive range of chain elements that could contain a row
* in the range y1 -- y2 inclusive
*/
static void
find_span_range(const CHAIN *chain, /* chain to search */
int y1, /* lower value of y */
int y2, /* upper value of y */
int *p0, /* lower limit to search */
int *p1) /* upper limit to search */
{
const int chainsize = chain->nElements;
int p; /* index for chain */
#if 0
unsigned int p0_l, p0_u; /* range for p0 while searching */
#endif
unsigned int p1_l, p1_u; /* range for p1 while searching */
OBJMASK *sv;
shAssert(chainsize > 0);
/*
* Ensure that the chain is indexed
*/
if(chainsize > 3 && !shChainIsIndexed(chain)) {
shChainIndexMake(chain, SH_CHAIN_INDEX_BY_POS);
}
/*
* Find the part of the chain that could intersect; we desire that
* indices p0 and p1
*/
p1_l = 0; p1_u = chainsize - 1;
#if 0
p0_l = 0; p0_u = chainsize - 1;
/*
* find p0 first, remembering anything we learn about p1 as we proceed
*/
for(;;) {
p = (p0_l + p0_u)/2;
if(p == p0_l) {
break;
}
sv = shChainElementGetByPos(chain, p);
if(sv->rmax < y1) { /* too small */
p0_l = p;
} else {
p0_u = p;
if(sv->rmin > y2) { /* too large even for p1 */
p1_u = p;
} else {
if(p > p1_l) {
p1_l = p;
}
}
}
}
*p0 = p0_l;
#else
*p0 = 0;
#endif
/*
* got p0; look for p1
*/
if(p1_l < *p0) {
p1_l = *p0;
}
for(;;) {
p = (p1_l + p1_u + 1)/2;
if(p == p1_u) {
break;
}
sv = shChainElementGetByPos(chain, p);
if(sv->rmin > y2) { /* too large */
p1_u = p;
} else {
p1_l = p;
}
}
*p1 = p1_u;
/*
* Deal with complications such as elements with the same rmin,
* but rmax out of order
*/
for(p = *p0; p > 0; p--) {
sv = shChainElementGetByPos(chain, p);
if(sv->rmax < y1) {
break;
}
}
*p0 = p;
for(p = *p1; p < chainsize - 1; p++) {
sv = shChainElementGetByPos(chain, p);
if(y2 < sv->rmin) {
break;
}
}
*p1 = p;
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
* Determine if a rectangle intersects the spans in mask.
*/
int
phRectIntersectMask(const CHAIN *chain, /* array of OBJMASK */
int x1, /* boundaries of rectangle */
int y1,
int x2,
int y2)
{
int i, j;
int i0, i1; /* range of i */
SPAN *s;
OBJMASK *sv;
int row0; /* row0 for first element of chain */
int rx1, rx2, ry1, ry2; /* "reduced" x1 etc.; row0 subtracted*/
shAssert(chain != NULL && chain->type == objmask_type);
shAssert(x1 <= x2);
shAssert(y1 <= y2);
if(shChainSize(chain) < 1) {
return(0);
}
/*
* find the range of possible OBJMASKs
*/
i0 = i1 = 0; /* make gcc happy */
find_span_range(chain, y1, y2, &i0, &i1);
sv = shChainElementGetByPos(chain, 0); row0 = sv->row0;
for(i = i0; i <= i1; i++) {
sv = shChainElementGetByPos(chain, i);
shAssert(sv->row0 == row0);
ry1 = y1 - sv->row0; ry2 = y2 - sv->row0;
rx1 = x1 - sv->col0; rx2 = x2 - sv->col0;
if(rx2 < sv->cmin || rx1 > sv->cmax || ry2 < sv->rmin || ry1 > sv->rmax){
continue; /* no match on bounding box */
}
s = sv->s;
for(j = 0; j < sv->nspan; j++) {
if(ry2 < s[j].y) { /* can't intersect, as s is sorted */
break;
}
if(ry1 > s[j].y || rx1 > s[j].x2 || rx2 < s[j].x1) {
continue;
}
return 1;
}
}
return 0;
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
* Determine if a pixel intersects the spans in a OBJMASK.
*/
int
phPixIntersectObjmask(
const OBJMASK *sv, /* input SPANVEC */
int x, /* pixel position */
int y
)
{
SPAN *s;
int offy;
int offx;
int i;
shAssert(sv != NULL);
if(x < sv->cmin || sv->cmax < x /* check bounding boxes */
|| y < sv->rmin || sv->rmax < y)
return 0;
s = sv->s;
offy = sv->row0;
offx = sv->col0;
for(i = 0; i < sv->nspan; i++) {
if(s[i].y + offy < y || y < s[i].y + offy
|| s[i].x2 + offx < x || x < s[i].x1 + offx)
continue;
return 1;
}
return 0;
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
* Determine if a pixel intersects the spans in mask.
*/
int
phPixIntersectMask(const CHAIN *chain, /* array of OBJMASKs */
int x, /* pixel position */
int y)
{
int chainsize; /* number of elements on chain */
OBJMASK *sv;
int i;
int i0, i1; /* range of possible values of i */
int p; /* index for chain */
int p0, p1; /* p0 <= p <= p1 could match */
int row0; /* row0 for first element of chain */
shAssert(chain != NULL && chain->type == objmask_type);
chainsize = chain->nElements;
if(chainsize < 1) {
return(0);
}
/*
* find the range of possible OBJMASKs
*/
p0 = p1 = 0; /* make gcc happy */
find_span_range(chain, y, y, &p0, &p1);
/*
* OK, we have to look more carefully at the remaining OBJMASKs
*/
sv = shChainElementGetByPos(chain, 0); row0 = sv->row0;
for(p = p0; p <= p1; p++) {
sv = shChainElementGetByPos(chain, p);
shAssert(sv->row0 == row0);
if(sv->rmin > y) { /*no further OBJMASKs can include x,y*/
return(0);
}
if(y > sv->rmax) {
continue;
}
if(x >= sv->cmin && x <= sv->cmax) { /* point is within bounding box */
const int nspan = sv->nspan;
const SPAN *s = sv->s;
const int y0 = y - sv->row0;
const int x0 = x - sv->col0;
/*
* Most OBJMASKs are simple, with one SPAN for each row of the image. We
* can use this to avoid a full binary search
*/
i = y - sv->rmin; /* initial guess */
if(i >= nspan) { /* hmm, not a good guess */
i0 = -1; i1 = nspan;
} else {
unsigned int step = 1; /* how much to step up/down */
if(y0 > s[i].y) { /* expand search upwards */
i0 = i; i1 = i0 + 1;
while(y0 >= s[i1].y) {
i0 = i1;
step += step; /* double step size */
i1 = i0 + step;
if(i1 >= nspan) { /* reached top of array */
i1 = nspan - 1;
break;
}
}
} else { /* expand it downwards */
i1 = i; i0 = i - 1;
if(i0 >= 0) {
while(y0 < s[i0].y) {
i1 = i0;
step += step; /* double step size */
i0 = i1 - step;
if(i0 < 0) { /* off bottom of array */
i0 = -1;
break;
}
}
}
}
}
/*
* OK, now a binary search to find the first SPAN with the desired row
*/
i = (i0 + i1)/2;
for(;;) {
if(y0 > s[i].y) {
i0 = i;
} else {
i1 = i;
}
if(i1 - i0 <= 1) {
if(i0 == -1 || i1 == nspan) { /* may be off end of array */
if(s[i].y == y0) {
break;
}
return(0);
}
i = i0;
break;
}
i = (i0 + i1)/2;
}
do { /* search all spans with y == y0 */
if(x0 >= s[i].x1 && x0 <= s[i].x2) {
return 1; /* Ah! It is in mask */
}
} while(++i < nspan && s[i].y == y0);
}
}
return 0;
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
* Extract all spanvecs in the CHAIN whose bounding boxes overlap the
* given bounding box.
*/
CHAIN *
phFindSVChainBB(
const CHAIN *chain, /* array of OBJMASK */
int x1, /* boundaries of rectangle */
int y1,
int x2,
int y2
)
{
CURSOR_T curs; /* cursor for chain */
OBJMASK *sv;
CHAIN *oChain;
char *cobjmask_type = (char *)objmask_type;
shAssert(chain != NULL && chain->type == objmask_type);
shAssert(x1 <= x2);
shAssert(y1 <= y2);
oChain = shChainNew(cobjmask_type);
curs = shChainCursorNew(chain);
while((sv = shChainWalk(chain,curs,NEXT)) != NULL) {
if(x2 < sv->cmin || sv->cmax < x1 /* check bounding boxes */
|| y2 < sv->rmin || sv->rmax < y1)
continue;
(void)shChainElementAddByPos(oChain,sv,cobjmask_type,TAIL,AFTER);
}
shChainCursorDel(chain,curs);
return oChain;
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
* Extract all spanvecs in the CHAIN whose bounding boxes overlap the
* given circle.
*/
CHAIN *
phFindSVChainBBCircle(
const CHAIN *chain, /* array of OBJMASK */
int x, /* centre of circle */
int y,
int rad /* radius of circle */
)
{
CURSOR_T curs; /* cursor for chain */
OBJMASK *sv;
CHAIN *oChain;
int rad2;
char *cobjmask_type = (char *)objmask_type;
shAssert(chain != NULL && chain->type == objmask_type);
rad2 = rad*rad;
oChain = shChainNew(cobjmask_type);
curs = shChainCursorNew(chain);
while((sv = shChainWalk(chain,curs,NEXT)) != NULL) {
int dx, dx1, dy, dy1;
int dist2;
dx = sv->cmin - x;
dx1 = x - sv->cmax;
if(dx > 0) { /* OBJMASK is to left of centre */
dist2 = dx*dx;
} else if(dx1 > 0) { /* OBJMASK is to right of centre */
dist2 = dx1*dx1;
} else { /* OBJMASK includes center */
dist2 = 0;
}
dy = sv->rmin - y; /* similarily in y */
dy1 = y - sv->rmax;
if(dy > 0) {
dist2 += dy*dy;
} else if(dy1 > 0) {
dist2 += dy1*dy1;
} else {
;
}
if(dist2 > rad2)
continue;
(void)shChainElementAddByPos(oChain,sv,cobjmask_type,TAIL,AFTER);
}
shChainCursorDel(chain,curs);
return oChain;
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
* Trim the mask so that it fits inside the rectangle.
*/
CHAIN *
phTrimMaskToRect (
const CHAIN *iMask, /* array of OBJMASK */
int rx1, /* boundaries of rectangle */
int ry1,
int rx2,
int ry2
)
{
CHAIN *oMask; /* output mask */
OBJMASK *isv; /* spanvecs from input mask */
OBJMASK *osv; /* spanvecs from output mask */
int i, j;
int inew;
int nmask; /* number of masks in iMask */
int npix; /* number of pixels in osv */
char *cobjmask_type = (char *)objmask_type;
shAssert(iMask != NULL && iMask->type == objmask_type);
shAssert(rx1 <= rx2);
shAssert(ry1 <= ry2);
oMask = shChainNew(cobjmask_type);
nmask = shChainSize(iMask);
for(j = 0; j < nmask; j++) {
isv = shChainElementGetByPos(iMask,j);
if(rx2 < isv->cmin || isv->cmax < rx1 ||
ry2 < isv->rmin || isv->rmax < ry1) {
continue; /* OBJMASK is outside rectangle */
}
osv = phObjmaskNew(isv->nspan);
npix = inew = 0;
for(i = 0; i < isv->nspan; i++) {
int y, x1, x2; /* unaliased from isv->s[i] */
y = isv->s[i].y;
if(y < ry1 || y > ry2) { /* span's above or below */
continue;
}
x1 = isv->s[i].x1;
x2 = isv->s[i].x2;
if(x2 < rx1 || x1 > rx2) { /* span's to left or right */
continue;
}
osv->s[inew].y = y; /* trim span to fit */
x1 = (x1 < rx1) ? rx1 : x1;
x2 = (x2 > rx2) ? rx2 : x2;
osv->s[inew].x1 = x1;
osv->s[inew].x2 = x2;
npix += (x2 - x1 + 1);
inew++;
}
if(inew == 0) {
phObjmaskDel(osv); /* There was, in fact, no overlap */
} else {
osv->nspan = inew;
osv->cmin = (isv->cmin > rx1) ? isv->cmin : rx1;
osv->cmax = (isv->cmax < rx2) ? isv->cmax : rx2;
osv->rmin = (isv->rmin > ry1) ? isv->rmin : ry1;
osv->rmax = (isv->rmax < ry2) ? isv->rmax : ry2;
osv->npix = npix;
(void)shChainElementAddByPos(oMask,osv,cobjmask_type,TAIL,AFTER);
}
}
return oMask;
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
*
* Return an OBJMASK that is the union of two OBJMASKs; the second mask
* may be NULL
*
* See also phObjmaskMerge() and phObjmaskOrObjmask()
*/
OBJMASK *
phObjmaskUnion(const OBJMASK *om1,
const OBJMASK *om2)
{
int i1, i2, j;
OBJMASK *uni; /* the desired union */
int y;
shAssert(om1 != NULL);
if(om2 == NULL) {
return(phObjmaskCopy(om1, 0, 0));
}
shAssert(om1->col0 == om2->col0 && om1->row0 == om2->row0);
uni = phObjmaskNew(om1->nspan + om2->nspan);
i1 = i2 = j = 0;
while(i1 < om1->nspan) {
y = om1->s[i1].y;
while(i2 < om2->nspan && om2->s[i2].y <= y) {
uni->s[j++] = om2->s[i2++];
}
uni->s[j++] = om1->s[i1++];
}
while(i2 < om2->nspan) {
uni->s[j++] = om2->s[i2++];
}
uni->nspan = j;
shAssert(uni->size == j);
phCanonizeObjmask(uni,1);
return(uni);
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
* Construct the mask which is the intersection of two masks.
* This is currently an order (sizeof(mask1)*sizeof(mask2)) operation.
* We may need to be more clever about this.
*/
CHAIN *
phMaskIntersection(
const CHAIN *mask1,
const CHAIN *mask2
)
{
CURSOR_T curs1; /* cursor for chain */
CURSOR_T curs2; /* cursor for chain */
OBJMASK *sv1;
OBJMASK *sv2;
OBJMASK *svnew;
CHAIN *imask; /* intersection mask */
char *cobjmask_type = (char *)objmask_type;
shAssert(mask1 != NULL && mask1->type == objmask_type);
shAssert(mask2 != NULL && mask2->type == objmask_type);
curs1 = shChainCursorNew(mask1);
curs2 = shChainCursorNew(mask2);
imask = shChainNew(cobjmask_type);
while((sv1 = shChainWalk(mask1,curs1,NEXT)) != NULL) {
int col0 = sv1->col0, row0 = sv1->row0;
while((sv2 = shChainWalk(mask2,curs2,NEXT)) != NULL) {
int irow1, irow2;
int inew;
SPAN *s1, *s2;
shAssert(sv2->col0 == col0 && sv2->row0 == row0);
/*
* check bounding box
*/
if(sv2->cmax < sv1->cmin || sv1->cmax < sv2->cmin ||
sv2->rmax < sv1->rmin || sv1->rmax < sv2->rmin) {
continue;
}
svnew = phObjmaskNew(sv1->nspan > sv2->nspan ?
sv1->nspan : sv2->nspan);
s1 = sv1->s;
s2 = sv2->s;
irow1 = 0;
irow2 = 0;
inew = 0;
while(irow1 < sv1->nspan && irow2 < sv2->nspan) {
int icol1, icol2;
/*
* find a span with a common y
*/
if(s1[irow1].y < s2[irow2].y) {
irow1++;
continue;
}
if(s2[irow2].y < s1[irow1].y) {
irow2++;
continue;
}
/*
* loop over spans with this y
*/
for(icol1 = irow1, icol2 = irow2;
icol1 < sv1->nspan && s1[icol1].y == s1[irow1].y
&& s2[icol2].y == s2[irow2].y; icol1++) {
while(icol2 < sv2->nspan &&
s2[icol2].y == s2[irow2].y &&
s2[icol2].x1 <= s1[icol1].x2) {
if(s2[icol2].x2 >= s1[icol1].x1) {
svnew->s[inew].y = s1[icol1].y;
svnew->s[inew].x1 = (s1[icol1].x1 > s2[icol2].x1) ?
s1[icol1].x1 : s2[icol2].x1;
svnew->s[inew].x2 = (s1[icol1].x2 < s2[icol2].x2) ?
s1[icol1].x2 : s2[icol2].x2;
inew++;
}
icol2++;
}
}
/*
* No intersection at this y value; proceed to next spans
*/
irow1 = icol1; irow2 = icol2;
}
if(inew > 0) {
int k, npix;
int x1, x2; /* unpacked from svnew */
/* Find new bounding box */
svnew->nspan = inew;
svnew->cmin = MAXSHORT;
svnew->cmax = -MAXSHORT;
svnew->rmin = svnew->s[0].y;
svnew->rmax = svnew->s[inew-1].y;
npix = 0;
for(k = 0; k < inew; k++) {
x1 = svnew->s[inew].x1;
x2 = svnew->s[inew].x2;
if(x1 < svnew->cmin) svnew->cmin = x1;
if(x2 > svnew->cmax) svnew->cmax = x2;
npix += (x2 - x1 + 1);
}
svnew->npix = npix;
for(k = 0; k < inew; k++) {
svnew->s[k].y -= svnew->rmin;
svnew->s[k].x1 -= svnew->cmin;
svnew->s[k].x2 -= svnew->cmin;
}
(void)shChainElementAddByPos(imask,svnew,cobjmask_type,TAIL,
AFTER);
} else {
phObjmaskDel(svnew);
}
}
}
shChainCursorDel(mask1, curs1);
shChainCursorDel(mask2, curs2);
return imask;
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
*
* Replace sv1 with the intersection of sv1 and sv2, i.e. sv1 &= sv2;
* see also phObjmaskIntersection(), phObjmaskNotIntersectionObjmask(),
* and phObjmaskAndObjmask().
*
* The mask sv1 is returned.
*
* This is currently an order sizeof(mask2) operation.
* We may need to be cleverer about this.
*/
OBJMASK *
phObjmaskAndObjmask(OBJMASK *sv1, /* mask to clip */
const OBJMASK *sv2) /* only keep pixels in this mask */
{
int col0_1, row0_1; /* == sv1->{col,row}0 */
int cmin_1, cmax_1, rmin_1, rmax_1; /* == sv1->{c,r}{min,max} */
int col0_2, row0_2;
int irow1, irow2;
int inew; /* index of new spans */
int npix; /* number of pixels in svnew */
SPAN *s1; /* == sv1->s */
const SPAN *s2; /* == sv2->s */
OBJMASK *svnew;
int x1, x2; /* limits of overlapping span */
shAssert(sv1 != NULL && sv2 != NULL);
col0_1 = sv1->col0; row0_1 = sv1->row0;
cmin_1 = sv1->cmin; cmax_1 = sv1->cmax;
rmin_1 = sv1->rmin; rmax_1 = sv1->rmax;
col0_2 = sv2->col0; row0_2 = sv2->row0;
/*
* check bounding box
*/
if(sv2->cmax + col0_2 < cmin_1 + col0_1 ||
cmax_1 + col0_1 < sv2->cmin + col0_2 ||
sv2->rmax + row0_2 < rmin_1 + row0_1 ||
rmax_1 + row0_1 < sv2->rmin + row0_2) {
return(phObjmaskRealloc(sv1, 0));
}
s1 = sv1->s;
s2 = sv2->s;
npix = inew = 0;
svnew = phObjmaskNew(sv1->nspan);
irow1 = 0;
irow2 = 0;
while(irow1 < sv1->nspan && irow2 < sv2->nspan) {
int icol1, icol2;
/*
* find a span with a common y
*/
if(s1[irow1].y + row0_1 < s2[irow2].y + row0_2) {
irow1++;
continue;
}
if(s2[irow2].y + row0_2 < s1[irow1].y + row0_1) {
irow2++;
continue;
}
/* loop over spans with this y */
for(icol1 = irow1, icol2 = irow2;
icol1 < sv1->nspan && s1[icol1].y == s1[irow1].y; icol1++) {
for(icol2 = irow2; icol2 < sv2->nspan && s2[icol2].y == s2[irow2].y &&
s2[icol2].x1 + col0_2 <= s1[icol1].x2 + col0_1; icol2++) {
if(s2[icol2].x2 + col0_2 >= s1[icol1].x1 + col0_1) {
/* the spans overlap */
if(s2[icol2].x1 + col0_2 <= s1[icol1].x1 + col0_1) {
x1 = s1[icol1].x1;
} else {
x1 = s2[icol2].x1 + col0_2 - col0_1;
}
if(s2[icol2].x2 + col0_2 < s1[icol1].x2 + col0_1) {
x2 = s2[icol2].x2 + col0_2 - col0_1;
} else {
x2 = s1[icol1].x2;
}
if(inew == svnew->size) {
phObjmaskRealloc(svnew, inew*1.4 + 2);
}
svnew->s[inew].y = s1[icol1].y;
svnew->s[inew].x1 = x1;
svnew->s[inew].x2 = x2;
npix += (x2 - x1 + 1);
inew++;
}
}
}
/*
* No intersection at this y value; proceed to next spans
*/
irow1 = icol1; irow2 = icol2;
}
if(inew == 0) { /* no intersection */
phObjmaskDel(svnew);
return(phObjmaskRealloc(sv1, 0));
} else {
svnew->nspan = inew;
svnew->npix = npix;
svnew->col0 = sv1->col0; svnew->row0 = sv1->row0;
phCanonizeObjmask(svnew,0);
shFree(sv1->s); /* copy svnew's spans to sv1 */
sv1->s = svnew->s;
sv1->npix = svnew->npix;
sv1->nspan = svnew->nspan;
sv1->size = svnew->size;
svnew->s = NULL;
phObjmaskDel(svnew);
}
return(sv1);
}
/*****************************************************************************/
/*
* This function does the real work for phObjmaskIntersection() and
* phObjmaskIntersectMask(). If intersect is NULL, only return a
* 1 for intersection 0 otherwise; otherwise find the intersection
* of the OBJMASK and CHAIN and return it as *intersect
*
* If returned, *intersect has row0, col0 taken from sv1 rather than mask2
*
* This is currently an order sizeof(mask2) operation.
* We may need to be more clever about this.
*/
static int
find_mask_intersection(const OBJMASK *sv1,
const CHAIN *mask2,
OBJMASK **intersect
)
{
int col0_1, row0_1; /* == sv1->{col,row}0 */
int cmin_1, cmax_1, rmin_1, rmax_1; /* == sv1->{c,r}{min,max} */
int i;
int inew; /* index of new spans */
int nmask2; /* number of masks on mask2 */
int npix; /* number of pixels in svnew */
OBJMASK *sv2;
OBJMASK *svnew;
int x1, x2; /* limits of overlapping span */
shAssert(sv1 != NULL);
shAssert(mask2 != NULL && mask2->type == objmask_type);
col0_1 = sv1->col0; row0_1 = sv1->row0;
cmin_1 = sv1->cmin; cmax_1 = sv1->cmax;
rmin_1 = sv1->rmin; rmax_1 = sv1->rmax;
svnew = phObjmaskNew(intersect == NULL ? 0 : sv1->nspan);
npix = inew = 0;
nmask2 = shChainSize(mask2);
for(i = 0; i < nmask2; i++) {
int col0_2, row0_2;
int irow1, irow2;
SPAN *s1, *s2;
sv2 = shChainElementGetByPos(mask2,i);
/*
* check bounding box
*/
if(sv2->cmax + sv2->col0 < cmin_1 + col0_1 ||
cmax_1 + col0_1 < sv2->cmin + sv2->col0 ||
sv2->rmax + sv2->row0 < rmin_1 + row0_1 ||
rmax_1 + row0_1 < sv2->rmin + sv2->row0)
continue;
s1 = sv1->s;
s2 = sv2->s;
col0_2 = sv2->col0; row0_2 = sv2->row0;
irow1 = 0;
irow2 = 0;
while(irow1 < sv1->nspan && irow2 < sv2->nspan) {
int icol1, icol2;
/* find a span with a common y */
if(s1[irow1].y + row0_1 < s2[irow2].y + row0_2) {
irow1++;
continue;
}
if(s2[irow2].y + row0_2 < s1[irow1].y + row0_1) {
irow2++;
continue;
}
/* loop over spans with this y */
for(icol1 = irow1, icol2 = irow2;
icol1 < sv1->nspan && s1[icol1].y == s1[irow1].y; icol1++) {
for(icol2 = irow2; icol2 < sv2->nspan && s2[icol2].y == s2[irow2].y
&& s2[icol2].x1 + col0_2 <= s1[icol1].x2 + col0_1; icol2++) {
if(s2[icol2].x2 + col0_2 >= s1[icol1].x1 + col0_1) {
/* the spans overlap */
if(s2[icol2].x1 + col0_2 <= s1[icol1].x1 + col0_1) {
x1 = s1[icol1].x1;
} else {
x1 = s2[icol2].x1 + col0_2 - col0_1;
}
if(s2[icol2].x2 + col0_2 < s1[icol1].x2 + col0_1) {
x2 = s2[icol2].x2 + col0_2 - col0_1;
} else {
x2 = s1[icol1].x2;
}
if(inew == svnew->size) {
if(intersect == NULL) { /* we just want the return value*/
phObjmaskDel(svnew);
return(1);
}
phObjmaskRealloc(svnew, inew*1.4 + 2);
}
svnew->s[inew].y = s1[icol1].y;
svnew->s[inew].x1 = x1;
svnew->s[inew].x2 = x2;
npix += (x2 - x1 + 1);
inew++;
}
}
}
/*
* No intersection at this y value; proceed to next spans
*/
irow1 = icol1; irow2 = icol2;
}
}
if(intersect != NULL) {
if(inew == 0) { /* no intersection */
phObjmaskDel(svnew);
svnew = NULL;
} else {
svnew->nspan = inew;
svnew->npix = npix;
svnew->col0 = sv1->col0; svnew->row0 = sv1->row0;
phCanonizeObjmask(svnew,0);
}
*intersect = svnew;
} else {
shAssert(inew == 0);
phObjmaskDel(svnew); /* mask2 and sv1 don't intersect */
}
return(inew == 0 ? 0 : 1);
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
* Return 1 if OBJMASK and the second OBJMASK chain have pixels in common,
* else 0.
*/
int
phObjmaskIntersectMask(const CHAIN *chain, /* array of OBJMASK */
const OBJMASK *sv) /* the OBJMASK in question */
{
return(find_mask_intersection(sv, chain, NULL));
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
* Construct the OBJMASK consisting of all pixels in the first OBJMASK
* and also in the second OBJMASK chain.
*
* See also phObjmaskIntersectionChain() and phObjmaskAndObjmask()
*/
OBJMASK *
phObjmaskIntersection(const OBJMASK *sv1,
const CHAIN *mask2)
{
OBJMASK *intersect = NULL;
(void)find_mask_intersection(sv1, mask2, &intersect);
return(intersect);
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
*
* Return an OBJMASK chain consisting of all the OBJMASKs in mask2 that
* intersect with om1; note that we don't copy the OBJMASKs, merely
* return pointers (but with their reference counts incremented)
*
* This is currently an order sizeof(mask2) operation.
* We may need to be more clever about this.
*
* See also phObjmaskIntersection()
*/
CHAIN *
phObjmaskIntersectionChain(const OBJMASK *om1,
const CHAIN *mask2)
{
int i;
int nmask2; /* number of masks on mask2 */
CHAIN *result = NULL; /* the desired result */
OBJMASK *om2;
shAssert(om1 != NULL);
shAssert(mask2 != NULL && mask2->type == objmask_type);
nmask2 = shChainSize(mask2);
for(i = 0; i < nmask2; i++) {
om2 = shChainElementGetByPos(mask2,i);
if(phObjmaskIntersect(om1, om2,0,0)) {
if(result == NULL) {
result = shChainNew((char *)objmask_type);
}
(void)shChainElementAddByPos(result, om2, (char *)objmask_type,
TAIL, AFTER);
om2->refcntr++;
}
}
return(result);
}
/*****************************************************************************/
/*
* here's the workhorse for phObjmaskNotIntersectionObjmask
*
* Note that it does _not_ set its result's bounding box
*/
static void
i_phObjmaskNotIntersectionObjmask(OBJMASK *svnew,
const OBJMASK *sv2)
{
int irow1, irow2;
int inew;
int ndel; /* number of spans deleted */
SPAN *s1, *s2;
int y; /* the y that we are examining */
/*
* check bounding box
*/
if(sv2->cmax < svnew->cmin || svnew->cmax < sv2->cmin ||
sv2->rmax < svnew->rmin || svnew->rmax < sv2->rmin) {
return;
}
/*
* OK, there may be some (partial?) spans to remove from svnew
*/
ndel = 0;
s1 = svnew->s;
s2 = sv2->s;
irow1 = 0;
irow2 = 0;
inew = svnew->nspan;
while(irow1 < svnew->nspan && irow2 < sv2->nspan) {
int icol1, icol2;
/* find a span with a common y */
if(s1[irow1].y < s2[irow2].y) {
irow1++;
continue;
}
if(s2[irow2].y < s1[irow1].y) {
irow2++;
continue;
}
/* loop over spans with this y */
y = s1[irow1].y;
shAssert(s2[irow2].y == y);
for(icol1 = irow1, icol2 = irow2; icol1 < svnew->nspan &&
s1[icol1].y == y && s2[icol2].y == y; icol1++) {
while(icol2 < sv2->nspan &&
s2[icol2].y == y && s2[icol2].x1 <= s1[icol1].x2) {
if(s2[icol2].x2 >= s1[icol1].x1) {
/* We've got some kind of overlap, find */
/* out what it is. */
if(s2[icol2].x1 <= s1[icol1].x1) {
if(s2[icol2].x2 < s1[icol1].x2) { /* overlap on left */
s1[icol1].x1 = s2[icol2].x2 + 1;
} else { /* complete overlap: delete span */
s1[icol1].y = -MAXSHORT + 1;
ndel++;
break; /* don't increment icol2 */
}
} else {
if(s2[icol2].x2 >= s1[icol1].x2) { /* overlap on right */
s1[icol1].x2 = s2[icol2].x1 - 1;
break; /* don't increment icol2 */
} else { /* in the middle: a new span */
if(inew == svnew->size) {
phObjmaskRealloc(svnew, inew*1.4 + 2);
s1 = svnew->s;
}
svnew->s[inew] = s1[icol1];
s1[icol1].x1 = s2[icol2].x2 + 1;
s1[inew].x2 = s2[icol2].x1 - 1;
inew++;
}
}
}
icol2++;
}
}
/*
* No intersection at this y value; proceed to next spans
*/
irow1 = icol1; irow2 = icol2;
}
if(ndel > 0 || inew > svnew->nspan) {
svnew->nspan = inew;
phCanonizeObjmask(svnew,1);
}
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
*
* Set all pixels in the second OBJMASK in the first
* (see also phObjmaskUnion()). The mask om1 is returned.
*/
OBJMASK *
phObjmaskOrObjmask(OBJMASK *om1,
const OBJMASK *om2)
{
int i;
int nspan1, nspan2;
SPAN *s1, *s2; /* == om[12]->s */
shAssert(om1 != NULL);
if(om2 == NULL) {
return(om1);
}
nspan1 = om1->nspan; nspan2 = om2->nspan;
phObjmaskRealloc(om1, nspan1 + nspan2);
om1->nspan += nspan2;
s1 = om1->s; s2 = om2->s;
for(i = 0; i < nspan2; i++) {
s1[nspan1 + i] = s2[i];
}
phCanonizeObjmask(om1, 1);
return(om1);
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
*
* Remove all pixels that are set in the second OBJMASK from the first
* (see also phObjmaskNotIntersectionObjmask() and phObjmaskAndObjmask()).
*
* The mask sv1 is returned.
*
* This is currently an order sizeof(sv2) operation.
* We may need to be cleverer about this.
*/
OBJMASK *
phObjmaskAndNotObjmask(OBJMASK *sv1,
const OBJMASK *sv2)
{
shAssert(sv1 != NULL);
shAssert(sv2 == NULL || (sv2->col0 == sv1->col0 && sv2->row0 == sv1->row0));
/*
* see if there are some spans to remove
*/
if(sv2 != NULL) {
i_phObjmaskNotIntersectionObjmask(sv1, sv2);
phObjmaskBBSet(sv1);
}
return(sv1);
}
/*
* <AUTO EXTRACT>
*
* Construct and return the OBJMASK consisting of all pixels in the
* first OBJMASK, but NOT in the second OBJMASK (which may be NULL).
* (See also phObjmaskAndNotObjmask() and phObjmaskAndObjmask())
*
* This is currently an order sizeof(sv2) operation.
* We may need to be more clever about this.
*/
OBJMASK *
phObjmaskNotIntersectionObjmask(const OBJMASK *sv1,
const OBJMASK *sv2)
{
int i;
OBJMASK *svnew;
shAssert(sv1 != NULL);
shAssert(sv2 == NULL || (sv2->col0 == sv1->col0 && sv2->row0 == sv1->row0));
/*
* start by simply copying sv1
*/
svnew = phObjmaskNew(sv1->nspan);
for(i = 0; i < sv1->nspan; i++) {
svnew->s[i] = sv1->s[i];
}
svnew->nspan = sv1->nspan;
svnew->npix = sv1->npix;
svnew->rmin = sv1->rmin; svnew->rmax = sv1->rmax;
svnew->cmin = sv1->cmin; svnew->cmax = sv1->cmax;
/*
* now see if there are some spans to remove
*/
if(sv2 != NULL) {
i_phObjmaskNotIntersectionObjmask(svnew, sv2);
}
phObjmaskBBSet(svnew);
return(svnew);
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
* Construct and return the OBJMASK consisting of all pixels in the
* first OBJMASK, but NOT in the second OBJMASK chain.
*
* This is currently an order sizeof(mask2) operation.
* We may need to be more clever about this.
*/
OBJMASK *
phObjmaskNotIntersectionObjmaskChain(const OBJMASK *sv1,
const CHAIN *mask2)
{
int col0, row0;
CURSOR_T curs2; /* cursor for chain */
const OBJMASK *sv2;
OBJMASK *svnew;
int i;
shAssert(sv1 != NULL);
shAssert(mask2 != NULL && mask2->type == objmask_type);
col0 = sv1->col0;
row0 = sv1->row0;
curs2 = shChainCursorNew(mask2);
svnew = phObjmaskNew(sv1->nspan);
for(i = 0; i < sv1->nspan; i++) {
svnew->s[i] = sv1->s[i];
}
svnew->nspan = sv1->nspan;
svnew->npix = sv1->npix;
svnew->rmin = sv1->rmin; svnew->rmax = sv1->rmax;
svnew->cmin = sv1->cmin; svnew->cmax = sv1->cmax;
while((sv2 = shChainWalk(mask2,curs2,NEXT)) != NULL) {
shAssert(sv2->col0 == col0 && sv2->row0 == row0);
i_phObjmaskNotIntersectionObjmask(svnew, sv2);
}
shChainCursorDel(mask2, curs2);
phObjmaskBBSet(svnew);
return(svnew);
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
* Construct the mask consisting of all pixels in the first mask, but
* NOT in the second mask.
* This is currently an order (sizeof(mask1)*sizeof(mask2)) operation.
* We may need to be more clever about this.
*/
CHAIN *
phMaskNotIntersection(
const CHAIN *mask1,
const CHAIN *mask2
)
{
CURSOR_T curs1; /* cursor for chain1 */
OBJMASK *sv1;
OBJMASK *svnew;
CHAIN *imask; /* mask of pixels in 1 but not in 2 */
char *cobjmask_type = (char *)objmask_type;
shAssert(mask1 != NULL && mask1->type == objmask_type);
shAssert(mask2 != NULL && mask2->type == objmask_type);
curs1 = shChainCursorNew(mask1);
imask = shChainNew(cobjmask_type);
while((sv1 = shChainWalk(mask1,curs1,NEXT)) != NULL) {
svnew = phObjmaskNotIntersectionObjmaskChain(sv1, mask2);
if(svnew->nspan > 0) {
(void)shChainElementAddByPos(imask,svnew,cobjmask_type,TAIL, AFTER);
} else {
phObjmaskDel(svnew);
}
}
shChainCursorDel(mask1, curs1);
return imask;
}
#endif /* !defined(STAND_ALONE) */
/*****************************************************************************/
/*
* <AUTO EXTRACT>
* Set pixels in a MASK from an OBJMASK
*/
void
phMaskSetFromObjmask(const OBJMASK *om, /* the OBJMASK */
MASK *mask, /* mask to set */
const int val) /* value to OR into mask */
{
char cval = val; /* unpacked from val */
int i;
int nspan; /* unpack obj->nspan for compiler */
SPAN *spans; /* SPANs in this OBJMASK */
int col0, row0, ncol, nrow; /* unpacked from mask (and corrected
for om->{row,col}0) */
int y, x1, x2; /* unpacked from a SPAN */
unsigned char **mask_rows; /* unpacked from obj1->mask->rows */
shAssert(om != NULL && mask != NULL);
/*
* Examine list of spans, setting bits in the MASK.
*/
mask_rows = mask->rows;
nrow = mask->nrow; ncol = mask->ncol;
row0 = mask->row0 - om->row0; col0 = mask->col0 - om->col0;
nspan = om->nspan;
spans = om->s;
for(i = 0;i < nspan;i++) {
int j;
unsigned char *mask_row;
y = spans[i].y - row0;
if(y < 0 || y >= nrow) {
continue;
}
x1 = spans[i].x1 - col0; x2 = spans[i].x2 - col0;
if(x1 < 0) {
x1 = 0;
}
if(x2 >= ncol) {
x2 = ncol - 1;
}
mask_row = mask_rows[y];
for(j = x1;j <= x2;j++) {
mask_row[j] |= cval;
}
}
}
#if !defined(STAND_ALONE)
/*****************************************************************************/
/*
* <AUTO EXTRACT>
* Set pixels in a MASK from a CHAIN of OBJMASK
*/
void
phMaskSetFromObjmaskChain(
const CHAIN *chain, /* array of OBJMASK */
MASK *mask, /* mask of REGION objs were found in */
const int val /* value to OR into mask */
)
{
char cval = val; /* unpacked from val */
CURSOR_T curs; /* cursor for chain */
int i;
int nspan; /* unpack obj->nspan for compiler */
SPAN *spans; /* SPANs in this OBJMASK */
int col0, row0, ncol, nrow; /* unpacked from mask (and corrected
for sv->{row,col}0) */
int y, x1, x2; /* unpacked from a SPAN */
unsigned char **mask_rows; /* unpacked from obj1->mask->rows */
OBJMASK *sv;
shAssert(chain != NULL && chain->type == objmask_type);
shAssert(mask != NULL);
/*
* Examine list of spans, setting the parent REGION's MASK.
*/
mask_rows = mask->rows;
nrow = mask->nrow; ncol = mask->ncol;
curs = shChainCursorNew(chain);
while((sv = shChainWalk(chain,curs,NEXT)) != NULL) {
row0 = mask->row0 - sv->row0; col0 = mask->col0 - sv->col0;
nspan = sv->nspan;
spans = sv->s;
for(i = 0;i < nspan;i++) {
int j;
unsigned char *mask_row;
y = spans[i].y - row0;
if(y < 0 || y >= nrow) {
continue;
}
x1 = spans[i].x1 - col0; x2 = spans[i].x2 - col0;
if(x1 < 0) {
x1 = 0;
}
if(x2 >= ncol) {
x2 = ncol - 1;
}
mask_row = mask_rows[y];
for(j = x1;j <= x2;j++) {
mask_row[j] |= cval;
}
}
}
shChainCursorDel(chain,curs);
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
*
* Given a possible non-simply-connected objmask, return an array of the
* simply connected components (followed by a NULL)
*
* Usually a set of new masks will be allocated, but, as a special case,
* if alloc_one is false and the initial mask is simply connected,
* and thus *nmask == 1, the routine'll return NULL (saving the expense
* of allocating an array and copying om)
*/
OBJMASK **
phObjmaskSplitSimple(const OBJMASK *om, /* initial OBJMASK */
int *pnmask, /* number of resulting masks or NULL */
int alloc_one) /* allocate a copy of om to return
if *nmask == 1? */
{
int i, j, k;
int *ids; /* ID values for spans */
int id; /* ID of current span */
int i0, i1; /* range of spans with current y */
int im0, im1; /* range of spans with previous y */
OBJMASK **masks = NULL; /* return array */
int next_id = 1; /* next id to use */
int nmask = 0; /* number of masks; *pnmask == nmask */
int nspan; /* == om->nspan */
int *nspans; /* number of spans in each OBJMASK */
SPAN *spans; /* == om->s */
int x1, x2; /* unpacked from a span */
int y; /* the row of current interest */
shAssert(om != NULL);
nspan = om->nspan;
spans = om->s;
if(pnmask == NULL) pnmask = &nmask;
/*
* handle trivial special case first; no spans in mask
*/
if(nspan == 0) {
*pnmask = nmask = 0;
if(alloc_one) {
masks = shMalloc((nmask + 1)*sizeof(OBJMASK *));
masks[0] = NULL;
}
return(masks);
}
/*
* we have to do some work. Work through om seeing which spans touch,
* and assigning each connected mask an id (we'll sometimes have to merge
* apparently disconnected masks of course, the classic \Lambda shaped
* object problem)
*/
ids = alloca(nspan*sizeof(int));
memset(ids, '\0', nspan*sizeof(int)); shAssert(ids[0] == 0);
nspans = alloca((nspan + 1)*sizeof(int));
y = spans[0].y - 2;
i0 = 0; i1 = -1; /* range of spans with s.y == y-1 */
i = 0;
while(i < nspan) {
if(spans[i].y == y + 1) { /* may touch previous spans */
im0 = i0; im1 = i1;
} else {
im0 = 0; im1 = -1;
}
y = spans[i].y;
for(i0 = i++; i < nspan && spans[i].y == y; i++) continue;
i1 = i - 1;
for(j = i0; j <= i1; j++) {
x1 = spans[j].x1; x2 = spans[j].x2;
id = ids[j];
for(k = im0; k <= im1; k++) {
if(spans[k].x1 <= x2 + 1 &&
spans[k].x2 >= x1 - 1) { /* spans touch */
if(id == 0) { /* not already assigned */
id = ids[j] = ids[k];
nspans[id]++;
} else if(id == ids[k]) { /* consistent assignment */
;
} else { /* inconsistent assignment */
int l;
const int idk = ids[k];
for(l = 0; l < j; l++) {
if(ids[l] == idk) {
ids[l] = id;
}
}
nspans[id] += nspans[idk];
nmask--; /* we merged two */
nspans[idk] = 0;
}
}
}
if(id == 0) { /* a new object */
ids[j] = next_id++;
nspans[ids[j]] = 1;
nmask++;
}
}
}
/*
* Is this the special case of a simply connected OBJMASK?
*/
if(nmask == 1) {
*pnmask = nmask;
if(alloc_one) {
masks = shMalloc((nmask + 1)*sizeof(OBJMASK *));
masks[0] = phObjmaskCopy(om, 0, 0);
masks[1] = NULL;
}
return(masks);
}
/*
* pack those spans into OBJMASKs of their own. Start by allocating the
* desired OBJMASKs; note that the array masks is initially sparse if
* we've had to merge OBJMASKs in the previous step
*/
*pnmask = nmask;
masks = shMalloc(next_id*sizeof(OBJMASK *));
masks[0] = NULL;
j = k = 0;
for(i = 1; i < next_id; i++) {
if(nspans[i] > 0) {
j++; k += nspans[i]; /* used in shAssertions */
masks[i] = phObjmaskNew(nspans[i]);
masks[i]->nspan = nspans[i];
masks[i]->row0 = om->row0; masks[i]->col0 = om->col0;
nspans[i] = 0;
} else {
masks[i] = NULL;
}
}
shAssert(j == nmask);
shAssert(k == om->nspan);
/*
* copy the spans into the proper places
*/
for(i = 0; i < nspan; i++) {
id = ids[i];
masks[id]->s[nspans[id]++] = spans[i];
}
/*
* make the masks array compact, and set bounding boxes
*/
for(i = j = 0; i < next_id; i++) {
if(masks[i] != NULL) {
shAssert(masks[i]->nspan == nspans[i]);
phObjmaskBBSet(masks[i]);
masks[j++] = masks[i];
}
}
masks[j] = NULL;
return(masks);
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
* Set a given pixel in a SPANMASK
*/
void
phSpanmaskSetAsPix(
SPANMASK *sm, /* SPANMASK to set */
int row, /* pixel location */
int col,
const S_MASKTYPE val /* type of mask */
)
{
OBJMASK *om;
char *cobjmask_type = (char *)objmask_type;
shAssert(sm != NULL);
shAssert(sm->cookie == SPAN_COOKIE);
om = phObjmaskNew(1);
om->npix = om->nspan = 1;
om->s[0].y = row;
om->s[0].x1 = col;
om->s[0].x2 = col;
om->cmin = col;
om->cmax = col;
om->rmin = row;
om->rmax = row;
(void)shChainElementAddByPos(sm->masks[val],om,cobjmask_type,TAIL, AFTER);
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
* Find how many pixels are set in an OBJMASK
*/
int phObjmaskNumPix(
const OBJMASK *mask
)
{
int i, npix=0;
SPAN *span;
span = mask->s;
for (i=0; i<mask->nspan; i++) {
npix += span[i].x2 - span[i].x1 + 1;
}
return npix;
}
/*****************************************************************************/
/*
* Here's an implementation of heapsort, specialised to sorting SPANs
* in y and x
*
* Because SPAN.y and SPAN.x1 are both less than 16 bits, we can generate
* a 32-bit sort key by putting y in the upper 16 bits, and x1 in the lower;
* if the spans are sorted on this they are sorted first by y and then by x
*/
static void
heap_sort(SPAN *s, unsigned int n)
{
unsigned int i, j, k, l;
SPAN elem;
if(n <= 1) return;
/*
* Build the heap
*/
l = n/2;
k = n - 1;
while(l > 0) {
elem = s[--l];
i = l;
j = 2*l + 1;
while(j <= k) {
if(j < k &&
SORTKEY(s[j].x1, s[j].y) < SORTKEY(s[j + 1].x1, s[j + 1].y)) {
j++;
}
if(SORTKEY(elem.x1, elem.y) < SORTKEY(s[j].x1, s[j].y)) {
s[i] = s[j];
i = j;
j = 2*j + 1;
} else {
j = k + 1;
}
}
s[i] = elem;
}
/*
* and destroy it again, resulting in a sorted array
*/
for(;;) {
elem = s[k];
s[k] = s[0];
if(--k == 0) {
s[0] = elem;
break;
}
i = 0;
j = 1;
while(j <= k) {
if(j < k &&
SORTKEY(s[j].x1, s[j].y) < SORTKEY(s[j + 1].x1, s[j + 1].y)) {
j++;
}
if(SORTKEY(elem.x1, elem.y) < SORTKEY(s[j].x1, s[j].y)) {
s[i] = s[j];
i = j;
j = 2*j + 1;
} else {
j = k + 1;
}
}
s[i] = elem;
}
}
/*****************************************************************************/
/*
* And here's an insertion sort. This is a Good Choice as the data to be
* sorted is nearly sorted (and thus insertion is linear with a small
* coefficient)
*/
static void
insertion_sort(SPAN *s, unsigned int n)
{
int i, j;
int nswap = 0;
SPAN elem;
SPAN s0;
if(n <= 1) return;
s0 = s[0];
s[0].y = -MAXSHORT; /* use as a sentinel */
for(j = 1;j < n;j++) {
elem = s[j];
for(i = j - 1;SORTKEY(s[i].x1, s[i].y) > SORTKEY(elem.x1, elem.y);i--) {
s[i + 1] = s[i];
nswap++;
}
if(i == 0) {
if(SORTKEY(s0.x1, s0.y) > SORTKEY(elem.x1, elem.y)) {
s[1] = s0;
s0 = elem;
nswap++;
continue;
}
}
s[i + 1] = elem;
}
s[0] = s0;
#if 0 /* was this a good choice of sort? */
if(nswap > n) {
fprintf(stderr,"insertion_sort: n == %d > nswap == %d\n",n,nswap);
}
#endif
}
/*****************************************************************************/
/*
* See if an OBJMASK is canonical, i.e.
* Each span has x2 >= x1
* All the spans are sorted in y-then-x
* npix is correct
*/
int
phObjmaskIsCanonical(const OBJMASK *om)
{
int i;
long key; /* key in sort; >= 32bits */
int npix; /* number of pixels in om */
long okey; /* old value of key */
int nspan = om->nspan; /* unalias nspan and s */
SPAN *s = om->s;
if(nspan <= 1) {
return(1);
}
npix = s[0].x2 - s[0].x1 + 1;
key = SORTKEY(s[0].x1, s[0].y);
if(s[0].x2 < s[0].x1) {
return(0);
}
for(i = 1;i < nspan;i++) {
if(s[i].x2 < s[i].x1) {
return(0);
}
okey = key;
key = SORTKEY(s[i].x1, s[i].y);
if(key < okey) {
return(0);
}
npix += s[i].x2 - s[i].x1 + 1;
}
return(om->npix == npix ? 1 : 0);
}
/*****************************************************************************/
/*
* See if a CHAIN of OBJMASKs is canonical, i.e.
* All the OBJMASKs have the same row0, col0
* The OBJMASKs rmin, cmin values are sorted
* None of the OBJMASKs overlap -- note that this is an N^2 check
*/
static int
is_canonical_objmaskChain(const CHAIN *chain)
{
CURSOR_T crsr1, crsr2;
long key; /* key in sort; >= 32bits */
long okey; /* old value of key */
int row0, col0;
const OBJMASK *obj1, *obj2;
shAssert(chain != NULL && chain->type == objmask_type);
crsr1 = shChainCursorNew(chain);
if((obj1 = shChainWalk(chain, crsr1, NEXT)) == NULL) {
shChainCursorDel(chain,crsr1);
return(1);
}
row0 = obj1->row0; col0 = obj1->col0;
key = SORTKEY(obj1->cmin, obj1->rmin);
crsr2 = shChainCursorNew(chain);
while((obj1 = shChainWalk(chain, crsr1, NEXT)) != NULL) {
okey = key;
key = SORTKEY(obj1->cmin, obj1->rmin);
if(obj1->row0 != row0 || obj1->col0 != col0) {
break;
}
if(key < okey) {
break;
}
shChainCursorSet(chain,crsr2,HEAD);
while((obj2 = shChainWalk(chain, crsr2, NEXT)) != obj1) {
if(phObjmaskIntersect(obj1,obj2,0,0)) {
break;
}
}
}
shChainCursorDel(chain, crsr1);
shChainCursorDel(chain, crsr2);
#if 1
if(obj1 != NULL) {
shError("canonical test fails");
obj1 = NULL;
}
#endif
return(obj1 == NULL ? 1 : 0);
}
/*****************************************************************************/
/*
* <AUTO EXTRACT>
*
* Grow an OBJMASK to NxN super-pixel boundaries. For example, if the
* superpixels are 4x4, the OBJMASK
* (y: x1, x2) = (1: 2, 3) (2: 3, 5) (3: 2, 4) (4: 1, 3)
* would become
* (0: 0, 7) (1: 0, 7) (2: 0, 7) (3: 0, 7)
* (4: 0, 3) (5: 0, 3) (6: 0, 3) (7: 0, 3)
* i.e. it covers all the superpixels that have at least one pixel in
* the original OBJMASK
*
* This is indended for use in matching master_masks to the binned
* version of the data region
*/
OBJMASK *
phObjmaskGrowToSuperpixel(const OBJMASK *om, /* OBJMASK to grow */
int n) /* size of superpixels */
{
int i,j,k;
int nspan; /* == om->nspan */
OBJMASK *onew; /* returned OBJMASK */
OBJMASK *obinned; /* om with binned coordinates */
int x1, x2, y;
shAssert(om != NULL);
shAssert(phObjmaskIsCanonical(om));
shAssert(n > 0);
/*
* Start by making a copy of the initial OBJMASK, which we then bin;
* we'll later expand it again
*/
obinned = phObjmaskCopy(om,0,0);
nspan = om->nspan;
for(i = 0;i < nspan;i++) {
obinned->s[i].y /= n;
obinned->s[i].x1 /= n;
obinned->s[i].x2 /= n;
}
phCanonizeObjmask(obinned, 1);
/*
* Each of those spans will expand to n spans when we unbin, so allocate
* the objmask and expand obinned into it
*/
onew = phObjmaskNew(n*obinned->nspan);
nspan = obinned->nspan;
for(i = j = 0;i < nspan;i++) {
y = n*obinned->s[i].y;
x1 = n*obinned->s[i].x1;
x2 = n*obinned->s[i].x2 + n - 1;
for(k = 0;k < n;k++) {
onew->s[j].y = y + k;
onew->s[j].x1 = x1;
onew->s[j++].x2 = x2;
}
}
onew->nspan = n*obinned->nspan;
onew->rmin = n*obinned->rmin;
onew->cmin = n*obinned->cmin;
onew->rmax = n*obinned->rmax + n - 1;
onew->cmax = n*obinned->cmax + n - 1;
shAssert(j == onew->nspan);
phCanonizeObjmask(onew, 1);
phObjmaskDel(obinned);
return(onew);
}
#endif /* !defined(STAND_ALONE) */
| 25.452999 | 79 | 0.521383 | [
"object"
] |
ec7270b0b5873836237ed291297b84d48ffe631d | 3,503 | h | C | moveit_core/collision_detection/include/moveit/collision_detection/collision_octomap_filter.h | Permobil-Senior-Design/moveit | 549e1e226f75f987724b3a8abbe1b49511f522b1 | [
"BSD-3-Clause"
] | 62 | 2019-02-13T04:29:31.000Z | 2021-01-03T18:29:42.000Z | moveit_core/collision_detection/include/moveit/collision_detection/collision_octomap_filter.h | Permobil-Senior-Design/moveit | 549e1e226f75f987724b3a8abbe1b49511f522b1 | [
"BSD-3-Clause"
] | 99 | 2019-02-10T19:33:30.000Z | 2019-07-11T07:54:04.000Z | moveit_core/collision_detection/include/moveit/collision_detection/collision_octomap_filter.h | Permobil-Senior-Design/moveit | 549e1e226f75f987724b3a8abbe1b49511f522b1 | [
"BSD-3-Clause"
] | 26 | 2019-02-10T07:53:14.000Z | 2021-09-19T17:14:32.000Z | /*********************************************************************
* Software License Agreement (BSD License)
*
* Copyright (c) 2012, Willow Garage, 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:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution.
* * Neither the name of Willow Garage nor the names of its
* contributors may be used to endorse or promote products derived
* from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
* BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*********************************************************************/
/* Author: Adam Leeper */
#ifndef MOVEIT_COLLISION_DETECTION_COLLISION_OCTOMAP_FILTER_
#define MOVEIT_COLLISION_DETECTION_COLLISION_OCTOMAP_FILTER_
#include <moveit/collision_detection/collision_common.h>
#include <moveit/collision_detection/collision_world.h>
namespace collision_detection
{
/** @brief Re-proceses contact normals for an octomap by estimating a metaball
* iso-surface using the centers of occupied cells in a neighborhood of the contact point.
*
* This is an implementation of the algorithm described in:
* A. Leeper, S. Chan, K. Salisbury. Point Clouds Can Be Represented as Implicit
* Surfaces for Constraint-Based Haptic Rendering. ICRA, May 2012, St Paul, MN.
* http://adamleeper.com/research/papers/2012_ICRA_leeper-chan-salisbury.pdf
*
* @param The octomap originally used for collision detection.
* @param The collision result (which will get its normals updated)
* @param The distance, as a multiple of the octomap cell size, from which to include neighboring cells.
* @param The minimum angle change required for a normal to be over-written
* @param Whether to request a depth estimate from the algorithm (experimental...)
* @param The iso-surface threshold value (0.5 is a reasonable default).
* @param The metaball radius, as a multiple of the octomap cell size (1.5 is a reasonable default)
*/
int refineContactNormals(const World::ObjectConstPtr& object, CollisionResult& res,
double cell_bbx_search_distance = 1.0, double allowed_angle_divergence = 0.0,
bool estimate_depth = false, double iso_value = 0.5, double metaball_radius_multiple = 1.5);
} // namespace collision_detection
#endif
| 52.283582 | 117 | 0.72338 | [
"object"
] |
ec73f4aa7279866f60af3549cbb91d00cc00b5fd | 9,002 | h | C | ash/wm/workspace/workspace_window_resizer.h | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2015-08-13T21:04:58.000Z | 2015-08-13T21:04:58.000Z | ash/wm/workspace/workspace_window_resizer.h | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | null | null | null | ash/wm/workspace/workspace_window_resizer.h | Fusion-Rom/android_external_chromium_org | d8b126911c6ea9753e9f526bee5654419e1d0ebd | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 1 | 2020-11-04T06:34:36.000Z | 2020-11-04T06:34:36.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 ASH_WM_WORKSPACE_WINDOW_RESIZER_H_
#define ASH_WM_WORKSPACE_WINDOW_RESIZER_H_
#include <vector>
#include "ash/wm/window_resizer.h"
#include "ash/wm/workspace/magnetism_matcher.h"
#include "base/compiler_specific.h"
#include "base/gtest_prod_util.h"
#include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h"
#include "ui/aura/window_tracker.h"
namespace ash {
class DockedWindowLayoutManager;
class PhantomWindowController;
class TwoStepEdgeCycler;
class WindowSize;
namespace wm {
class WindowState;
}
// WindowResizer implementation for workspaces. This enforces that windows are
// not allowed to vertically move or resize outside of the work area. As windows
// are moved outside the work area they are shrunk. We remember the height of
// the window before it was moved so that if the window is again moved up we
// attempt to restore the old height.
class ASH_EXPORT WorkspaceWindowResizer : public WindowResizer {
public:
// When dragging an attached window this is the min size we'll make sure is
// visible. In the vertical direction we take the max of this and that from
// the delegate.
static const int kMinOnscreenSize;
// Min height we'll force on screen when dragging the caption.
// TODO: this should come from a property on the window.
static const int kMinOnscreenHeight;
// Snap region when dragging close to the edges. That is, as the window gets
// this close to an edge of the screen it snaps to the edge.
static const int kScreenEdgeInset;
// Distance in pixels that the cursor must move past an edge for a window
// to move or resize beyond that edge.
static const int kStickyDistancePixels;
virtual ~WorkspaceWindowResizer();
static WorkspaceWindowResizer* Create(
wm::WindowState* window_state,
const std::vector<aura::Window*>& attached_windows);
// WindowResizer:
virtual void Drag(const gfx::Point& location_in_parent,
int event_flags) OVERRIDE;
virtual void CompleteDrag() OVERRIDE;
virtual void RevertDrag() OVERRIDE;
private:
WorkspaceWindowResizer(wm::WindowState* window_state,
const std::vector<aura::Window*>& attached_windows);
private:
friend class WorkspaceWindowResizerTest;
// The edge to which the window should be snapped at the end of the drag.
enum SnapType {
SNAP_LEFT,
SNAP_RIGHT,
SNAP_NONE
};
// Lays out the attached windows. |bounds| is the bounds of the main window.
void LayoutAttachedWindows(gfx::Rect* bounds);
// Calculates the new sizes of the attached windows, given that the main
// window has been resized (along the primary axis) by |delta|.
// |available_size| is the maximum length of the space that the attached
// windows are allowed to occupy (ie: the distance between the right/bottom
// edge of the primary window and the right/bottom of the desktop area).
// Populates |sizes| with the desired sizes of the attached windows, and
// returns the number of pixels that couldn't be allocated to the attached
// windows (due to min/max size constraints).
// Note the return value can be positive or negative, a negative value
// indicating that that many pixels couldn't be removed from the attached
// windows.
int CalculateAttachedSizes(
int delta,
int available_size,
std::vector<int>* sizes) const;
// Divides |amount| evenly between |sizes|. If |amount| is negative it
// indicates how many pixels |sizes| should be shrunk by.
// Returns how many pixels failed to be allocated/removed from |sizes|.
int GrowFairly(int amount, std::vector<WindowSize>& sizes) const;
// Calculate the ratio of pixels that each WindowSize in |sizes| should
// receive when growing or shrinking.
void CalculateGrowthRatios(const std::vector<WindowSize*>& sizes,
std::vector<float>* out_ratios) const;
// Adds a WindowSize to |sizes| for each attached window.
void CreateBucketsForAttached(std::vector<WindowSize>* sizes) const;
// If possible snaps the window to a neary window. Updates |bounds| if there
// was a close enough window.
void MagneticallySnapToOtherWindows(gfx::Rect* bounds);
// If possible snaps the resize to a neary window. Updates |bounds| if there
// was a close enough window.
void MagneticallySnapResizeToOtherWindows(gfx::Rect* bounds);
// Finds the neareset window to magentically snap to. Updates
// |magnetism_window_| and |magnetism_edge_| appropriately. |edges| is a
// bitmask of the MagnetismEdges to match again. Returns true if a match is
// found.
bool UpdateMagnetismWindow(const gfx::Rect& bounds, uint32 edges);
// Adjusts the bounds of the window: magnetically snapping, ensuring the
// window has enough on screen... |snap_size| is the distance from an edge of
// the work area before the window is snapped. A value of 0 results in no
// snapping.
void AdjustBoundsForMainWindow(int snap_size, gfx::Rect* bounds);
// Stick the window bounds to the work area during a move.
bool StickToWorkAreaOnMove(const gfx::Rect& work_area,
int sticky_size,
gfx::Rect* bounds) const;
// Stick the window bounds to the work area during a resize.
void StickToWorkAreaOnResize(const gfx::Rect& work_area,
int sticky_size,
gfx::Rect* bounds) const;
// Returns a coordinate along the primary axis. Used to share code for
// left/right multi window resize and top/bottom resize.
int PrimaryAxisSize(const gfx::Size& size) const;
int PrimaryAxisCoordinate(int x, int y) const;
// Updates the bounds of the phantom window for window snapping.
void UpdateSnapPhantomWindow(const gfx::Point& location,
const gfx::Rect& bounds);
// Restacks the windows z-order position so that one of the windows is at the
// top of the z-order, and the rest directly underneath it.
void RestackWindows();
// Returns the edge to which the window should be snapped to if the user does
// no more dragging. SNAP_NONE is returned if the window should not be
// snapped.
SnapType GetSnapType(const gfx::Point& location) const;
// Returns true if |bounds_in_parent| are valid bounds for snapped state type
// |snapped_type|.
bool AreBoundsValidSnappedBounds(wm::WindowStateType snapped_type,
const gfx::Rect& bounds_in_parent) const;
// Docks or undocks the dragged window.
void SetDraggedWindowDocked(bool should_dock);
wm::WindowState* window_state() { return window_state_; }
const std::vector<aura::Window*> attached_windows_;
// Returns the currently used instance for test.
static WorkspaceWindowResizer* GetInstanceForTest();
bool did_lock_cursor_;
// Set to true once Drag() is invoked and the bounds of the window change.
bool did_move_or_resize_;
// True if the window initially had |bounds_changed_by_user_| set in state.
bool initial_bounds_changed_by_user_;
// The initial size of each of the windows in |attached_windows_| along the
// primary axis.
std::vector<int> initial_size_;
// Sum of the minimum sizes of the attached windows.
int total_min_;
// Sum of the sizes in |initial_size_|.
int total_initial_size_;
// Gives a previews of where the the window will end up. Only used if there
// is a grid and the caption is being dragged.
scoped_ptr<PhantomWindowController> snap_phantom_window_controller_;
// Used to determine whether the window should be snapped or docked when
// the user drags a window to the edge of the screen.
scoped_ptr<TwoStepEdgeCycler> edge_cycler_;
// The edge to which the window should be snapped to at the end of the drag.
SnapType snap_type_;
// Number of mouse moves since the last bounds change. Only used for phantom
// placement to track when the mouse is moved while pushed against the edge of
// the screen.
int num_mouse_moves_since_bounds_change_;
// The mouse location passed to Drag().
gfx::Point last_mouse_location_;
// Window the drag has magnetically attached to.
aura::Window* magnetism_window_;
// Used to verify |magnetism_window_| is still valid.
aura::WindowTracker window_tracker_;
// If |magnetism_window_| is non-NULL this indicates how the two windows
// should attach.
MatchedEdge magnetism_edge_;
// Dock container window layout manager.
DockedWindowLayoutManager* dock_layout_;
// Used to determine if this has been deleted during a drag such as when a tab
// gets dragged into another browser window.
base::WeakPtrFactory<WorkspaceWindowResizer> weak_ptr_factory_;
DISALLOW_COPY_AND_ASSIGN(WorkspaceWindowResizer);
};
} // namespace ash
#endif // ASH_WM_WORKSPACE_WINDOW_RESIZER_H_
| 38.635193 | 80 | 0.731837 | [
"vector"
] |
ec7cfdd974ed31974520c67abf5284790c737325 | 1,937 | h | C | src/service/common/translation_job.h | mozilla/mts | 733ab64cd2993ca4039a7a9d0004b12d563287e5 | [
"Apache-2.0"
] | 5 | 2020-06-23T12:22:31.000Z | 2021-03-23T08:47:03.000Z | src/service/common/translation_job.h | fredblain/mts | cf7b5f7140cfbc918332d7b6c1818d0faa3e73dd | [
"Apache-2.0"
] | 1 | 2020-06-23T11:30:40.000Z | 2020-06-23T11:30:40.000Z | src/service/common/translation_job.h | fredblain/mts | cf7b5f7140cfbc918332d7b6c1818d0faa3e73dd | [
"Apache-2.0"
] | null | null | null | // -*- mode: c++; indent-tabs-mode: nil; tab-width: 2 -*-
#pragma once
#include <sys/time.h>
#include <thread>
#include "data/vocab.h"
#include "translation_options.h"
#include "translator/history.h"
// #include "3rd_party/rapidjson/include/rapidjson/document.h"
// #include "3rd_party/rapidjson/include/rapidjson/writer.h"
// #include "3rd_party/rapidjson/include/rapidjson/stringbuffer.h"
// #include "3rd_party/rapidjson/include/rapidjson/allocators.h"
namespace marian {
namespace server {
class Error {
std::string errmsg_;
public:
Error(std::string const& msg) : errmsg_(msg) {}
std::string const& str() { return errmsg_; }
};
class Job {
static std::atomic_ullong job_ctr_;
public:
typedef std::pair<struct timeval, struct timezone> timestamp;
typedef Result nbestlist_item; // see hypothesis.h
uint64_t const unique_id; // internal job id
uint64_t external_id{0}; // Client's job id
int priority{0}; // Job priority; currently not used
timestamp created; // time item was created
timestamp queued; // time item entered the queue
timestamp started; // time item left the queue
timestamp finished; // time item was translated and postprocessed
const std::vector<std::string> input;
const size_t nbestlist_size{1};
std::string translation;
NBestList nbest; // see translation/history.h for definition
Ptr<const History> history;
Ptr<Error> error;
std::function<void (Ptr<Job>)> callback;
// rapidjson::Document request; // RapidJson Document representing the json request
Job(uint64_t ejid, const std::string text,
const TranslationOptions& topts, const size_t pri=0);
void dequeued(); // record start time
void finish(Ptr<const History> h, const bool R2L, const Vocab& V);
// functions for keeping track of workflow
float totalTime() const;
float timeBeforeQueue() const;
float timeInQueue() const;
float translationTime() const;
};
}}
| 31.241935 | 85 | 0.722251 | [
"vector"
] |
ec7f3f46e540717d3d1f30ee76deb23dac471d5f | 1,565 | c | C | ext/vendor/ctags/main/objpool.c | tmm1/ctags.rb | df7a805ac45ca7edd45109708baafdb55e92b024 | [
"MIT"
] | 4 | 2017-02-07T20:04:31.000Z | 2022-01-30T14:04:45.000Z | ext/vendor/ctags/main/objpool.c | tmm1/ctags.rb | df7a805ac45ca7edd45109708baafdb55e92b024 | [
"MIT"
] | 1 | 2018-01-07T19:14:53.000Z | 2018-01-07T19:14:53.000Z | ext/vendor/ctags/main/objpool.c | tmm1/ctags.rb | df7a805ac45ca7edd45109708baafdb55e92b024 | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2016, Jiri Techet
*
* This source code is released for free distribution under the terms of the
* GNU General Public License version 2 or (at your option) any later version.
*
* Defines generic pool for object reuse reducing the amount of allocations
* and deallocations.
*/
/*
* INCLUDE FILES
*/
#include "general.h" /* must always come first */
#include "routines.h"
#include "objpool.h"
/*
* DATA DECLARATIONS
*/
struct sObjPool {
ptrArray *array;
unsigned int size;
objPoolCreateFunc createFunc;
objPoolDeleteFunc deleteFunc;
objPoolClearFunc clearFunc;
};
/*
* FUNCTION DEFINITIONS
*/
extern objPool *objPoolNew (unsigned int size,
objPoolCreateFunc createFunc, objPoolDeleteFunc deleteFunc, objPoolClearFunc clearFunc)
{
objPool* const result = xMalloc (1, objPool);
result->array = ptrArrayNew (deleteFunc);
result->size = size;
result->createFunc = createFunc;
result->deleteFunc = deleteFunc;
result->clearFunc = clearFunc;
return result;
}
extern void objPoolDelete (objPool *pool)
{
ptrArrayDelete (pool->array);
eFree (pool);
}
extern void *objPoolGet (objPool *pool)
{
void *obj;
if (ptrArrayCount (pool->array) > 0)
{
obj = ptrArrayLast (pool->array);
ptrArrayRemoveLast (pool->array);
}
else
obj = pool->createFunc ();
if (pool->clearFunc)
pool->clearFunc (obj);
return obj;
}
extern void objPoolPut (objPool *pool, void *obj)
{
if (obj == NULL)
return;
if (ptrArrayCount (pool->array) < pool->size)
ptrArrayAdd (pool->array, obj);
else
pool->deleteFunc (obj);
}
| 19.5625 | 88 | 0.709265 | [
"object"
] |
ec80304fd0a92f4e6b01ce33c38a8ce0c48ec852 | 910 | h | C | DiligentSamples/playground/pg_module/engine/src/DX11/QueryDX11.h | raptoravis/defpr | 7335474b09dde91710d7bb2725c06e88d95b86f3 | [
"Apache-2.0"
] | 3 | 2019-08-04T08:24:36.000Z | 2021-11-18T19:27:10.000Z | DiligentSamples/playground/pg_module/engine/src/DX11/QueryDX11.h | raptoravis/defpr | 7335474b09dde91710d7bb2725c06e88d95b86f3 | [
"Apache-2.0"
] | null | null | null | DiligentSamples/playground/pg_module/engine/src/DX11/QueryDX11.h | raptoravis/defpr | 7335474b09dde91710d7bb2725c06e88d95b86f3 | [
"Apache-2.0"
] | 1 | 2020-08-16T00:04:45.000Z | 2020-08-16T00:04:45.000Z | #pragma once
#include <Query.h>
class QueryDX11 : public Query
{
public:
QueryDX11( ID3D11Device2* pDevice, QueryType queryType, uint8_t numBuffers );
virtual ~QueryDX11();
virtual void Begin( int64_t frame = 0L );
virtual void End( int64_t frame = 0L );
virtual bool QueryResultAvailable( int64_t frame = 0L );
virtual QueryResult GetQueryResult( int64_t frame = 0L );
virtual uint8_t GetBufferCount() const;
protected:
private:
Microsoft::WRL::ComPtr<ID3D11Device2> m_pDevice;
Microsoft::WRL::ComPtr<ID3D11DeviceContext2> m_pDeviceContext;
typedef std::vector< Microsoft::WRL::ComPtr<ID3D11Query> > QueryBuffer;
QueryBuffer m_DisjointQueries;
// For timer queries, we need 2 sets of buffered queries.
QueryBuffer m_Queries[2];
QueryType m_QueryType;
// How many queries will be used to prevent stalling the GPU.
uint8_t m_NumBuffers;
}; | 28.4375 | 81 | 0.725275 | [
"vector"
] |
ec8537439ce16a730302704bd2694995ee80b1ca | 2,469 | h | C | content/public/browser/message_port_provider.h | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 14,668 | 2015-01-01T01:57:10.000Z | 2022-03-31T23:33:32.000Z | content/public/browser/message_port_provider.h | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 86 | 2015-10-21T13:02:42.000Z | 2022-03-14T07:50:50.000Z | content/public/browser/message_port_provider.h | chromium/chromium | df46e572c3449a4b108d6e02fbe4f6d24cf98381 | [
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD-3-Clause"
] | 5,941 | 2015-01-02T11:32:21.000Z | 2022-03-31T16:35:46.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 CONTENT_PUBLIC_BROWSER_MESSAGE_PORT_PROVIDER_H_
#define CONTENT_PUBLIC_BROWSER_MESSAGE_PORT_PROVIDER_H_
#include <string>
#include <vector>
#include "build/build_config.h"
#include "build/chromecast_buildflags.h"
#include "content/common/content_export.h"
#include "third_party/abseil-cpp/absl/types/optional.h"
#include "third_party/blink/public/common/messaging/web_message_port.h"
#if defined(OS_ANDROID)
#include "base/android/scoped_java_ref.h"
#endif
#if defined(OS_FUCHSIA) || BUILDFLAG(IS_CHROMECAST)
#include "third_party/blink/public/common/messaging/message_port_channel.h"
#endif
namespace content {
class Page;
// An interface consisting of methods that can be called to use Message ports.
class CONTENT_EXPORT MessagePortProvider {
public:
MessagePortProvider() = delete;
MessagePortProvider(const MessagePortProvider&) = delete;
MessagePortProvider& operator=(const MessagePortProvider&) = delete;
// Posts a MessageEvent to the main frame using the given source and target
// origins and data.
// See https://html.spec.whatwg.org/multipage/comms.html#messageevent for
// further information on message events.
// Should be called on UI thread.
static void PostMessageToFrame(Page& page,
const std::u16string& source_origin,
const std::u16string& target_origin,
const std::u16string& data);
#if defined(OS_ANDROID)
static void PostMessageToFrame(
Page& page,
JNIEnv* env,
const base::android::JavaParamRef<jstring>& source_origin,
const base::android::JavaParamRef<jstring>& target_origin,
const base::android::JavaParamRef<jstring>& data,
const base::android::JavaParamRef<jobjectArray>& ports);
#endif // OS_ANDROID
#if defined(OS_FUCHSIA) || BUILDFLAG(IS_CHROMECAST)
// If |target_origin| is unset, then no origin scoping is applied.
static void PostMessageToFrame(
Page& page,
const std::u16string& source_origin,
const absl::optional<std::u16string>& target_origin,
const std::u16string& data,
std::vector<blink::WebMessagePort> ports);
#endif // OS_FUCHSIA || BUILDFLAG(IS_CHROMECAST)
};
} // namespace content
#endif // CONTENT_PUBLIC_BROWSER_MESSAGE_PORT_PROVIDER_H_
| 35.782609 | 78 | 0.733495 | [
"vector"
] |
ec8546d359ccc9937aac94ea4fbfb1f1abe290d2 | 712 | h | C | Dlist.h | TomasOchoa/CSCI-261-Project6-DogieProgram-DoublyLinkedList | fb4e9f61b9305c735e65cd3aaef8ca329701ca13 | [
"MIT"
] | null | null | null | Dlist.h | TomasOchoa/CSCI-261-Project6-DogieProgram-DoublyLinkedList | fb4e9f61b9305c735e65cd3aaef8ca329701ca13 | [
"MIT"
] | null | null | null | Dlist.h | TomasOchoa/CSCI-261-Project6-DogieProgram-DoublyLinkedList | fb4e9f61b9305c735e65cd3aaef8ca329701ca13 | [
"MIT"
] | null | null | null | // CSCI 216 Fundamentals of Prgoramming II Spring 2015
// Program #6: Doubly Linked List
// Author: Tomas Ochoa
// Due Date: 3/23/2015
// The object of this program is to implement a doggie game using
// a doubly linked list. This file is the doubly linked list
// definition. This definition of the doubly linked list uses
// node class.
#ifndef __Dlist_h
#define __Dlist_h
#include "node.h";
class Dlist
{
public:
Dlist();
~Dlist();
bool empty();
bool insertFront(char *);
bool insertBack(char *);
char *removeFront();
char *removeBack();
void print();
//private:
node* head = new node;
};
#endif // End the __Dist_h definition if not already defined
| 21.575758 | 66 | 0.667135 | [
"object"
] |
ec8b6b2c07b60f7d4877e17c14226018cc8fe3e1 | 4,265 | h | C | android/android_42/base/media/libdrm/mobile1/include/parser/parser_dm.h | yakuizhao/intel-vaapi-driver | b2bb0383352694941826543a171b557efac2219b | [
"MIT"
] | null | null | null | android/android_42/base/media/libdrm/mobile1/include/parser/parser_dm.h | yakuizhao/intel-vaapi-driver | b2bb0383352694941826543a171b557efac2219b | [
"MIT"
] | null | null | null | android/android_42/base/media/libdrm/mobile1/include/parser/parser_dm.h | yakuizhao/intel-vaapi-driver | b2bb0383352694941826543a171b557efac2219b | [
"MIT"
] | null | null | null | /*
* Copyright (C) 2007 The Android Open Source Project
*
* 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 __PARSER_DM_H__
#define __PARSER_DM_H__
#ifdef __cplusplus
extern "C" {
#endif
#include <drm_common_types.h>
#define MAX_CONTENT_TYPE_LEN 64
#define MAX_CONTENT_ID 256
#define MAX_CONTENT_BOUNDARY_LEN 256
#define MAX_RIGHTS_ISSUER_LEN 256
#define DRM_MIME_TYPE_RIGHTS_XML "application/vnd.oma.drm.rights+xml"
#define DRM_MIME_TYPE_CONTENT "application/vnd.oma.drm.content"
#define HEADERS_TRANSFER_CODING "Content-Transfer-Encoding:"
#define HEADERS_CONTENT_TYPE "Content-Type:"
#define HEADERS_CONTENT_ID "Content-ID:"
#define TRANSFER_CODING_TYPE_7BIT "7bit"
#define TRANSFER_CODING_TYPE_8BIT "8bit"
#define TRANSFER_CODING_TYPE_BINARY "binary"
#define TRANSFER_CODING_TYPE_BASE64 "base64"
#define DRM_UID_TYPE_FORWORD_LOCK "forwardlock"
#define DRM_NEW_LINE_CRLF "\r\n"
#define HEADERS_TRANSFER_CODING_LEN 26
#define HEADERS_CONTENT_TYPE_LEN 13
#define HEADERS_CONTENT_ID_LEN 11
#define DRM_MESSAGE_CODING_7BIT 0 /* default */
#define DRM_MESSAGE_CODING_8BIT 1
#define DRM_MESSAGE_CODING_BINARY 2
#define DRM_MESSAGE_CODING_BASE64 3
#define DRM_B64_DEC_BLOCK 3
#define DRM_B64_ENC_BLOCK 4
typedef struct _T_DRM_DM_Info {
uint8_t contentType[MAX_CONTENT_TYPE_LEN]; /**< Content type */
uint8_t contentID[MAX_CONTENT_ID]; /**< Content ID */
uint8_t boundary[MAX_CONTENT_BOUNDARY_LEN]; /**< DRM message's boundary */
uint8_t deliveryType; /**< The Delivery type */
uint8_t transferEncoding; /**< Transfer encoding type */
int32_t contentOffset; /**< The offset of the media content from the original DRM data */
int32_t contentLen; /**< The length of the media content */
int32_t rightsOffset; /**< The offset of the rights object in case of combined delivery */
int32_t rightsLen; /**< The length of the rights object in case of combined delivery */
uint8_t rightsIssuer[MAX_RIGHTS_ISSUER_LEN];/**< The rights issuer address in case of separate delivery */
} T_DRM_DM_Info;
/**
* Search the string in a limited length.
*
* \param str The original string
* \param strSearch The sub-string to be searched
* \param len The length limited
*
* \return
* -NULL, when there is not the searched string in length
* -The pointer of this sub-string
*/
const uint8_t* drm_strnstr(const uint8_t* str, const uint8_t* strSearch, int32_t len);
/**
* Parse the DRM message format data.
*
* \param buffer (in)Input the DRM message format data
* \param bufferLen (in)The input buffer length
* \param pDmInfo (out)A structure pointer which contain information of DRM message headers
*
* \return
* -TRUE, when success
* -FALSE, when failed
*/
int32_t drm_parseDM(const uint8_t* buffer, int32_t bufferLen, T_DRM_DM_Info* pDmInfo);
#ifdef __cplusplus
}
#endif
#endif /* __PARSER_DM_H__ */
| 41.813725 | 116 | 0.603751 | [
"object"
] |
ec9047dc3cb00b164b70ffe3a3553189d3edad20 | 5,198 | h | C | kubernetes/api/AdmissionregistrationV1beta1API.h | brendandburns/c | ea2fb243e1fd71e96a1ae470b728c3767bf0f328 | [
"Apache-2.0"
] | 1 | 2020-03-25T19:45:53.000Z | 2020-03-25T19:45:53.000Z | kubernetes/api/AdmissionregistrationV1beta1API.h | brendandburns/c | ea2fb243e1fd71e96a1ae470b728c3767bf0f328 | [
"Apache-2.0"
] | null | null | null | kubernetes/api/AdmissionregistrationV1beta1API.h | brendandburns/c | ea2fb243e1fd71e96a1ae470b728c3767bf0f328 | [
"Apache-2.0"
] | null | null | null | #include <stdlib.h>
#include <stdio.h>
#include "../include/apiClient.h"
#include "../include/list.h"
#include "../external/cJSON.h"
#include "../include/keyValuePair.h"
#include "../model/v1_api_resource_list.h"
#include "../model/v1_delete_options.h"
#include "../model/v1_status.h"
#include "../model/v1beta1_mutating_webhook_configuration.h"
#include "../model/v1beta1_mutating_webhook_configuration_list.h"
#include "../model/v1beta1_validating_webhook_configuration.h"
#include "../model/v1beta1_validating_webhook_configuration_list.h"
// create a MutatingWebhookConfiguration
//
v1beta1_mutating_webhook_configuration_t*
AdmissionregistrationV1beta1API_createMutatingWebhookConfiguration(apiClient_t *apiClient ,v1beta1_mutating_webhook_configuration_t * body ,char * pretty ,char * dryRun ,char * fieldManager);
// create a ValidatingWebhookConfiguration
//
v1beta1_validating_webhook_configuration_t*
AdmissionregistrationV1beta1API_createValidatingWebhookConfiguration(apiClient_t *apiClient ,v1beta1_validating_webhook_configuration_t * body ,char * pretty ,char * dryRun ,char * fieldManager);
// delete collection of MutatingWebhookConfiguration
//
v1_status_t*
AdmissionregistrationV1beta1API_deleteCollectionMutatingWebhookConfiguration(apiClient_t *apiClient ,char * pretty ,int allowWatchBookmarks ,char * _continue ,char * dryRun ,char * fieldSelector ,int gracePeriodSeconds ,char * labelSelector ,int limit ,int orphanDependents ,char * propagationPolicy ,char * resourceVersion ,int timeoutSeconds ,int watch ,v1_delete_options_t * body);
// delete collection of ValidatingWebhookConfiguration
//
v1_status_t*
AdmissionregistrationV1beta1API_deleteCollectionValidatingWebhookConfiguration(apiClient_t *apiClient ,char * pretty ,int allowWatchBookmarks ,char * _continue ,char * dryRun ,char * fieldSelector ,int gracePeriodSeconds ,char * labelSelector ,int limit ,int orphanDependents ,char * propagationPolicy ,char * resourceVersion ,int timeoutSeconds ,int watch ,v1_delete_options_t * body);
// delete a MutatingWebhookConfiguration
//
v1_status_t*
AdmissionregistrationV1beta1API_deleteMutatingWebhookConfiguration(apiClient_t *apiClient ,char * name ,char * pretty ,char * dryRun ,int gracePeriodSeconds ,int orphanDependents ,char * propagationPolicy ,v1_delete_options_t * body);
// delete a ValidatingWebhookConfiguration
//
v1_status_t*
AdmissionregistrationV1beta1API_deleteValidatingWebhookConfiguration(apiClient_t *apiClient ,char * name ,char * pretty ,char * dryRun ,int gracePeriodSeconds ,int orphanDependents ,char * propagationPolicy ,v1_delete_options_t * body);
// get available resources
//
v1_api_resource_list_t*
AdmissionregistrationV1beta1API_getAPIResources(apiClient_t *apiClient);
// list or watch objects of kind MutatingWebhookConfiguration
//
v1beta1_mutating_webhook_configuration_list_t*
AdmissionregistrationV1beta1API_listMutatingWebhookConfiguration(apiClient_t *apiClient ,char * pretty ,int allowWatchBookmarks ,char * _continue ,char * fieldSelector ,char * labelSelector ,int limit ,char * resourceVersion ,int timeoutSeconds ,int watch);
// list or watch objects of kind ValidatingWebhookConfiguration
//
v1beta1_validating_webhook_configuration_list_t*
AdmissionregistrationV1beta1API_listValidatingWebhookConfiguration(apiClient_t *apiClient ,char * pretty ,int allowWatchBookmarks ,char * _continue ,char * fieldSelector ,char * labelSelector ,int limit ,char * resourceVersion ,int timeoutSeconds ,int watch);
// partially update the specified MutatingWebhookConfiguration
//
v1beta1_mutating_webhook_configuration_t*
AdmissionregistrationV1beta1API_patchMutatingWebhookConfiguration(apiClient_t *apiClient ,char * name ,object_t * body ,char * pretty ,char * dryRun ,char * fieldManager ,int force);
// partially update the specified ValidatingWebhookConfiguration
//
v1beta1_validating_webhook_configuration_t*
AdmissionregistrationV1beta1API_patchValidatingWebhookConfiguration(apiClient_t *apiClient ,char * name ,object_t * body ,char * pretty ,char * dryRun ,char * fieldManager ,int force);
// read the specified MutatingWebhookConfiguration
//
v1beta1_mutating_webhook_configuration_t*
AdmissionregistrationV1beta1API_readMutatingWebhookConfiguration(apiClient_t *apiClient ,char * name ,char * pretty ,int exact ,int export);
// read the specified ValidatingWebhookConfiguration
//
v1beta1_validating_webhook_configuration_t*
AdmissionregistrationV1beta1API_readValidatingWebhookConfiguration(apiClient_t *apiClient ,char * name ,char * pretty ,int exact ,int export);
// replace the specified MutatingWebhookConfiguration
//
v1beta1_mutating_webhook_configuration_t*
AdmissionregistrationV1beta1API_replaceMutatingWebhookConfiguration(apiClient_t *apiClient ,char * name ,v1beta1_mutating_webhook_configuration_t * body ,char * pretty ,char * dryRun ,char * fieldManager);
// replace the specified ValidatingWebhookConfiguration
//
v1beta1_validating_webhook_configuration_t*
AdmissionregistrationV1beta1API_replaceValidatingWebhookConfiguration(apiClient_t *apiClient ,char * name ,v1beta1_validating_webhook_configuration_t * body ,char * pretty ,char * dryRun ,char * fieldManager);
| 49.037736 | 386 | 0.835129 | [
"model"
] |
ec949df627ca7bb18c1256cc83045ee1e16849b1 | 7,172 | c | C | lib/extmem/external_memory.c | pth-demo-orga/trusty-lk-trusty | c7935db04b08df2da462e92ce224bb001c69fe8a | [
"MIT"
] | null | null | null | lib/extmem/external_memory.c | pth-demo-orga/trusty-lk-trusty | c7935db04b08df2da462e92ce224bb001c69fe8a | [
"MIT"
] | 1 | 2022-02-18T11:39:52.000Z | 2022-02-18T11:39:52.000Z | lib/extmem/external_memory.c | pth-demo-orga/trusty-lk-trusty | c7935db04b08df2da462e92ce224bb001c69fe8a | [
"MIT"
] | null | null | null | /*
* Copyright (c) 2020 LK Trusty Authors. All Rights Reserved.
*
* 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 <err.h>
#include <kernel/vm.h>
#include <lib/extmem/extmem.h>
#include <trace.h>
#define LOCAL_TRACE 0
static struct ext_mem_obj* ext_mem_obj_from_vmm_obj(struct vmm_obj* vmm_obj) {
return containerof(vmm_obj, struct ext_mem_obj, vmm_obj);
}
static struct ext_mem_obj* ext_mem_obj_from_bst_node(struct bst_node* node) {
return containerof(node, struct ext_mem_obj, node);
}
static int ext_mem_obj_cmp(struct bst_node* a_bst, struct bst_node* b_bst) {
struct ext_mem_obj* a = ext_mem_obj_from_bst_node(a_bst);
struct ext_mem_obj* b = ext_mem_obj_from_bst_node(b_bst);
return a->id < b->id ? 1 : a->id > b->id ? -1 : 0;
}
void ext_mem_obj_initialize(struct ext_mem_obj* obj,
struct obj_ref* ref,
ext_mem_obj_id_t id,
uint64_t tag,
struct vmm_obj_ops* ops,
uint arch_mmu_flags,
size_t page_run_count) {
obj->id = id;
obj->tag = tag;
obj->match_tag = 0;
obj->vmm_obj.ops = ops;
obj->arch_mmu_flags = arch_mmu_flags;
obj->page_run_count = page_run_count;
obj_init(&obj->vmm_obj.obj, ref);
bst_node_initialize(&obj->node);
}
bool ext_mem_insert(struct bst_root* objs, struct ext_mem_obj* obj) {
return bst_insert(objs, &obj->node, ext_mem_obj_cmp);
}
struct ext_mem_obj* ext_mem_lookup(struct bst_root* objs, ext_mem_obj_id_t id) {
struct ext_mem_obj ref_obj;
ref_obj.id = id;
return bst_search_type(objs, &ref_obj, ext_mem_obj_cmp, struct ext_mem_obj,
node);
}
void ext_mem_obj_set_match_tag(struct vmm_obj* obj, uint64_t match_tag) {
struct ext_mem_obj* ext_obj = ext_mem_obj_from_vmm_obj(obj);
ext_obj->match_tag = match_tag;
}
int ext_mem_obj_check_flags(struct vmm_obj* obj, uint* arch_mmu_flags) {
struct ext_mem_obj* ext_obj = ext_mem_obj_from_vmm_obj(obj);
LTRACEF("obj 0x%llx, obj arch_mmu_flags 0x%x, arch_mmu_flags 0x%x\n",
ext_obj->id, ext_obj->arch_mmu_flags, *arch_mmu_flags);
if (ext_obj->match_tag != ext_obj->tag) {
TRACEF("WARNING: tag mismatch: 0x%llx != 0x%llx\n", ext_obj->match_tag,
ext_obj->tag);
return ERR_ACCESS_DENIED;
}
if (!(*arch_mmu_flags & ARCH_MMU_FLAG_PERM_RO) &&
(ext_obj->arch_mmu_flags & ARCH_MMU_FLAG_PERM_RO)) {
TRACEF("rw access denied. arch_mmu_flags=0x%x, ext_obj->flags=0x%x\n",
*arch_mmu_flags, ext_obj->arch_mmu_flags);
return ERR_ACCESS_DENIED;
}
if (!(*arch_mmu_flags & ARCH_MMU_FLAG_PERM_NO_EXECUTE) &&
(ext_obj->arch_mmu_flags & ARCH_MMU_FLAG_PERM_NO_EXECUTE)) {
TRACEF("exec access denied. arch_mmu_flags=0x%x, ext_obj->flags=0x%x\n",
*arch_mmu_flags, ext_obj->arch_mmu_flags);
return ERR_ACCESS_DENIED;
}
/*
* Memory types must be consistent with external mappings, so don't allow
* the caller to specify them.
*/
if (*arch_mmu_flags & ARCH_MMU_FLAG_CACHE_MASK) {
TRACEF("cache attributes should come from vmm_obj, not from caller\n");
return ERR_INVALID_ARGS;
}
if (*arch_mmu_flags & ARCH_MMU_FLAG_NS) {
TRACEF("ARCH_MMU_FLAG_NS should come from vmm_obj, not from caller\n");
return ERR_INVALID_ARGS;
}
*arch_mmu_flags |= ext_obj->arch_mmu_flags;
return 0;
}
int ext_mem_obj_get_page(struct vmm_obj* obj,
size_t offset,
paddr_t* paddr,
size_t* paddr_size) {
struct ext_mem_obj* ext_obj = ext_mem_obj_from_vmm_obj(obj);
size_t index;
size_t page_offset;
LTRACEF("offset %zd page_run_count %zd\n", offset, ext_obj->page_run_count);
page_offset = offset;
index = 0;
while (index < ext_obj->page_run_count &&
ext_obj->page_runs[index].size <= page_offset) {
page_offset -= ext_obj->page_runs[index].size;
index++;
}
if (index >= ext_obj->page_run_count) {
TRACEF("offset %zd out of range index %zd >= %zd\n", offset, index,
ext_obj->page_run_count);
return ERR_OUT_OF_RANGE;
}
*paddr = ext_obj->page_runs[index].paddr + page_offset;
*paddr_size = ext_obj->page_runs[index].size - page_offset;
LTRACEF("offset %zd, index %zd/%zd -> paddr 0x%lx, size %zu\n", offset,
index, ext_obj->page_run_count, *paddr, *paddr_size);
return 0;
}
status_t ext_mem_map_obj_id(vmm_aspace_t* aspace,
const char* name,
ext_mem_client_id_t client_id,
ext_mem_obj_id_t mem_obj_id,
uint64_t tag,
size_t offset,
size_t size,
void** ptr,
uint8_t align_log2,
uint vmm_flags,
uint arch_mmu_flags) {
status_t err;
struct vmm_obj* vmm_obj = NULL;
struct obj_ref vmm_obj_ref = OBJ_REF_INITIAL_VALUE(vmm_obj_ref);
DEBUG_ASSERT(IS_PAGE_ALIGNED(size));
err = ext_mem_get_vmm_obj(client_id, mem_obj_id, tag, size + offset,
&vmm_obj, &vmm_obj_ref);
if (err) {
TRACEF("failed to get object, 0x%llx:0x%llx, to map for %s\n",
client_id, mem_obj_id, name);
return err;
}
/* If tag is not 0, match_tag must be set before the object can be mapped */
ext_mem_obj_set_match_tag(vmm_obj, tag);
err = vmm_alloc_obj(aspace, name, vmm_obj, offset, size, ptr, align_log2,
vmm_flags, arch_mmu_flags);
vmm_obj_del_ref(vmm_obj, &vmm_obj_ref);
if (err) {
TRACEF("failed to map object, 0x%llx:0x%llx, for %s\n", client_id,
mem_obj_id, name);
return err;
}
LTRACEF("mapped 0x%llx:0x%llx at %p\n", client_id, mem_obj_id, *ptr);
return err;
}
| 36.591837 | 80 | 0.639989 | [
"object"
] |
ec9504738455f655a397b3763c7296f02bae553f | 2,453 | h | C | aws-cpp-sdk-storagegateway/include/aws/storagegateway/model/DescribeStorediSCSIVolumesResult.h | ambasta/aws-sdk-cpp | c81192e00b572b76d175d84dff77185bd17ae1ac | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-storagegateway/include/aws/storagegateway/model/DescribeStorediSCSIVolumesResult.h | ambasta/aws-sdk-cpp | c81192e00b572b76d175d84dff77185bd17ae1ac | [
"Apache-2.0"
] | null | null | null | aws-cpp-sdk-storagegateway/include/aws/storagegateway/model/DescribeStorediSCSIVolumesResult.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/storagegateway/StorageGateway_EXPORTS.h>
#include <aws/core/utils/memory/stl/AWSVector.h>
#include <aws/storagegateway/model/StorediSCSIVolume.h>
namespace Aws
{
template<typename RESULT_TYPE>
class AmazonWebServiceResult;
namespace Utils
{
namespace Json
{
class JsonValue;
} // namespace Json
} // namespace Utils
namespace StorageGateway
{
namespace Model
{
class AWS_STORAGEGATEWAY_API DescribeStorediSCSIVolumesResult
{
public:
DescribeStorediSCSIVolumesResult();
DescribeStorediSCSIVolumesResult(const AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
DescribeStorediSCSIVolumesResult& operator=(const AmazonWebServiceResult<Aws::Utils::Json::JsonValue>& result);
inline const Aws::Vector<StorediSCSIVolume>& GetStorediSCSIVolumes() const{ return m_storediSCSIVolumes; }
inline void SetStorediSCSIVolumes(const Aws::Vector<StorediSCSIVolume>& value) { m_storediSCSIVolumes = value; }
inline void SetStorediSCSIVolumes(Aws::Vector<StorediSCSIVolume>&& value) { m_storediSCSIVolumes = value; }
inline DescribeStorediSCSIVolumesResult& WithStorediSCSIVolumes(const Aws::Vector<StorediSCSIVolume>& value) { SetStorediSCSIVolumes(value); return *this;}
inline DescribeStorediSCSIVolumesResult& WithStorediSCSIVolumes(Aws::Vector<StorediSCSIVolume>&& value) { SetStorediSCSIVolumes(value); return *this;}
inline DescribeStorediSCSIVolumesResult& AddStorediSCSIVolumes(const StorediSCSIVolume& value) { m_storediSCSIVolumes.push_back(value); return *this; }
inline DescribeStorediSCSIVolumesResult& AddStorediSCSIVolumes(StorediSCSIVolume&& value) { m_storediSCSIVolumes.push_back(value); return *this; }
private:
Aws::Vector<StorediSCSIVolume> m_storediSCSIVolumes;
};
} // namespace Model
} // namespace StorageGateway
} // namespace Aws
| 34.549296 | 159 | 0.775785 | [
"vector",
"model"
] |
ec997bc4ecfcd48754f180f00f3972af9be5b9c4 | 294 | h | C | solverModules/GIMME_solver_modules/Node.h | pedro19v/GIMME | c99cfe8465e8e2e3ca507a41e3f9dd09931051b1 | [
"CC-BY-4.0"
] | null | null | null | solverModules/GIMME_solver_modules/Node.h | pedro19v/GIMME | c99cfe8465e8e2e3ca507a41e3f9dd09931051b1 | [
"CC-BY-4.0"
] | null | null | null | solverModules/GIMME_solver_modules/Node.h | pedro19v/GIMME | c99cfe8465e8e2e3ca507a41e3f9dd09931051b1 | [
"CC-BY-4.0"
] | null | null | null | #pragma once
#include "Subspace.h"
#include "IntegerPartition.h"
#include "Edge.h"
class Node
{
public:
Subspace subspace;
IntegerPartition integerPartition;
std::vector<Edge> edgesFromThisNode;
bool tempFlag;
std::vector<int> tempIntegerRoots;
Node() {}
Node(Subspace subspace);
};
| 14.7 | 37 | 0.744898 | [
"vector"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.